Today, we replicate whatever we did on Pipes-Basic using FiFo. It is a pipe, but a name assigned to it. If I have a pipe, I can access only within the program, forked program and its decendants. I have to call it using integer array.
If I have a fifo, I can access it just like any other file. I can pass the information from one program to another. Now, we pass information from parent to child and then from child to parent using 2 FIFO files.
(read)child|<<----------------file_p2c.txt-----------------------<<|parent(write)
(write)parent|>>----------------file_c2p.txt----------------------->>|child(read)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45 | #include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<unistd.h>
#include<fcntl.h>
int main()
{
char p2c[15]="file_p2c.txt";
char c2p[15]="file_c2p.txt";
mkfifo(p2c,0666);
mkfifo(c2p,0666);
char wrch[20],rdch[20];
int siz=20;
memset(wrch,'\0',siz);
strcpy(wrch,"hello world");
pid_t id=fork();
if(id != 0)
{
int wfd = open(p2c,O_WRONLY);
int cw=write(wfd,wrch,siz);
printf("write -%s- of %d chars to %s\n",wrch,cw,p2c);
int rfd = open(c2p,O_RDONLY);
int cr=read(rfd,rdch,siz);
printf("read -%s- of %d chars from %s\n",rdch,cr,c2p);
wait(id,NULL,0);
} else {
int rfd = open(p2c,O_RDONLY);
int cr=read(rfd,rdch,siz);
printf("Read -%s- of %d chars from %s\n",rdch,cr,p2c);
printf("Sleeping for 5 seconds\n");
sleep(5);
int wfd = open(c2p,O_WRONLY);
int cw=write(wfd,wrch,siz);
printf("write -%s- of %d chars to %s\n",wrch,cw,c2p);
}
return 0;
}
|
Lets get into breaking down the code:
Creating FiFo files (#9 to #12)
Use mkfifo procedure to create 2 fifo files with 666 permission(read and write and not execute for all)
Initializing string buffers (#14 to #18)
Create 2 read and write strings. Initialize write string with "hello world"
Fork a child (#20)
Opening FiFO files;parent to child (#23, #33)
Parent opens the file_p2c.txt in write mode, child opens file_p2c.txt in read mode
Send traffic; parent to child(#24,#25,#34,#35)
Parent writes the wrch string and child reads into rdch string.
Sleep for 5 seconds(#38)
Opening FiFO files; child to parent(#27, #40)
Child opens the file_c2p.txt in write mode, parent opens file_c2p.txt in read mode
Send traffic; child to parent(#28,#29,#41,#42)
Child writes the wrch string and parent reads into rdch string.
Harvest Time
When this program is run
1
2
3
4
5
6 | # ./a.out
write -hello world- of 20 chars to file_p2c.txt
Read -hello world- of 20 chars from file_p2c.txt
Sleeping for 5 seconds
write -hello world- of 20 chars to file_c2p.txt
read -hello world- of 20 chars from file_c2p.txt
|
Observe that first 2 lines, we transfer data from parent to child. Sleep for 5 seconds and then transfer the same string from child to parent.