2017-05-06 42 views
0

我在做一个程序,它将接收3个参数,./a.out abc,其中a和c是列号,b和操作数由行分隔。将stdin(和存储值)管道读到子节点,执行切换并返回值

当它的真实再现stdin其他没有结果。

例子:

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

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

我试着在我的第一个版本,doint管道,并从标准输入读取数据时切需要它,但我的问题是,我失去了输入。

现在我试图从小孩的标准输入读取,存储并通过管道传递它,但对于我的测试,我猜测execlp没有得到stdin输入。

我不能使用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"); } 

} 
+0

一个问题,我可以看到的是,在许多炮弹“>”和“=”字符有特殊含义。为文字使用文字也有点难看。我更喜欢宏来澄清这一点。 –

+0

当我尝试在shell上使用“>”来避免重新指定问题。 宏的意思就像STDIN等? –

+0

我在说的是STDIN_FILENO,STDOUT_FILENO,STDERR_FILENO。是的,引用或逃避标志应该解决这种问题。 –

回答

0

固定这样的:

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