The first program is a data producer program. It creates the pipeline when it is needed, and then writes the data to the pipeline as quickly as possible. For convenience, the program does not initialize the buffer.
producer Procedures
/* Data producer */#include <unistd.h> #include <stdlib.h> #include <stdio.h> #include <string.h># Include <fcntl.h> #include <limits.h> #include <sys/types.h> #include <sys/stat.h> #define FIFO _name "/tmp/my_fifo" #define Buffer_size pipe_buf#define ten_meg (1024x768 * 1024x768 *10) int main () {int pipe_fd; int res; int open_mode = o_wronly; int bytes_sent = 0; Char buffer[buffer_size + 1]; if (-1 = = Access (Fifo_name, F_OK)) {res = Mkfifo (fifo_name, 0777); //Create a FIFO if (0! = Res) { fprintf (stderr, "Could not create FIFO%s\n", fifo_name); Exit (Exit_failure); }} printf ("Process%d opening FIFO o_wronly\n", Getpid ()); PIPE_FD = open (Fifo_name, open_mode); printf ("Process%d result%d\n", Getpid (), PIPE_FD); if (-1! = PIPE_FD) {while (Bytes_sent < ten_meg) {res = write (pipe_fd, buffer, buffer_size); if (-1 = = res) {FPRintf (stderr, "Write error on pipe\n"); Exit (Exit_failure); } bytes_sent + = res; } close (PIPE_FD); } else exit (Exit_failure); printf ("Process%d finished\n", getpid ()); Exit (exit_success);}
Consumer Programs
The second program is a consumer program that reads data from the FIFO and discards them.
/* Data consumer */#include <unistd.h> #include <stdlib.h> #include <stdio.h> #include <string.h># Include <fcntl.h> #include <limits.h> #include <sys/types.h> #include <sys/stat.h> #define FIFO _name "/tmp/my_fifo" #define Buffer_size pipe_bufint Main () {int pipe_fd; int res; int open_mode = o_rdonly; int bytes_read = 0; Char buffer[buffer_size + 1]; memset (buffer, ' n ', sizeof (buffer)); printf ("Process%d opening FIFO o_rdonly\n", Getpid ()); PIPE_FD = open (Fifo_name, open_mode); printf ("Process%d result%d\n", Getpid (), PIPE_FD); if (-1! = pipe_fd) {do {res = read (pipe_fd, buffer, buffer_size); if (-1 = = res) {fprintf (stderr, "Write error on pipe\n"); Exit (Exit_failure); } Bytes_read + = res; }while (res>0); Close (PIPE_FD); } else exit (Exit_failure); printf ("Process%d finished,%d bytes reaD\n ", Getpid (), bytes_read); Exit (exit_success);}
Program Run Results
Using FIFO to implement interprocess communication examples