Skip to content

Instantly share code, notes, and snippets.

@fakuivan
Last active June 12, 2021 21:27
Show Gist options
  • Save fakuivan/b5c92f91e2ebfd092c2f21146d0755c5 to your computer and use it in GitHub Desktop.
Save fakuivan/b5c92f91e2ebfd092c2f21146d0755c5 to your computer and use it in GitHub Desktop.
Helper script for running VcXsrv from WSL

Helper script for running VcXsrv from WSL

Add it to .bashrc

# Autostart VcXsrv
. <(~/vcxserv_helpers.sh ~/.vcxsrv.port)
#!/usr/bin/env bash
set -euo pipefail
randin () {
local ceil="$1"
local floor="$2"
local interval="$(("$ceil"-"$floor"+1))"
local result="$RANDOM"
let "result %= $interval"
echo "$(($result+$floor))"
}
vcxserv () {
nohup "/mnt/c/Program Files/VcXsrv/vcxsrv.exe" -multiwindow -clipboard -wgl "$1" > /dev/null 2>&1 &
sleep 1
xserver_running "$1"
}
vcxserv_env () {
local port="$1"
echo "export LIBGL_ALWAYS_INDIRECT=1"
echo "export DISPLAY=localhost:${port@Q}.0"
}
xserver_running () {
timeout 1s xset -display "$1" q &>/dev/null
}
error() { echo "$@" 1>&2; }
vcxserv_start () {
local port_file="$1" port
if [[ -r "$port_file" ]] && port="$(cat "$port_file")" && xserver_running ":$port"; then
vcxserv_env "$port";
return 0;
fi
port="$(randin 50000 10000)"
if ! vcxserv ":$port"; then
error "Failed to start server on display :${port}"
return 1
fi
echo "$port" > "$port_file"
vcxserv_env "$port"
}
vcxserv_start "$1"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment