Reputation: 9733
I am calling a command via system(command) call. But no other code is executed after this system() call.
Why is so? I thought, system() would create a child process for "command" execution and my program (parent of "command"-child) will continue executing code after that.
Am I not understanding system() correctly?
code:
printf("before \n");
system("tail -f filename"); /* long lived - never returns */
printf("after \n");
Here, I do not see after getting printed ever.
Upvotes: 3
Views: 3971
Reputation: 7155
A bit late but here is a solution (tested and working on Linux):
#include <sstream>
#include <cstdlib> //for system()-calls
#include <thread>
//just a utility-function..
template<typename...P> std::string says(P...p)
{
std::string r{};
std::stringstream ss("");
(ss<<...<<p);
r=ss.str();
return r;
}
#if defined(YOUR_COMPILERS_LINUX_DETECTION_FLAG)
template<typename...T> void _S_R_A_(const std::string &sc)
{
std::string s{};
s=says("nohup ", sc, " 1&2>/dev/null &"); //like old Windows TSR-call
std::system(s.c_str());
}
#else // if defined(YOUR_COMPILERS_WINDOWS_DETECTION_FLAG)
template<typename...T> void _S_R_A_(const std::string &sc) //assuming windows - NOT TESTED!
{
std::string s{};
s=says("start ", sc);
std::system(s.c_str());
}
#endif
template<typename...T> void SysRunApp(const std::string &sApp, T...t)
{
std::string sa{};
sa=says(sa, sApp, " ", t...); //caller must ensure parameters are
//correctly spaced/escaped etc
std::thread(_S_R_A_, sa).detach();
}
Upvotes: 0
Reputation: 84169
The system(3)
function causes your process to wait for the completion of the child.
You have to use the classic pair of fork(2)
and execve(2)
for what you want to do. You might also check whether your C library provides POSIX spawn(3)
.
Look into waitpid(2)
to keep the parent around.
Upvotes: 8