I am calling a command via 开发者_如何学JAVAsystem(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.
The system(3)
function causes your process to wait for the completion of the child.
Edit 0:
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)
.
Edit 1:
Look into waitpid(2)
to keep the parent around.
You have to fork(2) to continue executing code.
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();
}
精彩评论