我正在尝试使用forks,pipe和execs在C中模拟这个bash命令:ls -la | cut -c 20-30 | grep -v echelinho
,这是我到目前为止在执行后没有显示任何内容的代码:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <unistd.h>
#include <sys/types.h>
#include <signal.h>
#include <string.h>
#include <sys/wait.h>
int main (int argc , char**argv){
int **pipes;
int i;
int pid1, pid2, pid3;
pipes = malloc(2*sizeof(int*));
for(i=0;i<3;i++){
pipes[i] = malloc (2*sizeof(int));
pipe(pipes[i]);
}
pid1=fork();
if(!pid1){
close(pipes[0][0]);
dup2(pipes[0][1],1);
execlp("ls","ls","-la",NULL);
}
pid2=fork();
if(!pid2){
waitpid(pid1, NULL, 0);
close(pipes[0][1]);
close(pipes[1][0]);
dup2(pipes[0][0],0);
dup2(pipes[1][1],1);
execlp("cut","cut","-c", "20-30", NULL);
}
pid3=fork();
if(!pid3){
waitpid(pid2, NULL, 0);
close(pipes[1][1]);
dup2(pipes[1][0],0);
execlp("grep","grep","-v", "echelinho", NULL);
}
}
有人可以指出我的错误或让这段代码有效吗?我理解我不是错误处理,而且这不是一个很好的习惯,但我只是为了更好地理解这些概念,而不是用于实际/现实世界的应用程序。
答案 0 :(得分:0)
我设法自己解决了这些错误。
最有影响力的两个错误是:
这里是固定代码:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <unistd.h>
#include <sys/types.h>
#include <signal.h>
#include <string.h>
#include <sys/wait.h>
int main (int argc , char**argv){
int fdfst[2];
int fdsnd[2];
pipe(fdfst);
pipe(fdsnd);
switch(fork()){
case -1:
perror("Error on fork.");
case 0:
close(fdfst[0]);
close(fdsnd[0]);
close(fdsnd[1]);
dup2(fdfst[1],1);
close(fdfst[1]);
execlp("ls","ls","-la",NULL);
}
switch(fork()){
case -1:
perror("Error on fork.");
case 0:
close(fdfst[1]);
close(fdsnd[0]);
dup2(fdfst[0],0);
close(fdfst[0]);
dup2(fdsnd[1],1);
close(fdsnd[1]);
execlp("cut","cut","-c", "20-30", NULL);
}
switch(fork()){
case -1:
perror("Error on fork.");
case 0:
close(fdfst[0]);
close(fdfst[1]);
close(fdsnd[1]);
dup2(fdsnd[0],0);
close(fdsnd[0]);
execlp("grep","grep","-v", "echelinho", NULL);
}
close(fdfst[0]);
close(fdfst[1]);
close(fdsnd[0]);
close(fdsnd[1]);
wait(NULL);
wait(NULL);
wait(NULL);
exit(EXIT_SUCCESS);
}