繁体   English   中英

C - 将 awk/sed 标准输出重定向到管道不起作用

[英]C - Redirecting awk/sed stdout to pipe doesn't work

所以我有一个练习要做,这个练习的一部分要求我们执行一个作为参数传递的命令,能够在标准输入上传递一些字符串,并在标准输出和标准错误上得到它的输出。 我是怎么做到的,我需要将 stdout 和 stderr(孩子的,它将调用一个 exec)重定向到几个管道(管道的另一端由父级保持打开)。 我设法做到了,当我要求它执行 bash 并发送它“ls”时,它给了我我想要的东西,我想要的地方。 与猫和其他人一样。 问题是,当我尝试执行 awk 或 sed 时,管道上没有写入任何内容。 曾经。 如果我保持标准输出不变,它会按应有的方式打印它。 但是一旦我重定向标准输出,什么都没有。 我尝试了所有方法,select()、wait()、sleep()(即使不允许这样做)。 似乎没有任何效果。

我为我的意思做了一个最低限度的工作示例(显然,它缺乏约定和谨慎的写作,如 free() 和 close(),但它确实是工作),这是我所附的。 当我这样称呼它时,代码可以工作: ./program $(which bash)它提示输入一些东西,我写了“ls”,它给了我预期的结果,但是当我尝试./program $(which awk) '{print $0;}'我什么也没得到

这是代码(最小工作示例):

#define _GNU_SOURCE
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <stdlib.h>
#include <fcntl.h>
#include <string.h>
#include <sys/wait.h>
#include <sys/time.h>
#include <signal.h>
#include <errno.h>

int main(int argc, char* argv[]){
    int fdStdinP[2],fdStdoutP[2];
    char *string,*array[3];
    array[0]=argv[1];
    array[1]=argv[2];
    array[2]=0;
    pipe(fdStdinP);
    pipe(fdStdoutP);
    int pid=fork();
    if(pid==0){
        close(fdStdinP[1]);
        close(fdStdoutP[0]);
        dup2(fdStdinP[0],0);
        close(fdStdinP[0]);
        dup2(fdStdoutP[1],1);
        close(fdStdoutP[1]);
        //as suggested, the file descriptors are now closed
        execvp(argv[1],array);
        perror("");
        return 0;
    }
    close(fdStdinP[0]);
    close(fdStdoutP[1];
    string=calloc(1024,sizeof(char));
    read(0,string,1024);
    write(fdStdinP[1],string,1024);
    free(string);
    string=calloc(1024,sizeof(char));
    read(fdStdoutP[0],string,1024);
    printf("I have read:%s",string);
    return 0;
}

感谢您的时间。

awk 继续等待输入并缓冲其输出,因此似乎挂起。 关闭发送端将告诉 awk 它的输入已经结束,因此它将结束并刷新其输出。

write(fdStdinP[1],string,1024);
close(fdStdinP[1]);    // just added this line.

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM