我的程序应该打印出一个提示:myshell>当它准备好接受输入时。它必须读取一行输入,接受几个可能的命令。这是一个非常简单的shell,因此它只接受两个命令:run和exit。
#include<stdio.h>
#include<string.h>
#include <sys/types.h>
#include <errno.h>
#include <stdio.h>
#include <sys/wait.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
int h=0;
void keep(int sig){
h=1;
}
int main()
{
signal(SIGINT,keep);//gets into the interrupt
while(1)
{
printf("myshell>");
char line[255];
fgets(line, 255, stdin);
if(!strcmp(line,"\n")){//checks if the given line is not empty
continue;
}
if(h)
{
h=0;
continue;
}
int g = 0;
char *words[5];
words[g] = strtok(line," \n");//Tokenize the given line
while (words[g]!=NULL)//splitting the tokens
{
g++;
words[g] = strtok(NULL," \n");
}
if(strcmp(words[0],"run")==0)
{
int status;
printf("myshell:Started child pid %d \n",getpid());
pid_t result = fork();
printf("myshell:Started child pid %d \n",getpid());
if(result>0)
{
wait(&status);//gets into the wait state
}
else if (result == 0)//new child process created
{
char *args[3];
int k=0;
while(k<4)//take the whole string into array and execute
{
args[k] = words[k+1];
k++;
}
int output;
output = execvp(*args,args);
if(output==-1)
{
printf("myshell: could not find the program %s\n",words[1]);
}
}
}
else if(strcmp(words[0],"exit")==0)//comparing with the exit
{
exit(1);
}
else
{
printf("myshell: %s is not a valid command\n",words[0]);
}
}
return 0;
}
它适用于
./myshell
myshell> run ls
myshell: started child pid 7973
myshell myshell.c
我的shell应该支持使用;使用单个命令执行多个程序。为简单起见,我们假设在;之前和之后有一个空格。例如:
./myshell
myshell> run ls -l ; date ; who
但这不适用于此代码。