2 * lslocks(8) - list local system locks
4 * Copyright (C) 2012 Davidlohr Bueso <dave@gnu.org>
6 * Very generally based on lslk(8) by Victor A. Abell <abe@purdue.edu>
7 * Since it stopped being maintained over a decade ago, this
8 * program should be considered its replacement.
10 * This program is free software; you can redistribute it and/or modify
11 * it under the terms of the GNU General Public License as published by
12 * the Free Software Foundation; either version 2 of the License, or
13 * (at your option) any later version.
15 * This program is distributed in the hope that it would be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 * GNU General Public License for more details.
20 * You should have received a copy of the GNU General Public License
21 * along with this program; if not, write to the Free Software Foundation,
22 * Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
33 #include <sys/types.h>
36 #include <libsmartcols.h>
38 #include "pathnames.h"
39 #include "canonicalize.h"
45 #include "closestream.h"
47 #include "procutils.h"
65 const char *name
; /* header */
66 double whint
; /* width hint (N < 1 is in percent of termwidth) */
67 int flags
; /* SCOLS_FL_* */
71 /* columns descriptions */
72 static struct colinfo infos
[] = {
73 [COL_SRC
] = { "COMMAND",15, 0, N_("command of the process holding the lock") },
74 [COL_PID
] = { "PID", 5, SCOLS_FL_RIGHT
, N_("PID of the process holding the lock") },
75 [COL_TYPE
] = { "TYPE", 5, SCOLS_FL_RIGHT
, N_("kind of lock") },
76 [COL_SIZE
] = { "SIZE", 4, SCOLS_FL_RIGHT
, N_("size of the lock") },
77 [COL_MODE
] = { "MODE", 5, 0, N_("lock access mode") },
78 [COL_M
] = { "M", 1, 0, N_("mandatory state of the lock: 0 (none), 1 (set)")},
79 [COL_START
] = { "START", 10, SCOLS_FL_RIGHT
, N_("relative byte offset of the lock")},
80 [COL_END
] = { "END", 10, SCOLS_FL_RIGHT
, N_("ending offset of the lock")},
81 [COL_PATH
] = { "PATH", 0, SCOLS_FL_TRUNC
, N_("path of the locked file")},
82 [COL_BLOCKER
] = { "BLOCKER", 0, SCOLS_FL_RIGHT
, N_("PID of the process blocking the lock") }
85 static int columns
[ARRAY_SIZE(infos
) * 2];
86 static size_t ncolumns
;
90 static struct libmnt_table
*tab
; /* /proc/self/mountinfo */
92 /* basic output flags */
93 static int no_headings
;
94 static int no_inaccessible
;
100 struct list_head locks
;
109 unsigned int mandatory
:1,
115 static void rem_lock(struct lock
*lock
)
124 list_del(&lock
->locks
);
128 static void disable_columns_truncate(void)
132 for (i
= 0; i
< ARRAY_SIZE(infos
); i
++)
133 infos
[i
].flags
&= ~SCOLS_FL_TRUNC
;
137 * Associate the device's mountpoint for a filename
139 static char *get_fallback_filename(dev_t dev
)
141 struct libmnt_fs
*fs
;
145 tab
= mnt_new_table_from_file(_PATH_PROC_MOUNTINFO
);
150 fs
= mnt_table_find_devno(tab
, dev
, MNT_ITER_BACKWARD
);
154 xasprintf(&res
, "%s...", mnt_fs_get_target(fs
));
159 * Return the absolute path of a file from
160 * a given inode number (and its size)
162 static char *get_filename_sz(ino_t inode
, pid_t lock_pid
, size_t *size
)
169 char path
[PATH_MAX
], sym
[PATH_MAX
], *ret
= NULL
;
172 memset(path
, 0, sizeof(path
));
173 memset(sym
, 0, sizeof(sym
));
176 * We know the pid so we don't have to
177 * iterate the *entire* filesystem searching
180 sprintf(path
, "/proc/%d/fd/", lock_pid
);
181 if (!(dirp
= opendir(path
)))
184 if ((len
= strlen(path
)) >= (sizeof(path
) - 2))
187 if ((fd
= dirfd(dirp
)) < 0 )
190 while ((dp
= readdir(dirp
))) {
191 if (!strcmp(dp
->d_name
, ".") ||
192 !strcmp(dp
->d_name
, ".."))
195 /* care only for numerical descriptors */
196 if (!strtol(dp
->d_name
, (char **) NULL
, 10))
199 if (!fstatat(fd
, dp
->d_name
, &sb
, 0)
200 && inode
!= sb
.st_ino
)
203 if ((len
= readlinkat(fd
, dp
->d_name
, sym
, sizeof(sym
) - 1)) < 1)
218 * Return the inode number from a string
220 static ino_t
get_dev_inode(char *str
, dev_t
*dev
)
222 unsigned int maj
= 0, min
= 0;
225 sscanf(str
, "%02x:%02x:%ju", &maj
, &min
, &inum
);
227 *dev
= (dev_t
) makedev(maj
, min
);
231 static int get_local_locks(struct list_head
*locks
)
236 char buf
[PATH_MAX
], *tok
= NULL
;
241 if (!(fp
= fopen(_PATH_PROC_LOCKS
, "r")))
244 while (fgets(buf
, sizeof(buf
), fp
)) {
246 l
= xcalloc(1, sizeof(*l
));
247 INIT_LIST_HEAD(&l
->locks
);
249 for (tok
= strtok(buf
, " "), i
= 0; tok
;
250 tok
= strtok(NULL
, " "), i
++) {
253 * /proc/locks has *exactly* 8 "blocks" of text
254 * separated by ' ' - check <kernel>/fs/locks.c
258 tok
[strlen(tok
) - 1] = '\0';
259 l
->id
= strtos32_or_err(tok
, _("failed to parse ID"));
261 case 1: /* posix, flock, etc */
262 if (strcmp(tok
, "->") == 0) { /* optional field */
266 l
->type
= xstrdup(tok
);
269 case 2: /* is this a mandatory lock? other values are advisory or noinode */
270 l
->mandatory
= *tok
== 'M' ? 1 : 0;
272 case 3: /* lock mode */
273 l
->mode
= xstrdup(tok
);
278 * If user passed a pid we filter it later when adding
279 * to the list, no need to worry now. OFD locks use -1 PID.
281 l
->pid
= strtos32_or_err(tok
, _("failed to parse pid"));
283 l
->cmdname
= proc_get_command_name(l
->pid
);
285 l
->cmdname
= xstrdup(_("(unknown)"));
287 l
->cmdname
= xstrdup(_("(undefined)"));
290 case 5: /* device major:minor and inode number */
291 inode
= get_dev_inode(tok
, &dev
);
295 l
->start
= !strcmp(tok
, "EOF") ? 0 :
296 strtou64_or_err(tok
, _("failed to parse start"));
300 /* replace '\n' character */
301 tok
[strlen(tok
)-1] = '\0';
302 l
->end
= !strcmp(tok
, "EOF") ? 0 :
303 strtou64_or_err(tok
, _("failed to parse end"));
310 l
->path
= get_filename_sz(inode
, l
->pid
, &sz
);
312 /* no permissions -- ignore */
313 if (!l
->path
&& no_inaccessible
) {
319 /* probably no permission to peek into l->pid's path */
320 l
->path
= get_fallback_filename(dev
);
325 list_add(&l
->locks
, locks
);
332 static int column_name_to_id(const char *name
, size_t namesz
)
338 for (i
= 0; i
< ARRAY_SIZE(infos
); i
++) {
339 const char *cn
= infos
[i
].name
;
341 if (!strncasecmp(name
, cn
, namesz
) && !*(cn
+ namesz
))
344 warnx(_("unknown column: %s"), name
);
348 static inline int get_column_id(int num
)
351 assert((size_t) num
< ncolumns
);
352 assert(columns
[num
] < (int) ARRAY_SIZE(infos
));
358 static inline struct colinfo
*get_column_info(unsigned num
)
360 return &infos
[ get_column_id(num
) ];
363 static pid_t
get_blocker(int id
, struct list_head
*locks
)
367 list_for_each(p
, locks
) {
368 struct lock
*l
= list_entry(p
, struct lock
, locks
);
370 if (l
->id
== id
&& !l
->blocked
)
377 static void add_scols_line(struct libscols_table
*table
, struct lock
*l
, struct list_head
*locks
)
380 struct libscols_line
*line
;
382 * Whenever cmdname or filename is NULL it is most
383 * likely because there's no read permissions
384 * for the specified process.
386 const char *notfnd
= "";
391 line
= scols_table_new_line(table
, NULL
);
393 err(EXIT_FAILURE
, _("failed to allocate output line"));
395 for (i
= 0; i
< ncolumns
; i
++) {
398 switch (get_column_id(i
)) {
400 xasprintf(&str
, "%s", l
->cmdname
? l
->cmdname
: notfnd
);
403 xasprintf(&str
, "%d", l
->pid
);
406 xasprintf(&str
, "%s", l
->type
);
412 xasprintf(&str
, "%ju", l
->size
);
414 str
= size_to_human_string(SIZE_SUFFIX_1LETTER
, l
->size
);
417 xasprintf(&str
, "%s%s", l
->mode
, l
->blocked
? "*" : "");
420 xasprintf(&str
, "%d", l
->mandatory
? 1 : 0);
423 xasprintf(&str
, "%jd", l
->start
);
426 xasprintf(&str
, "%jd", l
->end
);
429 xasprintf(&str
, "%s", l
->path
? l
->path
: notfnd
);
433 pid_t bl
= l
->blocked
&& l
->id
?
434 get_blocker(l
->id
, locks
) : 0;
436 xasprintf(&str
, "%d", (int) bl
);
442 if (str
&& scols_line_refer_data(line
, i
, str
))
443 err(EXIT_FAILURE
, _("failed to add output data"));
447 static int show_locks(struct list_head
*locks
)
451 struct list_head
*p
, *pnext
;
452 struct libscols_table
*table
;
454 table
= scols_new_table();
456 err(EXIT_FAILURE
, _("failed to allocate output table"));
458 scols_table_enable_raw(table
, raw
);
459 scols_table_enable_json(table
, json
);
460 scols_table_enable_noheadings(table
, no_headings
);
463 scols_table_set_name(table
, "locks");
465 for (i
= 0; i
< ncolumns
; i
++) {
466 struct libscols_column
*cl
;
467 struct colinfo
*col
= get_column_info(i
);
469 cl
= scols_table_new_column(table
, col
->name
, col
->whint
, col
->flags
);
471 err(EXIT_FAILURE
, _("failed to allocate output column"));
474 int id
= get_column_id(i
);
485 scols_column_set_json_type(cl
, SCOLS_JSON_NUMBER
);
488 scols_column_set_json_type(cl
, SCOLS_JSON_BOOLEAN
);
491 scols_column_set_json_type(cl
, SCOLS_JSON_STRING
);
498 /* prepare data for output */
499 list_for_each(p
, locks
) {
500 struct lock
*l
= list_entry(p
, struct lock
, locks
);
502 if (pid
&& pid
!= l
->pid
)
505 add_scols_line(table
, l
, locks
);
508 /* destroy the list */
509 list_for_each_safe(p
, pnext
, locks
) {
510 struct lock
*l
= list_entry(p
, struct lock
, locks
);
514 scols_print_table(table
);
515 scols_unref_table(table
);
520 static void __attribute__((__noreturn__
)) usage(void)
525 fputs(USAGE_HEADER
, out
);
528 _(" %s [options]\n"), program_invocation_short_name
);
530 fputs(USAGE_SEPARATOR
, out
);
531 fputs(_("List local system locks.\n"), out
);
533 fputs(USAGE_OPTIONS
, out
);
534 fputs(_(" -b, --bytes print SIZE in bytes rather than in human readable format\n"), out
);
535 fputs(_(" -J, --json use JSON output format\n"), out
);
536 fputs(_(" -i, --noinaccessible ignore locks without read permissions\n"), out
);
537 fputs(_(" -n, --noheadings don't print headings\n"), out
);
538 fputs(_(" -o, --output <list> define which output columns to use\n"), out
);
539 fputs(_(" --output-all output all columns\n"), out
);
540 fputs(_(" -p, --pid <pid> display only locks held by this process\n"), out
);
541 fputs(_(" -r, --raw use the raw output format\n"), out
);
542 fputs(_(" -u, --notruncate don't truncate text in columns\n"), out
);
544 fputs(USAGE_SEPARATOR
, out
);
545 printf(USAGE_HELP_OPTIONS(24));
547 fputs(USAGE_COLUMNS
, out
);
549 for (i
= 0; i
< ARRAY_SIZE(infos
); i
++)
550 fprintf(out
, " %11s %s\n", infos
[i
].name
, _(infos
[i
].help
));
552 printf(USAGE_MAN_TAIL("lslocks(8)"));
557 int main(int argc
, char *argv
[])
560 struct list_head locks
;
563 OPT_OUTPUT_ALL
= CHAR_MAX
+ 1
565 static const struct option long_opts
[] = {
566 { "bytes", no_argument
, NULL
, 'b' },
567 { "json", no_argument
, NULL
, 'J' },
568 { "pid", required_argument
, NULL
, 'p' },
569 { "help", no_argument
, NULL
, 'h' },
570 { "output", required_argument
, NULL
, 'o' },
571 { "output-all", no_argument
, NULL
, OPT_OUTPUT_ALL
},
572 { "notruncate", no_argument
, NULL
, 'u' },
573 { "version", no_argument
, NULL
, 'V' },
574 { "noheadings", no_argument
, NULL
, 'n' },
575 { "raw", no_argument
, NULL
, 'r' },
576 { "noinaccessible", no_argument
, NULL
, 'i' },
580 static const ul_excl_t excl
[] = { /* rows and cols in ASCII order */
584 int excl_st
[ARRAY_SIZE(excl
)] = UL_EXCL_STATUS_INIT
;
585 setlocale(LC_ALL
, "");
586 bindtextdomain(PACKAGE
, LOCALEDIR
);
588 close_stdout_atexit();
590 while ((c
= getopt_long(argc
, argv
,
591 "biJp:o:nruhV", long_opts
, NULL
)) != -1) {
593 err_exclusive_options(c
, long_opts
, excl
, excl_st
);
606 pid
= strtos32_or_err(optarg
, _("invalid PID argument"));
612 for (ncolumns
= 0; ncolumns
< ARRAY_SIZE(infos
); ncolumns
++)
613 columns
[ncolumns
] = ncolumns
;
622 disable_columns_truncate();
626 print_version(EXIT_SUCCESS
);
630 errtryhelp(EXIT_FAILURE
);
634 INIT_LIST_HEAD(&locks
);
637 /* default columns */
638 columns
[ncolumns
++] = COL_SRC
;
639 columns
[ncolumns
++] = COL_PID
;
640 columns
[ncolumns
++] = COL_TYPE
;
641 columns
[ncolumns
++] = COL_SIZE
;
642 columns
[ncolumns
++] = COL_MODE
;
643 columns
[ncolumns
++] = COL_M
;
644 columns
[ncolumns
++] = COL_START
;
645 columns
[ncolumns
++] = COL_END
;
646 columns
[ncolumns
++] = COL_PATH
;
649 if (outarg
&& string_add_to_idarray(outarg
, columns
, ARRAY_SIZE(columns
),
650 &ncolumns
, column_name_to_id
) < 0)
655 rc
= get_local_locks(&locks
);
657 if (!rc
&& !list_empty(&locks
))
658 rc
= show_locks(&locks
);
660 mnt_unref_table(tab
);