问题描述
我的目的是为 fgets 创建一个 1 秒以内的时间.如果在 1 秒内没有收到任何输入,则程序终止.
My intention is to create a time out of 1 sec for fgets. If no input is received in 1 sec, then the program terminates.
我提出的设计是:父级为 SIGALRM 注册一个信号处理程序.然后它派生一个将触发 SIGALRM 的孩子,它继续调用 fgets.SIGALRM 将触发杀死父进程的处理程序.但是当我在 ubuntu 14.04 64 位上执行这个时,处理程序没有被触发,程序只是等待用户永远输入 fgets.
The design I come up with is:the parent registers a signal handler for SIGALRM. Then it forks a child which will trigger SIGALRM and it goes ahead and call fgets. The SIGALRM will trigger the handler which kills the parent process. But when I execute this on a ubuntu 14.04 64-bit, the handler is not triggered and the program just waits for user to input for fgets forever.
为什么会发生这种情况,我该如何解决?
Why would this happen and how can I fix this?
#include "csapp.h"
void handler() {
printf("lazy man\n");
kill(SIGKILL, getppid());
exit(0);
}
int main() {
char buf[100];
signal(SIGALRM, handler);
pid_t pid;
if ((pid = fork()) == 0) {
alarm(1);
} else {
fgets(buf, 100, stdin);
printf("%s", buf);
}
return 0;
}
~
推荐答案
如果您花时间阅读的手册 kill()
,你会发现你错过了参数的顺序.
If you will take time to read the manual of kill()
, you will see that you miss the order of the arguments.
int kill(pid_t pid, int sig);
修复:
kill(getppid(), SIGKILL);
另外,您的孩子在发出信号之前终止他的执行,您必须在调用 alarm()
之后添加一个 sleep()
以使其等待:
Plus, your child terminate his execution before that the signal is raise you must add a sleep()
after your call to alarm()
to make it wait:
alarm(1);
sleep(2);
最后,printf()
在信号处理程序中是不安全的,安全功能列表.
Finally, printf()
is not safe in a signal handler, list of safe function.
这篇关于为什么不能触发子进程中的信号处理程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!