A. fifo file creation, create a FIFO on file system
int ret = MKFIFO ("/tmp/fifo", mode);
Two. Open FIFO
Open ("/tmp/fifo", flag);
Depending on the flag, there are four ways to open them:
O_RDONLY: Block Until, this FIFO is opened by o_wronly mode
O_WRONLY: Block Until, this FIFO is opened by o_rdonly mode
o_rdonly| O_nonblock: Return immediately
o_wronly| O_nonblock: If this FIFO has been read-only open, return the file descriptor immediately, if not, return now-1
FIFO support Open,close,read,write.unlink function, o_rdonly and o_wronly combination open results are undefined
Four ways to open test code:
Fifo_read.c
#include <sys/stat.h>
#include <stdio.h>
#include <errno.h>
#include <fcntl.h>
int main ()
{
Char line[1024+1] = {' I '};
mode_t mode;
mode = s_irwxu| S_IRWXG;
if (Mkfifo ("/tmp/fifo", mode) < 0 && errno!=eexist)
{
printf ("Mkfifo failed!\n");
}
printf ("\ n");
int fd = open ("/tmp/fifo", o_rdonly);
if (fd<0)
{
printf ("Reader:first Open FIFO failed!\n");
}
Else
{
printf ("Reader:open FIFO secceed!\n");
}
Sleep (1);
FD = open ("/tmp/fifo", o_rdonly);
if (fd<0)
{
printf ("Reader:second Open FIFO failed!\n");
}
Else
{
printf ("Reader:second open FIFO secceed!\n");
}
If read (FD, line, 1024) < 0)
{
printf ("Reader:read FIFO failed!\n");
}
printf ("Get msg:%s \ n", line);
return 0;
}
Fifo_writer.c
#include <sys/stat.h>
#include <stdio.h>
#include <errno.h>
#include <fcntl.h>
#include <unistd.h>
#define MSG "Hello World!"
int main ()
{
Char line[1024] = {' I '};
mode_t mode;
mode = s_irwxu| S_IRWXG;
if (Mkfifo ("/tmp/fifo", mode) < 0 && errno!=eexist)
{
printf ("Mkfifo failed!");
}
printf ("\ n");
int fd = open ("/tmp/fifo", o_wronly);
if (fd<0)
{
printf ("Open FIFO failed!");
}
printf ("Writer:open secceed!\n");
Close (FD);
FD = open ("/tmp/fifo", o_wronly| O_nonblock);
if (FD < 0)
{
printf ("Writer:second Open failed!\n");
}
Else
{
printf ("Writer:second Open failed!\n");
}
Sleep (2);
FD = open ("/tmp/fifo", o_wronly| O_nonblock);
if (FD < 0)
{
printf ("Writer:third Open failed!\n");
}
Else
{
printf ("Writer:third open secceed!\n");
}
If write (FD, MSG, strlen (msg)) < 0)
{
printf ("Write FIFO failed!");
}
return 0;
}
FIFO_READ.C Generate executable File reader
FIFO_WRITER.C to generate an executable file writer
Test results:
[Read_ng@wukong workspace]$./reader &
[1] 17862
[Read_ng@wukong workspace]$./writer &
[2] 17863
[Read_ng@wukong workspace]$
Writer:open Secceed!
Reader:open FIFO secceed!
Writer:second Open failed!
Reader:second Open FIFO Secceed!
Writer:third Open Secceed!
Get Msg:hello World!
[1]-done./reader
[2]+ done./writer
[Read_ng@wukong workspace]$
Three. FIFO Reading and writing
1. If a FIFO, all open descriptors are closed, the content will be emptied, otherwise it will not empty
2.read, if there is data in the FIFO, it will read out, if not, and not be written to open return 0, indicating the end
3.write, if the FIFO is not read open, generates a signal sigpipe, causing the process to terminate