【linux】编写一个简单的shell
2017-05-09 22:00
513 查看
给出提示符,让用户输入一行命令,识别程序名和参数并调用适当的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,成功返回存储路径的指针
模拟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; }
相关文章推荐
- 用C语言编写一个Linux下的简单shell程序
- linux入门:编写一个简单的shell(仅支持部分ls,ps命令)
- 用C语言编写一个Linux下的简单shell程序
- 一个简单的shell脚本编写的GUI程序
- UNIX-LINUX编程实践教程->第八章->实例代码注解->写一个简单的shell->在shell中启动另一个程序
- linux之一个简单的shell程序
- 【sehll学习】linux运维一个简单shell脚本监控系统内存
- 【Linux】实现一个简单的shell
- 第一次使用linux并编写了一个dump mysql的程序,记录下简单的步骤
- linux下的一个简单md5shell
- 利用linux下的c语言编程来简单的实现一个shell功能实现!
- 在Linux下简单编写、编译并执行一个C语言程序
- UNIX-LINUX编程实践教程->第八章->实例代码注解->写一个简单的shell
- 编写一个简单的SHELL脚本
- Linux下,使用C/C++编写一个简单的消息处理程序
- 使用shell编写的一个简单的时钟(tput和date介绍)
- Linux下,使用C/C++编写"静态链接库"的一个简单例子
- 在Linux环境下编写一个简单的进度条
- 编写一个简单的http server(Linux, gcc)
- 编写自己的shell解析器(一)一个简单的循环命令输入和历史打印