【问题标题】:How to get child PID in C?如何在C中获得子PID?
【发布时间】:2012-02-27 04:46:24
【问题描述】:

我正在for-loop 中创建子进程。在子进程中,我可以使用getpid() 检索子PID。

但是,由于某种原因,当我尝试将 getpid() 的值存储到父进程声明的变量中时,当我在父进程中检查它时,更改将无效。我假设这与某种流程变量范围有关。不是很熟悉C,所以不能太确定。

无论如何,将子 PID(从子进程调用时)的getpid() 的结果存储到父进程中的变量中的方法是什么?

或者另一种方法是将fork() 存储到父变量中并调用该变量上的某个函数来检索孩子的PID?我也不知道该怎么做,所以如果这是更好的方法,你会怎么做?

【问题讨论】:

  • 哇,我觉得/我像个白痴,谢谢你的快速反应!!!!
  • @Johnsyweb 这显然是两句话。 s/ and inside the child process/. Inside these child processes/.
  • @glglgl:啊哈。我是个白痴。已经编辑了这个问题,让像我这样的人更清楚:)

标签: c fork pid


【解决方案1】:

fork 已经返回了孩子的 pid。只需存储返回值即可。

看看 man 2 fork:

返回值

 Upon successful completion, fork() returns a value of 0 to the child process and
 returns the process ID of the child process to the parent process.  Otherwise, a
 value of -1 is returned to the parent process, no child process is created, and
 the global variable errno is set to indicate the error.

【讨论】:

    【解决方案2】:

    获取父进程和子进程的进程id主要有两个函数。 getpid() 和 getppid()

    【讨论】:

    • -1 getpid() 返回调用进程的pid,而不是child(ren)
    【解决方案3】:

    前面的回答提到“fork()给子进程返回值0,把子进程的进程ID返回给父进程”。所以,代码可以这样写:

    pid = fork(); /* call fork() from parent process*/
    if (0 == pid)
    {
      /* fork returned 0. This part will be executed by child process*/
      /*  getpid() will give child process id here */
    }
    else
    {
      /* fork returned child pid which is non zero. This part will be executed by parent process*/
      /*  getpid() will give parent process id here */
    } 
    

    这个link很有帮助,讲解的很详细。

    【讨论】:

      【解决方案4】:

      如果你通过以下方式调用fork:

      pid = fork()
      

      那么 pid 实际上就是你的孩子的 PID。所以你可以从父级打印出来。

      【讨论】:

        【解决方案5】:

        如果fork()创建成功,则在子进程中返回0值。

        int main(void)
        {
            int id;
            id= fork();
            if(id==0)
            {
                printf("I am child process my ID is   =  %d\n" , getpid());
            }
        }
        

        【讨论】:

          【解决方案6】:

          是的,子进程的pid已经用fork()返回了,fork()调用一次返回两次,父子进程的返回值不同,所以可以这样做:

          pid_t pid, pid_c;
          pid = fork();
          if (pid == -1) {  // error
              perror("Falied to fork");
          } else if(pid == 0) {  // execute in child process
              // you can get child's pid by getpid() in child process:
              pid_t tmp_pid_c = getpid();
              execl("bin/ls", "ls", "./", NULL);
          } else {
              // you can also get child's pid that already returned by fork() in parent process
              pid_c = pid;
          }
          

          【讨论】:

            猜你喜欢
            • 2016-05-25
            • 2021-05-14
            • 2023-04-04
            • 1970-01-01
            • 2012-03-07
            • 2020-11-05
            • 2022-06-15
            • 2014-12-14
            • 1970-01-01
            相关资源
            最近更新 更多