Chinaunix首页 | 论坛 | 博客
  • 博客访问: 268769
  • 博文数量: 84
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 927
  • 用 户 组: 普通用户
  • 注册时间: 2015-03-06 23:00
个人简介

growing

文章分类

全部博文(84)

文章存档

2017年(6)

2016年(61)

2015年(17)

我的朋友

分类: LINUX

2016-06-22 10:44:22


  1. #include<stdio.h>
  2. #include<unistd.h>
  3. #include<sys/wait.h>
  4. #include<sys/types.h>
  5. #include<string.h>

  6. int main()
  7. {
  8.     while(1)
  9.     {
  10.       //printf("[enen@shiwo shell]#");
  11.       printf("[%s@localhost shell$", getlogin());
  12.       fflush(stdout);

  13.       char buff[1024];
  14.       memset(buff,'\0',sizeof(buff));

  15.       ssize_t _sz = read(0,buff,sizeof(buff)-1);
  16.       if(_sz > 0){
  17.           buff[_sz - 1] = '\0';
  18.       }
  19.       //printf("%s",buff);

  20.         char *my_argv[64];
  21.         char*p = buff;
  22.         int index = 1;
  23.         my_argv[0] = buff;
  24.         while(*p != '\0'){
  25.             if(*p == ' '){
  26.                 *p = '\0';
  27.                 ++p;
  28.                 my_argv[index++] = p;
  29.             }else{
  30.                 ++p;
  31.             }
  32.         }
  33.          my_argv[index] = NULL;
  34.          pid_t id = fork();
  35.          if(id == 0){
  36.           //child
  37.           //printf("I am child:%d\n",getpid());
  38.           //sleep(2);
  39.         // char *my_argv[] =
  40.         // {
  41.         // "ls",
  42.         // "-l",
  43.         // "-i",
  44.         // "-a",
  45.         // NULL
  46.         // };
  47.         // char* my_env[] = {
  48.         // "PATH=hello/i/am/fairy",NULL
  49.         // };
  50.           //execl("/bin/ls","ls","-l","-a","-i",NULL);
  51.           //execv("/bin/ls",my_argv);
  52.           //execle("./hello","ls",NULL,my_env);
  53.           //execlp("ls","ls","-l",NULL);
  54.           execvp(my_argv[0],my_argv);
  55.       }else{
  56.           //father
  57.           //printf("I am father:%d\n",getpid);
  58.           pid_t ret = waitpid(id,NULL,0);
  59.           if(ret > 0){
  60.              // printf("wait success!\n");
  61.           }else{
  62.              // printf("wait failes!\n");
  63.           }
  64.       }
  65.     }
  66.     return 0;
  67. }
Makefile

  1. shell:shell.c
  2.     gcc -o shell shell.c
  3. .PHONY:clean
  4. clean:
  5.     rm -f shell
阅读(1537) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~