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
- fork()系统调用函数
- 系统调用fork()函数
- linux系统调用函数心得:fork()
- fork系统调用
- fork()系统调用
- linux fork系统调用
- fork系统调用
- 系统调用分析:fork
- Linix fork系统调用
- linux 系统调用fork
- fork 系统调用
- Linux fork()系统调用
- fork系统调用
- fork系统调用
- 浅析fork系统调用
- fork系统调用过程
- 进程系统调用——fork函数深入理解
- 分析fork函数对应的系统调用处理过程
- 论NOIP2015我是如何滚粗的
- 白平衡原理
- LeetCode Combination Sum III DFS
- C++学习——多态原理
- 6、Block,数组排序
- fork()系统调用函数
- hadoop安装教程
- Java中字符串(String)的存储和赋值原理
- 禅与 Objective-C 编程艺术
- 曲面映射的算法理论基础
- 解决电脑开机黑屏只有鼠标的问题
- muduo库阅读(10)——进程信息
- 在TextView中添加文本时有时会改变一些文本字体的颜色
- Python 数据分析包:pandas 基础