C/C++执行外部程序(调用外部exe程序)

本文只做简单介绍,具体用法请参照MSDN。
  • C中的函数:
1.exec() 函数家族:
exec() 家族的函数将会创建一个新的进程来执行程序。
_execl, _wexecl
_execv, _wexecv
_execle, _wexecle
_execve, _wexecve
_execlp, _wexeclp
_execvp, _wexecvp
_execlpe, _wexeclpe
_execvpe, _wexecvpe
函数格式:
intptr_t _?exec*(
   const char *cmdname,
   const char *arg0,
   ... const char *argn,
   NULL
);
intptr_t _?execv*(
   const char *cmdname,
   const char *const *argv
);

2.spawn()函数家族:
spawn() 家族的函数将会创建一个新的进程来执行程序。
_spawnl, _wspawnl
_spawnv, _wspawnv
_spawnle, _wspawnle
_spawnve, _wspawnve
_spawnlp, _wspawnlp
_spawnvp, _wspawnvp
_spawnlpe, _wspawnlpe
_spawnvpe, _wspawnvpe
函数格式:
intptr_t _?pawn*(
   int mode,
   const char *cmdname,
   const char *arg0,
   const char *arg1,
   ... const char *argn,
   NULL,
   const char *const *envp
);
intptr_t _?pawnv*(
   int mode,
   const char *cmdname,
   const char *const *argv
);

3.system()函数
可用于执行控制台命令。
函数格式:
int system(
   const char *command
);
示例:
system( "type crt_system.txt" );

  • WIN32 API
1.WinExec()函数
只提供16位windows程序使用。
函数格式:
UINT WINAPI WinExec(
  __in  LPCSTR lpCmdLine,
  __in  UINT uCmdShow
);
示例:
WinExec("\"C:\\Program Files\\MyApp.exe\" -L -S", ...);

2.ShellExecute()函数
可以显示ui,基于com组件,使用前需要初始化com环境。
函数格式:
HINSTANCE ShellExecute(
  __in_opt  HWND hwnd,
  __in_opt  LPCTSTR lpOperation,
  __in      LPCTSTR lpFile,
  __in_opt  LPCTSTR lpParameters,
  __in_opt  LPCTSTR lpDirectory,
  __in      INT nShowCmd
);
示例:
CoInitializeEx(NULL, COINIT_APARTMENTTHREADED | COINIT_DISABLE_OLE1DDE);
ShellExecute(handle, NULL, <fully_qualified_path_to_folder>, NULL, NULL, SW_SHOWNORMAL);


3.CreateProcess()函数
函数格式:
BOOL WINAPI CreateProcess(
  __in_opt     LPCTSTR lpApplicationName,
  __inout_opt  LPTSTR lpCommandLine,
  __in_opt     LPSECURITY_ATTRIBUTES lpProcessAttributes,
  __in_opt     LPSECURITY_ATTRIBUTES lpThreadAttributes,
  __in         BOOL bInheritHandles,
  __in         DWORD dwCreationFlags,
  __in_opt     LPVOID lpEnvironment,
  __in_opt     LPCTSTR lpCurrentDirectory,
  __in         LPSTARTUPINFO lpStartupInfo,
  __out        LPPROCESS_INFORMATION lpProcessInformation
);
示例:
LPTSTR szCmdline = _tcsdup(TEXT("C:\\Program Files\\MyApp -L -S"));
CreateProcess(NULL, szCmdline, /* ... */);

 
 

 


posted @ 2010-10-09 19:16  LayzerAr  阅读(3932)  评论(0编辑  收藏  举报