您的位置:首页 > 其它

解决system调用返回ECHILD的问题

2015-08-03 11:14 225 查看
system调用返回ECHILD

再来看看system返回ECHILD错误的原因,根据system内部实现fork-exec-waitpid,查到应该是waitpid设置了errno,查看waitpid的man page,有下面的描述信息:

If the calling process has SA_NOCLDWAIT set or has SIGCHLD set to SIG_IGN, and the process has no unwaited-for children that were transformed into zombie processes, the calling thread shall block until all of the children of the process containing the calling thread terminate, and wait() and waitpid() shall fail and set errno to [ECHILD].

我的理解是,如果调用进程设置了SIGCHLD为SIG_IGN,那么使用waitpid的时候会阻塞,等待子进程执行完,并且设置errno为ECHILD。

由此我们解决问题的思路已经明朗了,因为我们的代码在最开始将SIGCHLD设置为SIG_IGN,所以现在我们在调用system的时候,需要将信号还原,设置为默认值SIG_DEF,参考了http://my.oschina.net/renhc/blog/54582 这篇博客后,修改方式如下:

typedef void (*sighandler_t)(int);
int pox_system(const char *cmd_line)
{
int ret = 0;
sighandler_t old_handler;

old_handler = signal(SIGCHLD, SIG_DFL);
ret = system(cmd_line);
signal(SIGCHLD, old_handler);

return ret;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: