【Linux】第一个简单shell
来源:互联网 发布:ubuntu安装jdk tar.gz 编辑:程序博客网 时间:2024/05/16 14:55
使用c/c++完成一个简单shell,具有基本功能
#include<stdio.h>#include<unistd.h>#include<stdlib.h>#include<sys/types.h>#include<wait.h>#include<pwd.h>#include<string.h>void GetLoginName(){struct passwd* pwd;pwd=getpwuid(getuid());printf("[%s@",pwd->pw_name);}void GetHostName(){char name[128]={0};gethostname(name,sizeof(name)-1);printf("%s",name);}void GetDir(){char pwd[128]={0};getcwd(pwd,sizeof(pwd)-1);int len=strlen(pwd);char* p=pwd+len;while(*p!='/'&&len--){p--;}p++;printf(" %s]&",p);}int main(){while(1){GetLoginName();GetHostName();GetDir();fflush(stdout);char line[1024];ssize_t _s=read(0,line,1024);char* myargv[10];char* start=line; myargv[0]=start;int i=1;if(_s>0){while(*start){if(isspace(*start)){while(isspace(*start)){*start='\0';start++;}myargv[i++]=start;}else{start++;}}}else{ continue;}myargv[i-1]=NULL;pid_t id=vfork();if(id==0){execvp(myargv[0],myargv);perror("error");}else{sleep(3);wait(NULL);}printf("\n");}运行结果
也可以直接将命令头输出,不用函数获取
#include<stdio.h>#include<unistd.h>#include<stdlib.h>#include<sys/types.h>#include<wait.h>#include<string.h>int main(){while(1){printf("[root@localhost 2.13]&");fflush(stdout);char line[1024];ssize_t _s=read(0,line,1024);char* myargv[10];char* start=line; myargv[0]=start;int i=1;if(_s>0){while(*start){if(isspace(*start)){while(isspace(*start)){*start='\0';start++;}myargv[i++]=start;}else{start++;}}}else{ continue;}myargv[i-1]=NULL;pid_t id=vfork();if(id==0){execvp(myargv[0],myargv);perror("error");}else{sleep(3);wait(NULL);}printf("\n");}return 0;}
0 0
- 【Linux】第一个简单shell
- Linux Shell的第一个小程序
- 【学习Linux】第一个shell脚本
- Linux shell - 1 第一个脚本
- 我的第一个linux shell脚本!!!
- Linux学习之第一个shell脚本
- linux之第一个shell脚本
- Linux Shell 之 我的第一个Shell程序
- Linux Shell 之 我的第一个Shell程序
- shell 第一个简单的脚本和变量
- linux之一个简单的shell程序
- 第一个shell
- 第一个shell程序
- 第一个shell脚本
- 第一个shell程序
- 第一个shell程序
- 第一个Shell
- 第一个Shell程序
- 和为S的两个数字
- Apache Mesos 学习
- [BZOJ4625][BeiJing2016]水晶 网络流
- Android中Log机制
- 支付宝支付即时到账接口在ThinkPHP商城中的应用
- 【Linux】第一个简单shell
- 在DragonBoard 410c上实现高并发处理TCP服务器
- 【笔记】SpringMVC系列框架 [ 2 ]
- 2. js中的 || 与 && 运算符
- 基于android的Socket通信
- javascript-正则表达式-支持正则的string方法
- linux下IPTABLES配置详解
- Ubuntu16 安装 caffe
- foreach循环