1. 程式人生 > >父程序利用fork()函式建立子程序並且利用shared_memory進行通訊的例項

父程序利用fork()函式建立子程序並且利用shared_memory進行通訊的例項

#include<stdio.h>
#include<unistd.h>
#include<sys/shm.h>
#include<sys/stat.h>
#define Maxsize 10
typedef struct
{
    int a[Maxsize];
    int length;
}A;
int main()
{
    int segment_id,fp;
    A* shared_mem;
    segment_id=shmget(IPC_PRIVATE,sizeof(A),S_IRUSR|S_IWUSR);
    fp=fork();
    if(fp==0)//說明是子程序
    {
        printf("i am son!\n");
        shared_mem=(A *)shmat(segment_id,NULL,0);
        shared_mem->a[0]=4;
        shared_mem->a[1]=1;
        shared_mem->length=2;
        shmdt(shared_mem);
    }
    else if(fp>0)
    {
        printf("i am father\n");
        for(int i=0;i<2;i++)
        {
            wait(NULL);
            shared_mem=(A *)shmat(segment_id,NULL,0);
            printf("1 %d  2 %d",shared_mem->a[0],shared_mem->a[1]);
            printf("length is %d",shared_mem->length);
            shmdt(shared_mem);
            shmctl(segment_id,IPC_RMID,NULL);
            exit(0);
        }

    }
}