TLDR: What you want is asnwered here with a nice "not oneshot" type service:
In case you wanna play things, i've do that before found the right answer. It worked sometimes, because it was setup wrong. If you use -bg or any other script that exit inmediately after executed, you'll need that, otherwise just stick to first link to run x11vnc service properly. I've ended using it, works perfect.
Advised: All stuff below just to play with
First of all, you must use service
RemainAfterExit=yes to make the "stop" action to work. I've been struggling untill i got mine working.
To stop the x11vnc server by "display" like you'll do with
vncserver -kill :1 (:1 here means :5901 because vnc uses default 590x ports) you need to use in example
lsof to get pid, then kill it, gracefully or not, you choose -9 option or other of your choice.
If you always use the service (then the same rfbport) with the service, you already know the listening port, so it could be like thit:
ExecStop=/bin/bash -c "/bin/kill -9 `lsof -i:5901 -t`"
Because those params only accepts binarys and doesn't allow pipe, you have to wrap all inside
bash -c "command"
Mine looks like https://gist.github.com/erm3nda/37e5720b4197a7a16c564418d377aac0 and doesnt work at boot, but works if you restart or start manually.
Server will not be killed if you run start again, but restart will do.
If you plan to run several x11servers in different ports, you must add @ to the service name then invoke with the number you want, and modify script to use %i as argument.
Just use x11vnc@NUMBER to start service:
Service filename: x11vnc@.service
Enable it with port 5901:
sudo systemctl enable x11vnc@1
Service ExecStart example: /usr/bin/x11vnc -forever -shared -bg -rfbport 590%i -display :0 -geometry 800x600 -rfbauth /etc/x11vnc.pass -listen 127.0.0$
Service ExecStop example: /bin/sh -c "/bin/kill -9
lsof -i:590%i -t"
sudo service x11vnc@1 start to run under port 5901
Mine looks like https://gist.github.com/erm3nda/fa0bfb8f3737dc6398889adb50fdc84b and doesnt work at boot, but works if you restart it or start manually.