#include #include #include #include #include #include typedef struct CLL { char ch; struct CLL *next; } CLL; int main (int argc, char **argv); char *readstring (int *len); //Polling is a technique that Linux uses to help manage I/O devices. //"poll" lets you know whether there is input to be read from a file //descriptor without actually reading that input. If there's no //input to be read, then your program can go on about its business. //If there is input, then your program can read or not read. //This sort of thing was necessary for text-based video games. //If you read from the keyboard, the program will block until //the input is entered. If you want to have the program do stuff //while the user is deciding what to type, you need to use poll //or something similar (such as select). int main (int argc, char **argv) { srand (time (NULL)); struct pollfd fds[1]; //An array of things to poll. Maybe terminals, or pipes or sockets fds[0].fd = 0; //I will check standard input, the keyboard. fds[0].events = POLLIN; //I will check to see if anything is waiting to be typed int dead = 0; while (!dead) { write (1,"What do you want to do? ",25); int ret = poll (fds,1,5000); //I'll poll using the fds structure, size 1, for a thousand milliseconds. It returns the number of things in the array for which input is available. if (ret == 0) { write (1,"\nWhile you were thinking, an ogre ate you!\n",43); dead = 1; } else { int len; char *s = readstring (&len); if (rand()%2==0) { write (1,"I don\'t know how to ",20); write (1,s,len); write (1,"\n",1); free (s); } else { write (1,"You got killed!\n",16); dead =1; } } } return 0; } char *readstring (int *len) { CLL *L = NULL; int ct = 0; char buf; char *final; while (1) { read (0,&buf,1); if (buf=='\n') break; CLL *N = malloc (sizeof (CLL)); N->ch = buf; N->next = L; L = N; ct++; } final = malloc (ct+1); *len = ct; final[ct] = '\0'; while (ct > 0) { ct--; final[ct] = L->ch; CLL *N = L; L = L->next; free (N); } return final; }