简单实现自己的myshell
用到以下三个函数:
fork:pid_t fork(void);
int execvp(const char *file,char * const argv[]);
pid wait(int *status);进程等待
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<string.h>
#include<sys/wait.h>
char *argv[8];
int argc = 0;
void do_shell()
{
int statu;
pid_t pid = fork();
if(pid == -1){
perror("fork error\n");
exit(EXIT_FAILURE);
}
if(pid == 0){
execvp(argv[0],argv);
perror("execvp error\n");
}else{
pid_t ret = wait(&statu);
if(ret == -1){
perror("wait error");
exit(-1);
}
}
}
void do_parse(char *buf)
{
int i = 0 ;
int status = 0;
while(buf[i]){
if((!isspace(buf[i]))&&(status ==0) ){
argv[argc++] = &buf[i];
status = 1;
}else if(isspace(buf[i])&&(status == 1)){
status = 0;
buf[i] = '\0';
}
i++;
}
argv[argc++] = NULL;
}
int main()
{
char buf[1024] = {};
while(1){
printf("myshell>:");
scanf("%[^\n]%*c",buf);
do_parse(buf);
do_shell();
}
}