linux程式設計 程序間通訊 共享記憶體

2021-08-05 19:46:52 字數 2265 閱讀 5257

共享記憶體程序間通訊機制主要用於實現程序間大量的資料傳輸。

1  建立共享記憶體

#include

#include

int shmget(key_t key, size_t size, int shm***);

2  共享記憶體控制

int shmctl(int shmid, int cmd, struct shmid_ds *buf);

3  對映共享記憶體物件

void *shmat(int shmid, const void *shmaddr, int shm***);

4分離共享記憶體物件

int shmdt(const void *shmaddr);

例項一父子程序通過共享記憶體通訊

#include

#include

#include

#include

#include

#include

#include

#include

int main(int argc,char* argv)

if(childpid == 0)

if((ptr = (char*)shmat(id,0,0)) == null)

for(i=0;argv[1][i]!='\0';i++)

printf("this is child.\nwrite argv[1] to shm.\nyou input charater count is %d\n",i);

exit(exit_success);

}else

if((ptr = (char*)shmat(id,0,0)) == null)

printf("this is parent.\ninput character is %s\n",ptr);

if(shmctl(id,ipc_rmid,null) == -1)

exit(exit_success);}}

例項二兩個程序通過共享記憶體通訊

同時,使用訊號量來保證兩個程序的讀寫同步。

傳送方程式如下

#include

#include

#include

#include

#include

#include

#include

#include

int main(int argc,char* argv)

if(semctl(semid,0,setval,0) == -1)

exit(exit_failure);

}key_t key1;

key1 = ftok("tmp2",4);

shid = shmget(key1,10*sizeof(char),0600|ipc_creat);

if(shid == -1)

sharem = shmat(shid,null,0);

if(sharem == null)

while(running)

}if(strcmp(sharem,"end") == 0)

running--;

}shmdt(sharem);

return 0;

}接收方程式如下

#include

#include

#include

#include

#include

#include

#include

#include

int main(int argc,char* argv)

if(semctl(semid,0,setval,0) == -1)

exit(exit_failure);

}key_t key1;

key1 = ftok("tmp2",4);

shid = shmget(key1,10*sizeof(char),0600|ipc_creat);

if(shid == -1)

sharem = shmat(shid,null,0);

if(sharem == null)

while(running)

printf("%s\n",sharem);

}if(strcmp(sharem,"end") == 0)

running--;

}shmdt(sharem);

if(shmctl(shid,ipc_rmid,0) != 0)

if(semctl(semid,ipc_rmid,0) != 0)

return 0;

}

Linux高階程式設計基礎 程序間通訊之共享記憶體

建立共享記憶體,寫程序每隔2秒向記憶體寫入一次 hello world 如果結束寫操作,則寫程序寫入 end 讀程序從共享記憶體讀取資料,並列印。直到讀到 end 為止。這是寫程序 include include include include include include include inc...

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

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

Linux程序間通訊 共享記憶體

共享記憶體是執行在同一臺機器上的程序間通訊最快的方式,因為資料不需要在不同的程序間複製。通常由乙個程序建立一塊共享記憶體區,其餘程序對這塊記憶體區進行讀寫。共享記憶體往往與其它通訊機制,如訊號量結合使用,來達到程序間的同步及互斥。首先要用的函式是shmget,它獲得乙個共享儲存識別符號。i nclu...