How to get child PID in C?

∥☆過路亽.° 提交于 2019-11-30 08:26:06

fork already returns the child's pid. Just store the return value.

look at man 2 fork:

RETURN VALUES

 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.

As mentioned in previous answer that "fork() returns a value of 0 to the child process and returns the process ID of the child process to the parent process." So, the code can be written in this way:

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 */
} 

This link is very helpful and explains in detail.

if fork() is successfully created then it returns 0 value in the child process.

int main()
{
int id;

id= fork();

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

If you are calling fork in the following way:

pid = fork()

Then pid is in fact your child PID. So you can print it out from the parent.

There are two main functions to get the process id of parent process and child. getpid() and getppid()

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!