What are the differences between running an executable straight from the command line and from a cron job in Linux?

StackOverflow https://stackoverflow.com/questions/1618238

  •  06-07-2019
  •  | 
  •  

Question

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!

Was it helpful?

Solution

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.

OTHER TIPS

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/

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'.

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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top