title: Getting all open files for process results in errno 12 = Out of Memory
body: <p>With the help of SO, I wrote an app that displays all open TCP/UDP connections in Swift.
  In the next step, I would like to get the process that opened the connection (pretty much as lsof does).</p>
  
  <p>Since lsof is open source, I could write the following code to get all the open files for a process:</p>
  
  <p>Bridging-Header:</p>
  
  <pre><code>#include &lt;mach/mach_types.h&gt;
  #include &lt;mach/vm_param.h&gt;
  #include &lt;mach/host_info.h&gt;
  #include &lt;mach/task_info.h&gt;
  #include &lt;mach/thread_info.h&gt;
  #include &lt;mach/vm_region.h&gt;
  #include &lt;libproc.h&gt;
  
  #include &lt;sys/proc_info.h&gt;
  #include &lt;sys/kdebug.h&gt;
  #include &lt;sys/msgbuf.h&gt;
  </code></pre>
  
  <p>(I don't think every include is needed, but at least it compiles for now).</p>
  
  <pre><code>for app in NSWorkspace.shared().runningApplications
      {
          let pid = app.processIdentifier
  
          var tai = proc_taskallinfo()
          let size = MemoryLayout&lt;proc_bsdinfo&gt;.size
          var result = proc_pidinfo(pid, PROC_PIDTASKALLINFO, 0, &amp;tai, Int32(size))
          let fileCount: Int32 = Int32(tai.pbsd.pbi_nfiles)
  
          if result &lt;= 0
          {
              if errno == ENOMEM
              {
                  Swift.print("Out of memory.")
              }
              Swift.print(errno)
              continue
          }
  
          var fid = proc_fdinfo()
          let fdInfoSize = MemoryLayout&lt;proc_fdinfo&gt;.size
          result = proc_pidinfo(pid, PROC_PIDLISTFDS, 0, &amp;fid, Int32(fdInfoSize) * fileCount)
  
          if result &lt;= 0
          {
              Swift.print("Error. No Files?")
          }
          else
          {
              Swift.print("Files found.")
          }
      }
  </code></pre>
  
  <p>The code was ported from C to Swift 3. The original C code looks like this:</p>
  
  <pre><code>int nb;
  struct proc_taskallinfo tai;
  ...  
  nb = proc_pidinfo(pid, PROC_PIDTASKALLINFO, 0, &amp;tai, sizeof(tai));
  </code></pre>
  
  <p>When I run my code, I get the errno 12 (Out of memory). Why?</p>
  
  <p>P.S. I know that the second proc_pidinfo will also fail because a pointer to an array of proc_fdinfo is returned and not a pointer to a single struct, but one step at a time. It's all about the errno 12.</p>