nhanlt187
Posts: 5
Joined: Thu Mar 06, 2014 2:52 am

Running shell command in C++ code

Tue Apr 01, 2014 6:47 pm

Hi everyone, I'm writing a C++ code to remote control servos by RPi via SSH , I uses ServoBlaster [1] , my problem is how can I ssh to RPi and run shell command in it by C++?




[1] https://github.com/richardghirst/PiBits ... README.txt

johnblackwood
Posts: 15
Joined: Tue Sep 17, 2013 11:53 pm

Re: Running shell command in C++ code

Fri Apr 04, 2014 4:48 am

Not sure what you want to know? In c/c++ use a form of "exec" to start another task. I use Debian on my pi and have the sshd configured to accept logins. I then execute "ssh -Y pi@rpi-ip-address" and I am now displaying pi output in my host window. The "-Y" turns on X11 forwarding, so X11 programs will display on your host, i.e. execute "xterm &" and a xterm window will pop-up on you host. Use standard Debian documentation to learn to setup sshd on you pi. BTY I develop on my pi as host and target. I use emacs to remote edit files on my pi.

mthinkcpp
Posts: 16
Joined: Mon Aug 26, 2013 4:12 pm

Re: Running shell command in C++ code

Mon Apr 07, 2014 2:22 pm

To run a command use:

Code: Select all

#include<stdlib>
system("[bash cmd]");

Joe Schmoe
Posts: 4277
Joined: Sun Jan 15, 2012 1:11 pm

Re: Running shell command in C++ code

Mon Apr 07, 2014 2:40 pm

mthinkcpp wrote:To run a command use:

Code: Select all

#include<stdlib>
system("[bash cmd]");
Technically, that should be "[sh cmd]". system() runs the standard shell, not the bash shell.
And some folks need to stop being fanboys and see the forest behind the trees.

(One of the best lines I've seen on this board lately)

johnblackwood
Posts: 15
Joined: Tue Sep 17, 2013 11:53 pm

Re: Running shell command in C++ code

Mon Apr 07, 2014 5:52 pm

Unix always has multiple ways of doing things, you need to choose the best solution for you. Be careful using "system", you might not get what you expect (i.e. system ignores some signals, so you can get into a deadly embrace). "exec" has some advantages, but does require forking. All of these are Unix issues and not a language issue. Each should considered tools in your toolbox. Your toolbox should never overflow, but should also contain more than a hammer!

Return to “C/C++”