gpt4 book ai didi

c - 如何在 C 中使用 fork?

转载 作者:行者123 更新时间:2023-12-04 01:27:50 28 4
gpt4 key购买 nike

完整代码如下:

#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;
}


这段代码应该使用 stdinstdout 重定向执行一个命令,然后等待它终止和 printf WEXITSTATUS(wstatus ) 收到。例如./allredir hexdump out_of_ls dump_file.

所以,我明白了fork()之前的一切。但我有以下问题:

  1. 据我所知,fork() 克隆了进程,但是我不明白它是如何执行命令的,因为 execlp 应该这样做,而代码永远不会到达那部分。
  2. 我不明白execlp 是如何工作的。为什么我们向它发送命令两次 (execlp(command, command, NULL);)?
  3. 如果我们不在任何地方传递 outfileexeclp 如何知道将输出重定向到哪里。
  4. 如果命令已经作为另一个参数传递,为什么我们还需要 infile

提前感谢您的回答。

最佳答案

  1. As far as I understand, fork() clones the process, however I do not understand how it executes the command, because execlp should do that and code never reaches that part.

Fork 在父进程空间中返回子进程的 pid,在新进程空间中返回 0。子进程调用 execlp。

if (fork()) { 
/* Parent process waits for child process */
}
else {
/* Son process */
execlp(command, command, NULL);
}

  1. I do not get how execlp works. Why do we send a command to it twice (execlp(command, command, NULL);)?

阅读execlp手册页和 this线程

The first argument, by convention, should point to the filename associated with the file being executed.


  1. How does execlp know where to redirect the output if we do not pass outfile nowhere.

重定向发生在关闭 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);
}

  1. Why do we even need an infile if the command is already passed as the other argument?

如果没有看到作为命令传递的参数,我们无法判断您的程序做了什么。

关于c - 如何在 C 中使用 fork?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61546956/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com