Zach Burlingame
Programming, Computers, and Other Notes on Technology

June, 2011Archive for

Ubuntu 11.04 Natty Narwhal Upgrade – Grub Prompt on First Reboot

Wednesday, June 29th, 2011

I just updated one of my VMs from Ubuntu 10.10 to 11.04 Natty Narwhal using the Update Manager. All seemed to go well during the upgrade process. When it rebooted for the first time however, I was left with a grub prompt rather than a booting system. Grrrrrr.

NOTE: The following assumes the default disk layout. If you installed to a different disk or partition, you’ll have to adjust the steps below accordingly.

The fix is to manually boot the system at the grub prompt by typing

set root=(hd0,1)
linux /boot/vmlinux-2.6.38-8-generic root=/dev/sda1 ro
initrd /boot/initrd.img-2.6.38-8-generic

Then once you are successfully booted, re-install grub like this:

sudo grub-install /dev/sda
sudo update-grub

Thanks to Rob Convery for the tip!

C Assert and Wrapping Macros in Do/While Loops

Friday, June 24th, 2011

I was planning on writing a couple of entries on C macros, including assert macros and why you should wrap your macros in do/while loops. While doing a bit of research I came across a couple of excellent blog posts by Charles Nicholson on these very topics. Rather than try and out do him, I’ll just refer you to him!

Building a Better Assert Macro

Why You Should Be Wrapping Your Macros in Do/While Loops

Limiting an Application to a Single Instance with Named Events

Tuesday, June 21st, 2011

Sometimes it’s desirable to allow only a single instance of an application per user or even per system. There are several ways you can do this.


In the case of a single instance per user session, you can use FindWindow to enumerate through the window handles for the current user session based on the window class and window title. This is actually how Microsoft Outlook does it. The drawback is that this only supports limiting the current session and it requires a window handle (i.e. doesn’t work in Console applications without creating a hidden window).

Use a File or Registry as a Lock

This method is used by VMware to establish whether a .vmdk file is locked by another process. Sometimes when you get an unclean shutdown of the owning VMware process, the file lock hangs around and the user must manually delete the file in order to boot the VM. This solution does not rely on a window handle and is thus applicable for any application that can access the disk which is good. However just like with with VMWare, using this as a solution for a single application instance could get us into a state where the user can’t run the app at all until they delete the lock file – not good.


This is one of the most prevalent and well documented. This technique places a uniquely named mutex in the either the global namespace (for a single system-wide instance) or the local namespace (for a single session-wide instance) using the CreateMutex Win32 API call and then detecting whether the object already exists when the application first starts. The mutex is torn down when the last process that holds a handle to the object exits. This prevents use from getting in a stale state where we can’t start any instances of the application at all. Since this solution doesn’t require a handle to a window, it’s suitable for any type of Windows application (e.g. Windows Application/WinForm, Console, Service).


This technique uses the same concept of a uniquely named event as the mutex technique. Also like the mutex solution, it’s suitable for any type of Windows application and the event is torn down when the last process that holds a handle to the event exits. The reason I choose this method over the global mutex however is that I overload the use of this event to serve as my shutdown signal. This allows me to use the same object to determine if an instance of an application is running as well as signal all instances of the application to terminate if necessary.

Based on my signal terminate solution here, you can limit an application to a single instance by removing this from initialize_terminate_event in signal_terminate.c

  // Make sure our instance of the application didn't already initialize the event
  if( fh_terminate_event != NULL )
    return SUCCESS;

and calling it at the beginning of your application’s main routine like this.

// Library Includes
#include <Windows.h>
#include <stdio.h>

// Application Includes
#include "error_codes.h"
#include "terminate.h"
#include "types.h"

Int32 main( Int32 argc, Char* argv[] )
  Int32 return_code = initialize_terminate_event( );
  // If the event already exists or if there is an error 
  // creating the event, just exit. 
  if( return_code != SUCCESS )
     return return_code;

  // Main routine here

Simple Reader-Writer Lock in C on Win32

Monday, June 20th, 2011

In a particular native C Win32 application, I have a few threads that regularly read a particular set of information while performing their main work routines and a single thread that updates that information. A readers-writer lock is well suited to a workload that is heavily read based with scarce writes.

The Win32 API provides a Slim Reader-Writer Lock. The problem is that it wasn’t added until Vista and I still need to support Windows XP. I wasn’t too keen on writing my own as writing thread-safe code – particularly synchronization objects – is notoriously tricky. A quick search turned up several solutions for a reader-writer lock in C++, but not too many in C. I was even less keen on using a fully-featured RWLock that wasn’t from a mature and active project or porting an implementation from C++. Fortunately, a basic RWL is not that difficult as far as synchronization objects go.

I decided to roll my own and I’ve placed the project on Bitbucket here. As I come across other threading needs, I’ll add any functions and utilities to it. There are certainly no guarantees that my implementation is bug-free but I did at least give a bit of thought. If you find anything, please share so that I can fix it!

HOWTO: Generate and Publish Doxygen Documentation in TeamCity

Sunday, June 12th, 2011

I’ve started using Doxygen and JavaDoc style comments on my native C/C++ applications for documentation generation. In keeping with my goal to have everything “just work” on checkout with minimal dependencies (ideally just Visual Studio and version control) I wanted to get it integrated directly into the project. That way anyone can generate the latest version of the documentation from their working copy whenever they need it. Since I use TeamCity for my continuous integration server, it was natural to have the CI server generate and publish the latest documents during the build process.

Setup Doxygen

Setup Doxygen in a Working Copy of your Project

  1. Download the Windows Doxygen zip package
  2. Create build/doxygen/bin
  3. Place DoxyFile in build/doxygen/
  4. Create build.xml in build/doxygen/
  5. +---build
    |   \---doxygen
    |       \---bin


    <?xml version="1.0" encoding="utf-8"?>
    <Project ToolsVersion="3.5" DefaultTargets="Doxygen" 
      <Target Name="Doxygen">
        <MakeDir Directories="$(OutputDirectory)" />
        <Exec Command="bin\doxygen.exe" />
  6. Test the script using MSBuild in a Visual Studio Command prompt
  7. [batch]
    cd /path/to/project/build/doxygen
    msbuild build.xml

  8. Add the documentation/doxygen output folder to your VCS ignore pattern. (e.g. for Mercurial, add the following to the .hgignore file)
  9. glob:documentation/doxygen/*
  10. Add the all the files (including doxygen.exe, build.xml, and DoxyFile) to version control, commit the changes and publish them to the master repo (e.g. for Mercurial)
  11. [batch]
    hg add
    hg commit -m"Added Doxygen"
    hg push ssh://user@reposerver://srv/hg/project

Setup Public Key Authentication

The following steps must be done on the BUILD SERVER. If you have multiple build servers/build agents for TeamCity, then you’ll need to duplicate most of these steps on each one. Alternatively, you can use a shared RSA key.

Generate an RSA public/private key pair

  1. Download and Install PuTTY.Look under “A Windows installer for everything except PuTTYtel”
  2. Open puttygen
  3. Click Generate
  4. Click Save Private Key
  5. Choose a location to save (I’ll use C:\keys for this example)
  6. Name the file (I’ll use buildserver.ppk for this example)
  7. Click Save Public Key
  8. Choose the same location used for the private key
  9. Name the file (I’ll use for this example)

The following steps must be done on the WEB SERVER

Add an account for the buildserver

sudo useradd buildserver

Setup public key authentication for the user

  1. Setup the necessary files, directories, and permissions
  2. su buildserver
    mkdir ~/.ssh
    chmod 700 ~/.ssh
    touch ~/.ssh/authorized_keys
    chmod 600 ~/.ssh/authorized_keys
    vim ~/.ssh/authorized_keys
  3. In PuTTYGen, copy the entire contents of the box labeled: “Public key for pasting into OpenSSH authorized_keys file:”
  4. Paste the contents into authorized_keys on the Web Server and save the file.

Setup Rsync

The following steps must be done on the BUILD SERVER.
Since Windows doesn’t natively have rsync, I use the cygwin packaged cwrsync.

  1. Download cwrsync
  2. I ran into problems with cwrsync being used in conjunction with plink where I received the following error:

    “Unable to read from standard input: The parameter is incorrect.”

    The problem apparently is when cygwin programs use redirected stdin/stdout handles. The solution I found to this was to use cygnative. From their website:

    Cygnative.exe is a wrapper for cygwin programs which call native Win32 programs with stdin and/or stdout handle redirected. Without cygnative.exe it is possible that the native program can not read from the handle and receives a “invalid handle” error.

  3. Download cygnative
  4. Create a script which will call cwrsync and pipe the rsync over an SSH connection from the build server to the web server.
  5. I placed this script during testing in project\build\doxygen\cwrsync.cmd I was only using it for testing before I put it into a TeamCity build step so I had no plans of commiting it to source control since it ultimately needs the private key which I don’t want in version control. If you aren’t going to use a TeamCity build step to publish the documentation, you can use this script as a starting point for your solution.

    REM *****************************************************************
    REM CWRSYNC.CMD – Batch file template to start your rsync command (s).
    REM By Tevfik K. (
    REM *****************************************************************
    REM Make environment variable changes local to this batch file

    SET LOCAL_DIR=../../documentation/doxygen/html
    SET REMOTE_SERVER=yer_remote_machine_name
    SET REMOTE_USER=yer_remote_user_name
    SET REMOTE_DIR=/var/cache/doxygen/yer_project_name
    SET SSH_KEY=yer_ssh_key
    SET PLINK_CMD=cygnative plink -i %SSH_KEY% -batch

    REM Specify where to find rsync and related files (C:\CWRSYNC)

    REM *****************************************************************
    REM Don’t Change Below This Line
    REM *****************************************************************

    REM Set HOME variable to your windows home directory. That makes sure
    REM that ssh command creates known_hosts in a directory you have access.

    REM Make cwRsync home as a part of system PATH to find required DLLs

    REM Publish the files

    REM Fix the permissions on the files

    In a command prompt, cd to the directory that the cwrsync.cmd script is and run it

    cd /path/to/cwrsync/script/

    It should ‘just work’. If you get an error running the script or your Web Server isn’t serving up the content, try turning up the verbosity of plink and and rsync by adding -v like this:

    SET RSYNC_ARGS=-arzvvvv
    SET PLINK_CMD=cygnative plink -v -i %SSH_KEY% -batch

Configure TeamCity

  1. Create a build step to generate the documentation using the build.xml file created earlier in your project’s build configuration.
  2. Runner type: MSBuild
    Build file path: build\doxygen\build.xml
    Working Directory:
    MSBuild version: Microsoft .NET Framework 4.0
    MSBuild ToolsVersion: 4.0
    Run platform: x86
    Targets: Doxygen
    Command line parameters:
    Reduce test failure feedback time:
    .NET Coverage tools:
    Report type:

    Click “Save”

  3. Create a build step to publish the documentation to the web server.
  4. Rather than use a CMD file in version control or pushing it out to all the build agents, I prefer to use a build step in the build configuration for the project in TeamCity. To use the script in the TeamCity build step, you have to use %% rather than % because TeamCity will treat the % as a TeamCity build property.

    Runner type: Command Line
    Working directory:
    Run: Custom Script
    Custom script: < the contents of your cwrsync.cmd from earlier, with every '%' replaced with '%%' >
    Report type:

    Click “Save”

  5. Run your build and verify that everything works!


Creating Temporary Files on Win32 in C – Part 2

Monday, June 6th, 2011

Last post I talked about the existing options for creating a temporary file on Win32 and the pros and cons of each. This time I’m going to show you the solution that I normally use.

I stated that a temporary file solution would ideally be:

  • Cross-platform
  • Guarantee a unique name
  • Support SBCS/MBCS/Unicode
  • Allow you to have some control over where the file goes
  • Automatically delete itself when you close it or the process exits.

I pretty much gave up on the cross-platform goal after reading through the various existing options. The level of complexity that was going to be required to handle all the nuances just wasn’t worth it to me.

A Partial Solution

I settled on a partial solution. One function which returns a temporary filename, supports SBCS/MBCS/Unicode, checks whether the filename already exists, and allows you to specify either the basepath or the filename (or both). Automatically deleting the file when you close it or the process exits is achieved via CreateFile and FILE_FLAG_DELETE_ON_CLOSE.

Ignoring the cross-platform goal, there are still two problems with this implementation.

  1. By separating the filename creation from the file creation, we still suffer from Race condition 2 “The function only generates filenames which are unique when they are created. By the time the file is opened, it is possible that another process has already created a file with the same name.”
  2. CreateFile returns a HANDLE, not a FILE* so you have to the API calls WriteFile, CloseFile, etc. rather than the CRT calls to fwrite, fclose, etc. [1]
[1] It may be possible to convert a Win32 HANDLE to a FILE* based on the information in this article.

Getting the Temporary Filename

#include <Windows.h>
#include <errno.h>
#include <stdlib.h>
#include <tchar.h>

#define SUCCESS                               +0
#define FAILURE_NULL_ARGUMENT                 -1         
#define FAILURE_API_CALL                      -3
#define FAILURE_INVALID_PATH                  -4
#define FAILURE_FILE_ALREADY_EXISTS           -5

Bool directory_exists( LPCTSTR p_path )
  DWORD attributes = GetFileAttributes( p_path );
  return ( attributes != INVALID_FILE_ATTRIBUTES &&
         (attributes & FILE_ATTRIBUTE_DIRECTORY) );

Bool file_exists( LPCTSTR p_path )
  DWORD attributes = GetFileAttributes( p_path );
  return ( attributes != INVALID_FILE_ATTRIBUTES &&
         !(attributes & FILE_ATTRIBUTE_DIRECTORY) );

int get_tmp_filename( LPCTSTR p_filename,
                        LPCTSTR p_basepath,
                        LPTSTR  p_tmp_filename,
                        DWORD   tmp_filename_size )
  TCHAR   tmp_path[MAX_PATH]  = { 0 };
  TCHAR   tmp_name[MAX_PATH]  = { 0 };

  // Parameter Validation
  if( p_tmp_filename == NULL )

  // Get a basepath
  if( p_basepath != NULL )
    _tcscpy_s( tmp_path, MAX_PATH, p_basepath );
  { // Use the CWD if a basepath wasn't supplied
    _tcscpy_s( tmp_path, MAX_PATH, TEXT(".\\") );
  if( !directory_exists( tmp_path ) )

  // Form the full filename
  if( p_filename != NULL )
    _tcscpy_s( tmp_name, MAX_PATH, tmp_path );
    _tcscat_s( tmp_name, MAX_PATH, TEXT("\\") ); 
    _tcscat_s( tmp_name, MAX_PATH, p_filename );
  { // Get a temporary filename if one wasn't supplied
    if( GetTempFileName( tmp_path, NULL, 0, tmp_name ) == 0 )
      _ftprintf( stderr, TEXT("Error getting temporary filename in %s.\n"), tmp_path );
      return FAILURE_API_CALL;

  // Copy over the result
  switch( _tcscpy_s( p_tmp_filename, tmp_filename_size, tmp_name ) )
  case 0:
    // Make sure that the file doesn't already exist before we suggest it as a tempfile.
    // They will still get the name in-case they intend to use it, but they have been warned.
    if( file_exists( tmp_name ) )
    return SUCCESS;
  case ERANGE:
    return FAILURE_API_CALL;

Create a File that is Automatically Deleted when the Last Handle is Closed or the Program Terminates Normally

HANDLE h_file = CreateFile( tmpfilename, 
                          NULL );

An Example of Putting It All Together

  HANDLE h_file;
  int    return_code;
  TCHAR  tmpfilename[_MAX_PATH] = { 0 };

  int return_code = get_tmp_filename( NULL, NULL, tmpfilename, _MAX_PATH );
  switch( return_code )
  case SUCCESS:
    return return_code;

  // Extract the DLL to disk
  h_file = CreateFile( tmpfilename, 
                         NULL );
  if( h_file == INVALID_HANDLE_VALUE )
    _ftprintf( stderr, TEXT("Error creating temporary file %s.\n"), tmpfilename );
    return GetLastError();

Creating Temporary Files on Win32 in C – Part 1

Thursday, June 2nd, 2011

So you wanna create a temporary file?

You’re in C, on Windows, and you want to create a temporary file. Ideally it would be:

  • Cross-platform
  • Guarantee a unique name
  • Support SBCS/MBCS/Unicode
  • Allow you to have some control over where the file goes
  • Automatically delete itself when you close it or the process exits.

You wish. There are at least four primary ways of creating a temporary file (if you include the Secure CRT, Unicode, MBCS, and TCHAR versions then there are at least 12)! Each of these provides one or two of the ideal features above, with a few providing more when used in combination with other functions. None of them provides all of these features.

In this post we discuss what our basic options are when creating a temporary file on Windows in C. In Part 2 we’ll discuss which method I prefer and how I’ve implemented it.

So tell me, What are my Options?


Creates a unique filename for the current-working directory of the process

  • Pros:
    • Part of the ISO C Standard
  • Cons
    • No unicode support
    • Potentially unsafe if the parameter is non-NULL and insufficiently sized
    • Race condition 1 – If the str parameter NULL, the returned str points to an internal static buffer that will be overwritten by subsequent calls from the same process.
    • Race condition 2 – The function only generates filenames which are unique when they are created. By the time the file is opened, it is possible that another process has already created a file with the same name.


Unicode version of tmpnam

Pros/Cons are the same as tmpnam, except it supports UNICODE instead of SBCS/MBCS and is Windows-only.


Generic-Text Routine Mapping. Used with TCHAR to map to tmpnam in MBCS builds and _wtmpnam in UNICODE builds.

Pros/Cons are the same as tmpnam/_wtmpnam except it can support either MBCS/UNICODE at build time and is Windows-only


Security-Enhanced CRT version of tmpnam

  • Pros:
    • Security enhancements (avoids buffer overflow and ensures null termination of string)
  • Cons:
    • Unique filenames in CWD only
    • No unicode support
    • Race condition 1 (see tmpnam above)
    • Race condition 2 (see tmpnam above)
    • Windows-only


Unicode version of tmpnam_s

Pros/Cons are the same as tmpnam_s, except it supports UNICODE instead of SBCS/MBCS.


Generic-Text Routine Mapping. Used with TCHAR to map to tempnam in MBCS builds and _wtempnam in UNICODE builds.

Pros/Cons are the same as _ttmpnam_s/_wtmpnam_s except it can support either MBCS/UNICODE at build time


From MSDN:

“_tempnam will generate a unique file name for a directory chosen by the following rules:

– If the TMP environment variable is defined and set to a valid directory name, unique file names will be generated for the directory specified by TMP.
– If the TMP environment variable is not defined or if it is set to the name of a directory that does not exist, _tempnam will use the dir parameter as the path for which it will generate unique names.
– If the TMP environment variable is not defined or if it is set to the name of a directory that does not exist, and if dir is either NULL or set to the name of a directory that does not exist, _tempnam will use the current working directory to generate unique names. Currently, if both TMP and dir specify names of directories that do not exist, the _tempnam function call will fail.

The name returned by _tempnam will be a concatenation of prefix and a sequential number, which will combine to create a unique file name for the specified directory. _tempnam generates file names that have no extension. _tempnam uses malloc to allocate space for the filename; the program is responsible for freeing this space when it is no longer needed.”

  • Pros:
    • There is a way to use a directory other than the default
    • Allocates memory for the return call so you don’t have to guess the size ahead of time
  • Cons:
    • Using a directory other than the default requires changing environment variables for the entire process
    • Holy crap, did you see how complex the rules are just to get a stupid temporary file name?!
    • Only creates a filename, not a file so Race Condition 2 applies again.
    • No Unicode support
    • Allocates memory that the caller has to remember to free (I like to keep my mallocs and frees matched as close together as possible)
    • Windows-only


Unicode version of _tempnam

Pros/Cons are the same as _tempnam, except it supports UNICODE instead of SBCS/MBCS


Generic-Text Routine Mapping. Used with TCHAR to map to tempnam in MBCS builds and _wtempnam in UNICODE builds.

Pros/Cons are the same as tempnam/_wtempnam except it can support either MBCS/UNICODE at build time


Creates a temporary file

  • Pros:
    • Part of the ISO standard
    • Creates a file (not a filename) and thus avoids Race Condition 2
    • The temporary file is automatically deleted when the file is closed, the program terminates normally, or when _rmtmp is called (assuming that the CWD doesn’t change)
  • Cons:
    • Creates a temporary file in the root directory – WTH?! This of course, requires Admin privs on Vista and later.


Windows-only version of tmpfile with the Secure-CRT enhancements.

Pros/Cons are otherwise the same as tmpfile.


Creates a name for a temporary file. If a unique file name is generated, an empty file is created and the handle to it is released; otherwise, only a file name is generated.

MSDN has an article on “Creating and Using a Temporary File” that uses this function. Note that it uses CreateFile which returns a HANDLE not a FILE*.

  • Pros:
    • Supports both Unicode (via GetTempFileNameW macro resolution) and MBCS (via GetTempFileNameA macro resolution)
    • Allows the caller to specify the path (yay!)
    • Allows the caller to specify a filename prefix (up to three characters)
  • Cons:
    • Caller needs to make sure the out buffer is MAX_PATH chars to avoid buffer overflow
    • While it can create the file, it releases the handle, which the caller has to reopen. This can create a security vulnerability where someone else can get to the file before the intented caller does.
    • Windows-only