Boost.进程检查进程是否终止

Boost.Process check if process terminated

本文关键字:进程 终止 是否 检查 Boost      更新时间:2023-10-16

是否可以检查进程是否终止?

我不想调用.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.process 0.6,如果您有 C++11 可用。