Delphi - CreateProcess - Execute multiple commands

后端 未结 1 554
忘掉有多难
忘掉有多难 2021-01-01 05:53

I want to achieve the following with a CreateProcess() - call:

  1. Change to an svn working-copy
  2. Execute svn commands
  3. Pipe the output to a file
1条回答
  •  礼貌的吻别
    2021-01-01 06:29

    You need to supply an executable file when you call CreateProcess. I guess you are used to calling ShellExecute which is more lax.

    You are clearly looking to call cmd.exe so you should add that to the command line. Rather than changing the working directory after cmd.exe has started, use the lpCurrentDirectory parameter of CreateProcess to do that. You will also need to pass the /C option to cmd.exe to make it close once the command has completed.

    So you need to change input to be this:

    input := GetEnvironmentVariable('COMSPEC') + ' /C ' + SVN_PATH + 
      ' log > C:\users\PhilippKober\UNIQUE_NAME_BLUB.txt';
    

    I use GetEnvironmentVariable('COMSPEC') as a means to obtain the path to the command interpretor.

    And then call CreateProcess like this:

    CreateProcess(
      nil, 
      PChar(input), 
      nil, 
      nil, 
      False, 
      CREATE_NEW_PROCESS_GROUP or NORMAL_PRIORITY_CLASS, 
      nil,
      'D:\Qport\trunk\Qport', 
      StartInfo, 
      ProcInfo
    );
    

    It is semantically cleaner to use or to combine flags than +, although it has the same effect for these flags.

    One thing to watch out for is that the second parameter must point to writeable memory. That's because CreateProcess may modify that parameter. As it happens, your setting of input will meet that requirement. In any case, a call to UniqueString would be recommended in my view to make it explicit that you are meeting that requirement.

    The other thing I see that is missing is code to close the handles that are returned by CreateProcess. Close those handles by doing this in the end:

    //WaitForSingleObject(ProcInfo.hProcess, INFINITE); //in case you want to wait for Process to terminate
    CloseHandle(ProcInfo.hProcess);
    CloseHandle(ProcInfo.hThread);
    

    0 讨论(0)
提交回复
热议问题