Modified code to use select() in while loop