#include #include #include #include #include #include #define SIZE 65536 int main(int argc, char *argv[]) { int pipefd[2]; // pipefd[0] represents input stream id, pipefd[1] represents output stream id. char buffer[SIZE]; // The buffer of main process. char childBuffer[SIZE]; // The buffer of sub-process. // If the number of arguments is not correct. if (argc != 3) { perror("Main: main [target] [destination].\n"); return 1; } char *srcFile = argv[1]; // Source char *dstFile = argv[2]; // Destination // Building a pipe. If the returned integer is less than 0, if (pipe(pipefd) < 0) { printf("An error occured when createing the pipe: %s\n", strerror(errno)); return 1; } pid_t pid = fork(); // Create a sub-process. if (pid == 0) { // pid == 0 represents it's a sub-process. close(pipefd[1]); // Close pipefd[1] ssize_t file_size = read(pipefd[0], childBuffer, sizeof(childBuffer)); // Get the size of child close(pipefd[0]); // Close pipefd[0] since it is unable to use. int dst_file_fd = open(dstFile, O_CREAT | O_WRONLY); // Read a file in writeonly mode. If the file does not exit, create a new one. write(dst_file_fd, childBuffer, file_size); // Write data from buffer into fd. close(dst_file_fd); // Close file } else if (pid > 0) { // pid > 0 represents it's a main process. close(pipefd[0]); // Close pipefd[0] int target_file_fd = open(srcFile, O_RDONLY); // Open a file in readonly mode. ssize_t file_size = read(target_file_fd, buffer, sizeof(buffer)); // Get size of the file write(pipefd[1], buffer, file_size); // Write data from buffer into pipefd[1] close(pipefd[1]); // Close pipefd[1] close(target_file_fd); // Close file } else { // When error occur printf("An error occured when forking child process. %s\n", strerror(errno)); return 1; } return 0; }