sharemem-use.c

来自「在Linux/UNIX下进程之间通信中的共享内存程序。」· C语言 代码 · 共 75 行

C
75
字号
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <string.h>


#define BUF_NUM (10)
int main()
{
	int id, pid, i;
	char *add;

    id=shmget(IPC_PRIVATE,BUF_NUM,0666);
    
	if(-1 == id)
	{
		printf("shmget error\r\n");
		return -1;
	}
	else
    {
		printf("creat memory successful, shmget is %d\r\n",id);
    }

    pid = fork();

    if(0 < pid)
        {
        add = shmat(id,0,0);
        
    	if((char *)-1 == add)
            {
    		printf("shmat error\r\n");
    		return -1;
    	    }
    	else
            {
    		printf("attached memory, address is %p\r\n", add);
            }
        memset(add, 20, BUF_NUM);
        printf("father: write buffer over\r\n");
        }
    else if(0 == pid)
        {
        sleep(3);
        #if 1
        add = shmat(id,(const void *)0x300000,0);
        #else
        add = shmat(id,0,0);
        #endif
    	if((char *)-1 == add)
            {
    		printf("shmat error\r\n");
    		return -1;
    	    }
    	else
            {
    		printf("attached memory, address is %p\r\n", add);
            }
        printf("child: read buffer\r\n");
        for(i = 0; i < BUF_NUM; i++)
            {
            printf("%d",add[i]);
            }
        printf("\r\n");
        }
    
	
	return 0;
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?