{"action":"closed","issue":{"url":"https://api.github.com/repos/mscdex/ssh2/issues/348","labels_url":"https://api.github.com/repos/mscdex/ssh2/issues/348/labels{/name}","comments_url":"https://api.github.com/repos/mscdex/ssh2/issues/348/comments","events_url":"https://api.github.com/repos/mscdex/ssh2/issues/348/events","html_url":"https://github.com/mscdex/ssh2/issues/348","id":114427661,"number":348,"title":"Race condition when using Client.exec()","user":{"login":"thrucker","id":6930612,"avatar_url":"https://avatars.githubusercontent.com/u/6930612?v=3","gravatar_id":"","url":"https://api.github.com/users/thrucker","html_url":"https://github.com/thrucker","followers_url":"https://api.github.com/users/thrucker/followers","following_url":"https://api.github.com/users/thrucker/following{/other_user}","gists_url":"https://api.github.com/users/thrucker/gists{/gist_id}","starred_url":"https://api.github.com/users/thrucker/starred{/owner}{/repo}","subscriptions_url":"https://api.github.com/users/thrucker/subscriptions","organizations_url":"https://api.github.com/users/thrucker/orgs","repos_url":"https://api.github.com/users/thrucker/repos","events_url":"https://api.github.com/users/thrucker/events{/privacy}","received_events_url":"https://api.github.com/users/thrucker/received_events","type":"User","site_admin":false},"labels":[],"state":"closed","locked":false,"assignee":null,"milestone":null,"comments":5,"created_at":"2015-10-31T18:49:55Z","updated_at":"2015-11-02T09:01:26Z","closed_at":"2015-11-02T09:01:26Z","body":"I'm using `Client.exec()` for executing a command and getting its exit code like this\r\n```\r\nclient.exec('some command', function(err, stream) {\r\n  if (err) throw err;\r\n  stream.on('close', function(code, signal) {\r\n    console.log('stream closed, code = ' + code + ', signal = ' + signal);\r\n    client.end();\r\n  });\r\n});\r\n```\r\nThis usually works, but I noticed that sometimes the `close` event is never emitted by the `stream`.\r\n\r\nI further investigated the issue and found that it's a race condition between actually executing the command and registering the event listener on the stream.\r\n\r\nIf you execute a command which runs really fast it may happen that the server already responed with the result before the `close` event listener is registered on the `stream`.\r\n\r\nTo reproduce this you can explicitly delay the registration of the listener like this\r\n```\r\nclient.exec('some command', function(err, stream) {\r\n  if (err) throw err;\r\n  setTimeout(function() {\r\n    stream.on('close', function(code, signal) {\r\n      console.log('stream closed, code = ' + code + ', signal = ' + signal);\r\n      client.end();\r\n    });\r\n  }, 200);\r\n});\r\n```\r\nIf the delay is big enough the event listener never gets called."}}