c++ - 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 中)所以你需要自己实现它。可以这样做:

#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。

关于c++ - Boost.Process 检查进程是否终止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35367735/

相关文章:

c++ - 对 'std::string Helper::ToString<int>(int const&)' 的 undefined reference

c++ - C++ 方法的 Visual Studio 2010 工具提示注释

c++ - 这个程序的名称是什么?

c++ - 查询从内存映射文件中检索到的 Rtree 时出现段错误

c++ - Visual Studio 2015 : Can't find `char * * __cdecl __p__environ(void)`

c++ - 由于 boost::throw_exception,boost::process 无法编译

c++ - 涉及函数的C++程序...请帮助我

c++ - 如何遍历包含 deque<MyData> 元素的斐波那契堆( boost )

c++ - 成员函数上的 boost::function

c++ - 将功能从控制台应用程序移动到共享库项目似乎会带来不相关的编译错误