realtime/ex03/t04_multiple_children_pipes.c

95 lines
2.4 KiB
C

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
void writer_process(int fd_write, FILE *file) {
unsigned char c;
// Close the unused read end of the pipe
close(fd_write - 1); // fd[0] is read end, fd[1] is write end, so fd_write - 1 points to read end
// Write the file data byte by byte to the pipe
while (fread(&c, 1, 1, file) > 0) {
write(fd_write, &c, 1);
}
// Close the write end of the pipe after finishing
close(fd_write);
exit(0); // Exit after writing
}
void reader_process(int fd_read) {
unsigned char read_char;
int i = 1;
// Close the unused write end of the pipe
close(fd_read + 1); // fd[1] is write end, so fd_read + 1 points to write end
// Read from the pipe and print in hexadecimal format
while (read(fd_read, &read_char, 1) > 0) {
printf(" %02x", read_char);
if (++i > 16) { // Print 16 bytes per line
printf("\n");
i = 1;
}
}
printf("\n");
// Close the read end of the pipe after finishing
close(fd_read);
exit(0); // Exit after reading and printing
}
int main(int argc, char *argv[]) {
if (argc < 2) {
fprintf(stderr, "Usage: %s <filename>\n", argv[0]);
exit(1);
}
// Open the file in binary mode
FILE *file = fopen(argv[1], "rb");
if (file == NULL) {
fprintf(stderr, "Can't open file %s\n", argv[1]);
exit(1);
}
int fd[2];
if (pipe(fd) != 0) {
fprintf(stderr, "Error while creating pipe!\n");
exit(1);
}
// Fork writer process
pid_t writer_pid = fork();
if (writer_pid < 0) {
fprintf(stderr, "Failed to create writer process.\n");
exit(1);
} else if (writer_pid == 0) {
// Writer process logic
writer_process(fd[1], file);
}
// Close file in the parent after creating the writer
fclose(file);
// Fork reader process
pid_t reader_pid = fork();
if (reader_pid < 0) {
fprintf(stderr, "Failed to create reader process.\n");
exit(1);
} else if (reader_pid == 0) {
// Reader process logic
reader_process(fd[0]);
}
// In the father process: close both ends of the pipe
close(fd[0]);
close(fd[1]);
// Wait for both children to finish
waitpid(writer_pid, NULL, 0);
waitpid(reader_pid, NULL, 0);
return 0;
}