进程创建/进程的终止

进程创建

fork函数

1.        对于fork函数,父进程中返回子进程的pid,因为父进程可能有多个子进程,但没有一个系统调换可以获取所有子进程的pid; 子进程中返回0,因为一个进程只能有一个父进程,可以通过getppid获取父进程的pid.

2.        对于fork函数,子进程获得父进程的数据段,堆,栈的副本。父子进程共享正文段。子进程中需要复制的内容并不会被立即完全复制,而是采用了写时复制(copy-on-write)技术。

 进程创建/进程的终止

vfork函数

vfork和fork一样都创建一个子进程,但是它不将父进程的地址空间完全复制到子进程中,因为子进程会立即调用exec(或exit),于是也就不会访问该地址空间。相反,在子进程调用execexit之前,它在父进程的空间中运行

 

进程创建/进程的终止

fork与vfork的区别

1.        上述对地址空间的复制。

2.        vfork保证子进程先运行,在它调用exec或exit之后父进程才可能被调度运行。

 

The vfork system call is somethingof an artifact. It is virtually identical to fork except that vfork guaranteesthat the user-space memory will not be copied.

In the bad old days, a fork callwould cause all the process’s user-space memory to be copied into new pages.This is especially wasteful if the only thing the child process is going to dois call exec. In that case, all that copying is done for nothing.

 

The problem with vfork is that itrequires the child process to call exec immediately, without modifying anymemory. This is harder than it sounds, especially if you consider that the execcall could fail. The vfork(2) man page has an interesting editorial on thistopic for the interested reader.

 

Copy on Write

When a process forks, both processesshare the same physical memory for as long as possible—that is, the kernelcopies only the page table entries and marks all the pages copy on write. Thiscauses a page fault when either process modifies the memory. When a page faultoccurs due to copy on write, the kernel allocates a new page of physicalstorage and copies the page before allowing it to be modified.

 进程创建/进程的终止

clone

clone 可以指定复制父进程中指定的内容。详见manclone.

进程的终止

进程终止的方式

1.      异常终止, core dump;

2.      调用exit(), _exit();

3.      从main函数return;

Exit()执行的动作

1.      调用退出处理程序, 其执行顺序和注册顺序相反; (atexit() or on_exit()) (无法取消退出处理程序, 但有全局执行标志, 这个标志可以用来检查是否注册退出处理程序或清除该标志达到屏蔽退出处理程序)

2.      刷新stdio流缓冲区;

3.      执行_exit()

孤儿进程 & 僵尸进程

孤儿进程: 父子进程, 父进程已死, init进程会接管该子进程, 该子进程称为孤儿进程.

僵尸进程: 子进程已经结束, 系统仍然运行其父进程在之后的某一时刻去执行wait(), 以确定该子进程是如何终止的. 内核将释放该子进程的大部分资源, 以便供系统中其它的进程重新使用. 该僵尸进程所唯一保留的是内核进程表中的一条记录, 其中包含: 进程ID, 终止状态, 资源使用数据等信息. 当父进程执行wait()后, 由于不再需要子进程剩余的最后信息, 内核将删除该僵死进程.

进程优先级/进程调度策略

http://www.cnitblog.com/flutist1225/articles/19989.html