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
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <netinet/in.h>
#define PORTSTART 10000
int main( int argc, char ** argv )
{
int N,Ne;
char buffer[BUFSIZ];
int i,ie;
int *sockfd,*newsockfd,*portno;
int portcount = PORTSTART;
socklen_t clilen = sizeof(struct sockaddr_in);
struct sockaddr_in *serv_addr,*cli_addr;
// Read arguments
if (argc<3) return 1;
sscanf(argv[1],"%i",&Ne);
sscanf(argv[2],"%i",&N);
// Allocate memory
sockfd = (int*)malloc(Ne*sizeof(int));
portno = (int*)malloc(Ne*sizeof(int));
newsockfd = (int*)malloc(Ne*sizeof(int));
serv_addr = (struct sockaddr_in*)malloc(Ne*sizeof(struct sockaddr_in));
cli_addr = (struct sockaddr_in*)malloc(Ne*sizeof(struct sockaddr_in));
// Create sockets
for (ie=0;ie<Ne;ie++) {
printf("Setting %2i:",ie); fflush(stdout);
sockfd[ie] = socket(AF_INET,SOCK_STREAM,0);
bzero((char*)&serv_addr[ie],sizeof(serv_addr[ie]));
serv_addr[ie].sin_family = AF_INET;
serv_addr[ie].sin_addr.s_addr = INADDR_ANY;
// Loop to find available ports
do {
portno[ie] = portcount;
serv_addr[ie].sin_port = htons(portno[ie]);
if (portcount>PORTSTART+100) {
printf("Port error: all ports tested\n");
return 1;
}
portcount++;
} while (bind(sockfd[ie],(struct sockaddr *) &serv_addr[ie],sizeof(serv_addr[ie])) < 0);
printf(" on port %i",portno[ie]); fflush(stdout);
listen(sockfd[ie],5);
// Ready to run child
sprintf(buffer,"./child %i %i &",ie,portno[ie]);
system(buffer);
printf(" -> OK\n");
}
// Wait for children connection
for (ie=0;ie<Ne;ie++) {
newsockfd[ie] = accept(sockfd[ie],(struct sockaddr *) &cli_addr[ie],&clilen);
}
// Iteration loop
for (i=0;i<N;i++) {
printf("%i: ",i); fflush(stdout);
// Run new children iteration
for (ie=0;ie<Ne;ie++) {
sprintf(buffer,"%i",ie);
write(newsockfd[ie],buffer,strlen(buffer));
}
// Wait for children processes
for (ie=0;ie<Ne;ie++) {
read(newsockfd[ie],buffer,BUFSIZ);
}
printf(" -> OK\n");
}
// Make children exit
for (ie=0;ie<Ne;ie++) {
write(newsockfd[ie],"done",4);
}
// Close sockets and deallocate memory
for (ie=0;ie<Ne;ie++) {
close(newsockfd[ie]);
close(sockfd[ie]);
}
free(sockfd);
free(portno);
free(newsockfd);
free(serv_addr);
free(cli_addr);
return 0;
}
| |