Fifo Explanation
Fifo Explanation
c
CopyEdit
#define FIFO_NAME "/tmp/my_fifo"
if (mkfifo(FIFO_NAME, 0666) == -1) {
perror("mkfifo");
exit(EXIT_FAILURE);
}
c
CopyEdit
printf("Enter a message to send to the child process: ");
if (fgets(buffer, MAX_MESSAGE_SIZE, stdin) == NULL) {
perror("fgets");
exit(EXIT_FAILURE);
}
buffer[strcspn(buffer, "\n")] = 0; // Remove trailing newline
c
CopyEdit
pid = fork();
if (pid == -1) {
perror("fork");
exit(EXIT_FAILURE);
}
c
CopyEdit
if (pid == 0) {
fifo_fd = open(FIFO_NAME, O_RDONLY); // Open FIFO for reading
if (fifo_fd == -1) {
perror("open");
exit(EXIT_FAILURE);
}
c
CopyEdit
else {
fifo_fd = open(FIFO_NAME, O_WRONLY); // Open FIFO for writing
if (fifo_fd == -1) {
perror("open");
exit(EXIT_FAILURE);
}
c
CopyEdit
unlink(FIFO_NAME);
Removes the FIFO file from the filesystem after use.
Summary of Execution
1. Parent Process
o Creates a named FIFO file (/tmp/my_fifo).
o Takes input from the user.
o Creates a child process.
o Writes the message into FIFO.
o Closes the FIFO file descriptor.
2. Child Process
o Opens FIFO for reading.
o Reads the message from FIFO.
o Prints the received message.
o Closes the FIFO file descriptor.
3. After execution, the FIFO file is deleted.
Example Output
css
CopyEdit
Enter a message to send to the child process: Hello, Child!
Parent (Writer) sent: Hello, Child!
Child (Reader) received: Hello, Child!