天天看點

linux多程序

使用fork建立子程序

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
int main(){

pid_t pid;
pid=fork();

if(pid==0){
	while(1){
		printf("this is the child process\n");
		sleep(1);
	}
}
else{
	while(1){
		printf("this is the father process\n");
		sleep(1);
	}
	
}

}
           

運作效果如下

this is the father process
this is the child process
this is the father process
this is the child process
this is the father process
this is the child process
this is the father process
this is the child process

           

vfork

vfork函數用于建立一個新程序,而該新程序的目的是exec一個新程序。

vfork與fork都建立一個子程序,但是它并不會将父程序的位址空間完全複制到子程序中,因為子程序會立即調用exec或exit,于是也就不會引用該位址空間。不過在子程序中調用exec或exit之前,它在父程序的空間中運作。

vfork與fork的另一個差別是:vfork保證子程序先運作,在它調用exec或exit之後父程序才開始運作。

wait和waitpid

  • wait函數等待子程序的結束信号。

    它是阻塞函數,隻有任意一個子程序結束,它才能繼續往下執行,否則卡住那裡等。

  • waitpid等待指定pid對應的程序結束,可以選擇阻塞或者不阻塞的方式。

exec

exec系列的函數有很多個,主要用來執行一個新的程式,即用一個全新的程式來替換子程序的内容。

參考文章

Linux多程序程式設計(典藏、含代碼)

《UNIX環境進階程式設計》

繼續閱讀