What is the difference between running an executable directly from the command line and running a cron job in Linux?

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

This executable works just fine if invoked from the command line (with admin privileges), but I found that it doesn't work for some commands when the cron job is automatically executed.

What are the differences in environment conditions (users, stdin, stdout, etc.). Should I wait for the scheduled execution of this executable to be done periodically using crontab?

Thank!

+2


source to share


4 answers


The most important difference is that files like .bashrc etc. are not executed before cron jobs, so a lot of the environment variables you would normally have on the command line will be missing. So if your program is not running in a cron job, paste it into a script that sets all the required environment variables.



As far as input and output is concerned, there is obviously no user interaction for cron jobs, so programs should not wait for input (if they do, provide it from an input file or directly to a script) and any output should be redirected to a log file ...

+5


source


This executable works just fine if invoked from the command line (with admin privileges), but I found that it doesn't work for some commands when the cron job is automatically executed.

In cron jobs you can specify which user should run the script, for example:



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

      

I specify that every day to run "do_work.php" as www data ... This file will be located in / etc / cron.d /

+2


source


Also, you should probably check the UID that cron uses to execute tasks, especially if it is a "global" / etc / crontab job and not a custom one. It may be that some permissions are missing if the job is run from "nobody" or "cron".

+1


source


basically

  • Current working directory - you cannot guarantee that this will be from cron. It might be $ HOME, but don't count on it.
  • Environment Variables - Most of the settings you have configured for regular logins will NOT be set, so there may be problems requiring certain environment variables. This specifically 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 temporary file, stdin will probably be null)

But essentially you cannot rely on much

  • The user ID, group ID, and additional groups must be set to match the normal login for the owner of the cron job.
+1


source







All Articles