網站首頁 編程語言 正文
問題提出:
回想一下:當一個程序只有主線程的時候調用fork,此時fork會創建出的子進程也會只有一條線程;
那要是把fork放入多線程的程序中呢?
我們來試驗下:
情況(1)fork在創建子線程之前
代碼:
#include <stdio.h> #include <pthread.h> #include <unistd.h> void* pthread_fun(void* arg) { printf("fun = %d\n", getpid()); pthread_exit(NULL); } int main() { fork(); pthread_t id; pthread_create(&id, NULL, pthread_fun, NULL); printf("main_pid = %d\n", getpid()); pthread_join(id, NULL); return 0; }
結果:fork出的子進程也會創建自己的子線程(兩個進程:四個線程
)
情況(2)fork在創建子線程之后
代碼:
#include <stdio.h> #include <pthread.h> #include <unistd.h> void* pthread_fun(void* arg) { printf("fun = %d\n", getpid()); pthread_exit(NULL); } int main() { pthread_t id; pthread_create(&id, NULL, pthread_fun, NULL); fork(); printf("main_pid = %d\n", getpid()); pthread_join(id, NULL); return 0; }
結果:創建子線程之后,再創建子進程,此時fork的子進程只會執行fork之后的代碼(兩個進程:三個線程
)
情況(3)子線程中的fork
代碼:
#include <stdio.h> #include <pthread.h> #include <unistd.h> void* pthread_fun(void* arg) { fork(); printf("fun = %d\n", getpid()); pthread_exit(NULL); } int main() { pthread_t id; pthread_create(&id, NULL, pthread_fun, NULL); printf("main_pid = %d\n", getpid()); pthread_join(id, NULL); return 0; }
結果:
結論:
fork處于哪個線程中,fork后創建的子進程將以該線程作為自己的主線程,并且執行該線程之后的代碼
原文鏈接:https://blog.csdn.net/xiaoxiaoguailou/article/details/121615303
相關推薦
- 2022-12-03 Golang檢查變量類型的四種方式_Golang
- 2022-11-03 C#中委托、事件和回調的使用及說明_C#教程
- 2022-09-14 Python定制類你不知道的魔術方法_python
- 2022-07-24 C語言超詳細i講解雙向鏈表_C 語言
- 2022-08-05 C#正則表達式Regex用法詳解_C#教程
- 2023-10-25 el-tree設置選中高亮/焦點高亮、選中的節點加深背景,更改字體顏色等
- 2022-09-03 Golang棧結構和后綴表達式實現計算器示例_Golang
- 2022-04-12 網絡編程——Http請求方式Get與Post
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支