示例#1
0
int main(int argc, char *argv[])
{
  struct usb_bus *bus;

  if (argc > 1 && !strcmp(argv[1], "-v"))
    verbose = 1;

  usb_init();

  usb_find_busses();
  usb_find_devices();

  for (bus = usb_busses; bus; bus = bus->next) {
    if (bus->root_dev && !verbose)
      print_device(bus->root_dev, 0);
    else {
      struct usb_device *dev;

      for (dev = bus->devices; dev; dev = dev->next)
        print_device(dev, 0);
    }
  }

  return 0;
}
示例#2
0
static int test_get_device_data(void)
{
	int ret;
	openusb_dev_data_t *devdata;
	unsigned int i, j;

	for(j=0;j<busnum;j++) {
		ret = openusb_get_devids_by_bus(libhandle, bus[j], &devids,
				&devnum);
		if(ret < 0) {
			printf("Error get devids by bus: %s\n",
					openusb_strerror(ret));
			return -1;
		}
		for(i=0;i<devnum;i++) {
			print_device(devids[i], 4);

			ret = openusb_get_device_data(libhandle, devids[i], 0,
					&devdata);
			if (ret < 0) {
				printf("Get device(%d) data error: %s\n", i,
						openusb_strerror(ret));
			}
			else
			{
				dump_dev_data(devdata);

				openusb_free_device_data(devdata);
			}
		}
		openusb_free_devid_list(devids);
	}
	
	return 0;
}
示例#3
0
/* debugging (non-protocol) routine to send a ping message to the
 * device_list[] element indexed by the int in "buf"
 */
void send_ping(char *buf)
{
    int device_index;
    int msg_len;
    message_t message;
    int result;

    memset(&message, 0, sizeof(message));

    result = sscanf(buf, "%d", &device_index);
    if (result != 1) {
        ddprintf("send_ping; no device index in '%s'\n", buf);
        return;
    }
    if (device_index < 0 || device_index >= device_list_count) {
        ddprintf("send_ping; device index '%d' out of range\n", device_index);
        return;
    }

    message.message_type = ping_msg;
    msg_len = ((byte *) &message.message_type)
            + sizeof(message.message_type)
            - ((byte *) &message);

    ddprintf("pinging device_list[%d]:  ", device_index);
    print_device(eprintf, stderr, &device_list[device_index]);
    sendum((byte *) &message, msg_len, &device_list[device_index]);

} /* send_ping */
示例#4
0
int main(int argc, char *argv[])
{
	libusb_device **devs;
	ssize_t cnt;
	int r, i;

	if (argc > 1 && !strcmp(argv[1], "-v"))
		verbose = 1;

	r = libusb_init(NULL);
	if (r < 0)
		return r;

	cnt = libusb_get_device_list(NULL, &devs);
	if (cnt < 0)
		return (int)cnt;

	for (i = 0; devs[i]; ++i) {
		print_device(devs[i], 0);
	}

	libusb_free_device_list(devs, 1);

	libusb_exit(NULL);
	return 0;
}
示例#5
0
void new_discovery() {
    struct ifaddrs *addrs,*ifa;
    getifaddrs(&addrs);
    ifa = addrs;
    while (ifa) {
        g_main_context_iteration(NULL, 0);
        if (ifa->ifa_addr && ifa->ifa_addr->sa_family == AF_INET) {
            if((ifa->ifa_flags&IFF_UP)==IFF_UP
                && (ifa->ifa_flags&IFF_RUNNING)==IFF_RUNNING
                && (ifa->ifa_flags&IFF_LOOPBACK)!=IFF_LOOPBACK) {
                new_discover(ifa);
            }
        }
        ifa = ifa->ifa_next;
    }
    freeifaddrs(addrs);

    
    fprintf(stderr, "new_discovery found %d devices\n",devices);
    
    int i;
    for(i=0;i<devices;i++) {
        print_device(i);
    }
}
示例#6
0
文件: dial.c 项目: SrsBusiness/ccast
int discovery_search_result(struct Upnp_Discovery *event) {
    if (event->ErrCode != UPNP_E_SUCCESS) {
        fprintf(stderr, "Error in discovering device\n");
        exit(-1);
    }

    IXML_Document *desc = NULL;
    int ret = UpnpDownloadXmlDoc(event->Location, &desc);
    
    if (ret != UPNP_E_SUCCESS) {
        fprintf(stderr, "Error in obtaining device description\n");
        exit(-1);
    }
    
    const char *UUID = get_device_property(desc, "UDN");

    if (!list_contains(&devices, UUID, chromecast_matches_UUID)) {
        struct chromecast_device *device = malloc(sizeof(struct chromecast_device));
        device->addr = ((struct sockaddr_in *)&event->DestAddr)->sin_addr;     
        device->device_name = create_string_copy(get_device_property(desc, "friendlyName"));
        device->device_type = create_string_copy(get_device_property(desc, "deviceType"));
        device->device_UUID = create_string_copy(UUID);
        device->device_OS = create_string_copy(event->Os);
        device->device_manufacturer = create_string_copy(get_device_property(desc, "manufacturer"));
        device->device_model_name = create_string_copy(get_device_property(desc, "modelName"));
        device->service_type = create_string_copy(get_device_property(desc, "serviceType"));
        device->service_version = create_string_copy(event->ServiceVer);
        device->service_id = create_string_copy(get_device_property(desc, "serviceId"));
        list_add_sync(&devices, device);
        print_device(device);
    }
    ixmlDocument_free(desc);
    return 0;
}
示例#7
0
文件: print.c 项目: chenggongtc/myls
void
print_long(OBJ *obj)
{
	struct stat *st;
	FTSENT      *p;
	char        mode[MODE_BUFF_SIZE];

	p = obj->obj_list;

	if(!obj->obj_isroot)
		print_total(obj->obj_size_total);

	while (p != NULL) {
		if (p->fts_number == FTS_NO_PRINT) {
			p = p->fts_link;
			continue;
		}

		st = p->fts_statp;

		/* print inode */
		if (f_ino)
			printf("%*"PRIuMAX" ", obj->obj_ino_max,
				(uintmax_t)st->st_ino);

		/* print number of blocks */
		if (f_block) {	
			print_block((int64_t)st->st_blocks * DEFAULT_BSIZE, 
				    obj->obj_block_max);
		}
		
		/* print mode */
		strmode(st->st_mode, mode);
		printf("%11s ", mode);

		/* print number of links */
		printf("%*"PRIuMAX" ", obj->obj_link_max, 
			(uintmax_t)st->st_nlink);

		/* print owner and group */
		print_user_and_group(st->st_uid, st->st_gid, 
				      obj->obj_user_max, obj->obj_group_max);

		/* print size */
		if (S_ISCHR(st->st_mode) || S_ISBLK(st->st_mode))
			print_device(st->st_rdev, obj->obj_major_max,
					obj->obj_minor_max);
		else
			print_size(st->st_size, obj->obj_size_max);

		print_date(st);
		print_name(p, WITH_LINK);

		putchar('\n');

		p = p->fts_link;
	}
}
示例#8
0
/* print information about all local interfaces (eth0 etc.) that we have open.
 */
void print_devices(void)
{
    int i;

    ddprintf("print_devices:\n");

    for (i = 0; i < device_list_count; i++) {
        // ddprintf("    %d:  ", i);
        ddprintf("    ");
        print_device(eprintf, stderr, &device_list[i]);
    }
}
示例#9
0
文件: main.c 项目: llmike/v4l2-tools
static CResult
list_devices ()
{
	CResult ret;
	unsigned int req_size = 0, buffer_size = 0, count = 0;
	CDevice *devices = NULL;
	int i;

	printf("Listing available devices:\n");

	do {
		// Allocate the required memory
		if(devices) free(devices);
		if(req_size) {		// No allocation the first time
			devices = (CDevice *)malloc(req_size);
			if(devices == NULL)
				return C_NO_MEMORY;
			buffer_size = req_size;
		}

		// Try to enumerate. If the buffer is not large enough, the required
		// size is returned.
		ret = c_enum_devices(devices, &req_size, &count);
		if(ret != C_SUCCESS && ret != C_BUFFER_TOO_SMALL)
			goto done;
	}
	while(buffer_size < req_size);

	if(count == 0) {
		printf("No devices found.\n");
		goto done;
	}

	// Print a list of all available devices
	for(i = 0; i < count; i++) {
		CDevice *device = &devices[i];
		print_device(device);

		ret = list_entities(device);
		if(ret != C_SUCCESS && ret != C_INVALID_ARG) {
			print_error("Unable to list device entities", ret);
			ret = C_SUCCESS;
		}
	}

done:
	if(devices) free(devices);
	if(ret)
		print_error("Unable to retrieve device list", ret);
	return ret;
}
示例#10
0
/* using the fd and if_index from device, send the message.
 * this is a low-level routine used only to send non-cloud messages.
 * but, it is called to send packets out of the cloud (eth or wlan ap)
 * and also to pass them along within the cloud.
 */
int sendum(byte *message, int msg_len, device_t *device)
{
    struct sockaddr_ll send_arg;
    int result;

    // noncloud_message_count++;

    if (db[25].d || db[26].d) { short_print_io_stats(eprintf, stderr); }

    check_msg_count();

    if (db[15].d) {
        // DEBUG_SPARSE_PRINT(
            ddprintf("sending payload message ");
            fn_print_message(eprintf, stderr,
                    (unsigned char *) message, msg_len);
        // )
    }

    if (db[14].d && is_wlan(device)) {
        ddprintf("sendum..\n");
    }
    if (use_pipes) {
        result = pio_write(&device->out_pio, message, msg_len);
        if (db[14].d && is_wlan(device)) {
            ddprintf("sendum; ");
            pio_print(stderr, &device->out_pio);
        }
    } else {
        memset(&send_arg, 0, sizeof(send_arg));
        send_arg.sll_family = AF_PACKET;
        send_arg.sll_halen = 6;
        memset(send_arg.sll_addr, 0, sizeof(send_arg.sll_addr));

        send_arg.sll_ifindex = device->if_index;

        if (db[1].d) { ddprintf("do the sendto..\n"); }
        block_timer_interrupts(SIG_BLOCK);
        result = sendto(device->fd, message, msg_len, 0,
                (struct sockaddr *) &send_arg, sizeof(send_arg));
        block_timer_interrupts(SIG_UNBLOCK);
        if (db[1].d) { ddprintf("sendto result:  %d\n", result); }
    }
    if (db[1].d) {
        DEBUG_SPARSE_PRINT(
            ddprintf("sending to ");
            print_device(eprintf, stderr, device);
        )
    }
示例#11
0
int main() {
  
  cudaDeviceReset();
  cudaDeviceSynchronize();
  
  // print device properties
  print_device();
    
  // create pointers to data
  const uint64_t size = N;
  DataArray* data_arr_ptr = (DataArray*) malloc((size_t) sizeof(DataArray)); // change to global variable <- easier to code
  
  // allocate memory for array of streams
  const uint8_t num_streams = 2; // rewrite on defines?
  streams_arr = (cudaStream_t*) malloc( (size_t) sizeof(cudaStream_t)*num_streams);
  
  // create threads
  const uint8_t num_threads = 2;
  printf("host thread id\t %u\ndevice thread id %u\n",KERNEL_THRD, MEMORY_THRD);
  
  pthread_t* thread_ptr_arr = (pthread_t*) malloc( (size_t) sizeof(pthread_t)*num_threads ); // alternatively pthread_t* thread_ptr_arr[num_threads];
  
  // init barier for threads
  pthread_barrier_init (&barrier, NULL, num_threads); // last number tells how many threads should be synchronized by this barier
  
  pthread_create(&thread_ptr_arr[KERNEL_THRD], NULL, host_thread, (void*) data_arr_ptr);
  pthread_create(&thread_ptr_arr[MEMORY_THRD], NULL, device_thread, (void*) data_arr_ptr);
  
  void* status;
  pthread_join(thread_ptr_arr[HOST_THRD], &status);
  pthread_join(thread_ptr_arr[DEVICE_THRD], &status);
  
  //printf("data visible in main thread:\n");  
  
  // Cleaning up
  free(thread_ptr_arr);
  free(streams_arr);
  free(data_arr_ptr);
  
  cudaThreadExit();
  cudaDeviceSynchronize();
  
  printf("Main: program completed. Exiting...\n");
  return EXIT_SUCCESS;
}
示例#12
0
文件: main.c 项目: minimaxwell/tools
int main( int argc, char **argv ) {

	GSList *elem = NULL;

	if(argc != 2) {
		printf("./report file\n");
		return 1;
	}

	GSList *ignore_list = NULL;
	ignore_list = g_slist_prepend( ignore_list, "Num reports" );
	ignore_list = g_slist_prepend( ignore_list, "RSSI" );
	ignore_list = g_slist_prepend( ignore_list, "Data length" );
	ignore_list = g_slist_prepend( ignore_list, "TX power" );

	GSList *reports = read_reports(argv[1], ignore_list);
/*	
	elem = reports;
	while (elem) {
		print_report( (t_report *) elem->data );
		elem = elem->next;
	}
*/
	GSList *merge_list = NULL;

	merge_list = g_slist_prepend( merge_list, "Flags");
	merge_list = g_slist_prepend( merge_list, "Event type");
	merge_list = g_slist_prepend( merge_list, "Address type");
	merge_list = g_slist_prepend( merge_list, "Service Data (UUID 0xfe9f)");
	merge_list = g_slist_prepend( merge_list, "16-bit Service UUIDs (complete)");
	merge_list = g_slist_prepend( merge_list, "128-bit Service UUIDs (partial)");
	merge_list = g_slist_prepend( merge_list, "Company");
	merge_list = g_slist_prepend( merge_list, "Name (complete)");
	merge_list = g_slist_prepend( merge_list, "Name (short)");

	GSList *devices = get_devices_by_field(reports, "Address", merge_list);

	elem = devices;
	while (elem) {
		print_device( (t_device *) elem->data);
		elem = elem->next;
	}

	return 0;
}
示例#13
0
/* debugging routine; send a cloud protocol ping message out each of
 * our interfaces.
 */
void test_devices()
{
    int i;
    int msg_len;
    message_t message;

    memset(&message, 0, sizeof(message));

    message.message_type = ping_msg;
    msg_len = ((byte *) &message.message_type)
            + sizeof(message.message_type)
            - ((byte *) &message);

    for (i = 0; i < device_list_count; i++) {
        ddprintf("testing device_list[%d]:  ", i);
        print_device(eprintf, stderr, &device_list[i]);
        sendum((byte *) &message, msg_len, &device_list[i]);
    }
} /* test_devices */
static int list_devices(bool parsable)
{
	char bus_type[] = "usb";
	char busid[SYSFS_BUS_ID_SIZE];
	char product_name[128];
	struct sysfs_bus *ubus;
	struct sysfs_device *dev;
	struct sysfs_device *intf;
	struct sysfs_attribute *idVendor;
	struct sysfs_attribute *idProduct;
	struct sysfs_attribute *bConfValue;
	struct sysfs_attribute *bNumIntfs;
	struct dlist *devlist;
	int i;
	int ret = -1;

	ubus = sysfs_open_bus(bus_type);
	if (!ubus) {
		err("could not open %s bus: %s", bus_type, strerror(errno));
		return -1;
	}

	devlist = sysfs_get_bus_devices(ubus);
	if (!devlist) {
		err("could not get %s bus devices: %s", bus_type,
		    strerror(errno));
		goto err_out;
	}

	/* remove interfaces and root hubs from device list */
	dlist_filter_sort(devlist, is_device, devcmp);

	if (!parsable) {
		printf("Local USB devices\n");
		printf("=================\n");
	}
	dlist_for_each_data(devlist, dev, struct sysfs_device) {
		idVendor   = sysfs_get_device_attr(dev, "idVendor");
		idProduct  = sysfs_get_device_attr(dev, "idProduct");
		bConfValue = sysfs_get_device_attr(dev, "bConfigurationValue");
		bNumIntfs  = sysfs_get_device_attr(dev, "bNumInterfaces");
		if (!idVendor || !idProduct || !bConfValue || !bNumIntfs) {
			err("problem getting device attributes: %s",
			    strerror(errno));
			goto err_out;
		}

		/* get product name */
		usbip_names_get_product(product_name, sizeof(product_name),
					strtol(idVendor->value, NULL, 16),
					strtol(idProduct->value, NULL, 16));
		print_device(dev->bus_id, idVendor->value, idProduct->value,
			     parsable);
		print_product_name(product_name, parsable);

		for (i = 0; i < atoi(bNumIntfs->value); i++) {
			snprintf(busid, sizeof(busid), "%s:%.1s.%d",
				 dev->bus_id, bConfValue->value, i);
			intf = sysfs_open_device(bus_type, busid);
			if (!intf) {
				err("could not open device interface: %s",
				    strerror(errno));
				goto err_out;
			}
			print_interface(busid, intf->driver_name, parsable);
			sysfs_close_device(intf);
		}
		printf("\n");
	}
示例#15
0
文件: scsi.c 项目: syedaunnraza/work
int			/* O - Exit status */
main(int  argc,		/* I - Number of command-line arguments (6 or 7) */
     char *argv[])	/* I - Command-line arguments */
{
  char		method[255],	/* Method in URI */
		hostname[1024],	/* Hostname */
		username[255],	/* Username info (not used) */
		resource[1024],	/* Resource info (device and options) */
		*options;	/* Pointer to options */
  int		port;		/* Port number (not used) */
  int		fp;		/* Print file */
  int		copies;		/* Number of copies to print */
  int		status;		/* Exit status */
#if defined(HAVE_SIGACTION) && !defined(HAVE_SIGSET)
  struct sigaction action;	/* Actions for POSIX signals */
#endif /* HAVE_SIGACTION && !HAVE_SIGSET */


 /*
  * Make sure status messages are not buffered...
  */

  setbuf(stderr, NULL);

 /*
  * Ignore SIGPIPE signals...
  */

#ifdef HAVE_SIGSET
  sigset(SIGPIPE, SIG_IGN);
#elif defined(HAVE_SIGACTION)
  memset(&action, 0, sizeof(action));
  action.sa_handler = SIG_IGN;
  sigaction(SIGPIPE, &action, NULL);
#else
  signal(SIGPIPE, SIG_IGN);
#endif /* HAVE_SIGSET */

 /*
  * Check command-line...
  */

  if (argc == 1)
  {
    list_devices();
    return (CUPS_BACKEND_OK);
  }
  else if (argc < 6 || argc > 7)
  {
    _cupsLangPrintf(stderr,
                    _("Usage: %s job-id user title copies options [file]\n"),
		    argv[0]);
    return (CUPS_BACKEND_FAILED);
  }

 /*
  * If we have 7 arguments, print the file named on the command-line.
  * Otherwise, send stdin instead...
  */

  if (argc == 6)
  {
    fp     = 0;
    copies = 1;
  }
  else
  {
   /*
    * Try to open the print file...
    */

    if ((fp = open(argv[6], O_RDONLY)) < 0)
    {
      perror("ERROR: unable to open print file");
      return (CUPS_BACKEND_FAILED);
    }

    copies = atoi(argv[4]);
  }

 /*
  * Extract the device name and options from the URI...
  */

  httpSeparateURI(HTTP_URI_CODING_ALL, cupsBackendDeviceURI(argv),
                  method, sizeof(method), username, sizeof(username),
		  hostname, sizeof(hostname), &port,
		  resource, sizeof(resource));

 /*
  * See if there are any options...
  */

  if ((options = strchr(resource, '?')) != NULL)
  {
   /*
    * Yup, terminate the device name string and move to the first
    * character of the options...
    */

    *options++ = '\0';
  }

 /*
  * Finally, send the print file...
  */

  status = print_device(resource, fp, copies);

 /*
  * Close input file and return...
  */

  if (fp != 0)
    close(fp);

  return (status);
}
示例#16
0
int print_device(struct usb_device *dev, int level)
{
  usb_dev_handle *udev;
  char description[256];
  char string[256];
  int ret, i;

  udev = usb_open(dev);
  if (udev) {
    if (dev->descriptor.iManufacturer) {
      ret = usb_get_string_simple(udev, dev->descriptor.iManufacturer, string, sizeof(string));
      if (ret > 0)
        snprintf(description, sizeof(description), "%s - ", string);
      else
        snprintf(description, sizeof(description), "%04X - ",
                 dev->descriptor.idVendor);
    } else
      snprintf(description, sizeof(description), "%04X - ",
               dev->descriptor.idVendor);

    if (dev->descriptor.iProduct) {
      ret = usb_get_string_simple(udev, dev->descriptor.iProduct, string, sizeof(string));
      if (ret > 0)
        snprintf(description + strlen(description), sizeof(description) -
                 strlen(description), "%s", string);
      else
        snprintf(description + strlen(description), sizeof(description) -
                 strlen(description), "%04X", dev->descriptor.idProduct);
    } else
      snprintf(description + strlen(description), sizeof(description) -
               strlen(description), "%04X", dev->descriptor.idProduct);

  } else
    snprintf(description, sizeof(description), "%04X - %04X",
             dev->descriptor.idVendor, dev->descriptor.idProduct);

  printf("%.*sDev #%d: %s\n", level * 2, "                    ", dev->devnum,
         description);

  if (udev && verbose) {
    if (dev->descriptor.iSerialNumber) {
      ret = usb_get_string_simple(udev, dev->descriptor.iSerialNumber, string, sizeof(string));
      if (ret > 0)
        printf("%.*s  - Serial Number: %s\n", level * 2,
               "                    ", string);
    }
  }

  if (udev)
    usb_close(udev);

  if (verbose) {
    if (!dev->config) {
      printf("  Couldn't retrieve descriptors\n");
      return 0;
    }

    for (i = 0; i < dev->descriptor.bNumConfigurations; i++)
      print_configuration(&dev->config[i]);
  } else {
    for (i = 0; i < dev->num_children; i++)
      print_device(dev->children[i], level + 1);
  }

  return 0;
}
示例#17
0
int main( int argc, char **argv )
{
	char *error = NULL;
	if ( !tempered_init( &error ) )
	{
		fprintf( stderr, "Failed to initialize libtempered: %s\n", error );
		free( error );
		return 1;
	}
	
	struct tempered_device_list *list = tempered_enumerate( &error );
	if ( list == NULL )
	{
		fprintf( stderr, "Failed to enumerate devices: %s\n", error );
		free( error );
	}
	else
	{
		if ( argc > 1 )
		{
			// We have parameters, so only print those devices that are given.
			int i;
			for ( i = 1; i < argc ; i++ )
			{
				bool found = false;
				struct tempered_device_list *dev;
				for ( dev = list ; dev != NULL ; dev = dev->next )
				{
					if ( strcmp( dev->path, argv[i] ) == 0 )
					{
						found = true;
						print_device( dev );
						break;
					}
				}
				if ( !found )
				{
					fprintf(
						stderr, "%s: TEMPered device not found or ignored.\n",
						argv[i]
					);
				}
			}
		}
		else
		{
			// We don't have any parameters, so print all the devices we found.
			struct tempered_device_list *dev;
			for ( dev = list ; dev != NULL ; dev = dev->next )
			{
				print_device( dev );
			}
		}
		tempered_free_device_list( list );
	}
	
	if ( !tempered_exit( &error ) )
	{
		fprintf( stderr, "%s\n", error );
		free( error );
		return 1;
	}
	return 0;
}
示例#18
0
文件: list_audio.c 项目: EQ4/faudio
 fa_for_each(x, fa_audio_all(session)) {
     if (!fa_check(x)) {
         print_device(x);
     }
 }
示例#19
0
文件: pk2dft.c 项目: GBert/misc
int dump_device_file(char *dumpdir) {
    char fname[255], fbase[255], *p;
    FILE *f, *fcfg;
    int i;

    /* create diretory */
    strcpy(fname, "mkdir ");
    strcat(fname, dumpdir);
    system(fname);

    /* write the config file */
    strcpy(fname, dumpdir);
    strcat(fname, "/config.cfg");
    if ((fcfg = fopen(fname, "w+")) == NULL)
	return -1;

    fprintf(fcfg, "# this configiration file was generated automatically\n");
    fprintf(fcfg, "# please modify it according to the rules :-)\n#\n");
    fprintf(fcfg, "# the source file contained:\n");
    fprintf(fcfg, "#   %d families,\n", hdr.num_families);
    fprintf(fcfg, "#   %d devices and\n", hdr.num_devices);
    fprintf(fcfg, "#   %d scripts.\n\n\n", hdr.num_scripts);
    fprintf(fcfg, "# for the device file header\n");
    fprintf(fcfg, "ver_major = %d\n", hdr.version[0]);
    fprintf(fcfg, "ver_minor = %d\n", hdr.version[1]);
    fprintf(fcfg, "ver_dot   = %d\n", hdr.version[2]);
    fprintf(fcfg, "compat    = %d\n", hdr.compat);
    fprintf(fcfg, "unused1a  = %d\n", hdr.unused1a);
    fprintf(fcfg, "unused1b  = %d\n", hdr.unused1b);
    fprintf(fcfg, "unused2   = %d\n", hdr.unused2);
    fprintf(fcfg, "notes     = \n\"%s\"\n\n\n", hdr.notes);

    /* write families */
    strcpy(fname, "mkdir ");
    strcat(fname, dumpdir);
    strcat(fname, "/families");
    system(fname);

    strcpy(fbase, dumpdir);
    strcat(fbase, "/families/");
    p = fbase + strlen(fbase);
    fprintf(fcfg, "# list of device family files\n");
    fprintf(fcfg, "families  = {\n");
    for (i = 0; i < hdr.num_families; i++) {
	special_cat(p, families[i].name);
	strcat(fbase, ".fam");
	printf("filename : \"%s\"\n", fbase);
	fprintf(fcfg, "\t\"%s\",\n", valid_string(fbase, g_tmp));
	if ((f = fopen(fbase, "w+")) == NULL) {
	    printf("error: cannot create file\n");
	    return -1;
	}
	print_family(f, &families[i]);
	fclose(f);
    }
    fprintf(fcfg, "}\n\n");

    /* write devices */
    strcpy(fname, "mkdir ");
    strcat(fname, dumpdir);
    strcat(fname, "/devices");
    system(fname);

    strcpy(fbase, dumpdir);
    strcat(fbase, "/devices/");
    p = fbase + strlen(fbase);
    fprintf(fcfg, "# list of device files\n");
    fprintf(fcfg, "devices   = {\n");
    for (i = 0; i < hdr.num_devices; i++) {
	special_cat(p, devices[i].part_name);
	strcat(fbase, ".dev");
	printf("filename : \"%s\"\n", fbase);
	fprintf(fcfg, "\t\"%s\",\n", valid_string(fbase, g_tmp));
	if ((f = fopen(fbase, "w+")) == NULL) {
	    printf("error: cannot create file\n");
	    return -1;
	}
	print_device(f, &devices[i]);
	fclose(f);
    }
    fprintf(fcfg, "}\n\n");

    /* write scripts */
    strcpy(fname, "mkdir ");
    strcat(fname, dumpdir);
    strcat(fname, "/scripts");
    system(fname);

    strcpy(fbase, dumpdir);
    strcat(fbase, "/scripts/");
    p = fbase + strlen(fbase);
    fprintf(fcfg, "# list of script files\n");
    fprintf(fcfg, "scripts   = {\n");
    for (i = 0; i < hdr.num_scripts; i++) {
	special_cat(p, scripts[i].name);
	strcat(fbase, ".scr");
	printf("filename : \"%s\"\n", fbase);
	fprintf(fcfg, "\t\"%s\",\n", valid_string(fbase, g_tmp));
	if ((f = fopen(fbase, "w+")) == NULL) {
	    printf("error: cannot create file\n");
	    return -1;
	}
	print_script(f, &scripts[i]);
	fclose(f);
    }
    fprintf(fcfg, "}");

    fclose(fcfg);

    return 0;
}
示例#20
0
/* for interface "device_name" (i.e., eth0 etc.), open a raw socket to
 * the interface and get a file descriptor for the socket.  add the
 * interface (file descriptor and all) to device_list[].
 *
 * as a special case, if the device type is an ad-hoc, that means this
 * is a description of another cloud box that we are communicating with
 * in ad-hoc mode.  in that case, find and copy the device_list[] entry
 * for our wireless lan interface.
 */
void add_device(char *device_name, mac_address_t mac_address,
        device_type_t device_type)
{
    device_t *device;
    static struct ifreq get_index;
    int result;
    struct sockaddr_ll bind_arg;
    mac_address_t mac_addr;
    int i;
    device_t *wlan;

    if (device_list_count >= MAX_CLOUD) {
        ddprintf("add_device:  too many devices.\n");
        goto finish;
    }

    device = &device_list[device_list_count];

    device->sim_device = 0;
    device->expect_k = 0;
    device->expect_n = -1;

    // if (db[0].d) {
        ddprintf("hi from add_device(%s)..\n", device_name);
    // }

    if (strstr(device_name, "wds") != NULL && device_type == device_type_wds) {
        device->device_type = device_type_wds;

    } else if (strstr(device_name, "wds") != NULL
        && device_type == device_type_cloud_wds)
    {
        device->device_type = device_type_cloud_wds;

    } else if (strcmp(device_name, wlan_device_name) == 0
        && device_type == device_type_wlan)
    {
        device->device_type = device_type_wlan;

    } else if (eth_device_name != NULL
        && strcmp(device_name, eth_device_name) == 0)
    {
        device->device_type = device_type_eth;

    } else if (have_mon_device &&
        strcmp(device_name, wlan_mon_device_name) == 0)
    {
        device->device_type = device_type_wlan_mon;

    } else if (ad_hoc_mode && device_type == device_type_ad_hoc) {
        bool_t found = false;
        device->device_type = device_type_ad_hoc;
        for (i = 0; i < device_list_count; i++) {
            if (device_list[i].device_type == device_type_wlan) {
                found = true;
                wlan = &device_list[i];
                break;
            }
        }
        if (!found) {
            ddprintf("add_device; couldn't find wireless device in ad_hoc mode");
            goto finish;
        }

    } else if (/*ad_hoc_mode &&*/ device_type == device_type_cloud_wlan) {
        device->device_type = device_type_cloud_wlan;

    } else if (/*ad_hoc_mode &&*/ device_type == device_type_cloud_eth) {
        device->device_type = device_type_cloud_eth;

    } else {
        ddprintf("add_device; unknown device_type '%s'\n", device_name);
        goto finish;
    }

    if (mac_address == 0) {
        result = mac_get(mac_addr, device_name);
        if (result != 0) {
            ddprintf("add_device:  mac_get on %s failed.\n",
                    device_name);
            goto finish;
        }
    } else {
        mac_copy(mac_addr, mac_address);
    }

    if (ad_hoc_mode && device_type == device_type_ad_hoc) {
        sprintf(device->device_name, wlan_device_name);
    } else {
        sprintf(device->device_name, device_name);
    }

    mac_copy(device->mac_address, mac_addr);

    if (use_pipes) {
        char fname[PATH_MAX];
        int fd;
        sprintf(fname, "%s/%s.cloud", pipe_directory, device_name);
        fd = repeat_open(fname, O_RDWR);
        ddprintf("opening wlan input device %s; fd %d\n", fname, fd);
        if (fd == -1) {
            ddprintf("add_device; could not open pipe %s:  %s\n", 
                    fname, strerror(errno));
            goto finish;
        }
        device->fd = fd;
        pio_init_from_fd(&device->in_pio, fname, fd);
        ddprintf("done..\n");

        sprintf(fname, "%s/%s.cooked", pipe_directory, device_name);
        fd = repeat_open(fname, O_RDWR);
        ddprintf("opening wlan output device %s; fd %d\n", fname, fd);
        if (fd == -1) {
            ddprintf("add_device; could not open pipe %s:  %s\n", 
                    fname, strerror(errno));
            goto finish;
        }
        device->out_fd = fd;
        pio_init_from_fd(&device->out_pio, fname, fd);
        ddprintf("done..\n");

    } else if (ad_hoc_mode && device_type == device_type_ad_hoc) {
        device->fd = wlan->fd;
        device->if_index = wlan->if_index;

    } else {
        device->fd = socket(PF_PACKET, SOCK_RAW, htons(ETH_P_ALL));
        if (device->fd == -1) {
            ddprintf("add_device:  socket failed\n");
            goto finish;
        }

        /* after a change of wep key, this fails. may need to delete and
         * re-create wds interface?
         */
        sprintf(get_index.ifr_name, device_name);
        result = ioctl(device->fd, SIOCGIFINDEX, &get_index);
        if (result == -1) {
            ddprintf("add_device:  could not get device index\n");
            goto finish;
        }
        device->if_index = get_index.ifr_ifindex;

        memset(&bind_arg, 0, sizeof(bind_arg));
        bind_arg.sll_family = AF_PACKET;
        bind_arg.sll_ifindex = get_index.ifr_ifindex;

        if (device_type == device_type_cloud_wlan
            || device_type == device_type_cloud_eth
            || device_type == device_type_cloud_wds)
        {
            bind_arg.sll_protocol = htons(CLOUD_MSG);

        } else if (db[47].d
            && ((ad_hoc_mode && !db[50].d && device_type == device_type_wlan)
                || device_type == device_type_wds))
        {
            bind_arg.sll_protocol = htons(WRAPPED_CLIENT_MSG);

        } else {
            bind_arg.sll_protocol = htons(ETH_P_ALL);
        }

        result = bind(device->fd, (struct sockaddr *) &bind_arg,
                sizeof(bind_arg));
        if (result == -1) {
            ddprintf("add_device:  bind failed\n");
            goto finish;
        }
    }

    if (db[50].d && device_type == device_type_ad_hoc) {
        ad_hoc_client_add(device->mac_address);
    }

    add_io_stat(device);

    device_list_count++;

    finish :

    // if (db[0].d) {
        ddprintf("this device:\n");
        print_device(eprintf, stderr, &device_list[device_list_count - 1]);
        ddprintf("all devices:\n");
        print_devices();
    // }

} /* add_device */
示例#21
0
文件: main.cpp 项目: 4ib3r/domoticz
int list_devices() {
	tdInit();
	int intNum = tdGetNumberOfDevices();
	if (intNum < 0) {
		char *errorString = tdGetErrorString(intNum);
		fprintf(stderr, "Error fetching devices: %s\n", errorString);
		tdReleaseString(errorString);
		return intNum;
	}
	printf("Number of devices: %i\n", intNum);
	int i = 0;
	while (i < intNum) {
		print_device( i );
		i++;
	}

	char protocol[DATA_LENGTH], model[DATA_LENGTH];
	int sensorId = 0, dataTypes = 0;

	int sensorStatus = tdSensor(protocol, DATA_LENGTH, model, DATA_LENGTH, &sensorId, &dataTypes);
	if(sensorStatus == 0){
		printf("\n\nSENSORS:\n\n%-20s\t%-20s\t%-5s\t%-5s\t%-8s\t%-20s\t%-20s\t%-20s\n", "PROTOCOL", "MODEL", "ID", "TEMP", "HUMIDITY", "RAIN", "WIND", "LAST UPDATED");
	}
	while(sensorStatus == 0){
		char tempvalue[DATA_LENGTH];
		tempvalue[0] = 0;
		char humidityvalue[DATA_LENGTH];
		humidityvalue[0] = 0;
		char windvalue[DATA_LENGTH];
		windvalue[0] = 0;
		char winddirectionvalue[DATA_LENGTH];
		winddirectionvalue[0] = 0;
		char windaveragevalue[DATA_LENGTH];
		windaveragevalue[0] = 0;
		char windgustvalue[DATA_LENGTH];
		windgustvalue[0] = 0;
		char rainvalue[DATA_LENGTH];
		rainvalue[0] = 0;
		char raintotvalue[DATA_LENGTH];
		raintotvalue[0] = 0;
		char rainratevalue[DATA_LENGTH];
		rainratevalue[0] = 0;
		char timeBuf[80];
		timeBuf[0] = 0;
		time_t timestamp = 0;

		if (dataTypes & TELLSTICK_TEMPERATURE) {
			tdSensorValue(protocol, model, sensorId, TELLSTICK_TEMPERATURE, tempvalue, DATA_LENGTH, (int *)&timestamp);
			strcat(tempvalue, DEGREE);
			strftime(timeBuf, sizeof(timeBuf), "%Y-%m-%d %H:%M:%S", localtime(&timestamp));
		}

		if (dataTypes & TELLSTICK_HUMIDITY) {
			tdSensorValue(protocol, model, sensorId, TELLSTICK_HUMIDITY, humidityvalue, DATA_LENGTH, (int *)&timestamp);
			strcat(humidityvalue, "%");
			strftime(timeBuf, sizeof(timeBuf), "%Y-%m-%d %H:%M:%S", localtime(&timestamp));
		}

		if (dataTypes & TELLSTICK_RAINRATE) {
			tdSensorValue(protocol, model, sensorId, TELLSTICK_RAINRATE, rainratevalue, DATA_LENGTH, (int *)&timestamp);
			strcat(rainratevalue, " mm/h, ");
			strcat(rainvalue, rainratevalue);
			strftime(timeBuf, sizeof(timeBuf), "%Y-%m-%d %H:%M:%S", localtime(&timestamp));
		}

		if (dataTypes & TELLSTICK_RAINTOTAL) {
			tdSensorValue(protocol, model, sensorId, TELLSTICK_RAINTOTAL, raintotvalue, DATA_LENGTH, (int *)&timestamp);
			//TODO detta blir väl fel, kan väl hamna i andra ordningar, eller hur?
			strcat(raintotvalue, " mm");
			strcat(rainvalue, raintotvalue);
			strftime(timeBuf, sizeof(timeBuf), "%Y-%m-%d %H:%M:%S", localtime(&timestamp));
		}

		if (dataTypes & TELLSTICK_WINDDIRECTION) {
			tdSensorValue(protocol, model, sensorId, TELLSTICK_WINDDIRECTION, winddirectionvalue, DATA_LENGTH, (int *)&timestamp);
			//TODO or use charToInteger in common?
			std::stringstream inputstream;
			inputstream << winddirectionvalue;
			int direction;
			inputstream >> direction;
			direction = direction / 22.5;
			std::string directionabbrev = "N";
			switch (direction) {
				case 1:
					directionabbrev = "NNE";
					break;
				case 2:
					directionabbrev = "NE";
					break;
				case 3:
					directionabbrev = "ENE";
					break;
				case 4:
					directionabbrev = "E";
					break;
				case 5:
					directionabbrev = "ESE";
					break;
				case 6:
					directionabbrev = "SE";
					break;
				case 7:
					directionabbrev = "SSE";
					break;
				case 8:
					directionabbrev = "S";
					break;
				case 9:
					directionabbrev = "SSW";
					break;
				case 10:
					directionabbrev = "SW";
					break;
				case 11:
					directionabbrev = "WSW";
					break;
				case 12:
					directionabbrev = "W";
					break;
				case 13:
					directionabbrev = "WNW";
					break;
				case 14:
					directionabbrev = "NW";
					break;
				case 15:
					directionabbrev = "NNW";
					break;
			}
			strcat(windvalue, directionabbrev.c_str());
			strcat(windvalue, ", ");
			strftime(timeBuf, sizeof(timeBuf), "%Y-%m-%d %H:%M:%S", localtime(&timestamp));
		}

		if (dataTypes & TELLSTICK_WINDAVERAGE) {
			tdSensorValue(protocol, model, sensorId, TELLSTICK_WINDAVERAGE, windaveragevalue, DATA_LENGTH, (int *)&timestamp);
			strcat(windaveragevalue, " m/s (");
			strcat(windvalue, windaveragevalue);
			strftime(timeBuf, sizeof(timeBuf), "%Y-%m-%d %H:%M:%S", localtime(&timestamp));
		}

		if (dataTypes & TELLSTICK_WINDGUST) {
			tdSensorValue(protocol, model, sensorId, TELLSTICK_WINDGUST, windgustvalue, DATA_LENGTH, (int *)&timestamp);
			strcat(windgustvalue, " m/s) ");
			strcat(windvalue, windgustvalue);
			strftime(timeBuf, sizeof(timeBuf), "%Y-%m-%d %H:%M:%S", localtime(&timestamp));
		}

		printf("%-20s\t%-20s\t%-5i\t%-5s\t%-8s\t%-20s\t%-20s\t%-20s\n", protocol, model, sensorId, tempvalue, humidityvalue, rainvalue, windvalue, timeBuf);

		sensorStatus = tdSensor(protocol, DATA_LENGTH, model, DATA_LENGTH, &sensorId, &dataTypes);
	}
示例#22
0
文件: usb.c 项目: JokeLook/dbstar
static int print_device(struct usb_device *dev, int level)
{
  usb_dev_handle *udev;
  char description[256];
  char string[256];
  int ret, i;
//	indent_usb_table = 0;
  udev = usb_open(dev);
  if (udev) {
    if (dev->descriptor.iManufacturer) {
      ret = usb_get_string_simple(udev, dev->descriptor.iManufacturer, string, sizeof(string));
      if (ret > 0)
        snprintf(description, sizeof(description), "%s - ", string);
      else
        snprintf(description, sizeof(description), "%04X - ",
                 dev->descriptor.idVendor);
    } else
      snprintf(description, sizeof(description), "%04X - ",
               dev->descriptor.idVendor);
	LOGE("The VID is %04X \n",dev->descriptor.idVendor);
	LOGE("indent_usb_table is %d\n",indent_usb_table);
	usb_table[indent_usb_table].vid = dev->descriptor.idVendor;
    
    if (dev->descriptor.iProduct) {
      ret = usb_get_string_simple(udev, dev->descriptor.iProduct, string, sizeof(string));
      if (ret > 0)
        snprintf(description + strlen(description), sizeof(description) -
                 strlen(description), "%s", string);
      else
        snprintf(description + strlen(description), sizeof(description) -
                 strlen(description), "%04X", dev->descriptor.idProduct);
    } else
      snprintf(description + strlen(description), sizeof(description) -
               strlen(description), "%04X", dev->descriptor.idProduct);
    LOGE("The PID is %04X\n",dev->descriptor.idProduct);
	usb_table[indent_usb_table].pid = dev->descriptor.idProduct;
    indent_usb_table ++;
  } else{
  	LOGE("Open failed! \n");
  	snprintf(description, sizeof(description), "%04X - %04X",
             dev->descriptor.idVendor, dev->descriptor.idProduct);
    LOGE("The VID:PID is 0x%04X : 0x%04X\n",dev->descriptor.idVendor,dev->descriptor.idProduct);
}


  printf("%.*sDev #%d: %s\n", level * 2, "                    ", dev->devnum,
         description);

  if (udev && verbose1) {
    if (dev->descriptor.iSerialNumber) {
      ret = usb_get_string_simple(udev, dev->descriptor.iSerialNumber, string, sizeof(string));
      if (ret > 0)
        printf("%.*s  - Serial Number: %s\n", level * 2,
               "                    ", string);
    }
  }

  if (udev)
    usb_close(udev);

  if (verbose1) {
    if (!dev->config) {
      printf("  Couldn't retrieve descriptors\n");
      return 0;
    }

    for (i = 0; i < dev->descriptor.bNumConfigurations; i++)
      print_configuration(&dev->config[i]);
  } else {
    for (i = 0; i < dev->num_children; i++)
      print_device(dev->children[i], level + 1);
  }
  
  return 0;
}
示例#23
0
/*
 * main should only control threads
 *
 * the threads should be invoked on different cores:
 * http://stackoverflow.com/questions/1407786/how-to-set-cpu-affinity-of-a-particular-pthread
 * https://www.google.pl/search?client=ubuntu&channel=fs&q=how+to+schedule+pthreads+through+cores&ie=utf-8&oe=utf-8&gfe_rd=cr&ei=PSudVePFOqeA4AShra2AAQ
 */
int main() {

    cudaDeviceReset();
    cudaDeviceSynchronize();

    // print device properties
    print_device();

    // create pointers to data
    const uint64_t size = N;
    double complex* data_r_host = NULL; // initializing with NULL for debuging purposes
    double complex* data_k_host = NULL; // initializing with NULL for debuging purposes
    DataArray* data_arr_ptr = (DataArray*) malloc((size_t) sizeof(DataArray)); // change to global variable <- easier to code
    create_data_arr(data_arr_ptr, &data_r_host, &data_k_host, size);

    // allocate memory for array of streams
    const uint8_t num_streams = 2; // rewrite on defines?
    streams_arr = (cudaStream_t*) malloc( (size_t) sizeof(cudaStream_t)*num_streams);

    // create threads
    const uint8_t num_threads = 2;
    printf("host thread id\t %u\ndevice thread id %u\n",HOST_THRD, DEVICE_THRD);

    pthread_t* thread_ptr_arr = (pthread_t*) malloc( (size_t) sizeof(pthread_t)*num_threads ); // alternatively pthread_t* thread_ptr_arr[num_threads];

    // init barier for threads
    pthread_barrier_init (&barrier, NULL, num_threads); // last number tells how many threads should be synchronized by this barier

    pthread_create(&thread_ptr_arr[HOST_THRD], NULL, host_thread, (void*) data_arr_ptr);
    pthread_create(&thread_ptr_arr[DEVICE_THRD], NULL, device_thread, (void*) data_arr_ptr);

//   for (uint8_t ii = 0; ii < num_threads; ii++) {
//     pthread_create(thread_ptr_arr[ii], NULL, host_thread, (void*) data_arr_ptr);
//   }

    //cudaStream_t stream1;
    //cudaStream_t stream2;
    //cudaStream_t* streams_arr[2] = {&stream1, &stream2};

    void* status;
    pthread_join(thread_ptr_arr[HOST_THRD], &status);
    pthread_join(thread_ptr_arr[DEVICE_THRD], &status);

    printf("data visible in main thread:\n");
    /*for (uint64_t ii=0; ii < (data_arr_ptr->size <= 32) ? data_arr_ptr->size : 32 ; ii++) {
      printf( "%lu.\t",ii );
      printf( "%lf + %lf\t", creal(data_r_host[ii]), cimag(data_r_host[ii]) );
      printf( "%lf + %lf\n", creal(data_k_host[ii]), cimag(data_k_host[ii]) );
    }*/



    free(thread_ptr_arr);
    free(streams_arr);
    free_data_arr(data_arr_ptr);
    cudaDeviceSynchronize();
    free(data_arr_ptr);

    cudaThreadExit();
    cudaDeviceSynchronize();

    printf("Main: program completed. Exiting...\n");
    return EXIT_SUCCESS;
}
示例#24
0
文件: usb.c 项目: JokeLook/dbstar
int usb_wifi_load_driver()
{
	int i,j;
	int usb_vidpid_count=0;
	int count = 100;
	struct usb_bus *bus;
	
	set_power_on(WIFI_POWER);
    usleep(2000000);
	
	LOGE("wifi_load_driver start!!\n");
	
	usb_init();
	usb_find_busses();
	usb_find_devices();
	if(usb_busses==NULL){
		LOGE("usb_busses is NULL\n");
	}
	else{
		LOGE("usb_busses is not NULL\n");
	}
	
	for (bus = usb_busses; bus; bus = bus->next) {
    	if (bus->root_dev && !verbose1){
			print_device(bus->root_dev, 0);
		}
    	else {
			struct usb_device *dev;
			for (dev = bus->devices; dev; dev = dev->next)
				print_device(dev, 0);
    	}
  	}  	
  	
  	if (is_driver_loaded()) {
		LOGD("wifi_driver has loaded!");
		return 0;
    }

	usb_vidpid_count = indent_usb_table;
	indent_usb_table = 0;
	
	
	LOGD("Start to search\n");
	LOGE("THE usb_vidpid_count is %d\n",usb_vidpid_count);	
    for (i = 0;i < usb_vidpid_count; i ++){
       // LOGD("The  serach vid:pid is 0x%x : 0x%x\n",usb_table[i].vid,usb_table[i].pid);    	
    	for(j = 0;j < NUM_OF_DONGLE;j ++){    		
    		//LOGD("The dongle no. is %d\n",j);
			if(dongle_registerd[j].search(usb_table[i].vid,usb_table[i].pid)==1){
				LOGD("search ok!");
				cur_vid = usb_table[i].vid;
				cur_pid = usb_table[i].pid;
				LOGD("The matched dongle no. is %d\n",j);
				//which_dongle_loaded = j;//record the dongle in use
				if((j == 3)||(j == 4)){
                	strcpy(WEXT_OR_NL80211,"nl80211");
            	}else {
                	strcpy(WEXT_OR_NL80211,"wext");
                }
				if(dongle_registerd[j].load() != 0){
					LOGD("Load Wi-Fi driver error!\n");
					return -1;
				}
			}
		}
	}
	
	return 0;
}
示例#25
0
int main(int argc, char *argv[])
{
	int rc = 0;

	struct udev *udev;

	struct sigaction act;
	sigset_t mask;
	struct udev_monitor *kernel_monitor = NULL;
	fd_set readfds;

	const char *filter_subsys    = "block";
	/* const char *filter_devtype   = "partition"; */
    const char *filter_action1   = "remove";
    const char *filter_action2   = "change";
    const char *filter_devsuffix;

    int kexec = 0;

	udev = udev_new();
	if (udev == NULL)
		goto out2;

	if (argc != 2 && argc != 3)
		goto out2;
	filter_devsuffix = argv[1];

    if (argc == 3 && !strcmp(argv[2], "kexec"))
        kexec = 1;

	/* set signal handlers */
	memset(&act, 0x00, sizeof(struct sigaction));
	act.sa_handler = sig_handler;
	sigemptyset(&act.sa_mask);
	act.sa_flags = SA_RESTART;
	sigaction(SIGINT, &act, NULL);
	sigaction(SIGTERM, &act, NULL);
	sigemptyset(&mask);
	sigaddset(&mask, SIGINT);
	sigaddset(&mask, SIGTERM);
	sigprocmask(SIG_UNBLOCK, &mask, NULL);

	kernel_monitor = udev_monitor_new_from_netlink(udev, "kernel");
	if (kernel_monitor == NULL) {
		fprintf(stderr, "error: unable to create netlink socket\n");
		rc = 3;
		goto out;
	}

	if (udev_monitor_filter_add_match_subsystem_devtype(kernel_monitor, filter_subsys, NULL /* filter_devtype */) < 0)
		fprintf(stderr, "error: unable to apply subsystem filter '%s:%s'\n", filter_subsys, "NULL" /* filter_devtype */);

	if (udev_monitor_enable_receiving(kernel_monitor) < 0) {
		fprintf(stderr, "error: unable to subscribe to kernel events\n");
		rc = 4;
		goto out;
	}

    /* lock process memory */
    if (mlockall(MCL_CURRENT) != 0)
        fprintf(stderr, "warning: failed to lock process memory: %s\n", strerror(errno));

	while (!udev_exit) {
		int fdcount;

		FD_ZERO(&readfds);
		if (kernel_monitor != NULL)
			FD_SET(udev_monitor_get_fd(kernel_monitor), &readfds);

		fdcount = select(udev_monitor_get_fd(kernel_monitor)+1,
				 &readfds, NULL, NULL, NULL);
		if (fdcount < 0) {
			if (errno != EINTR)
				fprintf(stderr, "error receiving uevent message: %s\n", strerror(errno));
			continue;
		}

		if ((kernel_monitor != NULL) && FD_ISSET(udev_monitor_get_fd(kernel_monitor), &readfds)) {
			struct udev_device *device;

			device = udev_monitor_receive_device(kernel_monitor);
			if (device == NULL)
				continue;
			if (print_device(device, filter_action1, filter_action2, filter_devsuffix))
                udev_exit = 1;

			udev_device_unref(device);
		}
	}

out:
	udev_monitor_unref(kernel_monitor);

out2:
	udev_unref(udev);

    if (udev_exit == 2)
        rc = 1;

    if (rc == 0 && kexec) {
        reboot(LINUX_REBOOT_CMD_KEXEC);

        fprintf(stderr, "error: failed to reboot via kexec: %s\n", strerror(errno));
        rc = 1;
    }

	return rc;
}
示例#26
0
static int adm_monitor(struct udev *udev, int argc, char *argv[]) {
        struct sigaction act = {};
        sigset_t mask;
        bool prop = false;
        bool print_kernel = false;
        bool print_udev = false;
        _cleanup_udev_list_cleanup_ struct udev_list subsystem_match_list;
        _cleanup_udev_list_cleanup_ struct udev_list tag_match_list;
        _cleanup_udev_monitor_unref_ struct udev_monitor *udev_monitor = NULL;
        _cleanup_udev_monitor_unref_ struct udev_monitor *kernel_monitor = NULL;
        _cleanup_close_ int fd_ep = -1;
        int fd_kernel = -1, fd_udev = -1;
        struct epoll_event ep_kernel, ep_udev;
        int c;

        static const struct option options[] = {
                { "property",        no_argument,       NULL, 'p' },
                { "environment",     no_argument,       NULL, 'e' }, /* alias for -p */
                { "kernel",          no_argument,       NULL, 'k' },
                { "udev",            no_argument,       NULL, 'u' },
                { "subsystem-match", required_argument, NULL, 's' },
                { "tag-match",       required_argument, NULL, 't' },
                { "help",            no_argument,       NULL, 'h' },
                {}
        };

        udev_list_init(udev, &subsystem_match_list, true);
        udev_list_init(udev, &tag_match_list, true);

        while ((c = getopt_long(argc, argv, "pekus:t:h", options, NULL)) >= 0)
                switch (c) {
                case 'p':
                case 'e':
                        prop = true;
                        break;
                case 'k':
                        print_kernel = true;
                        break;
                case 'u':
                        print_udev = true;
                        break;
                case 's':
                        {
                                char subsys[UTIL_NAME_SIZE];
                                char *devtype;

                                strscpy(subsys, sizeof(subsys), optarg);
                                devtype = strchr(subsys, '/');
                                if (devtype != NULL) {
                                        devtype[0] = '\0';
                                        devtype++;
                                }
                                udev_list_entry_add(&subsystem_match_list, subsys, devtype);
                                break;
                        }
                case 't':
                        udev_list_entry_add(&tag_match_list, optarg, NULL);
                        break;
                case 'h':
                        help();
                        return 0;
                default:
                        return 1;
                }

        if (!print_kernel && !print_udev) {
                print_kernel = true;
                print_udev = true;
        }

        /* set signal handlers */
        act.sa_handler = sig_handler;
        act.sa_flags = SA_RESTART;
        sigaction(SIGINT, &act, NULL);
        sigaction(SIGTERM, &act, NULL);
        sigemptyset(&mask);
        sigaddset(&mask, SIGINT);
        sigaddset(&mask, SIGTERM);
        sigprocmask(SIG_UNBLOCK, &mask, NULL);

        /* Callers are expecting to see events as they happen: Line buffering */
        setlinebuf(stdout);

        fd_ep = epoll_create1(EPOLL_CLOEXEC);
        if (fd_ep < 0) {
                log_error_errno(errno, "error creating epoll fd: %m");
                return 1;
        }

        printf("monitor will print the received events for:\n");
        if (print_udev) {
                struct udev_list_entry *entry;

                udev_monitor = udev_monitor_new_from_netlink(udev, "udev");
                if (udev_monitor == NULL) {
                        fprintf(stderr, "error: unable to create netlink socket\n");
                        return 1;
                }
                udev_monitor_set_receive_buffer_size(udev_monitor, 128*1024*1024);
                fd_udev = udev_monitor_get_fd(udev_monitor);

                udev_list_entry_foreach(entry, udev_list_get_entry(&subsystem_match_list)) {
                        const char *subsys = udev_list_entry_get_name(entry);
                        const char *devtype = udev_list_entry_get_value(entry);

                        if (udev_monitor_filter_add_match_subsystem_devtype(udev_monitor, subsys, devtype) < 0)
                                fprintf(stderr, "error: unable to apply subsystem filter '%s'\n", subsys);
                }

                udev_list_entry_foreach(entry, udev_list_get_entry(&tag_match_list)) {
                        const char *tag = udev_list_entry_get_name(entry);

                        if (udev_monitor_filter_add_match_tag(udev_monitor, tag) < 0)
                                fprintf(stderr, "error: unable to apply tag filter '%s'\n", tag);
                }

                if (udev_monitor_enable_receiving(udev_monitor) < 0) {
                        fprintf(stderr, "error: unable to subscribe to udev events\n");
                        return 2;
                }

                memzero(&ep_udev, sizeof(struct epoll_event));
                ep_udev.events = EPOLLIN;
                ep_udev.data.fd = fd_udev;
                if (epoll_ctl(fd_ep, EPOLL_CTL_ADD, fd_udev, &ep_udev) < 0) {
                        log_error_errno(errno, "fail to add fd to epoll: %m");
                        return 2;
                }

                printf("UDEV - the event which udev sends out after rule processing\n");
        }

        if (print_kernel) {
                struct udev_list_entry *entry;

                kernel_monitor = udev_monitor_new_from_netlink(udev, "kernel");
                if (kernel_monitor == NULL) {
                        fprintf(stderr, "error: unable to create netlink socket\n");
                        return 3;
                }
                udev_monitor_set_receive_buffer_size(kernel_monitor, 128*1024*1024);
                fd_kernel = udev_monitor_get_fd(kernel_monitor);

                udev_list_entry_foreach(entry, udev_list_get_entry(&subsystem_match_list)) {
                        const char *subsys = udev_list_entry_get_name(entry);

                        if (udev_monitor_filter_add_match_subsystem_devtype(kernel_monitor, subsys, NULL) < 0)
                                fprintf(stderr, "error: unable to apply subsystem filter '%s'\n", subsys);
                }

                if (udev_monitor_enable_receiving(kernel_monitor) < 0) {
                        fprintf(stderr, "error: unable to subscribe to kernel events\n");
                        return 4;
                }

                memzero(&ep_kernel, sizeof(struct epoll_event));
                ep_kernel.events = EPOLLIN;
                ep_kernel.data.fd = fd_kernel;
                if (epoll_ctl(fd_ep, EPOLL_CTL_ADD, fd_kernel, &ep_kernel) < 0) {
                        log_error_errno(errno, "fail to add fd to epoll: %m");
                        return 5;
                }

                printf("KERNEL - the kernel uevent\n");
        }
        printf("\n");

        while (!udev_exit) {
                int fdcount;
                struct epoll_event ev[4];
                int i;

                fdcount = epoll_wait(fd_ep, ev, ELEMENTSOF(ev), -1);
                if (fdcount < 0) {
                        if (errno != EINTR)
                                fprintf(stderr, "error receiving uevent message: %m\n");
                        continue;
                }

                for (i = 0; i < fdcount; i++) {
                        if (ev[i].data.fd == fd_kernel && ev[i].events & EPOLLIN) {
                                struct udev_device *device;

                                device = udev_monitor_receive_device(kernel_monitor);
                                if (device == NULL)
                                        continue;
                                print_device(device, "KERNEL", prop);
                                udev_device_unref(device);
                        } else if (ev[i].data.fd == fd_udev && ev[i].events & EPOLLIN) {
                                struct udev_device *device;

                                device = udev_monitor_receive_device(udev_monitor);
                                if (device == NULL)
                                        continue;
                                print_device(device, "UDEV", prop);
                                udev_device_unref(device);
                        }
                }
        }

        return 0;
}