c - system() 函数,同时 SIGCHLD 被忽略

标签 c linux unix signals child-process

这是我的代码示例

signal(SIGCHLD, SIG_IGN);

ret = system("ls -al");

if(ret < 0)
{
    perror("system failed");
    printf("return value is %d\n", ret);
}

可以毫无问题地执行ls -al 命令。

但是system()的返回值总是-1。在这种情况下,我无法获取命令的真正返回值。

一些引用资料说忽略 SIGCHLD 会影响 system() 中的 waitpid(),这就是为什么 system 总是返回 -1。

但更让我疑惑的是:SIGCHLD不是默认忽略了吗?那么为什么显式忽略 SIGCHLD 会导致这种情况呢?

有人能给我解释一下吗?

感谢@cnicutar,现在我明白了忽​​略 SIGCHLD 的影响。

但是现在我想知道有什么方法可以在SIGCHLD被忽略的情况下获取子进程的返回值吗?或者这是不可能的,因为 POSIX 规范和操作系统实现?

最佳答案

But what puzzles me more is that: isn't SIGCHLD ignored by default?

不,默认情况下它不会被忽略。默认情况下,根本没有处理程序,也不采取任何操作。

So why ignoring SIGCHLD explicitly would result in such case?

忽略 SIGCHLD 有一个有趣的副作用: child 不会变成僵尸

POSIX.1-2001 specifies that if the disposition of SIGCHLD is set to SIG_IGN or the SA_NOCLDWAIT flag is set for SIGCHLD (see sigaction(2)), then children that terminate do not become zombies and a call to wait() or waitpid() will block until all children have terminated, and then fail with errno set to ECHILD.

也就是说,您无需再等待子项,因为它们会自动收集。但是 system(3) 期待一个 child !所以 waitpid 返回一个错误并且 system(3) 行为。

关于c - system() 函数,同时 SIGCHLD 被忽略,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25039369/

相关文章:

c - 将 void 作为返回类型写入 malloc 的包装器

c - GIOChannel 有时读取有时不读取

c - Unix 管道实验挂起

bash - 让 head 显示文件的最后一行以外的所有内容 : command substitution and standard I/O redirection

在同一函数中使用不同的值多次调用函数

复合/while 循环

c - 读取文件中的数字并找到中位数 C

linux - 如何获取一段代码的 CPU 性能计数器

c - 在命令行和 Makefile 中定义宏,在 Linux 上使用 gcc 工作,编写 C 代码

linux - Thrift 0.8.0 无法安装在 ./configure