環境: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標誌打開,只能實現管道第一次讀取時阻塞,之後不會再出現阻塞狀態。