comparison base/System.cpp @ 101:ce1d385f4f89

* Use kill(pid, 0) instead of /proc or sysctl blather for looking up pids * Add OpenProcess call for Win32
author Chris Cannam
date Fri, 05 May 2006 12:34:51 +0000
parents 604bd4ee3ed4
children 173b39ea0728
comparison
equal deleted inserted replaced
100:2b1a16e38d2d 101:ce1d385f4f89
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 17
18 #ifdef __APPLE__
19 #include <sys/types.h>
20 #include <sys/sysctl.h>
21 #else
22 #ifndef _WIN32 18 #ifndef _WIN32
23 #include <unistd.h> 19 #include <signal.h>
24 #include <cstdio>
25 #include <sys/types.h>
26 #include <sys/stat.h>
27 #include <errno.h>
28 #endif
29 #endif 20 #endif
30 21
31 #include <iostream> 22 #include <iostream>
32 23
33 #ifdef _WIN32 24 #ifdef _WIN32
51 #endif 42 #endif
52 43
53 ProcessStatus 44 ProcessStatus
54 GetProcessStatus(int pid) 45 GetProcessStatus(int pid)
55 { 46 {
56 #ifdef __APPLE__ 47 #ifdef _WIN32
57 48 DWORD handle = OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, pid);
58 // See 49 if (!handle) {
59 // http://tuvix.apple.com/documentation/Darwin/Reference/ManPages/man3/sysctl.3.html 50 return ProcessNotRunning;
60 // http://developer.apple.com/qa/qa2001/qa1123.html 51 } else {
61 52 CloseHandle(handle);
62 int name[] = { CTL_KERN, KERN_PROC, KERN_PROC_PID, 0, 0 }; 53 return ProcessRunning;
63 name[3] = pid; 54 }
64 55 #else
65 int err; 56 if (kill(getpid(), 0) == 0) {
66 size_t length = 0; 57 if (kill(pid, 0) == 0) {
67 58 return ProcessRunning;
68 if (sysctl(name, 4, 0, &length, 0, 0)) { 59 } else {
69 perror("GetProcessStatus: sysctl failed"); 60 return ProcessNotRunning;
61 }
62 } else {
70 return UnknownProcessStatus; 63 return UnknownProcessStatus;
71 } 64 }
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 65 #endif
117 } 66 }
118 67