In: Computer Science
Ubuntu, Linux, MacOS use one of these systems.
1a. Create a C program that forks a child process that executes the
command ‘ls’.
1b. Extend the program you created in Problem 1a such that it takes
an argument. For example, the created child process should be able
to execute the command ‘ls’ with any arbitrary single argument such
as ‘ls -l’, and ‘ls -a’.
//Program for 1a
1a.
//solution
#include <stdio.h>
#include<string.h>
#include<stdlib.h>
#include<sys/wait.h>
#include<sys/unistd.h>
int main()
{
char *command[3];
int pid,status;
//create child process by using system call fork()
pid=fork();
if(pid > 0) // parent process
{
//wait for child to finish executing ls
wait(&status);
exit(0);
}
else //child process , execute ls command
{
//buld command
command[0]=(char*)malloc(sizeof(char)*3);
strcpy(command[0],"ls");
command[1]=NULL;
printf("Child process executes ls command\n");
printf("#####Output of ls command#####\n");
//execute using system call execvp
execvp(*command,command);
}
}
===============================
//Output
gcc mySh.c
./a.out
Child process executes ls command
#####Output of ls command#####
a.out main.sh mySh.c
========================================
//Program for 1b
1b.
//solution
#include <stdio.h>
#include<string.h>
#include<stdlib.h>
#include<sys/wait.h>
#include<sys/unistd.h>
//make program to take command line args
int main(int argc,char *argv[])
{
char *command[3];
int pid,status;
//if there is no otion given for ls command , print error message to user and exit
if(argc < 2)
{
printf("Usage: %s single_argument_to_ls_command\n",argv[0]);
exit(-1);
}
//create child process by using system call fork()
pid=fork();
if(pid > 0) // parent process
{
//wait for child to finish executing ls
wait(&status);
exit(0);
}
else //child process , execute ls command
{
//buld command
command[0]=(char*)malloc(sizeof(char)*3);
strcpy(command[0],"ls");
command[1]=(char*)malloc(sizeof(char)*3);
strcpy(command[1],argv[1]);
command[2]=NULL;
printf("Child process executes ls command with argument %s\n",argv[1]);
printf("#####Output of ls %s #####\n",argv[1]);
//execute using system call execvp
execvp(*command,command);
}
}
========================
//Output
gcc mySh.c
./a.out
Usage: ./a.out single_argument_to_ls_command
./a.out -l
Child process executes ls command with argument -l
#####Output of ls -l #####
total 16
-rwxr-xr-x 1 runner runner 8352 Oct 11 08:25 a.out
-rw-r--r-- 1 runner runner 0 Oct 11 08:08 main.sh
-rw-r--r-- 1 runner runner 1042 Oct 11 08:25 mySh.c
//Output2
gcc mySh.c
./a.out -a
Child process executes ls command with argument -a
#####Output of ls -a #####
. .bash_history .bashrc .profile main.sh
.. .bash_logout .go.sh a.out mySh.c