【问题标题】:Shell job control外壳作业控制
【发布时间】:2012-11-11 03:46:45
【问题描述】:

对于我的学校项目,我正在实施一个 shell,我需要工作控制方面的帮助。 如果我们输入一个命令,比如cat &,那么由于&,它应该在后台运行,但它不起作用。我有这个代码:

{
  int pid;  
  int status;  
  pid = fork();  
  if (pid == 0) {  
    fprintf(stderr, "Child Job pid = %d\n", getpid());  
    execvp(arg1, arg2);  
  } 
  pid=getpid();  
  fprintf(stderr, "Child Job pid is = %d\n", getpid());      
  waitpid(pid, &status, 0);  
}

【问题讨论】:

    标签: c shell


    【解决方案1】:

    您应该为 SIGCHLD 信号设置一个信号处理程序,而不是直接等待。每当子进程停止或终止时都会发送 SIGCHLD。查看process completion 的 GNU 描述。

    本文末尾有一个示例处理程序(我在下面或多或少地复制并粘贴了它)。试着用它来建模你的代码。

     void sigchld_handler (int signum) {
         int pid, status, serrno;
         serrno = errno;
         while (1) {
             pid = waitpid(WAIT_ANY, &status, WNOHANG);
             if (pid < 0) {
                 perror("waitpid");
                 break;
             }
             if (pid == 0)
               break;
             /* customize here.
                notice_termination is in this case some function you would provide
                that would report back to your shell.
             */             
             notice_termination (pid, status);
         }
         errno = serrno;
     }
    

    关于这个主题的另一个很好的信息来源是Advanced Programming in the UNIX Environment,第 8 章和第 10 章。

    【讨论】:

      【解决方案2】:

      父进程在子进程上调用waitpid,这将阻塞直到子进程改变状态(即终止)。

      【讨论】:

      • 查看waitpid的第三个参数;可以选择立即返回。在这种情况下,尽管 shell 稍后需要以某种方式返回该进程,以查看它是否已完成......
      猜你喜欢
      • 1970-01-01
      • 2018-10-26
      • 2014-02-21
      • 1970-01-01
      • 1970-01-01
      • 2012-07-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多