//------------------------------------------------------------------- // pingpipe.cpp // // This program shows how the 'pipe()' system-call can be used // to transfer information from a child-process to its parent. // Here the hostname for some computer on the local network is // typed as a command-line argument, and this application then // will respond by displaying that computer's IP-address. // // compile using: $ g++ pingpipe.cpp -o pingpipe // execute using: $ ./pingpipe // // programmer: ALLAN CRUSE // written on: 12 MAR 2008 //------------------------------------------------------------------- #include // for printf(), perror() #include // for open() #include // for exit() #include // for read(), write(), close() #include // for strchr() #include // for waitpid() char *args[4] = { "/bin/ping", "-c1", }; int main( int argc, char **argv, char **envp ) { if ( argc == 1 ) // command-line argument is needed { fprintf( stderr, "usage: pingpipe \n" ); exit(1); } else args[ 2 ] = argv[1]; // finish the args[] setup // create a 'pipe' for child-to-parent communication int fd[ 2 ]; pipe( fd ); if ( fork() == 0 ) { close( fd[0] ); // child closes the pipe's 'read' end close( STDOUT_FILENO ); // standard output is dup2( fd[1], STDOUT_FILENO ); // written to the pipe execve( args[0], args, envp ); // child executes 'ping' perror( "execve" ); exit(1); } close( fd[1] ); // parent closes the pipe's 'write' end waitpid( 0, NULL, 0 ); // then parent waits until child quits char info[ 80 ] = {0}; // buffer for data read from pipe int nbytes = read( fd[0], info, 79 ); // read from pipe if ( nbytes < 0 ) { perror( "read" ); exit(1); } // extract the IP-address for the specified host char *p = strchr( info, '(' ); // where IP-address starts char *q = strchr( info, ')' ); // where IP-address ends printf( "\nIP-address for \'%s\' is ", argv[1] ); for (int i = 1; i < q-p; i++) printf( "%c", p[i] ); printf( "\n\n" ); }