Perl sig-int and open

skip to solution

While recently re-writing our build script into a simple perl script I came across a problem.

I wanted to have the script put output from the commands that it was executing onto both the screen and into a file at the same time.

No problem, in perl you can open commands like you can files, by simply putting a pipe ‘|’ as the first character.

open(OUT, ">log.txt")
    || die "can't open log: $!";
open(STATUS, "netstat -an 2>&1 |")
    || die "can't fork: $!";
while () {
    next if /^(tcp|udp)/;
    print OUT;
close STATUS || die "bad netstat: $! $?";

This code will output the lines to both stdout and to a log file.

Great nice simple code that works using standard perl operations. However one thing that this does not provide is that the forked processes do not receive ‘Ctrl-C’ or ‘Sig-Int’ if you are more of a Unix head.

Which is really quite bad when you are creating a build script you want all processes to die if you need to pull the plug on a build.

So next I turned to calling a direct windows api call GenerateConsoleCtrlEvent calling this function on all child processes in a perl sig-int handler to send CTRL_C_EVENT (0) to each of these processes.

use Win32::Process::Info;
use Win32::API;

$SIG{INT} = 'killChildren';

sub killChildren
    print "Killing process\n";
    my $pi = Win32::Process::Info->new ();

'BOOL GenerateConsoleCtrlEvent(DWORD dwCtrlEvent,  DWORD dwProcessGroupId)');

    my %children = $pi->Subprocesses($$);
    foreach my $child (@{$children{$$}})
        GenerateConsoleCtrlEvent(0, $child);

However if you read the documentation of GenerateConsoleCtrlEvent closely:

Sends a specified signal to a console process group

So then you realize that the process must be created in a process group by calling CreateProcess and passing a CREATE_NEW_PROCESS_GROUP flag. Which is getting to be way too much work there must be a simpler way surely.

The solution I eventually came up with was perl calling via the system command and running an inline script.

open(CMD, "$^X -e \"system(q{$cmd});\" |") || die "Failed to run \"$cmd\": $!\n";

However since the commands I were executing had ” in them as well there were too many variants that were requiring regex replacement to get the commands working correctly.

So like any good web monkey I ended up Base64 encoding the command I wish to execute and then un-encoding it in the sub perl process.

Final Solution

sub RunCommand
    my ($cmd, $dontStop) = @_;
	print "$cmd\n";
	print BUILDLOG "$cmd\n";
	# Run the command through another instance of perl so that it can all be
	# killed when Sig-C is sent to this build file.
	# However command contain characters such as \ and " which are hard
	# to pas through 2 interpreters so base64 endcode and decode the command
	# $^X is a special variable that is the path to perl
	my $encoded = encode_base64($cmd);
  "$^X -e \"use MIME::Base64;system(decode_base64(q{$encoded}));\" |")
  || die "Failed to run \"$cmd\": $!\n";

        print "$_";
        print BUILDLOG "$_";

    if(!$dontStop and $? != 0)
        die "Command: $cmd\nFailed with code: $?\n";

    return $?;

Virtualbox 4.0 dhcp not working

Update Skip to solution

Virtualbox is a wonderful tool for pc virtualization. I use it all the time for testing installers and just general I don’t want to hose my PC if this goes pear shape type stuff.

It’s great for devloping Windows software that needs to work on different versions of the OS too. I test XP, Vista, 7; x32 and x64 versions without breaking a sweat.

However once up upgraded to the new version 4.0 of the product the some networks were no longer operational. Specifically those using the dhcp on host only connections.

I thought this may be an issue with old guest additions which I then proceeded to upgrade. Unfortunately this did no turn out to be the issue so I proceeded to give up an just use other network types.

However today I stumbled upon the solution and it came from somewhere completely unrelated to virtualbox.

The posting of the solution can be found on a forum My Digital Live here.

There appears to be some bug within the source code which the user has devised a patch for.

The Solution

Windows versions of Virtualbox only

  1. Download the compressed patch from
  2. Extract the program using 7-zip
  3. Open command prompt as Administrator and navigate to the directory where you extracted the program
  4. Run the extracted program vb4dhcp.exe passing a single argument to the VBoxC.dll
    vb4dhcp.exe "C:\Program Files\Oracle\VirtualBox\VBoxC.dll"

No you can run Virtualbox and it’s dhcp server runs again. 8)


Virtualbox 4.0.4 has been released and this regression has been fixed. Download it now.

When Websites Dissapear

Over the last 12 months many websites have ceased to exist, GeoCities served it’s last Under Construction gifas yahoo shut the service down. Back in high school I submitted an assignment as a website using this service, now long gone. And the web erupted in a sad chorus to the loss, with some nice tributes.

404 on wall

Then Jeff Atwood lost all of his website to catastrophic data loss. It makes me ponder the feebleness of the web and how it all falls down when a link disappears.

There are many internet spiders archiving the content of the web but that’s largely just text, not images. If you look way back your web browser you will wait for most websites as the now offline images timeout.

I recently took the decision to remove the gallery from my rarely visited part of the web. Mainly because of the maintenance overhead of running two separate web applications, wordpress and gallery, but also for the fact that wordpress now has built in gallery functionality and I rarely have images I want to share. Come to think of it I rarely take photos anyway.

In the end if you want control of you own online identity, ie. your own website, not Facebook, or blogger. Then I guess there will be content that disappears all the time, this dns record would quickly walk away if I didn’t pay the fee or even worse the website would be deactivated by the host if I don’t log into the forums.

A Truly Free Domain

Kitten with Money

If you have ever had a personal website, like me, you would know that your url to your website is important

However if you are also don’t like to pay for things that you can get for free, such as webhosting, you end up with a url that is not as nice as a top level domain.

There are some free domains at the top level but the never have the same feeling of a .net or .com.

So how did I get a .net without using my own money? Well I did but not through a credit card or check I did it by filling out online surveys. They offer cash out via paypal then all I needed was to buy the domain using the survey money.

I had enough in about 3 months just filling out surveys during my usual time on the web.

I ended up buying the domain through namecheap. They offer WhoIsGuard for free for the first year which is a great service so your personal details don’t show up in whois searches.

So it’s not entirely free but if you don’t value your time too much it’s not much work to do a few surveys and have a professional looking domain for your website.

And yes that is my cat! He is a year old now but still very cute, when I bought my last car the seller insisted on cash, I just couldn’t resist the photo opportunity.

time_t and printf

The bane of my existence is work where I use c++ primarily with MFC.

Now today I have come up to one or the most strange occurrence while debugging the database code in our product. I was formatting a string with sprintf and all of my time values were being formatted as “(null)“.

I know we should really be using parameterized queries but this is legacy code created by PC software guys, and I really don’t know if ODBC supports it in a database agnostic way.

Now we have been using Visual Studio 2005 for years but this code has not been working for years, the problem showed up around the database purging code.

When looking in the debugger at the formed SQL I noticed “(null)” showing up instead the numbers I was expecting.

It turns out we were using time_t as the type being fed into sprintf which under this version of Visual C++ is actually a 64-bit integer, or unsinged long long.

So the solution to this rather strange error in formatting is also quite strange, as in how do you format a unsinged long long into sprintf. Well it’s rather simple just add another formatter charter so if you have a signed long long use %lld or if you have a unsinged long long use %llu.

I hope you don’t get tripped up like I did. And if you were wondering why there was “(null)” in the string it’s because the next token was a string, %s, and intel architeture is little endian making the upper 4 bytes all zero, ie null.

Floder Properties in Windows Vista

When using the explorer in Windows Vista I was having trouble finding the folder properties, for showing hidden files among other things. Like everything else in Vista it has moved and changed name. No longer can you find it under “Tools” -> “Folder Options…”

But now under “Organize” -> “Folder and Search Options”

Location of Folder Options in Windows Vista
Location of Folder Options in Windows Vista

It really shook me and the help only had a link to open the options and didn’t tell you how to actually get to the options directly.

Death in a Digital Age

I have recently experienced a death in the family, which has started me wondering about how our digital persona’s will live on.

I personally spend alot of time on the internet, a couple of hours a day at least. Spending my time reading email and rss, writing a blog entry (ocasionally :P ), particiapating in online discussion (Stack Overflow at the moment), buying stuff, reasearching stuff. There is just soo many things that I rely on the internet for.

But at what point do these things dissapear, with the cheapness of media maybe what we create will exisit on forever. This webpage may not as hosts come and go like my first provider, but you can still see entries from there, not very pretty ones, with the internet archive.

It just goes to show that there really isn’t anyone who produces on the internet will ever trully die and therefore no one should be lost to history no matter how small your percived contribution was.

Just makes you think doesn’t it.

The house is finished!

Have you ever noticed that as time goes buy your passion for different things start to wain? I do it seems some things that you thought was important is not so important any more. Like blogging for instance :P

It has been quite a while now mainly because work has been heating up for me. I went on a week long trip to China visiting different customers.

And most importantly our house was finished and we moved in about 4 weeks ago Yey!

And we are loving it, the cat hasn’t adjusted too bad either. But the money is now flowing out finishing off the house. Oh well such is the life of a mortgagee.

House Update

Most people would know we bought land in April to build our first house on.

And since then we have been trying very hard to get approval to build the house we want on it. There was a clause in our title, Memorandum of Common Provisions to be exact. That no structure within the first metre of the boundary will be greater than 3.6 metres tall. And the house plan we decided to build once sited on the block made the height of the garage at 1 metre from the boundary 3.79 meters.

So both I and the build phoned the council to see what could be done, simple they said all you will need is a Planning permit and it should only take a couple of weeks for such a small item.

Thats when the fun really began it took the council 3 months not a couple of weeks to approve the permit and when we finally got it back we were told that the planning permit was not all that needed to be done to allow us to build our house :(

A planning permit like this gives you permission to get a licensed surveyor to draw up a plan that will then be approved by council which will then need to be submitted along with the title kept by the bank to the Titles Office.

So here’s the list of things that cost money along the way:

  • Planning Permit
  • Letters to neighbours
  • Plan
  • Approval of Plan with Council
  • Release of Title from bank
  • Submission to Titles office

So if anyone ever tells you that a Planing Permit is no big deal laugh in their face it is a big deal and it will take time effort and quite a bit of money.

But if you are going through something similar take a queue from me that I should have known earlier, you need to be a squeaky wheel. If the person says that something will be done on a certain date or in a “couple of days” then make sure you phone them then and find out if it has been done.

Other than that we are now very excited about the prospect of getting on with the building of our house :)