
Jeffrey R. answered 10/24/24
30+ Years of IT Expertise: Networking, Cybersecurity, Client/Serv
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <string.h>
#define BUFFER_SIZE 4096 // Define buffer size for reading/writing
void error_exit(const char *msg) {
perror(msg);
exit(EXIT_FAILURE);
}
int main(int argc, char *argv[]) {
if (argc != 3) {
fprintf(stderr, "Usage: %s <source_file> <destination_file>\n", argv[0]);
exit(EXIT_FAILURE);
}
int pipefd[2];
pid_t pid;
// Create a pipe
if (pipe(pipefd) == -1) {
error_exit("pipe");
}
// Fork a new process
pid = fork();
if (pid == -1) {
error_exit("fork");
}
if (pid > 0) {
// Parent process: reads from source file and writes to pipe
// Close the reading end of the pipe
close(pipefd[0]);
// Open source file for reading
int src_fd = open(argv[1], O_RDONLY);
if (src_fd == -1) {
error_exit("open source file");
}
// Read from source file and write to pipe
char buffer[BUFFER_SIZE];
ssize_t bytes_read, bytes_written;
while ((bytes_read = read(src_fd, buffer, sizeof(buffer))) > 0) {
bytes_written = write(pipefd[1], buffer, bytes_read);
if (bytes_written == -1) {
error_exit("write to pipe");
}
}
if (bytes_read == -1) {
error_exit("read from source file");
}
// Close the source file and the writing end of the pipe
close(src_fd);
close(pipefd[1]);
// Wait for child to finish
wait(NULL);
} else {
// Child process: reads from pipe and writes to destination file
// Close the writing end of the pipe
close(pipefd[1]);
// Open destination file for writing (create if it doesn't exist, truncate if it does)
int dest_fd = open(argv[2], O_WRONLY | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR);
if (dest_fd == -1) {
error_exit("open destination file");
}
// Read from pipe and write to destination file
char buffer[BUFFER_SIZE];
ssize_t bytes_read, bytes_written;
while ((bytes_read = read(pipefd[0], buffer, sizeof(buffer))) > 0) {
bytes_written = write(dest_fd, buffer, bytes_read);
if (bytes_written == -1) {
error_exit("write to destination file");
}
}
if (bytes_read == -1) {
error_exit("read from pipe");
}
// Close the destination file and the reading end of the pipe
close(dest_fd);
close(pipefd[0]);
exit(EXIT_SUCCESS);
}
return 0;
}

Jeffrey R.
Here's an idea and example for you that may help. It uses ordinary pipes for inter-process communication between a parent process (which reads the content from the source file and writes it to the pipe) and a child process (which reads from the pipe and writes to the destination file. Compilation: Compile the program using gcc: gcc -o pipe_filecopy pipe_filecopy.c Usage: Run the program by specifying the source file and the destination file: ./pipe_filecopy input.txt copy.txt This will copy the contents of input.txt to copy.txt using pipes for inter-process communication10/24/24