[英]Troubles with a pipe and a fork
I'm making a program that search files and sends it's results to other commands, like a pipe. ls |我正在制作一个搜索文件并将其结果发送到其他命令的程序,例如 pipe。ls | sort When I run the program nothing happens.The problem I think is that the child's waits for the parent to stop writting in the SO buffer for starting the reading. sort 当我运行程序时没有任何反应。我认为问题是孩子等待父母停止在 SO 缓冲区中写入以开始阅读。 This is what it sends to stdout and what the pipe should send to the other command.这是它发送到 stdout 的内容,也是 pipe 应该发送到其他命令的内容。
troneras@troneras-VirtualBox:~/Escritorio/busca.2012$ ./busca . -n . -print
./permisos.txt
./busca2.c
./mmap.pdf
./busca3.c~
./cuadernoso4.2011b.pdf
./busca.c~
./busca.c
./busca2.c~
./busca3.c
I don't understand what the problem is.我不明白问题出在哪里。
if(!strcmp(argv[4],"-pipe"))
{
int pipefd[2];
int pid,dummi;
if (pipe(pipefd)<0){
perror("pipe");
exit(1);
}
pid = fork();
if (pid<0){
perror("fork");
exit(1);
}
if (pid == 0){//Child process
close(pipefd[1]);//The child is only reading from the pipe
if(dup2(pipefd[0],0)!=0){perror("dup2");exit(1);}
close(pipefd[0]);
char *argumentos[argc-4];
int j;
for (j=5;j<argc;j++){
argumentos[j-5]=argv[j];
}
argumentos[j-5]= NULL;
execvp(argv[5],argumentos);
perror("execve: ");
}else{ //parent
close(pipefd[0]);
if(dup2(pipefd[1],1)!=1){perror("dup2");exit(1);}
close(pipefd[1]);
while(count--){
if(strcmp(files[count]->d_name,".") && strcmp(files[count]->d_name,"..")){
printf("%s/%s\n",argv[1],files[count]->d_name);
free(files[count]);
}
wait(&dummi);
}
}//end pipe
free(files);
BTW There is no reason to duplicate the argv[] array.顺便说一句,没有理由复制 argv[] 数组。 Instead of代替
char *argumentos[argc-4];
int j;
for (j=5;j<argc;j++){
argumentos[j-5]=argv[j];
}
argumentos[j-5]= NULL;
execvp(argv[5],argumentos);
You could just as well do你也可以这样做
execvp(argv[5],argv+5);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.