Skip to content
Advertisement

Using Fork for Command Line Arguements

I’m trying to execute the command “ls -l” but I’m not exactly sure how to approach it.

This is what I’ve tried:

int main(void) {
    char * input;
    char * args[2];
    char buff[100];

    input = malloc(sizeof(buff));

while(fgets(input,sizeof(input),stdin) != NULL) {

    printf("Enter a commandn");

    if(strcmp(input,"ls -ln") ==0) {
        pid_t childPid;

        childPid = fork();

        if(childPid == 0) {
            args[0] = "/bin/ls -l";
            args[1] = NULL;

            execv(args[0],args);
    }

}

}

free(input);
}

However, the command doesn’t seem to work here. It works if I just simply use “ls” but I want to use “ls -l” is there another argument I have to pass to get this to work?

Advertisement

Answer

First you have to understand this simple example.

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/wait.h>

int main() {

    /* status of child execution */
    int status;
    /* pointer * to array of char*(strings)*/
    char ** args;

    /* allocate memory for three char*(stings) */
    args = (char**) malloc( 3 * sizeof(char*) );

    /* fork program and store each fork id */
    pid_t childPid = fork();

    /* if this is child process */
    if(childPid == 0) {

        args[0] = "ls";
        args[1] = "-l";
        args[2] = NULL;

        /* execute args[0] command with args arguments */
        execvp(args[0],args);

        /* send execution code 0 to parent and terminate child */
        exit(0);

    } else {

        /* wait execution code from child*/
        wait(&status);

        /* free allocated space */
        free(input);
        free(args);

        /* exit program with received code from child */
        exit(status);
    }

}

I commented every line, but tell me if you want more informations. You have to understand how to execute commands from child and inform parent before continue to user’s input commands.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement