Posts Tagged ‘programming’

Threads and fork()

Thursday, November 15th, 2007

Combining POSIX threads and the fork() system call can be a bit messy. Here’s some facts you may not be aware of:

  1. A fork() call only clones the current thread
  2. This can have unintentional effects

The most noticable effect of this, for aspiring thread users, is that it’s unsafe to start any threads before doing the daemonization double fork().

A less obvious problem, though, is that any locks that are held by threads other than the current thread will remain in a locked state within the child’s context until the heat death of the universe. In situations where there are global background objects that keep locks, this means that doing much beyond an exec() is unsafe and, if that exec() fails, it is unsafe to call exit() if any global destructors touch locks. Use _exit() instead.

String Formatting in Grace

Thursday, September 13th, 2007

There are many places where programs written using grace seem to be syntactically closer to languages like Python than to C. String formatting used to be not one of these places. Historically, formatting text with dynamic elements within grace was a matter of using either string::printf() or file::printf(). These are C-style printf formatters, which means they accept a variable argument list consisting of a ‘format string’ and one or more integer or pointer arguments. When dealing with value and string objects, this means liberally using explicit casts like cval() and ival() to convert those to printf-compatible types.

The library version inside the repository now supports a friendlier way of going about things, one that does away with all the explicit casting in the form of the %format pseudo-keyword. In its most simple incarnation, it works mostly the same as a normal printf formatting operation, except that it can deal with any objects that can be cast to value:

  string test = “%i bottles of %s” %format (99, “beer”);

One level up on the funky scale is referring to positioned arguments:

  fout.writeln (”<%s>%s</%{0}s>” %format (”str”,”foo”));

Finally, you can access children of the first argument like this:

  value v;
  v["name"] = “John Smith”;
  v["email"] = “j.smith@example.net”;
 
  fout.writeln (”%[name]s <%[email]s>” %format (v));

This way of formatting, apart from being more flexible and less sensitive to formatting-related security problems (since it doesn’t need to follow arbitrary pointers), adds a lot of clarity to your source code, which is a major plus for keeping up maintainable code.