user344336
user344336

Reputation: 53

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

Well, I will put it plain and simple: I am a C++ pleb. 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?

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.

Upvotes: 4

Views: 4247

Answers (1)

rici
rici

Reputation: 241771

The system standard library function starts up a subshell and executes the provided string as a command within that subshell. (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.)

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. Many commands will output to stdout and/or stderr, and those outputs will not be supressed by system.

If you want the command to execute silently, then you can redirect stdout and/or stderr in the command itself:

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.

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. The same command would have the same behaviour if typed directly into a shell.

Upvotes: 5

Related Questions