yuz
yuz

Reputation: 21

Whether the function system() can be invoked in a thread or not?

I want to use system() to execute a cmd. If the cmd takes a long time like ping, it will block main thread.

So I want to create a child thread to handle it. In this child thread the system() will be invoked.

As we all know, the system() will fork a child process. I'm NOT sure whether any problem or side effect when the system() is invoked in a child thread.

Upvotes: 1

Views: 64

Answers (1)

P.P
P.P

Reputation: 121427

system() is marked as thread-safe by Linux/glibc documentation. See the man page. But with a caveat:

According to POSIX.1, it is unspecified whether handlers registered using pthread_atfork(3) are called during the execution of system(). In the glibc implementation, such handlers are not called.

From what you described, you probably don't have atfork handlers, so it's fine.

I want to use system() to execute a cmd. If the cmd takes a long time like ping, it will block main thread.

However, if the sole purpose of using a separate thread is to run a command, why not fork(2) directly and let it child process exec command? The main process can still carry on and can check whether the child process completed (e.g., using waitpid with WNOHANG). This would be cleaner in my opinion and avoids the fork+threads complexity.

Upvotes: 2

Related Questions