如何在C语言中使用fork?

问题描述 投票:1回答:1

下面是完整的代码。

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

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

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

  1. 据我所知: fork() 克隆进程,但是我不明白它是如何执行命令的,因为...。execlp 应该这样做,但代码永远不会到达该部分。
  2. 我不明白为什么 execlp 工作。为什么我们要向它发送两次命令(execlp(command, command, NULL);)?
  3. 如何 execlp 知道如果我们不传给 outfile 哪儿也不去
  4. 为什么我们甚至需要一个 infile 如果命令已经作为其他参数传递了?

先谢谢你的回答。

c fork
1个回答
4
投票
  1. 据我所知,fork()克隆了进程,但是我不明白它是如何执行命令的,因为execlp应该这样做,而代码从来没有到达这个部分。

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

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

  1. 我不明白execlp是如何工作的。为什么我们要把一条命令发送两次(execlp(command, command, NULL);)?

阅读 execlp 人页和 这个

按照惯例,第一个参数应该指向与被执行文件相关的文件名。


  1. 如果我们不在任何地方传递outfile,execlp怎么知道要把输出重定向到哪里。

重定向发生在关闭 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. 如果命令已经作为另一个参数传递了,为什么我们还需要一个infile呢?

如果没有看到作为命令传递的参数,我们就无法知道你的程序做了什么。

© www.soinside.com 2019 - 2024. All rights reserved.