Path: blob/master/concurrency-webserver/src/spin.c
910 views
#include <assert.h>1#include <stdio.h>2#include <stdlib.h>3#include <string.h>4#include <sys/time.h>5#include <unistd.h>67#define MAXBUF (8192)89//10// This program is intended to help you test your web server.11// You can use it to test that you are correctly having multiple threads12// handling http requests.13//1415double get_seconds() {16struct timeval t;17int rc = gettimeofday(&t, NULL);18assert(rc == 0);19return (double) ((double)t.tv_sec + (double)t.tv_usec / 1e6);20}212223int main(int argc, char *argv[]) {24// Extract arguments25double spin_for = 0.0;26char *buf;27if ((buf = getenv("QUERY_STRING")) != NULL) {28// just expecting a single number29spin_for = (double) atoi(buf);30}3132double t1 = get_seconds();33while ((get_seconds() - t1) < spin_for)34sleep(1);35double t2 = get_seconds();3637/* Make the response body */38char content[MAXBUF];39sprintf(content, "<p>Welcome to the CGI program (%s)</p>\r\n", buf);40sprintf(content, "%s<p>My only purpose is to waste time on the server!</p>\r\n", content);41sprintf(content, "%s<p>I spun for %.2f seconds</p>\r\n", content, t2 - t1);4243/* Generate the HTTP response */44printf("Content-Length: %lu\r\n", strlen(content));45printf("Content-Type: text/html\r\n\r\n");46printf("%s", content);47fflush(stdout);4849exit(0);50}51525354