微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

即使父进程关闭了它们的 FD,如何保持管道 FD 打开?

如何解决即使父进程关闭了它们的 FD,如何保持管道 FD 打开?

我必须关闭进程的管道 FD,但我希望它们在子进程中打开。一种解决方案可能是在 fork() 调用关闭 FD。如果我必须调用一次,它会提供解决方案。我在循环中调用它,所以即使我在 fork() 之后关闭了 FD,它也会在第一次迭代中工作。在下一次迭代中,它将再次关闭他们的 FD。那么我该如何处理这样的情况。我试图实现这一目标的代码如下:

//I want to execute pwd|sort > file.txt

char commands[2][30] = {"pwd","sort"};
char directory [2][30] = {"/usr/bin/pwd","/usr/bin/sort"}
char outputFile[30] = "file.txt"
int totalCommands = 2;
bool isOutputFilePresent = true;

//creating two pipes
int fd1[2];
int fd2[2];
pipe(fd1);
pipe(fd2);
//Closing the writing ends but keeping the reading ends open as closing them will destroy both the pipes
close (fd1[1]);
close (fd2[1]);

//loop to execute each command by creating a child process in each iteration
for (int i = 0; i < totalCommands; ++i)
{
    pid_t pid = fork();
    if (pid == 0)
    {
        if (i == totalCommands - 1)
        {
            if (i%2 == 0)
            {
                close(fd1[1]);
                close(fd2[0]);
                dup2(fd1[0],0);
                dup2(fd2[1],1);
            }
            else
            {
                close(fd2[1]);
                close(fd1[0]);
                dup2(fd2[0],0);
                dup2(fd1[1],1);
            }
        }
        else
        {
            if (i%2 == 0)
            { 
                close(fd2[0]);
                close(fd2[1]);
                close(fd1[1]);
                dup2(fd1[0],0);
            }
            else
            {
                close(fd1[0]);
                close(fd1[1]);
                close(fd2[1]);
                dup2(fd2[0],0);
            }
            if(isOutputFilePresent)
            {
                int outputFD = open (outputFile,O_WRONLY | O_CREAT);
                dup2(outputFD,1);
            }

        }
        execv(directory[i],commands[i]) //ignore the fact that i am passing command name instead of argument vector
    }
    wait(NULL);
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。