wait以及waitpid函数使用

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/qq_33472414/article/details/102546118

wait以及waitpid函数是干嘛的?
可以用来回收子进程结束的相关信息


wait:

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



int main(void)
{
	pid_t pid = -1;
	pid_t ret = -1;
	int status = -1;
	
	pid = fork();
	if (pid > 0)
	{
		// 父进程
		//sleep(1);
		printf("parent.\n");
		ret = wait(&status); //这里会阻塞,直到子进程结束
		
		printf("子进程已经被回收,子进程pid = %d.\n", ret);
		printf("子进程是否正常退出:%d\n", WIFEXITED(status));
		printf("子进程是否非正常退出:%d\n", WIFSIGNALED(status));
		printf("正常终止的终止值是:%d.\n", WEXITSTATUS(status));
	}
	else if (pid == 0)
	{
		sleep(10);
		// 子进程
		printf("child pid = %d.\n", getpid());
		return 51;
		//exit(0);
	}
	else
	{
		perror("fork");
		return -1;
	}
	
	return 0;
}

waitpid:

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



int main(void)
{
	pid_t pid = -1;
	pid_t ret = -1;
	int status = -1;
	
	pid = fork();
	if (pid > 0)
	{
		// 父进程
		//sleep(1);
		printf("parent, 子进程id = %d.\n", pid);
		//ret = wait(&status);
		//ret = waitpid(-1, &status, 0); //回收任意子进程,相当于wait
		ret = waitpid(pid, &status, 0); //阻塞式
		//ret = waitpid(pid, &status, WNOHANG);		// 非阻塞式
		
		printf("子进程已经被回收,子进程pid = %d.\n", ret);
		printf("子进程是否正常退出:%d\n", WIFEXITED(status));
		printf("子进程是否非正常退出:%d\n", WIFSIGNALED(status));
		printf("正常终止的终止值是:%d.\n", WEXITSTATUS(status));
	}
	else if (pid == 0)
	{
		// 子进程
		sleep(10);
		printf("child pid = %d.\n", getpid());
		return 51;
		//exit(0);
	}
	else
	{
		perror("fork");
		return -1;
	}
	
	return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_33472414/article/details/102546118