系统编程-进程-vfork使用、浅析

 

1. 先贴代码

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

int globvar = 6; /* external variable in initialized data */

int main(void)
{
    int var;      /* automatic variable on the stack */
    pid_t pid;

    var = 88;
    printf("before vfork, pid=%d \n", getpid()); /* we don't flush stdio */

    if ( (pid = vfork()) < 0 )
    {
        printf("vfork error");
    }
    else if (pid == 0)
    {             
    sleep(1); /* child */

    printf("child: pid=%d \n", getpid());
        globvar++; /* modify parent's variables */
        var++;
        //exit(0); /* child terminates */
    }else{

    printf("Im Parant \n");
    }

    /* parent continues here */
    printf("pid = %ld, glob = %d, var = %d\n", (long)getpid(), globvar, var);
    
    printf("1. pid=%d \n", getpid()); 
    sleep(3);
    printf("2. pid=%d \n", getpid()); 
    printf("3. pid=%d \n", getpid()); 

    _exit(0);
}

 

2. 

运行:

root@lmw-virtual-machine:/home/lmw/MINE/Linux_C_exercise/vfork#
root@lmw-virtual-machine:/home/lmw/MINE/Linux_C_exercise/vfork# gcc test1.c -o ab
root@lmw-virtual-machine:/home/lmw/MINE/Linux_C_exercise/vfork# ./ab
before vfork, pid=13810
child: pid=13811
pid = 13811, glob = 7, var = 89
1. pid=13811
2. pid=13811
3. pid=13811
Im Parant
pid = 13810, glob = 7, var = 89
1. pid=13810
2. pid=13810
3. pid=13810
root@lmw-virtual-machine:/home/lmw/MINE/Linux_C_exercise/vfork#
root@lmw-virtual-machine:/home/lmw/MINE/Linux_C_exercise/vfork#

 

分析:

即使上述代码处存在sleep(3)这个延时,运行发现子进程一定是先运行的,而且会运行到exit后才轮到父进程执行。

并且vfork后子进程改变的栈数据和全局数据是会影响到父进程内的。

 

小结: 1. vfork后,保证子进程先运行,在子进程调用exit等函数后主进程才会继续运行。

            2. vfork创建的子进程与父进程共享数据段。

 

关联博文:

系统编程-进程-fork深度理解、vfork简介

 

.

posted @ 2021-01-02 18:24  一匹夫  阅读(177)  评论(0编辑  收藏  举报