int pipe_fd; int res; int open_mode = O_RDONLY; char buf[100]; int bytes_read = 0; memset (buf,'\0',sizeof(buf)); pipe_fd = open(FIFO_NAME,open_mode); if (access(FIFO_NAME,F_OK) == -1) { res = mkfifo(FIFO_NAME,0777); if (res != 0) { fprintf (stderr,"Could not create fifo %s\n",FIFO_NAME); exit (EXIT_FAILURE); } } for(;;) { do { res = read(pipe_fd,buf,sizeof(buf)); bytes_read += res; }while (res > 0); // process data then go back and block ............ }
它通过一些代码在一个bash脚本中发送一个简单的缓冲区,像这样’./test 1′
#!/bin/bash pipe=/tmp/pipe if [[ ! -p $pipe ]]; then echo "Reader not running" exit 1 fi if [[ "$1" ]]; then echo "some string" >$pipe else echo "q" >$pipe fi
我在gdb中运行C代码程序,最初它会读取阻塞,但是一旦我调用bash脚本,C代码就不再阻塞,它会成功读取数据
缓冲区然后每次读取时都有0个字节读取,所以不知道为什么它不再阻塞. “一些字符串”数据在另一边正确接收.
我只需要坐在那里等待数据处理,然后回去等待更多
解决方法
I run the C code program in gdb and initially it does block on the read but as soon as i call the bash script the C code no longer blocks,it does successfully read the data from the buffer and then each time it reads there are 0 bytes read so not sure why its no longer blocking. The ‘some string’ data is correctly received at the other side.
0表示EOF.只有当连接到它们的进程用于读取和写入时,FIFO才能被读取或写入.当没有更多的作者(你的shell脚本被终止)时,通过read()返回EOF就会通知读者.
FIFO的行为方式与shell管道逻辑兼容,例如:
$mkfifo ./tmp1 $cat < input > ./tmp1 & $cat < ./tmp1 > /dev/null
如果read()不会返回EOF,则第二只猫会永久阻止.
I just need it to sit there waiting for data process it and then go back and wait for more
在C程序中,read()返回EOF后,必须重新打开()FIFO.
附:找到quite nice FIFO summary为你的.检查第二页上的表格.