Search code examples
node.jssocketsunixipcunix-socket

EADDRINUSE error if I force kill the process and then try to re-launch it


var arDrone = require('ar-drone');
var PaVEParser = require('./PaVEParser');
var output = require('fs').createWriteStream('./vid.h264');
var client;
var mostRecentFrame;
var frameCounter = 0;

const net = require('net');
const server = net.createServer((c) => {
  // 'connection' listener
  console.log('client connected');
  c.on('end', () => {
    console.log('client disconnected');
  });
    c.on('data', (data) => {
    c.write(mostRecentFrame);
    });
});
server.on('error', (err) => {
  throw err;
});
server.listen('/tmp/ard.sock', () => {
  console.log('server bound');
});

process.stdin.on('data', function() {
    console.log("Ending the program, landing the drone and terminating the connection.");
    server.close();
    process.exit();
});

When I force-kill this program, I cannot re-launch it.

daniel@beepboop:~/AR-drone Project$ node test-save-pngs-no-flight.js 
/home/daniel/AR-drone Project/test-save-pngs-no-flight.js:24
  throw err;
  ^

Error: listen EADDRINUSE /tmp/ard.sock
    at Object.exports._errnoException (util.js:1036:11)
    at exports._exceptionWithHostPort (util.js:1059:20)
    at Server._listen2 (net.js:1239:19)
    at listen (net.js:1288:10)
    at Server.listen (net.js:1377:5)
    at Object.<anonymous> (/home/daniel/AR-drone Project/test-save-pngs-no-flight.js:26:8)
    at Module._compile (module.js:556:32)
    at Object.Module._extensions..js (module.js:565:10)
    at Module.load (module.js:473:32)
    at tryModuleLoad (module.js:432:12)

I believe this is because the socket wasn't closed correctly.

  1. How can I make the program close the socket when I force kill it, and
  2. How can I manually close the socket afterwards from the command line?

Edit:

I am using Ubuntu 16.04. By force kill, I mean that I am hitting "control-C" during runtime.


Solution

  • Yes, this is how it works. This is a shorter example to reproduce it:

    var net = require('net');
    const server = net.createServer((c) => {
    });
    server.on('error', (err) => {
      throw err;
    });
    server.listen('/tmp/x.sock', () => {
      console.log('server bound');
    });
    

    You can avoid that problem by running:

    server.close();
    

    before the program exits.

    In your case you can avoid that problem by handling the SIGINT:

    var net = require('net');
    const server = net.createServer((c) => {
    });
    server.on('error', (err) => {
      throw err;
    });
    server.listen('/tmp/x.sock', () => {
      console.log('server bound');
    });
    process.on('SIGINT', () => {
      server.close();
      process.exit();
    });
    

    See also: