Question

Write a program in C called minishell that creates two child processes: one to execute 'ls...

Write a program in C called minishell that creates two child processes: one to execute 'ls -al' and the other to execute ‘grep minishell.c’. After the forks, the original parent process waits for both child processes to finish before it terminates. The parent should print out the pid of each child after it finishes. The standard output of 'ls -al' process should be piped to the input to the 'grep minishell.c' process. Make sure you close the unnecessary open files for the three processes. The output should be the one line that includes the directory entry for minishell.c. You will need to call the source file minishell.c for this to work properly.

0 0
Add a comment Improve this question Transcribed image text
Answer #1

Answer:

Creating two child processes using a C program called minishell

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/wait.h>

int main()
{

int pid1, pid2;
if((pid1 = fork()) == 0) // begin child one process
{
execlp("ls","-al",NULL); // showing the given command ('Is - al') as it is to be executed first
exit(0);
}
else
{
int s;

waitpid(pid1,&s,0);
if((pid2=fork()) == 0) // now begin the second child process
{
int fd = 0 ;
close(1); // close stdout
fd = open("grepminishell.c",O_CREAT|O_TRUNC); // open new fd so fd will 1
execlp("grep","grepminishell.c",NULL); // this command will fail.


}
else //begin the parent process
{
waitpid(pid2,&s,0); // wait for the first process to get finished and start second process
printf("child 1 pid - %d, child 2 pid - %d\n",pid1,pid2); // each parent should print pid of child before it gets terminated


}
}


}

Add a comment
Know the answer?
Add Answer to:
Write a program in C called minishell that creates two child processes: one to execute 'ls...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT