Skip to content

Instantly share code, notes, and snippets.

@jbreams
Created April 13, 2016 19:05
Show Gist options
  • Save jbreams/4464a02441ae866b0ecf18decfdb6ce3 to your computer and use it in GitHub Desktop.
Save jbreams/4464a02441ae866b0ecf18decfdb6ce3 to your computer and use it in GitHub Desktop.
#include <assert.h>
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/wait.h>
#include <unistd.h>
const char stringToPrint[] = "Hello, world!\n";
int main() {
int pipes[2];
assert(pipe(pipes) != -1);
pid_t pid = fork();
if (pid == 0) {
close(pipes[0]);
assert(dup2(pipes[1], fileno(stdout)) != -1);
assert(dup2(pipes[1], fileno(stderr)) != -1);
write(fileno(stdout), stringToPrint, strlen(stringToPrint));
_exit(0);
}
close(pipes[1]);
while(1) {
char buf[sizeof(stringToPrint) - 1];
memset(buf, 0, sizeof(buf));
ssize_t err = read(pipes[0], buf, sizeof(buf));
if (err == -1) {
fprintf(stderr, "could not read from pipe: %s", strerror(errno));
return 1;
}
if (err > 0)
puts(buf);
else
break;
fflush(stdout);
}
int status;
assert(waitpid(pid, &status, 0) != -1);
printf("child exited: %d" , WEXITSTATUS(status));
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment