Execute shell command using threads c++

2020-04-15 11:45发布

问题:

Is it possible to execute a shell command by creating a thread i.e. without using popen/system or any of the fork-exec variants? Why or why not?

To provide more context, I am running a multi-threaded program, where one of the threads needs to execute a shell script. It currently does it using popen(). However, since forking in a multi-threaded program is considered bad practice, is it possible to achieve the same by spawning a thread?

回答1:

Here's an useful summary on the multi-threading & fork+exec potential problems: http://www.linuxprogrammingblog.com/threads-and-fork-think-twice-before-using-them

It seems that if you want to execute other programs and even shell scripts, you have to use fork+exec, it's unavoidable. Just be careful and prepare your threads for such a "bad" event like fork. Also you could close all unnecessary file descriptors in a special single threaded trusted execute helper being run from the main application, if that's the problem.