0

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?

4

2 回答 2

2

你有几个问题:

  1. *args[0]是没有意义的。args是数组。args[0]是字符。什么是*args[0]

  2. 您必须创建一个以 NULL 结尾的数组char*,作为第二个参数传递。

  3. args[0]是 中的第一个字符args。你应该传递整个字符串(只是args),而不仅仅是它的第一个字符。

尝试类似:

char *argv[]={args,NULL};
execvp(args,argv);
于 2012-02-14T00:11:26.523 回答
0

这可能对您更有效:

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

它具有最少的必要标题;它有一个正确声明main()的——C99 需要一个显式的返回类型;它根据用户输入的信息运行 shell。错误消息正确地以换行符终止,除非用户在点击返回之前输入了超过 126 个字符。如果execvp()或任何exec*()函数返回,则失败;你不需要测试它的状态。

通过让 shell 完成真正的工作,我在作弊。但是您最终可能希望将用户输入的内容拆分为单词,以便命令位于首位并且有多个参数。然后,您分配了一个更大的argv数组,并解析字符串,将每个单独的参数放入其自己的条目中argv,然后使用execvp()开始有意义。请注意,如果要完成 I/O 重定向,那么必须由您的 shell 执行此操作(除非您运行真正的 shell 来为您执行此操作 - 就像我所做的那样)。

于 2012-02-14T00:26:32.493 回答