boost::p rocess 如何知道进程何时退出"gracefully or not"?

boost::process how to know when a process exited "gracefully or not"?

本文关键字:gracefully or not 退出 进程 rocess 何知道 boost 何时      更新时间:2023-10-16

等待 boost::process::child时,你怎么知道它是否优雅地退出了?

假设我创建了一个流程:

boost::process::child child( "myprg.exe", "5000" );
child.wait();
int res = child.exit_code();

其中myprg.exe是:

int main( int argc, char* argv[] )
{
    if ( argc == 2 )
    {
        boost::this_thread::sleep( boost::posix_time::milliseconds( atoi( argv[1] ) ) );
        return 1;
    }
    return 0;
}

注意:这是没有意义的MCVE,我同意Main应该返回0,如果成功。

我看到,如果有人在等待时杀死该过程(例如使用child.terminate或Windows Process Manager),则child.exit_code()将返回1。

因此,最终,当child.exit_code()为1时,我怎么知道这是该过程的主要输入功能返回的值还是该过程是否被杀死?

保证1将意味着过程被杀死?然后,程序不应该返回1并保留此退出代码以确定其被杀死且未干净退出的具体情况?

如果不是,boost::process API是否提供了一些可以知道过程是否干净或被杀死的东西?

因此,最终,当child.exit_code()为1时,我怎么知道这是该过程的主要输入功能返回的值还是该过程是否被杀死?

你不能。

保证1将意味着过程被杀死?

这取决于。至于Windows,根据此答案,它将是1,但没有记录在任何地方。请注意,杀死过程的返回代码取决于终止该过程的实例。对于Boost的终止功能,可以在详细信息/Windows/terminate.hpp中找到:

inline void terminate(child_handle &p)
{
    if (!::boost::winapi::TerminateProcess(p.process_handle(), EXIT_FAILURE))
        boost::process::detail::throw_last_error("TerminateProcess() failed");
    ::boost::winapi::CloseHandle(p.proc_info.hProcess);
    p.proc_info.hProcess = ::boost::winapi::INVALID_HANDLE_VALUE_;
}

因此,它总是返回EXIT_FAILURE,可能是1。但是,可以使过程返回任何值。

要区分您的流程是否以完全万无一失的方式优雅终止,因此,除了评估返回代码外,您还必须实现自己的通信机制。

您可以在子进程中设置错误处理程序以返回其他出口代码。例如,从stl库中添加std :: set_terminate:

int main( int argc, char* argv[] )
{
    std::set_terminate([](){ exit(2); });
    if ( argc == 2 )
    {        
        boost::this_thread::sleep(boost::posix_time::milliseconds(atoi(argv[1])));
        return 1;
    }
    return 0;
}