只需要记住使用OpenEvent来同步Event对象。
Project A:
#define _CRT_SECURE_NO_WARNINGS #include <Windows.h> #include <stdio.h> #include <time.h> HANDLE hEvent; int main() { hEvent = CreateEvent(NULL, TRUE, FALSE, L"Ev"); if (hEvent == NULL) { printf("Error event"); return -1; } PROCESS_INFORMATION pi; STARTUPINFO si; memset(&si, 0, sizeof(si)); si.cb = sizeof(si); if (!SetEvent(hEvent)) { printf("Setevent error "); return -1; } if (!CreateProcess(L"Project B.exe", NULL, NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi)) { printf("Cannot create process. "); return -1; } Sleep(3000); //这边需要延时关闭该进程,以便Project B有足够的时间获取hEvent对象 CloseHandle(hEvent); }
Project B:
#define _CRT_SECURE_NO_WARNINGS #include <Windows.h> #include <stdio.h> #include <time.h> HANDLE hEvent; int main() { hEvent = OpenEvent(EVENT_MODIFY_STATE | SYNCHRONIZE, FALSE, L"Ev"); //要有SYNCHRONIZE标志,这是同步所必须的 DWORD res; while (true) { res = WaitForSingleObject(hEvent, INFINITE); if (res == WAIT_OBJECT_0) { printf("Hello world! "); break; } } CloseHandle(hEvent); return 0; }