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

The following command is executed at the prompt: ps -A | grep firefox Show how t

ID: 3852325 • Letter: T

Question

The following command is executed at the prompt: ps -A | grep firefox Show how to implement the pipe above, by using the system calls: fork(2), execvp (3), pipe(2), close(2), and dup2(2). The system call execvp(3) is defined by: int execvp(const char* cmd, char* const argv []) Where cmd is the name of the file to be executed: and argv is an array of parameters to be passed to the command. (The last element of the array must be NULL.) Structure your solution like this skeleton: int main() { //Variable declarations here //Create pipe //Execute ps -A //Execute grep firefox //sleep (1) (instead of waiting for the commands to finish) }

Explanation / Answer


#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>

int main(int argc,char **argv)
{
int fd[2];
pid_t pd;
pipe(fd);
pd=fork();

if (pd == -1)
{
perror("Error forking...");
exit(1);
}
if (pd) //grep fireofx
{
wait(&pd);   
close(fd[1]);
close(0); //stdin closed
dup2(fd[0],0);
   char *execArgs[] = { "grep", "firefox", NULL };
execvp(execArgs[0], execArgs);
  

}
if (pd==0) //ps -A
{
close(fd[0]);   
close(1);   
dup2(fd[1],1);
   char *execArgs[] = { "ps", "-A", NULL };
execvp(execArgs[0], execArgs);
  

}


return 0;
}

===============================================

Output:

akshay@akshay-Inspiron-3537:~$ gcc grep.c
akshay@akshay-Inspiron-3537:~$ ./a.out
17466 ? 00:00:17 firefox

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