简体   繁体   English

在父子之间发送信号不起作用

[英]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'. 考虑以下程序,流程父亲创建流程孩子,流程父亲在屏幕上打印“ A”和“ B”,孩子在屏幕上写下“ C”和“ D”。 The problem is that I want the program to ONLY result with 'ACBD' This is the code : 问题是我只希望程序以'ACBD'结果出现这是代码:

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. 在父代码中调用kill之前,请添加sleep(1)。 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). 您还应该注意,输出已缓冲-这意味着它不会立即推送到终端,您可以通过添加“ \\ n”或调用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); 
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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