Does the program have to run as root? Using the crontab for the user would ensure the right home directory, file permissions, etc. as well as security advantages.
You could modify the job to run in a desired working directory. I believe the syntax would be something like:
15 7 * * * cd /home/myuser/ && /usr/bin/myprogram
Or pass it as an argument, (see various programs for examples of things like --config-path=~/mycustomconfig
). These have more flexibility, say if the program is installed once for multiple users.
Alternatively, to get the main executable path in the process, you can read /proc/self/exe
, you might then use dirname
to get the directory from the full path. e.g.
char path[MAX_PATH];
ssize_t len = readlink("/proc/self/exe", path, MAX_PATH);
if (len > 0 && len < MAX_PATH) {
path[len] = '\0';
char *directory = dirname(path);
}
In either case, the regular file I/O functions will create a file owned and writable by root
, if this is not desired, chown(path, owner, group)
might be used. stat(path, buf)
on the home directory could be a way to get the ID for chown
but not something I ever considered and there may be cases the directory is owned by the "wrong" user.