获取CreateProcess()启动的进程的PID

时间:2013-02-22 07:12:27

标签: c windows winapi pid createprocess

首先让我说明我不是来自C背景。我是一名PHP开发人员。所以我到目前为止所编写的所有内容都是通过从其他示例中获取一些零碎的东西并对其进行微调以满足我的要求。如果我提出过于基本或明显的问题,请耐心等待。

我正在使用FFmpeg通过

开始CreateProcess()
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;
}

我需要做的是获取该进程的PID,然后稍后检查一段时间后它是否仍在运行。这基本上就是我在寻找的东西:

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;   
}

我做了一些研究,发现在PID内返回PROCESS_INFORMATION,但我找不到显示如何获取它的示例。

一些元数据

操作系统: Windows 7
语言: C
IDE: Dev C ++

2 个答案:

答案 0 :(得分:12)

将您传递的PROCESS_INFORMATION结构作为最后一个参数拉到CreateProcess(),在您的情况下 pi.dwProcessId

但是,要检查它是否仍在运行,您可能只想等待进程句柄。

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;
}

在您发布main()时,您可以执行类似......

的操作
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;
}

答案 1 :(得分:4)

您可能希望使用win32 api函数GetProcessId()

#include <windows.h>

...

BOOL bSuccess = FALSE;
LPTSTR pszCmd = NULL;
PROCESS_INFORMATION pi = {0};
STARTUPINFO si = {0};
si.cb = sizeof(si);

pszCmd = ... /* assign something useful */

bSuccess = CreateProcess(NULL, pszCmd, NULL, NULL, TRUE, 0, NULL, NULL, &si, &pi);

if (bSuccess)
{
  DWORD dwPid = GetProcessId(pi.hProcess);
  ...
}
else
  ... /* erorr handling */

有关详情,请参阅此处:http://msdn.microsoft.com/en-us/library/windows/desktop/ms683215%28v=vs.85%29.aspx