快速用C寫一個(gè)簡(jiǎn)單的Shell
前言
??? 之所以會(huì)寫這篇文章,主要是因?yàn)槲蚁氲轿易铋_(kāi)始寫shell來(lái)練手的時(shí)候,查了許多資料,他們的實(shí)現(xiàn)都太復(fù)雜,所以實(shí)現(xiàn)一個(gè)簡(jiǎn)易的shell給需要的人做示例(注:本人還在讀高中,C是自學(xué)的,寫的不好請(qǐng)見(jiàn)諒?。?br>
需了解的函數(shù)
先來(lái)看主要用到的三個(gè)函數(shù),strtok用來(lái)分割字符,readline用來(lái)處理用戶輸入,execvp(execve的變種,自己找PATH去啟動(dòng)程序),提供這些函數(shù)頭文件分別為string.h,
readline.h , unistd.h
extern char *strtok (char *__restrict __s, const char *__restrict __delim)
extern char *readline PARAMS((const char *))
extern int execvp (const char *__file, char *const __argv[])
怎么實(shí)現(xiàn)
??? 聲明一個(gè)char類型的數(shù)組,調(diào)用readline()獲得用戶輸入存儲(chǔ)在該數(shù)組,再調(diào)用strtok()使指針數(shù)組指向該數(shù)組,然后fork出一個(gè)子進(jìn)程,在子進(jìn)程下調(diào)用execvp()函數(shù)
源碼
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <readline/readline.h>
#include <wait.h>
#include <sys/types.h>
char *argv[] = {NULL};
void input_strtok(char *input)
{
??? argv[0] = strtok(input," ");
??? short i = 0;
??? while(argv[i] != NULL)
?? ??? ?argv[++i] = strtok(NULL," ");
}
int exec_cmd(char *argv[])
{
??? pid_t pidN = fork();
??? if(pidN < 0) {
??? fprintf(stderr,"Error in fork");
??? return -1;
??? }
??? else if(pidN == 0) {
??? if(execvp(argv[0],argv) < 0)
??????? fprintf(stderr, "myshell?: command : %s : could not found\n", argv[0]);
??? exit(0);
??? } else {
??? ??? wait(NULL);
??? }
??? return 0;
}
int main()
{
??? char display_readline[13];
??? sprintf(display_readline,"%s","myshell >>> ");
??? while (1) {
?? ?char *input = malloc(sizeof(char)*1024);
??? memset(input,0x00,1024); //初始化數(shù)組
?? ?input = readline(display_readline); //獲得用戶輸入
?? ?if(strcmp(input,"exit") == 0)
?? ???? exit(0);
?? ?input_strtok(input); //分割字符串
?? ?exec_cmd(argv); //fork出一個(gè)子進(jìn)程然后運(yùn)行程序
?? ?free(input);
??? }
}
后記
????雖然代碼經(jīng)過(guò)測(cè)試,但仍有許多不足,懇請(qǐng)大佬們指出