views:

197

answers:

3

CreateProcess() returns false when the commandline contains a path.I don't understand why.

Here I simplified the operation:

function ExecProcess(path:string):boolean;
var StartupInfo:TstartupInfo;
    ProcInfo:TProcessInformation;
begin
  FillChar( StartupInfo, SizeOf( TStartupInfo ), 0 );
  StartupInfo.cb := SizeOf( TStartupInfo );
  Result:= CreateProcess(nil, PChar(path), Nil, Nil, False, 0, Nil,     PChar(ExtractFilePath(path)),StartupInfo,ProcInfo);
end;

begin
  ExecProcess(ParamStr(0) + ExtractFilePath(ParamStr(0)));
end.

Result is false.

How do I include path in commandline?

+3  A: 

Whenever I have problems with paths, it is either

  1. The path has spaces in it and needs to be wrapped in quotes
  2. The backslashes in the path are being treated like escape characters and need to be doubled '\'
Geoff
+4  A: 

If you gave some debugging info such as the values of ParamStr(0) and Path, I think you'd find your own answer. I think the error is here: ParamStr(0) + ExtractFilePath(ParamStr(0))

So if your app is c:\apps\foo.exe then you're going to be effectively calling: ExecProcess('c:\apps\foo.exec:\apps\');

I don't think that's what you wanted. However, you don't say what you're doing, so it's hard to know for sure....

Chris Thornton
+2  A: 

As Chris mentioned, you're concatenating the two values (without a space between them) into one long string. Since `c:\apps\foo.exec:\apps\' probably isn't quite what you intended, you probably shouldn't be doing that.

In addition, if either of the paths contain spaces, you may need to add double-quotes. Delphi has a funtion in SysUtils just for that purpose:

var
  AppPath, ExePath: string
begin
  // Setup StartupInfo and ProcInfo as before. Omitted for brevity here.
  ExePath := AnsiQuotedStr(ParamStr(0), '"');
  AppPath := AnsiQuotedStr(ExtractFilePath(ExePath), '"');
  Result:= CreateProcess(nil, ExePath, Nil, Nil, False, 0,
                         Nil, Apppath, StartupInfo, ProcInfo);

end;

Note that by assigning the two values to string variables, the PChar cast isn't usually necessary, as the compiler will implicitly handle it for you.

Ken White