==============================================================
  Experiment 06: IPC Using Pipes
==============================================================
  [Back to Index]
--------------------------------------------------------------

THEORY:
  A pipe allows one process to send data to another
  (unidirectional). Created using pipe() system call.

  fd[0] = Read end
  fd[1] = Write end

  System Calls:
    pipe()  - Create communication channel
    fork()  - Create child process
    write() - Send data through pipe
    read()  - Receive data from pipe

  AIM: Two processes cooperate to evaluate sqrt(b^2 - 4ac)
    - Child computes 4ac, sends to parent via pipe
    - Parent computes b^2, receives 4ac, calculates result

--------------------------------------------------------------

SOURCE CODE: pipe_expression.c

--------------------------------------------------------------
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <math.h>
#include <stdlib.h>

int main() {

    int fd[2];
    pid_t pid;

    int a, b, c;
    int fourac;
    int bsquare;
    double result;

    printf("Enter values of a, b and c: ");
    scanf("%d %d %d", &a, &b, &c);

    // Create pipe
    pipe(fd);

    // Create child process
    pid = fork();

    if (pid < 0) {
        printf("Fork failed\n");
        return 1;
    }

    // Child Process
    if (pid == 0) {

        close(fd[0]); // Close read end

        fourac = 4 * a * c;

        // Send value to parent
        write(fd[1], &fourac, sizeof(fourac));

        close(fd[1]);
    }

    // Parent Process
    else {

        close(fd[1]); // Close write end

        bsquare = b * b;

        // Read value from child
        read(fd[0], &fourac, sizeof(fourac));

        result = sqrt(bsquare - fourac);

        printf("Value of sqrt(b^2 - 4ac) = %.2lf\n", result);

        close(fd[0]);
    }

    return 0;
}
--------------------------------------------------------------

==============================================================
  [Prev: Exp 05]  |  [Next: Exp 07]
==============================================================