Inter-process Communication-fifo
One more way to communicate between processes is FIFO.
FIFO is also a pipeline: A well-known pipeline. From the name can be seen. It is also a queue.
FIFO must be created before using FIFO communication
$ Mkfifo Myfifo
You can then just use the Myfifo like a file.
Fifo_w.c
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <sys/types.h> #include < sys/stat.h> #include <sys/fcntl.h>struct stu{int id;char name[20];}; int main (int argc, char **argv) {if (argc! = 2) {fprintf (stderr, "Usage:./app fifo\n"); exit (1);} int fd;if (FD = open (argv[1], o_wronly)) < 0) {fprintf (stderr, "Open:can not open file:%s\n", argv[1]); exit (1);} struct Stu ZX = {0, "Zhangxiang"};int id = 0;while (1) {id++;zx.id = Id;write (fd, &ZX, sizeof (ZX)); sleep (1);} Close (FD); return 0;}
Fifo_r.c
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <sys/types.h> #include < sys/stat.h> #include <sys/fcntl.h>struct stu{int id;char name[20];}; int main (int argc, char **argv) {if (argc! = 2) {fprintf (stderr, "Usage:./app FIFO"); exit (1);} int fd;if (FD = open (argv[1], o_rdonly)) < 0) {fprintf (stderr, "Open:can not open file:%s", argv[1]); exit (1);} struct Stu Zx;while (1) {Read (FD, &ZX, sizeof);p rintf ("id=%d,name=%s\n", Zx.id, Zx.name); sleep (1);} Close (FD); return 0;}
Test
in the demo sample above, a process continuously writes data from the struct type to the FIFO. There is also a process that continuously reads data from the FIFO. So as to achieve inter-process communication.
CCPP Blog Folder
Linux system programming: interprocess communication-fifo