c - 如何在 C 中将 execv 与生成的路径一起使用?

标签 c bash shell unix malloc

我有一项任务,其中我们必须创建一个 shell。其中一部分包括使用不同 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: No such file or directory

因此删除多余的 \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 */
}

关于c - 如何在 C 中将 execv 与生成的路径一起使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52240612/

相关文章:

java - 如何在 Rooted android 设备中使用 shell 命令读取短信?

shell - 仅对文件的前 100 行进行排序

c - 如何在 C 中表示内存中的 FLOAT 数

c - 在终端上键入`node`时运行的代码

c - 带有未声明变量的 Typedef 结构

linux - 带有 grep 的 Bash 函数,使用 if 和 then 语句

linux - 通过 bash 将文件从一个目录排序并复制到另一个目录

perl - 如何检查文件大小并将结果添加到 Perl 中的 Excel 电子表格中?

c - SDL2 如何渲染原始格式的像素?

常见的误解 : Files have an EOF char at their end