简单的shell程序

/*************************************************************************
    > File Name: myshell.c
    > Author: 
    > Mail: 
    > Created Time: 2017年02月22日 星期三 19时34分38秒
 ************************************************************************/

#include<stdio.h>
#include<pwd.h>
#include<unistd.h>
#include<sys/wait.h>
#include<stdlib.h>
#include<ctype.h>
#define INFO_BUFFER_SIZE 256
int main()
{
    int count = 1;
    while(1)
    {
        struct passwd *pwd;
        pwd = getpwuid(getuid());//获取当前用户名

        //获取当前主机名
        char infoBuf[INFO_BUFFER_SIZE];
        gethostname(infoBuf,INFO_BUFFER_SIZE);

        //获取当前路径
        char _pwd[INFO_BUFFER_SIZE]; 
        getcwd(_pwd,sizeof(_pwd));

        printf("%s@%s:%s $ ",pwd->pw_name,infoBuf,_pwd);
        fflush(stdout);

        char cmd[128];
        size_t _s = read(0,cmd,sizeof(cmd)-1);

        if(_s > 0) //read success,_s is read number
        {
            cmd[_s-1] = '\0';
        }else if(_s <= 0){
            perror("read");
            return 1;
        }

        char* _argv[32];//save cmd
        _argv[0] = cmd;
        char* start = cmd;// pointer is a falg
        int i = 1;
        while(*start)
        {
            if(isspace(*start)){
                *start = '\0';
                start++;
                _argv[i] = start;
                i++;
                continue;
            }
            start++;
        }

        _argv[i] = NULL;
        pid_t id =fork();
        if(id < 0){
            perror("fork");
        }
        else if(id == 0){
            //child
            execvp(_argv[0],_argv);
            exit(1);
        }
        else if(id > 0){
            //father
            int status = 0;
            pid_t ret = waitpid(id,&status,0);
            if(WIFEXITED(status)&&ret == id)
            ;
            // printf("wait success\n");
            else{
                printf("wait child failed\n");
                return 1;
            }
        }


    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值