Send shell command remotely via ssh in C++

Nhan Ly picture Nhan Ly · Apr 6, 2014 · Viewed 8.2k times · Source

I want to open a ssh session to my Raspberry Pi and run simple command echo 0=+10 > /dev/servoblaster at what time I want ( means not using system("ssh [email protected] echo 0=+10 > /dev/servoblaster") because it takes time to run ssh again). What is the easiest way in C++?

Answer

Mats Petersson picture Mats Petersson · Apr 6, 2014

Assuming you only need one-way communication, open the ssh connection with FILE *ssh = popen("ssh [email protected]", "w") instead of system. That will give you a handle to write to, e.g. fprintf(ssh, "echo 0=%#d > /dev/servoblaster", 10);. The ssh connection is then avilable until you pclose(ssh); at some later point.

If you need to read back, you will need to open both sides of a pipe, which requires a "proper fork jobbie". You could perhaps start with this example, in that case.

fork() and pipes() in c