In: Computer Science
You will write a C program to fork a child process. The child
process will print the current time/date. The parent will wait for
the child to complete.
Here is how you can programmatically call the Linux date command
from a C program.
execlp("/bin/date","date",NULL);
Your C file should be named myfork.c
The binary will be named myfork.
Code in C
#include<stdio.h>
#include<stdlib.h>
#include<sys/wait.h>
#include<unistd.h>
//Main function
int main()
{
//pid_t is a datatype used for representing the process id
pid_t cpid;
//creating two proccess parent and child using fork()
//checking if the process is child
if (fork()== 0)
{
//we can identify the process by checking the pid_t if it is 0 then
it is a child process
//printing the date
printf(" ",execlp("/bin/date","date",NULL));
// terminate child
exit(0);
}
//checking if the process is parent
else
//if so then waiting until the child process finish its execution
by wait() function
cpid = wait(NULL);
return 0;
}
Screenshots
Input\output