9

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?

SKi
  • 8,007
  • 2
  • 26
  • 57
  • 2
    Check this out, this may help http://www.linuxprogrammingblog.com/threads-and-fork-think-twice-before-using-them – Intrepidd Nov 20 '12 at 10:44

3 Answers3

8

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).

maxschlepzig
  • 35,645
  • 14
  • 145
  • 182
3

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.

Azeem
  • 11,148
  • 4
  • 27
  • 40
cdleonard
  • 6,570
  • 2
  • 20
  • 20
2

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.