【问题标题】:child and parent process id子进程和父进程 ID
【发布时间】:2013-08-11 20:01:57
【问题描述】:

只是对子进程块中的父 pid 值感到困惑。我的程序如下:

 int main(int argc, char *argv[])
  {
    pid_t pid;
    pid=fork();
    if(pid==-1){
            perror("fork failure");
            exit(EXIT_FAILURE);
    }
    else if(pid==0){
            printf("pid in child=%d and parent=%d\n",getpid(),getppid()); 
    }
    else{
            printf("pid in parent=%d and childid=%d\n",getpid(),pid);
    }
    exit(EXIT_SUCCESS);
  }

输出: parent=2642 和 childid=2643 中的 pid

pid=2643 和 parent=1

在“高级 Unix 编程”中,它说子进程可以使用 getppid() 函数获取父进程 ID。但在这里我得到“1”,即“init”进程ID。

如何在子进程块中获取父 pid 值。请帮助我获取输出。

我在“Linux Mint OS”中执行,但在“WindRiver”操作系统中没有遇到这个问题。这个程序会根据操作系统改变行为吗?

【问题讨论】:

标签: c fork pid


【解决方案1】:

那是因为父亲可以/将在儿子之前退出。如果父亲在没有请求其孩子的返回值的情况下存在,则孩子将由 pid=1 的进程拥有。经典 UNIX 或 GNU 系统 SystemV init 上有什么。

解决方法是在父亲中使用waitpid()

int main(int argc, char *argv[])
{
    pid_t pid;
    pid=fork();
    if(pid==-1){
        perror("fork failure");
        exit(EXIT_FAILURE);
    }
    else if(pid==0){
        printf("pid in child=%d and parent=%d\n",getpid(),getppid()); 
    }
    else{
        printf("pid in parent=%d and childid=%d\n",getpid(),pid);
    }

    int status = -1;
    waitpid(pid, &status, WEXITED);

    printf("The child exited with return code %d\n", status);
    exit(EXIT_SUCCESS);
}

【讨论】:

  • 我把“sleep(2)”放在程序的最后,运行良好,你的回答是正确的。
【解决方案2】:

在分叉之后,您有两个新进程,您可以知道父进程中的子 ID,但反之则不行。如果你真的需要这个,你必须在 fork 之前打开一个管道(popen),然后父母可以将它写入管道并且孩子可以读取它。

【讨论】:

    【解决方案3】:

    一旦父进程完成执行,子进程仍在运行。然后孩子被称为孤儿(因为它的父母死了),如果您以 root 登录(其 pid =1),它将被 init 进程采用。

    如果您希望子级在父级之前先退出,请使用 wait() 系统调用及其变体。

    【讨论】:

      【解决方案4】:
      #include <stdio.h>
      #include <unistd.h>
      
      int main()
      {
        int pid,pid2;
        pid=fork();
      
        if (pid<0) {
          printf("fork failed");
          exit(-1);
        } else if (pid==0) {
          printf("child id is%d",getpid());
          execlp("/bin/ls","is",NULL);
          printf("\nsleeping for 2 seconds using pid of child class");
          sleep(2);
      
          printf("killing the child process");
          kill(getpid());
        } else {
          wait(NULL);
          printf("The parent id is %d\n",getpid());
          printf("The child id is %d\n",getpid());
          printf("\nsleeping for 3 seconds without pid");
          sleep(3);
          printf("\nchild completed\n");
      
          exit(0);
        }
      }
      

      【讨论】:

      • 解释你的答案
      • 这是一个计算子id和父id的基本c程序,包括sleep函数。
      【解决方案5】:

      很简单,因为父进程不再存在。如果你调用wait()系统函数,那么它会一直存在,直到子进程完成它的工作,你会得到父进程的PID。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-05-23
        • 2011-07-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-08-09
        相关资源
        最近更新 更多