如何使用execvp()

问题描述 投票:12回答:1

用户将读取一行,我将保留第一个单词作为execvp的命令。

让我们说他会输入“cat file.txt”...命令将是cat。但我不知道如何使用这个execvp(),我读了一些教程,但仍然没有得到它。

#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\n");
            exit(1);
        }
        else if (pid == 0) {          
            if (execvp(command, buf) < 0) {     
                printf("*** ERROR: exec failed\n");
                exit(1);
            }
        }
        else                                  
        while (wait(&status) != pid)       
            ;
        free(buf);
        printf(">");
    }///end While
    return 0;
}
c shell fork execvp
1个回答
31
投票

第一个参数是您要执行的文件,第二个参数是一个以空字符结尾的字符串数组,表示the man page中指定的文件的相应参数。

例如:

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
© www.soinside.com 2019 - 2024. All rights reserved.