title: C++ Ubuntu not releasing lock on lock file when terminated
body: <p>I have a C++ script, which checks whether any action has to be done and if so it starts the right processor C++ script. However, since it runs every x minutes it also checks whether the processor isn't still running using lock files.</p>
  
  <p>I use the following function to acquire the lock:</p>
  
  <pre><code>int LockFile(string FileNameToLock) {
      FileNameToLock += ".lock";
      int fd = open(FileNameToLock.c_str(), O_RDWR | O_CREAT, 0666);
      int rc = flock(fd, LOCK_EX | LOCK_NB);
      if (rc || rc == -1) {
          cout &lt;&lt; errno &lt;&lt; endl;
          cout &lt;&lt; strerror(errno) &lt;&lt; endl;
          return -1;
          }
      return fd;
      }
  </code></pre>
  
  <p>The code that is being executed:</p>
  
  <pre><code>[...]
  if (LockFile(ExecuteFileName, Extra) == -1) {
      cout &lt;&lt; "Already running!" &lt;&lt; endl; //MAIN IS ALREADY RUNNING
      //RETURNS ME Resource temporarily unavailable when processor is running from an earlier run
      exit(EXIT_SUCCESS);
      }
  if (StartProcessor) { //PSEUDO
      int LockFileProcessor = LockFile("Processor");
      if (LockFileProcessor != -1) {
          string Command = "nohup setsid ./Processor"; //NOHUP CREATES ZOMBIE?
          Command += IntToString(result-&gt;getInt("Klantnummer"));
          Command += " &gt; /dev/null 2&gt;&amp;1 &amp;"; //DISCARD OUTPUT
          system(Command.c_str());
          //STARTS PROCESSOR (AS ZOMBIE?)
          }
      }
  </code></pre>
  
  <p>The <strong><em>first run works well</em></strong>, however when the main script runs <strong><em>again</em></strong>, the lock file returns -1, which means an error occurred (only when the processor is still running). The errno is 11 which results in the error message: <code>Resource temporarily unavailable</code>. <strong><em>Note that this only happens when the (zombie) processor is still running. (However, the main script has already terminated, which should close the file handle?)</em></strong></p>
  
  <p>For some reason, the zombie keeps the file handle to the lock file of the main script open???</p>
  
  <p>I have no idea where to look for this problem.</p>
  
  <p><strong>SOLVED:</strong>
  see my answer</p>