node ninja
node ninja

Reputation: 32996

How to query child processes in C++

My c++ program will spawn several child processes using fork() and execv(). How can I query those processes? If I wanted to shut one down, how would I do that?

Upvotes: 0

Views: 1004

Answers (3)

Jason
Jason

Reputation: 32510

After a call to fork(), you can use either wait(&status_int) or waitpid(child_pid, &status_int, WNOHANG) to detect the return status of children, using the latter if you don't want to block waiting for a child. The passed argument &status_int would be a pointer to an int that will hold the return status of the child process after it has exited. If you want to wait for any forked process to complete, and don't care about the return value, you can simply make a call to wait(NULL), or for a non-blocking version, waitpid(-1, NULL, WNOHANG).

Upvotes: 0

riwalk
riwalk

Reputation: 14223

Probably the best way that I know of to communicate between processes after a fork() is through sockets (see socketpair()).

From there, you can probably make anything work by just defining a protocol for communication (including the request to terminate).

Upvotes: 1

C. K. Young
C. K. Young

Reputation: 223033

When you fork, the return value is 0 in the child process, and the child's process ID (pid) in the parent process.

You can then call kill with that pid to see if it's still running, or request a shutdown. To check if the process is running, use 0 as the signal, then check the return value (0 == running; -1 == not running). To request a shutdown, use SIGTERM as the signal.

Upvotes: 5

Related Questions