使用任意一个exec家族函数设计一个自己的终端解释器,可以完成
类似常规bash的效果。比如
myconsole>>ls
…
myconsole>>ps
…
myconsole>>exit 终端退出。。。
myconsole>>xxx
不可识别的命令
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>
int mystytem(int argc, char *argv[])
{
char *n;
char s[64];
gets(s);
int i=0;
char * arg[64];
n = strtok(s, " ");
while (n) {
arg[i]=n;
i++;
n = strtok(NULL, " ");}
arg[i]=NULL;
pid_t pid = fork();
if(pid < 0)
{
perror("fork error");
return -1;
}
else if(pid == 0)
{
int ret=execvp(arg[0],arg);
exit(ret);
fflush(arg[0]);
}
int status = 0;
wait(&status);
if(status != 0)
printf("不可识别的命令\n");
if(!strcmp(arg[0],"exit"))
{
exit(0);
}
else
{
wait(NULL);
}
return 0;
}
int main(int argc, char *argv[])
{
while(1)
{
setvbuf(stdout, NULL, _IONBF, 0);
printf("myconsole >> ");
mystytem(argc,argv);
}
return 0;
}