I have written a C utility that may be launched manually or on a regular basis, by a cron rule. Inside the C program I want to know if it was launched by a cron rule or not.
Reading the user name with getlogin_r renders the same username wether it is launched manually or by cron.
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main() {
char *username = malloc(80);
getlogin_r(username, 80);
printf("owner: %s\n", username);
return 0;
}
Any idea?
Following user sj95126 suggestion, I found an indirect (but good enough) way of detecting if a program has been launched by cron or not.
When it comes to run a command-line present at the crontab,
croncreates a non-interactive shell for it, i.e., one without standard input, standard output and standard error. This circumstance can be easily tested with theisatty()function from theunistd.hlibrary.This is a POC of the idea.
When launched manually the output is like this
when launched by cron the output can still be captured piping the standard output to a file
and the content of the file is
This link was very helpful too https://unix.stackexchange.com/questions/46789/check-if-script-is-started-by-cron-rather-than-invoked-manually