C语言多进程共享内存

使用shmget在父进程与子进程之间建立一个共享内存段,允许子进程将Fibonacci序列的内容写入共享内存段,父进程等待子进程,当子进程完成后,父进程输出Fibonacci序列。

#include 
#include 
#include 
#include 
#include 
#include 
#include 
#define SIZE 1024

int main()
{
	int shmid ;
	int *shmaddr ;
	struct shmid_ds buf ;
	int fib[20] ={0,1};
	int flag = 0;
	int pid ;

	//a.accept the argc and check error
	int num;
	printf("please input a finger.\n");
	scanf("%d",&num);
	if(num<0)
	{
		printf("number should be >=0.");
		return -1;
	}
	
	//b.new a shm
	shmid = shmget(IPC_PRIVATE, SIZE, IPC_CREAT|0600 ) ;//shm flag
	if ( shmid < 0 )
	{
		perror("new shm error") ;
		return -1 ;
	}

	//d.new child prossess	
	pid = fork() ;
	if ( pid == 0 )//child process
	{
        //c.connent address
        shmaddr = (int *)shmat( shmid, NULL, 0 ) ;
		if ( (int)shmaddr == -1 )
		{
			perror("shmat addr error") ;
			return -1 ;
		}

		//e.make fibonacci in child process,write and lost connent
		if(num == 1)
			fib[1] = fib[2];
		else if(num > 2)
		{
			for(int i = 2;i <= num - 1;i++)
				fib[i] = fib[i - 1] + fib[i - 2];
		}

		shmaddr = fib;

        shmdt( shmaddr ) ;//lost connect
		return 0;
	} 
	else if ( pid > 0)//parent process
   	{
		//f.printf ansswer in parent process
		int status;
		wait(&status);
		flag = shmctl( shmid, IPC_STAT, &buf) ;//manage
		if ( flag == -1 )
		{
			perror("shmctl shm error") ;
			return -1 ;
		}

		shmaddr = (int *) shmat(shmid, NULL, 0 ) ;//put into process address
		if ( (int)shmaddr == -1 )
		{
			perror("shmat addr error") ;
			return -1 ;
		}

		for(int j = 1;j <= num;j ++)
		{
			printf("%d ",*shmaddr);
			shmaddr ++;
		}
       	printf("\n");
		
	//	g.lost and delete shm
		shmdt( shmaddr ) ;
		shmctl(shmid, IPC_RMID, NULL) ;
	}
	else
	{
		perror("fork error") ;
		shmctl(shmid, IPC_RMID, NULL) ;
	}
	return 0 ;
}

最终不能输出fibonacci序列,输出为0常数列。原因待查。

将整型数组fib[]转化为字符串,可以得到正确输出。

你可能感兴趣的:(C语言多进程共享内存)