How to get child PID in C?

后端 未结 5 650
失恋的感觉
失恋的感觉 2020-12-31 03:10

I\'m creating child processes in a for-loop. Inside the child process, I can retrieve the child PID with getpid().

However, for some reas

相关标签:
5条回答
  • 2020-12-31 03:43

    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.
    
    0 讨论(0)
  • 2020-12-31 03:49

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

    int main(void)
    {
        int id;
        id= fork();
        if(id==0)
        {
            printf("I am child process my ID is   =  %d\n" , getpid());
        }
    }
    
    0 讨论(0)
  • 2020-12-31 03:51

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

    0 讨论(0)
  • 2020-12-31 03:53

    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.

    0 讨论(0)
  • 2020-12-31 03:55

    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.

    0 讨论(0)
提交回复
热议问题