最近需要用到,稍微研究了下。
1. 供CreateProcess启动的进程test.exe,只是打印出参数而已。

#include "stdafx.h"
#include <stdlib.h>
#include <iostream>
#include <string>
using namespace std;

int main(int argc, char* argv[])
{
cout<<"Args count:"<<argc<<endl;
for(int i=0;i<argc;i++){
cout<<"args"<<i<<"="<<argv[i] <<endl;
}

int arg1 = atoi(argv[1]);
string str = argv[2];
cout<<arg1<<"---"<<str<<endl;

getchar();
return 0;
}
  1. 程序
// CreateProcess.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"

#include <windows.h>
#include <stdio.h>

int main(int argc, char* argv[])
{
STARTUPINFO si = { sizeof(si) };
PROCESS_INFORMATION pi;

si.dwFlags = STARTF_USESHOWWINDOW;
si.wShowWindow = true; //TRUE表示显示创建的进程的窗口
TCHAR cmdName[] =TEXT("d://test.exe");
TCHAR cmdline2[] =TEXT("12 34 56 88");//参数
int p1 = 66;char p2[] = "53";int p3 = 99;
sprintf(cmdline2,"%d %s %d",p1,p2,p3);//格式化参数
BOOL bRet = ::CreateProcess (
cmdName,
cmdline2, //在Unicode版本中此参数不能为常量字符串,因为此参数会被修改
NULL,
NULL,
FALSE,
CREATE_NEW_CONSOLE,
NULL,
NULL,
&si,
&pi);

int error = GetLastError();
if(bRet)
{
printf("新进程的进程ID号:%d \n", pi.dwProcessId);
printf("新进程的主线程ID号:%d \n", pi.dwThreadId);
}
else
{
printf("error code:%d\n",error );
}
Sleep(2000);
TerminateProcess(pi.hProcess, 0);//终止进程
::CloseHandle (pi.hThread);
::CloseHandle (pi.hProcess);
return 0;
}

/*
1. 直接启动进程,不等待执行完成
BOOL ret = CreateProcess(NULL, cCommandLine, NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi);
if (ret) {
// 关闭子进程的主线程句柄
CloseHandle(pi.hThread);
// 关闭子进程句柄
CloseHandle(pi.hProcess);
}
2. 等待执行完成
BOOL ret = CreateProcess(NULL, cCommandLine, NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi);
if (ret) {
// 关闭子进程的主线程句柄
CloseHandle(pi.hThread);
// 等待子进程的退出
WaitForSingleObject(pi.hProcess, INFINITE);
// 获取子进程的退出码
GetExitCodeProcess(pi.hProcess, &dwExitCode);
// 关闭子进程句柄
CloseHandle(pi.hProcess);
}
//*/