给出提示符,让用户输入一行命令,识别程序名和参数并调用适当的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;
}