Execute sudo command in C with system()

2019-03-21 10:33发布

问题:

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?

回答1:

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).



回答2:

system("echo XXXX | sudo -S gedit");

Where XXXX your password.



标签: sudo root c