如何在C中使用fork?
以下是完整的代码:如何在C中使用fork?,c,fork,C,Fork,以下是完整的代码: #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; i
#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;
}
#包括
#包括
#包括
#包括
#包括
#包括
int main(int argc,char*argv[]){
char*命令、*infle、*outfile;
int wstatus;
command=argv[1];
infle=argv[2];
outfile=argv[3];
if(fork()){
等待(&wstatus);
printf(“退出状态:%d\n”,WEXITSTATUS(wstatus));
}
否则{
关闭(0);
打开(仅限填充);
关闭(1);
打开(outfile,O|u create | O|u TRUNC | O|u WRONLY,0644);
execlp(命令,命令,空);
}
返回0;
}
此代码应分叉并执行带有stdin和stdout重定向的命令,然后等待它终止并
printf WEXITSTATUS(wstatus)
收到。e、 g./allredir hextump out\u of \u ls dump\u文件
所以,在fork()
之前,我什么都懂。但我有以下问题:
fork()
克隆进程,但我不理解它是如何执行命令的,因为execlp
应该这样做,而代码永远不会到达该部分execlp
是如何工作的。为什么我们要向它发送两次命令(execlp(command,command,NULL);
)execlp
如何知道在哪里重定向输出infle
if (fork()) {
/* Parent process waits for child process */
}
else {
/* Son process */
execlp(command, command, NULL);
}
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);
}
如果没有看到作为命令传递的参数,我们无法判断您的程序执行什么操作。您确定您的
open
调用工作正常并返回了预期的fds吗?一些assert
s会有所帮助。代码是否工作,而您只是不了解如何工作,或者是否存在问题?