Hoe execvp() te gebruiken

De gebruiker leest een regel en ik bewaar het eerste woord als een commando voor execvp.

Laten we zeggen dat hij “cat file.txt”zal typen … commando zal cat zijn. Maar ik weet niet zeker hoe ik deze execvp()moet gebruiken, ik heb enkele tutorials gelezen maar snap het nog steeds niet.

#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;
}

Antwoord 1, autoriteit 100%

Het eerste argument is het bestand dat u wilt uitvoeren, en het tweede argument is een array van null-terminated strings die de juiste argumenten voor het bestand vertegenwoordigen zoals gespecificeerd in de man-pagina.

Bijvoorbeeld:

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

Antwoord 2

In cpp moet u speciale aandacht besteden aan stringtypes wanneer u execvpgebruikt:

#include <iostream>
#include <string>
#include <cstring>
#include <stdio.h>
#include <unistd.h>
using namespace std;
const size_t MAX_ARGC = 15; // 1 command + # of arguments
char* argv[MAX_ARGC + 1]; // Needs +1 because of the null terminator at the end
// c_str() converts string to const char*, strdup converts const char* to char*
argv[0] = strdup(command.c_str());
// start filling up the arguments after the first command
size_t arg_i = 1;
while (cin && arg_i < MAX_ARGC) {
    string arg;
    cin >> arg;
    if (arg.empty()) {
        argv[arg_i] = nullptr;
        break;
    } else {
        argv[arg_i] = strdup(arg.c_str());
    }
    ++arg_i;
}
// Run the command with arguments
if (execvp(command.c_str(), argv) == -1) {
    // Print error if command not found
    cerr << "command '" << command << "' not found\n";
}

Referentie:
execlp、execvp用法與範例

Other episodes