忽略SIGCHLD的system()函数 [英] system() function while SIGCHLD is ignored

查看:180
本文介绍了忽略SIGCHLD的system()函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的代码示例

signal(SIGCHLD, SIG_IGN);

ret = system("ls -al");

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

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

The ls -al command can be executed without any problem.

但是 system()的返回值始终为-1。在这种情况下,我无法获得命令的实际返回值。

But the return value of system() is always -1. In this case, I can't get the real return value of the command.

某些参考文献指出忽略SIGCHLD会影响 waitpid() system()中,这就是为什么 system 总是返回-1的原因。

Some reference says that ignore SIGCHLD would affect waitpid() in system(), that's why system always returns -1.

但令我更加困扰的是:默认情况下,SIGCHLD是否不被忽略?那么,为什么显式地忽略SIGCHLD会导致这种情况呢?

But what puzzles me more is that: isn't SIGCHLD ignored by default? So why ignoring SIGCHLD explicitly would result in such case?

有人可以向我解释吗?

@cnicutar现在我了解忽略SIGCHLD的影响。

Thanks to @cnicutar now I understand the effects of ignoring SIGCHLD.

但是现在我想知道是否有任何方法可以在忽略SIGCHLD的情况下获取子进程的返回值?还是由于POSIX规范和OS实现而这不可能吗?

But now I'm wondering is there any methods to get the return value of child process while SIGCHLD is ignored? Or is this just impossible due to the POSIX specification and OS realizaiton?

推荐答案


但是,令我更加困扰的是:默认情况下,SIGCHLD是否会被忽略? p>

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

否,默认情况下不会被忽略。默认情况下,根本没有处理程序并且不执行任何操作。

No, by default it is not ignored. By default there is simply no handler and no action is taken.


那么为什么显式忽略SIGCHLD会导致这种情况?

So why ignoring SIGCHLD explicitly would result in such case?

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

Ignoring SIGCHLD has an interesting side-effect: children don't become zombies.


POSIX.1-2001指定是否将SIGCHLD的处置设置为
SIG_IGN或SA_NOCLDWAIT标记为SIGCHLD设置(请参阅
sigaction(2)),然后终止的子代不会成为僵尸,并且
a调用 wait() waitpid()将阻塞,直到所有子
都终止,然后在errno设置为ECHILD时失败。

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)想要一个孩子!因此, waitpid 返回错误,并且 system(3)起作用。

That is, you don't need to wait any longer for children since they get collected automatically. But system(3) expected a child! So waitpid returns an error and system(3) behaves.

这篇关于忽略SIGCHLD的system()函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆