下面是完整的代码。
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/wait.h>
int main(int argc, char *argv[]) {
char *command, *infile, *outfile;
int wstatus;
command = argv[1];
infile = argv[2];
outfile = argv[3];
if (fork()) {
wait(&wstatus);
printf("Exit status: %d\n", WEXITSTATUS(wstatus));
}
else {
close(0);
open(infile, O_RDONLY);
close(1);
open(outfile, O_CREAT|O_TRUNC|O_WRONLY, 0644);
execlp(command, command, NULL);
}
return 0;
}
这段代码应该是fork和执行一个命令,并同时使用了 stdin 和 stdout 重定向,然后等待它终止,并 printf WEXITSTATUS(wstatus)
收到。例如: ./allredir hexdump out_of_ls dump_file
.
所以,我明白之前的一切 fork()
. 但我有以下问题。
fork()
克隆进程,但是我不明白它是如何执行命令的,因为...。execlp
应该这样做,但代码永远不会到达该部分。execlp
工作。为什么我们要向它发送两次命令(execlp(command, command, NULL);
)?execlp
知道如果我们不传给 outfile
哪儿也不去infile
如果命令已经作为其他参数传递了?先谢谢你的回答。
- 据我所知,fork()克隆了进程,但是我不明白它是如何执行命令的,因为execlp应该这样做,而代码从来没有到达这个部分。
Fork在父进程空间返回子进程的pid,在新进程空间返回0。子进程对execlp进行调用。
if (fork()) {
/* Parent process waits for child process */
}
else {
/* Son process */
execlp(command, command, NULL);
}
- 我不明白execlp是如何工作的。为什么我们要把一条命令发送两次(execlp(command, command, NULL);)?
按照惯例,第一个参数应该指向与被执行文件相关的文件名。
- 如果我们不在任何地方传递outfile,execlp怎么知道要把输出重定向到哪里。
重定向发生在关闭 stdin 和 stdout 文件描述符之前。而重定向发生在打开文件时,文件描述符可以容纳0和1。
else {
/* redirecting stdin */
close(0);
open(infile, O_RDONLY);
/* redirecting stdout */
close(1);
open(outfile, O_CREAT|O_TRUNC|O_WRONLY, 0644);
execlp(command, command, NULL);
}
- 如果命令已经作为另一个参数传递了,为什么我们还需要一个infile呢?
如果没有看到作为命令传递的参数,我们就无法知道你的程序做了什么。