开发者

How to query child processes in C++

开发者 https://www.devze.com 2023-03-01 04:16 出处:网络
My c++ program will spawn several child processes using fork() and execv(). How can I query th开发者_StackOverflow社区ose processes? If I wanted to shut one down, how would I do that?When you fork, th

My c++ program will spawn several child processes using fork() and execv(). How can I query th开发者_StackOverflow社区ose processes? If I wanted to shut one down, how would I do that?


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.


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


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

0

精彩评论

暂无评论...
验证码 换一张
取 消