2008年7月24日星期四

进程fork

学习了一段时间进程,用fork()函数把原来的进程,变为俩个进程,其实就是fork()创建了一个新的进程,新进程返回"0",原来的进程继续执行,返回一个新的PID。
在man手册中说fork create a child process
SYNOPSIS:梗概
#include
#include
pid_t fork(void);
看这是什么呢?pid_t是在types.h这个文件下的
pid_t Used for process IDs and process group IDs.
而fork()函数在unistd.h下定义了,而且还有 pid_t vfork(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:
SEE ALSO
clone(2), execve(2), setrlimit(2), unshare(2), vfork(2), wait(2), capa-
bilities(7), credentials(7)
也就是说我们也要看这些相关的函数,才可以更好的理解和运用fork()函数。
进程是正在运行的程序,其实他是一个运行着一个或者多个线程的地址空间和这些线程所需
的系统资源。每一个进程将会被分配一个PID。进程有自己的栈空间,用于保存函数中的局>部变量和控制函数的调用与返回。进程还有自己的环境空间,包含专门为这个进程建立的环
境变量。进程还必须维护自己的程序计数器,这个计数器用来记录他执行到的位置,即执行
线程中的位置。
Linux进程表就像一个数据结构,它把当前加载在内存中所有进程的有关信息保存在一个表>中,其中包括进程的PID,进程的状态,命令字符串和其他一些ps命令输出的各类信息。每>个进程都是由一个我们称之为“父进程”的进程启动的,被父进程启动的进程叫做子进程。系
统运行的第一个进程是init进程启动的,它是其他所有进程的祖先进程。
Linux调度器以进程的优先级为基础来决定运行哪个进程。
等待一个进程用wait()
子进程终止时,它还与父进程之间的关联还会保持,直到父进程也完全结束或者是调用wait
才告结束。因此,在进程表中子进程不会立刻被释放。虽然子进程的不再运行,但是它仍然
存在于系统之中,它的退出码还需要保存起来以备父进程今后的wait调用,这时它将成为一
个死进程或者是僵死进程。
* 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 (sigpend-
ing(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(3)).

* The child does not inherit outstanding asynchronous I/O operations
from its parent (aio_read(3), aio_write(3)).

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:

没有评论:

time