1

I have some troubles: it is not clear for me how to synchronise parent and child processes using signals, and this code doesn't work. I thought that it should work like that: parent sends signal to child, child's pause() is end, child sends signal to parent, parent's pause() is end .. etc why it is not so?

#include <stdlib.h>
#include <stdio.h>
#include <signal.h>
#include <sys/types.h>

void handler_cp() {
}

void handler_pc() {
}

void child_proc() {
    int i = 0;
    for (; i < 50; ++i) {
        pause();
        kill(getppid(), SIGUSR2);
    }

void parent_proc(pid_t ch) {
    int j = 0;
    for (; j < 50; ++j) {
        kill(ch, SIGUSR1);
        pause();
    }
}

int main(int argc, char* argv[]) {
    signal(SIGUSR1, handler_cp);
    signal(SIGUSR2, handler_pc);
    pid_t ch = fork();
    if (ch == 0)
        child_proc();
    else
        parent_proc(ch);
    return 0;
}
4

2 回答 2

2

The signal may arrive before pause is called, in which case it will deadlock. Using signals for synchronization is, in general, a very bad idea.

于 2013-03-30T17:11:45.730 回答
1

In the child_proc method, reverse the lines as :

          kill(getppid(),SIGUSR2);
          pause();

This will wake the parent before the child goes to sleep.

于 2015-02-01T12:25:05.803 回答