linux c语言实现 执行shell命令

// 可以在一行输入命令

#include <stdio.h>

#include <string.h>
#include <stdlib.h>
#include <ctype.h>
#include <signal.h>

#define STRLEN 50
#define ARGNUM 20

char** Split(char *str){                                        // 拆分字符串,将输入的字符串拆分成一个一个单词
    int szLen = strlen(str);
    int ipos = 0,i = 0, wordlen;
    int argnum = 0;
    char wordBuf[STRLEN+1];
    char **argbuf = (char**)calloc(sizeof(char*),ARGNUM);
    

    while(isspace(str[ipos])) ipos++;
    
    i = 0,wordlen = 0;
    for(i=ipos; i<szLen; i++){
        if(isspace(str[i])){
                if(wordlen>0){
                    wordBuf[wordlen]='\0';
                    argbuf[argnum]=(char*)calloc(sizeof(char),strlen(wordBuf)+1);
                    strcpy(argbuf[argnum],wordBuf);
                    argnum++;
                }
                wordlen = 0;
                continue;
        }    
        else if(isprint(str[i])){
            wordBuf[wordlen]=str[i];
            wordlen++;
        }
    }
    return argbuf;
}

void execute(char **arglist){                                      // 处理命令
    int pid = fork();
    int status;
    switch(pid){
    case -1:perror("fork fail");
        exit(1);
    case  0:execvp(arglist[0],arglist);
        perror("execvp fail");
        exit(1);
    default:while(wait(&status) != pid) ;
        printf("child exited with state %d,%d\n",status>>8,status&0733);
        break;
    }
}
int getlistlen(char **arglist){                                       // 获取命令长度,作为结束的标志
    int len = 0;
    for(len=0;;len++)
        if(arglist[len] == NULL) break;
    return len;
}

void setup(){
    signal(SIGINT,SIG_IGN);
    signal(SIGQUIT,SIG_IGN);
}

int main(){
    while(1){
    setup();
    char strbuf[STRLEN+1];
    char **arglist = (char**)calloc(sizeof(char*),ARGNUM);
    int  arglen = 0;
    printf("input a your operate in one line:\n");
    fgets(strbuf,STRLEN,stdin);
    fflush(stdin);
    arglist = Split(strbuf);
    arglen  = getlistlen(arglist);
    if(arglen)
        execute(arglist);
    else break;
    printf("\n");
    }
    return 0;
}

// 没有完成: 让shell不被用户按下的中断或退出键杀死!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值