Maus
Maus

Reputation: 2776

Get the child PID after system()

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()?

Upvotes: 4

Views: 4402

Answers (4)

Leo103
Leo103

Reputation: 871

I had this problem. Solved it by:

int syspid,status;
pid_t ppid=getpid();
syspid=ppid+1

status=system(argv[1]); //here argv1 was another program;

This might not always work, but most of the time the system()'s PID is the parent's pid +1 (unless you have multiple forks).

Upvotes: 0

Alexey
Alexey

Reputation: 1

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.

Upvotes: -1

Michael F
Michael F

Reputation: 40869

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().

Upvotes: 4

unwind
unwind

Reputation: 400109

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.

Upvotes: 8

Related Questions