create child process by fork in linux using C
The tutorial is about to create child process by fork() in linux using C.
fork() which is the library funtion, is used to create child process.I will explain fork() using C.
Now the question is what happens when the child process is created?
When we use fork(), this function splits the running process into two processes, in which one is the parent and other is the child process.
Lets understand this with an examplethis is the C code- #include<stdio.h>
#include<unistd.h> // for fork()
void main()
{ printf("Before calling fork()");
fork();
printf("After calling fork()");
}
- Output:
Before calling fork()
After calling fork()
After calling fork()
#include<unistd.h> // for fork()
void main()
{ printf("Before calling fork()");
fork();
printf("After calling fork()");
}
Before calling fork()
After calling fork()
After calling fork()
Here, we can see that as the fork() is called the program splitted into
two parallel processes which work simultaneously.
Lets apply our newly learned concept on next level- #include<stdio.h>
#include<unistd.h>
void main()
{
int PID;
PID=fork();
if(PID==0)
{
//child process
printf("The pdf files are copying on the Desktop");
}
else if(PID>0)
{
//parent process
execl("cp" ,"*.txt" ,"/Desktop" ,NULL);
}
else
printf("Child process isnt created");
}
#include<unistd.h>
void main()
{
int PID;
PID=fork();
if(PID==0)
{
//child process
printf("The pdf files are copying on the Desktop");
}
else if(PID>0)
{
//parent process
execl("cp" ,"*.txt" ,"/Desktop" ,NULL);
}
else
printf("Child process isnt created");
}
NOTE
fork() returns 0 if child process is created
fork() returns PID or process ID of the child process to the parent process.
fork() returns Negative value if child process creation fails.
In above program, child process is displaying the phrase "The pdf files are copying on the Desktop"
and parent process is copying the pdf files.
You can choose the directory according to your system configuration.
Hence guys, this is all about to create child process by fork in linux using C
alternative link download