I am hacking away at a uni assignment and have come across a problem with my code which is supposed to spawn 2 processes, where the second process waits for the 1st to complete before executing. This is what I have so far:
sem_t mutex;
int producer; int consumer;
sem_init(&mutex, 0, 1);
producer = fork();
consumer = fork();
if (producer == 0) {
if (VERBOSE) printf("Running producer\n");
/* down semaphore */
sem_wait(&mutex);
/* START CRITICAL REGION */
get_files(N);
/* END CRITICAL REGION */
/* up semaphore */
sem_post(&mutex);
if (VERBOSE) printf("Ending producer\n");
exit(0);
}
if (consumer == 0) {
if (VERBOSE) printf("Running consumer\n");
/* down semaphore */
sem_wait(&mutex);
/* START CRITICAL REGION */
/* do stuff */
/* END CRITICAL REGION */
/* up semaphore */
sem_post(&mutex);
if (VERBOSE) printf("Ending consumer\n");
exit(0);
}
/* parent waits for both to complete */
wait(NULL);
Now, I know that in the "real-world" this is really stupid. If my 'consumer' does nothing while until my 'producer' is finished, then you might as well not have 2 processes like this, but the assignment is trying to illustrate a race-condition, so that why we've been specifically told to do it this way.
So, my problem is that the consumer process isn't waiting for the producer. I assumed that since the semaphore was taken down in the producer (sem_wait(&mutex);
) then it wouldn't be available to the consumer until sem_post(&mutex);
is called in the producer.
Additionally, as best as I can tell, the line wait(NULL);
isn't waiting for both processes to complete.
Have I critically misunderstood something?