C语言 getppid equivalent to get child pid



getppid()返回父进程的进程ID。

因为任何给定的进程在任何时候都只能有一个父进程。从getppid返回是有意义的。

是否存在对getChildPid的等效系统调用?

我知道一个过程可能会有很多孩子,但就我而言,我确信我的过程在任何时候都只有一个孩子。所以,在我的情况下,进行如上所述的系统调用是有意义的。

编辑:子级由外部库生成,该库不公开fork()返回的pid。

一个进程可以有很多子进程,而调用只返回其中一个子进程是没有意义的。最广泛使用的机制是保存fork返回的pid。

有些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;
}

您可以维护以下结构。现在,当您执行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 processrn");
     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..rn");
    /** whenever you do fork ..do this routine **/

}

执行get()和set()从文件中读取。你将能够检索到它。从设计的角度来看,这是一个很好的问题,也许我会为fork做一个包装器。与其调用fork,不如调用我的函数。

最新更新