SittingBull SittingBull - 4 months ago 12
Bash Question

I want my simple shell program do basic unix commands

I wrote a simple shell program in c.The program gets hostname and also exits if I type exit.However, I also want my shell program to do exact command operations like

ls
,
ls -a
,
echo
etc.I'm writing the relative portion of the program below:

if ( strlen(command) == 4 &&strncmp("exit", command, 4) == 0 ){
exit(0);
}

else{

argv = getoptions(command);

if(fork()== 0){
execvp(argv[0],argv);

}
else {
wait(NULL);
}


Here,
getoptions()
is a char** function that I wrote in a different class.This function takes a command string and spits out each token of the string.How do I test each token for, say
ls
command and do exactly what ls does on shell?

Answer

The shell can either use the system call, but that is not always possible, so you can use exec and pass you command to exec and the operating system will execute the program.

#include <unistd.h>
int main(int argc, char **argv) {
    /* The most basic example */
    char *execArgs[] = { "ls", "-al", 0 };
    execvp("ls", execArgs);
    return(0);
}

The important thing to understand is that you must use a char * array as a parameter to exec. You can also make a pipeline, but then you need to study some more.