dexterous_stranger dexterous_stranger - 6 months ago 23
Linux Question

How to invoke ssh exit from the C program under Linux Platform?

My existing application has a customized CLI - command line interface. I am trying to call ssh from the existing application to the remote PC, which runs the same application, with a customized CLI. I can't use lib ssh to create a session but I want to use the existing Linux SSH application.
Here is the code, I have used to invoke ssh from one application residing in 1 PC to another PC. My problem is that how can I exit from the SSH. I see that invoking exit has no affects. What I should do any idea? Here is my sample program to do a SSH.

INT4 do_ssh(tCliHandle CliHandle, CHR1 *destIp)
{
FILE *writePipe = NULL;
char readbuff[1024];
char cmd[1024];
pid_t pid;
int fd[2];
int childInputFD;
int status;

memset(cmd,'\0',sizeof(cmd));

sprintf(cmd,"/usr/bin/ssh -tt %s",destIp);

/** Enable For debugging **/
//printf("cmd = %s\r\n",cmd);

/** create a pipe this will be shared on fork() **/
pipe(fd);

if((pid = fork()) == -1)
{
perror("fork");
return -1;
}
if( pid == 0 )
{
gchildPid = getpid();
system(cmd);
}
else
{
/** parent process -APP process this is **/
while( read(fd[0], readbuff, sizeof(readbuff)) != 0 )
{
CliPrintf(CliHandle,"%s", readbuff);
printf("%s", readbuff);
}
close(fd[0]);
close(fd[1]);
}

return 0;
}


Results - I can see that the ssh is invoked - I can type the password and can do the SSH on the remote PC application. But, I don't know how to exit the SSH session. What I should do to exit the SSH session?

Answer

In the child-process the standard output is not redirected to your pipe, you need to use e.g. dup2 like this:

dup2(fd[1], STDOUT_FILENO);

before the call to system.

And don't use system to execute the program, use the exec family of functions instead.

So the child process should look like this:

if( pid == 0 )
{
    // Make standard output use our pile
    dup2(fd[1], STDOUT_FILENO);

    // Don't need the pipe descriptors anymore
    close(fd[0]);
    close(fd[1]);

    // Execute the program
    execlp("ssh", "ssh", "-tt", destIp, NULL);
}

Also, in the parent process you need to wait for the child process once you're done.


And if you don't want to bother with pipes and processes and waiting and such, simply use popen instead, which will handle it all for you and give you a nice FILE * you can use.