2009-11-05 158 views
0

您好我正在使用一些共享内存在不同的进程读取和写入数据。我正在使用消息队列来存储数据在读取和写入操作之间发生更改的消息。消息队列。 msgsend msgrcv。系统V在C系统调用(Linux)

/* struct that defines a message */ 
struct msgbuf{ 
    long mtype;   /* must be positive */ 
    int childId;  //ID of child sending message 
    int bufferChanged; //Buffer at which value was changed 
    int beforeValue; //Value before child sleeps 
    int afterValue;  //Value after child sleeps 
}; 

所以在阅读,写作和检查的变化过程店的消息通过以下方式

struct msgbuf msg = {BUFFER_CHANGED, id, position, read, bufferArr[position]}; 
if(msgsnd(msqid, &msg, sizeof(msg), 0)== -1){ 
    perror("msgsnd in read.write"); 
} 

这是工作的罚款。哦,顺便说一下,我如何创建消息队列。

#define BUFFER_CHANGED 1 

qKey = ftok("./", 'A'); 

msqid = msgget(qKey, (IPC_CREAT | 0666)); 

/*Perform the following if the call is unsuccessful.*/ 
if(msqid == -1){ 
    printf ("\nThe msgget call failed, error number = %d\n", errno); 
} 
/*Return the msqid upon successful completion.*/ 
else{ 
    printf ("\nMessage queue successful. The msqid = %d\n", msqid); 
    //exit(0); 
} 

所以我的问题是,我不太清楚如何从队列中检索消息并将它们显示在屏幕上。我一直在阅读msgrcv()系统调用,但对我来说不是很清楚。

rc = msgrcv(msqid, &msg, sizeof(msg), BUFFER_CHANGED, IPC_NOWAIT); 

rcint因为msgrcv()返回一个int。我如何将这个int指向实际的消息?如何从消息中读取内容,以便我可以显示它们?我假设这应该在某种循环中完成。

回答

0

返回值是一个int,因为它告诉你它读入消息缓冲区的数据量 - 在你的情况下,你想看到4 * sizeof(int)返回一个完整的消息。如果rc返回-1,则表示有错误。如果rc作为正数返回,则至少有一些msg的字段将具有收到的消息数据。

查看man page了解更多详情。

0
rc = msgrcv(msqid, &msg, sizeof(msg), BUFFER_CHANGED, IPC_NOWAIT) 

msg包含要在屏幕上显示的数据。由于使用IPC_NOWAIT,函数立即返回而不会阻塞。如果没有msg被读取,则rc值将为-1,否则将为从msgq中读取的字节数。