2017-05-06 6 views
0

私は3つの引数、./a.out abcを受け取ります。ここで、aとcは列番号で、bとはで区切られた行からのオペランド。stdin(および値を格納する)パイプを子に読み込み、切り取りを行い、値を返す

trueの場合は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

一つの問題は、多くのシェルで「>」と「=」の文字は特別なを持っているということです意味。 fdにリテラルを使用するのは少し醜いです。私はそれを明確にするためにマクロを好む。 –

+0

シェルで試してみると、 ">"を使って再読みの問題を回避しています。 マクロは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 
関連する問題