对于如下C语言程序 int main() { pid_t pid; int a=1; pid=fork(); if(pid==0、 pfintf(“This is the son process,a=%d\n”,++a);

admin2021-03-19  27

问题 对于如下C语言程序
  int main()
  {
  pid_t pid;
  int a=1;
  pid=fork();
  if(pid==0、
  pfintf(“This is the son process,a=%d\n”,++a);
  else
  pfintf(“This is the dad process,a=%d\n”,--a);
  }
  在UNIX操作系统中正确编译链接后,其运行结果为(    )。

选项 A、This is the son process,a=2
    This is the dad process,a=0
B、This is the son process,a=2
C、This is the dad process,a=0
D、This is the dad process,a=2
    This is the son process,a=09

答案A

解析 函数fork()的作用是通过系统调用创建一个与原来进程几乎完全相同的进程。对于子进程返回标识符0;对于父进程返回子进程的PID。父进程和子进程拥有各自的局部变量a,初始值都为1;所以子进程中PID为0,执行的是第1个printf,由a的值为1,先自增再输出值,可知输出的是This is the son process,a=2;而父进程中PID为子进程的PID,不为0,执行的是第2个printf,由a的值为1,先自减再输出值,可知输出的是This is the dadpFocess.a=0。故本题答案选择A选项。
转载请注明原文地址:https://kaotiyun.com/show/3K8Z777K
0

最新回复(0)