tags:

views:

260

answers:

3

Hi,

As far as I understand, the system() call uses internally fork() and exec() but encapsulates them for a easier handling.

Is it possible to get the PID from the child process created with the system() call?

Aim: I want to be able to SIGINT any child process after a certain timeout. I could rebuild the system() function by using fork() and exec(). But all I need is the child's PID and perhaps there is shortcut by using system()?

+6  A: 

Typically, system() is a synchronous operation. This means it won't return until the child has exited, i.e. there is no valid PID for the child process when system() returns, since the child process no longer exists.

unwind
Yes - the process has gone when system() returns.
MarkR
+3  A: 

There's no way (that I know of) when using system(). Besides, with system() there's the additional step of launching a shell which will execute your command, making this a tad more difficult. You're probably better off replacing it with fork() and exec().

Michael Foukarakis
A: 

However, there is a way of doing what you want via the /proc file system. You can go through process directories (directory names are PIDs) and check the "status" files. There's a PPid entry in each of them specifying the parent pid.

This way, if you get a "status" file which specifies the PID of your process as PPID, then its folder name in /proc file system is the value you are looking for.

Alexey
unless another part of your program/library/etc has forked a program behind your back. Replacing system(command) by { pid = fork + execl("/bin/sh","sh","-c",command,(char *)NULL); pid } is really simple and much more reliable, not to mention porable.
vlabrecque