Skip to content

Instantly share code, notes, and snippets.

@mutsune
Last active October 17, 2021 12:22
Show Gist options
  • Save mutsune/eda02f1790e6c705a2d27c51f92b57db to your computer and use it in GitHub Desktop.
Save mutsune/eda02f1790e6c705a2d27c51f92b57db to your computer and use it in GitHub Desktop.
pipe and redirect implement
foo
bar
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
int main()
{
int pipefd[2];
int pid;
char *cat_args[] = {"cat", "in", NULL};
char *grep_args[] = {"grep", "foo", NULL};
pipe(pipefd);
pid = fork();
if (pid == 0)
{
dup2(pipefd[0], STDIN_FILENO);
close(pipefd[1]);
execvp("grep", grep_args);
}
else
{
dup2(pipefd[1], STDOUT_FILENO);
close(pipefd[0]);
execvp("cat", cat_args);
}
}
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
int main()
{
int in, out;
char *grep_args[] = {"grep", "foo", NULL};
in = open("in", O_RDONLY);
out = open("out", O_WRONLY | O_CREAT, S_IRUSR | S_IRGRP | S_IWGRP | S_IWUSR);
dup2(in, STDIN_FILENO);
dup2(out, STDOUT_FILENO);
close(in);
close(out);
execvp("grep", grep_args);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment