Monday, November 12, 2007

Fun With PERL

I'm pretty proud of myself right now, because I just used PERL to do something cool. In my 360 class (CS 360 - Internet Programming) we're building a web server, and I keep finding new mistakes of mine to fix. It's going well, but there seems to be some kind of limit in Linux to the number of semaphores I'm allowed to create. So when my program dies a few times (without removing the semaphores it created), it won't create semaphores on restart. Up till now, I've been restarting the computer when this happened.

Did some investigating, and I found out that there's a nice little utility, ipcs, that prints out all the IPC (interprocess communication) stuff - message queues, shared memory, and (of course) semaphores. There's another nice little utility, ipcrm, that removes IPC stuff.

I could go through and remove all my semaphores every time, OR I could use my newfound PERL knowledge to make the computer do it for me. Being a geek, I found the second option way cooler.

Anyway, here's my code. Enjoy! (Note that I don't guarantee it on anything. Also, note that it deletes ALL semaphores under your user. So don't run this if anything else you're running is using semaphores. Finally, use this at your own risk!)


#!/usr/bin/perl

open(IPCS, "ipcs|") || die("Couldn't run ipcs.\n");

$startedSems = 0;
while (<IPCS>){
if ($startedSems){
if ($_ =~ /------ Message Queues --------/){
$startedSems = 0;
}
else{
($currkey, $currid, $usr) = split /\s+/;
if ($currid != "" && $usr eq "yourUserNameHere"){
$cmd = "ipcrm -s " . $currid . "|";
open (IPCRM, $cmd);
while (<IPCRM>){
print;
}
close(IPCRM);
print "Removed sem id=$currid\n";
}
}
}
else{
if ($_ =~ /------ Semaphore Arrays --------/){
$startedSems = 1;
}
}
}
close(IPCS);


Oh yeah, two more things. Change yourUserNameHere to your user name. And last of all, either chmod a+x the file to make it executable, or perl it.

No comments: