c - 进程退出前打印退出状态

标签 c shell exit

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/

相关文章:

c++ - 非常奇怪的 C 行为

c - C编程如何以写模式生成1024个文件

ios - ld : library not found for -lyoutube-ios-player-helper

bash - 用 exit 结束 bash 脚本有什么好处

c - 了解 EOF 和中断

c - 这个 C 中的 Codechef 阶乘解是如何工作的?

bash - 防止 bash 在变量输出中添加单引号

ios - UIImage 不在屏幕上绘制

bash - shell 脚本: kill program after set time if output file is empty

android - android 中的退出按钮不起作用