弹出后重复文件描述符 [英] Duplicate file descriptor after popen
问题描述
我正在使用popen在linux下执行命令,然后4个进程将使用相同的输出. 我试图再次复制文件描述符,以将其传递给每个进程. 这是我的代码:
I am using popen to execute a command under linux, then 4 process wile use the same output. I am trying to duplicate the file descriptor again to pass it to each process. here is my code:
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更改后,它将不再起作用. 这个答案太接近我所需要的: 链接
actually if total set to 1 it work fin, after changing total = 4 it does not work anymore. this answer is too close to what i need: link
推荐答案
您当前的方法可能无法满足您的要求.当您仅复制文件描述符时,它们都指向同一管道-没有 data 将被复制.对于source命令发送的每个数据块,正好有一个进程要读取它.
Your current approach probably won't do what you want. When you just duplicate the file descriptors, they all refer to the same pipe - no data is going to get duplicated. For each block of data sent by the source command, exactly one process is going to read it.
如果要复制数据(如tee
实用程序一样),则需要明确地这样做:
If you want to duplicate the data (like the tee
utility does), then you will need to explicitly do so:
#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. */
错误处理留给读者练习;)
Error-handling is left as an exercise for the reader ;)
这篇关于弹出后重复文件描述符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!