1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282
| #include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <pthread.h>
#include <sys/wait.h>
#include <errno.h>
#include <fcntl.h>
typedef struct
{
int exist;
pthread_t tid;
int socket_id;
} client_t;
#define DEBUG 1
#ifdef DEBUG
#define DEBUG_TEST 1
#else
#define DEBUG_TEST 0
#endif
#define debug_print(fmt, ...) \
do { if (DEBUG_TEST) fprintf(stderr, "%s:%d:%s(): " fmt, __FILE__, \
__LINE__, __func__, __VA_ARGS__); } while (0)
#define NB_CONNECTIONS_PAR_THREAD 1
#define NB_THREADS 2
#define NUM_PORT_SERVER 2000
#define NB_CONNECTIONS_PAR_PROCESSUS 3
//####################### client #######################
void * client (void *userdata)
{
client_t *client = userdata;
char hello[] = "Ah! Bonjour, vous\n";
int i;
printf ("Nouveau thread\n");
/*
* boucle pour utiliser le même thread pour plusieurs connexions.
*/
for (i = 0; i < NB_CONNECTIONS_PAR_THREAD; i++)
{
/* attente initialisation client->socket_id pour
* communiquer avec le client.
*/ debug_print("client->socket_id %d\n",client->socket_id);
while (client->socket_id == -1)
sleep (1);
write (client->socket_id, hello, strlen (hello));
shutdown (client->socket_id, 2);
close (client->socket_id);
client->socket_id = -1;
}
/* une structure pour chaque thread.
* La présence de client->exist == 1 indique son existence.
*/
client->exist = 0;
printf ("Fin du thread\n");
return (NULL);
}
//####################### create_new_thread #######################
int create_new_thread (int socket_id, int nombre_max_de_threads)
{
debug_print("Utilisation du socket_id %d dans create_new_thread\n",socket_id);
client_t *thread_params;
int i;
/* Tableau de structures client_t avec un élément par thread.
*/
if (NULL ==
(thread_params = malloc (NB_THREADS * sizeof *thread_params)))
{
fprintf (stderr, "Problème avec malloc()\n");
exit (EXIT_FAILURE);
}
for (i = 0; i < NB_THREADS; i++)
{
thread_params[i].exist = 0;
thread_params[i].socket_id = -1;
}
while (1)
{
pthread_attr_t *thread_attributes;
int client_id;
int thread_id;
if (-1 == (client_id = accept (socket_id, NULL, 0))
&& (errno != EWOULDBLOCK))
{
fprintf (stderr, "Erreur sur accept()\n");
exit (EXIT_FAILURE);
}
debug_print("Accept() OK: client_id %d pour socket_id %d\n",client_id, socket_id);
thread_id = -1;
while (thread_id == -1)
{
/* Cherche un thread oisif. */
for (i = 0; i < NB_THREADS; i++)
{
if ((thread_params[i].exist != 0)
&& (thread_params[i].socket_id == -1))
{
thread_id = i;
thread_params[i].socket_id = client_id;
printf ("Thread %d\n", i);
break;
}
}
if (NB_THREADS == i)
{
/* Réutilisation des threads si possible.
* Si tous les threads existants sont occupés,
* nous créons si possible un nouveau thread.
*/
for (i = 0; i < NB_THREADS; i++)
{
if (thread_params[i].exist == 0)
{
/* Création du nouveau thread. */
thread_id = i;
thread_params[i].socket_id = client_id;
debug_print("Utilisation du thread %d pour client_id %d\n",thread_id,client_id);
thread_params[i].exist = 1;
/* Initialisation des attributs d'un futur thread
* pour qu'il soit détaché. */
printf ("Thread %d\n", i);
if (NULL ==
(thread_attributes =
malloc (sizeof *thread_attributes)))
{
fprintf (stderr, "Problème avec malloc()\n");
exit (EXIT_FAILURE);
}
if (0 != pthread_attr_init (thread_attributes))
{
fprintf (stderr, "Problème avec "
"pthread_attr_init()\n");
free (thread_attributes);
exit (EXIT_FAILURE);
}
if (0 != pthread_attr_setdetachstate (
thread_attributes,
PTHREAD_CREATE_DETACHED))
{
fprintf (stderr, "Problème avec "
"pthread_attr_setdetachstate()\n");
free (thread_attributes);
exit (EXIT_FAILURE);
}
/* Création du thread. */
if (0 !=
pthread_create (&(thread_params[i].tid),
thread_attributes, client,
&(thread_params[i])))
{
fprintf (stderr,
"Problème avec pthread_create()\n");
free (thread_attributes);
exit (EXIT_FAILURE);
}
debug_print("Creation du thread %d pour client_id %d sur socket_id %d\n",thread_id,client_id, socket_id);
/* Libération des ressources nécessaires pour les attributs
* du thread. */
pthread_attr_destroy (thread_attributes);
break;
}
}
}
/* Si thread_id != -1, un thread a été trouvé ou créé et nous quittons.
* Sinon, nous bouclons dans l'attente de la libération d'un thread.
*/
if (thread_id == -1)
sleep (1);
else
return (socket_id);
}
}
exit (EXIT_SUCCESS);
}
//####################### create_tcp_server #######################
int create_tcp_server (int port, int nb_max_clients)
{
int socket_id;
int optval = 1;
struct sockaddr_in sockname;
/* Création de la socket. */
if (-1 == (socket_id = socket (PF_INET, SOCK_STREAM, 0)))
{
fprintf (stderr, "Impossible de créer une socket\n");
exit (EXIT_FAILURE);
}
/* Changement d'un paramètre de la socket pour permettre une
* réutilisation immédiate après sa fermeture.
*/
debug_print("Socket créé. socket_id: %d dans le PID %d\n",socket_id,getpid());
setsockopt (socket_id, SOL_SOCKET, SO_REUSEADDR, &optval,
sizeof (int));
/* Affectation d'une adresse. */
memset ((char *) &sockname, 0, sizeof (struct sockaddr_in));
sockname.sin_family = AF_INET;
sockname.sin_port = htons (port);
sockname.sin_addr.s_addr = htonl (INADDR_ANY);
//debug_print("Socket ID: %d\n",socket_id);
if (-1 ==
(bind
(socket_id, (struct sockaddr *) &sockname,
sizeof (struct sockaddr_in))))
{
fprintf (stderr, "Erreur sur bind() dans le processus %d, avec l'erreure \"%s\"'\n",getpid(),strerror(errno));
exit (EXIT_FAILURE);
}
debug_print("Bind() OK: socket_id %d\n",socket_id);
/* Mise en écoute de la socket. */
if (-1 == (listen (socket_id, nb_max_clients)))
{
fprintf (stderr, "Erreur sur listen()\n");
exit (EXIT_FAILURE);
}
debug_print("listen() OK: socket_id %d\n",socket_id);
socket_id = create_new_thread(socket_id, NB_CONNECTIONS_PAR_THREAD);
return socket_id;
}
//############################# main #############################
int main ()
{
int socket_id;
int client_id;
long socket_flags;
socket_id = create_tcp_server (2000, 10);
debug_print("create_tcp_server OK: socket_id %d\n",socket_id);
fcntl (socket_id, F_GETFL, &socket_flags);
socket_flags |= O_NONBLOCK;
fcntl (socket_id, F_SETFL, socket_flags);
while (1)
{
int pid;
client_id = -1;
while (-1 == client_id)
{
while (waitpid (-1, NULL, WNOHANG) > 0);
}
switch ((pid = fork ()))
{
case -1:
fprintf (stderr, "Problème avec fork()\n");
exit (EXIT_FAILURE);
case 0:
debug_print("PID créé. %d\n",getpid());
debug_print("Client_ID. %d\n",client_id);
create_new_thread(socket_id, NB_CONNECTIONS_PAR_THREAD);
default:
close (client_id);
}
}
exit (EXIT_SUCCESS);
} |
Partager