【发布时间】:2015-12-12 14:21:55
【问题描述】:
Linux 支持“sys/wait.h”中定义的 POSIX 等待机制。 wait, waitid, waitpid 方法可用于在使用fork 创建的父进程和子进程之间交换状态信息。
Windows 既不提供(原生)fork 支持,也不提供 POSIX 等待机制。相反,还有其他方法可用于 spwan 子进程,即CreateProcess。
当将使用 fork/wait 以 C 或 C++ 编写的 linux 应用程序移植到 Windows 时,在父进程中监视子进程的状态变化(即 WEXITED, WSTOPPED, WCONTINUED)最合适的 native* 方法是什么?
*native 意味着不使用 Windows 未附带或由 MS 以运行时环境形式直接提供的其他库、框架、程序(如 cygwin、minGW)。
编辑:根据 cmets 的要求,我确实提供了一些关于应该以伪代码形式解决什么问题的更多信息:
//creates a new child process that is a copy of the parent (compare
//POSIX fork()) and returns some sort of handle to it.
function spawnChild()
// returns TRUE if called from the master process FALSE otherwise
function master()
// return TRUE if called from a child process FALSE otherwise
function child()
// returns TRUE if child process has finished its work entirely,
// FALSE otherwise.
function completelyFinished()
//sends signal/message "sig" to receive where receiver is a single
//handle or a set of handles to processes that shall receive sig
function sendSignal(sig, receiver)
// terminates the calling process
function exit()
// returns a handle to the sender of signal "sig"
function senderOf(sig)
function masterprocess()
master //contains handle to the master process
children = {} //this is an empty set of handles to child processes
buf[SIZE] //some memory area of SIZE bytes available to master process and all children
FOR i = 0 TO n - 1
//spawn new child process and at its handle to the list of running
//child processes.
children <- children UNION spawnChild()
IF(master())
<logic here>
sendSignal(STARTWORKING, children) //send notification to children
WHILE(signal = wait()) // wait for any child to respond (wait is blocking)
IF signal == IMDONE
<logic here (involving reads/writes to buf)>
sendSignal(STARTWORKING, senderOf(signal))
ELSEIF signal == EXITED
children <- children \ signal.sender //remove sender from list of children
ELSEIF(child())
WHILE(wait() != STARTWORKING);
<logic here (involving reads/writes to buf)>
IF completelyFinished()
sendSignal(EXITED, master)
exit()
ELSE
sendSignal(IMDONE, master)
【问题讨论】:
-
Windows 进程的“状态”与 POSIX 进程不同。如果您想等待进程退出,您可以使用 GetExitCodeProcess 进行轮询,也可以简单地将 WaitForSingleObject(或其亲属之一)与进程句柄一起使用。
-
所以你真的对进程间通信感兴趣,根本不关心 Posix 信号?
-
“任何与所述 POSIX 信号的行为最相似的适当机制”。真的没有什么接近的。 Win32 不能那样工作。你真正想要解决的问题是什么?
-
@norritt 但是你的程序没有做
kill(parentPid, SIGCONT)因为它作为一个信号进来,而不是你waitid的东西。我试图了解原始 unix 程序是如何设计的,以便孩子自己生成停止、继续和退出事件,以便与父母交流。这对我来说是奇怪的部分。 Windows 的方式是使用 IPC 机制,而不是试图将 IPC 塞入子进程生命周期通知中。 -
您正试图将方形钉 (POSIX) 放入圆孔 (Win32)。如果你足够用力的话,你可以把它放进去,但这需要大量的工作,而且你不会得到最好的结果。
标签: c windows monitoring wait status