2016-09-26 96 views
0
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"); 
    } 
} 

这是我的自定义外壳程序中的执行功能。当我执行诸如gedit &之类的操作时,会在打印下一个提示之前打印退出状态。我该如何解决? 我在做什么错?该过程的退出状态在退出之前已打印

+0

你是什么意思“打印之前”?你想要它打印后? –

+0

当子进程退出时,它应该显示退出状态的权利?像gedit&在后台打开文本编辑器。当我点击关闭该过程时,然后才显示退出状态。在此之前,这个过程还在继续......好吗? –

+0

好吧,如果有一个已经运行的gedit实例,并且你再次运行它,新实例将立即退出。许多GUI程序都这样做,所以尝试使用非GUI界面程序。 – redneb

回答

0

无论变量bg设置为什么,execute()都会阻止等待函数完成。换句话说,无论您是否想在后台运行进程,都会得到相同的行为。

几点建议:

  • 当你想在后台运行的过程,不叫waitpid函数()或wait()在执行(),而是只返回PID。调用者将负责检测进程何时终止。
  • 如果execute()运行前台进程,则返回一个已知的非进程PID,如-1,以便调用者知道不要将其添加到后台进程列表中。
  • 调用者应该在打印提示之前检查其后台进程列表 - 前台进程完成或后台进程运行后。确保这是通过非阻塞呼叫完成的。
  • 传入bg作为参数执行