假设我们有一个烟斗int InPipe[2];
。读取整个可用数据输入后,如何读取输入,直到管道为空而不阻塞为止?
我知道这个问题已经被问过几次了,但是我无法组装一个合适的函数。
到目前为止,这是我的代码:
int InPipe[2];
char buffer[1024];
int rc;
while (true){
read(InPipe[0], buffer, sizeof(buffer));
fprintf(stdout, “%s“, buffer);
bzero(&buffer, sizeof(buffer)); // Clearing Buffer
}
任何想法,建议和代码段
从管道读取
尝试从
pipe
当前为空的a读取,block
直到至少一个字节已写入pipe
。如果管道的写端是关闭的,则从管道中读取的进程将在读取了所有剩余数据后看到end-of-file
(即read()
返回0)pipe
。
取自linux接口编程。
你不能!在这种情况下,从管道读取的过程将被阻塞。
由于人们的评论,我要添加此部分:
我们可以使用a pipe
来允许两个进程之间的通信。要使用管道连接两个进程,pipe()
请在调用之后再调用fork()
。紧接在之后fork()
,一个进程关闭其用于管道写端的描述符,另一个进程关闭其用于读端的描述符。例如,如果父级将数据发送给子级,则它将关闭其对管道的读取描述符filedes[0]
,而子级将为其对管道的写入描述符关闭filedes[1]
,则此代码将为:
int filedes[2];
if (pipe(filedes) == -1) /* Create the pipe */
errExit("pipe");
switch (fork()) /* Create a child process */
{
case -1:
errExit("fork");
case 0: /* Child */
if (close(filedes[1]) == -1) /* Close unused write end */
errExit("close");
/* Child now reads from pipe */
break;
default: /* Parent */
if (close(filedes[0]) == -1) /* Close unused read end */
errExit("close");
/* Parent now writes to pipe */
break;
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句