使用 C/C++ 应用程序持续监控 linux 控制台日志
Continuously monitor linux console logs using C/C++ application
我有一个第三方库应用程序,它连续运行并在发生某些事件时生成控制台打印。
我想在某些特定事件发生时采取一些行动,因此我需要持续监控控制台打印以触发我的行动。
是否可以编写可以在控制台 (stdout) 上连续监视字符串转储程序并在检测到一行时进行处理的应用程序。
我曾尝试使用 'popen' 函数,但它一直在等待,直到库应用程序停止执行。
这是我使用 open
的示例代码
#include <stdio.h>
int main()
{
FILE *fd = NULL;
char buf[512] = {0};
fd = popen ("./monitor","r");
while (fgets (buf, 512, fd) != NULL)
{
printf ("__FILE__ : message : %s\n",buf);
}
printf ("EOF detected!\n");
return 0;
}
谁能告诉我监控控制台日志的正确方法并采取行动。
提前致谢。
普拉蒂克
这是我最近编写的一段示例代码,它从 stdin 读取并打印到 stdout 。
void echo(int bufferSize) {
// Disable output buffering.
setbuf(stdout, NULL);
char buffer[bufferSize];
while (fgets(buffer, sizeof(buffer), stdin)) {
printf("%s", buffer);
}
}
据我所知,您遇到了类似的问题,因为我最初因为没有使用而延迟输出:
setbuf(stdout, NULL);
您也可以从 stdin 读取(这就是我的示例代码所做的),只需将您的命令通过管道传输到您的 C 代码,或者如果您只想过滤输出,通过管道将其传输到 grep。如果它是标准化的 syslog 日志,您还可以在日志文件上使用 tail:
tail -f <logfile>| <your c prgoramme>
或
仅用于归档
tail -f <logfile>|grep "<your string here>"
或者如果没有日志文件管道标准输出以这种方式记录:
<your app>|<your c prgoramme>
或
<your app>| grep "<your string here>"
由写入 stdout
的 shell 脚本模拟的第 3 方程序
#!/bin/bash
while true; do
echo "something"
sleep 2
done
你想写这样的东西来捕获第 3 方程序的输出,然后根据信息采取行动:
#!/bin/bash
while read line; do
if [[ $line == "something" ]]; then
echo "do action here"
fi
done
然后将它们与管道运算符结合起来:
./dosomething.sh | act.sh
我有一个第三方库应用程序,它连续运行并在发生某些事件时生成控制台打印。 我想在某些特定事件发生时采取一些行动,因此我需要持续监控控制台打印以触发我的行动。
是否可以编写可以在控制台 (stdout) 上连续监视字符串转储程序并在检测到一行时进行处理的应用程序。
我曾尝试使用 'popen' 函数,但它一直在等待,直到库应用程序停止执行。 这是我使用 open
的示例代码#include <stdio.h>
int main()
{
FILE *fd = NULL;
char buf[512] = {0};
fd = popen ("./monitor","r");
while (fgets (buf, 512, fd) != NULL)
{
printf ("__FILE__ : message : %s\n",buf);
}
printf ("EOF detected!\n");
return 0;
}
谁能告诉我监控控制台日志的正确方法并采取行动。
提前致谢。
普拉蒂克
这是我最近编写的一段示例代码,它从 stdin 读取并打印到 stdout 。
void echo(int bufferSize) {
// Disable output buffering.
setbuf(stdout, NULL);
char buffer[bufferSize];
while (fgets(buffer, sizeof(buffer), stdin)) {
printf("%s", buffer);
}
}
据我所知,您遇到了类似的问题,因为我最初因为没有使用而延迟输出:
setbuf(stdout, NULL);
您也可以从 stdin 读取(这就是我的示例代码所做的),只需将您的命令通过管道传输到您的 C 代码,或者如果您只想过滤输出,通过管道将其传输到 grep。如果它是标准化的 syslog 日志,您还可以在日志文件上使用 tail:
tail -f <logfile>| <your c prgoramme>
或 仅用于归档
tail -f <logfile>|grep "<your string here>"
或者如果没有日志文件管道标准输出以这种方式记录:
<your app>|<your c prgoramme>
或
<your app>| grep "<your string here>"
由写入 stdout
的 shell 脚本模拟的第 3 方程序#!/bin/bash
while true; do
echo "something"
sleep 2
done
你想写这样的东西来捕获第 3 方程序的输出,然后根据信息采取行动:
#!/bin/bash
while read line; do
if [[ $line == "something" ]]; then
echo "do action here"
fi
done
然后将它们与管道运算符结合起来:
./dosomething.sh | act.sh