如何向通过 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 能够向 foo 发送 SIGCONT,以便它可以继续打印任务,然后再次发送 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;
}