Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 SetEvent call fails. What is the reason and solution of this problem?

like image 786
summerlight Avatar asked Feb 22 '26 01:02

summerlight


2 Answers

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.

like image 143
Steve Townsend Avatar answered Feb 24 '26 13:02

Steve Townsend


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.

like image 45
Mark Tolonen Avatar answered Feb 24 '26 13:02

Mark Tolonen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!