UNIXworkcode

/* * DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE * Version 2, December 2004 * * Copyright (C) 2016 Olaf Wintermann <olaf.wintermann@gmail.com> * * Everyone is permitted to copy and distribute verbatim or modified * copies of this license document, and changing it is allowed as long * as the name is changed. * * DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE * TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION * * 0. You just DO WHAT THE FUCK YOU WANT TO. */ #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <sys/types.h> #include <sys/wait.h> int main(int argc, char** argv) { int newin[2]; int newout[2]; int newerr[2]; if(pipe(newin) || pipe(newout) || pipe(newerr)) { perror("pipe"); return EXIT_FAILURE; } pid_t pid = fork(); if(pid == 0) { // child // we need stdin, stdout and stderr refer to the previously // created pipes if(dup2(newin[0], STDIN_FILENO) == -1) { perror("dup2"); return EXIT_FAILURE; } if(dup2(newout[1], STDOUT_FILENO) == -1) { perror("dup2"); return EXIT_FAILURE; } if(dup2(newerr[1], STDERR_FILENO) == -1) { perror("dup2"); return EXIT_FAILURE; } // we need to close this unused pipe // otherwise stdin cannot reach EOF close(newin[1]); // execute program return execl("/usr/bin/bc", "bc", NULL); // end of child process } else if(pid > 0) { // parent // close unused pipe endpoints close(newout[1]); close(newerr[1]); // write to child write(newin[1], "5+2\n", 4); close(newin[1]); // read from child char buf[64]; ssize_t r; while((r = read(newout[0], buf, 64)) > 0) { write(STDOUT_FILENO, buf, r); } int status = -1; waitpid(pid, &status, 0); printf("child status code: %d\n", status); // close all remaining pipes close(newin[0]); close(newout[0]); close(newerr[0]); } else { // error perror("fork"); return EXIT_FAILURE; } return (EXIT_SUCCESS); }