fork()系统调用函数

来源:互联网 发布:vscode 技巧 编辑:程序博客网 时间:2024/05/18 04:57

在linux中 man fork 查看fork()函数,可以发现:

 系统提示:

#include <sys/types.h>
       #include <unistd.h>
       pid_t fork(void); //返回一个PID


DESCRIPTION
       fork()  creates  a child process that differs from the parent process only in its PID and PPID, and in
       the fact that resource utilizations are set to 0.  File locks and pending signals are not inherited.

       Under Linux, fork() is implemented using copy-on-write pages, so the only penalty that  it  incurs  is
       the time and memory required to duplicate the parent’s page tables, and to create a unique task struc-
       ture for the child.


RETURN VALUE
       On success, the PID of the child process is returned in the parent’s thread of execution, and a  0  is
       returned  in  the child’s thread of execution.  On failure, a -1 will be returned in the parent’s con-
       text, no child process will be created, and errno will be set appropriately.

ERRORS
       EAGAIN fork() cannot allocate sufficient memory to copy the parent’s page tables and allocate  a  task
              structure for the child.


       EAGAIN It  was  not  possible to create a new process because the caller’s RLIMIT_NPROC resource limit
              was encountered.  To exceed this limit, the process must have either the CAP_SYS_ADMIN  or  the
              CAP_SYS_RESOURCE capability.

       ENOMEM fork() failed to allocate the necessary kernel structures because memory is tight.


     

在语句fpid=fork()之前,只有一个进程在执行这段代码,但在这条语句之后,就变成两个进程在执行了,这两个进程的几乎完全相同,将要执行的下一条语句都是if(fpid<0)……

    为什么两个进程的fpid不同呢,这与fork函数的特性有关。fork仅仅被调用一次,却能够返回两次,它可能有三种不同的返回值:

    1)在父进程中,fork返回新创建子进程的进程ID;

    2)在子进程中,fork返回0;

    3)如果出现错误,fork返回一个负值;

    在fork函数执行完毕后,如果创建新进程成功,则出现两个进程,一个是子进程,一个是父进程。在子进程中,fork函数返回0,在父进程中,fork返回新创建子进程的进程ID。我们可以通过fork返回的值来判断当前进程是子进程还是父进程。

简单例子:


需要注意的是:


与fork()类似的函数有system()

0 0
原创粉丝点击