CreateProcess()中lpCommandLine的问题

Trouble with lpCommandLine in CreateProcess()

本文关键字:问题 lpCommandLine CreateProcess      更新时间:2023-10-16

argI有一些代码:

CreateProcess(L"D:\prog\forLb1SPZ.exe",L"D:\prog\forLb1SPZ.exe D:\1.txt",NULL,NULL,FALSE,0,NULL,NULL,&si,&pi)

这段代码正在工作,但是…文件在程序(编写此代码的地方)附近创建,名称为"D"——argv[1]的第一个符号。怎么了?

forLb1SPZ.exe中的代码

#include "stdafx.h"
#include "iostream"
#include <stdio.h>
#include <math.h>
using namespace std;
int _tmain(int argc, char* argv[])
{
    int value;
  FILE *Ptr;
  Ptr=fopen("argv[1]","w");
  for(int i=0;i<20000;i++){
      value=rand();
    fprintf(Ptr,"%d i=%d n",value,i);
  }
  fclose(Ptr);
    return 0;
}

lab2SPZ.exe(主程序)中的代码

#include "stdafx.h"
#include "iostream"
#include <windows.h>
#include <stdio.h>
using namespace std;
int main()
{
STARTUPINFO si;
PROCESS_INFORMATION pi;
ZeroMemory(&si, sizeof(si));
si.cb = sizeof(si);
ZeroMemory(&pi, sizeof(pi));
if(!CreateProcess(L"D:\forLb1SPZ.exe","D:\forLb1SPZ.exe D:\1.txt",NULL,NULL,FALSE,0,NULL,NULL,&si,&pi))
{printf( "creating failn");system("pause");return 0;}


printf("handle: %Xn", pi.hProcess);
WaitForSingleObject( pi.hProcess, INFINITE );

system("pause");
return 0;
}

您确定是CreateProcess正在创建该文件,而不是lb1spz .exe吗?

注意:

  1. 你正在使用宽字符串。如果forLb1SPZ.exe使用ANSI字符串,它可能会在D之后看到一个。如果它应该,比如说,打开"D:1.txt",它可能会看到文件名为"D"(我对此并不肯定,但我想操作系统不会转换编码。我可能是错的,但确实是错的)。尝试使用CreateProcessA,看看是否有区别。
  2. 第二个参数必须是LPTSTR而不是LPCTSTR。你正在传递一个字符串字面量,根据文档,字符串可能会被CreateProcess改变。如果发生这种情况,你将有未定义的行为,并可能崩溃。
  3. 你在第一个和第二个参数中都传递了应用程序名称。这通常是多余的。这是故意的吗?