7B) C program to create a child process and to read commands from the standard input and execute them. [VTU SS&OS]

vtu ss & os 7b
Code:
Explanation:
This program creates a child process. In the child process, we keep on ask users, some commands to execute in the system using system() command.

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

include all necessary header files for normal operation.

void main()
{
char command[20];
int ch,pid=fork();

main function. call fork() to create a child process.
if it returns 0, you are in child process, so ask user for commands and keep on executing until he wants.

if(pid==0)
{
        printf("The child process: ");
do
{
printf("Enter the command: ");
scanf("%s",command); 
system(command); 
printf("Press 1 to continue\n Press 0 to exit\n");
scanf("%d",&ch);
}while(ch!=0);
}

same thing is done here. if pid==0, we are in child process. so, with do while loop, until choice=1, ask user for command, store it in a string. call that command in system using system() function. Also ask user whether to continue or not, continue the same steps until user presses 0.

else
{
wait();
}
} //of main()

wait() in parent process waits until child gets completed. Then terminates the program.

He is a simple passionate tech freak who himself is an engineering student at Canara Engineering college. He likes App Development, Web designing, Blogging, Youtubing, Debugging and also is a CodeGeek!

Sharing is sexy!

Related Articles

Share your views about this article!