简体   繁体   English

隐藏在使用system()时使用的控制台命令? C ++ Linux

[英]Hiding console command used while using system()? C++ Linux

Well, I will put it plain and simple: I am a C++ pleb. 好吧,我将它简单明了地说:我是C ++平民。 Still trying to learn though. 仍在尝试学习。

My question is: is it possible to run a command though the terminal using system() command without letting the command be shown in the console/terminal? 我的问题是:是否可以在使用system()命令的终端上运行命令,而不会在控制台/终端中显示该命令?

Example: 例:

system("sudo service sshd start") ;
Output: Sudo service sshd start

Where as I want: 我想在哪里:

system("sudo service sshd start") ;
output: (Blank)

Note: I am on linux. 注意:我在linux上。

The system standard library function starts up a subshell and executes the provided string as a command within that subshell. system标准库函数启动一个子Shell,并在该子Shell中将提供的字符串作为命令执行。 (Note that a subshell is simply a process running a shell interpreter; the particular shell interpreter invoked by system will depend on your system. No terminal emulator is used; at least, not on Unix or Unix-like systems.) (请注意,子shell只是运行shell解释器的进程; system调用的特定shell解释器将取决于您的系统。不使用终端仿真器;至少在Unix或类似Unix的系统上不使用。)

The system function does not reassign any file descriptors before starting the subshell, so the command executes with the current standard input, output and error assignments. 在启动子Shell之前, system功能不会重新分配任何文件描述符,因此该命令以当前的标准输入,输出和错误分配执行。 Many commands will output to stdout and/or stderr, and those outputs will not be supressed by system . 许多命令将输出到stdout和/或stderr,而这些输出将不会被system抑制。

If you want the command to execute silently, then you can redirect stdout and/or stderr in the command itself: 如果您希望命令以静默方式执行,则可以在命令本身中重定向stdout和/或stderr:

system("sudo service sshd start >>/dev/null 2>>/dev/null") ;

Of course, that will hide any error messages which might result from the command failing, so you should check the return value of system and provide your own error message (or log the information) if it is not 0. 当然,这将隐藏命令失败可能导致的任何错误消息,因此,如果不为0,则应检查system的返回值并提供自己的错误消息(或记录信息)。

This really has very little to do with the system call or the fact that you are triggering the subshell from within your own executable. 这实际上与system调用或您从自己的可执行文件中触发子Shell的事实无关。 The same command would have the same behaviour if typed directly into a shell. 如果直接在shell中键入相同的命令,将具有相同的行为。

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

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