1 /*
2 * CDDL HEADER START
3 *
4 * The contents of this file are subject to the terms of the
5 * Common Development and Distribution License, Version 1.0 only
6 * (the "License"). You may not use this file except in compliance
7 * with the License.
8 *
9 * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
10 * or http://www.opensolaris.org/os/licensing.
11 * See the License for the specific language governing permissions
12 * and limitations under the License.
13 *
14 * When distributing Covered Code, include this CDDL HEADER in each
15 * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
16 * If applicable, add the following below this CDDL HEADER, with the
17 * fields enclosed by brackets "[]" replaced with your own identifying
18 * information: Portions Copyright [yyyy] [name of copyright owner]
19 *
20 * CDDL HEADER END
21 */
22
23
24 #include <errno.h>
25 #include <limits.h>
26 #include <pthread.h>
27 #include <stdlib.h>
28 #include <string.h>
29 #include <sys/param.h>
30 #include <sys/sysctl.h>
31 #include <sys/types.h>
32 #include <unistd.h>
33
34 const char *
getexecname(void)35 getexecname(void)
36 {
37 static char execname[PATH_MAX + 1] = "";
38 static pthread_mutex_t mtx = PTHREAD_MUTEX_INITIALIZER;
39 char *ptr = NULL;
40 ssize_t rc;
41
42 (void) pthread_mutex_lock(&mtx);
43
44 if (strlen(execname) == 0) {
45 int error, name[4];
46 size_t len;
47
48 name[0] = CTL_KERN;
49 name[1] = KERN_PROC;
50 name[2] = KERN_PROC_PATHNAME;
51 name[3] = -1;
52 len = PATH_MAX;
53 error = sysctl(name, nitems(name), execname, &len, NULL, 0);
54 if (error != 0) {
55 rc = -1;
56 } else {
57 rc = len;
58 }
59 if (rc == -1) {
60 execname[0] = '\0';
61 } else {
62 execname[rc] = '\0';
63 ptr = execname;
64 }
65 } else {
66 ptr = execname;
67 }
68
69 (void) pthread_mutex_unlock(&mtx);
70 return (ptr);
71 }
72