I have simulated the conversation between a caller and receiver using fork and pipe. The parent process is the receiver and the child process is the caller. Each message is terminated by a newline.
The program seems to be running correctly. Should I take care of any other condition?
#include <stdio.h>
#include <string.h>
#include <stdbool.h>
#include <sys/types.h>
#include <unistd.h>
#define BUF_LEN 512
#define READ_END 0
#define WRITE_END 1
int main()
{
int fd[2];
if (pipe(fd) == -1) {
fprintf(stderr, "Pipe failed");
return 1;
}
pid_t pid = fork();
if (pid < 0) {
fprintf(stderr, "Fork failed");
return 1;
}
// the parent process is the receiver
if (pid > 0) {
close(fd[WRITE_END]);
char buffer[BUF_LEN + 1] = "";
bool end_call = false;
do {
// strcpy(buffer, "");
if (read(fd[READ_END], buffer, sizeof buffer) != 0) {
// char *start = buffer;
char msg[BUF_LEN + 1] = "";
char *end = buffer;
int i = strlen(msg);
while (*end) {
msg[i++] = *(end++);
msg[i] = '\0';
if (msg[strlen(msg) - 1] == '\n') {
printf("Receiver: Received %s", msg);
if (!strcmp(msg, "Bye!\n")) {
end_call = true;
}
strcpy(msg, "");
i = strlen(msg);
}
}
// if (strcmp(buffer, "")) {
// printf("Received %s", buffer);
// }
}
} while (!end_call);
close(fd[READ_END]);
} else {
close(fd[READ_END]);
// const char *msg = "Hello";
char buffer[BUF_LEN + 1] = "";
bool end_call = false;
printf("Caller: Enter messages to be sent to the receiver."
"(\"Bye!\" to end call)\n");
do {
// printf("Caller: ");
fgets(buffer, sizeof buffer, stdin);
if (!strcmp(buffer, "Bye!\n")) {
end_call = true;
}
// printf("Sent %s\n", buffer);
write(fd[WRITE_END], buffer, strlen(buffer) + 1);
} while (!end_call);
close(fd[WRITE_END]);
}
return 0;
}