这是我的代码示例
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()
orwaitpid()
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/