【OS学习】之 Process API

本文介绍了UNIX系统中使用fork()创建新进程的方法,详细解释了如何利用wait()让父进程等待子进程完成,以及如何通过exec()运行不同的程序。此外还探讨了不同场景下这些系统调用的具体行为。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  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;而对于父进程,返回值为子进程的进程标识符(非零);
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值