xref: /kvmtool/builtin-list.c (revision 8a09361d6a526e17511b01464cbe2c67fa9476bc)
1 #include <kvm/util.h>
2 #include <kvm/kvm-cmd.h>
3 #include <kvm/builtin-list.h>
4 #include <kvm/kvm.h>
5 
6 #include <stdio.h>
7 #include <string.h>
8 #include <signal.h>
9 #include <fcntl.h>
10 
11 #define PROCESS_NAME "kvm"
12 
13 static int print_guest(const char *name, int pid)
14 {
15 	char proc_name[PATH_MAX];
16 	char *comm = NULL;
17 	FILE *fd;
18 
19 	sprintf(proc_name, "/proc/%d/stat", pid);
20 	fd = fopen(proc_name, "r");
21 	if (fd == NULL)
22 		goto cleanup;
23 	if (fscanf(fd, "%*u (%as)", &comm) == 0)
24 		goto cleanup;
25 	if (strncmp(comm, PROCESS_NAME, strlen(PROCESS_NAME)))
26 		goto cleanup;
27 
28 	printf("%5d %s\n", pid, name);
29 
30 	free(comm);
31 
32 	fclose(fd);
33 
34 	return 0;
35 
36 cleanup:
37 	if (fd)
38 		fclose(fd);
39 	if (comm)
40 		free(comm);
41 
42 	kvm__remove_pidfile(name);
43 	return 0;
44 }
45 
46 int kvm_cmd_list(int argc, const char **argv, const char *prefix)
47 {
48 	printf("  PID GUEST\n");
49 
50 	return kvm__enumerate_instances(print_guest);
51 }
52