自己实现简单shell的小例子

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h> //execve()
#include <sys/types.h> //pid_t
#include <sys/wait.h> //waitpid()

int main()
{
    int i, j, l, status;
    pid_t p;
    char *command;
    char **argv;
    command = (char *)malloc(sizeof(char)*30);
    argv = (char **)malloc(sizeof(char *)*30);

    while(1)
    {
        printf("myshell>"); // 输出命令提示符
        memset(command, 0, sizeof(char)*30);
        if(fgets(command, 30, stdin) == NULL) // 读命令
            continue;
        l = strlen(command) - 1;
        if(command[l] == '\n')
            command[l] = 0;
        //将读取的一行字符解析到argv中
        j = 0;
        argv[j] = command;
        j++;

        l = strlen(command);
        for(i=0; i<l; i++)
        {
            if(command[i] == ' ')
            {
                command[i] = 0;
                if(command[i+1] != ' ')
                {
                    argv[j] = &command[i+1];
                    j++;
                }
            }
        }
        argv[j] = NULL;

        //创建进程执行命令
        p = fork();
        if(p != 0) // 父进程
        {
            waitpid(-1, &status, 0);
        }
        else // 子进程
        {
            execve(argv[0], argv, NULL);
        }
    }

    free(argv);
    free(command);
    return 0;
}

waitpid()函数解释
参数一:
小于-1表示等待进程组识别码为其绝对值的任何子进程。
等于-1表示等待任何子进程,相当于 wait()。
等于0表示等待进程组识别码与目前进程相同的任何子进程。
大于0表示等待任何子进程识别码为pid的子进程。
参数二:
子进程的结束状态值,如果不在意结束状态值,则
参数 status 可以设成 NULL。
参数三:
参数options提供了一些额外的选项来控制waitpid,如果我们不想使用它们,也可以把options设为0。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值