gpt4 book ai didi

c - 读取标准输入(并存储值)管道到子级,进行剪切并返回值

转载 作者:行者123 更新时间:2023-11-30 16:46:18 25 4
gpt4 key购买 nike

我正在编写一个程序,它将接收 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

关于c - 读取标准输入(并存储值)管道到子级,进行剪切并返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43822912/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com