0

I am getting deadlock and I don't understand why. I want process of child 2 finish before child 1, but program is getting deadlock.

#include <stdio.h>
#include <unistd.h>
#include <semaphore.h>
#include <sys/wait.h>

int main() {
    int pid1, pid2;
    sem_t sem;

    sem_init(&sem, 1, 0);
    pid1 = fork();

    if (pid1 == 0) { // child 1
        sem_wait(&sem);
        printf("Child 1 PID: %d\n", getpid());
        sem_destroy(&sem);
    } else { // parent
        pid2 = fork();
        if (pid2 == 0) { // child 2
            printf("Child 2 PID: %d\n", getpid());
            sem_post(&sem);
        } else { // parent
            wait(NULL); // wait for child 2
            wait(NULL); // wait for child 1
            printf("Parent PID: %d\n", getpid());
        }
    }

    return 0;
}
MwahMallah
  • 33
  • 3
  • Do you want to ensure that the second child *terminates* before the first one does, or (only) that the second prints its output before the first prints its own? – John Bollinger Apr 28 '23 at 15:07
  • Possible answers here: [Do forked child processes use the same semaphore?](https://stackoverflow.com/questions/6847973/do-forked-child-processes-use-the-same-semaphore) – pmacfarlane Apr 28 '23 at 15:19

1 Answers1

-1

You should change the parameter value of sem_init to 1.

int sem_init(sem_t *sem, int pshared, unsigned int value);
sem_init(&sem, 1, 1);

According to this post:

Sem init value for

  • That would be counterproductive. The purpose of the semaphore is to prevent the first child from proceeding until after the second child has run. Setting the initial value to 1 would break that. – John Bollinger Apr 28 '23 at 15:06