#include #include #include #include int main(void) { // fork creates 2 identical copies of the program // only return value is different printf("This is the start of the program.\n"); int p[2]; if (pipe(p) == -1) { // reader reads from p[0] perror("pipe"); // writer writes to p[1] return 1; } pid_t pid = fork(); if (pid == -1) { perror("fork"); // print why the fork failed return 1; } else if (pid == 0) { close(p[0]); // Close unused read end in child FILE *f = fdopen(p[1], "w"); if (f == NULL) { perror("fdopen"); return 1; } printf("I am the child because fork() returned %d.\n", pid); fprintf(f, "hello parent\n"); fclose(f); close(p[1]); // Close write end after use } else { close(p[1]); // Close unused write end in parent FILE *f = fdopen(p[0], "r"); if (f == NULL) { perror("fdopen"); return 1; } printf("I am the parent because fork() returned %d.\n", pid); char buf[256]; if (fgets(buf, sizeof(buf), f) != NULL) { printf("I got this message from the child: %s", buf); } else { perror("fgets"); } fclose(f); close(p[0]); // Close read end after use wait(NULL); // Wait for child process to terminate } return 0; }