如何将 C 程序中调用的 system() 的输出重定向到 syslog?

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")

当我 运行 我的程序处于 foreground 模式时一切正常,但在生产中是 service,所以我需要在 syslog 中查看 system 的输出,而不是在 stdoutstderr.

我正在努力寻找最好和最不痛苦的选择。 有正确的方法吗?

正确的方法是使用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 输出有其缺陷(例如,它也可能 return 首先是 grep 过程)。为什么不在迭代 ps 输出的 C 代码中搜索正确的进程?或者直接使用 OS 提供的函数遍历过程 table?