I have this assignment where I have to create a program on C/C++ for linux, where it sends a string char by char from one process to another, and when the second process receives the characters it uppercase them.
This is the code I wrote, if someone can tell me if the sharing process is done right or I'm missing something.
#include <iostream.h>
#include <stdio.h>
#include <string.h>
int main(int argc, char *argv[]) {
int childpid;
char *string = "Hello";
char *letter;
childpid = fork();
if(childpid == 0) {
for (int i = 0; i<string.length; i++) {
letter = string[i];
printf(letter);
}
} else {
read(letter);
printf(letter.toupper());
}
return 0;
}
Code update:
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <unistd.h>
int main(int argc, char *argv[]) {
pid_t pid;
int mypipe[2];
int ret;
char *string = "Hello";
char *buf[20];
int bytesread;
ret = pipe(mypipe);
if(ret == -1) {
perro("Pipe failed");
exit(1);
}
pid = fork();
if(pid == 0) {
for(var i = 0; i<string.length; i++) {
write(mypipe[1],string[i],1);
}
} else {
while( (bytesread = read(mypipe[0],buf,15)) > 0)
{
buf[bytesread] = '\0';
printf("buf: %s\n", buf.toupper());
}
}
return 0;
}
pipeanddup2.man 2 pipein a terminal.readin loop. You'll probably be ok in this toy example but you are not guaranteed to get your entire read request in one call. (2) close your pipe ends. It's not just good hygiene, it's how EOF is sent to the other side.