[英]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.