Chinaunix首页 | 论坛 | 博客
  • 博客访问: 539874
  • 博文数量: 156
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 1183
  • 用 户 组: 普通用户
  • 注册时间: 2013-11-22 11:42
文章分类

全部博文(156)

文章存档

2015年(67)

2014年(89)

分类: LINUX

2014-12-04 10:20:25


  1. /***************************************************************
  2.  *  fork如果成功,在子进程里return 0, 在父进程里return 子进程里的pid
  3.  *  pid > 0, getpid返回当前进程的pid, getpid返回当前进程的父进程pid
  4.  *  fork函数将父进程拷贝一份,变量也被拷贝一份,当fork返回以后,会有两段
  5.     一样的代码执行,但是先后顺序不确定,根据内核决定
  6.  ***************************************************************/
  7. #include
  8. #include <unistd.h>
  9. #include <sys/types.h>
  10. #include <stdlib.h>

  11. int g = 6;

  12. int main()
  13. {
  14.     pid_t pid;

  15.     printf("before fork \n");
  16.     if((pid = fork()) < 0)
  17.     {
  18.         printf("fork error \n");
  19.     }

  20.     else if(pid == 0)
  21.     {
  22.         g++; //7
  23.         printf("I am in child process \n");
  24.     }

  25.     else
  26.     {
  27.      sleep(2); //6
  28.         printf("I am in parent process \n");
  29.         printf("%d\n", pid); //printf child process pid
  30.     }

  31.     printf("%d\n", g);
  32.     printf("%d\n", getpid()); //printf parent process pid

  33.     exit(0);
  34. }

       输出结果:

            

阅读(923) | 评论(0) | 转发(0) |
1

上一篇:Fab

下一篇:getpid1

给主人留下些什么吧!~~