Linux模拟shell的实现

  shell用fork建立新进程,用exex在新进程中运行用户指定的程序,最后shell用wait命令等待新进程结束。wait系统调用同时从内核取得退出状态或者信号序号以告知子进程是如何结束的。

1 #include<stdio.h>
  2 #include<stdlib.h>
  3 #include<unistd.h>
  4 #include<sys/wait.h>
  5 #include<sys/types.h>
  6 int main()
  7 {
  8     printf("[g33@localhost myShell]$");
  9     fflush(stdout);
 10     sleep(5);
 11     char cmd[128];
 12     ssize_t s = read(0,cmd,sizeof(cmd)-1);
 13 //  cmd[s-1]='\0';
 14     if(s>0)
 15     {                                                                       
 16         cmd[s-1]='\0';
 17     }
 18     else
 19     {
 20         perror("read");
 21         return 1;
 22     }
 23     printf("%s\n",cmd);
 24
 25     char *_argv[32];                                                        
 26     _argv[0]=cmd;
 27     char *start = cmd;
 28     int i = 1;
 29     while(*start)
 30     {
 31         if(isspace(*start))
 32         {
 33             *start = '\0';
 34             start++;
 35             _argv[i] = start;
 36             i++;
 37             continue;
 38         }
 39         start++;
 40     }                                                                       
 41         _argv[i]=NULL;
 42     pid_t id = fork();
 43     if(id<0)
 44     {
 45         perror("fork");
 46     }
 47     else if(id==0)
 48     {//child
 49
 50             execvp(_argv[0],_argv);
 51             exit(2);
 52     }
 53     else
 54     {//father
 55         int status = 0;
 56         pid_t ret = waitpid(id,&status,0);
 57         if(ret>0&&WIFEXITED(status))
 58         {                                                                   
 59             printf("wait success...exit code:%d\n",WEXITSTATUS(status));
 60         }
 61         else
 62         {
 63             printf("wait filed..\n");
 64             return 3;
 65         }
 66     }
 67
 68     return 0;
 69 }
 70
 
 


 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值