I have these silly doubts relating to fork() system call, Shall be grateful if anyone please answer these questions.
For eg-
#include<stdio.h>
#include<sys/types.h>
#include<unistd.h>
int main()
{
pid_t pid;
pid=fork();
if(pid==0)
{
printf("Child Process");
}
else if(pid>0)
{
printf("Parent Process");
}
else
{
printf("Unable to create");
}
}
I have tried this code-
#include<stdio.h>
int main()
{
int x;
x=fork();
if(x==0)
{
printf("Child Process");
}
else if(x>0)
{
printf("Parent Process");
}
else
{
printf("Unable to create");
}
}
Can someone please give an answer to my queries?
Using pid_t
means that the source code is portable to eg systems that use a 64-bit PID.
The processes execute in that order because that is how the scheduler has decided to execute them.
Here pid_t is the 64-bit unsigned int, You can find it out in header files. This basically used to make the program portable.
Why parent process first?
Ans: 1 . After forking a process child had to copy the memory layout of parent process ( copying the head, stack, initialized data, uninitialized data ), So that time parent has nothing to do, So in most of the cases, parent has to execute first.
But in a few cases when child executes first, only when parent scheduling time expires.
In UNIX system /proc/sys/kernel/sched_runs_first, make this value 1 to make sure that the child process runs first.
In Conclusion, this behavior is not defined and undetminstic, Better to use any syncing methods.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.