开发者

Using event object in inter-process

I'm trying to use event object in win32 environment to synchronize two processes. Below are the simplified code of two programs.

// process1
int main()
{
    HANDLE h = CreateEvent(NULL, FALSE, FALSE, TEXT("Hello"));
    WaitForSingleObject(h, INFINITE);
//  RunProcess(L"process2.exe", L"");
}

// process2
int main()
{
    HANDLE h = OpenEvent(EVENT_MODIFY_STATE, FALSE, TEXT("Hello"));
    SetEvent(h);    
}

It's quite simple, and works well when two processes are launched independently. However it does not work when the process 1 launches process 2 as a child process (which is commented in the above code) - the SetEve开发者_C百科nt call fails. What is the reason and solution of this problem?


Your code needs to check and handle errors. Both CreateEvent and OpenEvent will return NULL if they fail, in that case you need to check the error using GetLastError.

Your calls to WaitForSingleObject and SetEvent should be checked per the MSDN docs as well.

The order in which you need to do things in the parent process is:

  • CreateEvent
  • Start child process
  • WaitForSingleObject.

Otherwise you will hit the problem called out by @Mark Tolonen.

It would also be best to have a timeout on your wait, to handle the case where the child process fails to start, exits unexpectedly, or hangs.

An alternative approach if you intend to use this parent/child relationship would be to allow inheritance of the event handle. Then the event does not need to be named, and nobody else can 'squat' on it in a DoS attack on your apps. You can pass the handle value to the child as a command-line parameter. You do this using the bInheritHandle field on the eventAttributes parameter to CreateEvent.

A Boolean value that specifies whether the returned handle is inherited when a new process is created. If this member is TRUE, the new process inherits the handle.


Are you sure? As written, if process1 creates process2 in the current location, it will never create process2 because it will wait forever for the event to be fired. Create process2 first, then wait for the event to be set.


You have a NULL security descriptor, which the documentation says cannot allow the handle to be inherited by children processes, specifically:

If this parameter is NULL, the handle cannot be inherited by child processes

Maybe you need to create a proper security descriptor?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜