Question

I'm making a basic shell, it is working fine, but there is one problem. Currently if I provide args such as

cat testtextfile

the execvp command works fine. However if I provide something like

cat hello\ world

ie. a file with a whitespace in the name, the command will not work. How do I get execvp to understand args of this kind.

The following is an extract of my code, that does work if I change args3[1] to something like "-n":

char *args3[3];

args3[0] = "cat";
args3[1] = "hello\\ world";
args3[2] = NULL;

if ((child = fork()) == 0) { //child
    printf("pid of child = %ld\n", (long) getpid());
    execvp(args3[0], args3); //arg[0] is the command

    fprintf(stderr, "execvp failed \n");
    exit(1);
} else { //parent

    if (child == (pid_t)(-1)) {
        fprintf(stderr, "fork failed.\n"); exit(1);
    } else {

        if (doNotWait == 0){
            c = wait(&cstatus); //wait for child
            printf("child %ld exited with status = %d\n",
            (long) c, cstatus);
        } else {
            printf("not waiting for child process\n");
        }
    }

}
return 0;
Was it helpful?

Solution

args3[1] = "hello\\ world";

should be

args3[1] = "hello world";

In the command cat hello\ world, you need to escape the space between "hello" and "word" because you do not want shell to treat "hello world" as two words, therefore after shell processed the command line arguments properly, the first argument to cat should be hello world, not hello\ world.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top