2012-12-18 97 views
0

我试图运行从高级Linux编程书的例子(清单3.4,第51页):为什么这个Linux编程C示例代码失败?

#include <stdio.h> 
#include <stdlib.h> 
#include <sys/types.h> 
#include <unistd.h> 

/* Spawn a child process running a new program. PROGRAM is the name 
of the program to run; the path will be searched for this program. 
ARG_LIST is a NULL-terminated list of character strings to be 
passed as the program’s argument list. Returns the process ID of 
the spawned process. */ 
int spawn(char* program, char** arg_list) { 
    pid_t child_pid; 
    /* Duplicate this process. */ 
    child_pid = fork(); 
    if (child_pid != 0) 
     /* This is the parent process. */ 
     return child_pid; 
    else { 
     /* Now execute PROGRAM, searching for it in the path. */ 
     execvp(program, arg_list); 
     /* The execvp function returns only if an error occurs. */ 
     fprintf(stderr, "an error occurred in execvp\n"); 
     abort(); 
    } 
    return 0; 
} 

int main() { 
    /* The argument list to pass to the "ls” command. */ 
    char* arg_list[] = { "ls", /* argv[0], the name of the program. */ 
    "-l", "/", NULL /* The argument list must end with a NULL. */ 
    }; 
    /* Spawn a child process running the "ls” command. Ignore the 
    returned child process ID. */ 
    spawn(" ls", arg_list); 
    printf("done with main program\n"); 
    return 0; 
} 

而且我得到了:

an error occurred in execvp 
done with main program 

任何想法有什么不对吗? (使用Ubuntu 10.10)

+2

'ls'之前的空间可以成为问题吗? –

+1

尝试''ls“'而不是''ls”'。甚至是“/ bin/ls”。此外,你可以从'errno'获得关于错误的信息;你为什么不检查那个? –

+0

而不是(或除了)fprintf,添加'perror(“Execvp失败”);'。这将打印出一个人类可读的错误消息,解释发生了什么。 – Neal

回答

2

按照汤姆的要求:

的问题似乎是(额外)空间的字符串名称命令英寸

请记住,您并未拨打bash(shell)解释器并为其提供字符串命令。您正在“命名”一个命令,在这方面,它类似于命名文件,与可用命令(文件)进行比较时会考虑所有字符。

1

快速的猜测,而无需验证:您可能必须提供完整路径ls命令,像/斌/ LS

+0

只要二进制文件可以基于'PATH'找到,就不需要完整路径。由于所提供的代码有一个空格作为可执行文件名的第一个字符(这可能是一个错误),所以您的完整路径解决方案将起作用,但原因不正确。这就是说,完整的路径仍然是可取的! – mah

+0

这应该是一条评论。 – Willem

1

传递给你的重生功能的“程序”的说法是不正确。按照execvp手册页的规定:

这些函数的初始参数是要执行的文件的名称。

这里要执行的文件为/斌/ LS

相关问题