Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

windows - system() and CreateProcess() / CreateProcessW()

I want to execute a TEST.exe in a C program. While I use

system( "TEST.exe <input-file> output-file" );

I can get what I expected.

But CreateProcessW() didn't work properly when I use the following code (see How do I run an external program?):

if (CreateProcessW(const_cast<LPCWSTR>(FullPathToExe.c_str()), 
    pwszParam, 0, 0, false, 
    CREATE_DEFAULT_ERROR_MODE, 0, 0, 
    &siStartupInfo, &piProcessInfo) != false) 
{ 
    /* Watch the process. */ 
    dwExitCode = WaitForSingleObject(piProcessInfo.hProcess,  (SecondsToWait * 1000)); 
    iReturnVal = GetLastError(); 
} 
else 
{ 
    /* CreateProcess failed */ 
    iReturnVal = GetLastError(); 
} 

where

FullPathToExe="TEST.exe", pwszParam="TEST.exe <input-file> output-file".

And WaitForSingleObject() returns 258, GetLastError() returns 1813 ("The specified resource type cannot be found in the image file.").

Also, The above CreateProcessW() code works fine when I run my own HelloProcess.exe (print hello, and sleep some seconds determined by the following number, then exit.) with

FullPathToExe="HelloProcess.exe", pwszParam="HelloProcess.exe 10".

Any ideas? Thanks for any hints!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

system actually spawns a cmd instance in which your command is run:

The system function passes command to the command interpreter, which executes the string as an operating-system command. system refers to the COMSPEC and PATH environment variables that locate the command-interpreter file (the file named CMD.EXE in Windows NT). If command is NULL, the function simply checks to see whether the command interpreter exists.
Documentation of system

This is why redirection operators such as < and > work. This is not the case for CreateProcess which really just spawns a process instead of a shell that executes another process. Since the redirection operators are a feature of the shell and not the OS you'd have to do input and output to the process manually.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...