Ai
1 Star 0 Fork 0

20155326刘美岑/lmc20155326

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
mybash.c 2.00 KB
一键复制 编辑 原始数据 按行查看 历史
20155326刘美岑 提交于 2017-12-09 11:45 +08:00 . mybash
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <string.h>
#include <unistd.h>
#include <pwd.h>
#define PATH "/home/"
void print_info()
{
uid_t id = getuid();
char *status = "$";
if( id == 0)
{
status = "#";
}
struct passwd *p = getpwuid(id);
if(p == NULL)
{
printf("mybash>>");
fflush(stdout);
return;
}
char path[128] = {0};
getcwd(path,256);
char *q = "/";
char *s = strtok(path,"/");
while( s != NULL)
{
q = s;
s = strtok(NULL,"/");
}
char hostname[128] = {0};
gethostname(hostname,128);
printf("[%s@%s %s]%s ",p->pw_name,hostname,q,status);
}
int main()
{
while(1)
{
print_info();
char buff[128] = {0};
fgets(buff,128,stdin);
buff[strlen(buff)-1] = 0;
char *myargv[10] = {0};
char *s = strtok(buff," ");
if(s == NULL)
{
continue;
}
myargv[0] = s;
int i = 1;
while((s = strtok(NULL," ")) != NULL)
{
myargv[i++] = s;
}
if(strcmp(myargv[0],"exit") == 0)
{
exit(0);
}
else if(strcmp(myargv[0],"cd") == 0)
{
if(chdir(myargv[1]) == -1)
{
perror("chdir error");
}
continue;
}
pid_t pid = fork();
assert(pid != -1);
if(pid == 0)
{
char path[256] = {0};
if(strncmp(myargv[0],"./",2) != 0 && strncmp(myargv[0],"/",1) != 0)
{
strcpy(path,PATH);
}
strcat(path,myargv[0]);
execv(path,myargv);
perror("execv error");
exit(0);
}
else
{
wait(NULL);
}
}
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
C
1
https://gitee.com/lmc1998/lmc20155326.git
git@gitee.com:lmc1998/lmc20155326.git
lmc1998
lmc20155326
lmc20155326
master

搜索帮助