-2

I have a program written in C that creates and reads a config file. It assumes that the config file is in the same directory as it is.

The program is run by fcron as root. If root runs this program, then the config file is created in root's home directory. It needs to be created in the user's directory where the program is.

I don't know enough about user management in linux to solve this, so the only way I can think to solve this is to get the executable's path by modifying argv[0].

Is there a better way?

Korgan Rivera
  • 495
  • 3
  • 9
  • Take a look at [this](https://stackoverflow.com/questions/1023306/finding-current-executables-path-without-proc-self-exe) question. – Federico klez Culloca Apr 15 '19 at 15:32
  • Possible duplicate of [Finding current executable's path without /proc/self/exe](https://stackoverflow.com/questions/1023306/finding-current-executables-path-without-proc-self-exe) – Tsyvarev Apr 15 '19 at 22:37

1 Answers1

1

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.

Fire Lancer
  • 29,364
  • 31
  • 116
  • 182