Plan 9 from Bell Labs’s /usr/web/sources/contrib/andrey/cmd/lsof.c

Copyright © 2021 Plan 9 Foundation.
Distributed under the MIT License.
Download the Plan 9 distribution.


#include <u.h>
#include <libc.h>
#include <bio.h>

#define NAMELEN 28

void	lsof(char*);
void	error(char*);
int	cmp(void*, void*);

Biobuf	bout;

void
main(int argc, char *argv[])
{
	int fd, i, tot, none = 1;
	Dir *dir, **mem;

	Binit(&bout, 1, OWRITE);
	if(chdir("/proc")==-1)
		error("/proc");

	if(argc > 1) {
		while(--argc && ++argv)
			lsof(*argv);
		exits(0);
	}

	fd=open(".", OREAD);
	if(fd<0)
		error("/proc");
	tot = dirreadall(fd, &dir);
	if(tot <= 0){
		fprint(2, "ps: empty directory /proc\n");
		exits("empty");
	}
	mem = malloc(tot*sizeof(Dir*));
	for(i=0; i<tot; i++)
		mem[i] = dir++;

	qsort(mem, tot, sizeof(Dir*), cmp);
	for(i=0; i<tot; i++){
		lsof(mem[i]->name);
		none = 0;
	}

	if(none)
		error("no processes; bad #p");
	exits(0);
}

void
lsof(char *s)
{
	char buf[64];
	Biobuf *bfd;
	char *p;

	sprint(buf, "%s/fd", s);
	bfd = Bopen(buf, OREAD);
	if(bfd == 0)
		return;

	if((p = Brdstr(bfd, '\n', 0)) != nil)		/* skip cwd */
		free(p);
	while((p = Brdstr(bfd, '\n', 0)) != nil) {
		Bprint(&bout, "%-8s %s", s, p+2);
		free(p);
	}
	Bterm(bfd);
}

void
error(char *s)
{
	fprint(2, "lsof: %s: ", s);
	perror("error");
	exits(s);
}

int
cmp(void *va, void *vb)
{
	Dir **a, **b;

	a = va;
	b = vb;
	return atoi((*a)->name) - atoi((*b)->name);
}

Bell Labs OSI certified Powered by Plan 9

(Return to Plan 9 Home Page)

Copyright © 2021 Plan 9 Foundation. All Rights Reserved.
Comments to [email protected].