fork与vfork、wait与waitpid区别

fork之后父进程子进程分离,各自有各自的内存空间,两个进程在OS管理下运行,无法确定谁先运行

vfork后,父子程序共享内存空间,一般vfork搭配execve函数,创建子进程拉起别的进程(不用复制内存空间效率也更高)。子进程运行结束后运行父进程。

execve替换代码段、数据段、堆栈段、进程控制块PCB。

 

pid_t wait(int *status);

The wait() system call suspends execution of the calling process until a child specified by pid argument has changed stse.

wait()系统调用暂停执行调用进程,直到pid参数指定的子进程发生更改为止。(父进程阻塞直到pid子进程结束)。

pid_t waitpid(pid_t pid, int *status, int options);

The waitpid() waits only for terminated children,but behavior is modifiable via the options argument.

waitpid()只等待已终止的子节点,但行为可以通过options参数修改.(waitpid等待任意子程序结束,通过options参数修改)。

<-1  meaning wait for any child process whose process group ID is equal to the absolute value of pid.

-1 meaning wit for any child process.

0 meaning wait for any child process whose process group ID is equal to that of the calling process.

>0 meaning wait for the child whose process ID is equal to the value of pid.

 

wait返回-1的原因

1.The calling process does not have any unwaited-for childern.

2.WNOHANG was not set and an unblocked signal or a SIGCHLD was caught;see signal(7).

 

wait的简单应用

创建10个子进程等待结束

 

 

vfork和execve

vfork后父进程创建一个子进程,用execve拉起来另外一个进程完全替代原来的子进程。但是拉起来的进程依旧是父进程的子进程。

下面的代码在vfork后,用execve拉起来hello_world程序。

hello_world程序打印hello_worl并且abort退出。原子程序exit退出。

然后在父程序中接收子程序的结束状态,判断是hello_world的abort结束,还是原来子程序的exit退出。

hello_world程序代码

结果

打印出other,父程序收到hello_world的abort结束。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值