LINUX 进程编程

2025-06-21 16:45:45
推荐回答(1个)
回答1:

第一眼觉着没啥难度的问题,看了看还是挺纠结的。Linux 的 man 手册上有写到:

vfork() is a special case of clone(2). It is used to create new processes without copying the page tables of the parent process. It may be useful in performance-sensitive applications where a child is created which then immediately issues an execve(2).

vfork() differs from fork(2) in that the calling thread is suspended until the child terminates (either normally, by calling _exit(2), or abnormally, after delivery of a fatal signal), or it makes a call to execve(2). Until that point, the child shares all memory with its parent, including the stack. The child must not return from the current function or call exit(3), but may call _exit(2).

结合wiki上的,简单说,vfork创建了一个轻量级进程(LWP),但是它并不将父进程的地址空间完全复制到子进程中,不会复制页表。在子进程调用exec或exit之前,他在父进程的空间中运行;在子进程调用exec或exit之前,父进程阻塞。

至于重复两次子进程,当没有return语句时,你的main会被返回一个0(当然是在程序最后自动添加上去的了~~)。所以,你等于子进程没有调用exit而是return。

对于exit与return,要这么理解——exit让整个进程直接终止;return返回入口点(调用点)。你这里没有用exit而使用了return,return 0在一个函数中是正常的返回过程,它会使得程序返回到函数被调用处,回复之前的执行流程,return 语句不会被执行。

至于答案中有出现的 孤儿进程 和 守护进程——vfork机制下,父进程绝对 “不会比子进程早结束”!!!(如果你不嫌之前的分析太长而仔细看完过的话,不难理解这个)。这完全没有孤儿进程的事情好不好~~