I’m new to c language and Linux. I have a problem related to fork(),getpid()and exec()function.
I wrote a c program using fork() call the code of my program is following”
code:
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdlib.h>
void fun()
{
printf("\n this is trial for child process");
}
int main (int argc, char const *argv[])
{
int i,status,pid,t;
if(pid=fork()<0)
{
printf("\nfailed to create the process\n");
}
if(pid=fork()==0)
{
printf("\n the child process is created");
fun();
exit(1);
}
while(wait(&status)!=pid);
return 0;
}
The out put of this program is following:
the child process is created
this is trial for child process
the child process is created
this is trial for child process
Now my questions are as follows:
- Why the output of program showing same thing twice? The output supposed to be “child process is created this is trial for child process”
- Why the output is not according to code ?
- Can we have a program which has 4 processes and all the processes perform different task for example one process print “my name”. One process print “my age”, the other process print “my address ?
- How to make multiple process in main function ?
- How to control the execution of multiple process ?
- what does the
exec()function do? Can anyone please explain me the working ofexec(),fork(),getpid()with a source code?
Please help this novice fellow.
In this code you are creating Three process not including your main process.
is itself a statement , which forks a new process even though it is inside an if statement condition. After the first fork() call the remaining codes will be executed twice. so next fork call will be called twice. You have already created a new process.
That is consider a process A forks B (not from your code)
printf statement executes twice(one for A and one for B). For A it prints(A is parent)
and B prints
So in your question
this is the second fork which is already executing twice. So each of this execution creates a new child process. For both childs pid value is 0. So your print statement executes, which is what you see in the output. But for both parents a pid value will be there and your if condition fails, so it wont print. These two childs are your second and third processes..So in short you create 3 processes along with the main process