diff --git a/mercurial/commandserver.py b/mercurial/commandserver.py
index 5542bc9125c93e6cf3568d3ab3cecf7fe5963f38_bWVyY3VyaWFsL2NvbW1hbmRzZXJ2ZXIucHk=..9683dfb6f13a1dd1cf8182e743bab8a270394642_bWVyY3VyaWFsL2NvbW1hbmRzZXJ2ZXIucHk= 100644
--- a/mercurial/commandserver.py
+++ b/mercurial/commandserver.py
@@ -320,4 +320,5 @@
         # redirect stdio to null device so that broken extensions or in-process
         # hooks will never cause corruption of channel protocol.
         with procutil.protectedstdio(ui.fin, ui.fout) as (fin, fout):
+            sv = server(ui, self.repo, fin, fout)
             try:
@@ -323,5 +324,4 @@
             try:
-                sv = server(ui, self.repo, fin, fout)
                 return sv.serve()
             finally:
                 sv.cleanup()