#include <stdio.h>
#include <fcntl.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
#define STDIN 0
#define STDOUT 1
int main(int argc, char* argv[]) {
int channel[2] = {0};
int STDOUT_BACKUP = dup(STDOUT);
int STDIN_BACKUP = dup(STDIN);
pipe(channel);
int ret = fork();
if (ret) {
close(channel[1]);
wait(NULL);
dup2(channel[0], STDIN);
int destFile = open("./r.txt", O_CREAT|O_WRONLY, S_IRUSR);
dup2(destFile, STDOUT);
if (!fork()) {
execlp("wc", "wc", "-l", NULL);
} else {
wait(NULL);
dup2(STDOUT_BACKUP, STDOUT);
dup2(STDIN_BACKUP, STDIN);
close(destFile);
close(channel[0]);
execlp("ls", "ls", "-l", NULL);
fflush(NULL);
}
} else {
close(channel[0]);
int fromFile = open("/etc/passwd", O_RDONLY);
dup2(fromFile, STDIN);
dup2(channel[1], STDOUT);
close(fromFile);
close(channel[1]);
execlp("grep", "grep", "-v", "usr", NULL);
}
return 0;
}