zoukankan      html  css  js  c++  java
  • 进程间通信(一)

    1 消息队列

      消息队列是消息的链接表 , 存放在内核中并由消息队列标识符标识。

      m s g g e t用于创建一个新队列或打开一个现存的队列。

      m s g s n d用于将新消息添加到队列尾端。

      m s g r c v用于从队列中取消息。

      调用的第一个函数通常是m s g g e t,其功能是打开一个现存队列或创建一个新队列。

    2信号

    3共享存储

    (1)int shmget(key_t key, int size, int shmflg),开辟或使用一块共享内存。

    (2)void *shmat(int shmid, const void *shmaddr, int shmflg), 将参数shmid所指向的共享内存与当前进程连接。当使用某共享内存时,需要先使用shmat,达成连接。

    (3)int shmdt(const void *shmaddr),将先前用shmat连接的共享内存与当前进程解除连接。参数shmaddr为shmat返回的共享内存的地址。在完成对共享内存的使用后,需要使用shmdt解除连接。

    (4)int shmctl(int shmid, int cmd, struct shmid_ds *buf),控制内存的操作。当cmd为IPC_RMID时,删除shmid所指的共享内存。

     代码示例:

    #include "ourhdr.h"
    #include <sys/shm.h>
    
    #define	ARRAY_SIZE	40000
    #define	MALLOC_SIZE	100000
    #define	SHM_SIZE	100000
    #define	SHM_MODE	0600	/* user read/write */
    
    char	array[ARRAY_SIZE];	/* uninitialized data = bss */
    
    int
    main(void)
    {
    	int		shmid;
    	char	*ptr, *shmptr;
    
    	printf("array[] from %lx to %lx
    ", (unsigned long)&array[0],
    	  (unsigned long)&array[ARRAY_SIZE]);
    	printf("stack around %lx
    ", (unsigned long)&shmid);
    
    	if ((ptr = malloc(MALLOC_SIZE)) == NULL)
    		err_sys("malloc error");
    	printf("malloced from %lx to %lx
    ", (unsigned long)ptr,
    	  (unsigned long)ptr+MALLOC_SIZE);
    
    	if ((shmid = shmget(IPC_PRIVATE, SHM_SIZE, SHM_MODE)) < 0)
    		err_sys("shmget error");
    	if ((shmptr = shmat(shmid, 0, 0)) == (void *)-1)
    		err_sys("shmat error");
    	printf("shared memory attached from %lx to %lx
    ",
    	  (unsigned long)shmptr, (unsigned long)shmptr+SHM_SIZE);
    
    	if (shmctl(shmid, IPC_RMID, 0) < 0)
    		err_sys("shmctl error");
    
    	exit(0);
    }
    

      

  • 相关阅读:
    5.2 spring5源码--spring AOP源码分析三---切面源码分析
    5.2 spring5源码--spring AOP源码分析二--切面的配置方式
    在Dubbo中使用Zookeeper入门案例
    Dubbo直连方式改造
    Dubbo直连方式
    16.3.3 对矢量可执行的其它操作
    16.3.2 可对矢量(vector)执行的操作
    16.3 标准模板库
    16.2.2 有关智能指针的注意事项
    16.2.1 使用智能指针
  • 原文地址:https://www.cnblogs.com/huanhuanang/p/4444311.html
Copyright © 2011-2022 走看看