简体   繁体   中英

C semaphores using sem_wait()

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);

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM