Write a programl that creates two child processes: one to execute \'ls\' and the
ID: 3775460 • Letter: W
Question
Write a programl that creates two child processes: one to execute 'ls' and the other to execute 'sort'. After the forks, the original parent process waits for both child processes to finish before it terminates. The standard output of 'ls' process should be piped to the input to the 'sort' process. Make sure you close the unnecessary open files for the three processes. In C.
I have:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <unistd.h>
#include <fcntl.h>
/
int main()
{
pid_t pid1,pid2;
pid1 = fork();
if(pid1 < 0)
{
/* an error occurred */
perror("fork failed");
exit(-1);
}
else if(pid1 == 0)
{
/* child process1 */
system("ls > input.txt");
return 0;
}
else
{
/* parent process */
wait(&pid1);
pid2 = fork();
if(pid2 < 0)
{
perror("fork failed");
exit(-1);
}
else if(pid2 == 0)
{
/* child process2 */
system("sort -d input.txt");
return 0;
}
else
{
/*Parent Process*/
wait(&pid2);
return 0;
}
}
return 0;
}
but i would like it to work with no system calls. Any ideas?
Explanation / Answer
for ls you can do this :
char *argument[2];
argument[0]="/bin/ls"; // first argument is the full path to executable i.e ls command
argument[1]=NULL; // list of arguments must be null terminated
Now replace the below statement using: execv
system("ls > input.txt");
replace to
execv(argument[0],argument);
Same way we can put a sort program in the bin directory and make it executable. say we created a sort file of sort.c and compile and place the sort in /bin .
so /bin/sort is accesible.If you place argument[0] to be
argument[0]="/bin/sort";
argument[1]=NULL; // list of arguments must be null terminated
execv(argument[0],argument);
Hope it helps. ls will work without no system calls but not sure about the sort. Most probably it will work.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.