4
9

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

pythonでposixメッセージキューを扱う

Posted at

概要

  • Unix系のプロセス間通信などで使用するposixメッセージキューをpythonで扱う
  • posix_ipcモジュールを使ってプロセス間通信を行う

手順

  • pipでposix_ipcをインストールします
$ sudo pip install posix_ipc
  • posix_ipcモジュールのMessageQueueクラスを使うことでposixキューの各操作ができます

実装

  • 送信側

#!/usr/local/env python
# -*- coding: utf-8 -*-

import json
import posix_ipc
import time

if __name__ == "__main__":
    posix_ipc.unlink_message_queue("/queue_name")

    mq = posix_ipc.MessageQueue("/queue_name", posix_ipc.O_CREX)
    counter = 0
    while True:
        counter += 1

        # sendでエンキュー, str, unicodeを送信
        mq.send(json.dumps({"loop_count": counter}))
        print "queue: %d" % counter
        time.sleep(1.0)

    posix_ipc.unlink_message_queue("/queue_name")

  • 受信側
#!/usr/local/env python
# -*- coding: utf-8 -*-

import json
import posix_ipc
import time

if __name__ == "__main__":
    mq = posix_ipc.MessageQueue("/queue_name")
    while True:
        msg = mq.receive()
        print json.loads(msg[0])
        time.sleep(0.5)
  • キューの名前は/から始める必要があり、複数の/を含めることはできない(階層構造にはできない
  • メッセージキューの最大メッセージ数はデフォルトでは10
4
9
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
9

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?