Last active
January 10, 2018 13:11
-
-
Save rightson/50a9dfb0e3e751d96143150e86a5fff6 to your computer and use it in GitHub Desktop.
Simple pipe and redirect
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <unistd.h> | |
#include <fcntl.h> | |
#include <stdio.h> | |
int main(int argc, char *argv[], char *envp[]) | |
{ | |
// goal: emulate the behavior of `ls -l | grep prog > output 2> errfile` | |
int outfd; | |
int errfd; | |
int pipefd[2]; | |
if (pipe(pipefd) < 0) { | |
perror("pipe"); | |
_exit(-1); | |
} | |
if (fork() == 0) { | |
dup2(pipefd[1], 1); | |
execlp("ls", "ls", "-l", NULL); | |
} | |
close(pipefd[1]); | |
if (fork() == 0) { | |
outfd = open("outfile", O_CREAT|O_WRONLY|O_TRUNC, 0755); | |
errfd = open("errfile", O_CREAT|O_WRONLY|O_TRUNC, 0755); | |
fcntl(outfd, F_SETFD, FD_CLOEXEC) | |
fcntl(errfd, F_SETFD, FD_CLOEXEC) | |
dup2(pipefd[0], 0); | |
dup2(outfd, 1); | |
dup2(errfd, 2); | |
execlp("grep", "grep", "prog", NULL); | |
} | |
close(pipefd[0]); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment