00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017
00018
00019
00020
00021
00022
00023
00024
00025
00026
00027
00028
00029
00030
00031
00032
00033
00034
00035
00036
00037
00038
00039
00040
#include <sys/types.h>
00041
#if !defined(_MSC_VER) && !defined(_MINGW_) && !(defined WIN32)
00042
#include <sys/wait.h>
00043
#endif
00044
#include <plearn/base/stringutils.h>
00045
#include "IPopen.h"
00046
00047
namespace PLearn {
00048
using namespace std;
00049
00050
#ifndef _MINGW_
00051
00052 int IPServer::ip_port = 15000;
00053 int IPServer::max_connections = 100;
00054
00055 void IPopen::launch(
IPServer &server,
const string& command) {
00056
if (
verbose)
00057 cout <<
"IPopen launches:" <<
endl << command <<
endl;
00058
00059
if (fork() == 0) {
00060
00061 system(command.c_str());
00062 exit(1);
00063 }
00064
establish_communication(server);
00065 }
00066
00067 IPopen::~IPopen() {
00068
00069 shutdown(
socket_fd, 2);
00070 close(
socket_fd);
00071 }
00072
00073
00074
void
00075 IPopen::establish_communication(
IPServer &server)
00076 {
00077
int addr_len =
sizeof(
struct sockaddr_in);
00078
00079
00080
socket_fd = accept(server.
get_socket_fd(),
00081 (
struct sockaddr *)server.
get_address(),
00082
#ifndef SGI
00083
(socklen_t *)&addr_len);
00084
#else //def SGI
00085
&addr_len);
00086
#endif //ndef SGI
00087
if (socket_fd <= 0)
00088
PLERROR(
"Failure to connect with client");
00089
00090
00091
pipe.
attach(socket_fd);
00092
00093
00094 }
00095
00096
00097
00098
int
00099 establish_connection(
int n_hosts,
const char *hostnames[],
int port_no)
00100 {
00101
struct sockaddr_in address;
00102
struct hostent *hostinfo;
00103
00104
00105
int server_socket = socket(AF_INET, SOCK_STREAM, 0);
00106
if (server_socket <= 0)
00107
PLERROR(
"Cannot create socket");
00108
00109 address.sin_family = AF_INET;
00110 address.sin_port = htons(port_no);
00111
00112
for (
int i = 0; i < n_hosts; ++i) {
00113 hostinfo = gethostbyname(hostnames[i]);
00114
if (!hostinfo)
00115 inet_pton(AF_INET, hostnames[i], &address.sin_addr);
00116
00117
else
00118 address.sin_addr = *(
struct in_addr *)*hostinfo->h_addr_list;
00119
00120
00121
if (connect(server_socket, (
struct sockaddr *)&address,
sizeof(address)))
00122
00123
continue;
00124
00125
00126
int nodelay = 1;
00127 setsockopt(server_socket, IPPROTO_TCP, TCP_NODELAY, (
char *)nodelay,
sizeof(
int));
00128
00129
00130
return server_socket;
00131 }
00132
PLERROR(
"Connection to server failed");
00133
return -1;
00134 }
00135
#endif // ~_MINGW_
00136
00137 }