Thanks for your suggestions. For the usage "qemu-nbd -f disk.img", adding some code could implement it. I think it could be like "losetup -f" usage. #qemu-nbd -f show the first free nbd device at this moment. user can choose to issue "qemu-nbd -c THAT_DEVICE disk.img" or not. #qemu-nbd -f disk.img find a free nbd device and connect disk.img to that device.
How do you think? For the race conditions caused by executing multiple qemu-nbd -f at the same time, I've tried both ways (1. lock; 2. if one device not work, trying other devices until one works). In my testing, the 2nd way has problem. When issuing "qemu-nbd -c /dev/nbd0 disk.img -v" and "qemu-nbd -c /dev/nbd0 disk1.img -v" at the same time, the latter one will eventually exit with EXIT_FAILURE, but the first one cannot work normally as well, it cannot show disk partitions. Executing multiple "qemu-nbd -f" has same problem. So, it seems using lock from a earlier time is more proper. In my testing, I'm using file lock (fcntl). For "qemu-nbd -c" case, if lock failed, qemu-nbd exits directly. For "qemu-nbd -f" case, if lock failed, redo find_free_nbd_device (there might be updates) and then try to connectdisk.img to the new free device. Will post V2 soon. >>> Ian Campbell <ian.campb...@citrix.com> 11/17/2011 1:23 AM >>> On Wed, 2011-11-16 at 10:34 +0000, Stefan Hajnoczi wrote: > On Wed, Nov 16, 2011 at 6:57 AM, Chunyan Liu <cy...@suse.com> wrote: > > Currently qemu-nbd does not support finding free nbd device for users like > > "losetup -f" and issuing "qemu-nbd -c /dev/nbdX disk.img" won't report error > > message when /dev/nbd is already in use. It makes things a little confusing. > > This patch adds "-f" option to qemu-nbd to support finding a free nbd device > > for users. Please review and share your comments. Thanks. > > > > Signed-off-by: Chunyan Liu <cy...@suse.com> > > --- > > qemu-nbd.c | 65 > > +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++- > > 1 files changed, 64 insertions(+), 1 deletions(-) > > This patch finds a free device but does not immediately attach to it > and use it. Interfaces like this are prone to race conditions, I > think it would make more sense to combine the -f option with running > the actual NBD server. > > I suggest: > qemu-nbd -f disk.img > > That way it is safe to execute multiple qemu-nbd -f at the same time > without race conditions. I agree, but you'd also need some locking inside qemu-nbd wouldn't you? Or have it just keep trying devices until one works perhaps. > Plus it probably makes the user's life > easier than having to say qemu-nbd -c $(qemu-nbd -f) disk.img. Absolutely. Ian.