From b87071d747fec80cdee7722a8bf57cf874725909 Mon Sep 17 00:00:00 2001 From: yoe Date: Mon, 31 Mar 2008 08:18:51 +0000 Subject: [PATCH] r331: Add code to detect whether a device is connected --- nbd-client.8.sgml | 20 ++++++++++++++++++++ nbd-client.c | 26 ++++++++++++++++++++++++++ 2 files changed, 46 insertions(+) diff --git a/nbd-client.8.sgml b/nbd-client.8.sgml index 25c23af..8d2f5d0 100644 --- a/nbd-client.8.sgml +++ b/nbd-client.8.sgml @@ -68,6 +68,10 @@ manpage.1: manpage.sgml &dhpackage; + + &dhpackage; + + DESCRIPTION @@ -128,6 +132,22 @@ manpage.1: manpage.sgml + -c + + Check whether the specified nbd device is + connected. + If the device is connected, &dhpackage; will exit + with an exit state of 0 and print the PID of the &dhpackage; + instance that connected it to stdout. + If the device is not + connected or does not exist (for example because the nbd + module was not loaded), &dhpackage; will exit with an exit + state of 1 and not print anything on stdout. + If an error occurred, &dhpackage; will exit with an exit + state of 2, and not print anything on stdout either. + + + -d Disconnect the specified nbd device from the diff --git a/nbd-client.c b/nbd-client.c index 51927b1..4e4777b 100644 --- a/nbd-client.c +++ b/nbd-client.c @@ -28,6 +28,7 @@ #include #include #include +#include #ifndef __GNUC__ #error I need GCC to work @@ -37,6 +38,27 @@ #define MY_NAME "nbd_client" #include "cliserv.h" +int check_conn(char* devname) { + char buf[256]; + int fd; + int len; + if(!strncmp(devname, "/dev/", 5)) { + devname+=5; + } + snprintf(buf, 256, "/sys/block/%s/pid", devname); + if((fd=open(buf, O_RDONLY))<0) { + if(errno==ENOENT) { + return 1; + } else { + return 2; + } + } + len=read(fd, buf, 256); + buf[len-1]='\0'; + printf("%s\n", buf); + return 0; +} + int opennet(char *name, int port, int sdp) { int sock; struct sockaddr_in xaddrin; @@ -191,6 +213,7 @@ int main(int argc, char *argv[]) { fprintf(stderr, "nbd-client version %s\n", PACKAGE_VERSION); fprintf(stderr, "Usage: nbd-client [bs=blocksize] [timeout=sec] host port nbd_device [-swap] [-persist]\n"); fprintf(stderr, "Or : nbd-client -d nbd_device\n"); + fprintf(stderr, "Or : nbd-client -c nbd_device\n"); fprintf(stderr, "Default value for blocksize is 1024 (recommended for ethernet)\n"); fprintf(stderr, "Allowed values for blocksize are 512,1024,2048,4096\n"); /* will be checked in kernel :) */ fprintf(stderr, "Note, that kernel 2.4.2 and older ones do not work correctly with\n"); @@ -221,6 +244,9 @@ int main(int argc, char *argv[]) { printf("done\n"); return 0; } + if(strcmp(argv[0], "-c")==0) { + return check_conn(argv[1]); + } if (strncmp(argv[0], "bs=", 3)==0) { blocksize=atoi(argv[0]+3); -- 1.7.10.4