There are two points here that I think you've missed:
First, system
is a synchronous call. That means, your program (or, at least, the thread calling system
) waits for the child to complete. So, if your command
is long-running, both your main thread and your worker thread will be blocked until it completes.
Secondly, you are "joining" the worker thread at the end of main
. This is the right thing to do, because unless you join or detach the thread you have undefined behaviour. However, it's not what you really intended to do. The end result is not that the child process continues after your main process ends... your main process is still alive! It is blocked on the pthread_join
call, which is trying to wrap up the worker thread, which is still running command
.
In general, assuming you wish to spawn a new process entirely unrelated to your main process, threads are not the way to do it. Even if you were to detach your thread, it still belongs to your process, and you are still required to let it finish before your process terminates. You can't detach from the process using threads.
Instead, you'll need OS features such as fork
and exec
(or a friendly C++ wrapper around this functionality, such as Boost.Subprocess). This is the only way to truly spawn a new process from within your program.
But, you can cheat! If command
is a shell command, and your shell supports background jobs, you could put &
at the end of the command (this is an example for Bash syntax) to make the system
call:
- Ask the shell to spin off a new process
- Wait for it to do that
- The new process will now continue to run in the background
For example:
const std::string command = "./myLongProgram &";
// ^
However, again, this is kind of a hack and proper fork mechanisms that reside within your program's logic should be preferred for maximum portability and predictability.