C - Using execvp with user input

时间秒杀一切 提交于 2019-12-12 02:48:25

问题


I'm currently trying to have my C program read Unix arguments from the user. I've so far searched this site but I haven't been able to figure out exactly what I'm doing wrong - though admittedly my pointer implementation skills are rather limited.

The following is how I have the code now; I've been messing around with the pointers with no luck. The errors are also saying that I need to use const *char, but I've seen in other examples the *char can be input by the user.

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>

main()
{
    char args[128];
    //User input
    printf("> ");
    fgets(args, 128, stdin);
    execvp(args[0], *args[0]);
}

The error I get is as follows:

smallshellfile.c: In function ‘main’:
smallshellfile.c:13:21: error: invalid type argument of unary ‘*’ (have ‘int’)
smallshellfile.c:13:5: warning: passing argument 1 of ‘execvp’ makes pointer from integer without a cast [enabled by default]
/usr/include/unistd.h:575:12: note: expected ‘const char *’ but argument is of type ‘char’

Does anyone know what the problem may be?


回答1:


You have several problems:

  1. *args[0] is meaningless. args is array. args[0] is char. what is *args[0]?

  2. You have to create a NULL-terminated array of char*, to pass as 2nd argument.

  3. args[0] is the first char in args. you should pass the whole string (just args), not only its first char.

Try something like:

char *argv[]={args,NULL};
execvp(args,argv);



回答2:


This might work better for you:

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

int main(void)
{
    char args[128];
    char *argv[] = { "sh", "-c", args, 0 };
    printf("> ");
    if (fgets(args, 128, stdin) != 0)
    {
        execvp(argv[0], argv);
        fprintf(stderr, "Failed to exec shell on %s", args);
        return 1;
    }
    return 0;
}

It has the minimum necessary headers; it has a correctly declared main() - C99 requires an explicit return type; it runs the shell on the information the user types in. The error message is correctly terminated with a newline unless the user typed more than 126 characters before hitting hitting return. If execvp() or any of the exec*() functions returns, it failed; you don't need to test its status.

I'm cheating phenomenally by making the shell do the real work. But you may end up wanting to split what the user typed into words, so that the command is first and there are multiple arguments. You'd then allocated a bigger argv array, and parse the string, putting each separate argument into its own entry in argv and then using execvp() begins to make sense. Note that if there is I/O redirection to be done, then it is your shell that will have to do it (unless you run the real shell to do it for you - like I did).



来源:https://stackoverflow.com/questions/9269927/c-using-execvp-with-user-input

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!