0

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);
7
  • Show us, how did you initialized semarophe variable. Commented May 1, 2017 at 9:08
  • Can you explain what you mean by the "current process"? Once you explain what you mean by that, just wrap the call to sem_wait in an if statement that tests whatever it is you need to test. Commented May 1, 2017 at 9:34
  • Well, in for loop i call fork() N times, so i create N processes. So current process i mean each process every iteration. Commented May 1, 2017 at 9:36
  • @SevO I don't follow. If the current process is each process every iteration, then what isn't the current process? Commented May 1, 2017 at 9:43
  • Let's say i=0 and first process is called. Code comes to part where semaphore is blocked. I want to accomplish that even process is blocked, loop continues, so one by one i create queue of processes and at the end i use sem_post() and release them. Commented May 1, 2017 at 9:48

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.