你可以让父进程等待子进程退出,然后关闭父进程。像
ShellExecute
这样的 Win API 遗留函数不返回进程标识符,因此必须直接使用核心系统调用
CreateProcess
。然后,您可以使父进程等待子进程退出/终止。您可以使用
WaitForSingleObject
Win API 同步函数来实现此操作。以下示例演示了所述技术:
#include <cstdlib>
#include <cstdio>
#include <cstring>
#ifdef _WIN32
# define HAS_BSOD
# include <windows.h>
#endif
#if defined(unix) \
|| defined(__unix) \
|| defined(_XOPEN_SOURCE) \
|| defined(_POSIX_SOURCE)
# include <sys/types.h>
# include <sys/wait.h>
#endif
#if defined(__GNUC__) && !defined(_alloca)
# define _alloca(__s) __builtin_alloca( (__s) )
#endif
int execute_and_wait(const char* command, const char *args);
#ifdef HAS_BSOD
int execute_and_wait(const char* command, const char *args)
{
::STARTUPINFOW cif;
std::memset(&cif, 0, sizeof(cif));
cif.cb = sizeof(cif);
::PROCESS_INFORMATION pi;
std::memset( &pi, 0, sizeof(pi) );
const std::size_t len = std::strlen(command) + std::strlen(args) + 2;
char* cmdline = static_cast<char*>( _alloca( len ) );
std::memset(cmdline, 0, len);
std::strcat(cmdline, command);
std::strcat(cmdline, " ");
std::strcat(cmdline, args);
::UINT acp = ::GetACP();
const std::size_t wlen = ::MultiByteToWideChar(acp, 0, cmdline, len, nullptr, 0) + 1;
wchar_t* wcmdline = static_cast<wchar_t*>( _alloca(wlen) );
std::memset(wcmdline, 0, wlen );
::MultiByteToWideChar(acp, 0, cmdline, len, wcmdline , wlen );
if ( ::CreateProcessW(
NULL,
wcmdline,
NULL,
NULL,
FALSE,
NORMAL_PRIORITY_CLASS,
NULL,
NULL,
&cif,
&pi)
)
{
::WaitForSingleObject( pi.hProcess, INFINITE );
int ret = EXIT_FAILURE;
::GetExitCodeProcess(pi.hProcess,LPDWORD(&ret));
::CloseHandle( pi.hProcess );
::CloseHandle( pi.hThread );
return ret;
}
return EXIT_FAILURE;
}
#else
int execute_and_wait(const char* command, const char *args)
{
::pid_t child_pid = ::fork();
if(child_pid < 0)
return EXIT_FAILURE;
if(0 == child_pid) {
::execl(command, args);
::exit(EXIT_FAILURE);
}
int ret;
::waitpid(child_pid, &ret, 0);
return ret;
}
#endif
#ifdef HAS_BSOD
static const char *SYS_EDITOR = "notepad.exe";
#else
static const char *SYS_EDITOR = "less";
#endif
int main(int argc, const char** argv)
{
std::printf("About to fork with: %s \n", __FILE__ );
int exit_code = execute_and_wait(SYS_EDITOR, __FILE__);
std::printf("This is it, exit code :%d \n", exit_code);
return 0;
}
![waitpid result](https://istack.dev59.com/yrfje.webp)
如果您能使用Boost处理过程, 代码将如下所示:
#include <iostream>
#include <boost/process.hpp>
#ifdef _WIN32
static const char *SYS_EDITOR = "notepad.exe ";
#else
static const char *SYS_EDITOR = "vi ";
#endif
int main()
{
std::string path(SYS_EDITOR);
path.append( __FILE__ );
std::cout << "About to fork with command : " << path << std::endl;
std::error_code ec;
boost::process::child c(path);
c.wait(ec);
return c.exit_code();
}
我的建议是最好不要阅读这个MSDN页面