简体   繁体   中英

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

I managed to output the correct order of process id's for each individual process but my issue is that I can't display the child's PID.

My program is able to print parent's PID, and grandchild's PID. I do see the child's PID but it displays as parent's PID.

How can I compute child's PID and add it to my code? I would like my output to display parent's PID, child's PID, and grandchild's 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 ); } 

截图

it does not seem you are prining the child PID before the 2nd fork()

change:

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

to:

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

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

here, just after the first line, print getpid(), instead of printing it later. Then use pid2 or different identifier, instead of using same pid. That will solve all your problems.

 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;//

Why the problem happened? Because only after 'second case 0', that is child of the child your are printing getpid(), which apparently prints grand child's PID. Instead you should try 'default:' which will work for first level child & second level parent (that is not grand child since not pid!=0). Notably you did not allow case for parent. you gave one case for failure (-1) and another for child(0) and none for parent.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM