sysv_mq 是一个用于 SysV 消息队列的 Go 封装。在使用此库之前,请务必阅读 SysV 消息队列的手册、msgrcv(2) 和 msgsnd(2)。 sysv_mq
是一个非常轻量的封装,不会隐藏任何错误。
公共 API 的文档可以在 Godoc 上查看。
sysv_mq 在 Linux 和 OS X 上进行了测试。要运行测试,请运行 make test
。 这会确保在运行测试之前删除您系统上当前的所有消息队列。
示例,它向键为 0xDEADBEEF
的队列发送消息(如果不存在则创建它)。
go
package main
import (
"fmt"
"github.com/Shopify/sysv_mq"
)
func main() {
mq, err := sysv_mq.NewMessageQueue(&sysv_mq.QueueConfig{
Key: 0xDEADBEEF, // SysV IPC key
MaxSize: 1024, // Max size of a message
Mode: sysv_mq.IPC_CREAT | 0600, // Creates if it doesn't exist, 0600 permissions
})
if err != nil {
fmt.Println(err)
}
// Send a message to the queue, with message type 1, without flags.
err = mq.SendString("Hello World", 1, 0)
if err != nil {
fmt.Println(err)
}
// Receive a message from the queue, 0 gives you the top message regardless of
// message type passed to send().
response, mtype, err := mq.ReceiveString(0)
if err != nil {
fmt.Println(err)
}
fmt.Printf("[%d] %s", mtype, response)
// Output:
// [1] Hello World
}
SendBytes()
和 ReceiveBytes()
发送任何类型的字节切片。 SendString()
和 ReceiveString()
是字节切片函数的简单封装,方便使用,并且将使用 UTF-8 编码。sysv_mq.IPC_NOWAIT
标志使其立即返回。SendBytes()
、ReceiveBytes()
和 NewMessageQueue()
都进行系统调用,这些调用可能会被信号中断(如果您执行阻塞的 ReceiveBytes()
,则非常常见)。在这种情况下,错误将是 EAGAIN
。这里没有对其进行封装,因为如果调用会阻塞或队列已满,EAGAIN
也是错误。有关更多信息,请查阅手册。版权所有 (c) 2013 Shopify。 根据 MIT-LICENSE 发布。