OSDN Git Service

Fix no pic
[uclinux-h8/uClinux-dist.git] / user / procps / pwdx.c
1 // Copyright 2004 Nicholas Miell
2 //
3 // This file may be used subject to the terms and conditions of the
4 // GNU Library General Public License Version 2 as published by the
5 // Free Software Foundation.This program is distributed in the hope
6 // that it will be useful, but WITHOUT ANY WARRANTY; without even the
7 // implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
8 // PURPOSE. See the GNU Library General Public License for more
9 // details.
10
11 #include <stdio.h>
12 #include <string.h>
13 #include <stdlib.h>
14 #include <sys/types.h>
15 #include <regex.h>
16 #include <limits.h>
17 #include <unistd.h>
18 #include <errno.h>
19
20 #include "proc/version.h"
21
22 static void die(const char *msg) NORETURN;
23 static void die(const char *msg)
24 {
25      fputs(msg, stderr);
26      exit(1);
27 }
28
29 static void version(void) NORETURN;
30 static void version(void)
31 {
32      printf("pwdx (%s)\n", procps_version);
33      exit(0);
34 }
35
36 int main(int argc, char* argv[])
37 {
38      char buf[PATH_MAX+1];
39      regex_t re;
40      int i;
41
42      if (argc < 2)
43           die("Usage: pwdx pid...\n");
44
45      // Allowed on the command line:
46      //
47      // --version
48      // -V
49      // /proc/nnnn
50      // nnnn
51      //
52      // where nnnn is any number that doesn't begin with 0.
53      //
54      // If --version or -V are present, further arguments are ignored
55      // completely.
56         
57      regcomp(&re, "^((/proc/+)?[1-9][0-9]*|-V|--version)$",
58              REG_EXTENDED|REG_NOSUB);
59
60      for (i = 1; i < argc; i++) {
61           if (regexec(&re, argv[i], 0, NULL, 0) != 0) {
62                snprintf(buf, sizeof buf, "pwdx: invalid process id: %s\n", argv[i]);
63                die(buf);
64           }
65           if (!strcmp("-V", argv[i]) || !strcmp("--version", argv[i]))
66                version();
67      }
68
69      regfree(&re);
70
71      for (i = 1; i < argc; i++) {
72           char * s = buf;
73           int len;
74           
75           // At this point, all arguments are in the form /proc/nnnn
76           // or nnnn, so a simple check based on the first char is
77           // possible
78           if (argv[i][0] != '/')
79                snprintf(buf, sizeof buf, "/proc/%s/cwd", argv[i]);
80           else
81                snprintf(buf, sizeof buf, "%s/cwd", argv[i]);
82
83           // buf contains /proc/nnnn/cwd symlink name on entry, the
84           // target of that symlink on return
85           if ((len = readlink(buf, buf, PATH_MAX)) < 0) {
86                s = strerror(errno == ENOENT ? ESRCH : errno);
87           } else {
88                buf[len] = 0;
89           }
90
91           printf("%s: %s\n", argv[i], s);
92      }
93
94      return 0;
95 }