[21][9][单选]对于如下 C 语言程序
int main( { pid_t pid; int a = 20; pid = fork(; if(pid == 0 printf("This is the son process, a=%d\n", a - 1; else printf("This is the dad process, a=%d\n", a + 1; } 在 UNIX 操作系统中正确编译链接后执行,其运行结果是
This is the son process, a=19 This is the dad process, a=21
This is the son process, a=18
This is the dad process, a=22
This is the dad process, a=19 This is the son process, a=21
答案
This is the son process, a=19 This is the dad process, a=21
解析
在 UNIX 类操作系统中,父进程通过调用 fork(函数创建子进程,子进程获得与父进程地址空间相同的一份拷贝,包括文本、数据、堆栈段、以及用户栈,fork 函数被调用一次,却返回两次:一次是在调用进程中,一次是在新创建的子进程中,所以题目程序中的变量 a,在父进程和子进程中存在 2 份,初始值都是 20,程序运行后子进程输出 a = 19,父进程输出 a = 21。
涉及考点:第 3 章 进程线程模型
转载请注明出处。