Linux process communication (SystemV) Section 2 ------> FIFO

Source: Internet
Author: User
I. Some simple understandings: We know that the pipeline has no signs, so we can only communicate in the same process Group. it is not possible between processes produced by different ancestors !! Therefore, the FIFO mechanism can only be single-stream! The difference is that FIFO has a flag! Each FIFO has... i. some simple understandings: We know that pipelines have no signs, so we can only communicate in the same process Group. different ancestor-generated processes cannot !! Therefore, the FIFO mechanism can only be single-stream! The difference is that FIFO has a flag! Each FIFO has a path name! FIFO is also known as "famous pipeline" # include # Include Int mkfifo (const char * pathname, mode_t mode); mode is the same as that in the open function. the default value is O_CREAT | O_EXCL if FIFO already exists, then an EEXIST error is returned! If it does not exist, a new FIFO is created. If you only open the FIFO, you can use the open () function! A created FIFO can only be read or written, but cannot be performed simultaneously. (Half duplex) for FIFO: first-in-first-out, so read from the beginning and write from the end to view the created pipeline: ls-lF/tmp/my_fifo> prwxr-xr-x 1 pt gf 0/tmp/my_fifo | note: The first character in the ls command output result is p, indicates that this is an MPs queue. Last | the symbol is added by the-F option of the ls command. it also indicates that it is a pipeline. II. # include # Include # Include # Include Int main () {intres; if (res = mkfifo ("/tmp/my_fifo", 0777) = 0) //!> For mkfifo, 0 is returned if the operation is successful. otherwise,-1 is returned {//!> Note that the full name is/tmp/my_fifo, which is actually the my_fifo file printf ("stored ocreated \ n");} return0; //!> Exit (EXIT_SUCCESS);} III. 1. Introduction: two independent programs: 1. producer program, which creates a pipeline as needed and writes data to the pipeline as quickly as possible. 2. the consumer program reads data from the FIFO and discards the data. 2. Code: # include # Include # Include # Include # Include # Include # Include # Define export o_name "/tmp/Linux/my_fifo" //!> Full name of FIFO # define BUFFER_SIZE 40 //!> PIPE_BUF, before linux 2.6.11, is 4096 and later is 65536. # Define TEN_MEG 36*10 //!> (1024*1024*10) int main () {intpipe_fd; intres; required pen_mode = O_WRONLY; //!> Producer: write data ~ Int bytes = 0; charbuffer [BUFFER_SIZE + 1] = "abcdefghijklmnopqrstuvwxyz"; //!> 36 Test characters, if (access (export o_name, F_ OK) =-1) //!> If the object does not exist (if the object exists, the access return value is 0) {res = mkfifo (stored o_name, 0777); //!> If (res! = 0) //!> If the file is successfully created, 0 is returned. otherwise,-1 is returned. if the file is not successfully created, {fprintf (stderr, "Can't create fifo % s \ n", stored o_name) is returned ); exit (EXIT_FAILURE) ;}} printf ("Process % d opening FIFO O_WRONLY \ n", getpid (); pipe_fd = open (kerbero_name, open_mode); //!> Open the created file in write-only mode (note that the file descriptor is returned by open) //!> Start from this: the producer starts writing files, so the Device needs to be started. then, the "consumer" executes the CPU printf ("Process % d ---> file id: % d \ n ", getpid (), pipe_fd); if (pipe_fd! =-1) //!> For open, FILE_ID is returned for success, and-1 is returned for failure (success ~) {Chartest_char = '0'; while (bytes <TEN_MEG) //!> Specify the size as TEN_MEG {//! >>>>>>>>>>>>>>>>>>>>>>>>>>>>> Test_char ++; //!> As a test character (indicating whether or not the data read at the beginning is written) int len = strlen (buffer); //!> Test string processing (only test) buffer [len] = test_char; buffer [len + 1] = '\ 0 '; //! >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> Res = write (pipe_fd, buffer, BUFFER_SIZE); //!> Write data to a file (note that the number of bytes written at a time is returned) if (res =-1) {fprintf (stderr, "Write error on pipe \ n "); exit (EXIT_FAILURE);} printf ("producer write: --->"); puts (buffer); bytes + = res;} close (pipe_fd); //!> Close File Descriptor (that is, close File s)} else {exit (EXIT_FAILURE);} printf ("Process % d finish... \ n ", getpid (); exit (0) ;}# include # Include # Include # Include # Include # Include # Include # Define export o_name "/tmp/Linux/my_fifo" //!> Note that the path to be accessed by the consumer is the "producer" write Path File (one write and one read) # define BUFFER_SIZE 40 //!> PIPE_BUF //!> PIPE_BUF, before linux 2.6.11, is 4096 and later is 65536. Int main () {intpipe_fd; intres; inclupen_mode = O_RDONLY; //!> Consumer read-only int bytes = 0; charbuffer [BUFFER_SIZE + 1]; memset (buffer, '\ 0', sizeof (buffer); //!> Printf ("Process % d opening FIFO O_RDONLY \ n", getpid (); pipe_fd = open (writable o_name, open_mode); //!> Open an existing file read-only printf ("Process % d result % d \ n", getpid (), pipe_fd); if (pipe_fd! =-1) {res = read (pipe_fd, buffer, BUFFER_SIZE); //!> Read for the first time (to prevent data loss) while (res> 0) {bytes + = res; printf ("consumer read: --->"); puts (buffer ); res = read (pipe_fd, buffer, BUFFER_SIZE); //!> Read data from the file to buffer} close (pipe_fd);} else {exit (EXIT_FAILURE);} printf ("Process % d finished, % d bytes read/n ", getpid (), bytes); exit (EXIT_SUCCESS);} 3. operation and result analysis: the principle is that consumers and producers share the famous pipe (FIFO), which is essentially a pointer. Both are backward and the values are also backward, therefore, the order of each fetch is the write order to compile the two programs: gcc-o c cons. cgcc-o p per. c. run these two programs: run the producer program in the background. /p & re-run the consumer program. /c terminal COPY: pt @ ubuntu :~ /Desktop/net programming/Process communication/FIFO/Producer Consumer $./p & [1] 6055 Process 6055 opening FIFO O_WRONLY pt @ ubuntu :~ /Desktop/net programming/process communication/FIFO/Producer Consumer $. /c Process 6056 opening FIFO O_RDONLYProcess 6056 result 3 Process 6055 ---> file id: 3 producer write: ---> abcdefghijklmnopqrstuvwxyz1 //!> Note: The producer reads the written content. the producer writes the data: ---> abcdefghijklmnopqrstuvwxyz12 //!> That is to say, the pointer follows, and it is not read by the common file consumer: ---> abcdefghijklmnopqrstuvwxyz1 producer write: ---> abcdefghijklmnopqrstuvwxyz123 consumer read: ---> Producer write: ---> abcdefghijklmnopqrstuvwxyz123 producer write: ---> Consumer read: ---> abcdefghijklmnopqrstuvwxyz1234 producer write: ---> Consumer read: ---> Producer write: ---> AB Consumer read: ---> abcdefghijklmnopqrstuvwxyz123456 producer write: ---> abcdefghijklmnopqrstuvwxyz12345678 consumer read: ---> Producer write: ---> Consumer read: ---> abcdefghijklmnopqrstuvwxyz123456789Process 6055 finish... process 6056 finished, bytes read/n [1] + Done. /p 4. 1. introduction server should create 1 in a well-known path To listen to requests from all clients! Therefore, you can enable the read pipe port and the write port. for sub-processes, you only need to write data! However, in order to return the feedback from the server, the child process still needs pipe to accept the data fromserver; you can create it with your own ID! 2. Code: # include # Include # Include # Include # Include # Include # Include # Define SERVER_FIFO_NAME "/tmp/Linux/server_fifo" # define CLIENT_FIFO_NAME "/tmp/Linux/client _ % d_fifo" //!> Note that you need to create different FIFO records for different clients (which can be formatted according to your unique pid) # define BUFFER_SIZE PIPE_BUF # define MESSAGE_SIZE 20 # define NAME_SIZE 256 typedef structmessage/!> Message data structure {pid_tpid; chardata [MESSAGE_SIZE + 1];} message; # include "cs. h" int main () {intserver_fifo_fd; //!> Enable intclient_fifo_fd; //!> Open the client FIFO descriptor messagemsg; //!> Receives the client's request de information char * p; //!> This value is only for simple data processing. charclient_1_o_name [NAME_SIZE]; //!> First obtain the client's msg, obtain the client's pid, and splice it into the client's pid for feedback. if (access (server_kerbero_name, F_ OK) =-1) //!> If server's FIFO does not exist, create the FIFO file {if (mkfifo (server_1_o_name, 0777) =-1) //!> Create a server FIFO {printf ("Fail To Create server fifo"); exit (EXIT_FAILURE); //!> Failure }}server_incluo_fd = open (server_incluo_name, O_RDONLY); if (server_incluo_fd =-1) //!> Fail to open the fifo file {printf ("Failto open server_incluo_file"); exit (EXIT_FAILURE);} sleep (5); while (read (server_incluo_fd, & msg, sizeof (msg)> 0) //!> Exist themsg (mainly to obtain data for processing, and also to obtain the client's pid to obtain the feedback of the client's fifo pipe) {//!> Note: Here it must be that while is not if, because there are multiple clients, so a so-called endless loop (that is, when the last client is closed, it will end) p = msg. data; //!> Pointer processing (simple data processing) while (* p) //!> When the string has not ended {(* p) = toupper (* p); //!> Process uppercase letters (p ++;} sprintf (client_1_o_name, client_1_o_name, msg. pid); //!> Format the data to the standard client name client_javaso_fd = open (client_javaso_name, O_WRONLY); if (client_javaso_fd =-1) //!> Fait to open {printf ("Fait to open client FIFO... "); exit (EXIT_FAILURE);} write (client_kerbero_fd, & msg, sizeof (msg); //!> Write into client fifo close (client_1_o_fd);} close (server_1_o_fd); unlink (server_1_o_name); //!> Close the Link exit (EXIT_SUCCESS);} # include "cs. h "int main () {intserver_1_o_fd; intclient_1_o_fd; charclient_1_o_name [NAME_SIZE]; messagemsg; msg. pid = getpid (); sprintf (client_incluo_name, client_incluo_name, getpid (); //!> Format the client name if (access (client_kerbero_name, F_ OK) =-1) //!> Without this FIFO file, create {if (mkfifo (client_1_o_name, 0777) =-1) //!> Fail to create client fifo {printf ("Fail to create client fifo..."); exit (EXIT_FAILURE) ;}} server_incluo_fd = open (server_incluo_name, O_WRONLY); //!> Write content if (server_kerbero_fd =-1) {printf ("Failto open server fifo... "); exit (EXIT_FAILURE);} sprintf (msg. data, "hello from % d... ", msg. pid); //!> Formatting to msg waiting to send printf ("% d send the msg... ", getpid (); write (server_1_o_fd, & msg, sizeof (msg); close (server_1_o_fd); client_1_o_fd = open (client_1_o_name, O_RDONLY ); if (client_incluo_fd =-1) {printf ("Failto open client fifo... "); exit (EXIT_FAILURE);} if (read (client_incluo_fd, & msg, sizeof (msg)> 0) {printf (" \ nClient % d recived msg: ---> % s \ n ", msg. pid, msg. data);} close (c Lient_1_o_fd); unlink (client_1_o_name); exit (EXIT_SUCCESS);} Finally, the essence is to create a file as a swap zone! The result is to create a file, open the file, and operate the file... From the column in shanshanpt
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.