1

Inside my C code I call system to have result from a bash command.

I.e. system("ps aux | grep my_prog | head -n 1")

All is fine when I run my program in foreground mode, but in production is a service, so I need to see the output of system in syslog, not on stdout or stderr.

I'm struggling to find the best and least painful option here. Is there a proper way to do it?

Jens
  • 69,818
  • 15
  • 125
  • 179
Kyrol
  • 3,475
  • 7
  • 34
  • 46
  • 1
    "Least painful" greatly depends on your perspective. What may be the simplest changes for you to make now could very well be extremely painful down the road. For example `system( "sh -c 'ps aux | grep my_prog | sed 1q | logger'");` may seem painless now, but could lead to weeping and gnashing of teeth in the future. – William Pursell Nov 27 '20 at 15:42
  • Thanks @WilliamPursell , that's eaxactly why I wrote about the "pain", because I saw the `logger` option but I don't want to it at all. – Kyrol Nov 27 '20 at 15:44

1 Answers1

3

The proper way is to use popen() instead of system() and then the syslog interface, 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);

Also note that grepping ps output has its pitfalls (e.g. it may also return the grep process first). Why not search for the proper process in the C code iterating over ps output? Or directly iterate over the process table using functions your OS provides?

Jens
  • 69,818
  • 15
  • 125
  • 179
  • Thank you, I'll give it a try. I think this is the best solution. – Kyrol Nov 27 '20 at 15:45
  • Thanks. I implemented as you suggested and it works. Could you give me additional explanation on your notes about the `ps` pitfalls, not sure i understood. Thanks – Kyrol Nov 28 '20 at 18:14
  • @Kyrol A simple grep for process my_prog will usually return at least two matches. The `head -n 1` selects the first, but how do you know ps does not return the grep process first? It's an assumption you make that might become false. – Jens Nov 28 '20 at 18:33
  • I got your point. So, how can I iterate over the process table in my C code. I never did that, is something new. Any hints ? Thank you – Kyrol Nov 28 '20 at 18:42
  • 1
    @Kyrol On my system, FreeBSD, I can ask the kernel for the process table with `kvm_getprocs()`. For Linux, maybe https://stackoverflow.com/questions/939778 is a starting point. But it could be enough to just use `popen("ps aux")` and then use strcmp() to find the interesting process. – Jens Nov 28 '20 at 18:54