The issue you're experiencing where the script works when run manually but fails with a bad_alloc error when run as a service is likely related to environment differences or resource limits. Here are several approaches to diagnose and fix the problem:
1. Check Service Environment
Services run with a minimal environment. Your script relies on .bashrc and setup.bash, which may not be fully available in the service context.
Solution:
- Explicitly set all required environment variables in the service file or script.
- Use absolute paths for all files and dependencies.
2. Increase Memory Limits
A bad_alloc error suggests the process is running out of memory. Services often have stricter resource limits.
Solution:
3. Debug the Service
To see what's happening when the service runs, add logging or run it interactively.
Solution:
4. Use systemd Properly
If you're using systemd, create a proper service file instead of a script.
Example Service File (/etc/systemd/system/tts_node.service):
[Unit]
Description=TTS Node Service
After=network.target
[Service]
Type=simple
User=unitree
Group=unitree
WorkingDirectory=/home/unitree/gto_audio/src/sound_ros2/sound_ros2
Environment="PYTHONUNBUFFERED=1"
EnvironmentFile=/home/unitree/gto_audio/install/setup.bash
ExecStart=/usr/bin/python /home/unitree/gto_audio/src/sound_ros2/sound_ros2/tts_node.py
Restart=on-failure
RestartSec=5s
[Install]
WantedBy=multi-user.target
Steps:
- Create the service file.
- Reload
systemd:
sudo systemctl daemon-reload
- Start the service:
sudo systemctl start tts_node
- Enable it to start on boot:
sudo systemctl enable tts_node
5. Check for Missing Dependencies
The service might not have access to the same libraries or environment as your user.
Solution:
6. Run as the Correct User
The service might be running as root or another user with different permissions.
Solution:
- Specify the user in the service file (as shown above).
7. Test with Minimal Environment
Run the script with a minimal environment to simulate the service:
env -i /usr/bin/python "$SOURCES_DIR/tts_node.py"
This will help identify missing environment variables.
8. Check for Resource Leaks
If the script works briefly but then fails, there might be a memory leak.
Solution:
- Profile the script with
memory_profiler or valgrind to check for leaks.
Final Notes
By following these steps, you should be able to identify and fix the issue.