gpt4 book ai didi

c++ - boost::process 如何知道进程何时退出 "gracefully or not"?

转载 作者:搜寻专家 更新时间:2023-10-31 02:08:23 67 4
gpt4 key购买 nike

在等待 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时,如何知道这是进程主入口函数返回的值,还是进程被kill了呢?

是否保证 1 表示进程已被终止?那程序是不是应该返回1,保留这个退出码,来识别具体是什么情况被杀了,没有干净退出?

如果不是,boost::process API 是否提供一些信息来了解进程是干净地结束还是被杀死?

最佳答案

So, in the end, when child.exit_code() is 1, how can I know if this is the value returned by the process's main entry function or if the process was killed?

你不能。

Is it guaranteed that 1 will mean process was killed?

这取决于。至于 Windows,根据 this答案,它将是 1,但无处记录。请注意,终止进程的返回码由终止进程的实例决定。对于 Boost 的终止函数,可以在 detail/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。但是,可以让进程返回任何值。

为了区分您的进程是否以完全安全且可移植的方式正常终止,因此除了评估返回码之外,您还必须实现自己的通信机制。

关于c++ - boost::process 如何知道进程何时退出 "gracefully or not"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47629677/

67 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com