我需要在一个线程中启动一个 3rd 方程序,等待从 stdout/stderr 和 C++ 获得结果。
- 有哪些方法可用?
- 它们是跨平台的吗?我的意思是,我可以将它们都用于 cl/gcc 吗?
我需要在一个线程中启动一个 3rd 方程序,等待从 stdout/stderr 和 C++ 获得结果。
在 Unix 上:
http://linux.die.net/man/3/execl
#include <sys/types.h>
#include <unistd.h>
void run_process (const char* path){
pid_t child_pid;
/* Duplicate this process. */
child_pid = fork ();
if (child_pid != 0){
/* This is the parent process. */
int ret = waitpid(child_pid, NULL, 0);
if (ret == -1){
printf ("an error occurred in waitpid\n");
abort ();
}
}
else {
execl (path, path);
/* The execvp function returns only if an error occurs. */
printf ("an error occurred in execl\n");
abort ();
}
}
在 Windows 上:
http://msdn.microsoft.com/en-us/library/ms682425%28v=vs.85%29.aspx
# include <windows.h>
void run_process (const char* path){
STARTUPINFO si;
PROCESS_INFORMATION pi;
ZeroMemory( &si, sizeof(si) );
si.cb = sizeof(si);
ZeroMemory( &pi, sizeof(pi) );
bool ret = = CreateProcess(
NULL, // No module name (use command line)
path, // Command line
NULL, // Process handle not inheritable
NULL, // Thread handle not inheritable
false, // Set handle inheritance to FALSE
0, // No creation flags
NULL, // Use parent's environment block
NULL, // Use parent's starting directory
&si, // Pointer to STARTUPINFO structure
&pi // Pointer to PROCESS_INFORMATION structure
)
if (!ret){
printf("Error");
abort();
}
WaitForSingleObject(pi.hProcess, INFINITE);
CloseHandle(pi.hProcess);
CloseHandle(pi.hThread);
}
有一组 posix 函数来启动外部可执行文件 - 请参阅exec - 它们是跨平台的。要在 windows 上执行某些特定任务,您可能需要使用 windows 特定的createprocess。
这些通常会阻塞,因此您必须在新线程中启动它们。线程通常不是跨平台的,尽管您可以在 Windows 上使用 posix (pthreads)。
另一种方法是使用诸如Qt或 wxWidgets 跨平台库之类的东西。
系统应该独立于平台,但如果担心以相同的安全权限运行程序,您可能希望坚持使用 createprocess (win)/exec (others)。