Go Premium for a chance to win a PS4. Enter to Win

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 2630
  • Last Modified:

pipe(), fork(), exec(), ... providing input to and capturing output of a child process in C++

I am writing a C++ program, which should create a sub- process to start a telnet session to another server. Then it should login to that server (on the telnet login) and execute one or more command(s) on the remote server. The C++ program provides all the input for this process (username, password, servername, commands, ...) and should capture all the output returned by the telnet session process inside some variable. How can this be accomplished ? This is what I have so far, but since I'm not very good at working with pipes and children, I need the experts help on this one..

Thanks in advance.




#include <string>
#include <stdio.h>
#include <sys/fcntl.h>
#include <unistd.h>

using namespace std;

int main(){

      string telnetString = "telnet";
      char* arguments[2];
      arguments[0] = "telnet";
      arguments[1] = "myserver.com";

      string loginname = "myLogin";
      string password = "mypass";
      string command = "ls -l > listing.txt"; // should create listing.txt on remote server (for testing only)

    ////
    // example of a possible real life series of commands :
   ////
  string command1 = "cd public_html";
  string command2 = "cat index.html"; // returns the output (= the contents of public_html/index.html on the remote server)
                                                       // back to the C++ program !!


      int fd2[2];
      int pipetest;

      pipetest = pipe(fd2);

      if(pipetest != 0) exit(1);
      else
      {
            // Pipe OK
            int pid;
            pid = fork();

            if(pid < 0) exit(2);

            if(pid == 0)
            { // child

                  ////
                  // NOT SURE ABOUT THIS PART !!
                  ////


                  ////
                  // Redirect childs input from parents output.
                  ////
                  //fd2[0] = 1;

                  close(fd2[1]);
                  dup2(fd2[0], 1);

                  ////
                  // Start the telnet program somehow
                  ////
                  execvp( telnetString.c_str() , arguments );
            }

            ////
            // Do the telnet (= child) login stuff
            // end execute the commands (just one for now)
            ////

            printf("%s\n", loginname.c_str());
            printf("%s\n", password.c_str());
            printf("%s\n", command.c_str());
            //printf("%s\n", command2.c_str());
            printf("exit\n"); // exit the telnet session

            ////
            // Find some way to capture the output of the telnet process
            // in this C++ program, to parse it later on.
            ////

      }

return 0;
};
0
Hoegje
Asked:
Hoegje
  • 5
  • 4
1 Solution
 
freewellCommented:
int main(int argc, char* argv[])
{
   char   psBuffer[128];
   FILE   *pPipe;
   char   psCommand[] = "dir *.c /on /p";

   if( (pPipe = _popen( psCommand, "rt" )) == NULL )
      exit( 1 );

   while( !feof( pPipe ) )
   {
      if( fgets( psBuffer, 128, pPipe ) != NULL )
         printf( psBuffer );
   }

   printf( "\nProcess returned %d\n", _pclose( pPipe ) );

   return 0;
}
0
 
jkrCommented:
You'd use 'pipe()' for that purpose:

#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>

int main (int argc, char **argv)
{
  int filedes1[2], filedes2[2];
  int pid;
 
  /* Argument checking. */

  if (argc < 4)
    {
      puts("Wrong number of arguments given");
      exit(1);
    }

  /* Make our first pipe. */

  if (pipe(filedes1) == -1)
    {
      perror ("pipe");
      exit(1);
    }

  /* Make our second pipe. */
 
  if (pipe(filedes2) == -1)
    {
      perror ("pipe");
      exit(1);
    }

  /* Fork a child */

  if ((pid = fork()) == 0)
    {
      dup2(filedes1[0], fileno(stdin)); /* Copy the reading end of the pipe. */
      dup2(filedes2[1], fileno(stdout)); /* Copy the writing end of the pipe */
     
      /* Uncomment this if you want stderr sent too.

      dup2(filedes2[1], fileno(stderr));

      */

      /* If execl() returns at all, there was an error. */
     
      if (execl(argv[1], argv[1] == -1)) /* Bye bye! */
      {
        perror("execl");
        exit(128);
      }
    }
  else if (pid == -1)
    {
      perror("fork");
      exit(1);
    }
  else
    {
      int output;
      char c;

      write(filedes1[1], argv[2], strlen(argv[2])); /* Write the string */

      if((output = open(argv[3], O_WRONLY)) == -1)
      {
        perror("open");
        exit(1);
      }

      while (read(filedes2[0], &c, 1) != 0)
        write(output, &c, 1);
   
      exit(0);
    }
}
0
 
jkrCommented:
BTW, code taken from (and more info at) http://www.gmonline.demon.co.uk/cscene/CS4/CS4-06.html
0
What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

 
HoegjeAuthor Commented:
I tried it, and the program skips all the child's code, because pid != 0. Wehn i am stepping through the program and I check pid every time, it changes from the uninitialised value to the parents pid value. So it does not start up any telnet session...

What next ?
0
 
jkrCommented:
>>I tried it, and the program skips all the child's code, because pid != 0

Yes, that is what the parent process is supposed to do. How are you calling the program?
0
 
jkrCommented:
BTW, found an error in the above code:

      if (execl(argv[1], argv[1] == -1)) /* Bye bye! */

should read

      if (execl(argv[1], argv[1]) == -1) /* Bye bye! */
0
 
HoegjeAuthor Commented:
Here is my code :

#include <string>
#include <stdio.h>
#include <sys/fcntl.h>
#include <unistd.h>
#include <sys/types.h>
#include <iostream>

using namespace std;

int main(){

      string telnetString = "telnet";
      char* arguments[2];
      arguments[0] = "telnet";
      arguments[1] = "myServer.com";

      string loginname = "myLogin";
      string password = "myPass";
      //string command = "cd public_html";
      string command = "ls -l > listing.txt";
      string command2 = "cat index.html";
      string strExit = "exit";


      int fd1[2];
      int fd2[2];
      int pipetest;
      int pid;

      pipetest = pipe(fd1);
      if(pipetest != 0) exit(1); // or ptest == -1

      pipetest = pipe(fd2);
      if(pipetest != 0) exit(1); // or ptest == -1
 
      {
            // Pipe OK
 

            if( (pid = fork()) == 0)
            { // child


                  ////
                  // Copy reading end of the pipe.
                  ////
 
                  dup2(fd1[0], fileno(stdin));

                  ////
                  // Copy writing end of the pipe.
                  ////

                  dup2(fd2[1], fileno(stdout));

                  close(fd2[1]);
                  dup2(fd2[0], 1);

                  ////
                  // Copy stderr too
                  ////
                  // dup2(fd2[1], fileno(stderr));

                  ////
                  // execute subprocess
                  // if it returns, there was an error
                  ////
                  execv( telnetString.c_str() , arguments );
            }
            else
            { // parent

                  int output;
                  char c;

                  ////
                  // Do the telnet (= child) login stuff
                  // end execute the commands (just one for now)
                  ////
                  write( fd1[1], loginname.c_str(), loginname.size() );
                  write( fd1[1], password.c_str(), password.size() );
                  write( fd1[1], command.c_str(), command.size() );
                  write( fd1[1], strExit.c_str(), strExit.size() );
                  write( fd1[1], strExit.c_str(), strExit.size() );

                  ////
                  // Find some way to capture the output of the telnet process
                  // in this C++ program, to parse it later on.
                  ////
/*                  while( read(fd2[0], &c, 1) != 0 ){
                        cerr << c;
                  }
                  exit(0);
*/
            }
      }

return 0;
};


What can I do ?
0
 
HoegjeAuthor Commented:
Does anybody know how I should access the child node ?
0
 
HoegjeAuthor Commented:
Ok, I found a solution myself, a bit of very low level code and stuff, but the important thing is I got it to work..
0
 
HoegjeAuthor Commented:
#include <sys/types.h>
#include <sys/stat.h>
#include <cstdio>
#include <string>

using namespace std;

int ha_dados (FILE * fp, long ttl)
{
        fd_set rfd;
        struct timeval tv;
        int fd;

        tv.tv_usec = 0;
        tv.tv_sec = ttl;

        fd = fileno (fp);

        FD_ZERO (&rfd);
        FD_SET (fd, &rfd);

        return (select (fd + 1, &rfd, NULL, NULL, &tv));
}

int waitfor (FILE * fp, char * match, int print)
{
        int ch, x;

        x = 0;
        do {
                if (!ha_dados (fp, 10)) {
                        printf ("Timed out\n");
                        return (0);
                }

                ch = getc (fp);
                if (ch < 0) return 0;
                if (ch == match[x]) x++;
                if (print) putchar (ch);
        } while (match[x] != '\0');
        return (x);
}

int main (int argc, char **argv)
{
        FILE * out, * in;

      ////
      // Create a special FIFO file, similar to a named pipe
      ////
        mkfifo ("telnetMD.out", 0600);

        out = popen ("/bin/telnet swis.uia.ac.be 1>telnetMD.out 2>/dev/null", "w");
        if (!out) return (-1);

        in = fopen ("telnetMD.out", "r");
        if (!in) {
                fclose (out);
                return (-1);
        }

      ////
      // Make sure input and output is unbuffered
      ////
        setbuf (out, NULL);
        setbuf (in, NULL);

        if (waitfor (in, "login:", 0) == 0) {
                fclose (out);
                fclose (in);
                return (-1);
        }

        fprintf (out, "myLogin\n");

        if (waitfor (in, "Password: ", 0) == 0) {
                fclose (out);
                fclose (in);
                return (-1);
        }
        fprintf (out, "myPassword\n");

        if (waitfor (in, "$", 0) == 0) {
                printf ("Login failed\n");
                fclose (out);
                fclose (in);
                return (-1);
                return (-1);
        }

      fprintf (out, "cd public_htm\n");
      waitfor(in, "$", 1);

        fprintf (out, "ls -l\n");
        waitfor (in, "$", 1);

        fprintf (out, "exit\n");
        waitfor (in, ">", 0);

        fprintf (out, "exit\n");
        waitfor (in, "$", 0);


        fclose (out);
        fclose (in);

      system("rm telnetMD.out");

        return (0);
}
0

Featured Post

Vote for the Most Valuable Expert

It’s time to recognize experts that go above and beyond with helpful solutions and engagement on site. Choose from the top experts in the Hall of Fame or on the right rail of your favorite topic page. Look for the blue “Nominate” button on their profile to vote.

  • 5
  • 4
Tackle projects and never again get stuck behind a technical roadblock.
Join Now