Inter-process Communication-fifo
Another way to communicate between processes is FIFO. FIFO is another pipe: a well-known pipe. As you can see from the name, it's also a queue.
FIFO must be created before using FIFO communication
$ Mkfifo Myfifo
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 example above, one process continuously writes data from the struct type to the FIFO, and another process continuously reads the data from the FIFO to achieve interprocess communication.
CCPP Blog Directory
Copyright NOTICE: This article is for bloggers original articles, reproduced, please indicate the source.
Linux/C + +: interprocess communication-fifo