Welcome!

By registering with us, you'll be able to discuss, share and private message with other members of our community.

SignUp Now!
  • Guest, before posting your code please take these rules into consideration:
    • It is required to use our BBCode feature to display your code. While within the editor click < / > or >_ and place your code within the BB Code prompt. This helps others with finding a solution by making it easier to read and easier to copy.
    • You can also use markdown to share your code. When using markdown your code will be automatically converted to BBCode. For help with markdown check out the markdown guide.
    • Don't share a wall of code. All we want is the problem area, the code related to your issue.


    To learn more about how to use our BBCode feature, please click here.

    Thank you, Code Forum.

Process syncronization

john_

New Coder
I have written a program in c that firstly creates two processes with fork. The child process writes 2000 characters to a file and the parent process reads the characters from the file. The reading process is done with the use of threads. There are 4 threads and each one of them reads 500 characters. I have used a semaphore to wait for the child process to complete first. sem_post(&sem) at the end of child process and sem_wait(&sem) at the beginning of the parent process. But it doesn't work. The program gets into the child process and doesn't do anything. If I instead use waitpid the program runs fine. What do causes the problem?
 
The problem could be that the child process is not completing before the parent process, so the semaphore is never posted. To solve this, you should use a synchronization mechanism like waitpid() in the parent process to ensure that the child process has completed before the parent process continues.

Additionally, it's possible that the semaphore may not be initialized correctly, or there could be a race condition where the parent process reads from the file before the child process has written to it. You should also check that the file is open correctly and that the semaphore is being used correctly, such as correctly initializing it, destroying it when finished, and properly releasing and acquiring the semaphore.
 
I agree that sync'ing the parent and child processes is best done using waitpid. If that works fine as you say, why would you want to use semaphores anyway ? It's been ages since I tried them out, to the point I can't remember how my test program worked. Actually I'm not at all sure anybody still uses them these days.
Just curious, why do you use 4 threads to read 2000 characters from a file ? Or is this just an exercise in threading ? Are they all reading at the same time, each starting at its own offset ?
 

New Threads

Buy us a coffee!

Back
Top Bottom