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; } |
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 |