##system,waitpid使用时的坑
system这个函数可以用来执行shell命令,这也是我们平常使用比较多,或者说比较喜欢使用的地方,但使用时也有很多坑等着你。
下面这段代码大家应该不难理解,作用是忽略掉SIGCHLD这个信号量。
/* Ignore SIGCHLD to avoid zombie process */
if (signal(SIGCHLD, SIG_IGN) == SIG_ERR) {
return -1;
} else {
return 0;
}
你把SIGCHLD忽略掉,你会很理直气壮的说,防止wait/waitpid收尸时出现僵死进程,你说得很对,很合理,僵尸进程是需要有人来处理,否则也是一件很糟糕的事。
可是,在程序的另一个模块里,可能不是你这组的人开发的,是另一组负责开发的,他们想用system函数去执行一些shell命令来为他们处理一些业务逻辑之类的事,比如:
int status = system(“gzip -c /var/opt/abc.txt > /var/opt/abc.zip”);
你会发现status一直不等于0,为什么呢?在回答为什么前,先熟悉下system函数。
-
system函数
system() executes a command specified in command by calling /bin/sh -c command, and returns after the command has been completed. During execution of the command, SIGCHLD will be blocked, and SIGINT and SIGQUIT will be ignored.
system()函数调用/bin/sh来执行参数指定的命令,/bin/sh 一般是一个软连接,指向某个具体的shell,比如bash,-c选项是告诉shell从字符串

最低0.47元/天 解锁文章
5137

被折叠的 条评论
为什么被折叠?



