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?
Sometimes, we would like to allow all users with sudo privilege to run a program as root without asking for passwords. Now, all users with sudo privilege can run the script /tmp/test/cpvimrc.sh as the superuser without providing passwords.
If you prefix “sudo” with any command, it will run that command with elevated privileges or in other words allow a user with proper permissions to execute a command as another user, such as the superuser. This is the equivalent of “run as administrator” option in Windows.
The sudo command allows you to run programs with the security privileges of another user (by default, as the superuser). It prompts you for your personal password and confirms your request to execute a command by checking a file, called sudoers , which the system administrator configures.
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 reason system(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 because sudo
works by using setuid, and that doesn't play well with system()
. Therefore, use the exec(3)
family of functions instead (except for execlp()
and execvp()
). See man 3 system
for more information.
Now, with that being said, don't use system(3)
or exec(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).
system("echo XXXX | sudo -S gedit");
Where XXXX your password.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With