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?
So, it's considered to be thread-safe and can be safely called by multiple threads at the same time. All threads can safely call the factorial() method and will get the expected result without interfering with each other and without altering the output that the method generates for other threads.
Deadlocks, Starvation, Livelock and Race Conditions Deadlocks, starvation, and race conditions are the bane of multithreaded programming and they can bring down any system in which they occur.
write() is certainly thread-safe. The problem is that a partial write() could require multiple calls in order to completely write the data, and while that is "thread-safe" it could result in interleaved data.
Advantages of Multithreaded Processes All the threads of a process share its resources such as memory, data, files etc. A single application can have different threads within the same address space using resource sharing. It is more economical to use threads as they share the process resources.
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).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With