/* a simple shell */
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <string.h>
#include <errno.h>
#define SHELL_NAME "sh1"
#define PROMPT_ENVIRONMENT_VARIABLE "PROMPT"
char *prompt;
int main(int argc,char **argv)
{
char cmd[80];
int statval;
/*Dtermine prompt value.*/
if((prompt=getenv(PROMPT_ENVIRONMENT_VARIABLE))==NULL)
prompt=SHELL_NAME":";
/*Process commands until exit,or death by signal.*/
while(1) {
/*Prompt and read a command.*/
printf(prompt);
gets(cmd);
/*Process built-in commands.*/
if(strcasecmp(cmd,"exit")==0)
break;
/*Process non-built-in commands.*/
if(fork()==0) {
execlp(cmd,cmd,NULL);
fprintf(stderr,"%s:Exec%sfailed:%s\n",argv[0],cmd,strerror(errno));
exit(1);
}
wait(&statval);
if(WIFEXITED(statval)) {
if(WEXITSTATUS(statval)) {
fprintf(stderr,"%s:child exited with status %d.\n",argv[0],WEXITSTATUS(statval));
}
}
else {
fprintf(stderr,"%s:child died unexpectedly.\n",argv[0]);
}
}
}
My friend help me modify it, as follows:
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <string.h>
#include <errno.h>
#define SHELL_NAME "sh1"
#define SHELL_GETS(var) printf(prompt); gets(var)
#define SHELL_CMD(str) strcasecmp(cmd, str) == 0
char *prompt;
int main(int argc,char **argv)
{
char cmd[80];
int statval;
if(!(prompt = getenv("PROMPT")))
prompt = SHELL_NAME ": ";
while(1) {
SHELL_GETS(cmd);
if (SHELL_CMD("exit"))
break;
if (fork() == 0) {
execlp(cmd, cmd, NULL);
fprintf(stderr, "%s:Exec %sfailed:%s\n", argv[0], cmd, strerror(errno));
exit(1);
}
wait(&statval);
if (WIFEXITED(statval)) {
if (WEXITSTATUS(statval)) {
fprintf(stderr, "%s:child exited with status %d.\n", argv[0], WEXITSTATUS(statval));
}
}
else {
fprintf(stderr, "%s:child died unexpectedly.\n", argv[0]);
}
}
}