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.
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
}
}
}
Write a program in C called minishell that creates two child processes: one to execute 'ls...