-2

我写了以下代码,但我总是得到输出:“错误!” (未计划返回的 execv 函数)

我究竟做错了什么???

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <time.h>
#include <math.h>
#include <string.h>
#include <malloc.h>
#include "LineParser.h"

#define LOCATION_LEN 200
char* getL(void);

int main(int argc,char *argv[])
{
    char *loc = getL();
    char *args[] = {loc,"ls",NULL};
    int i;
    execv(args[0],args);
    printf("ERROR!");
    free(loc);
}

char* getL(void)
{
    char *buff = (char**)malloc(sizeof(char)*LOCATION_LEN);
    getcwd(buff,LOCATION_LEN);
    return buff;
}
4

2 回答 2

3

阅读execv(3)execve(2)perror(3)的文档。至少,你应该编码

int main(int argc, char *argv[]) {
  char *loc = getL();
  char *args[] = { loc, "ls", NULL };
  int i;
  execv(args[0], args);
  perror("execv");
  free(loc);
}

gcc -Wall -g您应该使用gdb调试器进行编译。

你的使用execv显然是错误的(你需要一个完整的路径,例如"/bin/ls",并且参数的顺序是错误的)。您可能需要exevcp(3)并且实际上至少应该编写代码:

  char *args = { "ls", loc, NULL };
  execvp("ls", args);
  perror("execvp")

如果您坚持使用专门的execv(3)您可以尝试

  char *args = { "ls", loc, NULL };
  execv("/bin/ls", args);
  perror("execv")

我不明白你的代码应该做什么。您可能对glob(7)glob(3)感兴趣。

您可能应该阅读Advanced Linux Programming。似乎有几个概念你还不够了解。我猜strace(1)可能对您有用(至少通过运行strace ls *.c了解正在发生的事情)。

也许你getL的正是 GNU 函数get_current_dir_name(3)正在做的事情,但(char**)它里面的演员阵容是严重错误的。并且你应该在调用 getcwd(2buff ) 之前最好使用memset(3)清除缓冲区(并且你应该测试 ̀ malloc getcwd` 的失败)and of

也许你想要opendir(3)readdir(3)asprintf(3)stat(2);有了所有这些,你甚至可以避免跑步ls

如果你正在编写一些 shell,你应该使用strace一些现有的 shell,并且在阅读了我在这里给出的所有参考资料之后,研究自由软件shell 的源代码,如sashGNU bash

于 2014-10-05T15:53:35.607 回答
0

您没有将正确的参数传递给 execv。第一个参数必须是您希望运行的可执行文件的路径,但您将路径传递到当前工作目录。

更新getL以返回ls.

于 2014-10-05T15:32:41.877 回答