Write a program in C that creates a child and between father and child, there will be two-way communication using pipes. His father would read a file (whose name will give the user) and will send letters to the child. The child will count the number of words starting from 'a' if the number is, whether X is greater than 5, then the child will create his own child (grandchild). The grandchild of the establishment will send, by whatever means you deem possible, the grandfather * of X number and exit. * Note: Grandfather = initial process of the father, that father of his father's
I'm confused on elencho to count the 'a' and on how to set up the second and POS piping will send the result to his grandfather. If you reply me with the right code I 'll undestand it right once.
Τhank you.
Here is what I 've wrote so far:
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
main(){
int fd1[2],fd2[2], pid, pid2, ptr1, i, status, status2, count;
char arxeio[100];
char x;
char buf[1000];
char buf1[1000];
FILE *fp;
count = 0;
i = 0;
if (pipe(fd1) == -1){
perror("pipe");
exit(1);
}
pid = fork();
switch (pid)
{
case -1:
perror("Fork error\n");
exit(99); // in case of error
case 0:
close(fd1[1]);
for (i=0; i <= sizeof(buf); i++)
{
buf1[i] = read(fd1[0], buf, sizeof(buf));
//printf("%c\n", buf[i]);
}
i=0;
if (buf1[i] == 'a' ){ count++; i++;}
while( buf1[i] != '\0' )
{
if (buf1[i] == ' ')
{
if (buf1[i+1] == 'a')
{
count++;
i++;
}
}
i++;
}
printf("%d\n", count);
if (count > 5 )
{
if (pipe(fd2) == -1){
perror("pipe");
exit(1);
pid2 = fork();
switch (pid2)
{
case -1:
perror("Fork error\n");
exit(99); // in case of error
case 0:
close(fd2[1]);
status = read(fd2[0], count );
default:
close(fd2[0]);
write(fd2[0],count );
close(fd2[1]);
wait(&status);
}
}
exit(0);
default:
printf("Dwse onoma enos arxeiou...\n");
scanf("%s", arxeio);
close(fd1[0]);
fp = fopen(arxeio, "r");
getc(fp);
fclose(fp);
write(fd1[1], buf, sizeof(buf));
close(fd1[1]);
wait(&status); // waits till the child process ends
}
}