系统编程PIPE/FIFO用file descriptor沟通是否需要fflush()?

alan4chen 2014-11-21 12:45:57
我的疑问是 假设两个process做沟通(比如fork或其他),使用pipe或fifo的,并且双方都是用file descriptor (文件描述符?)做read write,所以是unbuffered IO,read write本身直接调用system call, 所以不需要fflush。
可是,助教说pipe和fifo其中也有buffer,要用fdopen打开再fflush,可是我感觉很多余。
助教说做很多次pipe沟通的时候,如果不flush的话,残留在pipe的buffer可能本来这次要传的内容会变成下次才传……
我翻The Linux Programming Interface 44.6上写只有popen才需要(比如用setbuf来变unbuffered)……
所以,想请问大神 到底需不需要fdopen再fflush呢?还是说fdopen之后用fp来fread fwrite(治标不治本?)

多谢!

大致我的意思 代码如下:(可能有错,只是想表达上面那个意思)


//PIPE 的情况:
int main(int argc, char *argv[]){
int pfd[2];
pipe(pfd);

if(fork() == 0){
char string1[30] = "abcdefg";
close(pfd[0]);
write(pfd[1], string1, sizeof(string1));
int fp = fdopen(pfd[0]); // 这行有必要吗
fflush(fp); // 这行有必要吗?
exit(0);
}

close(pfd[1]);
char string2[30];
read(pfd[0], string2, sizeof(string2));

exit(0);
}

//FIFO 的情况:
int main(int argc, char *argv[]){
mkfifo("./myfifo", 0777);

if(fork() == 0){
char string1[30] = "abcdefg";
int fd1 = open("./myfifo", O_WRONLY);
write(pfd1, string1, sizeof(string1));
int fp = fdopen(pfd1); // 这行有必要吗?
fflush(fp); // 这行有必要吗?
exit(0);
}

int fd2 = open("./myfifo", O_RDONLY);
char string2[30];
read(fd2, string2, sizeof(string2));

exit(0);
}
...全文
435 6 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
mymtom 2014-11-21
  • 打赏
  • 举报
回复
引用 2 楼 JiangWenjie2014 的回复:
1)先fdopen再fflush,为什么不先open再fsync,这不是多此一举吗? 2)诸如pipe、socketpair之类的东西,往里面写数据本来在内核就是内存拷贝,难道还要flush刷到磁盘上?据我所知,fsync,fflush之类的都是将缓冲数据都写到磁盘上才返回的,那么pipe,socketpair这些内核里面维护的结构是否需要fsync,fflush,你可以做个实验再下结论。
fsync写到磁盘才返回 fflush写到内核就返回
JiangWenjie2014 2014-11-21
  • 打赏
  • 举报
回复
1)先fdopen再fflush,为什么不先open再fsync,这不是多此一举吗? 2)诸如pipe、socketpair之类的东西,往里面写数据本来在内核就是内存拷贝,难道还要flush刷到磁盘上?据我所知,fsync,fflush之类的都是将缓冲数据都写到磁盘上才返回的,那么pipe,socketpair这些内核里面维护的结构是否需要fsync,fflush,你可以做个实验再下结论。
mymtom 2014-11-21
  • 打赏
  • 举报
回复
write和read是不需要fflush的, fflush最终就是调用write DESCRIPTION The function fflush() forces a write of all user-space buffered data for the given output or update stream via the stream’s underlying write function. The open status of the stream is unaffected. If the stream argument is NULL, fflush() flushes all open output streams.
LFYer 2014-11-21
  • 打赏
  • 举报
回复
建议看看APUE第三章《文件I/O》和第五章《标准I/O》,什么是Linux系统的东西,什么是C标准的东西,这个要分清楚。
LFYer 2014-11-21
  • 打赏
  • 举报
回复
所谓的全缓冲、行缓冲、不缓冲那是C标准I/O库的东西。。你直接使用read和write系统调用,根本不经过C标准I/O库,也就无所谓什么全缓冲、行缓冲、不缓冲了。。
alan4chen 2014-11-21
  • 打赏
  • 举报
回复
引用 1 楼 mymtom 的回复:
write和read是不需要fflush的, fflush最终就是调用write DESCRIPTION The function fflush() forces a write of all user-space buffered data for the given output or update stream via the stream’s underlying write function. The open status of the stream is unaffected. If the stream argument is NULL, fflush() flushes all open output streams.
所以即使write到pipe中也是不需要fflush的哦?

23,217

社区成员

发帖
与我相关
我的任务
社区描述
Linux/Unix社区 应用程序开发区
社区管理员
  • 应用程序开发区社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧