Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the PID of the process started by CreateProcess()

Let me start off by stating that I'm not from C background. I'm a PHP developer. So everything that I've coded so far is by taking bits and pieces from other examples and fine tuning them to meet my requirements. So please bear with me if I ask way too basic or obvious questions.

I'm starting FFmpeg using CreateProcess() through

int startFFmpeg()
{
    snprintf(cmd, sizeof(cmd), "D:\\ffpmeg\bin\ffmpeg.exe -i D:\\video.mpg -r 10 D:\\frames");

    PROCESS_INFORMATION pi;
    STARTUPINFO si={sizeof(si)};
    si.cb = sizeof(STARTUPINFO);
    int ff = CreateProcess(NULL, cmd, NULL, NULL, TRUE, 0, NULL, NULL, &si, &pi);
    return ff;
}

What I need to do is get the PID of that process and then check later to see if it still running after some time. This is basically what I'm looking for:

int main()
{
    int ff = startFFmpeg();
    if(ff)
    {
       // great! FFmpeg is generating frames
       // then some time later
       if(<check if ffmpeg is still running, probably by checking the PID in task manager>) // <-- Need this condition
       {
            // if running, continue
       }
       else
       {
           startFFmpeg();
       }
    } 
  return 0;   
}

I did some research and found out that PID is returned within the PROCESS_INFORMATION, but I couldn't find an example showing how to fetch it.

Some metadata

OS : Windows 7
Language : C
IDE : Dev C++

like image 362
asprin Avatar asked Feb 22 '13 07:02

asprin


1 Answers

Pull it from the PROCESS_INFORMATION structure you pass as the last parameter to CreateProcess(), in your case pi.dwProcessId

However, to check if it is still running, you may want to just wait on the process handle.

static HANDLE startFFmpeg()
{
    snprintf(cmd, sizeof(cmd), "D:\\ffpmeg\bin\ffmpeg.exe -i D:\\video.mpg -r 10 D:\\frames");

    PROCESS_INFORMATION pi = {0};
    STARTUPINFO si = {0};
    si.cb = sizeof(STARTUPINFO);
    if (CreateProcess(NULL, cmd, NULL, NULL, TRUE, 0, NULL, NULL, &si, &pi))
    {
        CloseHandle(pi.hThread);
        return pi.hProcess;
    }
    return NULL;
}

In your launching main() you can then do something like...

int main()
{
    HANDLE ff = startFFmpeg();
    if(ff != NULL)
    {
        // wait with periodic checks. this is setup for
        //  half-second checks. configure as you need
        while (WAIT_TIMEOUT == WaitForSingleObject(ff, 500))
        {
            // your wait code goes here.
        }

        // close the handle no matter what else.
        CloseHandle(ff);
    }
    return 0;
}
like image 130
WhozCraig Avatar answered Sep 25 '22 19:09

WhozCraig