尝试实现shell程序我遇到了以下情况。
我想实现至少一个级别的管道(不链接) 例 我希望我的shell可以执行以下命令
ls | less
这是我的片段
int main()
{
pid_t pid;
int fd[2];
char buffer[1024];
pipe(fd);
pid=fork();
if(pid==0){
close(fd[0]);
dup2(fd[1],1);
close(fd[1]);
execlp( "ls","ls",NULL);
exit(0);
}else{
//parent
wait(NULL);
close(fd[1]);
read(fd[0],buffer,sizeof(buffer)); // the parent reads the output of the last command
// from stdout
//printf("Recived:: %s\n",buffer); //for debugging --- and it works(got the output of the last command printed)!
pid=fork();
if(!pid){
//printf("In new child ::%s\n",buffer);// this line stil works
**/** !! HERE IS THE ISSUE **/**
// I want to pass the a filename as an argument to the next command
// in this case for less
// someting like this execlp("less","less",filename.ext,NULL);
// my question is how can I get file name in this situation
//I tried to get file struct from the file discriptor and the tried to get
// file name from that file , but faild!
//FILE * file=fdopen(fd[0],"r+");
//file->name;
execlp("less","less",buffer ,NULL);
}
}
return 0;
}