c - 打开后重复的文件描述符

标签 c linux file-descriptor

我在 linux 下使用 popen 执行命令,然后 4 个进程将使用相同的输出。 我试图再次复制文件描述符以将其传递给每个进程。 这是我的代码:

FILE* file_source = (FILE*) popen(source_command, "r");
int fd = fileno(file_source);
fdatasync(fd);

int dest_fd[4], y, total = 4;
    for (y = 0; y < total; y++) {
        dest_fd[y] = dup(fd);
    }

实际上,如果将 total 设置为 1 它可以正常工作,但在更改 total = 4 后它就不再工作了。 这个答案太接近我需要的了: link

最佳答案

您当前的方法可能无法满足您的要求。当您只是复制文件描述符时,它们都引用同一个管道 - 不会复制任何数据。对于源命令发送的每个数据 block ,只有一个进程将读取它。

如果您想复制数据(就像 tee 实用程序所做的那样),那么您需要明确地这样做:

#define TOTAL 4

int dest_fd[TOTAL];
int dest_fd_wr[TOTAL];
int y;

/* Build pipes for reading the data from the child process */
for (y = 0; y < TOTAL; y++)
{
    int p[2];

    pipe(p);
    dest_fd[y] = p[0];
    dest_fd_wr[y] = p[1];
}

/* Create a child process to handle the "tee"-style duplication */
if (fork() == 0)
{
    /* Child process */
    FILE *file_source = popen(source_command, "r");
    FILE *file_sink[TOTAL];
    char buffer[2048];
    size_t nbytes;

    for (y = 0; y < TOTAL; y++)
    {
        close(dest_fd[y]);
        file_sink[y] = fdopen(dest_fd_wr[y], "w");
    }

    while ((nbytes = fread(buffer, 1, sizeof buffer, file_source)) > 0)
    {
        for (y = 0; y < TOTAL; y++)
        {
            fwrite(buffer, 1, nbytes, file_sink[y]);
        }
    }

    _exit(0);
}

for (y = 0; y < TOTAL; y++)
{
    close(dest_fd_wr[y]);
}

/* Now have a set of file descriptors in dest_fd[0..TOTAL-1] that each have
 * a copy of the data from the source_command process. */

错误处理留给读者作为练习;)

关于c - 打开后重复的文件描述符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2780943/

相关文章:

c - 将参数传递给函数时 C 中的段错误

c - 第一个 C 编译器使用了什么样的词法分析器/解析器?

Linux Netcat 按预期工作但在 Raspberry Pi 上不是 QTCPSocket

c++ - 给定文件描述符如何 : Obtain the device node of the device containing a file,

node.js - 写入 Node 中的文件描述符 3

python - 在 Python 中的文件末尾添加一些东西?

c - 如何在国际象棋 AI 中正确检查 caSTLing?

c - 当进程连续写入文件时如何清空文件

c++ - 使用 g++ 链接对象时出现问题

java - 如何将java打印行移动到控制台窗口的顶部?