New paste Repaste Download
#include <iostream>
#include <unistd.h>
#include <sys/socket.h>
#include <cmath>
#include <cstring>
#include <vector>
#include <sys/wait.h>
void compute_subprocess(int fd) {
    while (true) {
        double number;
        ssize_t n = read(fd, &number, sizeof(number));
        if (n <= 0) break; // EOF or error
        double result = std::sqrt(number);
        write(fd, &result, sizeof(result));
    }
    close(fd);
}
int main() {
    std::vector<double> tasks = {4.0, 9.0, 16.0, 25.0};
    for (double number : tasks) {
        int fds[2];  // fds[0] <-> parent, fds[1] <-> child
        if (socketpair(AF_UNIX, SOCK_STREAM, 0, fds) == -1) {
            perror("socketpair");
            return 1;
        }
        pid_t pid = fork();
        if (pid == -1) {
            perror("fork");
            return 1;
        } else if (pid == 0) {
            // Child process
            close(fds[0]);  // Close parent's end
            compute_subprocess(fds[1]);
            return 0;
        } else {
            // Parent process
            close(fds[1]);  // Close child's end
            write(fds[0], &number, sizeof(number));
            double result;
            read(fds[0], &result, sizeof(result));
            std::cout << "sqrt(" << number << ") = " << result << std::endl;
            close(fds[0]);
            waitpid(pid, nullptr, 0);  // Wait for child to exit
        }
    }
    return 0;
}
Filename: None. Size: 1kb. View raw, , hex, or download this file.

This paste expires on 2025-05-11 11:17:25.778127. Pasted through web.