繁体   English   中英

如何调用 execl(或 simlar)并为子进程设置信号处理程序?

[英]How to call execl (or simlar) and set signal handlers for the child process?

我正在尝试编写一个程序caller ,它用sigaction捕获SIGINT ,并调用一个外部程序prog 我了解如何在一个简单的程序上使用sigaction ,但我不知道如何使用它为其他进程设置信号处理程序(例如,由execl调用)。

以下是 MWE:

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是这样的:

#include <stdio.h>
#include <unistd.h>

int main() {
    for(int i=0; ; i++) {
        sleep(1);
        printf("epoch: %d\n",i);
    }
}

但是当我运行caller时,我看到 prog.c 的prog.c ,并且点击^C确实停止了程序(信号没有被捕获)。 我想这与execl的工作方式有关(它创建了一个新进程,它不继承父母的信号处理程序——对吗?)那么,我怎样才能完成我想做的事情呢?

谢谢!

execl("./prog", "./prog", "./prog", (char*) NULL);

或者如果它不起作用,请在此处查看: https://pubs.opengroup.org/onlinepubs/9699919799/functions/exec.html

暂无
暂无

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

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