[英]Using a pipe to execute cat and grep
我想在文件上执行cat
然后使用grep
搜索该文件中存在的字符串的次数
我当前的代码:
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/wait.h>
int main() {
pid_t pid ;
int fd[2];
pipe(fd);
pid = fork();
if(pid == 0) {
// close sdout and redirect output to fd[1]
close(1);
dup(fd[1]);
close(fd[0]);
close(fd[1]);
char *exp[] = {"cat", "filename.txt", NULL};
if( (execvp("cat", exp)) < 0) {
perror("Execvp failed from child");
}
exit(EXIT_FAILURE);
}
else if(pid > 0) {
// close stdin and redirect input to fd[0]
wait(NULL);
close(0);
dup(fd[0]);
close (fd[1]);
close(fd[0]);
char *exp[] = {"grep", "-c", "name", "filename.txt", NULL};
if((execvp("grep", exp)) < 0) {
perror("Execvp failed from parent");
}
exit(EXIT_FAILURE);
}
else {
printf("Error in forking");
exit(EXIT_FAILURE);
}
close(fd[0]);
close(fd[1]);
return 0;
}
我得到一个 0 的 output 这是错误的,因为我正在搜索的字符串存在于文件中并从终端运行grep
会导致不同的 output 发生这种情况,为什么要这样做?
解决方案:
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/wait.h>
int main() {
pid_t pid ;
int fd[2];
pipe(fd);
pid = fork();
if(pid == 0) {
// close sdout and redirect output to fd[1]
close(1);
dup(fd[1]);
close(fd[0]);
close(fd[1]);
char *exp[] = {"cat", filename.txt", NULL};
execvp("cat", exp);
exit(EXIT_FAILURE);
}
else if(pid > 0) {
// close stdin and redirect input to fd[0]
close(0);
dup(fd[0]);
close (fd[1]);
close(fd[0]);
char *exp[] = {"grep", "-c", "name", NULL};
execvp(exp[0], exp);
exit(EXIT_FAILURE);
}
else {
printf("Error in forking");
exit(EXIT_FAILURE);
}
close(fd[0]);
close(fd[1]);
return 0;
}
该问题的主要解决方法是从评论中删除文件名,正如一位用户指出的那样,这让我得到了正确的 output。 但是,正如另一位用户在评论中建议的那样,需要进行一些优化,例如删除wait(NULL)
并删除对exec
返回的内容的测试。 感谢大家!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.