简体   繁体   中英

fork() system call in linux

I have these silly doubts relating to fork() system call, Shall be grateful if anyone please answer these questions.

  • Does fork() system call returns an integer? If yes,then why while
    executing the fork() system call,we are taking its value in pid_t ?
    Can't we just write int x=fork() ;

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");
}
}
  • Why we are executing pid=fork() instead of int x=fork()?
  • The above program gives an output- Parent ProcessChild Process Why it is first executing the parent process and not the child?

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");
        }
    }
  • I have tried to collect the value of fork() in an integer variable in gcc compiler of ubuntu 15.04 and its working fine,not showing any error and giving the same result as the above program will give.
  • Is it the compiler problem or is this code fine? Even I haven't given the header fies sys/types.h and unistd.h,still not showing any errors.

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.

  1. But in a few cases when child executes first, only when parent scheduling time expires.

  2. 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM