Files
djumbai/src/client/client.c
2024-05-11 17:32:12 +01:00

67 lines
1.5 KiB
C

#include "client.h"
#include <stdio.h>
int send_message(unsigned int sender, unsigned int receiver) {
int pipe_to_child[2];
if (pipe(pipe_to_child) == -1) {
perror("pipe");
exit(EXIT_FAILURE);
}
pid_t pid = fork();
if (pid == -1) {
perror("fork");
exit(EXIT_FAILURE);
}
if (pid == 0) { // Child process
close(pipe_to_child[1]); // Close write end of pipe
// Redirect stdin to read from pipe_to_child
dup2(pipe_to_child[0], STDIN_FILENO);
execlp("./bin/djumbai_client_send/djumbai_client_send", "djumbai_client_send", NULL);
close(pipe_to_child[0]);
// If execlp fails
perror("execlp");
exit(EXIT_FAILURE);
} else { // Parent process
close(pipe_to_child[0]); // Close read end of pipe
printf("Please enter your message (Max of %ld bytes):\n", MAX_CONTENT_SIZE - 1);
char content[MAX_CONTENT_SIZE];
fgets(content, MAX_CONTENT_SIZE, stdin);
message msg;
if (new_message(&msg, sender, 0, receiver, content) != 0) {
printf("Error when creating new message\n");
}
// Serialize the message
unsigned char buffer[MESSAGE_SIZE];
if (serialize_message(&msg, MESSAGE_SIZE, buffer) == -1) {
fprintf(stderr, "Error: Serialization failed\n");
return 1;
}
write(pipe_to_child[1], buffer, MESSAGE_SIZE);
// Close the write end of the pipe
close(pipe_to_child[1]);
// Wait for the child process to finish
wait(NULL);
}
return 0;
}
int main() {
// TODO: Client parsing to be done
unsigned int sender = getuid();
unsigned int receiver = 1000;
send_message(sender, receiver);
return 0;
}