#include<stdio.h> #include<stdlib.h> #include<string.h> #include<sys/types.h> #include<sys/wait.h> #include<unistd.h> intmain() { //define pipe int fd_parent[2]; int fd_child[2]; char first_str[] = "humb1e"; char second_str[]="hacked_by_"; pid_t p; //check if create successfully if (pipe(fd_parent) == -1) { fprintf(stderr, "Pipe Failed"); return1; } if (pipe(fd_child) == -1) { fprintf(stderr, "Pipe Failed"); return1; } p = fork(); if (p < 0) { fprintf(stderr, "fork Failed"); return1; } // Parent process elseif (p > 0) { char concat_str[100];
close(fd_parent[0]); // Close reading end of first pipe
// Write input string and close writing end of first // pipe. write(fd_parent[1], second_str, strlen(second_str) + 1); close(fd_parent[1]);
// Wait for child to send a string wait(NULL);
close(fd_child[1]); // Close writing end of second pipe
// Read string from child, print it and close // reading end. read(fd_child[0], concat_str, 100); printf("Concatenated string:%s\n", concat_str); close(fd_child[0]); }
// child process else { close(fd_parent[1]); // Close writing end of first pipe
// Read a string using first pipe char concat_str[100]; read(fd_parent[0], concat_str, 100);
// Concatenate a fixed string with it int k = strlen(concat_str); int i; for (i = 0; i < strlen(first_str); i++) concat_str[k++] = first_str[i];
concat_str[k] = '\0'; // string ends with '\0'
// Close both reading ends close(fd_parent[0]); close(fd_child[0]);
// Write concatenated string and close writing end write(fd_child[1], concat_str, strlen(concat_str) + 1); close(fd_child[1]);