#include #include "jrb.h" #include "socketfun.h" #include typedef struct { char *name; int age; char *ssn; } Entry; JRB t; void *server_thread(void *v) { int *fdp; JRB tmp; FILE *fin, *fout; int age; char fn[300], ln[300], ssn[100], n[300]; char command[300]; Entry *e; fdp = (int *)v; fin = fdopen(*fdp, "r"); if (fin == NULL) { perror("making fin"); exit(1); } fout = fdopen(*fdp, "w"); if (fout == NULL) { perror("making fout"); exit(1); } while(fscanf(fin, "%s", command) != EOF) { if (strcmp(command, "ADD") == 0) { fscanf(fin, "%s %s %d %s", fn, ln, &age, ssn); e = (Entry *) malloc(sizeof(Entry)); e->name = (char *) malloc(sizeof(char)*(strlen(ln)+strlen(fn)+3)); strcpy(e->name, ln); strcat(e->name, ", "); strcat(e->name, fn); e->ssn = (char *) strdup(ssn); e->age = age; jrb_insert_str(t, e->name, new_jval_v(e)); } else if (strcmp(command, "PRINT") == 0) { fprintf(fout, "__________________________________________________\n"); jrb_traverse(tmp, t) { e = (Entry *) tmp->val.v; fprintf(fout, "%-30s -- %11s %4d\n", e->name, e->ssn, e->age); } fprintf(fout, "--------------------------------------------------\n"); fflush(fout); } else if (strcmp(command, "DELETE") == 0) { fscanf(fin, "%s %s", fn, ln); strcpy(n, ln); strcat(n, ", "); strcat(n, fn); tmp = jrb_find_str(t, n); if (tmp == NULL) { fprintf(fout, "Error: No %s %s\n", fn, ln); fflush(fout); } else { jrb_delete_node(tmp); } } else if (strcmp(command, "DONE") == 0) { return NULL; } else { fprintf(fout, "Bad command: %s\n", command); fflush(fout); } } return NULL; } main(int argc, char **argv) { pthread_t tid; int fdp[1]; int sock; if (argc != 3) { fprintf(stderr, "usage: ssnserver1 host port\n"); exit(1); } t = make_jrb(); sock = serve_socket(argv[1], atoi(argv[2])); fdp[0] = accept_connection(sock); pthread_create(&tid, NULL, server_thread, fdp); pthread_exit(NULL); }