I had a similar question before. My parent process should send a string which contains characters. The child should receive the string and convert all characters into big characters. My problem is that my pipes aren't working at all. It doesn't receive any messages nor I am not sure if the messages are sent properly. Any advices how to use pipe between processes properly?
Thank you in advance
Here is my code:
#include <stdlib.h>
#include <stdio.h>
#include <signal.h>
#include <unistd.h>
#include <sys/types.h>
#include <string.h>
#define BUF 64
void recv_and_send(int fd1, int fd2){
char *buffer = malloc(sizeof(char)*BUF);
read(fd2, buffer, strlen(buffer));
for(int i = 0; i < strlen(buffer); i++){
if(buffer[i] < 123 && buffer[i] > 96) {
buffer[i] -= 32;
}
}
write(fd1, buffer, strlen(buffer));
free(buffer);
}
int main(void) {
pid_t pid;
int fd1[2], fd2[2];
pipe(fd1);
pipe(fd2);
char *buffer = malloc(sizeof(char)*BUF);
switch(pid = fork()) {
case -1:
perror("Error in fork()\n");
break;
case 0: //child
close(fd1[0]); //fd1[1] zum schreiben
close(fd2[1]); //fd2[0] zum lesen
recv_and_send(fd1[1], fd2[0]);
close(fd1[1]);
close(fd2[0]);
break;
default: //parent
close(fd1[1]); //fd1[0] zum lesen
close(fd2[0]); //fd2[1] zum schreiben
char string1[] = "a b c d";
strcpy(buffer, string1);
write(fd2[1], buffer, strlen(buffer));
memset(buffer, 0, BUF);
read(fd1[0], buffer, strlen(buffer));
printf("Die Großbuchstaben sind: %s\n", buffer);
break;
}
}
It would be really helpful if anyone has a working code example that shows how to use pipes between processes.