gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:12:29 34 4
gpt4 key购买 nike

我在 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/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com