如何通过systemctl在Linux服务器上稳定运行Prolog Web服务?
Hey, let's break down why your Prolog service stops right after starting and fix it up.
Looking at your service status output, these two lines tell the whole story:
Dec 27 23:25:41 LinuxVM bash[112275]: % Started server at http://localhost:8000/ Dec 27 23:25:41 LinuxVM bash[112275]: % halt
SWI-Prolog successfully spins up your HTTP server, but then immediately runs the halt command and exits the process. By default, SWI-Prolog terminates once it finishes executing the startup goal you passed (server(8000).). Since your systemd service uses Type=simple, it interprets the process exit as the service completing its job, so it marks the service as inactive (dead).
Fixes to Try (Pick One)
1. Modify the Startup Script to Keep Prolog Running
Update your prolog_init.sh to add the -t interactive flag. This tells SWI-Prolog to enter interactive mode after starting the server, which keeps the process alive instead of halting:
swipl -s /home/username/prolog.pl -g "server(8000)." -t interactive
2. Adjust Your Prolog Code to Block After Startup
Edit your prolog.pl file to add a blocking call in the server/1 predicate. This makes the process wait indefinitely after starting the server, preventing it from exiting:
server(Port) :- http_server(http_dispatch, [port(Port)]), thread_get_message(_). % Waits for a never-arriving message to keep the process running
3. Optimize the Systemd Service (Optional, Pair with Above Fixes)
To make your service more robust, tweak the prolog.service file:
- Run the service as your user instead of root (safer)
- Set the working directory to your Prolog file's location
- Add an automatic restart policy to handle unexpected crashes
Here's the updated service file:
[Unit] Description=Prolog Service [Service] Type=simple User=username # Replace with your actual username WorkingDirectory=/home/username ExecStart=/bin/bash /home/username/prolog_init.sh Restart=always # Auto-restart if the service crashes [Install] WantedBy=multi-user.target
Verify the Fix
After making your changes, reload systemd and restart the service:
sudo systemctl daemon-reload sudo systemctl restart prolog
Check the status to confirm it's running:
sudo systemctl status prolog
You should see Active: active (running) if everything works correctly.
内容的提问来源于stack exchange,提问作者H. Soares

