#include<sys/types.h>#include<unistd.h>#include<stdio.h>intmain(){int count =0;pid_t pid; pid =fork();if(pid <0)printf("error in fork!\n");elseif(pid ==0)printf("I am the child process,ID is %d,count is %d(%p)\n",getpid(),count,&count);elseprintf("I am the parent process,ID is %d,count is %d(%p)\n",getpid(),count,&count);return0;}// 输出I am the parent process,ID is 5188,count is 0(0x7ffd5e311580)I am the child process,ID is 5189,count is 1(0x7ffd5e311580)
现在的Linux内核采用一种更为有效的方法,称之为写时复制(Copy On Write,COW)。这种思想相当简单:父进程和子进程共享页帧而不是复制页帧。然而,只要页帧被共享,它们就不能被修改,即页帧被保护。无论父进程还是子进程何时试图写一个共享的页帧,就产生一个异常,这时内核就把这个页复制到一个新的页帧中并标记为可写。原来的页帧仍然是写保护的:当其他进程试图写入时,内核检查写进程是否是这个页帧的唯一属主,如果是,就把这个页帧标记为对这个进程是可写的。
这个函数可以让进程自己挂起seconds秒,sleep函数是由操作系统的 nanosleep 函数实现的,On Linux, sleep() is implemented via nanosleep(2). See the nanosleep(2) man page for a discussion of the clock used.核心代码:
#include<sys/types.h>
#include<unistd.h>
#include<stdio.h>
int main()
{
pid_t pid;
int cnt = 0;
pid = vfork();
if(pid<0)
printf("error in fork!\n");
else if(pid == 0)
{
cnt++;
printf("cnt=%d\n",cnt);
printf("I am the child process,ID is %d\n",getpid());
_exit(0); // _exit(0);
}
else if(pid > 0)
{
cnt++;
printf("cnt=%d\n",cnt);
printf("I am the parent process,ID is %d\n",getpid());
}
return 0;
}
// 输出
cnt=1
I am the child process,ID is 19713
cnt=2
I am the parent process,ID is 19712
// 如果注释掉 __exit(0),则会出现一下错误:
cnt=1
I am the child process,ID is 13986
cnt=-134746042
I am the parent process,ID is 13985
test_vfork: cxa_atexit.c:100: __new_exitfn: Assertion `l != NULL' failed.
[1] 13985 abort (core dumped) ./test_vfork
unsigned int sleep(unsigned int seconds); // 以秒为单位