现在的位置: 首页 > 综合 > 正文

简单的Shell

2013年07月27日 ⁄ 综合 ⁄ 共 629字 ⁄ 字号 评论关闭
#include<string.h>
#include<stdio.h>
#include<unistd.h>
#include<sys/wait.h>
#define M_C_L 256
#define M_A_N 20
int main()
{
    char command[M_C_L];
    char *token[M_A_N];
    char *cur=NULL;
    char * const delim=" ";
    int i,status;
    pid_t pid;
    while(1)
    {
        //循环初始化
        i=0;
        memset(command,0,sizeof(command));
        memset(token,0,sizeof(token));
        //输出提示符
        printf(">>>");
        //读入一行并解析成参数表
        fgets(command,sizeof(command),stdin);
        command[strlen(command)-1]=0;
        cur=command;
        while (token[i] = strsep(&cur,delim)) {
            puts(token[i]);
            i++;
         }
        //exec调用
        pid=fork();
        if(pid==0)
        {
            if(token[1]==0)
                execlp(token[0],token[0],(char*)0);
            else
                execvp(token[0],token+1);
        }
        if ((pid = waitpid(pid, &status, 0)) < 0)
			puts("waitpid error");
    }
    return 0;
}

抱歉!评论已关闭.