簡體   English   中英

如何將信號發送到通過fork和execl創建的子進程?

[英]How to send signal to a child process created via fork and execl?

假設我有一個程序foo ,它可以永久打印,但在此之前已停止,

int main(int argc, char * argv[])
{
    kill(getpid(), SIGSTOP);
    while(1) {
        printf("foo\n");
    }
    return 0;
}

然后我有一個程序bar ,它可以分叉並運行foo

int main(int argc, char * argv[])
{
    pid_t pid = fork();
    if (pid == 0)
    {
        execl("foo", "foo", NULL);
    }
    return 0;
}

現在,我希望bar能夠將SIGCONT發送給foo以便它可以繼續執行其打印任務,然后稍后再次發送SIGSTOP,甚至以后再次發送SIGCONT,依此類推。

我不知道該怎么做。 有什么幫助嗎?

編輯:我想出了我的問題。 顯然, foo程序在運行時尚未准備好立即接受信號。 當我做的時候

sleep(5);
int rc = kill(pid, SIGCONT);

有效。

pid_t pid = fork();
if (pid == 0)
{
    execl("foo", "foo", NULL);
}
int rc = kill(pid, 18);
return 0;

建議:不要忘記處理系統調用中的錯誤代碼! 不處理錯誤代碼的工作方式更糟! 您可以在一個程序中執行這兩個操作。 在這種情況下,它將更加有效:

#include <errno.h>

int main(int argc, char * argv[])
{
    int rc = 0;

    pid_t pid = fork();
    if (pid == 0) /* child */
    {
        kill(getpid(), SIGSTOP);
        if (rc == -1) {
                  perror("Something wrong while kill() in child");
        }
        while (1) {
                  printf("foo\n");
        }
    } else if (pid > 0) { /* father */
        rc = kill(pid, SIGCONT);
        if (rc == -1) {
                  perror("Something wrong while kill() in parent");
        }
    } else if (pid < 0) {
        perror("Something wrong while fork()");

        return -1;
    }

    return 0;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM