小编Saf*_*afy的帖子

当grep通过POSIX管道接收输入并输出到POSIX管道时,它的行为是什么?

我有这个程序,为孩子的stdin,stdout和stderr分叉并创建三个POSIX管道.在分叉之后,子和父关闭它们各自管道的适当端,使得子只能从stdin管道读取并且只写入stdout和stderr管道(而父对面的情况则相反).接下来,子进程关闭并将子进程的stdin,stdout和stderr复制到其打开的管道端,然后使用execvp执行其名称作为父进程的参数传入的程序.程序在行为时应该像cat,ls,rm,banner和ps这样的命令没有任何明显的问题.

但是,当我在终端中运行程序时,如下所示:

程序grep blah

它需要输入但不输出任何东西到终端,但当我尝试:

grep blah

在终端中,grep等待输入并在输入包含单词"blah"时将其打印出来.所以问题是,这是因为我的程序有问题,如下所示?或者当grep必须通过POSIX管道进行通信时,这种行为是否正常?谢谢你的阅读.

这是有问题的程序(请原谅第一次格式化发布):

#include <stdio.h>
#include <stdlib.h> 
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <signal.h>
#include <limits.h>        
int status, cpid; int child = 1;
char mode = 'c';

sigset_t sigMask;
void childHandler(){
    sigprocmask(SIG_BLOCK,&sigMask,NULL);
    int i = waitpid(-1,&status,WNOHANG);
    if(i){
        fprintf(stderr, "The child <%d> has terminated with code <%d>\n",cpid,         WEXITSTATUS(status));
        child = 0;
        mode = 'c';
    }
    sigprocmask(SIG_UNBLOCK,&sigMask,NULL);
 }


 int DEBUG = 0;
 int SLOW = 1;

 fd_set readfds,writefds,errorfds;
 struct timeval timeout;
 int numready;
 int cin,cout,cerr,in,out,err; …
Run Code Online (Sandbox Code Playgroud)

c linux grep posix pipe

2
推荐指数
1
解决办法
1366
查看次数

标签 统计

c ×1

grep ×1

linux ×1

pipe ×1

posix ×1