Due in 5 hours, Unix linux homework
my name is BAO TRUONG btw
in case you ahve to put the name
in the assignment
first name Bao, last name Truong
TwoPipesTwoChildren.cpp:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
int main(int argc, char **argv) {
int status;
char *cat_args[] = {"ls", "-ltr", NULL};
char *grep_args[] = {"grep", "3340", NULL};
char *wc_args[] = {"wc", "-l", NULL};
// create two pipea to send the output of "ls" process to "grep" process and to "wc" process
int pipe_A[2];
int pipe_B[2];
pipe(pipe_A);
pipe(pipe_B);
pid_t pid_A, pid_B;
//first child
if( !(pid_A = fork()) ) {
close(pipe_A[0]);
dup2(pipe_A[1], 1); /* redirect standard output to pipe_A write end */
close(pipe_A[1]);
execvp(*cat_args, cat_args);
exit(0);
}
//second child
else if( !(pid_B = fork()) ) {
close(pipe_A[1]);
dup2(pipe_A[0], 0); /* redirect standard input to pipe_A read end */
close(pipe_A[0]);
close(pipe_B[0]);
dup2(pipe_B[1], 1); /* redirect standard output to pipe_B write end */
close(pipe_B[1]);
execvp(*grep_args, grep_args);
}
//parent
else {
close(pipe_A[1]);
close(pipe_A[0]);
close(pipe_B[1]);
dup2(pipe_B[0], 0); /* redirect standard input to pipe_B read end */
close(pipe_B[0]);
execvp(*wc_args, wc_args);
}
close(pipe_B[1]);
close(pipe_B[0]);
return(0);
}
TwoPipesThreeChildren.cpp: #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <fcntl.h> #include <sys/types.h> #include <sys/stat.h> int main(int argc, char **argv) { int status; char *cat_args[] = {"ls", "-ltr", NULL}; char *grep_args[] = {"grep", "3340", NULL}; char *wc_args[] = {"wc", "-l", NULL}; // create two pipea to send the output of "ls" process to "grep" process and to "wc" process int pipe_A[2]; int pipe_B[2];
pipe(pipe_A);
pid_t pid_A, pid_B, pid_C; //first child if( !(pid_A = fork()) ) { close(pipe_A[0]); dup2(pipe_A[1], 1); /* redirect standard output to pipe_A write end */ close(pipe_A[1]); execvp(*cat_args, cat_args); exit(0); } pipe(pipe_B); //second child if( !(pid_B = fork()) ) { close(pipe_A[1]); dup2(pipe_A[0], 0); /* redirect standard input to pipe_A read end */ close(pipe_A[0]); close(pipe_B[0]); dup2(pipe_B[1], 1); /* redirect standard output to pipe_B write end */ close(pipe_B[1]); execvp(*grep_args, grep_args); } close(pipe_A[1]); close(pipe_A[0]); //third child if( !(pid_C = fork()) ) { close(pipe_B[1]); dup2(pipe_B[0], 0); /* redirect standard input to pipe_B read end */ close(pipe_B[0]); execvp(*wc_args, wc_args); } close(pipe_B[1]); close(pipe_B[0]); return(0); }