Click here to Skip to main content
15,885,546 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,

when i using boost child to create a Spawn Child.parent and child process are created.If terminate a parent process(Ctrl + c ) it terminated, but child process is not Killed. child is alive only.how to kill child process if parent terminated?

What I have tried:

#include <stdio.h>
#include <unistd.h>
#include <iostream>
#include <boost/process.hpp>

namespace bp = boost::process;
int main(int argc, char* argv[]) 
{
	std::vector<std::string> StringVector;

	StringVector = { "/home/Test/child_process/sample_exe" };
	bp::child *child;
	child = new bp::child(StringVector);
	if (child->running())
		std::cout<<"Child process created "<<std::endl;

	return 0;
}
Posted
Updated 18-Jan-21 18:34pm
v2
Comments
Richard MacCutchan 18-Jan-21 4:18am    
You need to trap the Ctrl-C interrupt and kill the child then. If the main process does not terminate gracefully then boost has no way of closing the child.
Stefan_Lang 18-Jan-21 6:36am    
What is your point in having a child process if it can't lead a separate life? Or to put it the other way round: if you want your child to die with the parent, why not create a thread instead? Threads are automatically killed with the master thread.

This is just a guess, but I like to think that the terms child and parent were chosen deliberately because children are normally allowed to outlive their parents. Whereas slaves depend on their master - and in some cases even in death. Therefore the use of 'master' and 'slave' for threads.

1 solution

As Richard pointed out, you can trap Ctrl-C and then pass a signal to the child to exit gracefully.

If you are on linux, and you have the source code to the child process, you can set the Parent Death Signal using prctl(PR_SET_PDEATH_SIG, <signum>). This tells the kernel to deliver signal <signum> to the process when the parent dies. You will then have to install a signal handler to catch the signal and do appropriate processing. Alternatively, you could pass the child process the PID of the parent when you spawn it, and have the child periodically check for the existence of the parent, and do the right thing when the parent exits.

If you don't have the source to the parent, or you do not wish, or are unable to modify it, then maybe a "shim" process could be written to spawn the child process, and use either or both of the above techniques to signal the child when the parent dies. But, of course, you then have the problem of what to do if the shim dies unexpectedly.
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900