Use launchd to start VMware's VM on VNC connection I have a VM (VMware Fusion) with enabled VNC access. I want to be able to access it from the network. Unfortunately, VMware requires VM to be running to be able to accept VNC connections and vmware-vmx is the process that listens on VNC port.

My idea was to have launchd job that will run desired VM when something comes to the port.
I've ended up with the following launchd job:

&lt;?xml version="1.0" encoding="UTF-8"?&gt;
&lt;!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"&gt;
&lt;plist version="1.0"&gt;
&lt;dict&gt;
    &lt;key&gt;Label&lt;/key&gt;
    &lt;string&gt;com.kulakov.vm.development&lt;/string&gt;
    &lt;key&gt;ProgramArguments&lt;/key&gt;
    &lt;array&gt;
        &lt;string&gt;/usr/local/bin/vmw&lt;/string&gt;
        &lt;string&gt; &lt;/string&gt;
    &lt;/array&gt;
    &lt;key&gt;StandardOutPath&lt;/key&gt;
    &lt;string&gt;/Users/kentzo/Desktop/com.kulakov.vm.development.log&lt;/string&gt;
    &lt;key&gt;StandardErrorPath&lt;/key&gt;
    &lt;string&gt;/Users/kentzo/Desktop/com.kulakov.vm.development.log&lt;/string&gt;
    &lt;key&gt;Sockets&lt;/key&gt;
    &lt;dict&gt;
        &lt;key&gt;NetworkListener&lt;/key&gt;
        &lt;dict&gt;
            &lt;key&gt;SockServiceName&lt;/key&gt;
            &lt;string&gt;5906&lt;/string&gt;
            &lt;key&gt;SockType&lt;/key&gt;
            &lt;string&gt;stream&lt;/string&gt;
        &lt;/dict&gt;
    &lt;/dict&gt;
    &lt;key&gt;Debug&lt;/key&gt;
    &lt;true/&gt;
&lt;/dict&gt;
&lt;/plist&gt;


/usr/local/bin/vmw:

#!/bin/bash
/Applications/VMware\ Fusion.app/Contents/Library/vmrun -T fusion start "$1" nogui


The problem is that launchd listens on the port and I have to stop this before I can run VM. The only way to stop it to listen on the port I've found so far is to unload the job. Unfortunately it also stops the job itself and prevents VM from launching.

Is it possible to somehow tell launchd to stop listening on a port within the daemon?
Your problem here is that if launchd is going to listen on the VNC port, well, then it's going to get the traffic on the VNC port.  The approved ways for a daemon program to deal with this are either to expect the network traffic on StdIn and StdOut or to collect a list of file descriptors from launchd and use one of those for the network communication.  Otherwise the client is going to create a connection and then see the connection closed by launchd while it starts up the daemon. 

I suggest you have launchd listen on another port and spawn a simple program that just pipes input to /dev/null while also launching the VM.  So then to start the VM you telnet to this special port. 

Or, you know, the easy thing to do is just always have the VM running. :-)