[英]Unix and Signal Handlers (C)
I'm a student and I am trying to understand signals within a course about Unix programming. 我是一名学生,我正在尝试了解有关Unix编程的课程中的信号。
To start, I wanted to test a simple example: a process makes a child and needs a confirmation of the actual creation. 首先,我想测试一个简单的示例:一个过程产生了一个孩子,需要确认实际的创建。 I fork, and within the child I send a SIGUSR1 to the father with kill(getppid(), SIGUSR1);
我分叉,并在孩子中使用kill(getppid(),SIGUSR1)将SIGUSR1发送给父亲。 Then, within the father, I wrote a pause();
然后,在父亲里面,我写了一个pause(); sys call to block the process until a signal is received, and then I wrote the (sigaction(SIGUSR1, &sa, NULL) check.
sys调用将阻止该过程,直到收到信号为止,然后我编写了(sigaction(SIGUSR1,&sa,NULL)检查。
Problem is, the signal is sent and the program stops, with no handler execution. 问题是,没有处理程序执行,就发送了信号,程序停止了。
I compile it with 我用它编译
$gcc -Wall -o test test.c
I get no warnings, and the output is 我没有警告,输出是
$I am the father
$I am the child
$User defined signal 1
I know I could do this in other ways (with sleep sys call, etc.), but I just want to understand why this code doesn't work. 我知道我可以通过其他方式(使用sleep sys调用等)来执行此操作,但是我只是想了解为什么此代码无法正常工作。
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
void new_child (int sig){
write(1,"I made a new child\n",50);
}
int main(){
pid_t child;
struct sigaction sa;
sigemptyset(&sa.sa_mask);
sa.sa_flags = 0;
sa.sa_handler = new_child;
switch(child = fork()){
case -1:
printf("Error.\n");
exit(EXIT_FAILURE);
case 0:
printf("I am the child\n");
kill(getppid(), SIGUSR1);
break;
default:
printf("I am the father\n");
pause();
if (sigaction(SIGUSR1, &sa, NULL) == -1){
printf("Signal error.\n");
exit(EXIT_FAILURE);
}
printf("I'm done.");
kill (child, SIGKILL);
exit(EXIT_SUCCESS);
}
}
I know this question has already been asked, but I cannot seem to find a solution that works in my case. 我知道已经问过这个问题,但是我似乎找不到适合我的解决方案。
You must change the signal at the beginning of the code so that it can execute as soon as SIGUSR is received – Anjaneyulu 您必须在代码的开头更改信号,以便在收到SIGUSR后立即执行– Anjaneyulu
" You must change the signal at the beginning of the code ... " this restriction is a bit tight. “ 您必须在代码的开头更改信号... ”此限制有点严格。 The signal handler needs to be install latest just before calling
fork()
. 信号处理程序需要在调用
fork()
之前最新安装。 – alk – alk
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.