2- 等待進程終止

參考:https://blog.csdn.net/dongyanxia1000/article/details/79239333

https://my.oschina.net/u/3857782/blog/1857551

 

wait()監控子進程結束,這是個阻塞接口,通過下面的示例可以感性認識到。

如果沒有子進程或者子進程不結束會返回失敗。

除了wait()之外,還有wait3()、wait4()、waitpid()等接口,用於監控特定子進程結束

 

示例:

#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<sys/types.h>
#include<sys/wait.h>

int main(void)
{
	pid_t pid;
	int status;
	int loop = 0;
	
	pid = fork();
	
	if(pid > 0)
	{
		printf("%s[%d] i'm parent!  pid is %d \n", __func__, __LINE__, getpid());
	}
	else if(pid == 0)
	{
		for(loop=0;loop<10;loop++)
			printf("%s[%d]:loop(%d) i'm child! pid is %d\n",  __func__, __LINE__, loop, getpid());
		sleep(3);
		abort();
		//exit(0);
	}
	else
	{
		printf("%s[%d] fork err!\n", __func__,  __LINE__);
		exit(-1);
	}
	
	/*以下爲創建爲子進程後,返回父進程繼續執行*/
	printf("fork finish, return father process!\n"); 
	
	/* 阻塞,直到子進程退出 
	如果子進程不執行exit、return、abort等退出動作,會等待失敗*/
	pid = wait(&status);
	if(pid == -1)   
		perror("wait");
	
	/*等待子進程退出成功*/	
	printf("%s[%d] i'm parent! pid=%d\n", __func__,  __LINE__, pid);
	
	/*打印子進程退出的情況
	1- WIFEXITED(status):子進程正常退出;WEXITSTATUS(status)返回status低8位
	2- WIFSIGNALED(status):子進程由信號量終止,例如執行abort();WTERMSIG(status)返回信號編號;WCOREDUMP(status)如果進程終止時生成了core,返回ture
	3- WIFSIGNALED(status):子進程停止或繼續執行;WSTOPSIG(status)返回終止的信號編號
	*/
	if(WIFEXITED(status))
		printf("%s[%d] normal terminal with exit status=%d\n", __func__, __LINE__, WEXITSTATUS(status));
	
	if(WIFSIGNALED(status))
		printf("%s[%d] kill by signal status=%d%s\n", __func__,  __LINE__, WTERMSIG(status), WCOREDUMP(status)? "(dumped core)" : "");
	
	if(WIFSTOPPED(status))
		printf("%s[%d] stopped by signal status=%d\n", __func__,  __LINE__, WSTOPSIG(status));
	
	return 0;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章