Today, we try to send a message through FIFO file from one program to another program.
(write)file_send|>>----------------file_fifo.txt----------------------->>|file_recv(read)
Sender Script
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | #include<stdio.h> #include<stdlib.h> #include<string.h> #include<fcntl.h> int main() { char fil[15]="file_fifo.txt"; char wrch[20]; int siz=20; memset(wrch,'\0',siz); strcpy(wrch,"hello world"); int fd = open(fil,O_WRONLY); int cw=write(fd,wrch,siz); printf("Sender: write -%s- of %d chars to %s\n",wrch,cw,fil); return 0; } |
Lets breakdown the script
- Line 8: Take the fifo file into a string
- Line 10-14: Initialize the string with "hello world"
- Line 16: Open the file in write only mode
- Line 17: Send the text
Receiver Script
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | #include<stdio.h> #include<stdlib.h> #include<fcntl.h> int main() { char fil[15]="file_fifo.txt"; mkfifo(fil,0666); char rdch[20]; int siz=20; int fd = open(fil,O_RDONLY); printf("Receiver: Waiting for message from Sender\n"); int rd=read(fd,rdch,siz); printf("Receiver: read -%s- of %d chars to %s\n",rdch,rd,fil); return 0; } |
Lets breakdown the script
- Line 8-9: Create a fifo file using mkfifo function. As receiver is to the executed before sender, we have to create fifo file here.
- Line 11-12: Initialize character array to read the message from Sender program.
- Line 14: Open the fifo file in read only mode
- Line 16: Read the message from sender into rdch string
Execution
Start the receiver first. It will be blocked waiting for message from Sender.
1 2 3 | # gcc fifo-recv.c -o fifo-recv # ./fifo-recv Receiver: Waiting for message from Sender |
Start the sender in another terminal. It will send the message.
1 2 3 | # gcc fifo-send.c -o fifo-send # ./fifo-send Sender: write -hello world- of 20 chars to file_fifo.txt |
Verify in the receiver terminal, receive program would have received the message.
1 2 3 4 | # gcc fifo-recv.c -o fifo-recv # ./fifo-recv Receiver: Waiting for message from Sender Receiver: read -hello world- of 20 chars to file_fifo.txt |
No comments:
Post a Comment