my_bash

#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#include <assert.h>
#include <sys/types.h>
#include <sys/utsname.h>
#include <pwd.h>


#define LEN 10
char* Cmd[LEN] = {0};
int count = 0;


char OLDPWD[1024] = {0};


void out_flag()
{
char flag = '$';
struct passwd *pw = getpwuid(getuid());


if(getuid() == 0)
{
flag = '#';
}


struct utsname host;
uname(&host);
char *hostname = strtok(host.nodename, ".");


char path[128] = {0};
getcwd(path, 127);//获取当前目录的绝对路径


char *p = strtok(path, "/");
char *nowdir = NULL;
while(p!= NULL)
{
nowdir = p;
p = strtok(NULL, "/");
}


if(nowdir == NULL)
{
nowdir = "/";
}
if(strcmp(nowdir, pw->pw_name) == 0)
{
nowdir = "~";
}


printf("[%s@%s %s]mybash%c ", pw->pw_name, hostname,
nowdir, flag);
fflush(stdout);
}


void cut_cmd(char *cmd)
{
char *p = strtok(cmd, " ");
while(p != NULL)
{
Cmd[count++] = p;
p = strtok(NULL, " ");
}
}


int special_cmd()
{
//cd    exit 
if(strncmp("cd", Cmd[0], 2) == 0)
{
if(Cmd[1] == NULL || strncmp(Cmd[1], "~", 1) == 0)
{
//切换到家目录
struct passwd *pw = getpwuid(getuid());
Cmd[1] = pw->pw_dir;
}
else if(strncmp(Cmd[1], "-", 1) == 0)
{
//切换到家目录到上一次所在目录
if(strlen(OLDPWD) == 0)
{
printf("mybash: cd :: OLDPWD not set\n");
return 1;
}


Cmd[1] = OLDPWD;
printf("%s\n", Cmd[1]);
}


char str[1024] = {0};
getcwd(str, 1023);
chdir(Cmd[1]);    // 切换路径
strcpy(OLDPWD, str);


return 1;
}
if(strncmp("exit", Cmd[0], 4) == 0)
{
exit(0);
}


return 0;
}


void clear_cmd()
{
int i = 0;
for(;i < count; ++i)
{
Cmd[i] = 0;
}


count = 0;
}


void main()
{
while(1)
{
out_flag();
char cmd[128] = {0};
fgets(cmd, 128, stdin); //获取命令
cmd[strlen(cmd) - 1] = 0; //去掉最后一个回车符


if(strlen(cmd) == 0) // 判别用户的无效输入
{
continue;
}


cut_cmd(cmd); // 切割cmd


int res = special_cmd(); // 判别是否是需要集成到bash中的特殊命令
if(res == 1)
{
clear_cmd(); //清空全局的指针数组,并将count归0
continue;
}


pid_t pid = fork();
assert(pid != -1);


if(pid == 0)
{
// 用命令的可执行文件(./mybin)替换当前进程
char path[1024] = "/home/stu/mydir/LG1702shell/mybin/";
if(strstr(Cmd[0], "/") != NULL)
{
memset(path, 0, 1024);
}
strcat(path, Cmd[0]);
execv(path, Cmd);
printf("mybash: %s : command not found\n", Cmd[0]);
exit(0);
}
else
{
wait(NULL);
}


clear_cmd();
}
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值