Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Hello, I am working a simple c program runs in unix that will allows user to ent

ID: 3587978 • Letter: H

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 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.

Explanation / Answer

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);

}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote