[英]How to call execl (or simlar) and set signal handlers for the child process?
I am trying to write a program, caller
, which traps SIGINT
with sigaction
, and calls an external program, prog
.我正在尝试编写一个程序caller
,它用sigaction
捕获SIGINT
,并调用一个外部程序prog
。 I understand how to use sigaction
on a simple program, but I don't know how to use it to set signal handlers for other processes (called by execl
, for example).我了解如何在一个简单的程序上使用sigaction
,但我不知道如何使用它为其他进程设置信号处理程序(例如,由execl
调用)。
The following is a MWE:以下是 MWE:
caller.c
is this: caller.c
是这样的:
#include <stdio.h>
#include <signal.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
void got_sig(int sig) {
printf("SIGNAL caught: %d\n",sig);
}
int main () {
struct sigaction sa;
(void) sigfillset(&sa.sa_mask);
sa.sa_handler = got_sig;
sa.sa_flags=0;
sigaction(SIGINT,&sa,NULL);
printf("\n");
execl("./prog", "./prog", (char*) NULL);
}
prog.c
is this: prog.c
是这样的:
#include <stdio.h>
#include <unistd.h>
int main() {
for(int i=0; ; i++) {
sleep(1);
printf("epoch: %d\n",i);
}
}
But when I run caller
, I see the output of prog.c
, and hitting ^C
does stop the prorgam (the signal is not trapped).但是当我运行caller
时,我看到 prog.c 的prog.c
,并且点击^C
确实停止了程序(信号没有被捕获)。 I suppose this is related to how execl
works (it creates a new process, which does not inherit the parents' signal handlers -- is this right?) So, how can I accomplish what I am trying to do?我想这与execl
的工作方式有关(它创建了一个新进程,它不继承父母的信号处理程序——对吗?)那么,我怎样才能完成我想做的事情呢?
Thank you!谢谢!
execl("./prog", "./prog", "./prog", (char*) NULL);
Or if it's not working, check out here: https://pubs.opengroup.org/onlinepubs/9699919799/functions/exec.html或者如果它不起作用,请在此处查看: https://pubs.opengroup.org/onlinepubs/9699919799/functions/exec.html
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.