void execute(char **argv,int num)
{
int i;
pid_t pid;
int status;
int child_status;
if ((pid = fork()) < 0)
{ /* fork a child process*/
printf("*** ERROR: forking child process failed\n");
exit(1);
}
else if (pid == 0)
{ /* for the child process: */
int c;
if (c==execvp(argv[0], argv) < 0)
{ /* execute the command */
printf("%d\n", c);
printf("*** ERROR: exec failed\n");
perror(" ");
exit(1);
}
}
else if(bg!=1){
while (waitpid(pid,&status,WNOHANG|WUNTRACED));
}
else if(bg==1)
{
wait (&child_status);
if (WIFEXITED (child_status))
{
printf("the child process exited normally, with exit code %d\n",
WEXITSTATUS (child_status));
}
else
printf ("the child process exited abnormally\n");
}
}
这是我在自定义 shell 中的执行函数。当我做类似 gedit &
的事情时在打印下一个提示之前打印退出状态。我该如何解决?
我做错了什么?
最佳答案
无论变量 bg 设置为什么,execute() 都会阻塞等待函数完成。换句话说,无论您是否想在后台运行进程,您都会得到相同的行为。
一些建议:
- 当你想在后台运行一个进程时,不要在execute()中调用waitpid()或wait(),而只返回PID。调用者将负责检测进程何时终止。
- 如果execute()运行前台进程,则返回一个已知的非进程PID,例如-1,以便调用者知道不要将其添加到后台进程列表中。
- 调用者可能应该在打印提示之前检查其后台进程列表 - 在前台进程完成或后台进程运行之后。确保这是通过非阻塞调用完成的。
- 传入bg作为参数执行
关于c - 进程退出前打印退出状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39709778/