Sunday, November 06, 2005

Hello World Web Server

/* The Hello World web server. Type http://localhost:2001 in your
   web browser after running this program. */

#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

#define SOURCE_PORT 2001 /* Use a large port number. */
#define SIZE 1024

/* This is used to initialize an address with a port */

void initaddr(struct sockaddr_in * s,char *hostname,int port) {
  s->sin_family=AF_INET;
  s->sin_port=htons(port);
  inet_aton(hostname,&s->sin_addr);
  memset(&s->sin_zero,0,8);
}

int main() {
  struct sockaddr_in source_addr,new_addr;
  int sockfd;
  int newfd;
  char message[SIZE];
  int sin_size=sizeof(struct sockaddr_in);
  sockfd=socket(PF_INET,SOCK_STREAM,0);
  initaddr(&source_addr,"127.0.0.1",SOURCE_PORT);
  bind(sockfd,(struct sockaddr *)&source_addr,sin_size);
  listen(sockfd,1);
  while(newfd=accept(sockfd,(struct sockaddr *)&new_addr,&sin_size)) {
    recv(newfd,message,SIZE,0);
    strcpy(message,"Hello world!!\n");
    send(newfd,message,strlen(message),0);
    close(newfd);
  }
  close(sockfd);
}

Wednesday, November 02, 2005

Multithreading

/* An attempt at multithreading using POSIX threads library. */
/* Pretty much useless */
/* Compile with gcc filename.c -lpthread */

#include <stdio.h&rt;
#include <pthread.h&rt;

int val=0;
int exited=0;

/* Takes input and displays the value of val. */
void *input_thread(void *ptr) {
  char ch='d';
  while(ch!='q') {
    scanf("%c",&ch);
    switch(ch) {
    case 'd':
      printf("Val:%d\n",val);
      break;
    case 'q':
      break;
    }
  }
  exited=1;   /* Should be kept under lock, but is not. */
}
/* Keeps on incrementing val */
void *compute_thread(void *ptr) {
  while(!exited) 
    val=(val+1)%0xffff;  /* Keep it low. This again should have been under lock. */
}
int main() {
  pthread_t i_thread,c_thread;
  pthread_create(&i_thread,NULL,input_thread,(void *)0);
  pthread_create(&c_thread,NULL,compute_thread,(void *)0);
  /* Wait for both threads to exit before exiting main */
  pthread_join(i_thread,NULL);
  pthread_join(c_thread,NULL);
  return 0;
}