xref: /freebsd/sys/contrib/openzfs/lib/libspl/getexecname.c (revision 22649d4dba730d46244fd2dff4fd174903c8379f)
1 // SPDX-License-Identifier: CDDL-1.0
2 /*
3  * This file and its contents are supplied under the terms of the
4  * Common Development and Distribution License ("CDDL"), version 1.0.
5  * You may only use this file in accordance with the terms of version
6  * 1.0 of the CDDL.
7  *
8  * A full copy of the text of the CDDL should have accompanied this
9  * source.  A copy of the CDDL is also available via the Internet at
10  * https://opensource.org/license/CDDL-1.0.
11  */
12 /*
13  * Copyright 2007 Sun Microsystems, Inc.  All rights reserved.
14  * Use is subject to license terms.
15  */
16 
17 
18 #include <limits.h>
19 #include <pthread.h>
20 #include <stdlib.h>
21 #include <string.h>
22 #include <unistd.h>
23 #include "libspl_impl.h"
24 
25 
26 const char *
getexecname(void)27 getexecname(void)
28 {
29 	static char execname[PATH_MAX + 1] = "";
30 	static pthread_mutex_t mtx = PTHREAD_MUTEX_INITIALIZER;
31 
32 	char *ptr = execname;
33 	ssize_t rc;
34 
35 	(void) pthread_mutex_lock(&mtx);
36 
37 	if (strlen(execname) == 0) {
38 		rc = getexecname_impl(execname);
39 		if (rc == -1) {
40 			execname[0] = '\0';
41 			ptr = NULL;
42 		} else {
43 			execname[rc] = '\0';
44 		}
45 	}
46 
47 	(void) pthread_mutex_unlock(&mtx);
48 	return (ptr);
49 }
50