views:

116

answers:

4

I have this executable that queries a remote server for a command, executes it on the local machine and returns the stdout (and also possibly stderr) from it back to the server.

This executable runs just fine if called from the command line (as root), but I found it's failing for some commands when executed automatically by the cron job.

What are the differences in terms of environment (users, stdin, stdout, etc.) I should expect when scheduling this executable to run periodically using crontab?

Thanks!

+5  A: 

The most important difference is that files like .bashrc etc. are not executed before cron jobs, so a lot of environment variables that you normaly have in the command line will be missing. So if your program doesn't work in the cron job, embedd it in a script that sets all the necessary environment variables.

Regarding input and output, there is obviously no user interaction for cron jobs, so the programs should not expect input (if they do, provide it from an input file or directly in the script), and any output should be redirected into a log file.

ammoQ
A little additional hint: Java programs sometimes use AWT functions, even though they have no gui at all. Especially when they manipulate images, but also e.g. HSSF when calculating column widths. Such programs must be started with -Djava.awt.headless=true in a cron job, otherswise they break because there is no X available in cron. In the commandline of an XTerm, you simply do not notice that...
ammoQ
+2  A: 

This executable runs just fine if called from the command line (as root), but I found it's failing for some commands when executed automatically by the cron job.

In cron jobs you can specify what user to run the script as, for example:

0 0 * * * www-data /usr/bin/php /var/www/foo/do_work.php

I am specifying to run 'do_work.php' as www-data everyday... This file would be located in /etc/cron.d/

clownbaby
+1  A: 

Also, you should probably check the UID that cron uses for running the tasks, especially if it's a 'global' /etc/crontab job, not a user-level one. Could be that some permissions are lacking if the job is running from 'nobody' or 'cron'.

neuviemeporte
+1  A: 

Mainly

  • Current working directory - you cannot guarantee what this is going to be from cron. It may be $HOME, but don't count on it
  • Environment variables - most that you have setup for normal logins will NOT be set, so things which require environment variables to have specific values may fail. This notably includes $PATH.
  • stdin / stdout / stderr will not be a tty, so some programs will behave differently because of this (stdout and err will probably be a temp file; stdin will probably be null)

But essentially you can't rely on much

  • User ID, group id and supplementary groups should be set as per a normal login for the owner of the cron job
MarkR