Main Content

Sockets, time handling and keyboard interrupt handling in C

Archive - Originally posted on "The Horse's Mouth" - 2015-03-27 11:55:28 - Graham Ellis

A new example from last week's C course - a simple TCP/IP server that processes one connection at a time, taking a user's input into a "giftbox" and returning the donantion made by the previous person. The scenario is that you may be given wonderful gifts by people - but sometimes they're not wonderful for you and you would like to swap them!

It's all too easy when writing a new example to include too much into it so that readers are overwhelmed; I've tried in this case to make sockets simple, whilst at the same time providing something that works practically. The code illustrates:
  • a server written in C
  • some time handling in C
  • how we trap ^C (keyboard interrupts) in C via signals
The code could be extended to provide
  • cleaner shutdown
  • forking to handle multiple parallel connections
  • extension to handle longer user input strings / gift descriptions
  • error checking
  • additional logging

Program source is [here] - together with sample outputs from running it - on server, with client and the logfile. This is not something that we cover on every C / C++ course as it's specialist interest - but if you come on one of our public C courses and have an interest, I'll cover it after class f