In: Computer Science
•Modify p4.c so that the output file p4.output is created but also displayed to standard output ( the screen ). This should be done by another instance of exec().
•Implement the pipe() command to do the following:
$> grep –o else p4.c | wc –l
p4.c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <fcntl.h>
#include <sys/wait.h>
int main(int argc, char *argv[]) {
int rc = fork();
if (rc < 0) {
// fork failed
fprintf(stderr, "fork failed\n");
exit(1);
} else if (rc == 0) {
// child: redirect standard output to a
file
close(STDOUT_FILENO);
open("./p4.output", O_CREAT|O_WRONLY|O_TRUNC,
S_IRWXU);
// now exec "wc"...
char *myargs[3];
myargs[0] = strdup("wc"); //
program: wc (word count)
myargs[1] = strdup("p4.c"); // arg: file to
count
myargs[2] =
NULL;
// mark end of array
execvp(myargs[0], myargs); // runs word
count
} else {
// parent goes down this path (main)
int rc_wait = wait(NULL);
}
return 0;
}
Done accordingly. Comment for further help. Please uprate.
CODE:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <fcntl.h>
#include <sys/wait.h>
int main(int argc, char *argv[]) {
int rc = fork();
int rc2=fork();
if (rc < 0) {
// fork failed
fprintf(stderr, "fork failed\n");
exit(1);
} else if (rc == 0) {
close(STDOUT_FILENO);
// child: redirect standard output to a file
open("./p4.output", O_CREAT|O_WRONLY|O_TRUNC, S_IRWXU);
// now exec "wc"...
char *myargs[3];
myargs[0] = strdup("wc"); // program: wc (word count)
myargs[1] = strdup("p4.c"); // arg: file to count
myargs[2] = NULL; // mark end of array
execvp(myargs[0], myargs); // runs word count
}else if (rc2==0){
char *myargs0[3];
myargs0[0] = strdup("wc"); // program: wc (word count)
myargs0[1] = strdup("p4.c"); // arg: file to count
myargs0[2] = NULL; // mark end of array
execvp(myargs0[0], myargs0); // runs word count
} else {
// parent goes down this path (main)
int rc_wait = wait(NULL);
}
return 0;
}
Output: