【OS学习】之 Process API

来源:互联网 发布:云豹直播源码 下载 编辑:程序博客网 时间:2024/06/06 02:38

  UNIX presents one of the most intriguing ways to create a new process with a pair of system calls: fork() and exec(). A third routine, wait(), can be used by a process wishing to wait for a process it has created to complete.

一、The fork() System Call

这里写图片描述
这里写图片描述

  The process calls the fork() system call, which the OS provides as a way to create a new process. The odd part: the process that is created is an (almost) exact copy of the calling process.

  有的UNIX系统有两种形式的fork(), ①复制所有线程,②只复制调用了系统调用fork()的线程。

  Notice:父进程打印了”hello world”,而子进程没,且子进程被创建后在父进程执行完指令(不包括done指令,即return)后再执行,并从创建它的位置开始。凡凡认为:因为Scheduler(调度程序),将子进程放入就绪队列。



二、The wait() System Call

这里写图片描述
这里写图片描述

  However, if the parent does happen to run first, it will immediately call wait(); this system call won’t return until the child has run and exited2. Thus, even when the parent runs first, it politely waits for the child to finish running, then wait() returns, and then the parent prints its message.

  父进程通过系统调用wait()来等待子进程的完成。当子进程完成时(通过显示或隐式调用exit()),父进程会从wait()调用处开始继续,并调用系统调用exit()以表示结束。如果在子进程运行时(父进程)没有什么可做,那么它采用系统调用wait()把自己移除就绪队列来等待子进程的终止



三、The exec() System Call

这里写图片描述
这里写图片描述

This system call is useful when you want to run a program that is different from the calling program.

However, often you want to run a different program; exec()does just that (Figure 5.3, page 5).

  调用fork()之后立即调用exec(),那么没有必要复制所有线程,因为exec()参数所指定的程序会替代整个进程。


Tips:

int rc = fork();

对于新(子)进程,系统调用fork()的返回值为0;而对于父进程,返回值为子进程的进程标识符(非零);

1 0
原创粉丝点击