背景:cp.exe是我写的一个程序,可在命令行下运行,有两个参数,一个指定输入文件,后一个指定输出文件,以下试验是为了实现在vc中调用这个现成的程序,并在其运行完成后继续其它任务。
运行cp的命令为 cp inputfile outputfile
在cp的实现代码中,参数初始化如下
int Option::init (int na, char* arg[])
{
if (na < 3)
{
printf ("parser\n\n");
printf ("parse <input file> <output file>\n");
printf ("\n");
return 0;
}
return 1;
}
因此,用CreateProcess运行命令时,参数设置如下,szCommandLine内容里要将exe路径再写一遍
char *execmd="F:\\cp.exe";
char *szCommandLine="F:\\cp.exe F:\\comp.txt F:\\out.txt";
USES_CONVERSION;
BOOL bStat = CreateProcess( A2T(execmd), A2T(szCommandLine) , NULL, NULL,
FALSE,NULL,NULL,NULL,&si,&pi );
调用cp的全部代码如下:
#include <stdio.h>
#include <afxwin.h>
#include <shellapi.h>
#include <conio.h>
void main(){
STARTUPINFO si; //This is an [in] parameter
ZeroMemory(&si, sizeof(si));
si.cb = sizeof si ; //Only compulsory field
PROCESS_INFORMATION pi;
//char *execmd="C:\\Windows\\System32\\notepad.exe";
//char *szCommandLine="D:\\静态方法.txt";
char *execmd="F:\\cp.exe";
char *szCommandLine="F:\\cp.exe F:\\comp.txt F:\\out.txt";
USES_CONVERSION;
BOOL bStat = CreateProcess( A2T(execmd), A2T(szCommandLine) , NULL, NULL,
FALSE,NULL,NULL,NULL,&si,&pi );
/*BOOL bStat = CreateProcess( _T("C:\\Windows\\System32\\notepad.exe"), _T("D:\\静态方法.txt"), NULL, NULL,
FALSE,0,NULL,NULL,&si,&pi );*/
if(bStat){
WaitForSingleObject(pi.hProcess,INFINITE);
CloseHandle(pi.hThread);
CloseHandle(pi.hProcess);
}
else{
AfxMessageBox(_T("The process could not be started..."));
}
printf("hello\n");
printf("hello\n");
printf("hello\n");
printf("hello\n");
printf("hello\n");
while( !_kbhit() );
}