淮北市礦務(wù)局工程建設(shè)公司網(wǎng)站網(wǎng)站百度關(guān)鍵詞排名軟件
c/cpp - 多線程/進程 多進程
- 多進程
- 創(chuàng)建多進程
- 進程等待
多進程
宏觀上 兩個進程完全并發(fā)的
父子進程具有互相獨立的進程空間
父進程結(jié)束,不影響子進程的執(zhí)行
創(chuàng)建多進程
#include <sys/types.h>
#include <unistd.h>
#include <stdio.h>int main(){pid_t pid;/* == eg1 ==*/// while (1)// {// // 進程ID號// printf("pid = %d\n",getpid());// // 該進程 的 父進程的ID號// printf("pid parent = %d\n",getppid());// }// /* == eg2 == */// printf("pid = %d\n",getpid());// // 復(fù)制一個進程當作子進程// // 如果調(diào)用成功,返回子進程id號,非0,子進程的id好為0// pid =fork();// printf("pid = %d\n",pid);// printf("hell world"); // fork之后 父進程 子進程都執(zhí)行該語句/* == eg3 ==*/pid_t pid1;pid_t pid2;pid1 =fork();pid2=fork();printf("pid1 = %d, pid2 = %d\n",pid1,pid2);// fork樹/*A -A -A: pid1=id(B), pid2=id(C)-C: pid1=id(B)(拷貝出來的), pid2=0-B -B: pid1=0, pid2=id(D)-D: pid1=0(拷貝出來的), pid2=0 */return 0;
}
例子2
#include <sys/types.h>
#include <unistd.h>
#include <stdio.h>int main(){pid_t pid;pid =fork();printf("pid = %d\n",pid);/*A -A pid=id(B)-B pid=0 *//*宏觀上 兩個進程完全并發(fā)的 父子進程具有互相獨立的進程空間父進程結(jié)束,不影響子進程的執(zhí)行*/// 根據(jù)id號 區(qū)分父進程 子進程,執(zhí)行不同的任務(wù)if (pid>0) // parent process{while (1){printf("parent process running...\n");sleep(1);}}else if (pid==0) // child process{ while (1){printf("child process running...\n");sleep(1);}}else{printf("ERROR: fork failed\n");return -1;}return 0;
}
進程等待
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>int main(int argc,char* argv[])
{pid_t child_pid;int num;for (int i=1;i<argc;i++){switch (fork()){case 0: // 當前是子進程printf("child process %d start id= %d, sleep %s\n",i,getpid(),argv[i]);sleep(atoi(argv[i]));exit(0);break;case -1:perror("fork()\n");exit(0);default:break;}}/*A -A break -A break -A break-A3 exit運行之后結(jié)束,不再fork-A2 exit運行之后結(jié)束不在fork-A1 exit(子進程結(jié)束)不再fork*/num=0;// 表示主進程一直等待,直到所有子進程結(jié)束再結(jié)束主進程while (1){child_pid=wait(NULL); // wait表示多個子進程中的一個結(jié)束就返回if (child_pid==-1) // -1 表示沒有可以正在運行的子進程{printf("no more child process runnig\n");exit(0);}num++;printf("wait() child pid=%d over,num=%d\n",child_pid,num);}return 0;
}/*child process 2 start id= 24667, sleep 10child process 1 start id= 24666, sleep 5child process 3 start id= 24668, sleep 15wait() child pid=24666 over,num=1wait() child pid=24667 over,num=2wait() child pid=24668 over,num=3no more child process runnig*/