Вот что должен делать мой код:
Ребенок должен:
1. Посылать символ в родительский
2. Получать целое число от родительского и печатать его
Родитель должен:
1. Прочитать символ, отправленный от ребенка, и распечатать его
2. Привести его к целому числу и отправить результат ребенку
Вот код, который я написал :
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<sys/types.h>
#include<string.h>
#include<sys/wait.h>
int main()
{
int fd1[2];
int fd2[2];
pid_t p;
if (pipe(fd1)==-1)
{
fprintf(stderr, "Pipe Failed" );
return 1;
}
if (pipe(fd2)==-1)
{
fprintf(stderr, "Pipe Failed" );
return 1;
}
p = fork();
if (p<0)
{
fprintf(stderr, "fork Failed" );
return 1;
}
if (p==0){
char c='a';
int received;
close(fd1[0]);
write(fd1[1], c, sizeof(char));
close(fd1[1]);
close(fd2[1]);
read(fd2[0], received, sizeof(int));
printf("Printing from child ");
printf(" ");
printf("%d", received);
close(fd2[0]);
}
if (p >0)
{
char received;
close(fd1[1]);
read(fd1[0], received, sizeof(char));
printf("Printing from parent ");
printf(" ");
printf("%c", received);
close(fd1[0]);
close(fd2[0]);
int test=(int)received;
write(fd2[1], test, sizeof(test));
close(fd2[1]);
}
}
Мой текущий вывод следующий: Печать из родительского элемента Печать из дочернего элемента 0
Я предполагаю, что родительский элемент читает из канала перед тем, как дочерний элемент пишет в него, как исправить что?