关于有名管道的一个问题。

NGC3623 2016-08-18 02:46:59
我以阻塞模式打开两个的读写两个进程。
在两个进程都启动后。调用write往管道写数据,但是read为什么处于阻塞状态?当写进程关闭打开的文件描述符后,这个read才会退出阻塞状态,读取到数据呢。
tie代码。write:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>


int main(void){
char buffer[1024];
int num;

//if(mkfifo("pipe", 0666) == -1){
// perror("");
//}
int fd = open("pipe", O_WRONLY);
printf("open success\n");
while(1){
scanf("%s", buffer);
if(strcmp(buffer, "q") == 0){
break;
}
num = write(fd, buffer, strlen(buffer) + 1);
printf("Write char: %d\n", num);
}
close(fd);
}

read:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>



int main(void){
char buffer[1024];
int fd = open("pipe", O_RDONLY);
printf("open success\n");
while(read(fd, buffer, 1024) > 0){
printf("-----------------------");
printf("%s", buffer);
}
printf("quit");
close(fd);
}




...全文
445 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
NGC3623 2016-08-19
  • 打赏
  • 举报
回复
引用 2 楼 xinzha 的回复:
scanf没有读到行结束符吧,所以认为没有到解阻塞的时候
read阻塞不是应该在write写如完成后就结束了吗?因为write是内核调用,不存在缓存的原因。而且返回值为写入的字符数量,也表示写入成功了吧。懵的。搞不懂。
猪头三小队长 2016-08-19
  • 打赏
  • 举报
回复
scanf没有读到行结束符吧,所以认为没有到解阻塞的时候
NGC3623 2016-08-18
  • 打赏
  • 举报
回复
我把写进程那句读取用户输入的scanf改成了:
read(STDIN_FILENO, buffer, sizeof(buffer));
问题得以解决,但是不知道为什么会产生这样子的问题。

23,125

社区成员

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

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