簡體   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