什么 execl ("/bin/emacs", "/etc/fstab");做?

What does execl ("/bin/emacs", "/etc/fstab"); do?

例如:

int pid1 = fork();
printf("%s\n", "[1]");
int pid2 = fork();
printf("%s\n", "[2]");
if ((pid1 == 0) && (pid2 == 0)) {
    printf("%s\n", "[3]");
    execl("/bin/emacs", "/etc/fstab");
    int pid3 = fork();
    printf("%s\n", "[4]");
} else {
    printf("%s\n", "[5]");
}

这条线的实际作用是什么?

The execl family of functions replaces the current process image with a new process image.

所以这个程序开始了,只是让运行通过程序:

它将进程分成 2 个,第一个 fork 打印:

[1]
[1]

之后它再次分叉,所以你有 4 个进程和一个打印:

[2]
[2]
[2]
[2]

一个子进程有 pid == 0。有一个 pid1 的子进程和一个 pid2 的子进程,所以正好是:

[3] 

execl 来了。此时它到底做了什么?

这个问题引起了人们对分叉新进程的注意,除了它有意澄清 execl 是如何工作的。因此,它声明为:

int execl(const char *path, const char *arg, ...);

where is an unspecified pathname for the sh utility, file is the process image file, and for execvp(), where arg0, arg1, and so on correspond to the values passed to execvp() in argv[0], argv1, and so on.

The arguments represented by arg0,... are pointers to null-terminated character strings. These strings shall constitute the argument list available to the new process image. The list is terminated by a null pointer. The argument arg0 should point to a filename string that is associated with the process being started by one of the exec functions.

(取自execl documentation

所以,这意味着您缺少一些参数。在这种情况下,您应该像这样使用它:

execl("/bin/emacs", "/bin/emacs", "/etc/fstab", (char*)NULL);

此调用应使用参数 /etc/fstab 启动 emacs 编辑器 - 这意味着 emacs 编辑器将打开(如果已安装),其中 fstab 文件的内容位于 /etc/.