0

我正在尝试运行 Advanced Linux Programming 一书(清单 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 (shell) 解释器并为其提供字符串命令。您正在“命名”一个命令,在这方面它类似于命名文件,在与可用命令(文件)进行比较时会考虑所有字符。

于 2012-12-18T21:36:26.553 回答
1

快速猜测,无需验证:您可能必须提供 ls 命令的完整路径,例如 /bin/ls

于 2012-12-18T13:40:58.507 回答
1

您传递给 spawn 函数的“程序”参数不正确。由 execvp 的手册页指定:

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

这里你要执行的文件是 /bin/ls

于 2012-12-18T13:46:08.763 回答