Inter Process Communication using named Pipes: FIFO - BunksAllowed

BunksAllowed is an effort to facilitate Self Learning process through the provision of quality tutorials.

Community

Inter Process Communication using named Pipes: FIFO

Share This
In the previous tutorial, we discussed how inter-process communication can be established, where both of the communicating processes have been started from a common ancestor process.

In this tutorial, we will discuss how two unrelated processes are able to communicate with each other.

To establish this kind of communication we can use named pipes, often known as FIFO. It's a special type of file that exists as a name in the file system.

In this context, we are developing two programs namely, main_process.c and child_process.c. The programs are shown below:

Source code of main_process.c
#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 NAMED_FIFO "/tmp/my_fifo" #define BUFFER_SIZE PIPE_BUF #define SIZE 1024 int main() { int pipe_file_desc; int result; int pipe_open_mode = O_WRONLY; int bytes_sent = 0; char buffer[BUFFER_SIZE + 1]; if (access(NAMED_FIFO, F_OK) == -1) { result = mkfifo(NAMED_FIFO, 0777); if (result != 0) { fprintf(stderr, "Could not create fifo %s\n", NAMED_FIFO); exit(EXIT_FAILURE); } } printf("Process %d opening FIFO O_WRONLY\n", getpid()); pipe_file_desc = open(NAMED_FIFO, pipe_open_mode); printf("Process %d result %d\n", getpid(), pipe_file_desc); if (pipe_file_desc != -1) { while(bytes_sent < SIZE) { result = write(pipe_file_desc, buffer, BUFFER_SIZE); if (result == -1) { fprintf(stderr, "Write error on pipe\n"); exit(EXIT_FAILURE); } bytes_sent += result; } (void)close(pipe_file_desc); } else { exit(EXIT_FAILURE); } printf("Process %d finished\n", getpid()); exit(EXIT_SUCCESS); }
Source code of child_process.c
#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 NAMED_FIFO "/tmp/my_fifo" #define BUFFER_SIZE PIPE_BUF int main() { int pipe_file_desc; int result; int pipe_open_mode = O_RDONLY; char buffer[BUFFER_SIZE + 1]; int bytes_read = 0; memset(buffer, '\0', sizeof(buffer)); printf("Process %d opening FIFO O_RDONLY\n", getpid()); pipe_file_desc = open(NAMED_FIFO, pipe_open_mode); printf("Process %d result %d\n", getpid(), pipe_file_desc); if (pipe_file_desc != -1) { do { result = read(pipe_file_desc, buffer, BUFFER_SIZE); bytes_read += result; } while (result > 0); (void)close(pipe_file_desc); } else { exit(EXIT_FAILURE); } printf("Process %d finished, %d bytes read\n", getpid(), bytes_read); exit(EXIT_SUCCESS); }


Happy Exploring!

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.