2012-12-18 95 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

相關問題