systemv 訊息佇列使用訊息佇列識別符號標識,這個標識好像鍊錶中的頭節點,包含了許多資訊,當然最主要的還是指向資料節點的兩個指標msg_first
和msg_last
,分別表示訊息佇列中的第乙個和最後乙個訊息節點。
操作systemv訊息佇列的函式。
其中#include
#include
#include
int msgget(key_t key, int msg***);
key
既可以是ipc_private
,也可以是ftok
函式的返回值。當key
的值為ipc_private
或者當前沒有訊息佇列與給定key
相關聯時,將建立乙個新的訊息佇列。
msg***
指定獲取訊息佇列時的許可權組合:當它被指定ipc_creat
和ipc_excl
時且跟key
關聯的訊息佇列已經存在,則msgget
呼叫失敗且設定errno=eexist
msgget
開啟乙個訊息佇列後,我們使用msgsnd往其放乙個訊息,好像鍊錶插入新節點。
#include
#include
#include
int msgsnd(int msqid, const
void *msgp, size_t msgsz, int msg***);
msqid
是msgget返回的識別符號
msgp
是乙個結構指標,它有乙個模板:
struct msgbuf ;
不過一般情況下,應用通常使用自己定義的訊息型別,訊息內容也不僅僅侷限於文字,因為對於msgp
來說,它只是乙個指標而已。
從訊息佇列中讀出乙個訊息。
其中#include
#include
#include
ssize_t msgrcv(int msqid, void *msgp, size_t msgsz, long msgtyp, int msg***);
msgp
引數指定接收訊息的存放位置,與msgsnd
一樣,該指標指向緊挨在真正的訊息資料之前返回的長整數型別字段。
msgsz
指定了資料大小,不包含型別字段。
msgtyp
指定讀出訊息的型別。
msg***
指定請求型別訊息不在佇列時怎麼處理。
成功返回時,將返回接收訊息中資料的位元組數,不含訊息型別的那幾個位元組。
依然是實現簡單生產者消費者模型,不同管道,某個程序往乙個佇列中寫入乙個訊息之前,不求另乙個某個程序正在等待該佇列上的乙個訊息到達。
資料結構定義
#ifndef __msg_h__
#define __msg_h__
#define maxsize 256
struct message_
;typedef
struct message_ message;
#endif
傳送方(生產者)
//sysv_send.c
#include
#include
#include
#include
#include
#include
#include "msg.h"
int main(int argc,char **argv)
msqid=msgget(key,mflag);//msgget函式呼叫
if((msqid < 0) && (errno!=eexist))//msgget失敗且不是因為訊息佇列已經存在
if(msqid < 0)//訊息佇列已經存在
}memset(&msg,0x00,sizeof(message));
strcpy(msg.buff,"helloworld666");
msg.mlength=strlen(msg.buff);
int i;
for(i = 0;i < 3;i++ )
}return
0;}
接收方(消費者)
#include
#include
#include
#include
#include
#include
#include "msg.h"
int main(int argc,char **argv)
msqid=msgget(key,ipc_creat);//將忽視ipc_creat關鍵字
if (msqid < 0)
memset(&msg,0x00,sizeof(message));
int i;
for(i=2;i>=0;i--)
msgctl(msqid,ipc_rmid,0);//刪除訊息佇列
return
0;}
makefile
終端可以使用# makefile
progs =send recv
cleanfiles = core core.*
*.core
*.otemp.*
*.out typescript* \
*.lc
*.lh
*.bsdi
*.sparc
*.uw
all :$
cflags+=-g
libs+=
recv: sysv_recv.o
@$$$ $^ -o $@ $
@rm*.o
send: sysv_send.o
@$$$ $^ -o $@ $
@rm*.o
clean:
rm -f $
$
ipcs
等命令檢視和操作systemv ipc物件。 linux程序間通訊 筆記
用於程序間通訊,建立乙個管道,一端寫,一端讀 include intpipe int fildes 2 fides 0 讀取,fides 1 寫入 成功返回0,失敗返回 1 示例 include include include include include intmain pid t pid fo...
程序間通訊筆記 2
訊號量 訊號量一般配合其他方式一起使用,主要實現程序間的互斥與同步,而不是快取資料。訊號量表示資源的數量,控制訊號量的方式有兩種原子操作 p操作 將這個訊號量減一,減一後如果訊號量小於0代表資源已被占用程序需要阻塞等待。反之表明資源可用可以正常執行。v操作 把訊號量加一,加一後如果訊號量大於等於0代...
System V程序間通訊 共享記憶體
一 共享記憶體ipc原理 共享記憶體程序間通訊機制主要用於實現程序間大量資料的傳輸,共享記憶體是在記憶體中單獨開闢的一段記憶體空間,這段記憶體空間有自己特有的資料結構,包括訪問許可權 大小和最近訪問時間。資料結構定義如下 struct shmid ds 兩個程序在使用此共享記憶體空間之前,需要在程序...