Reputation: 572
I have a C++ program that, based on user input, needs to start and stop a given Linux program.
I've simplified the logic I'm currently using in the following code:
int pid = fork();
if (pid == -1)
{
//Handle error
}
else if (pid == 0)
{
execlp("my_program", nullptr);
exit(0);
}
else
{
//Main program stuff
if(/* user selects close "my_program"*/)
{
kill(pid, SIGTERM);
}
//Other main program stuff
}
Everything is working, but I was wondering if there were any other approaches, maybe more in the modern C++ style, that could be used in this situation.
Thanks in advance.
Upvotes: 2
Views: 286
Reputation: 586
The modern way would be to use a library like Boost.Process https://www.boost.org/doc/libs/1_78_0/doc/html/process.html or Qt https://doc.qt.io/qt-5/qprocess.html.
Upvotes: 2
Reputation: 897
Take a look at boost::process.
There are several ways a process can be spawned. For example, in your example, you fork the process, but you don't close the cloned file descriptors in the child process. That is an often forgotten practice by those that invoke fork and can lead to binding to port problems (port/address already in use) or other hard-to-debug issues.
Even boost didn't do that quite correctly for some time.
Upvotes: 3