2
3

More than 5 years have passed since last update.

LinuxでC++からdmesg(/dev/kmsg)の更新監視

Last updated at Posted at 2016-06-03

Linuxでpythonからdmesg(/dev/kmsg)の更新監視 - Qiita

上の記事で、pythonで書いたが、C++のほうでも意外と簡単に書けた。

#include <iostream>
#include <string>
#include <fstream>

int main()
{
    std::ifstream ifs("/dev/kmsg");

    ifs.seekg(0, std::ios_base::end);

    std::string str;

    for (;;) {
        std::getline(ifs, str);
        std::cout << str << std::endl;
    }

    return 0;
}

pythonではやり方がいまいちわからなかったが、C++ の fstream では
ifs.seekg(0, std::ios_base::end) でファイルの末尾まで seek できる。(ブロッキングされない)

実行とその結果は以下のようになる。

実行結果と終了(監視側)
$ g++ tailf_kmsg.cpp
$ ./a.out
12,676,80928667951,+;stop aaa
12,677,80932948508,-;stop bbb
12,678,80938639308,-;stop ccc

/dev/kmsg にリダイレクトすることで、擬似的にドライバのログの出力を確認している

実行結果と終了(更新側サンプル)
$ sudo sh -c "echo aaa > /dev/kmsg"
$ sudo sh -c "echo bbb > /dev/kmsg"
$ sudo sh -c "echo ccc > /dev/kmsg"

参考

ストリームの読み込み位置を自由に変えるには?|C++ フリーでぷろぐらみんぐ

2
3
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
2
3