c - 如何在 C 中将 execv 与生成的路径一起使用?
问题描述
我有一个任务,我们必须创建一个外壳。其中一部分包括使用生成不同 unix 命令的路径。(例如:/bash/ls)。使用 execv,如果我硬编码路径,我可以让一切正常工作,但如果我生成它,则不能。
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sys/syscall.h>
#include <unistd.h>
void command(char *args[]);
int main (int argc, char **argv) {
//get the command and arguments
char buffer[32];
char *b = buffer;
size_t bufferSize = 32;
int counter = 0;
char *tokens[10];
char *delims = " \t\n";
printf("dash> ");
getline(&b, &bufferSize, stdin);
tokens[0] = strtok(buffer, delims);
while (tokens[counter] != NULL) {
counter++;
tokens[counter] = strtok(NULL, delims);
}
command(tokens);
}
void command(char *args[]) {
//create path
char *path = NULL;
int length = strlen(args[0]);
path = malloc(5 + length + 1);
strcat(path, "/bin/");
strcat(path, args[0]);
char *input[2];
input[0] = malloc(512);
strcpy(input[0], path);
printf(input[0]); //the path prints out properly
//input[0] = "/bin/ls"; <--- this works!
input[1] = NULL;
//start execv
pid_t pid;
pid = fork();
if(pid < 0) {
printf("ERROR: fork failed.");
exit(0);
}
else if (pid == 0) {
execv(input[0], input);
printf("error.");
}
free(path);
free(input[0]);
}
有人有想法么?我很确定这是 malloc 的问题,但我不知道如何规避它。
解决方案
getline()
既然你正在阅读表格stdin
,这个问题
getline(&b, &bufferSize, stdin);
当你传递给函数时,\n
在 & 末尾存储新行字符,而不是这就是失败的原因buffer
tokens
command()
args
ls\n
ls
execv
execv:没有这样的文件或目录
所以删除那个额外的\n
字符以正确解析tokens
,例如
ssize_t read;
read = getline(&b, &bufferSize, stdin); /* always check the return value */
if(read != -1 ) {
b[read-1] = '\0'; /* replace \n with \0 */
}
推荐阅读
- sql-server - 在两个不同的服务器中处理并发事务
- javascript - 如何验证 ]0,100000 形式的数字范围
- java - 持久化时引用没有外键的静态表
- memory - 双端口存储器
- excel - 用户窗体内的进度条
- c# - 使用 C# 在 Word Doc 中更改绝对图片大小
- sql - 前 10 名 - 多个表(联合) - SQL
- c++ - QT Gridlayout Item点击后不突出显示?
- reactjs - 如何使用 react-loadable 从库中导出各种组件
- javascript - 运行 Angular 应用程序时出错:“let-”仅支持 ng-template 元素