fork函数
如何创建进程?
fork函数使用
先认识这两点即可
- fork有两个返回值
- 父子进程代码共享,数据各自开辟空间,私有一份(采用写时拷贝)
第一点验证代码:
运行结果:
第二点验证代码:
运行结果:
如何理解复制代码,数据私有呢?
附:linux手册描述
NAME
fork - create a child process
SYNOPSIS
#include <unistd.h>
pid_t fork(void);
DESCRIPTION
fork() creates a new process by duplicating the calling process. The new process, referred to as the child, is an exact duplicate of the calling process, referred to as the parent, except for the
following points:
* The child has its own unique process ID, and this PID does not match the ID of any existing process group (setpgid(2)).
* The child's parent process ID is the same as the parent's process ID.
* The child does not inherit its parent's memory locks (mlock(2), mlockall(2)).
* Process resource utilizations (getrusage(2)) and CPU time counters (times(2)) are reset to zero in the child.
* The child's set of pending signals is initially empty (sigpending(2)).
* The child does not inherit semaphore adjustments from its parent (semop(2)).
* The child does not inherit record locks from its parent (fcntl(2)).
* The child does not inherit timers from its parent (setitimer(2), alarm(2), timer_create(2)).
* The child does not inherit outstanding asynchronous I/O operations from its parent (aio_read(3), aio_write(3)), nor does it inherit any asynchronous I/O contexts from its parent (see io_set‐
up(2)).
The process attributes in the preceding list are all specified in POSIX.1-2001. The parent and child also differ with respect to the following Linux-specific process attributes:
* The child does not inherit directory change notifications (dnotify) from its parent (see the description of F_NOTIFY in fcntl(2)).
* The prctl(2) PR_SET_PDEATHSIG setting is reset so that the child does not receive a signal when its parent terminates.
* The default timer slack value is set to the parent's current timer slack value. See the description of PR_SET_TIMERSLACK in prctl(2).
翻译结果:
姓名
fork-创建子进程
简介
#包括<unistd.h>
pid\ t叉(空);
说明
fork()通过复制调用进程来创建一个新进程。新进程(称为子进程)与调用进程(称为父进程)完全相同,但
以下几点:
*子进程有自己唯一的进程ID,并且此PID与任何现有进程组的ID不匹配(setpgid(2))。
*子进程的父进程ID与父进程ID相同。
*子级不继承其父级的内存锁(mlock(2)、mlockall(2))。
*子进程中的进程资源利用率(getrusage(2))和CPU时间计数器(times(2))重置为零。
*子级的挂起信号集最初为空(sigpending(2))。
*子级不从其父级继承信号量调整(semop(2))。
*子项不从其父项继承记录锁(fcntl(2))。
*子级不从其父级继承计时器(setitimer(2)、alarm(2)、timer\u create(2))。
*子级不会从其父级继承未完成的异步I/O操作(aio\ U read(3)、aio\ U write(3)),也不会从其父级继承任何异步I/O上下文(请参阅io\ U set‐0)
向上(2))。
上述列表中的流程属性都在POSIX.1-2001中指定。父进程和子进程在以下特定于Linux的进程属性方面也有所不同:
*子目录不从其父目录继承目录更改通知(dnotify)(请参阅fcntl(2)中F_NOTIFY的描述)。
*prctl(2)PR\u SET\u PDEATHSIG设置被重置,这样子级在其父级终止时不会收到信号。
*默认计时器时差值设置为父级的当前计时器时差值。参见prctl(2)中PR\u SET\u TIMERSLACK的描述。