我在实施自己的手工制作的外壳时遇到了一些麻烦。我已经能够分叉一个进程并使用waitpid在foregroud中运行它,但是当我尝试在后台运行简单的进程时,例如'sleep 5&',这个过程似乎永远都会运行。 checkListJobs将确定进程是否已完成运行,但它永远不会停止。任何帮助将不胜感激。我假设错误在我的“foo”函数中。
void insertJob(int pid) {
printf("beginning job %d.\n", pid);
struct job *node = malloc(sizeof(struct job));
node->pid = pid;
node->next = NULL;
if(root == NULL) {
root = node;
} else {
node->next = root;
root = node;
}
}
void checkListJobs(int z) {
curr = root;
while(curr!=NULL) {
if(kill(curr->pid,0) != 0) {
if(prev==NULL) {
prev = curr;
root = curr;
} else {
prev->next = curr->next;
}
} else {
if(!z) printf("%d is still running.\n", curr->pid);
}
prev = curr;
curr = curr->next;
}
}
//code for child forking
void foo(char *cmd, char *argv[], int args) {
int bgFlag;
if(!strcmp(argv[args], "&")){
argv[args] = '\0';
bgFlag = 1;
}
int pid = fork();
int status = 0;
if(pid==0){
if(bgFlag) {
fclose(stdin); // close child's stdin
fopen("/dev/null", "r"); // open a new stdin that is always empty
}
execvp(cmd, argv);
// this should never be reached, unless there is an error
fprintf (stderr, "unknown command: %s\n", cmd);
exit(0);
} else {
if(!bgFlag) {
waitpid(pid, &status, 0);
} else {
insertJob(pid);
}
if (status != 0) {
fprintf (stderr, "error: %s exited with status code %d\n", cmd, status);
} else {
// cmd exec'd successfully
}
}
// this is the parent still, since the child always terminates from exec or exit
// continue being a shell...
}
答案 0 :(得分:1)
您需要为SIGCHLD安装信号处理程序,因为这将告诉您的程序子进程何时完成。收到SIGCHLD后,您应该调用wait()(或者值为-1的waitpid(),因为您不知道哪个子项已完成,只是一个子项已完成)。 / p>
编写处理程序最安全的方法是:
volatile sig_atomic_t sigchld;
int handle_child(int sig)
{
if (sig == SIGCHLD)
sigchld = 1;
}
在主循环中,检查sigchld
是否为1.如果是,则子进程结束,然后您可以调用waidpid()
(使用PID为-1,因为您因为多个孩子可能同时结束,所以不会知道哪个孩子在一个循环中结束了(见下文)。此外,如果任何系统调用返回错误并且errno
为EINTR
,那么它会被信号中断,因此要么返回到主循环的顶部,要么检查sigchld
并相应地处理(并且不要忘记尽快将sigchld
重置为0。
for(;;)
{
int status;
pid_t child;
child = waitpid(-1,&status,WNOHANG);
if (child == -1)
{
if (errno == ECHILD) break; /* no more children */
/* error, handle how you wish */
}
/* handle the return status of the child */
}
sigchld = 0;
你可以从信号处理程序中调用waitpid()
(POSIX说这样做是安全的)但你真的不应该在中做任何其他事情信号处理程序,因为它可能导致非常微妙的错误(例如,在调用malloc()
期间引发SIGCHLD ---信号处理程序中导致调用malloc()
的任何代码将导致非常讨厌的问题。这就是为什么我建议在信号处理程序中设置一个标志 - 你在信号处理程序中做的越多越好。)