Server concurent cu procese pentru problema precedenta:
server_concurent.c
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 |
#include <sys/types.h> #include <sys/socket.h> #include <stdio.h> #include <netinet/in.h> #include <netinet/ip.h> #include <string.h> void deservire_client(int c) { // deservirea clientului uint16_t a, b, suma; recv(c, &a, sizeof(a), MSG_WAITALL); recv(c, &b, sizeof(b), MSG_WAITALL); a = ntohs(a); b = ntohs(b); suma = a + b; suma = htons(suma); send(c, &suma, sizeof(suma), 0); close(c); // sfarsitul deservirii clientului; } int main() { int s; struct sockaddr_in server, client; int c, l; s = socket(AF_INET, SOCK_STREAM, 0); if (s < 0) { printf("Eroare la crearea socketului server\n"); return 1; } memset(&server, 0, sizeof(server)); server.sin_port = htons(1234); server.sin_family = AF_INET; server.sin_addr.s_addr = INADDR_ANY; if (bind(s, (struct sockaddr *) &server, sizeof(server)) < 0) { printf("Eroare la bind\n"); return 1; } listen(s, 5); l = sizeof(client); memset(&client, 0, sizeof(client)); while (1) { c = accept(s, (struct sockaddr *) &client, &l); printf("S-a conectat un client.\n"); if (fork() == 0) { // fiu deservire_client(c); return 0; } // se executa doar in parinte pentru ca fiul se termina mai sus din cauza exit-ului } } |