之前学了一些和进程有关的特性,什么进程控制啊进程替换啊,我们来尝试自己搓一个shell()吧
首先我们观察shell的界面,发现centos的界面上有命令提示符:
[主机名@用户名+当前路径]
我们可以通过调用系统函数获取当前路径,调用环境变量来获取我们的用户名、主机名
//打印命令提示行的函数,命令提示行包括用户名+主机名+当前工作目录
//此为获取用户名
int checkChild();
void Redirection();
void checkRedir();
int length(char* arr[]);
const char* getUser(){
char* user=getenv("USER");
if(user){
return user;
}else{
return "None";
}
}
//此为获取主机名
const char* getHost(){
char* host=getenv("HOSTNAME");
if(host){
return host;
}else{
return "None";
}
}
//此为获取当前路径
const char* getPwd(){
static char cwd[SIZE];
if(getcwd(cwd,sizeof(cwd))!=NULL){
return cwd;
}else{
return "None";
}
}
大概就长这样:
但是我发现了一个问题:写这个程序的时候我的Linux系统是centos,可以通过环境变量获取
但是我吧系统换成ubantu的时候,ubantu的环境变量设置里默认没有hostname这个环境变量
解决这个办法有两种:
1.在环境变量里添加我们的hostname,手动添加
2.通过C语言的gethostname函数来获取
我们这里用一下第二个吧:
const char* getUser(){
static char hostname[1024];
if(gethostname(hostname,sizeof(hostname))==0){
return hostname;
}else{
return "userNone";
}
}
无语了。。。写错接口了
应该是这样:
const char* getUser(){
char* user=getenv("USER");
if(user){
return user;
}else{
return "usernameNone";
}
}
//此为获取主机名
const char* getHost(){
static char hostname[1024];
if(gethostname(hostname,sizeof(hostname))==0){
return hostname;
}else{
return "userNone";
}
}
//此为获取当前路径
const char* getPwd(){
static char cwd[SIZE];
if(getcwd(cwd,sizeof(cwd))!=NULL){
return cwd;
}else{
return "None";
}
}
然后再加入一个整合上面三个函数的接口:
//这是整合上面三者的函数
void MakeCommandLine(){
char line[SIZE];
const char* username=getUser();
const char* hostname=getHost();
const char* cwd=getPwd();
snprintf(line,sizeof(line), "[%s@%s %s]#", username, hostname, cwd);
//snprintf是给定大小的更安全的向内存空间中写入的printf(写到缓冲区)
printf("%s",line);
fflush(stdout);
//printf("[%s@%s %s]#",getUser(),getHost(),getPwd());
}
这个整合上面三个函数的接口中使用了snprintf(),平常我们打印字符串到显示器上使用的是printf(),根据我们之前学习的缓存区的概念,snprintf其实就是把数据输入到缓存区内,sprintf函数也可以,但ssnprintf函数更安全
然后再刷新输出
这样就