2014-10-05 63 views
-3

我写了下面的代码,但总是得到输出:“ERROR!” (execv函数没有预定返回)我的execv()函数在linux下不工作ubuntu

我在做什么错?

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

首先,从'execv'返回检查errno。然后检查你传递的参数。 – Duck 2014-10-05 14:38:12

+0

execv返回-1 – Roni 2014-10-05 14:47:53

+1

当然它返回-1。使用'errno'和'strerror'或'perror'来解释为什么......也就是你的参数。 – Duck 2014-10-05 15:49:35

回答

0

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

更新getL将完整路径返回到ls

+0

'malloc'中声明'#include ',因为ls的完整路径是什么? – Roni 2014-10-05 15:38:44

+1

在终端运行'哪个ls'知道这个。通常它是'/ bin/ls' – 2014-10-05 16:56:19

2

阅读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(2)之前清除缓冲区使用memset(3)buff(你应该测试针对的malloc and of getcwd`故障)

也许你想opendir(3)readdir(3)asprintf(3)stat(2);所有这些,你甚至可以避开运行ls

如果您编码一些贝壳,你应该strace一些现有的外壳,并且在已经阅读所有我在这里给参考,研究free software壳的源代码像sashGNU bash

+0

谢谢 但是必须在execv中使用,那么请你向我解释它是如何工作的? 我不明白功能参数。 – Roni 2014-10-05 16:12:39

+0

阅读我给你的所有链接(这应该需要几个小时的阅读)。我不会试着解释我给你的参考资料解释得比我在几分钟内解释得更好。并请*编辑你的问题*改善*。 – 2014-10-05 16:17:50

+0

我想你说的话 但它仍然无法正常工作 http://www.siz.co.il/my.php?i=yme2vgnyyt1y.png – Roni 2014-10-05 16:41:51