fork与vfork、wait与waitpid区别

xiaoxiao2025-04-05  11

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结束。

转载请注明原文地址: https://www.6miu.com/read-5027563.html

最新回复(0)