1
我试图使用execvp
来运行grep
。这一计划背后的思想是fork一个子进程,使孩子sort
一个名为sortfile,然后父进程应在有序输出使用grep
文件。以下是我的代码。Grep永不退货
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#define READ 0
#define WRITE 1
int main(int argc, char* argv) {
pid_t cpid;
int status;
int pipefd[2];
pipe(pipefd);
char* args[] = {"grep", "f", NULL};
cpid = fork();
if(cpid == 0) {
dup2(pipefd[READ], READ);
dup2(pipefd[WRITE], WRITE);
close(pipefd[READ]);
close(pipefd[WRITE]);
if(execlp("sort", "sort", "sortfile", NULL) == -1) {
perror("sort");
}
} else {
dup2(pipefd[READ], READ);
dup2(pipefd[WRITE], WRITE);
close(pipefd[READ]);
close(pipefd[WRITE]);
wait(&status);
if(execvp("grep", args) == -1) {
perror("grep");
}
}
}
我使用DUP2复制管道的文件描述符到标准输入和标准输出,然后关闭未使用的文件描述符。即使这样的方案无法返回,这使我相信它试图从其他没有进行写入,从而阻断过程中的文件进行读取。我完全失去了这一点,可以使用一些提示。 sortfile的内容是a b f s g
。
我的上帝,我甚至没有想到这一点。我修复了'dup2'调用,它正在工作。如果您将其作为答案发布,我会接受它。 –