Ubuntu下Linux程序間通訊 共享記憶體

2021-10-07 00:18:44 字數 1534 閱讀 8854

linux提供了多種程序間通訊的方法,常見有管道(匿名)、fifo(有名管道)、訊息佇列、訊號量、共享記憶體,socket通訊

linux程序間通訊——匿名管道

linux程序間通訊——fifo(有名管道)

linux程序間通訊——訊息佇列

linux程序間通訊——訊號量

linux程序間通訊——共享記憶體

5.共享記憶體

共享記憶體是在記憶體中開闢一段空間,供不同的程序訪問。

#include

#include

intshmget

(key_t key,size_t size,

int shm***)

;void

*shmat

(int shmid,

const

void

*shmaddr,

int shm***)

;int

shmdt

(const

void

*shmaddr)

;

shmget()函式用來建立共享記憶體,key是記憶體標識,size是共享記憶體位元組數,shm***是記憶體操作方式。

shmat()函式是獲取共享記憶體首位址,shmid是共享記憶體id。

例項shm_write.c

#include

#include

#include

#include

#include

#include

intmain()

ptr=

(char*)

shmat

(shmid,0,

0);//獲取共享記憶體首位址if(

(void*)

-1==ptr)

strcpy

(ptr,shm_str)

;//寫入資料

shmdt

(ptr)

;//分離共享記憶體

return0;

}

shm_read.c

#include

#include

#include

#include

#include

#include

intmain()

ptr=

(char*)

shmat

(shmid,0,

0);//獲取共享記憶體首位址if(

(void*)

-1==ptr)

printf

("share memory:%s\n"

,ptr)

;//列印資料

shmdt

(ptr)

;//分離共享記憶體if(

shmctl

(shmid, ipc_rmid,0)

==-1)

//釋放記憶體

return0;

}

never give up!

Ubuntu下Linux程序間通訊 匿名管道

linux程序間通訊 匿名管道 linux程序間通訊 fifo 有名管道 linux程序間通訊 訊息佇列 linux程序間通訊 訊號量 linux程序間通訊 共享記憶體 linux提供了多種程序間通訊的方法,常見有管道 匿名 fifo 有名管道 訊息佇列 訊號量 共享記憶體,socket通訊。1.匿...

Ubuntu下Linux程序間通訊 訊號量

linux提供了多種程序間通訊的方法,常見有管道 匿名 fifo 有名管道 訊息佇列 訊號量 共享記憶體,socket通訊。linux程序間通訊 匿名管道 linux程序間通訊 fifo 有名管道 linux程序間通訊 訊息佇列 linux程序間通訊 訊號量 linux程序間通訊 共享記憶體 4.訊...

linux下程序間通訊

linux下程序間通訊的幾種主要手段簡介 管道 pipe 及有名管道 named pipe 管道可用於具有親緣關係程序間的通訊,有名管道克服了管道沒有名字的限制,因此,除具有管道所具有的功能外,它還允許無親緣關係程序間的通訊 訊號 signal 訊號是比較複雜的通訊方式,用於通知接受程序有某種事件發...