1 /* vim: set syntax=javascript ts=8 sts=8 sw=8 noet: */
   2 
   3 var BINDING = require('./lockfd_binding');
   4 
   5 function
   6 check_arg(pos, name, value, type)
   7 {
   8         if (typeof (value) !== type) {
   9                 throw (new Error('argument #' + pos + ' (' + name +
  10                     ') must be of type ' + type));
  11         }
  12 }
  13 
  14 function
  15 lockfd(fd, callback)
  16 {
  17         check_arg(1, 'fd', fd, 'number');
  18         check_arg(2, 'callback', callback, 'function');
  19 
  20         BINDING.lock_fd(fd, "write", false, function (ret, errno, errmsg) {
  21                 if (ret === -1) {
  22                         var err = new Error('File Locking Error: ' + errmsg);
  23                         err.__errno = errno;
  24 
  25                         callback(err);
  26                         return;
  27                 }
  28 
  29                 callback(null);
  30         });
  31 }
  32 
  33 function
  34 lockfdSync(fd)
  35 {
  36         var cb_fired = false;
  37         var err;
  38 
  39         check_arg(1, 'fd', fd, 'number');
  40 
  41         BINDING.lock_fd(fd, "write", true, function (ret, errno, errmsg) {
  42                 cb_fired = true;
  43 
  44                 if (ret === -1) {
  45                         err = new Error('File Locking Error: ' + errmsg);
  46                         err.__errno = errno;
  47                         return;
  48                 }
  49         });
  50 
  51         if (!cb_fired) {
  52                 throw (new Error('lockfdSync: CALLBACK NOT FIRED'));
  53         } else if (err) {
  54                 throw (err);
  55         }
  56 
  57         return (null);
  58 }
  59 
  60 module.exports = {
  61         lockfd: lockfd,
  62         lockfdSync: lockfdSync
  63 };