Linux系统编程:fork函数的使用【循环创建N个子线程】
生活随笔
收集整理的這篇文章主要介紹了
Linux系统编程:fork函数的使用【循环创建N个子线程】
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
fork函數介紹
在linux下面進行系統編程,一定要養成一個好習慣,不懂的函數 直接 找男人,用man 指令進行查看,雖然是全英文 但是要強迫自己 學會看英文文檔!下面是介紹,我們看重點。
FORK(2) Linux Programmer's Manual FORK(2)NAMEfork - create a child processSYNOPSIS#include <unistd.h>pid_t fork(void);DESCRIPTIONfork() creates a new process by duplicating the calling process. The new process is referred to as the child process. The callingprocess is referred to as the parent process.The child process and the parent process run in separate memory spaces. At the time of fork() both memory spaces have the samecontent. Memory writes, file mappings (mmap(2)), and unmappings (munmap(2)) performed by one of the processes do not affect theother. RETURN VALUEOn success, the PID of the child process is returned in the parent, and 0 is returned in the child. On failure, -1 is returned inthe parent, no child process is created, and errno is set appropriately.我們重點看RETURN VALUE ,大致意思是 子進程創建成功 將子進程的PID 返回給父進程,且將0 返回給子進程!就是所fork 函數有2個返回值。因為fork成功會有新的子進程產生,和父進程在此處一起往下繼續執行并搶占資源。這個能理解,那么創建循環換創建N個子進程 就手到擒來了。
循環創建N個子進程代碼
代碼很簡單,為了讓進程按順序打印給每個進程加了一個sleep。getpid函數是獲取當前進程的pid,getppid是獲取當前進程的父進程的pid。
#include <stdio.h> #include <unistd.h> #include <sys/types.h> int main() {int i;pid_t pid;for(i = 0; i < 5;i++){pid = fork();//子進程就退出循環,父進程繼續創建子進程if(pid == 0){break;}}if(i < 5){sleep(i);printf("I'm child thread %d,pid=%d,ppid=%d\n",i+1,getpid(),getppid());}else{sleep(i);printf("I'm parent thread,pid=%d,ppid=%d\n",getpid(),getppid());}return 0;}運行結果
可以看到,我們的main函數主進程 也是有父進程的,是bash進程,bash進程運行我們的可執行程序,然后創建main進程。
總結
以上是生活随笔為你收集整理的Linux系统编程:fork函数的使用【循环创建N个子线程】的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 安装redisclient、redis-
- 下一篇: Nvidia Jetson TX2+In