这是完整的代码:
#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重定向来fork和执行一个命令,然后等待其终止并printf WEXITSTATUS(wstatus)
接收到。例如:./allredir hexdump out_of_ls dump_file
。
因此,在fork()
之前,我理解了一切。但是我有以下问题:
- 据我所知,
fork()
会克隆进程,但我不明白它如何执行该命令,因为execlp
应该执行该命令,而代码从未到达过那一部分。 - 我不明白
execlp
的工作原理。为什么我们要两次发送命令给它 (execlp(command, command, NULL);
)? - 如果我们没有传递
outfile
,execlp
如何知道重定向输出到哪里。 - 如果命令已经作为另一个参数传递,为什么我们还需要
infile
呢?
提前感谢您的回答。
open
调用已经成功并返回了你期望的文件描述符吗?一些assert
语句会有所帮助。 - Stephen Newell