3

I'm having trouble redirecting C printf statements to a file with a program running as root.

I have a program with several informational printf statements and other libraries which print errors via stderr. I'd like to log these to a file. If I start the program from the command line, I can see stderr and stdout messages.

sudo ./myprogram

If I try to redirect like so,

sudo ./myprogram >> log_file 2>&1

The log_file only contains stderr, and stdout disappears.

I suspect the issue is related to the root user not being connected to stdout, but I haven't found a solution.

My ultimate goal is to run this program at system start as root, while logging stderr and stdout to a log_file.
I've been trying this using crontab,

 sudo crontab -e

and adding the line,

@reboot bin/myprogram >> log_file 2>&1

This generates stderr messages but stdout disappears, same as command line.

Any help is appreciated, thanks!

Edits & updates: Testing this morning, the redirection behaves the same without sudo. A typical printf statement looks like:

printf("info: passed safety check\n");

I'm using a default set up for ubuntu 14.04 on an ARM processor, so I believe I'm using bash. I confirmed with,

echo $SHELL

produces

/bin/bash
user2977486
  • 35
  • 1
  • 4

2 Answers2

2

The behaviour of printf() seems to depend on the location of stdout.

  1. If stdout is sent to the console, then printf() is line-buffered and is flushed after a newline is printed.
  2. If stdout is redirected to a file, the buffer is not flushed unless fflush() is called.
  3. Moreover, if printf() is used before stdout is redirected to file, subsequent writes (to the file) are line-buffered and are flushed after newline.

Source: Why does stdout need explicit flushing when redirected to file?

I'm not well versed with C programming, but apparently you need to add fflush(stdout); after every printf statement. Try it out from the command line. If it works, it should work with cron.

More questions on this topic:

Alaa Ali
  • 32,213
0

The TLDP HowTo has this nice syntax for redirection of both stdout and stderr:

  @reboot /path/to/program &> /path/to/log

The HowTo says that it's sometimes suitable for cron entries.

muru
  • 207,228