Is it safe to call system(3) from multi-threaded process?

你。 提交于 2020-08-04 05:14:31

问题


system() function is implemented by using fork(), execve() and wait() functions. I have heard that fork() function is dangerous in multi-threaded programs. So, is the system() function also dangerous in multi-threaded programs?

What problems it may cause?


回答1:


fork is dangerous in threaded programs unless followed by execve. Since only the current thread is forked there's very little you can do in a forked multi-threaded program other than execve. You should probably make sure you're not taking any locks after the fork.

Since system() does fork + exec, it should be safe.




回答2:


The system() function isn't necessarily thread-safe.

POSIX.1-2008 specifies (as well as POSIX.1-2001):

The system() function need not be thread-safe.

For example, Solaris 10 documents system() as thread-unsafe:

The system() function manipulates the signal handlers for SIGINT, SIGQUIT, and SIGCHLD. It is therefore not safe to call system() in a multithreaded process, since some other thread that manipulates these signal handlers and a thread that concurrently calls system() can interfere with each other in a destructive manner.

This man page also suggests popen() as thread-safe work-around. Note that popen() doesn't change any signal handlers.

On Linux, system() is thread-safe.

Note that system() doesn't necessarily calls fork(). A implementation could use vfork(), instead. Or, on Linux, it could directly call clone(). It could even use posix_spawn().

Although forking in a multi-threaded program can be challenging, a fork directly followed by an exec is safe, in general (modulo open file descriptors).




回答3:


Fork is dangerous in multithreaded programs because it does not copy all running threads. It should be ok with system, but if you have signal handlers and multiple threads wait()ing you could again have a mess.



来源:https://stackoverflow.com/questions/13471489/is-it-safe-to-call-system3-from-multi-threaded-process

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!