I don't need to wait for them, I just need a yes or no.
I'm executing a program that I know is going to fork (and the children are likely to fork too). If run correctly, it should take care of all the its children and exit them when it finishes. I need to write a test that checks if this is true. Orphaned processes get assigned to the init process, so I cannot see them in pstree anymore.
Bonus points if I can get a list of their PIDs so I can send SIGKILL to them. Ideally if it's something POSIX-y, so it would work on *BSD.
When a process terminates, the PPID of its children is set to 1 (adoption by init), but the PGID (process group identifier) and the SID (session identifier) don't change.
The process's children probably don't change their process group, unless they're intended to be daemons. Assuming they don't, start the process to be tested in its own process group. Call setpgid(getpid(), getpid())
from your test framework, after forking and before calling execve
to execute the program being tested. Call kill(-test_program_pid, 0)
(kill
with a negative pid
argument and the signal value 0) to test whether there is a running process with the PGID test_program_pid
. Pass SIGKILL
as the signal argument to kill them all.
test_program_pid = fork();
if (test_program_pid) {
waitpid(test_program_pid, &status, 0);
if (kill(-test_program_pid, 0)) {
record_failue("some child processes were not terminated properly");
}
kill(-test_program_pid, SIGKILL);
} else {
setpgid(getpid(), getpid());
execve("/program/to/test", …);
}
An alternative method would be to create a temporary file and open it in the program that you're testing and nowhere else. If the program calls execve
, make sure that the file descriptor is opened without the O_CLOEXEC
flag (or call fcntl(fd, FD_CLOEXEC, 0)
). This method assumes that the program doesn't go and close the file descriptors that it doesn't use explicitly. You can then run fuser /temp/file
to list the processes that have this file open, and fuser -k /temp/file
to kill them. A variant of this approach that works even with programs that close file descriptors they don't use, but assumes that the program doesn't change its current directory, is to create a temporary directory and change to that directory to run the program.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments