2

I have some routines which make several writes to a stdio stream to make a single log message. To keep each message separate, even in multi-threaded applications, I bracket each message with calls to flockfile() and funlockfile(). In my unit tests, I would like to check that the lock hasn't been left dangling, but how can I tell?

I thought of doing a ftrylockfile(), but the lock is recursive, it will just succeed if I do it from the same thread as the initial flockfile(). There is a lock count under the hood, but I see no way read it, or check its zeroness.

3
  • One solution is to start programming in C++ and use RAII :-)
    – Praetorian
    Jul 21, 2011 at 20:33
  • C++ is no fun no more, that's why I switched to C. I'm all for RAII, but that still doesn't help the unit tests. To quote the Gospel of Knuth: ``Beware of bugs in the above code; I have only proved it correct, not tried it.'' Jul 21, 2011 at 21:01
  • RAII does help because it's something you don't need to unit test any more. Stack unwinding guarantees that the destructor is called which in turn calls funlockfile() for every instance that that object's constructor called flockfile(). But, anyway, I was only making a joke. Don't have an answer to your question.
    – Praetorian
    Jul 21, 2011 at 21:04

1 Answer 1

3

Since you are doing this in a unit test, mock flockfile() and funlockfile(). In your mocks you can keep track of the count and verify it is zero when you complete.

2
  • Thanks for that - it is isn't prefect, since there's no nice way to attach separate a count to each output stream. But that should be fine. Jul 22, 2011 at 4:48
  • 1
    @Adrian - If you also mock fopen(), you can return a FILE* that contains a lock count and increment/decrement the count for each file in your flockfile mocks. Or you can maintain a list of all of the FILE* objects you've seen in your mocks with separate counters attached to each. Or you can just keep a single global count but log each lock and unlock so that, in case of failure (i.e. nonzero count at the end), you can more easily figure out where the missing unlock should do.
    – bstpierre
    Jul 22, 2011 at 11:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.