gpt4 book ai didi

c++ - 父进程的父进程 ID - Linux

转载 作者:太空宇宙 更新时间:2023-11-04 04:05:45 25 4
gpt4 key购买 nike

我有一个链中的三个进程:P1 -> P2 -> P3。我希望能够从子进程(P3)中打印出所有三个进程的 id。

所以,我的问题是如何使用 getppid() 等获取孙子(P3)的祖 parent (P1)的pid?

或者我是否必须将每个进程的 pid 存储在自己的变量中以供以后使用(不可取)?

感谢您为我提供的任何帮助。另外,只是因为,这是迄今为止我的代码:

//test_wait.cpp
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <stack>

using namespace std;

int main()
{
pid_t pid; //process id
const char *message;
int n;
int exit_code;
std::stack<int> proc_stack;

cout << "Fork program starting\n";
proc_stack.push(getpid());
pid = fork();
switch ( pid ) {
case -1:
cout << "Fork failure!\n";
return 1;
case 0:
pid = fork();
switch ( pid ) {
case -1:
cout << "Fork Failure!\n";
return 1;
case 0:
cout << "Grandchild PID: " << getpid() << endl;
cout << "Parent PID: " << getppid() << endl;
cout << "Grand Parent PID: " << proc_stack.top() << endl;
exit_code = 9;
break;
default:
exit_code = 0;
break;
}
default:
exit_code = 0;
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
}
exit ( exit_code );
}

所以,我最终使用堆栈来存储信息。如上面的代码所示。

最佳答案

在子情况0时,您需要打印pid和ppid:引用此代码。

  //test_wait.cpp
#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 << "fork program starting\n";
pid = fork();
switch ( pid ) {
case -1:
cout << "Fork failure!\n";
return 1;
case 0:
cout << "Child1 finished: PID = " << getpid() << endl;
cout << "Parent PID = " << getppid() << endl;
pid = fork();
switch ( pid ) {
case -1:
cout << "Fork Failure!\n";
return 1;
case 0:
cout << "Child2 finished: PID = " << getpid() << endl;
cout << "Parent PID = " << getppid() << endl;
message = "This is the child\n";
n = 5;
exit_code = 9;
break;
default:
message = "This is the parent\n";
n = 3;
exit_code = 0;
break;
}
default:
message = "This is the grand parent\n";
n = 3;
exit_code = 0;
break;
}
for ( int i = 0; i < n; ++i ) {
cout << message;
sleep ( 1 );
}
//waiting for child to finish
if ( pid != 0 ) { //parent
int stat_val;
pid_t child_pid;

child_pid = wait ( &stat_val ); //wait for child
}
exit ( exit_code );
}

您还可以从/proc获取ppid

cat/proc/pid/stat例如对于 PID #20467:

cat /proc/20467/stat

20467 (abc) S 20137 20467 20125 34818 20467 4202496 1930 5196 22 0 113 162 32 25 20 0 1 0 1701252 14548992 1606 4294967295 4194304 6492552 2076847264 2076842300 694388884 0 0 0 134889479 2151083916 0 0 17 0 0 0 221 0 0

上面的 20137(第 4 字段)是 PPID。

关于c++ - 父进程的父进程 ID - Linux,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21224943/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com