#include #include #include #include #include #include #include #include #include // on demand scheduling of tasks to workers // receive request from worker i -> send task to compute to worker i // when no more tasks are available, send an EOS termination // // usage is: // a.out portno // number of the port used to get worker task requests #define MAXHOSTNAME 80 int main(int argc, char * argv[]) { int s,si, retcode, i; unsigned int salen; struct sockaddr_in sa,sai; char hostname[MAXHOSTNAME]; int task = 0; // tasks are positive integeres, in this case int tasklimit = 100; // we'll send tasklimit tasks before stopping int eos = -1; // special task to denote End Of Stream // code needed to set up the communication infrastructure printf("Declaring socket\n"); si = socket(AF_INET,SOCK_STREAM,0); // socket for inputs if(si == -1) {perror("opening socket for input"); return -1;} sai.sin_family = AF_INET; sai.sin_port = htons(atoi(argv[1])); gethostname(hostname,MAXHOSTNAME); memcpy(&sai.sin_addr, (gethostbyname(hostname)->h_addr), sizeof(sa.sin_addr)); printf("Binding to %s\n",inet_ntoa(sai.sin_addr)); retcode = bind(si,(struct sockaddr *) & sai, sizeof(sai)); if(retcode == -1) { perror("while calling bind"); return -1; } printf("Listening socket\n"); retcode = listen(si,1); if(retcode == -1) { perror("while calling listen"); return -1; } while(1==1) { salen = sizeof(sa); printf("Accepting connections .... \n"); s = accept(si,(struct sockaddr *)&sa,&salen); // accept a connection if(s == 1) { perror("while calling an accept"); return -1; } retcode = read(s,&i,sizeof(int)); // read request from worker if(retcode == -1) { perror("while reading task from worker"); return -1; } printf("%d ",i); fflush(stdout); if(task < tasklimit) { // send a task to the requesting worker write(s,&task,sizeof(task)); printf("sent task %d to worker %d\n",task,i); task++; // next task to be sent } else { // if no more tasks, then send an EOS write(s,&eos,sizeof(task)); printf("Send EOS to worker %d\n",i); } close(s); } printf("Closing operations\n"); return 0; }