Program that creates a shell and executes some shell commands

720 Words3 Pages
/* myshell.c

Description: Program that creates a shell and executes some shell commands

*/

#include

#include

#include

#include

#include

#include

#include

extern char **getln();

// Function used to check the file input direction command

int inputFile(char **args, char **fileIn) {

int i,j;

//go thorough the command line arguments

for(i=0;args[i] != NULL;i++) {

// check for the input direction symbol

if(args[i][0] == '<') {

// save the filename command

if(args[i+1] != NULL) {

*fileIn = args[i+1];

}

/*for(j=i;args[j-1] != NULL;j++) {

args[j] = args[j+2];

}*/

return 1;

}

}

return 0;

}

// Function used to check the file output direction command

int outputFile(char **args, char **fileOut) {

int i,j;

// go thorough the command line arguments

for(i=0;args[i] != NULL;i++) {

// Look for the output direction symbol

if(args[i][0] == '>') {

// save the filename command

if(args[i+1] != NULL) {

*fileOut = args[i+1];

}

/*for(j=i;args[j-1] != NULL; j++) {

args[j] = args[j+2];

}*/

return 1;

}

}

return 0;

}

// The main function of the program responsible for creating the shell

main() {

// all the variables used in the programs functionality

int i;

char **args;

int status;

pid_t child;

int checkInput;

int checkOutput;

int flag =0;

char *fileOut;

char *fileIn;

int sum=0;

int num;

long convert;

int j;

int count=0;

int k;

int counter;

int checkProduct;

while(1) {

sum =0;

int argCount = 0;

args = get...

... middle of paper ...

... checkInput = inputFile(args, &fileIn);

checkOutput = outputFile(args, &fileOut);

// fork a new process for commands on the command line argument

child = fork();

if(child >= 0) {

if(child == 0) {

// check if there is any file input redirection command and execute it

if(checkInput == 1) {

freopen(fileIn, "r", stdin);

}

// check if there is any file output redirection command and execute it

if(checkOutput == 1) {

freopen(fileOut, "w+", stdout);

}

execvp(args[0],args);

exit(0);

}

// wait for the child process to stop executing

else {

// check if there is an ampersend for background processing, if it is then dont wait

if(flag == 0) {

wait(&status);

}

}

}

else {

printf("Fork failed, the shell is exiting...
");

return 1;

}

}

}

More about Program that creates a shell and executes some shell commands

Open Document