Linux System Programming 37 Process Control-Cross Allocation Method of Process Allocation

Previously, N processes were used to calculate whether N natural numbers are prime. This method is flawed. If the value of N is very large, then it is not very realistic.

So you can consider the cross allocation method of the process to realize the calculation, as follows, the parent process forks () 3 child processes, and the 3 child processes are used to calculate N natural numbers.

The cross-distribution method of processes realizes finding prime numbers

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

#define LEFT 200
#define RIGHT 250
#define N 3


int main(void)
{
	int i,j,mark,n;
	pid_t pid;
	
	for(n = 0; n < N; n++)
	{
		pid = fork();
		if(pid < 0)
		{
			fprintf(stderr,"fork() failed!\n");
			exit(1);
		}
		else if(pid == 0)//child
		{
			
			for(i = LEFT+n; i <= RIGHT; i+=N)
			{
				mark = 1;
				for(j = 2; j < i/2; j++)
				{
					if(i % j ==0)
					{
						mark = 0;
						break;
					}
			
				}

				if(mark)
					printf("[%d]%d is a primer\n",n,i);
			}

			exit(0);//!!!
		}
		
	}

	for(n = 0;n < N; n++)
		wait(NULL);

	exit(0);
}




mhr@ubuntu:~/Desktop/xitongbiancheng/test$ gcc test.c 
mhr@ubuntu:~/Desktop/xitongbiancheng/test$ 
mhr@ubuntu:~/Desktop/xitongbiancheng/test$ ./a.out 
[2]211 is a primer
[2]223 is a primer
[2]229 is a primer
[2]241 is a primer
[0]227 is a primer
[0]233 is a primer
[0]239 is a primer
mhr@ubuntu:~/Desktop/xitongbiancheng/test$ 

As a result, it can be seen that process 0 and process 2 have obtained several prime numbers respectively. The disorder is due to process scheduling problems.

The parent process fork() three child processes continuously, and then waits for the child process to terminate and release resources. The three child processes continue to execute from the position where they were fork(), and terminate the process after calculation.

Guess you like

Origin blog.csdn.net/LinuxArmbiggod/article/details/113795423