如何在C语言中使用fork函数?

3

这是完整的代码:

#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重定向来fork和执行一个命令,然后等待其终止并printf WEXITSTATUS(wstatus)接收到。例如:./allredir hexdump out_of_ls dump_file

因此,在fork()之前,我理解了一切。但是我有以下问题:

  1. 据我所知,fork()会克隆进程,但我不明白它如何执行该命令,因为execlp应该执行该命令,而代码从未到达过那一部分。
  2. 我不明白execlp的工作原理。为什么我们要两次发送命令给它 (execlp(command, command, NULL);)?
  3. 如果我们没有传递outfileexeclp如何知道重定向输出到哪里。
  4. 如果命令已经作为另一个参数传递,为什么我们还需要infile呢?

提前感谢您的回答。


这可能会有所帮助:https://dev59.com/8Ww05IYBdhLWcg3wXAiF - Tormund Giantsbane
你确定你的 open 调用已经成功并返回了你期望的文件描述符吗?一些 assert 语句会有所帮助。 - Stephen Newell
2
代码是否工作,只是你不明白它是如何工作的,还是存在问题? - Erich Kitzmueller
1个回答

4
据我所知,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如何知道在哪里重定向输出。

重定向是通过关闭标准输入和标准输出文件描述符来进行的。重定向是通过打开文件,其文件描述符将容纳条目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?

如果不看作为命令的参数,我们无法确定程序的功能。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接