~jkaivo/getprogname

655f41b76907269af71fd67a87cbe0391b90a99f — Jakob Kaivo 2 years ago 289a943
initial commit of code
3 files changed, 41 insertions(+), 0 deletions(-)

A .gitignore
A getprogname.c
A getprogname.h
A .gitignore => .gitignore +3 -0
@@ 0,0 1,3 @@
*.o
*.so
*.a

A getprogname.c => getprogname.c +29 -0
@@ 0,0 1,29 @@
#define _POSIX_C_SOURCE 2
#include <limits.h>
#include <stdio.h>
#include <unistd.h>

char *get_program_name(size_t n, char buf[static n])
{
	char cmd[_POSIX_ARG_MAX];
	snprintf(cmd, sizeof(cmd), "ps -p %ld -o comm=", (long)getpid());

	FILE *pip = popen(cmd, "r");
	if (pip == NULL) {
		return NULL;
	}

	if (fscanf(pip, "%s", buf) != 1) {
		pclose(pip);
		return NULL;
	}

	pclose(pip);
	return buf;
}

char *getprogname(void)
{
	static char progname[_POSIX_NAME_MAX];
	return get_program_name(sizeof(progname), progname);
}

A getprogname.h => getprogname.h +9 -0
@@ 0,0 1,9 @@
#ifndef GETPROGNAME_H
#define GETPROGNAME_H

#include <stddef.h>

char *get_program_name(size_t n, char buf[static n]);
char *getprogname(void);

#endif