【问题标题】:How to access semaphore from child program如何从子程序访问信号量
【发布时间】:2012-12-19 21:24:17
【问题描述】:

以下程序,编译为 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());
  }
}

【问题讨论】:

  • 打印出错误怎么办?

标签: c windows process semaphore


【解决方案1】:

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

【讨论】:

  • 另一种选择是使信号量句柄可继承(并在对 CreateProcess 的调用中设置继承句柄标志),以便子进程继承原始句柄的副本,强制信号量保持打开状态.当然,在大多数实际情况下,父母最好保持打开状态,但也有一些极端情况。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-04-16
  • 1970-01-01
  • 2019-04-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多