comparison base/System.cpp @ 98:604bd4ee3ed4

* Add a method in System.{cpp,h} to try to establish whether a process of a given pid is running or not * Make TempDirectory store its process ID, and clean up any old temporary directories it finds that correspond to non-running processes
author Chris Cannam
date Fri, 05 May 2006 11:28:04 +0000
parents d397ea0a79f5
children ce1d385f4f89
comparison
equal deleted inserted replaced
97:22494cc28c9f 98:604bd4ee3ed4
12 License, or (at your option) any later version. See the file 12 License, or (at your option) any later version. See the file
13 COPYING included with this distribution for more information. 13 COPYING included with this distribution for more information.
14 */ 14 */
15 15
16 #include "System.h" 16 #include "System.h"
17
18 #ifdef __APPLE__
19 #include <sys/types.h>
20 #include <sys/sysctl.h>
21 #else
22 #ifndef _WIN32
23 #include <unistd.h>
24 #include <cstdio>
25 #include <sys/types.h>
26 #include <sys/stat.h>
27 #include <errno.h>
28 #endif
29 #endif
30
31 #include <iostream>
17 32
18 #ifdef _WIN32 33 #ifdef _WIN32
19 34
20 extern "C" { 35 extern "C" {
21 36
32 } 47 }
33 48
34 } 49 }
35 50
36 #endif 51 #endif
52
53 ProcessStatus
54 GetProcessStatus(int pid)
55 {
56 #ifdef __APPLE__
57
58 // See
59 // http://tuvix.apple.com/documentation/Darwin/Reference/ManPages/man3/sysctl.3.html
60 // http://developer.apple.com/qa/qa2001/qa1123.html
61
62 int name[] = { CTL_KERN, KERN_PROC, KERN_PROC_PID, 0, 0 };
63 name[3] = pid;
64
65 int err;
66 size_t length = 0;
67
68 if (sysctl(name, 4, 0, &length, 0, 0)) {
69 perror("GetProcessStatus: sysctl failed");
70 return UnknownProcessStatus;
71 }
72
73 if (length > 0) return ProcessRunning;
74 else return ProcessNotRunning;
75
76 #elsif _WIN32
77
78 return UnknownProcessStatus;
79
80 #else
81
82 char filename[50];
83 struct stat statbuf;
84
85 // Looking up the pid in /proc is worth a try on any POSIX system,
86 // I guess -- it'll always compile and it won't return false
87 // negatives if we do this first check:
88
89 sprintf(filename, "/proc/%d", (int)getpid());
90
91 int err = stat(filename, &statbuf);
92
93 if (err || !S_ISDIR(statbuf.st_mode)) {
94 // If we can't even use it to tell whether we're running or
95 // not, then clearly /proc is no use on this system.
96 return UnknownProcessStatus;
97 }
98
99 sprintf(filename, "/proc/%d", (int)pid);
100
101 err = stat(filename, &statbuf);
102
103 if (!err) {
104 if (S_ISDIR(statbuf.st_mode)) {
105 return ProcessRunning;
106 } else {
107 return UnknownProcessStatus;
108 }
109 } else if (errno == ENOENT) {
110 return ProcessNotRunning;
111 } else {
112 perror("stat failed");
113 return UnknownProcessStatus;
114 }
115
116 #endif
117 }
118