0

Advanced Linux Programming book (リスト 3.4、51 ページ) の例を実行しようとしています。

#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 を使用)

4

3 に答える 3

2

トムのリクエストによると:

問題は、コマンド名の文字列内の (余分な) スペースにあるようです。

bash (シェル) インタープリターを呼び出して文字列コマンドを与えるのではないことに注意してください。コマンドに「名前を付ける」ことは、ファイルに名前を付けることに似ています。使用可能なコマンド (ファイル) と比較する際に、すべての文字が考慮されます。

于 2012-12-18T21:36:26.553 に答える
1

検証なしの簡単な推測: おそらく /bin/ls のように ls コマンドへのフルパスを指定する必要があります

于 2012-12-18T13:40:58.507 に答える
1

spawn 関数に渡す "program" 引数が正しくありません。execvp のマニュアルページで指定されているとおり:

これらの関数の最初の引数は、実行するファイルの名前です。

ここで実行したいファイルは /bin/ls です

于 2012-12-18T13:46:08.763 に答える