Wednesday, November 23, 2005
AOS Exercise 1
用pipe()與dup()寫出 ps aux | grep ghhwang | wc > foo 的效果
#include <stdio.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#define READ 0
#define WRITE 1
#define STDIN 0
#define STDOUT 1
int main() {
int pid_1, pid_2, pid_3, pfd_1[2], pfd_2[2], fd;
pipe(pfd_1);
pipe(pfd_2);
if( (pid_1 = fork()) != 0 ) {
if( (pid_2 = fork()) != 0 ) {
if( (pid_3 = fork()) != 0 ) {
close(pfd_1[READ]);
close(pfd_1[WRITE]);
close(pfd_2[READ]);
close(pfd_2[WRITE]);
wait((int *)0);
wait((int *)0);
wait((int *)0);
}
else {
close(STDIN);
dup(pfd_2[READ]);
close(pfd_1[READ]);
close(pfd_1[WRITE]);
close(pfd_2[READ]);
close(pfd_2[WRITE]);
fd = open("foo", O_WRONLY | O_CREAT, S_IREAD | S_IWRITE);
close(STDOUT);
dup(fd);
close(fd);
execl("/bin/wc", "wc", (char *)NULL);
}
}
else {
close(STDIN);
close(STDOUT);
dup(pfd_1[READ]);
dup(pfd_2[WRITE]);
close(pfd_1[READ]);
close(pfd_1[WRITE]);
close(pfd_2[READ]);
close(pfd_2[WRITE]);
execl("/bin/grep", "grep", "ghhwang", (char *)NULL);
}
}
else {
close(STDOUT);
dup(pfd_1[WRITE]);
close(pfd_1[READ]);
close(pfd_1[WRITE]);
close(pfd_2[READ]);
close(pfd_2[WRITE]);
execl("/bin/ps", "ps", "aux", (char *)NULL);
}
exit(0);
}



