I am writing a piece of C code that will run some sudo
command in system("sudo ip route ...")
function call.
This call is being done in a pthread created by the main thread, and the main program is being executed with sudo ./program
when starting up.
When I run the program, Ubuntu prompts me to enter password for nobody:
[sudo] password for nobody:
I also tried to do system("ip route ...")
straightly but it gives me negative return meaning that it is not executed.
What should I do in the thread to allow the system()
call to use the sudo
privilege inherited from the main program?
You don't need to do anything special to inherit the root privileges that
sudo
has given you. Processes generally automatically inherit the privileges of their parents. The reasonsystem(3)
isn't working is probably either because you're root (see below) or because you're on a thread.That being said, don't use
system(3)
. This is becausesudo
works by using setuid, and that doesn't play well withsystem()
. Therefore, use theexec(3)
family of functions instead (except forexeclp()
andexecvp()
). Seeman 3 system
for more information.Now, with that being said, don't use
system(3)
orexec(3)
. Instead, just directly call the C API for manipulating the IP tables. Why would you waste system resources spawning a new process or two, when you could just simplify your program instead? (At this point you're getting to the point where your question belongs on Stack Overflow, though).Where XXXX your password.