Start program in new process and output its process id

Share your advanced PureBasic knowledge/code with the community.
Mistrel
Addict
Addict
Posts: 3415
Joined: Sat Jun 30, 2007 8:04 pm

Start program in new process and output its process id

Post by Mistrel »

This is a little program I wrote which mimics the most basic behavior of the "start" command from the Windows command line. It runs a program in a separate process and outputs its process id to the command line where it can be captured and killed at some later time.

I'm currently using it in conjunction with the Python fakemail.py script and a PHP unit test. The fake mail server is started before the tests are run and killed at the end in a very automated fashion. :)

Code: Select all

OpenConsole()

#kExit_Code_Error=1
#kExit_Code_Success=0

Procedure GetProcessId_(hProcess)
  Static *pGetProcessId
  
  If Not *pGetProcessId
    *pGetProcessId=GetProcAddress_(GetModuleHandle_("kernel32.dll"),"GetProcessId")
  EndIf
  
  If Not *pGetProcessId
    ProcedureReturn 0
  EndIf
  
  ProcedureReturn CallFunctionFast(*pGetProcessId,hProcess)
EndProcedure

Procedure RunProgram_(ProgramName.s, Parameter.s="", WorkingDirectory.s="", Visible=#SW_SHOW)
  Protected ShellExInfo.SHELLEXECUTEINFO
  
  ShellExInfo\cbSize=SizeOf(ShellExInfo)
  ShellExInfo\fMask=#SEE_MASK_NOCLOSEPROCESS
  ShellExInfo\lpVerb=@"Open"
  ShellExInfo\lpFile=@ProgramName.s
  ShellExInfo\lpParameters=@Parameter.s
  ShellExInfo\lpDirectory=@WorkingDirectory.s
  ShellExInfo\nShow=Visible
  
  ShellExecuteEx_(@ShellExInfo)
  
  ProcedureReturn GetProcessId_(ShellExInfo\hProcess)
EndProcedure

If Not CountProgramParameters()
  End #kExit_Code_Success
EndIf

Path.s=ProgramParameter(0)

If CountProgramParameters()>1
  For i=2 To CountProgramParameters()
    If Params.s
      Params.s+" "
    EndIf
    
    Params.s+ProgramParameter(i-1)
  Next i
EndIf

ProgramId=RunProgram_(Path.s,Params.s,GetCurrentDirectory())

If ProgramId
  PrintN(Str(ProgramId))
Else
  End #kExit_Code_Error
EndIf

End #kExit_Code_Success
peterb
User
User
Posts: 60
Joined: Sun Oct 02, 2005 8:55 am
Location: Czech Republic
Contact:

Re: Start program in new process and output its process id

Post by peterb »

a small improvement for regular handling with parameters containing spaces (like path "\Documents and Settings\", etc. )

Code: Select all

; .....
Path.s = ProgramParameter ( 0 )

If CountProgramParameters() > 1
  For i = 1 To CountProgramParameters() - 1
    
    ParamsPart.s = ProgramParameter ( i )
    
    If Params.s
      Params.s+" "
      
    EndIf
    
    If FindString ( ParamsPart, " " )
      ParamsPart = #DQUOTE$ + ParamsPart + #DQUOTE$
      
    EndIf
    
    Params.s + ParamsPart
  Next i
EndIf
; .....
peterb
Post Reply