CreateProcess应用

本文介绍如何通过CreateProcess函数在VC环境中调用一个名为cp.exe的外部程序,并确保程序执行完毕后再继续执行后续任务。该程序用于复制文件,接受两个参数:输入文件和输出文件。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


背景: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() );

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值