简体   繁体   English

在C代码中使用su命令

[英]Use of su command in c code

I want to use a command in my c code. 我想在我的C代码中使用命令。 This command works properly when i am a superuser in terminal (using su) but does not work when I use sudo. 当我是终端的超级用户(使用su)时,此命令可以正常使用,但是当我使用sudo时,此命令不起作用。 I gathered that I can use system() in my c code as follows 我收集到可以在我的C代码中使用system(),如下所示

system("su -c \"mycommand\"")

myCommand is a command that sends input to some device, like (echo 1 > mydevice) myCommand是一个将输入发送到某些设备的命令,例如(echo 1> mydevice)

I compiled my c code using gcc and run the output file. 我使用gcc编译了我的C代码并运行输出文件。 The trouble is, it wants root password from terminal when it comes to this line. 问题是,涉及到此行时,它需要从终端输入root密码。 Is there a way I supply password programatically? 我可以通过编程方式提供密码吗? I did it before with sudo command with -S option, but sudo command does not work for this case. 我之前使用带-S选项的sudo命令做到了,但是sudo命令在这种情况下不起作用。 If it is not possible, is there another way to deal with this? 如果不可能的话,还有其他方法可以解决吗?

试试这个,

system("sudo sh -c \"mycommand\"");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM