Reputation: 1213
getppid() returns process ID of parent process.
Since any given process can have only one parent at any time. Return from getppid makes sense.
Is there any equivalent system call to getChildPid?
I am aware that a process can have many children but in my case, I am sure that my process will have only one child at any point of time. So, in my case it does make sense to have a system call like above.
Edit: the child is produced by an external library which does not expose the pid returned by fork()
.
Upvotes: 1
Views: 2306
Reputation: 9685
Some APIs are broken and don't expose the pid of the child - on MacOS, AuthorizationExecuteWithPrivileges
is an example. It's completely wrong of the API not to give you the child pid, because you have to be able to waitpid
on it to clean up the zombie!
For these broken APIs, here's a workaround (used for example by Chrome). In pseudocode:
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;
}
Upvotes: 1
Reputation: 6526
You could maintain the following structure. Now, when you do a fork(), check the return value(PID). If it is non-zero (more than zero),then it is the parent process. Now, copy that process id in the array.
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 **/
}
Do a get() and set() to read from the file. You will be able to retrieve it. It is a nice question in design point of view, perhaps I would have made a wrapper for fork. Instead of calling fork, call my function.
Upvotes: -1
Reputation: 43508
A process can have many children and it doesn't make sense to have a call that would only return one of them. The most widely used mechanism is to save the returned pid from fork
.
Upvotes: 3