Question
Hello, I am working a simple c program runs in unix that will allows user to enter desire command and then ask user whether the
Hello, I am working a simple c program runs in unix that will allows user to enter desire command and then ask user whether the output should be re-directed to another command and if user enters Y, it will re-directe and prints output. Most of the parts were handled in other c file and I just need to implement this function and this is what I've got so far.
void execute_output_to_other(char *cmd1, char *const argv1[], char *cmd2_with_argv2) {
FILE *pipe = popen(cmd1, "r");
if (!pipe) {
perror("** Command failed **");
exit(1);
}
if (pipe == 0) {
close(1);
dup(fileno(pipe));
execv(cmd2_with_argv2, argv1);
}
char buffer[2048];
while (fgets(buffer, 2048, pipe)) {
fprintf(stderr,"WC: %s", buffer);
}
if (pclose(pipe) == -1) {
perror("pclose()");
exit(1);
}
fprintf(stderr, "** Command successful ** ");
exit(0);
}
example output on shell should be like this:
> Enter a command you want to run: /bin/ls -la > Should the output be re-directed to another command? [Y/N] Y > Enter that other command: /usr/bin/wc -l 11 ** Command successful **
In order to achieve it, I need to use popen(), pclose(), dup() for sure but stuck now. Any ideas about it? I only need to implement that function to make it run.
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started