正 文

利用API在Windows下创建进程和线程


www.7dspace.com  更新日期:2006-1-24 5:09:04  七度空间


/*测试程序1:

  示例如何使用进程的launch程序,通过在命令行中加载相应的命令文件,去按照命令文件中指定的程序路径打开相应的程序去执行*/

#include <windows.h>
#include <stdio.h>
#include <string.h>
#define MAX_LINE_LEN 80

int main(int argc,char* argv[])
{
//local variables
FILE* fid;
char cmdLine[MAX_LINE_LEN];
//CreateProcess parameters
LPSECURITY_ATTRIBUTES processA=NULL;//Default
LPSECURITY_ATTRIBUTES threadA=NULL;//Default
BOOL shareRights=TRUE;//Default
DWORD creationMask=CREATE_NEW_CONSOLE;//Window per process.
LPVOID enviroment=NULL;//Default
LPSTR curDir=NULL;//Default
STARTUPINFO startInfo;//Result
PROCESS_INFORMATION procInfo;//Result

//1.Read the command line parameters

if(argc!=2)
{
fprintf(stderr,"Usage:lanch<launch_set_filename>\n");
exit(0);
}

//2.Open a file that coutain a set of commands

fid=fopen(argv[1],"r");

//3.For every command in the launch file

while(fgets(cmdLine,MAX_LINE_LEN,fid)!=NULL)
{
 //Read a command from the file
 if(cmdLine[strlen(cmdLine)-1]=='\n')
  cmdLine[strlen(cmdLine)-1]='\0';//Remove NEWLINE
 //Create a new process to execute the command
 ZeroMemory(&startInfo,sizeof(startInfo));
 startInfo.cb=sizeof(startInfo);
 if(!CreateProcess(
   NULL,//File name of executable
   cmdLine,//command line
   processA,//Process inherited security
   threadA, //Thread inherited security
   shareRights,//Rights propagation
   creationMask,//various creation flags
   enviroment,//Enviroment variable
   curDir, //Child's current directory
   &startInfo,
   &procInfo
  )
 )
{
 fprintf(stderr,"CreatProcess failed on error %d\n",GetLastError());
 ExitProcess(0);
}
}
//Terminate after all commands have finished.
return 0;
}

  通过上面这段极其简洁的代码,完成了看似有些难度的任务,让我们充分感受到采用一些高级的编程手段所带来的便捷与高效.

6页,页码:[1] [2] [3] [4] [5] [6] 

上一篇:Excel中录入固定格式数据的技巧
下一篇:Windows 2000缓冲区溢出技术原理
标题:利用API在Windows下创建进程和线程 作者:EmilMatthew 来源:blog
收藏此页】【打印】【关闭
站 内 搜 索
 

热 点 导 读
特 别 推 荐