环境:ubuntu 14.04 gcc
写入管道端:
fifo_send.c
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/types.h> #include <sys/stat.h> #include <unistd.h> #include <fcntl.h> typedef struct _msgcontent{ char szAction[512]; char szDevice[512]; char mountPath[512]; }UMSGCONTENT; int main (int argc, char *argv[]) { int fd; UMSGCONTENT umsg; strcpy ((char *)&umsg.szAction, "add"); strcpy ((char *)&umsg.szDevice, "/dev/sda1"); strcpy ((char *)&umsg.mountPath, "/mnt"); mkfifo ("/tmp/.mountFifo", 0777); fd = open ("/tmp/.mountFifo", O_WRONLY); write (fd, &umsg, sizeof (umsg)); close (fd); return 0; }
读取管道fifo_receive.c
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/types.h> #include <sys/stat.h> #include <unistd.h> #include <fcntl.h> typedef struct _msgcontent{ char szAction[512]; char szDevice[512]; char mountPath[512]; }UMSGCONTENT; int main (int argc, char *argv[]) { int fd; UMSGCONTENT umsg; fd = open ("/tmp/.mountFifo", O_RDWR); if (fd < 0) { printf ("open failed\n"); return -1; } printf ("open succes\n"); while (1) { int res = read (fd, &umsg, sizeof (umsg)); printf ("szAction [%s] \n", umsg.szAction); printf ("szDevice [%s] \n", umsg.szDevice); printf ("mountPath [%s] \n", umsg.mountPath); } close (fd); return 0; }
编译,运行:
gcc fifo_send.c -o fifo_send gcc fifo_receive.c -o fifo_receive
第一步:运行fifo_send $ ./fifo_send 第二步:运行fifo_receive $ ./fifo_receive szAction [add] szDevice [/dev/sda1] mountPath [/mnt]
这样就可以实现,管道的每次读写数据时,如果数据为空则都是阻塞状态
注意: 在接收管道数据的时候(fifo_receive.c)
open 函数打开时,如果使用O_RDONLY标志打开,只能实现管道第一次读取时阻塞,之后不会再出现阻塞状态。