fork函数小结

1.调用一次,返回两次。

 

2.子进程中fork返回0,父进程中fork返回子进程的PID。原因是:①在子进程中通过调用getppid可以方便的指导父进程的PID;②没有一个函数可以使父进程获得其所有子进程的PID。(所以在fork返回时,将子进程的PID直接返回给父进程)

注:子进程的ID不可能为0,因为PID为0的进程是swapper进程。

 

3.父、子进程共享正文段,不共享数据、堆、栈段,子进程获得父进程数据、堆、栈段的副本。

注:目前,大多数实现并直接复制父进程的数据、堆栈段,而是使用写时复制(Copy-On-Write)技术,在修改这块内存区域时,才会为被修改的数据创建副本。

 

4.子进程会获得缓冲区的副本,即fork前进程缓冲区中的数据未被flush掉,则fork后,子进程能够获得父进程缓冲区中的数据。

 

5.父进程所有被打开的文件描述符都会被复制到子进程中。

注:fork之后处理文件描述符通常有两种情况:

①父进程等待子进程结束;

②父、子进程各自执行不同的正文段(父、子进程各自关闭不需要使用的文件描述符);

 

6.fork之后父、子进程的区别:

①fork的返回值;

②进程ID不同;

③父进程也不同;

④子进程的tms_utime、tms_stime、tms_cutime和tms_ustime均被设置为0;

⑤父进程设置的文件锁不会被子进程继承;

⑥子进程的未处理的闹钟被清除;

⑦子进程的未处理信号集设置为空集;

 

7.fork失败的主要原因:

①系统中进程数目已经达到上限;

②该实际用户的进程总数达到系统限制;

③内存不足

 

8.fork的两种用法:

①一个进程希望复制自己,使得父、子进程执行不同的代码段。如父进程监听端口,收到消息后,fork出子进程处理消息,父进程仍然负责监听消息。

②一个进程需要执行另一个程序。如fork后执行一个shell命令。

 

 

man fork
FORK(2)                    Linux Programmer’s Manual                   FORK(2)

NAME
       fork - create a child process

SYNOPSIS
       #include <sys/types.h>
       #include <unistd.h>

       pid_t fork(void);

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 structure 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 context, no child pro-
       cess 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 encoun-
              tered.  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.

CONFORMING TO
       SVr4, 4.3BSD, POSIX.1-2001.

EXAMPLE
       See pipe(2) and wait(2).

SEE ALSO
       clone(2), execve(2), setrlimit(2), unshare(2), vfork(2), wait(2), capabilities(7)

Linux 2.6.6                       2004-05-27                           FORK(2)
(END)

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值