进程创建, 等待, 终止

一、创建进程

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>

int main()
{
	pid_t ret = fork();
	if (ret > 0)
	{
		printf("father = %d\n", getpid());
		
		while (1)
		{
			sleep(1);
		}
	}
	else if (ret == 0)
	{
		printf("child = %d\n", getpid());
		exit(0);
	}
	else
	{
		perror("fork");
	}
	return 0;
}

二、进程等待

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

int main()
{
	pid_t ret = fork();
	if (ret > 0)
	{
		printf("father = %d\n", getpid());
		wait(NULL);
		while (1)
		{
			sleep(1);
		}
	}
	else if (ret == 0)
	{
		printf("child = %d\n", getpid());
		exit(0);
	}
	else
	{
		perror("fork");
	}
	return 0;
}

三、进程终止

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

int main()
{
	pid_t ret = fork();
	if (ret > 0)
	{
		printf("father = %d\n", getpid());
		int status;
		wait(&status);
		// printf("status = %d\n", status);
		if (status & 0xff)
		{
			printf("进程异常终止! 信号 = %d\n", status & 0x7f);
		}
		else
		{
			printf("进程正常终止! 退出码 = %d\n", (status >> 8) & 0xff);
		}
		while (1)
		{
			sleep(1);
		}
	}
	else if (ret == 0)
	{
		printf("child = %d\n", getpid());
		exit(0);
	}
	else
	{
		perror("fork");
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/xinwenhuayu/article/details/83178143
今日推荐