execvp didn't pass args to called program

I want to load a new program by fork and exec, and pass args to the new program. But I was failed.

//fork_exec.c
int main()
{
    char *args[] = {"/home"};
    pid_t pid = fork();
    switch(pid)
    {
    case -1:
        return;
    case 0://child
        execvp("ls",args);
        _exit(1);
    default://parent
        return;
    }
}

I compile the file fork_exec.c then get a file a.out. Then I type

./a.out

in the terminate.I suggested that a list of files in the /home will be shown on the screen. But the shown files war fork_exec.c and a.out in fact. So I guess that the args was not passed to the ls program successfully. Please someone tell me what happened and why. Thanks.

Upvotes: 0

Views: 75

Answers (1)

Jeegar Patel
Jeegar Patel

Reputation: 27210

int main()
{
    char * args[] = {"ls","/home/",NULL};
    pid_t pid = fork();
    switch(pid)
    {
    case -1:
        return;
    case 0://child
        execvp(args[0],args);
        _exit(1);
    default://parent
        return;
    }
}

This works. Try out and read its MAN page.

Upvotes: 4

Related Questions