【问题标题】:SIGCHLD is sent on SIGCONT on Linux but not on macOSSIGCHLD 在 Linux 上的 SIGCONT 上发送,但在 macOS 上不发送
【发布时间】:2018-01-28 15:25:30
【问题描述】:

在主进程中我监听 SIGCHLD:

signal(SIGCHLD, &my_handler);

然后我fork()execv() 让它在后台运行(例如/bin/cat)。

当我尝试从终端向子进程发送 SIGSTOP 时,my_handler() 被调用。但是当我尝试向它发送 SIGCONT 时,处理程序不会在 macOS 上调用,而是在我的 Ubuntu 上执行。

男人:

SIGCHLD:子状态已更改。

我错过了什么吗?这是预期的行为吗?我在 Ubuntu 上编写了我的应用程序,并希望它也能在 mac 上运行。

我也尝试了sigaction(),但结果相同。

这里有一个示例代码来演示:

#include <signal.h>
#include <sys/wait.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>

void    my_handler(int signum)
{
    printf("\t SIGCHLD received\n");
    fflush(stdout);
}

void    my_kill(pid_t pid, int signum)
{
    printf("Sending %d\n", signum);
    fflush(stdout);

    kill(pid, signum);

    printf("Sent %d\n\n", signum);
    fflush(stdout);
}

int main()
{
    pid_t   pid;
    char    *cat_args[2] = {"/bin/cat", NULL};

    signal(SIGCHLD, &my_handler);
    pid = fork();

    if (pid == 0)
    {
        execv("/bin/cat", cat_args);
    }
    else
    {   
        my_kill(pid, SIGSTOP);
        my_kill(pid, SIGCONT);
        wait(NULL);
    }
    return 0;
}

在 macOS 上输出:

Sending 17
         SIGCHLD received
Sent 17

Sending 19
Sent 19

【问题讨论】:

  • printf("\t SIGCHLD received\n"); fflush(stdout); 在信号处理程序中?!?!?你是否试图让你的进程陷入僵局?您可以从信号处理程序中安全地调用 only 异步信号安全函数。 printf()fflush() 不是异步信号安全的。

标签: c linux macos signals child-process


【解决方案1】:

该行为是可选的。实现不需要在继续时生成 SIGCHLD。 POSIX.1-2008(2016版)使用的语言是“may”而不是“shall”:

当一个停止的进程继续运行时,可能会为其父进程生成一个 SIGCHLD 信号,除非父进程设置了 SA_NOCLDSTOP 标志。

-System Interfaces, 2.4.3 Signal Actions

...一个 SIGCHLD 信号可能在调用进程的任何停止子进程继续运行时生成。

- System Interfaces sigaction "Description"

添加了重点。

【讨论】:

    【解决方案2】:

    我错过了什么吗?

    可能不会。

    这是预期的行为吗?

    可能是的。

    OSX 基于 4.4 BSD,这个 BSD 根本不支持在子进程继续时向父进程发送SIGCHLD。早期版本的 Linux 也缺乏这种支持。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-01-22
      • 2016-01-21
      • 2020-11-29
      • 1970-01-01
      • 2023-02-07
      • 1970-01-01
      相关资源
      最近更新 更多