【发布时间】:2014-12-10 23:28:49
【问题描述】:
这是我试图理解的一段代码:
#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 ();
}
}
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;
}
我无法理解 spawn 函数的指针是如何工作的。它要求的参数是char* program 和char** arglist。在main方法中,我们调用方法并传入"ls"和char* arglist[],我理解为一个指针数组。 char* program 与"ls" 是如何对应的,因为"ls" 不是指向char 的指针。 char** arglist,它是一个指向 char 的指针的指针,如何对应于 char* arglist[],它是一个指针数组?
我只是无法理解指针在此代码示例中的工作方式。
另外,在main 中,对于char* arg_list[],我们是否基本上存储了指向每个字符的指针?例如,arg_list[0] 将保存"l" 的地址,arg_list[1] 将保存"s" 的地址,arg_list[2] 将保存"-" 的地址
【问题讨论】:
-
C 字符串是一系列以 0 结尾的字符,因此您可以通过指向字符串中第一个字符的指针来引用它们。同样,数组是连续内存位置中的一系列值,因此
char[](或多或少)等同于char*。 -
仅供参考,
arg_list[0]是指向"ls"的指针,arg_list[1]是指向"-l"的指针,arg_list[2]是指向"/"的指针,arg_list[4]是 @ 987654349@指针。 -
@Rup:多于少。并且知道确切的差异很重要。
-
顺便说一句:当心你使用的不那么聪明的智能报价。他们错了。
-
顺便说一句:
“an error occurred in execvp\n”你有奇怪的引号。
标签: c arrays pointers exec fork