使用 system() 在 C 中执行 sudo 命令 [英] Execute sudo command in C with system()

查看:150
本文介绍了使用 system() 在 C 中执行 sudo 命令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一段 C 代码,它将在 system("sudo ip route ...") 函数调用中运行一些 sudo 命令.

I am writing a piece of C code that will run some sudo command in system("sudo ip route ...") function call.

这个调用是在主线程创建的一个pthread中完成的,主程序在启动时用sudo ./program执行.

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.

运行程序时,Ubuntu提示我输入nobody密码:

When I run the program, Ubuntu prompts me to enter password for nobody:

[sudo] 无人密码:

我也尝试直接执行 system("ip route ...") 但它给了我否定的回报,这意味着它没有被执行.

I also tried to do system("ip route ...") straightly but it gives me negative return meaning that it is not executed.

在线程中应该怎么做才能让system()调用使用从主程序继承的sudo权限?

What should I do in the thread to allow the system()call to use the sudo privilege inherited from the main program?

推荐答案

您无需执行任何特殊操作即可继承 sudo 赋予您的根权限.进程通常会自动继承其父进程的权限.system(3) 不工作的原因可能是因为你是 root(见下文)或因为你在一个线程上.

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.

话虽如此,不要使用system(3).这是因为 sudo 使用 setuid 工作,而 system() 则不能很好地发挥作用.因此,请改用 exec(3) 系列函数(execlp()execvp() 除外).有关详细信息,请参阅 man 3 system.

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.

现在,根据那个的说法,不要使用system(3) exec(3).相反,只需直接调用 C API 来操作 IP 表.既然可以简化程序,为什么还要浪费系统资源来生成一两个新进程?(不过,此时您的问题属于 Stack Overflow).

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() 在 C 中执行 sudo 命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆