I need to make a child process and create two pipes each going one way between the parent and child process. I have to send a message ("Greetings") to the child byte by byte which reads it byte by byte and then converts the chars to uppercase and sends the message back to the parent in the same fashion. I am having trouble with the pipe aspect of it, my program works with one pipe and then I tried to add a pipe and got this.
Code:
#include <sys/types.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <stdlib.h>
#define BUFFER_SIZE 25
#define READ_END 0
#define WRITE_END 1
#define READ_END2 0
#define WRITE_END2 1
int main(void)
{
int ch = 0;
int ch2 = 0;
char write_msg[BUFFER_SIZE] = "Greetings";
char write_msg2[BUFFER_SIZE];
char read_msg[BUFFER_SIZE];
int fd[2];
int fd2[2];
pid_t pid;
if (pipe(fd) == -1) {
fprintf(stderr, "Pipe failed");
return 1;
}
if (pipe(fd2) == -1) {
fprintf(stderr, "Pipe failed");
return 1;
}
pid = fork();
if (pid < 0) {
fprintf(stderr, "Fork failed");
return 1;
}
if (pid>0){
close(fd[READ_END]);
close(fd2[WRITE_END2]);
while (write_msg[ch] != 0)
{
write(fd[WRITE_END], &write_msg[ch], strlen(write_msg)+1);
ch++;
}
close(fd[WRITE_END]);
while (read_msg[ch] != 0)
{
read(fd2[READ_END2], &read_msg[ch2], 1);
printf("%c", read_msg[ch2]);
if (ch2%2 == 0) {
ch2++;
}
}
}
else {
close(fd[WRITE_END]);
close(fd2[READ_END2]);
ch = 0;
ch2 =0;
while (read_msg[ch] != 0)
{
read(fd[READ_END], &read_msg[ch], 1);
write_msg2[ch] = toupper(&read_msg[ch]);
printf("%c", read_msg[ch]);
if (ch%2 == 0) {
ch++;
}
}
while (write_msg2[ch2] != 0)
{
write(fd2[WRITE_END2], &write_msg2[ch2], strlen(write_msg2)+1);
ch2++;
}
close(fd2[READ_END]);
}
return 0;
}