加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

【进程控制下】实现一个简易的shell

发布时间:2020-12-15 19:31:39 所属栏目:安全 来源:网络整理
导读:1.shell原理 运用程序替换的原理来实现的,shell自己就是一个进程。 1 .获取命令行 2 .解析命令行 3 .创建子进程( fork ) 4 .替换子进程( exec ) 5 .父进程等待子进程退出( wait ) 2.shell #include unistd.h #include sys/wait.h #include stdio.h #inclu

1.shell原理
运用程序替换的原理来实现的,shell自己就是一个进程。

1.获取命令行
2.解析命令行
3.创建子进程(fork)
4.替换子进程(exec5.父进程等待子进程退出(wait)

2.shell

#include <unistd.h> 
#include <sys/wait.h> 
#include <stdio.h> 
#include <stdlib.h> 
#include <string.h>

char *argv[8]; 
int argc = 0;

void do_parse(char *buf)  //解析
{
    int i;
    int status = 0;
    for (argc=i=0; buf[i]; i++ ) 
    {
        if ( !isspace(buf[i]) &&status == 0 )
        { 
            argv[argc++] = buf+i;  //将输入的命令存入数组
            status = 1;
        } else if ( isspace(buf[i]) ) 
        { 
            status = 0;
            buf[i] = 0;
        }
    }   
    argv[argc] = NULL;
}

void do_execute( void )  //替换
{
    pid_t pid = fork();
    switch( pid ) 
    { 
        case -1: 
        perror("fork");  //创建进程失败
        break;
        case 0:   //子进程
        execvp(argv[0],argv);  //替换子进程
        perror("execvp");
        exit(EXIT_FAILURE); 
        default:  //父进程
        {
            int st;
            while ( wait(&st) != pid )  //成功返回被等待进程pid,失败返回-1。
                ;   
        }
    }
}

int main( void )
{
    char buf[1024] = {}; 
    while ( 1 ){
    printf("myshell@host: "); 
    scanf("%[^n]%*c",buf); 
    //%[^n] 读入任意多的字符,直到遇到"n"停止
    do_parse(buf); 
    do_execute();
    }
    return 0;
}

实现效果:

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读