识别儿童过程的孩子?

时间:2017-01-23 08:25:14

标签: c fork

如何识别子进程与其子进程?

 pid_t pid = fork();
 if (pid == 0) // child 1
 {
   int pid2 = fork(); 
   if (pid2 == 0)// child of child 1
   { ....

我们如何区分孩子1和孩子?他们都有相同的pid 0?

1 个答案:

答案 0 :(得分:1)

  

fork()返回值:   0 - 在儿童过程中;   PID - >父进程中的子PID; -1 - >错误

您可以通过getpid()

在子流程中获取PID
 if (pid == 0) {
   pid_t child_pid = getpid();
 }

您的代码包含一些细节:

 pid_t pid = fork();
 if (pid == 0) // child 1
 {
   // child process
   pid_t p = getpid(); // Child process pid
   int pid2 = fork(); 
   if (pid2 == 0) { 
     // child of child process
     pid_t p = getpid(); // Child of child process pid
   } else if (pid2 > 0) {
     // Still child process
     //pid2 -> child of child PID
   }
 } else if (pid > 0) {
   // Still main process
   // pid -> child PID
   pid_t p = getpid(); // Main process pid
 }
相关问题