如何在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
  • 提前感谢您的回答

  • 据我所知,fork()克隆进程,但我不理解它如何执行命令,因为execlp应该这样做 代码永远不会到达那个部分
  • Fork在父空间中返回子进程的pid,在新进程空间中返回0。子进程调用execlp

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

  • 我不明白execlp是如何工作的。为什么我们要向它发送两次命令 (execlp(command,command,NULL);)
  • 阅读手册页和线程

    按照惯例,第一个参数应该指向文件名 与正在执行的文件关联


  • 如果我们没有传递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);
    }
    

  • 如果命令已经作为另一个参数传递,为什么还要使用infle呢

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

    您确定您的
    open
    调用工作正常并返回了预期的fds吗?一些
    assert
    s会有所帮助。代码是否工作,而您只是不了解如何工作,或者是否存在问题?