pipe_demo.c

Download
c 95 lines 2.3 KB
 1/**
 2 * Pipe Demo: Parent-child bidirectional communication
 3 *
 4 * Demonstrates two-pipe pattern for bidirectional IPC.
 5 * Parent sends a task, child processes it and replies.
 6 *
 7 * Build: make
 8 * Usage: ./pipe_demo
 9 */
10
11#include <stdio.h>
12#include <stdlib.h>
13#include <string.h>
14#include <ctype.h>
15#include <unistd.h>
16#include <sys/wait.h>
17
18#define BUF_SIZE 256
19
20/* Convert string to uppercase (child's task) */
21static void to_upper(char *str) {
22    for (int i = 0; str[i]; i++)
23        str[i] = toupper((unsigned char)str[i]);
24}
25
26int main(void) {
27    int parent_to_child[2];  /* Parent writes, child reads */
28    int child_to_parent[2];  /* Child writes, parent reads */
29
30    if (pipe(parent_to_child) < 0 || pipe(child_to_parent) < 0) {
31        perror("pipe");
32        exit(EXIT_FAILURE);
33    }
34
35    pid_t pid = fork();
36    if (pid < 0) {
37        perror("fork");
38        exit(EXIT_FAILURE);
39    }
40
41    if (pid == 0) {
42        /* === Child process === */
43        close(parent_to_child[1]);  /* Close write end */
44        close(child_to_parent[0]);  /* Close read end */
45
46        char buffer[BUF_SIZE];
47        ssize_t n;
48
49        while ((n = read(parent_to_child[0], buffer, BUF_SIZE - 1)) > 0) {
50            buffer[n] = '\0';
51            printf("[Child PID=%d] Received: \"%s\"\n", getpid(), buffer);
52
53            to_upper(buffer);
54            write(child_to_parent[1], buffer, strlen(buffer));
55        }
56
57        close(parent_to_child[0]);
58        close(child_to_parent[1]);
59        exit(EXIT_SUCCESS);
60    }
61
62    /* === Parent process === */
63    close(parent_to_child[0]);  /* Close read end */
64    close(child_to_parent[1]);  /* Close write end */
65
66    const char *messages[] = {
67        "hello world",
68        "pipe communication",
69        "inter-process messaging"
70    };
71
72    char reply[BUF_SIZE];
73
74    for (int i = 0; i < 3; i++) {
75        printf("[Parent] Sending: \"%s\"\n", messages[i]);
76        write(parent_to_child[1], messages[i], strlen(messages[i]));
77
78        /* Small delay to let child process */
79        usleep(50000);
80
81        ssize_t n = read(child_to_parent[0], reply, BUF_SIZE - 1);
82        if (n > 0) {
83            reply[n] = '\0';
84            printf("[Parent] Reply:   \"%s\"\n\n", reply);
85        }
86    }
87
88    close(parent_to_child[1]);
89    close(child_to_parent[0]);
90    wait(NULL);
91
92    printf("Done!\n");
93    return 0;
94}