gpt4 book ai didi

c - 确定终止进程的pid

转载 作者:行者123 更新时间:2023-11-30 17:39:36 25 4
gpt4 key购买 nike

我试图找出发送 SIGCHLD 信号的进程的 pid,并且我想在为 SIGCHLD 创建的信号处理程序中执行此操作。我该怎么做?我正在尝试:

int pid = waitpid(-1, NULL, WNOHANG);

因为我想等待生成的任何子进程。

最佳答案

如果您使用waitpid()或多或少如图所示,您将被告知一个已死亡的子进程的 PID - 通常,这将是唯一已死亡的进程,但如果您收到一堆子进程,您可能会收到一个信号和许多信号收集尸体。因此,使用:

void sigchld_handler(int signum)
{
pid_t pid;
int status;
while ((pid = waitpid(-1, &status, WNOHANG)) > 0)
{
unregister_child(pid, status); // Or whatever you need to do with the PID
}
}

如果您不关心子进程的退出状态,可以将 &status 替换为 NULL

不同的系统对 waitpid() 返回值的记录略有不同。然而,POSIX 是比较谨慎的之一,它说:

If wait() or waitpid() returns because the status of a child process is available, these functions shall return a value equal to the process ID of the child process for which status is reported. If wait() or waitpid() returns due to the delivery of a signal to the calling process, -1 shall be returned and errno set to [EINTR]. If waitpid() was invoked with WNOHANG set in options, it has at least one child process specified by pid for which status is not available, and status is not available for any process specified by pid, 0 is returned. Otherwise, -1 shall be returned, and errno set to indicate the error.

关于c - 确定终止进程的pid,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21764580/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com