How can I create a file in the `/ etc` folder in Linux using C?
I am writing a C program that will check a config file every time it starts setting some variables.
The first time I run the program, I assume there will be no configuration file, so I need to create one (with default settings).
I have already said that the program configuration files belong to a folder /etc
, more specifically to a specific folder created specifically for the program itself (i.e. /etc/myprog
). Here's the first question I had to ask: is it true? Why /etc
?
Anyway, I tried to create this file using this:
open("/etc/myprog/myprog.conf", O_WRONLY | O_CREAT, 0644);
open
returns -1
and sets the global variable errno
to 2
(i.e. the folder doesn't exist ). If I try to create a file right inside /etc
(so "/etc/myprog.conf"
as the first argument open
), I get the errno
value instead 13
(i.e. allowed ).
Is there a way to grant my program writable rights to /etc
?
EDIT: I see that most users are suggesting to use sudo
. If possible, I would prefer to avoid this option, as this file only needs to be created once (on first run). Maybe I should make 2 different executables? (for example, myprog_bootstrap
and myprog
, to start only the first s sudo
)
source to share
Another possibility might be to make your executable setuid . Your program will then invoke the setreuid (2) system call as appropriate .
However, be very careful. Programs like /bin/login
(or /usr/bin/sudo
) are coded this way, but any subtle mistake in your program opens up security holes for the worm bank. So please be paranoid when writing such code and check it out for others.
Perhaps a better approach might be to have your installation routine create /etc/yourfile
some kind of symbolic link (created once during installation to some file for writing elsewhere) ....
By the way, you can create a group for your program and make the -t set-time- /etc/yourfile
writable to the group and make your program setgid. Or even, dedicate a user to your program and assign /etc/yourfile
that user to that user.
Or, during installation, create a directory /etc/myprog/
and belong to the corresponding user (or group) and will be writable by that user (or group).
PS. See also Advanced Linux Programming , capabilities (7) , credentials (7) and execve (2)
source to share