QQ登录

只需一步,快速开始

 找回密码
 注册

QQ登录

只需一步,快速开始

查看: 965|回复: 0

编写一个类似shell的程序时候遇到一个问题

[复制链接]
发表于 2006-1-1 14:03:57 | 显示全部楼层 |阅读模式
最近在做老师布置的作业,要求我们实现一个类似shell的程序,并且支持命令管道,如ps -xj |more,我编了一个,但是出了问题,请大家帮我看一下
源程序:

代码:
[code:1]#include<unistd.h>
#include<sys/stat.h>
#include<stdio.h>
#include<sys/types.h>
#include<sys/wait.h>
#include<stdlib.h>
#include<fcntl.h>
#include<string.h>

int main(int argc,char* argv[]){
     int n,fd[2];
     pid_t pid;

     if(pipe(fd)<0)
         exit(-1);
  
     if((pid=fork())<0)
         exit(-1);
     else if(pid>0){//parent
         close(fd[0]);

     if(fd[1]!=STDOUT_FILENO){
         
             if(dup2(fd[1],STDOUT_FILENO)!=STDOUT_FILENO)
                     printf("dup error");
             close(fd[1]);
      }

      execlp("ps","ps","-xj",(char*)0);      
      if(waitpid(pid,NULL,0)<0)
           printf("wait error");
      exit(0);

   }else{//child

        printf("enter child");
        close(fd[1]);

        if(fd[0]!=STDIN_FILENO){
        
            if(dup2(fd[0],STDIN_FILENO)!=STDIN_FILENO)
                 printf("dup error");
              close(fd[0]);
        }
        execlp("more","more",(char*)0);
        exit(0);
}
}  [/code:1]
结果整个程序就停住了。弄了半天不知什么回事,请各位指点
您需要登录后才可以回帖 登录 | 注册

本版积分规则

GMT+8, 2024-10-1 21:46 , Processed in 0.040829 second(s), 16 queries .

© 2021 Powered by Discuz! X3.5.

快速回复 返回顶部 返回列表