将标准输入(和存储值)管道读取到子级,进行切割,然后 return 值

Read stdin (and store value) pipe to child, do a cut, and return value

我正在编写一个将接收 3 个参数的程序,./a.out a b c,其中 a 和 c 是列号,b 和操作数来自由 :.

分隔的行

当它为 true 时重现标准输入,否则没有结果。

示例:

$ ./a.out 1 > 2
$ 5:2:1:6
5:2:1:6

$ ./a.out 2 = 4
$ 1:2:3:4
$

我在我的第一个版本中尝试过,在剪辑需要时点入管道并从标准输入中读取,但我的问题是我丢失了输入。

现在我正在尝试从子进程中的标准输入读取数据,存储并通过管道传递它,但对于我的测试,我猜测 execlp 没有获得标准输入输入。

我不会使用 awk,这是为了学术工作。

我此时的代码:

int main(int argc, char const *argv[]){

    int n,f;
    char coluna1[16];
    char coluna2[16];
    char strin[PIPE_BUF];
    //put together args cut
    char buffer[PIPE_BUF];
    sprintf(buffer, "-f%s,%s",argv[1],argv[3]);

    //pipes
    int fd[2];
    int fd2[2];
    pipe(fd);
    pipe(fd2);

    if(!fork()) {
        close(fd[0]); //close read
        dup2(fd[1],1); //std output duplicated to pipe write
        close(fd2[0]); //close read
        //readline stdin
        n = read(0,strin,PIPE_BUF);
        write(fd2[1],strin,n);
        //cut -d: -f2,4 -
        execlp("cut","cut","-d:",buffer,"-",NULL);
    }
    //pai recebe do pipe
    close(fd[1]); //close write
    close(fd2[1]); //close write
    n = read(fd2[0],strin,PIPE_BUF); //read stdin from pipe
    f = read(fd[0],buffer,PIPE_BUF); //stdout from cut
    sscanf(buffer,"%[^:]:%s",coluna1,coluna2);

    //write the result from the cut to "bug check"
    write(1,buffer,f);

    //printfs just to check if everything worked
    if(strcmp(argv[2],"=")) if(atoi(coluna1) == atoi(coluna2)) { write(1,strin,n); printf("ACERTEI NO =\n"); }
    if(strcmp(argv[2],">=")) if(atoi(coluna1) >= atoi(coluna2)) { write(1,strin,n); printf("ACERTEI NO >=\n"); }
    if(strcmp(argv[2],"<=")) if(atoi(coluna1) <= atoi(coluna2)) { write(1,strin,n); printf("ACERTEI NO <=\n"); }
    if(strcmp(argv[2],">")) if(atoi(coluna1) > atoi(coluna2)) { write(1,strin,n); printf("ACERTEI NO >\n"); }
    if(strcmp(argv[2],"<")) if(atoi(coluna1) < atoi(coluna2)) { write(1,strin,n); printf("ACERTEI NO <\n"); }
    if(strcmp(argv[2],"!=")) if(atoi(coluna1) != atoi(coluna2)) { write(1,strin,n); printf("ACERTEI NO !=\n"); }

}

修复如下:

if(!fork()) {
    close(fd[0]); //close read
    dup2(fd[1],1); //std output duplicated to pipe write
    close(fd2[1]); //close write
    dup2(fd2[0],0); //std input from father duplicated to pipe read
    //cut -d: -f2,4 -
    execlp("cut","cut","-d:",buffer,"-",NULL);
}
//father
close(fd[1]); //close write
close(fd2[0]); //close read
n = read(0,strin,PIPE_BUF);
write(fd2[1],strin,n);
close(fd2[1]);
//n = read(fd2[0],strin,PIPE_BUF); //read stdin from pipe
f = read(fd[0],buffer,PIPE_BUF); //stdout from cut