【问题标题】:setpgid for Child Process: No Such Process子进程的setpgid:没有这样的进程
【发布时间】:2018-01-31 00:36:14
【问题描述】:

我不知道为什么我的电脑会出现这样的错误。我已经在其他一些计算机上测试了代码。效果很好。

如果我删除sleep(2),它会起作用。我想我应该能够为僵尸进程设置 PGID。是否依赖于操作系统实现?

#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>

#define CHECK(syscall, msg) do {                    \
    if ((syscall) == -1) {                          \
      perror(msg);                                  \
      _exit(1);                                     \
    }                                               \
  } while(0)

#define SAFE_CLOSE_NOT_STD(fd) do {                                 \
    if (fd != STDIN_FILENO && fd != STDOUT_FILENO && fd != -1) {    \
      CHECK(close(fd), "close error");                              \
      fd = -1;                                                      \
    }                                                               \
  } while(0)

int main () {
  int ls_pid;
  char *ls_argv[] = { "ls", NULL };

  CHECK(ls_pid = fork(), "fork error");
  if (!ls_pid) {
    CHECK(setpgid(0, 0), "child setpgid error");
    CHECK(execvp(ls_argv[0], ls_argv), "execve error");
  } else {
    printf("child pid:%d\n", ls_pid);
    sleep(2); // no error arises if I remove this line
    CHECK(setpgid(ls_pid, ls_pid), "setpgid error"); // error here
  }
  CHECK(wait(NULL), "wait error");

  printf("Finish\n");
}

【问题讨论】:

    标签: c unix operating-system


    【解决方案1】:

    您在睡眠时收到错误,因为子进程已退出并且不再存在。除了调用wait,你不能对僵尸进程做任何事情。

    【讨论】:

      【解决方案2】:

      sleep 发生时parents 执行它切换到child 进程和子进程execvp 用新进程替换当前进程并退出。当2 seconds 子进程不存在后返回父进程时,setpgid 失败的原因。

      CHECK(setpgid(ls_pid, ls_pid), "setpgid error");
      

      setpgid 的手册页可以看出,这是一个EACCES 错误

      试图更改进程组 ID 调用进程的子进程之一和 child 已经执行了 execve(2) (setpgid(), setpgrp())。

      【讨论】:

      • 假设我在子进程退出之前更改了它的PGID。现在子进程和父进程有不同的PGID。哪个是前台组?
      • 任何时候,会话中只有一个进程组可以是终端的前台进程组;其余进程组在后台。
      猜你喜欢
      • 2018-03-26
      • 1970-01-01
      • 1970-01-01
      • 2021-06-11
      • 1970-01-01
      • 2016-11-16
      • 2014-05-11
      • 2016-06-25
      • 2014-08-26
      相关资源
      最近更新 更多