【发布时间】:2020-08-16 04:58:03
【问题描述】:
这里是完整的代码:
#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;
}
这段代码应该分叉并执行一个带有 stdin 和 stdout 重定向的命令,然后等待它终止并收到printf WEXITSTATUS(wstatus)。例如./allredir hexdump out_of_ls dump_file.
所以,我了解fork() 之前的一切。但我有以下问题:
- 据我了解,
fork()克隆了进程,但我不明白它是如何执行命令的,因为execlp应该这样做,而代码永远不会到达那部分。 - 我不明白
execlp的工作原理。为什么我们要向它发送两次命令 (execlp(command, command, NULL);)? - 如果我们不通过
outfile,execlp如何知道将输出重定向到哪里。 - 如果命令已经作为另一个参数传递,为什么我们还需要
infile?
提前感谢您的回答。
【问题讨论】:
-
您确定您的
open调用有效并返回了您期望的fds?一些asserts 会有所帮助。 -
代码是否有效,您只是不明白如何,还是有问题?