gpt4 book ai didi

c - execv 函数调用的参数无效

转载 作者:太空宇宙 更新时间:2023-11-04 08:28:12 25 4
gpt4 key购买 nike

程序应该做什么的例子:

./executable ls -l

应该做同样的事

ls -l

所以基本上它是一个无用的 shell 命令解释器。

我创建了一个包含/bin/commandname 的字符串fullpath 和一个二维数组arguments,它基本上是 argv 但没有前两个条目(executablecommandname)。

对于 ./executable ls -l 示例,它实际上返回以下内容:

full path: /bin/ls
Argument 0: -l

这是正确的,但是 execv 实际上什么也没做。

我该如何解决这个问题?

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

int main(int argc, char** argv){

char path[6] = "/bin/";
char* fullpath = (char*)malloc(strlen(path)+strlen(argv[1]));
strcat(fullpath, path);
strcat(fullpath, argv[1]);
printf("full path: %s\n", fullpath);

char *arguments[argc-1];
int i;
for(i=0; i<argc-2; i++){
arguments[i] = (char*)malloc(strlen(argv[i+2]));
strcpy(arguments[i], argv[i+2]);
printf("Argument %d: %s\n", i, argv[i+2]);
}

execv("/bin/ls", arguments);

return 0;
}

最佳答案

当我们修改以下行时,您的程序似乎可以正常运行:

char *arguments[argc-1];

你的 char ** 参数必须像这一行:

char *arguments[] = { "/bin/ls", "-l", NULL };

换句话说,不要忘记先指明命令;并确保将 NULL 放在字符 ** 的末尾。

祝你好运! ;)

关于c - execv 函数调用的参数无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29461881/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com