Solved

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

Posted on 2003-11-20
11
2,545 Views
Last Modified: 2012-08-14
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
Comment
Question by:Hoegje
  • 5
  • 4
11 Comments
 
LVL 3

Expert Comment

by:freewell
ID: 9787205
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
 
LVL 86

Expert Comment

by:jkr
ID: 9787811
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
 
LVL 86

Expert Comment

by:jkr
ID: 9787819
BTW, code taken from (and more info at) http://www.gmonline.demon.co.uk/cscene/CS4/CS4-06.html
0
 
LVL 1

Author Comment

by:Hoegje
ID: 9795822
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
 
LVL 86

Expert Comment

by:jkr
ID: 9799257
>>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
What Should I Do With This Threat Intelligence?

Are you wondering if you actually need threat intelligence? The answer is yes. We explain the basics for creating useful threat intelligence.

 
LVL 86

Expert Comment

by:jkr
ID: 9799298
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
 
LVL 1

Author Comment

by:Hoegje
ID: 9809381
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
 
LVL 1

Author Comment

by:Hoegje
ID: 9816503
Does anybody know how I should access the child node ?
0
 
LVL 1

Author Comment

by:Hoegje
ID: 9904280
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
 
LVL 1

Accepted Solution

by:
Hoegje earned 0 total points
ID: 9947922
#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

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

Written by John Humphreys C++ Threading and the POSIX Library This article will cover the basic information that you need to know in order to make use of the POSIX threading library available for C and C++ on UNIX and most Linux systems.   [s…
Introduction This article is the first in a series of articles about the C/C++ Visual Studio Express debugger.  It provides a quick start guide in using the debugger. Part 2 focuses on additional topics in breakpoints.  Lastly, Part 3 focuses on th…
The goal of the tutorial is to teach the user how to use functions in C++. The video will cover how to define functions, how to call functions and how to create functions prototypes. Microsoft Visual C++ 2010 Express will be used as a text editor an…
The viewer will be introduced to the member functions push_back and pop_back of the vector class. The video will teach the difference between the two as well as how to use each one along with its functionality.

762 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

15 Experts available now in Live!

Get 1:1 Help Now