简体   繁体   中英

sending signals between father and child is not working

Consider the following program where a process father creates a process child , the father should print on the screen 'A' and 'B' , the child writes 'C' and 'D'. The problem is that I want the program to ONLY result with 'ACBD' This is the code :

void main () {
int pid;
signal(SIGUSR1,SIG_IGN);
if (pid=fork()) {
    printf("A");
    kill(pid,SIGUSR1);
    pause();
    printf("B");
}
else {
    pause();
    printf("C");
    kill(getppid(),SIGUSR1);
    printf("D");
}
}

But its the output is NOTHING ! Any help would be appreciated !

There is a chance that parent is trying to sent signal while 'child' is not alive yet. Add sleep(1) before calling kill in parent code. However it's not nice solution... Furthermore you should add signal handler function (even an empty one). You should also be aware that the output is buffered - it means it is not pushed to terminal immediately, you can force pushing it by adding "\\n" or calling fflush(stdout).

#include <stdio.h> 
#include <signal.h>
void main () {
int pid;
void signal_handler(int test) {}
signal(SIGUSR1, signal_handler);
if (pid=fork()) {
    printf("A");
    fflush(stdout);
    sleep(1);
    kill(pid,SIGUSR1);
    pause();
    printf("B");
    fflush(stdout);
}
else {
    pause();
    printf("C");
    fflush(stdout);
    kill(getppid(),SIGUSR1);
    printf("D");
    fflush(stdout); 
  }
}

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