我在for-loop中创建子进程.在子进程内部,我可以检索子PID getpid().
但是,出于某种原因,当我尝试将值存储getpid()到父进程声明的变量中时,当我在父进程中检查它时,更改无效.我假设这与某种过程变量范围有关.不太熟悉C,所以不能太确定.
无论如何,什么是将getpid()子PID 的结果(当从子进程调用时)存储到父进程中的变量的方法?
或者也许另一种方法是存储fork()到父变量中并调用该变量上的某个函数来检索子节点的PID?我不知道怎么做,所以如果这是更好的方法,你会怎么做?
MBy*_*ByD 30
fork已经返回孩子的pid.只需存储返回值.
看看男人2叉:
返回值
Run Code Online (Sandbox Code Playgroud)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.
正如前面的回答中提到的,“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 */
}
Run Code Online (Sandbox Code Playgroud)
此链接非常有用并详细解释。