进程退出前打印退出状态
The exit status of the process is printed before it exits
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() ,而只是 return PID。调用者将负责检测进程何时终止。
- 如果 execute() 运行 是一个前台进程,return 一个已知的非进程 PID,例如 -1,因此调用者知道不要将它添加到后台进程列表中。
- 调用者可能应该在打印提示之前检查其后台进程列表 - 在前台进程完成或后台进程有 运行 之后。确保这是通过非阻塞调用完成的。
- 传入bg作为参数执行
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() ,而只是 return PID。调用者将负责检测进程何时终止。
- 如果 execute() 运行 是一个前台进程,return 一个已知的非进程 PID,例如 -1,因此调用者知道不要将它添加到后台进程列表中。
- 调用者可能应该在打印提示之前检查其后台进程列表 - 在前台进程完成或后台进程有 运行 之后。确保这是通过非阻塞调用完成的。
- 传入bg作为参数执行