自己写shell第二天, 增加回显和显示当前路径以及当前用户
1. 使用fgets来获取当前命令
2. 使用getcwd API来获取当前路径
3. 使用getlogin_r来获取当前用户
效果:

/** * jsh 程序,简单的shell程序 * * created : jeff * date: 2013.1.28 * version: first version * * modified: jeff * date : 2013.1.29 * version : v1.0 * reason : 增加回显功能和显示用户以及当前目录的能力 * * * *********************************************/#include <stdio.h>#include <unistd.h>#include <stdlib.h>#include <getopt.h>#define VERSION \ "jsh version 1.0.0\n"\#define MAX_PATH_LENGTH 1024#define MAX_COMMAND_LENGTH 1024#define MAX_USER_LENGTH 128#define USAGE\ "Usage: jsh [GNU long option] [option] ...\n\ jsh [GNU long option] [option] script-file ...\n\ long option:\n\ --version\n\ --help\n"\static struct option longOptions[]={ {"version", 0, NULL,'v' }, {"help", 0, NULL, 'h'}};static char user[MAX_USER_LENGTH]={0,};static char currentWorkPath[MAX_PATH_LENGTH]={0,};static char command[MAX_COMMAND_LENGTH]={0,};static void usage();static void version();static void readopt(int argc, char** argv);int main(int argc, char** argv){ int opt = 0; char* path = NULL; int getuserret = 0; if(argc<2) { while(1) { /** *显示当前目录和用户 */ if((path=getcwd(currentWorkPath, sizeof(currentWorkPath))) == NULL) break; if( getuserret = getlogin_r(user, sizeof(user)) !=0) break; fprintf(stdout, "%s:%s$ ", user, currentWorkPath); if(fgets(command, sizeof(command), stdin)) { /** * * TODO do command stuff * */ }else { break; } } }else{ readopt(argc, argv); } return 0;}static void usage(){ fprintf(stdout, USAGE);}static void version(){ fprintf(stdout, VERSION);}static void readopt(int argc, char** argv){ int opt=0;while( (opt=getopt_long(argc,argv,"vh",longOptions, NULL)) !=EOF) { switch(opt) { case 'h': usage(); break; case 'v': version(); break; default: usage(); break; } }}