[真1][9][单选]对于如下 C 语言程序
int main() { pid_t pid; int a = 5; pid = fork(); if (pid == 0) printf("This is the son process, a=%d\n", ++a); else printf("This is the dad process, a=%d\n", --a); }
在 UNIX 操作系统中正确编译链接后运行,其运行结果为
This is the son process, a = 6 This is the dad process, a = 4
This is the son process, a = 6
This is the dad process, a = 4
This is the dad process, a = 6 This is the son process, a = 4
答案
This is the son process, a = 6 This is the dad process, a = 4
解析
fork(函数调用的返回值有两种情况:若返回值为 0,表示子进程返回;若返回值为 - 1,表示创建子进程失败;若返回值为大于 0 的值,表示父进程返回,返回值为子进程的进程 ID。在上述程序中,父进程和子进程都有自己独立的数据空间,在父进程中 a = 5,在子进程中 a = 5。当子进程执行时,a 先输出为 5 然后自增为 6;当父进程执行时,a 先输出为 5 然后自减为 4。故选择 A 选项。
转载请注明出处。