如何从子程序访问信号量

时间:2013-01-05 16:57:33

标签: c windows process semaphore

以下程序编译为a.exe并作为“a.exe parent”调用,打印出“bad”。如何让它打印“好”?

编辑:GetLastError返回2

/* Inter-process Communication */
#include <windows.h>
#include <assert.h>
#include <stdio.h>

static HANDLE semaphore;
static STARTUPINFO StartupInfo;
static PROCESS_INFORMATION ProcessInfo;
static char *Args = "a.exe child";

int createChildProcess()
{
  memset(&StartupInfo, 0, sizeof(StartupInfo));
  StartupInfo.cb = sizeof(STARTUPINFO);
  StartupInfo.dwFlags = STARTF_USESHOWWINDOW;
  StartupInfo.wShowWindow = SW_HIDE;

  if (!CreateProcess( NULL, Args, NULL, NULL, FALSE,
                      0,
                      NULL,
                      NULL,
                      &StartupInfo,
                      &ProcessInfo))
    {
      return 0;
    }

  return 1;
}

int main(int argc, char * argv[])
{

  if(!strcmp(argv[1], "child")) {
    semaphore = OpenSemaphore(SYNCHRONIZE|SEMAPHORE_MODIFY_STATE,
                              FALSE, "Global\\EZShare");
    if(semaphore==NULL) {
      printf("bad\n");
    }
    else {
      printf("good\n");
    }

  }
  else {
    semaphore = CreateSemaphore(NULL, 1, 1, "Global\\EZShare");
    assert(semaphore!=NULL);
    assert(createChildProcess());
  }
}

1 个答案:

答案 0 :(得分:3)

父进程在子进程打开信号量之前退出,当它发生时,信号量被销毁。在父母退出Sleep(10000)之前添加main(),你会得到“好”(对于真正的程序,最好等待子进程而不是睡觉)。