1.多进程并发

题目:编写程序,利用fork()产生来两个进程,首先显示一下两个子进程及父进程的进程标识符,然后,让父进程显示1-26个数字,子进程1显示26个大写字母,子进程2显示26个小写字母。让大小写字母及数字夹杂交错输出。

#include<stdio.h>
#include<string.h>
#include<unistd.h>
int main()
{
	int p1, p2;
	int i = 1;
	char ch1 = 'A', ch2 = 'a';
	while((p1 = fork()) == -1);
	if(p1)
	{
		while((p2 = fork()) == -1);
		if(p2)
		{
			//parent;
			printf("This is parent process, pid = %d\n", getpid());
			while(i <= 26)
			{
				printf("Parent process print : %d\n", i);
				i = i + 1;
				sleep(1);
			}
		}
		else
		{
			//child2
			printf("This is child process2, pid = %d\n", getpid());
			while(ch2 <= 'z')
			{
				printf("Child process2 print : %c\n", ch2);
				ch2 = ch2 + 1;
				sleep(1);
			}
		}
	}//if
	else
	{
		//child1
		printf("This is child process1, pid = %d\n", getpid());
		while(ch1 <= 'Z')
		{
			printf("Child process1 print : %c\n", ch1);
			ch1 = ch1 + 1;
			sleep(1);
		}
	}//else
	return 0;
}

修改程序,让两个子进程夹杂输出结束后,父进程输出开始。

#include<stdio.h>
#include<string.h>
#include<unistd.h>
int main()
{
	int p1, p2;
	int i = 1;
	char ch1 = 'A', ch2 = 'a';
	while((p1 = fork()) == -1);
	if(p1)
	{
		while((p2 = fork()) == -1);
		if(p2)
		{
			//parent;
			printf("This is parent process, pid = %d\n", getpid());
			wait(0);//修改
			wait(0);//修改
			while(i <= 26)
			{
				printf("Parent process print : %d\n", i);
				i = i + 1;
				sleep(1);
			}
		}
		else
		{
			//child2
			printf("This is child process2, pid = %d\n", getpid());
			while(ch2 <= 'z')
			{
				printf("Child process2 print : %c\n", ch2);
				ch2 = ch2 + 1;
				sleep(1);
			}
		}
	}//if
	else
	{
		//child1
		printf("This is child process1, pid = %d\n", getpid());
		while(ch1 <= 'Z')
		{
			printf("Child process1 print : %c\n", ch1);
			ch1 = ch1 + 1;
			sleep(1);
		}
	}//else
	return 0;
}


你可能感兴趣的:(wait,多进程并发)