Window c++ 创建子进程
在window系统中,创建一个子进程可以使用CreateProcessA方法实现,其函数API如下:
BOOL CreateProcessA(
LPCSTR lpApplicationName,
LPSTR lpCommandLine,
LPSECURITY_ATTRIBUTES lpProcessAttributes,
LPSECURITY_ATTRIBUTES lpThreadAttributes,
BOOL bInheritHandles,
DWORD dwCreationFlags,
LPVOID lpEnvironment,
LPCSTR lpCurrentDirectory,
LPSTARTUPINFOA lpStartupInfo,
LPPROCESS_INFORMATION lpProcessInformation
);
主要参数如下:
-
lpApplicationName
是可执行文件的名称,该名称可以是带完整路径;也可以是只有名称,这种情况下只能在当前路径下查找。需要注意的是,文件名一定要有后缀.exe。例如:
E:\code\c++\myproject\vs2008\bin\test.exe或者是test.exe当然该参数我们也可以设置为NULL,可以执行程序由lpCommandLine参数决定。
-
lpCommandLine
当lpApplicationName 设置为NULL时,可执行程序文件名由lpCommandLine中的第一空格作为界定符。空格后面才是执行参数。在lpCommandLine中设置可执行程序,有以下几个好处:
- 对于系统命令,可以不写命令路径和后缀.exe,此时系统默认是exe后缀。
- 不写路径的情况,它可以去指定路径下搜索,包括path路径,windows目录等。
-
bInheritHandles
指定子进程是否能继承父进程的对象句柄 -
lpStartupInfo
设置子进程启动信息,一般用设置子进程窗口如何显示。 -
lpProcessInformation
返回子进程的进程句柄和子进程对应的主线程句柄
总结:
为了方便,我们一般设置lpApplicationName为NULL,可执行文件名由lpCommandLine决定;使用默认属性我们可以设置参数为NULL.
-
lpCommandLine参数格式:
exe + 空格 + 参数 -
对于非系统命令,exe要是完整路径,如果是系统命令可直接是命令名称
-
对于无输入参数,则lpCommandLine是命令名称或者带路径的exe即可。
该函数的简单使用如下:
#include <windows.h>
#include <stdio.h>
#include <tchar.h>
void _tmain( int argc, TCHAR *argv[] )
{
STARTUPINFO si;
PROCESS_INFORMATION pi;
ZeroMemory( &si, sizeof(si) );
si.cb = sizeof(si);
ZeroMemory( &pi, sizeof(pi) );
if( argc != 2 )
{
printf("Usage: %s [cmdline]\n", argv[0]);
return;
}
// Start the child process.
if( !CreateProcess( NULL, // No module name (use command line)
argv[1], // 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
)
{
printf( "CreateProcess failed (%d).\n", GetLastError() );
return;
}
// Wait until child process exits.
WaitForSingleObject( pi.hProcess, INFINITE );
// Close process and thread handles.
CloseHandle( pi.hProcess );
CloseHandle( pi.hThread );
}
为了方便使用和代码复用,我实现了一个CWorkProcess进程管理类,类设计如下:
class CWorkProcess
{
public:
//CWorkProcess subProcess("ping","192.168.0.1");
//CWorkProcess subProcess("ping",NULL);
//CWorkProcess subProcess("E:\\code\\c++\\project\\sleep_timer.exe,NULL", "10");
CWorkProcess(char* szApp, char* arg);
~CWorkProcess();
//启动进程
bool LaunchProcess();
//进程检查
bool CheckIfProcessIsActive();
//结束进程
bool StopProcess();
//进程等待
bool Wait(int nTimeout);
private:
PROCESS_INFORMATION m_pi;
char* m_pszCmd;
};
这个类具体实现参考github:
https://github.com/jinxiang1224/cpp/blob/master/proces/WorkProcess.cpp
作者:Jimmy1224
来源:CSDN
原文:https://blog.csdn.net/c_base_jin/article/details/88373366
版权声明:本文为博主原创文章,转载请附上博文链接!
更多推荐
所有评论(0)