2014-05-12 54 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