Trying to use execvp () in C with user input in unix

I am trying to create a program that will ask the user for a command, and then use exec to execute this command.

For example, if they gave me "ls -la", I would have to run this command. I tried the following code:

#include <stdio.h>
#include <unistd.h>
#include <string.h>

int main()
{

    int ret, num_args;

    printf("Enter number of arguments (Example: \"ls -la\" has 1 argument): ");
    scanf("%d", &num_args);

    char *cmd[num_args];

    printf("Enter command name: ");
    scanf("%s", &cmd[0]);

    int i;
    for (i = 0; i < num_args; i++)
    {
            printf("Enter parameter: ");
            scanf("%s", &cmd[i]);
    }

    execvp(cmd[0], cmd);
}

However, when I tried the next run, it gave me a “segmentation error”

$ ./a.out 
Enter number of arguments (Example: "ls -la" has 1 argument): 2
Enter command name: ls
Enter parameter: -la
Enter parameter: .
Segmentation fault
$

Any ideas?

+3
source share
5 answers

, getline() scanf() fgets(). getline() NULL. . getline() , .

glibc getline() .

getline ( , , ):

#include <stdio.h>
#include <unistd.h>
#include <string.h>

int main()
{

    printf("Enter number of arguments (Example: \"ls -la\" has 1 argument): \n");

    char *num = NULL;
    size_t sz = 0;
    getline(&num, &sz, stdin);

    int num_args;
    sscanf(num, "%d", &num_args);

    char *cmd[num_args+2];
    memset(cmd, 0, sizeof(char*) * (num_args+2));

    printf("Enter command name: \n");


    int len = getline(&cmd[0], &sz, stdin); 

    cmd[0][len-1] = '\0';

    int i;
    for (i = 1; i < num_args+1; i++)
    {
        printf("Enter parameter: \n");
        sz = 0;
        len = getline(&cmd[i], &sz, stdin);
        cmd[i][len-1] = '\0';
    }

    return execvp(cmd[0], cmd);

}
+3

. num_args char:

char *cmd[num_args];

, num_args + 1 ( , cmd[0]). - :

const unsigned int MAX_LEN = 512; // Arbitrary number
char cmd[num_args + 1][MAX_LEN];

scanf , , . fgets, , :

fgets(cmd[i], MAX_LEN, stdin);

, fgets , ( , ).

+3

, argv, execvp, (char *)NULL, , .

+2

- , cmd.

+1

man scanf(). , , " ", , % as.

char *my_string;
scanf("%as", &my_string);

, .. () , .

-1

Source: https://habr.com/ru/post/1715850/


All Articles