Linux/C + +: interprocess communication-fifo

Source: Internet
Author: User

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.