Linux下父子进程的全局变量

磨砺技术珠矶,践行数据之道,追求卓越价值 

回到上一级页面: PostgreSQL杂记页     回到顶级页面:PostgreSQL索引页 

[作者 高健@博客园  luckyjackgao@gmail.com] 

用这个从网上找的例子,看父子进程对全局变量的拥有是否不同:

#include <sys/types.h>    
#include <stdio.h>    
#include <stdlib.h>    
    
int glob = 6;    
char buf[] = "a write to stdout\n";    
    
int main()    
{    
    int var;    
    pid_t pid;    
       
    var = 88;    
       
    fprintf(stderr, "%s", buf); 
    printf("before fork/n");    
       
    if(( pid = fork() ) < 0 )    
    {    
            fprintf(stderr, "fork error/n");
    }    
    else if(pid == 0)    
    {    
            glob++;
            var++;
            printf("child process/n");
            printf("pid = %d, father pid = %d, glob = %d, var = %d/n", 
                        getpid(), getppid(), glob, var); exit(0); } else { sleep(2); printf("father process/n"); printf("pid = %d, father pid = %d, glob = %d, var = %d/n",
                        getpid(), getppid(), glob, var); } return 0; }

运行结果如下:

a write to stdout
before fork
child process pid=13712, father pid=13711, glob=13662, var=7
father process pid=13711, father pid=13539, glob=6, var=6

这表明,父子进程各有各的全局变量。

[作者 高健@博客园  luckyjackgao@gmail.com] 

回到上一级页面: PostgreSQL杂记页     回到顶级页面:PostgreSQL索引页 

磨砺技术珠矶,践行数据之道,追求卓越价值 

原文地址:https://www.cnblogs.com/gaojian/p/2612230.html