2014-05-12 65 views
1

我需要在Linux中使用消息操作(msgrcv,msgsnd,msgctl)實現二進制信號量。 我的代碼:使用消息操作的二進制信號量

#include<string.h> 
#include<time.h> 
#include<sys/ipc.h> 
#include<sys/msg.h> 
#include<sys/wait.h> 
#include<sys/errno.h> 

extern int errno;  // error NO. 
#define MSGPERM 0600 // msg queue permission 
#define MSGTXTLEN 60 // msg text length 

int msgqid, rc; 
int done; 

struct msg_buf 
{ 
    long mtype; 
    char mtext[MSGTXTLEN]; 
} msg,msg2; 

int main(int argc,char **argv) 
{ 
    msgqid = msgget(IPC_PRIVATE, MSGPERM|IPC_CREAT); 
    if (msgqid < 0) 
    {  
     perror(strerror(errno)); 
     printf("Failed to create message with id = %d\n", msgqid); 
     return 1; 
    } 
    printf("Message %d created\n",msgqid); 


    // message to send 
    msg.mtype = 1; // set the type of message 
    sprintf (msg.mtext, "%s\n", "Old message..."); 
    rc = msgsnd(msgqid, &msg, sizeof(msg.mtext), 0); 
    if (rc < 0) 
    { 
     perror(strerror(errno)); 
     printf("Could not send, rc = %d\n", rc); 
    } 

    // message to send 
    msg.mtype = 1; // set the type of message 
    sprintf (msg.mtext, "%s\n", "New message..."); 
    rc = msgsnd(msgqid, &msg, sizeof(msg.mtext), 0); 
    if (rc < 0) 
    { 
     perror(strerror(errno)); 
     printf("Could not send, rc = %d\n", rc); 
    } 

    // read the message from queue 
    rc = msgrcv(msgqid, &msg, sizeof(msg.mtext), 0, 0); 
    if (rc < 0) 
    { 
     perror(strerror(errno)); 
     printf("Could not read, rc=%d\n", rc); 
    } 
    printf("Received message: %s\n", msg.mtext); 

    // remove the queue 
    rc=msgctl(msgqid,IPC_RMID,NULL); 
    if (rc < 0) 
    { 
     perror(strerror(errno)); 
     printf("Deleting message failed, rc=%d\n", rc); 
    } 
    printf("Message %d deleted\n",msgqid); 

    return 0; 
} 

據我所知消息操作的力學,所述第一消息與FLAG 0,不IPC_NOWAIT發送,因此所述第二消息將不能夠被髮送。實際上,我的程序正確地打印了舊的消息,但試圖發送第二封消息的過程並不像預期的那樣結束。

編輯

演習的主要目標是:「使用渠道和信息創建一個二進制信號」 該指令中的示例僅包含這四個函數用法(msgget,msgsnd,msgctl,msgrcv)和一些標誌。

+0

您可以備份並描述分配,而不是您的解決方案中感知的障礙嗎? – Duck

+0

在編輯部分進行了描述。 – Cheslav

+0

什麼是「頻道」 - 多個msgtypes,多個隊列?什麼是「一些標誌」? – Duck

回答

1

man 7 svipc看來,SysV消息隊列的唯一限制是隊列中存在的字節總數。因此,你有兩個解決方案:

  • 使用msgctl到的最大字節數設置爲一個消息的大小,並使用這個精確的尺寸只有消息
  • 使用POSIX消息隊列,而不是它允許你指定一個最大消息數量mq_open
+0

我想知道這是否真的是這個練習的重點,這看起來很不正確。 – Duck

+1

不管是什麼原因,他都會問如何用理論上可能的阻塞消息傳遞API來製作信號量。 – Grapsus

+0

正確。隨你。我早些時候寫了一個更長的解釋,爲什麼我認爲這很荒謬,但事實是,我真的不在乎如此讓它成爲。 – Duck