检查 child PID 是否正在等待 Scanf
Check if a child PID is waiting for an Scanf
我有一个代码,在某些时候会分叉一个 child。
child 唯一的代码是 scanf。
parent进程需要监控tischild进程的状态:
1) 运行
2) 在scanf中等待输入
3) 终止
使用 waitpid 和 WNOHANG 检查是否终止很简单。问题是我不知道如何区分 child 进程是否正在等待输入。
PS.: 我的案例有一个限制,我无法将信息从 child 发送到它的 parent。否则我可以在 scanf 之前和之后使用变量。
PS.: 我在linux
如何检查 child 进程是否进入了等待 scanf 输入(或一般的 IO)的状态?
您在使用 <Windows.h>
吗?这是您要查找的内容吗?
WaitForInputIdle
Waits until the specified process has finished processing its initial input and is waiting for user input with no input pending, or until the time-out interval has elapsed.
HANDLE hProc;
// get hProc here
WaitForInputIdle(hProc, INFINITE); // wait forever until input idle
// do something here
有关 API 的更多信息可在此处找到:
https://msdn.microsoft.com/en-us/library/windows/desktop/ms687022(v=vs.85).aspx
进程和IO的概念通常是分离的。 child 和 parent 进程之间没有交换信号,除了发送到 parent pid 并传播到 children 的 unix(kill)信号。 =26=]
Waitpid 只是等待 child pid 的终止,returning 它的状态代码。
如果你想在 parent 和 child 之间交换数据,你需要在两个进程之间创建一个 pipe
(参见 man -s 2 pipe
),参见手册页一个例子。
如果你想在child中使用scanf
(来自stdin的输入),你需要将pipefd[0]
绑定到stdin文件描述符0
(或者STDIN_FILENO).
现在您可以在 parent 进程中使用 select
或 poll
来检查 child 是否准备好读取 parent 发送的数据至 pipefd[1]
.
如果您使用 printf
或其他一些 stdio.h
方法写入 child(例如通过 STDOUT_FILENO),[=55= 上的 IO ] 可能无论如何都会阻塞,即使 select
或 poll
告诉 child 已准备好接收数据,如果 child 读取速度太慢或停止读取太早并且输出缓冲区已满(我认为默认大小为 4096 字节)。
一个unistd.h
写调用可能return一个值
nw = write(pipefd[1], buffer, nbytes);
nw < nbytes
如果 child 没有读取那么多 (nbytes
) 个字节的输入。
所以在进行异步通信时要小心绊倒的危险。当您了解异步方法时,检查 CSP(通信顺序进程)方法作为一种不同且更稳定的通信方法,它使用同步通信。
我有一个代码,在某些时候会分叉一个 child。 child 唯一的代码是 scanf。 parent进程需要监控tischild进程的状态: 1) 运行 2) 在scanf中等待输入 3) 终止
使用 waitpid 和 WNOHANG 检查是否终止很简单。问题是我不知道如何区分 child 进程是否正在等待输入。
PS.: 我的案例有一个限制,我无法将信息从 child 发送到它的 parent。否则我可以在 scanf 之前和之后使用变量。
PS.: 我在linux
如何检查 child 进程是否进入了等待 scanf 输入(或一般的 IO)的状态?
您在使用 <Windows.h>
吗?这是您要查找的内容吗?
WaitForInputIdle
Waits until the specified process has finished processing its initial input and is waiting for user input with no input pending, or until the time-out interval has elapsed.
HANDLE hProc;
// get hProc here
WaitForInputIdle(hProc, INFINITE); // wait forever until input idle
// do something here
有关 API 的更多信息可在此处找到: https://msdn.microsoft.com/en-us/library/windows/desktop/ms687022(v=vs.85).aspx
进程和IO的概念通常是分离的。 child 和 parent 进程之间没有交换信号,除了发送到 parent pid 并传播到 children 的 unix(kill)信号。 =26=]
Waitpid 只是等待 child pid 的终止,returning 它的状态代码。
如果你想在 parent 和 child 之间交换数据,你需要在两个进程之间创建一个 pipe
(参见 man -s 2 pipe
),参见手册页一个例子。
如果你想在child中使用scanf
(来自stdin的输入),你需要将pipefd[0]
绑定到stdin文件描述符0
(或者STDIN_FILENO).
现在您可以在 parent 进程中使用 select
或 poll
来检查 child 是否准备好读取 parent 发送的数据至 pipefd[1]
.
如果您使用 printf
或其他一些 stdio.h
方法写入 child(例如通过 STDOUT_FILENO),[=55= 上的 IO ] 可能无论如何都会阻塞,即使 select
或 poll
告诉 child 已准备好接收数据,如果 child 读取速度太慢或停止读取太早并且输出缓冲区已满(我认为默认大小为 4096 字节)。
一个unistd.h
写调用可能return一个值
nw = write(pipefd[1], buffer, nbytes);
nw < nbytes
如果 child 没有读取那么多 (nbytes
) 个字节的输入。
所以在进行异步通信时要小心绊倒的危险。当您了解异步方法时,检查 CSP(通信顺序进程)方法作为一种不同且更稳定的通信方法,它使用同步通信。