C++ 进程检查进程是否终止
是否可以检查进程是否已终止 我不想调用C++ 进程检查进程是否终止,c++,boost,boost-process,C++,Boost,Boost Process,是否可以检查进程是否已终止 我不想调用.wait(),因为它正在阻塞,我想管理一个超时,然后我将终止进程 现在我有以下代码: child c = launch(exec, args, ctx); auto timeout = boost::posix_time::seconds(3); boost::this_thread::sleep(timeout); c.terminate(); 但它不会等待终止,也不会检查进程是否优雅地终止。这不在boost.process 0.5中(在0.6中是),
.wait()
,因为它正在阻塞,我想管理一个超时,然后我将终止进程
现在我有以下代码:
child c = launch(exec, args, ctx);
auto timeout = boost::posix_time::seconds(3);
boost::this_thread::sleep(timeout);
c.terminate();
但它不会等待终止,也不会检查进程是否优雅地终止。这不在boost.process 0.5中(在0.6中是),所以您需要自己实现它。可以这样做:
#if defined (BOOST_WINDOWS_API)
template<typename Child>
inline bool is_running(const Child &p, int & exit_code)
{
DWORD code;
//single value, not needed in the winapi.
if (!GetExitCodeProcess(p.proc_info.hProcess, &code))
throw runtime_error("GetExitCodeProcess() failed");
if (code == 259) //arbitrary windows constant
return true;
else
{
exit_code = code;
return false;
}
}
#elif defined(BOOST_POSIX_API)
tempalte<typename Child>
inline bool is_running(const Child&p, int & exit_code)
{
int status;
auto ret = ::waitpid(p.pid, &status, WNOHANG|WUNTRACED);
if (ret == -1)
{
if (errno != ECHILD) //because it no child is running, than this one isn't either, obviously.
throw std::runtime_error("is_running error");
return false;
}
else if (ret == 0)
return true;
else //exited
{
if (WIFEXITED(status))
exit_code = status;
return false;
}
}
#endif
#如果已定义(BOOST_WINDOWS_API)
模板
内联bool正在运行(const Child&p、int&exit代码)
{
德沃德码;
//单值,winapi中不需要。
if(!GetExitCodeProcess(p.proc\u info.hProcess,&code))
抛出运行时_错误(“GetExitCodeProcess()失败”);
if(code==259)//任意windows常量
返回true;
其他的
{
退出代码=代码;
返回false;
}
}
#定义的elif(BOOST_POSIX_API)
坦帕尔特
内联bool正在运行(const Child&p、int&exit代码)
{
智力状态;
auto-ret=::waitpid(p.pid,&status,WNOHANG | WUNTRACED);
如果(ret==-1)
{
if(errno!=ECHILD)//因为它没有子对象在运行,所以这个子对象显然也没有。
throw std::runtime_error(“is_running error”);
返回false;
}
else if(ret==0)
返回true;
否则退出
{
如果(妻子退出(状态))
退出代码=状态;
返回false;
}
}
#恩迪夫
或者只要使用boost.process 0.6,如果您有C++11可用。使用via boost::asio怎么样?