c-在后台运行的程序的退出状态 [英] c - exit status of a program running in background

查看:73
本文介绍了c-在后台运行的程序的退出状态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个任务,其中我必须创建一个迷你外壳,该迷你外壳能够执行很多工作,包括作业控制.我设法使用fork和execvp创建新作业.但我也想获取execvp运行的程序的退出代码.从我从其他帖子中查找的内容来看,我可以使用if(WIFEXITED(status))来做到这一点.

I have an assignment in which I have to create a mini shell which is capable of doing a lot of things including job control. I managed to create new jobs using fork and execvp. But I also want to get the exit codes of the programs run by execvp. From what I have looked up from other posts I can do this by using if(WIFEXITED(status)).

但是,如果用户输入&",我们还需要在后台运行该过程在外壳中带有进程名称.因此,在子程序在后台完成时等待父进程等待是没有意义的.我是否可以设置任何中断来通知父进程子进程已结束?然后,我可以使用if(WIFEXITED(status))语句获取退出代码.

But we are also required the run the process in the background if user enters '&' with the process name in the shell. So it doesn't make sense to wait for the parent process to wait while the child program finishes in background. Is there any interrupt that I can set up which notifies the parent process that the child process has ended? Then I can use the if(WIFEXITED(status)) statement to get the exit code.

示例

sleep 100 &

将在后台运行,而我可以在前台同时执行其他shell命令.

will run in the background while I can execute other shell commands in the foreground simultaneously.

推荐答案

如果您没有做任何特别的事情,当孩子去世时,父母会收到SIGCHLD.不过请注意,多个子项可以同时终止,并且您会收到一个信号.解决此问题的正确方法是循环(在信号处理程序中):

If you don't do anything special the parent receives a SIGCHLD when the child dies. Careful though, multiple children can terminate at the same time and you'll get a single signal. The correct way to handle this is to loop (in the signal handler):

while (waitpid(-1, NULL, WNOHANG) > 0)
    /* Stuff. */

这篇关于c-在后台运行的程序的退出状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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