linux下自定义的bash

#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <unistd.h>
#include <string.h>
#include <signal.h>
#include <pwd.h>
#define MAX_ARGV_NUM 10
#define PATH      //"/home/Desktop/project/mybin/exec/" 通过exec调用的可执行文件的目的路径

void printinfo();
int main(int agrc, char *agrv[])
{
   char *myargv[MAX_ARGV_NUM] = {0};
   while(1)
   {
		memset(myargv, 0, MAX_ARGV_NUM);//避免前次的输入对下此的影响
        printinfo();
        char buff[128] = {0};
		fgets(buff, 128, stdin);//从标准输入获取命令
        buff[strlen(buff)-1] = 0;
        myargv[0] = strtok(buff, " ");
        int i = 0;
        char *s = NULL;
        while ((s = strtok(NULL, " ")) != NULL)
        {
			myargv[++i] = s;
        }

 		int tag = 0;
		if (myargv[0] == NULL)
		{
			continue;
		}
        if (!(strcmp("exit", myargv[0])))
        {
		exit(0);
        }

        if (!(strcmp(myargv[0], "cd")))
        {
		if (chdir(myargv[1]) == -1)
		{
			printf("error\n");
			continue;
		}
	}

	char path_info[256] = {0};
	if (strncmp(buff, "/", 1)!=0 && strncmp(buff, "./", 2)!=0)
	{
		strcpy(path_info, PATH);
	}
        int pid = fork();
        assert(pid != -1);
	strcat(path_info, myargv[0]);
        if (pid == 0)
        {
		//execvp(myargv[0], myargv);
		execv(path_info, myargv);
		printf("bash: command not found\n");
		exit(0);
        }
        wait(NULL);     
   }
}



void printinfo()
{
        uid_t uid = getuid();
        char s = '#';
        if (uid != 0)
		{
			s = '$';
 		}

        struct passwd *p = getpwuid(uid);//获取当前用户的uid
        assert(p!=NULL);
     
		char hostname[128] = {0} ;
        gethostname(hostname, 128);//获取当前用户的名字
	
        char address[256] = {0};
		if (getcwd(address, 256) == NULL)
        {
              perror("error");
        }
        char *q1 = "/"; 
		char *q = strtok(address, "/");
        while(q != NULL)
		{
			q1 = q;
            q = strtok(NULL,"/");
		}
        printf("[%s@%s %s]%c",p->pw_name, hostname, q1, s);
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值