@@ -77,10 +77,10 @@ void forward_response(int infd, int outfd)
77
77
fprintf (stderr , "Content-length: %d\n" , content_length );
78
78
#endif
79
79
// read content
80
- char * content_buf = (char * )malloc ((content_length + 1 )* sizeof (char ));
80
+ char * content_buf = (char * )Malloc ((content_length + 1 )* sizeof (char ));
81
81
Rio_readnb (& rio , content_buf , content_length );
82
82
string_appendn (& response , content_buf , (size_t )content_length );
83
- free (content_buf );
83
+ Free (content_buf );
84
84
}
85
85
if (Rio_readlineb (& rio , buf , MAXLINE ) != 0 ) {
86
86
// TODO: error handling
@@ -125,8 +125,6 @@ void forward(int fromfd)
125
125
#endif
126
126
127
127
sprintf (request_buf , "%s %s %s\r\n" , method , dir , version );
128
- int clientfd = Open_clientfd (
129
- host , port );
130
128
131
129
int has_host = 0 ;
132
130
// request headers
@@ -166,12 +164,25 @@ void forward(int fromfd)
166
164
#ifdef DEBUG
167
165
fprintf (stderr , "request buf:\n%s\n" , request_buf );
168
166
#endif
167
+ int clientfd = Open_clientfd (
168
+ host , port );
169
169
Rio_writen (clientfd , request_buf , strlen (request_buf ));
170
170
171
171
// receive data
172
172
// read_response(clientfd);
173
173
174
174
forward_response (clientfd , fromfd );
175
+ Close (clientfd );
176
+ }
177
+
178
+ void * thread (void * vargp )
179
+ {
180
+ int connfd = * ((int * )vargp );
181
+ Pthread_detach (pthread_self ());
182
+ Free (vargp );
183
+ forward (connfd );
184
+ Close (connfd );
185
+ return NULL ;
175
186
}
176
187
177
188
@@ -186,14 +197,20 @@ int main(int argc, char **argv)
186
197
int listenfd = Open_listenfd (argv [1 ]);
187
198
struct sockaddr_storage clientaddr ;
188
199
socklen_t clientlen = sizeof (clientaddr );
200
+ int * connfdp ;
189
201
while (1 ) {
190
- int connfd = Accept (listenfd ,
202
+ connfdp = Malloc (sizeof (int ));
203
+ * connfdp = Accept (listenfd ,
191
204
(SA * )& clientaddr ,
192
205
& clientlen );
193
- if (connfd == -1 ) {
206
+ if (* connfdp == -1 ) {
207
+ Free (connfdp );
194
208
// TODO: error report
209
+ } else {
210
+ // TODO: use thread pool
211
+ pthread_t tid ;
212
+ Pthread_create (& tid , NULL , thread , connfdp );
195
213
}
196
- forward (connfd );
197
214
}
198
215
return 0 ;
199
216
}
0 commit comments