SittingBull SittingBull - 1 year ago 70
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 -a
etc.I'm writing the relative portion of the program below:

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


argv = getoptions(command);

if(fork()== 0){

else {

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
command and do exactly what ls does on shell?

Answer Source

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);

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download