[clug-talk] Call a program in C and get the child PID?

Mark Carlson carlsonmark at gmail.com
Mon Sep 19 10:14:43 PDT 2005

On 9/19/05, Roy Souther <roy at silicontao.com> wrote:
> Does anyone know how to call a child program in C and get the PID?
> The system command only returns the exit code, fork copies the running
> program and the many version of exec terminate the original program.
> I want to spawn the called program, keep it running and get the PID
> back. I want my C program to start a shell in xterm and then be able to
> go and do other things and watch for the xterm shell to be closed by the
> user.
> go_do("xterm &");
> ChildPid = SomeHowGetTheChildPid();

I'm not sure exactly what you are trying to do here, but if you need
info on spawning processes, you can consult the Advanced Linux
Programming book (oh, how I love creative commons) Chapter 3, section
2 (pages 48-51.)

Full book:

Relevant chapter:

Their method (and the only one I've heard of so far) is to fork() and
use an exec() function (such as execvp or execlp) to replace the child
process with another program.  The fork() command returns two PIDs (if
you don't know the fork() command, it is explained in that section
IIRC) one of which is the PID of the child process.

There is a sample program on Page 51 that I think does part of what
you are asking.  I don't remember off the top of my head how to wait
until the child process is finished, but I should have some code at
home if you are still interested later today.

At any rate, anybody who is interested in Linux programming should
thumb through the book (if you can print it off it is much easier :-)
and if anyone knows of any other good books, please let me know.

-Mark Carlson

More information about the clug-talk mailing list