1

The following program, compiled as a.exe and invoked as "a.exe parent", prints "bad." How do I make it print "good?"

Edit: GetLastError returns 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());
  }
}
4

1 回答 1

3

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

于 2013-01-05T17:06:26.810 回答