I have a bash script which runs as a cronjob. This script runs several commands and one of them is the following virsh command:
/usr/bin/virsh list --all
When I run this script in the terminal (as root) or as a cronjob (as root also) the virsh command works as expected and lists all the virtual machines.
During my testing and debugging of this script, I noticed that if I send the script to the background or if I send it to the background and then disown it, the script hangs indefinitely at the virsh command. Below I provide some more details.
To illustrate the issue, let's assume a simple script "test.bash":
[root@kvm-host]# cat test.bash
#!/bin/bash
/usr/bin/virsh list --all
When I run the script test.bash in the foreground it works as expected:
[root@kvm-host]# bash -x test.bash
+ /usr/bin/virsh list --all
Id Name State
----------------------------------------
27 slave1 running
29 ubuntu_discourse running
30 osticket running
31 lubuntu_desktop running
- slave2 shut off
When I run the script test.bash in the background it hangs indefinitely at the virsh command:
[root@kvm-host]# bash test.bash 2>stderr &
[1] 1119722
[root@kvm-host]# ps aux | grep virsh | grep -v grep
root 1119723 0.0 0.0 442660 16012 pts/4 Tl 17:07 0:00 /usr/bin/virsh list --all
[1]+ Stopped bash test.bash 2> stderr
If I send the script to the background and disown it, the script also hangs at the virsh command:
[root@kvm-host]# bash -x test.bash 2>stderr & disown
[1] 1119502
[root@kvm-host]# ps aux | grep virsh | grep -v grep
root 1119503 0.0 0.0 442656 15956 pts/4 Tl 17:05 0:00 /usr/bin/virsh list --all
I have tried running the virsh command with -c qemu:///system and the behaviour is the same when I send the script test.bash to the background. As you can see above, I have also tried running the script without "bash -x". I have also tried running the script redirecting both stderr and stdout to /dev/null. Finally, I have also tried running the script without redirecting stderr or stdout to any file. The issue is the same in all these cases.
Is it possible to run the virsh command in the background as described? Any comments would be highly appreciated. Thank you!
Here are some details about my system:
[root@kvm-host]# cat /etc/redhat-release
Rocky Linux release 8.6 (Green Obsidian)
[root@kvm-host]# virsh -V
Virsh command line tool of libvirt 8.0.0
See web site at https://libvirt.org/
Compiled with support for:
Hypervisors: QEMU/KVM ESX Test
Networking: Remote Network Bridging Interface netcf Nwfilter
Storage: Dir Disk Filesystem SCSI Multipath iSCSI LVM RBD Gluster
Miscellaneous: Daemon Nodedev SELinux Secrets Debug DTrace Readline