歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux基礎 >> Linux技術 >> linux下進程通信方式

linux下進程通信方式

日期:2017/3/3 11:34:12   编辑:Linux技術
1、概念
不同進程看到共同區域


2、特點
(1)是進程間通信最快的方式,對不同內存的映射(少了兩次拷貝)
(2)不提供任何同步互斥機制,也不自己維護
(3)接口簡單
3、通信方式
由文件系統提供--管道
由system V提供--消息隊列、信號量、共享內存
共享內存與信號量搭配使用
4、實現shmat、shmdt
at:掛接 dt:去掛接
0
1
2
1
0
創建
掛接
被另一進程看到
退出
再退出
代碼實現:
shm.h文件:
#ifndef __SHM__
#define __SHM__
#include<stdio.h>
#include<sys/shm.h>
#include<sys/ipc.h>
#include<sys/wait.h>
#include<unistd.h>
#define __PATH__ "."
#define __PROJECT__ 8888
#define __SHM_SIZE__ 4096
int get_shm();
char* at_shm();
int delete_shm();
int rm_shm();
#endif
shm.c文件:
#include"shm.h"
int get_shm()
{
key_t key=ftok(__PATH__,__PROJECT__);
int flag=IPC_CREAT|0666;
int shm_id=shmget(key,__SHM_SIZE__,flag);
if(shm_id==-1){
printf("get share memory error!\n");
}else{
printf("get share memory success!\n");
}
return shm_id;
}
char *at_shm(int shm_id)
{
return(char*)shmat(shm_id,NULL,0);
}
int delete_shm(char *addr)
{
return shmdt(addr);
}
//if success,return(),else return -1
int rm_shm(int shm_id)
{
return shmctl(shm_id,IPC_RMID,NULL);
}
test_shm.c文件:
#include"shm.h"
int main()
{
int shm_id=get_shm();
pid_t id=fork();
if(id<0){
printf("fork error\n");
return 1;
}else if(id==0){//child
char *buf=at_shm(shm_id);
int i=0;
while(i<4096){
buf[i]='X';
i++;
}
buf[4096]='\0';
delete_shm(buf);
}else{ //father
char *buf=at_shm(shm_id);
sleep(5);
printf("%S\n",buf);
delete_shm(buf);
waitpid(id,NULL,0);
rm_shm(shm_id);
}
return 0;
}
Makefile文件:
test_shm:shm.c test_shm.c
gcc -o $@ $^
.PHONY:clean
clean
rm -f test_shm
運行結果:
[zr@localhost shm]$ makegcc -o test_shm shm.c test_shm.c[zr@localhost shm]$ ./test_shmget share memory success![zr@localhost shm]$
Copyright © Linux教程網 All Rights Reserved