Linux下父子进程的全局变量
生活随笔
收集整理的這篇文章主要介紹了
Linux下父子进程的全局变量
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
磨礪技術珠磯,踐行數據之道,追求卓越價值?
回到上一級頁面: PostgreSQL雜記頁 ? ? 回到頂級頁面:PostgreSQL索引頁?
[作者 高健@博客園 ?luckyjackgao@gmail.com]?
用這個從網上找的例子,看父子進程對全局變量的擁有是否不同:
復制代碼 #include <sys/types.h> ? ? #include <stdio.h> ? ? #include <stdlib.h> ? ? int glob = 6; ? ? char buf[] = "a write to stdout\n"; ? ? int main() ? ? { ? ? int var; ? ? pid_t pid; ? ? var = 88; ? ? fprintf(stderr, "%s", buf);? printf("before fork/n"); ? ? if(( pid = fork() ) < 0 ) ? ? { ? ? fprintf(stderr, "fork error/n"); } ? ? else if(pid == 0) ? ? { ? ? glob++; var++; printf("child process/n"); printf("pid = %d, father pid = %d, glob = %d, var = %d/n",? getpid(), getppid(), glob, var); exit(0); } ? ? else ? ? { ? ? sleep(2); printf("father process/n"); printf("pid = %d, father pid = %d, glob = %d, var = %d/n",? getpid(), getppid(), glob, var); } ? ? return 0; ? ? } 復制代碼 運行結果如下:
a write to stdout before fork child process pid=13712, father pid=13711, glob=13662, var=7 father process pid=13711, father pid=13539, glob=6, var=6
這表明,父子進程各有各的全局變量。
本文轉自健哥的數據花園博客園博客,原文鏈接:http://www.cnblogs.com/gaojian/archive/2012/07/27/2612230.html,如需轉載請自行聯系原作者
回到上一級頁面: PostgreSQL雜記頁 ? ? 回到頂級頁面:PostgreSQL索引頁?
[作者 高健@博客園 ?luckyjackgao@gmail.com]?
用這個從網上找的例子,看父子進程對全局變量的擁有是否不同:
復制代碼 #include <sys/types.h> ? ? #include <stdio.h> ? ? #include <stdlib.h> ? ? int glob = 6; ? ? char buf[] = "a write to stdout\n"; ? ? int main() ? ? { ? ? int var; ? ? pid_t pid; ? ? var = 88; ? ? fprintf(stderr, "%s", buf);? printf("before fork/n"); ? ? if(( pid = fork() ) < 0 ) ? ? { ? ? fprintf(stderr, "fork error/n"); } ? ? else if(pid == 0) ? ? { ? ? glob++; var++; printf("child process/n"); printf("pid = %d, father pid = %d, glob = %d, var = %d/n",? getpid(), getppid(), glob, var); exit(0); } ? ? else ? ? { ? ? sleep(2); printf("father process/n"); printf("pid = %d, father pid = %d, glob = %d, var = %d/n",? getpid(), getppid(), glob, var); } ? ? return 0; ? ? } 復制代碼 運行結果如下:
a write to stdout before fork child process pid=13712, father pid=13711, glob=13662, var=7 father process pid=13711, father pid=13539, glob=6, var=6
這表明,父子進程各有各的全局變量。
本文轉自健哥的數據花園博客園博客,原文鏈接:http://www.cnblogs.com/gaojian/archive/2012/07/27/2612230.html,如需轉載請自行聯系原作者
總結
以上是生活随笔為你收集整理的Linux下父子进程的全局变量的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Python 学习笔记 -- 继承与多态
- 下一篇: 线程工具类(根据电脑逻辑处理器个数控制同