簡體   English   中英

使用PID跟蹤父進程並顯示其子和孫PID

[英]Trace parent process with PID and display it's child and grandchild PID

我設法為每個進程輸出正確的進程ID順序,但是我的問題是我無法顯示子進程的PID。

我的程序能夠打印父母的PID和孫子的PID。 我確實看到了孩子的PID,但它顯示為父母的PID。

如何計算孩子的PID並將其添加到代碼中? 我希望我的輸出顯示父母的PID,孩子的PID和孫子的PID。

 #include <sys/types.h> #include <sys/wait.h> #include <unistd.h> #include <iostream> #include <stdio.h> #include <stdlib.h> using namespace std; int main() { pid_t pid; //process id const char *message; int n; int exit_code; cout << "\\nfork program starting\\n"; pid = fork(); switch ( pid ) { case -1: cout << "Fork failure!\\n"; return 1; case 0: pid = fork(); cout << "Parent PID = " << getppid() << endl; switch ( pid ) { case -1: cout << "Fork Failure!\\n"; return 1; case 0: cout << "Grandchild finished: PID = " << getpid() << endl; message = "This is the child\\n"; n = 5; exit_code = 9; break; } } //waiting for child to finish if ( pid != 0 ) { //parent int stat_val; pid_t child_pid; child_pid = wait( &stat_val ); //wait for child if (WIFEXITED (stat_val)) cout << "child exited with code " << WEXITSTATUS (stat_val) << endl; else cout << "child terminated abnormally!" << endl; } exit ( exit_code ); } 

截圖

似乎您沒有在第二個fork()之前優先使用子PID

更改:

case 0:
   pid = fork();
    cout << "Parent PID = " << getppid() << endl;
    switch ( pid ) {
      case -1:
        cout << "Fork Failure!\n";
        return 1;
    [...]
    }

至:

case 0:
   cout << "Child PID = " << getpid() << endl;
   pid = fork();

   cout << "Parent PID = " << getppid() << endl;
   switch ( pid ) {
      case -1:
        cout << "Fork Failure!\n";
        return 1;
   [...]
   }

在這里,在第一行之后,打印getpid(),而不是稍后打印。 然后使用pid2或其他標識符,而不是使用相同的pid。 那將解決您的所有問題。

 case 0:
   pid = fork();
    cout << "Parent PID = " << getppid() << endl;
    switch ( pid ) {
    case -1:
      cout << "Fork Failure!\n";
      return 1;
  case 0:
    cout << "Grandchild finished: PID = " << getpid() << endl;//

為什么會發生問題? 因為僅在“第二種情況0”之后,即您的孩子的孩子才打印getpid(),這顯然打印了孫孩子的PID。 相反,您應該嘗試使用“ default:”,它將對一級子級和二級父級起作用(因為不是pid!= 0,因此不是孫級子代)。 值得注意的是,您不允許父母的情況。 您給出了一種失敗的情況(-1),另一種失敗的情況是孩子(0),而沒有任何一種情況。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM