getppid()返回父进程的进程ID。
因为任何给定的进程在任何时候都只能有一个父进程。 从getppid返回是有道理的。
是否有与getChildPid相同的系统调用?
我知道一个过程可以有很多孩子,但就我而言,我确信我的过程在任何时候都只有一个孩子。因此,在我的情况下,如上所述进行系统调用是有意义的。
编辑:子项由外部库生成,该库不会公开fork()
返回的pid。
答案 0 :(得分:3)
一个进程可以有很多子进程,只有一个进程才能返回其中一个进程。最广泛使用的机制是从fork
保存返回的pid。
答案 1 :(得分:1)
有些API被破坏,并且没有暴露孩子的pid - 在MacOS上,AuthorizationExecuteWithPrivileges
就是一个例子。 API没有给你孩子pid是完全错误的,因为你必须能够waitpid
来清理僵尸!
对于这些损坏的API,这是一种解决方法(例如由Chrome使用)。在伪代码中:
pid_t sneakyFork(std::vector<const char*> args) {
std::vector<const char*> newArgs = makeVect(
"/usr/bin/perl","-w", "-e",
"printf \"%s,%s\\n\", $$, getppid();"
"$ENV{PATH} = '/usr/bin:/bin';"
"delete @ENV{'IFS', 'CDPATH', 'ENV', 'BASH_ENV'};"
"if ($#ARGV >= 0 and $ARGV[0] =~ /^(\\/.*)$/)"
"{ $ARGV[0] = $1;"
" for ($i=1; $i <= $#ARGV; $i++)"
" { $ARGV[$i] =~ /^(.*)$/; $ARGV[$i] = $1; }"
" die unless exec { $ARGV[0] } @ARGV; }",
(char*)0
);
newArgs.insert(newArgs.end(), args.begin(), args.end());
newArgs.push_back(0);
int pipe = nasty_library_call_with_stdout_inherited(newArgs);
char buf[1024];
read(pipe, &buf); // error checking...
pid_t pid, ppid;
parseBuf(buf, &pid, &ppid); // strchr for ',' and strtoul
if (ppid == getpid())
return pid; // we're the parent, the trick worked
else
return -1;
}
答案 2 :(得分:-1)
您可以维护以下结构。现在,当你执行fork()时,检查返回值(PID)。如果它不为零(大于零),则它是父进程。现在,在数组中复制该进程id。
typedef struct
{
char process[128];
pid_t current_pid;
pid_t child_pid[127];
unsigned int child_pid_index;
}my_pid_record;
my_pid_record sample;
if( ( p = fork()) > 0 )
{
printf("I am a parent process\r\n");
sample.current_pid = getpid();
strcpy(sample.process,argv[0]);
sample.child_pid[child_pid_index] = p;
child_pid_index++;
/** basically write this information on the disk **/
/** This is your lookup table **/
fwrite(file, sample....)
flush();
}
else
{
printf("I am child process..\r\n");
/** whenever you do fork ..do this routine **/
}
执行get()和set()以从文件中读取。您将能够检索它。从设计的角度来看,这是一个很好的问题,也许我会为fork做一个包装器。而不是调用fork,调用我的函数。