c - 如何在 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;
    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/

相关文章:

使用函数和指针更改数组的元素

c - 通过多个进程读取同一个txt的不同部分

使用 fork() 创建正好 5 个进程

perl - 使用 Parallel::ForkManager 限制进程

c - 在 C 中存储和使用大数

c++ - 使用事件同步线程

c - 双递归函数后使用顺序索引扫描数组

c - 告诉 gcc 专门展开一个循环

PHP+fork() : How to run a fork in a PHP code

等待用户输入特定秒数的 C 程序