【发布时间】:2015-10-24 14:28:27
【问题描述】:
我知道 fork() 中的父进程和子进程都是两个独立的进程,但我试图了解静态变量在子进程中声明和初始化时的行为。请考虑以下代码:
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
static int z = 99;
void main(){
int x=99;
int pid;
pid = fork();
switch(pid){
case -1: printf("fork failed.");break;
case 0: printf("I am the Child[PID=%d].\n",getpid());
static int y=99;
x++;y++;z++;
printf("x=%d, y=%d, z=%d\n",x,y,z);break;
default: wait(NULL);
//int y = 99;
printf("Child has finished. I am the parent[PID=%d].\n",getpid());
printf("x=%d, y=%d, z=%d\n",x,y,z);
}
}
输出:
为什么在父 printf 语句中 y 的值为 99?尽管父母等待孩子完成,并且在孩子中,y的值在设置为99后更改为100“y++”。
【问题讨论】: