1. 程式人生 > >程序建立, 等待, 終止

程序建立, 等待, 終止

一、建立程序

#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;
}