【linux】编写一个简单的shell

给出提示符,让用户输入一行命令,识别程序名和参数并调用适当的exec函数执行程序,待执行完成后再次给出提示符。

模拟Shell的提示符:

这里写图片描述
我们要用到三个函数:

1)getpwnam()
这里写图片描述

这里写图片描述

void GetLoginName() {
struct passwd* pass;
pass = getpwuid(getuid());
printf(“[%s@”,pass->pw_name); }

2)gethostname()
这里写图片描述
函数功能:获得主机名
参数:一个字符数组,len是希望读取的字符数
返回值:成功返回0,失败返回-1

3)getcwd()函数
这里写图片描述
函数功能:获得当前工作目录的的绝对路径,
参数:存储在buf为首地址的空间中,size表示读取字符稍微略大的个数
返回值:失败返回NULL,成功返回存储路径的指针

#include<stdio.h>
#include<unistd.h>
#include<string.h>
#include<sys/types.h>
#include<pwd.h>
#include<sys/wait.h>
#include<stdlib.h>
#include<ctype.h>
void GetLoginName()
 {
         struct passwd* pwd;
         pwd = getpwuid(getuid());
         printf("[%s@", pwd->pw_name);
 }

 void GetHostName()
 {
       char name[100] = { 0 };
       gethostname(name, sizeof(name)-1);
       printf("%s", name);

 }
 void GetDir()
 {
     char pwd[100] = { 0 };
     getcwd(pwd, sizeof(pwd)-1);
     int len = strlen(pwd);
     char* start = pwd + len - 1;

         while (*start != '/'&&len--)
         {
                 --start;
         }
     start++;
     printf("%s]#", start);


 }

 int main()
 {

     while (1)
     {
         GetLoginName();
         GetHostName();
         GetDir();
         fflush(stdout);

         char line[1024];
         ssize_t s = read(0, line, 1024);
         char* _argv[32];
         char* start = line;
         _argv[0] = start;

         int i = 1;
         if (s > 0)
         {
             while (*start)
             {
                 if (isspace(*start))
                 {
                     while (isspace(*start))
                     {
                         *start = '\0';
                         start++;
                     }
                     _argv[i++] = start;

                 }
                 else
                 {
                     start++;
                 }

             }
         }
         else
         {
             continue;
         }
         i--;
         _argv[i] = NULL;

         for (int j = 0; j < i; j++)
         {
             printf("debug:%s\n", _argv[j]);
         }

         pid_t id = vfork();

         if (id < 0)
         {
             perror("fork unsuccessfully");
         }
         else if (id == 0)//child
         {
             execvp(_argv[0], _argv);

         }
         else
         {
             //  sleep(1);
             //wait(NULL);
             int status;
             waitpid(id, &status, 0);
             printf("wait child sucessffly,siganl:%dretcode:%d\n", status & 0xff, (status >> 8) & 0xf & 0xfff);

         }
     }

     return 0;
 }

这里写图片描述
这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值