2012-02-05 82 views
11

我在for -loop中创建子进程。在子进程内部,我可以用getpid()检索子PID。如何在C中获取子PID?

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

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

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

+0

哇我觉得/我像一个白痴,thx的快速反应! – Derek 2012-02-05 07:51:27

+0

@Johnsyweb这显然是2句话。在子进程/里面。在这些子进程里面''。 – glglgl 2012-02-05 07:56:58

+0

@glglgl:啊哈。我是个白痴。已经编辑了这个问题,让像我这样的人更清楚:) – Johnsyweb 2012-02-05 08:00:00

回答

24

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

看看人2叉:

返回值

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. 
-4

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

+2

-1'getpid()'返回调用进程的pid,而不是它的子(ren) – Celeritas 2014-09-26 00:53:32

1

正如前面的答案中所述,“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是非常有益和详细解释。

0

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

pid = fork() 

然后PID其实你的孩子PID。所以你可以从父母打印出来。