linux下管道程序求解
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <errno.h>
#define MAX_CMD_LEN 100
int main()
{
pid_t child_b,child_c;
int pipefds[2];
int i,j;
char *pipe_front,*pipe_behind,*guodu;
char command[MAX_CMD_LEN];
char *arg1[]={"/usr/bin/wc",NULL};
char *arg2[]={"/bin/cat","new_pipe.c",NULL};
char cmd1[MAX_CMD_LEN],cmd2[MAX_CMD_LEN];
//while(1){
printf("please Enter command>");
fgets(command,MAX_CMD_LEN,stdin);
command[strlen(command)-1]=0;
guodu=command;
pipe_front=strsep(&guodu,"|");
pipe_behind=guodu;
for(i=0;i<strlen(pipe_front);i++)
cmd1[i]=*pipe_front++;
for(j=0;j<(pipe_behind);j++)
cmd2[j]=*pipe_behind++;
// printf("pipe_front=%s\n",pipe_front);
// printf("pipe_behind=%s\n",pipe_behind);
pipe(pipefds);
if(!(child_b=fork()))
{
close(pipefds[1]);
close(0);
dup2(pipefds[0],0);
close(pipefds[0]);
execlp(cmd2,cmd2,NULL);
// execve("/usr/bin/wc",arg1,NULL);
}
close(pipefds[0]);
if(!(child_c=fork()))
{
close(1);
dup2(pipefds[1],1);
close(pipefds[1]);
execlp(cmd1,cmd1,NULL);
// execve("/bin/cat",arg2,NULL);
// execlp(command,command,NULL);
}
close(pipefds[1]);
wait4(child_b,NULL,0,NULL);
return 0;
}
如果用execve的话就能正常运行,但只能固定,用execlp的话就根本不能统计出来,都是0,用ls |wc,不知道如何解,目前这个能运行但会出现段错误,求解!
------解决方案--------------------
咱也看看 int execlp(const char *file, const char *arg, ...); 的函数原型再用吧, 你传的是argv数组,人家要求传去变参。