[英]How to redirect the output of system() called in a C program to syslog?
在我的C代碼中,我調用system
以獲得 bash 命令的結果。
即system("ps aux | grep my_prog | head -n 1")
當我在前台模式下運行我的程序時一切都很好,但在生產中是一個service ,所以我需要在syslog
中查看system
的 output ,而不是在stdout
或stderr
上。
我正在努力在這里找到最好和最不痛苦的選擇。 有正確的方法嗎?
正確的方法是使用popen()
而不是system()
然后使用 syslog 接口man 3 syslog
:
NAME
closelog, openlog, syslog - send messages to the system logger
SYNOPSIS
#include <syslog.h>
void openlog(const char *ident, int option, int facility);
void syslog(int priority, const char *format, ...);
void closelog(void);
#include <stdarg.h>
void vsyslog(int priority, const char *format, va_list ap);
另請注意,grepping ps
output 有其缺陷(例如,它也可能首先返回grep
進程)。 為什么不在 C 代碼迭代ps
output 中搜索正確的過程? 還是使用您的操作系統提供的功能直接迭代進程表?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.