72f8ba24304c4648c18e11f0aa2287f2

This is 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]);
		}
	}
	
}

Refactorings

No refactoring yet !

F1e3ab214a976a39cfd713bc93deb10f

Tj Holowaychuk

March 31, 2009, March 31, 2009 15:46, permalink

No rating. Login to rate!

Im not pro at C so I cant help much, some style changes I find help the readability though.

#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]);
    }
  }
  
}

Your refactoring





Format Copy from initial code

or Cancel