Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
539 views
in Technique[技术] by (71.8m points)

c - How to use execvp()

The user will read a line and i will retain the first word as a command for execvp.

Lets say he will type "cat file.txt" ... command will be cat . But i am not sure how to use this execvp(), i read some tutorials but still didn't get it.

#include <stdio.h>
#include <stdlib.h>

int main()
{
    char *buf;
    char command[32];
    char name[32];
    char *pointer;
    char line[80];
    printf(">");

    while((buf = readline(""))!=NULL){   
        if (strcmp(buf,"exit")==0)
        break;

        if(buf[0]!=NULL)
        add_history(buf);

        pointer = strtok(buf, " ");
        if(pointer != NULL){
            strcpy(command, pointer);
        }

        pid_t pid;

        int  status;

        if ((pid = fork()) < 0) {     
            printf("*** ERROR: forking child process failed
");
            exit(1);
        }
        else if (pid == 0) {          
            if (execvp(command, buf) < 0) {     
                printf("*** ERROR: exec failed
");
                exit(1);
            }
        }
        else                                  
        while (wait(&status) != pid)       
            ;
        free(buf);
        printf(">");
    }///end While
    return 0;
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The first argument is the file you wish to execute, and the second argument is an array of null-terminated strings that represent the appropriate arguments to the file as specified in the man page.

For example:

char *cmd = "ls";
char *argv[3];
argv[0] = "ls";
argv[1] = "-la";
argv[2] = NULL;

execvp(cmd, argv); //This will run "ls -la" as if it were a command

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...