Reputation: 301
I am working with semaphores and I am struggling with one part of code.
CODE:
// semaphore initialized to zero
for( int i = 0; i < N; i++ )
{
fork();
// statements
sem_wait(semaphore);
printf("Process %d is done\n", i);
exit(0);
}
for( int i = 0; i < N; i++ )
{
sem_post(semaphore);
}
Problem is, that loop stops after first iteration because of sem_wait
, but i would like it to stop only that current process, so all other iterations can be done and at the end of code, i will 'release' all processes. Is there a way how to accomplish this?
Thank you!
EDIT:
// initialization of semaphore
semaphore = mmap(NULL, sizeof(sem_t), PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANONYMOUS, -1, 0);
sem_init(semaphore, 1, 0);
Upvotes: 0
Views: 648
Reputation: 2022
Please check fork return value. On that basis, you will be sure if code is executed under child or parent process. Accordingly call sem_wait.
Upvotes: 1