使用shmget在父进程与子进程之间建立一个共享内存段,允许子进程将Fibonacci序列的内容写入共享内存段,父进程等待子进程,当子进程完成后,父进程输出Fibonacci序列。
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <sys/ipc.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/shm.h>
#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