Logo ROOT   6.08/02
Reference Guide
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Properties Friends Macros Groups Pages
TUnixSystem.cxx
Go to the documentation of this file.
1 // @(#)root/unix:$Id: 887c618d89c4ed436e4034fc133f468fecad651b $
2 // Author: Fons Rademakers 15/09/95
3 
4 /*************************************************************************
5  * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. *
6  * All rights reserved. *
7  * *
8  * For the licensing terms see $ROOTSYS/LICENSE. *
9  * For the list of contributors see $ROOTSYS/README/CREDITS. *
10  *************************************************************************/
11 
12 //////////////////////////////////////////////////////////////////////////
13 // //
14 // TUnixSystem //
15 // //
16 // Class providing an interface to the UNIX Operating System. //
17 // //
18 //////////////////////////////////////////////////////////////////////////
19 
20 #include "RConfigure.h"
21 #include "RConfig.h"
22 #include "TUnixSystem.h"
23 #include "TROOT.h"
24 #include "TError.h"
25 #include "TOrdCollection.h"
26 #include "TRegexp.h"
27 #include "TPRegexp.h"
28 #include "TException.h"
29 #include "Demangle.h"
30 #include "TEnv.h"
31 #include "TSocket.h"
32 #include "Getline.h"
33 #include "TInterpreter.h"
34 #include "TApplication.h"
35 #include "TObjString.h"
36 #include "Riostream.h"
37 #include "TVirtualMutex.h"
38 #include "TObjArray.h"
39 #include <map>
40 #include <algorithm>
41 #include <atomic>
42 
43 //#define G__OLDEXPAND
44 
45 #include <unistd.h>
46 #include <stdlib.h>
47 #include <sys/types.h>
48 #if defined(R__SUN) || defined(R__AIX) || \
49  defined(R__LINUX) || defined(R__SOLARIS) || \
50  defined(R__FBSD) || defined(R__OBSD) || \
51  defined(R__MACOSX) || defined(R__HURD)
52 #define HAS_DIRENT
53 #endif
54 #ifdef HAS_DIRENT
55 # include <dirent.h>
56 #else
57 # include <sys/dir.h>
58 #endif
59 #if defined(ULTRIX) || defined(R__SUN)
60 # include <sgtty.h>
61 #endif
62 #if defined(R__AIX) || defined(R__LINUX) || \
63  defined(R__FBSD) || defined(R__OBSD) || \
64  defined(R__LYNXOS) || defined(R__MACOSX) || defined(R__HURD)
65 # include <sys/ioctl.h>
66 #endif
67 #if defined(R__AIX) || defined(R__SOLARIS)
68 # include <sys/select.h>
69 #endif
70 #if defined(R__LINUX) || defined(R__HURD)
71 # ifndef SIGSYS
72 # define SIGSYS SIGUNUSED // SIGSYS does not exist in linux ??
73 # endif
74 #endif
75 #if defined(R__MACOSX)
76 # include <mach-o/dyld.h>
77 # include <sys/mount.h>
78  extern "C" int statfs(const char *file, struct statfs *buffer);
79 #elif defined(R__LINUX) || defined(R__HURD)
80 # include <sys/vfs.h>
81 #elif defined(R__FBSD) || defined(R__OBSD)
82 # include <sys/param.h>
83 # include <sys/mount.h>
84 #else
85 # include <sys/statfs.h>
86 #endif
87 
88 #include <utime.h>
89 #include <syslog.h>
90 #include <sys/stat.h>
91 #include <setjmp.h>
92 #include <signal.h>
93 #include <sys/param.h>
94 #include <pwd.h>
95 #include <grp.h>
96 #include <errno.h>
97 #include <sys/resource.h>
98 #include <sys/wait.h>
99 #include <time.h>
100 #include <sys/time.h>
101 #include <sys/file.h>
102 #include <sys/socket.h>
103 #include <netinet/in.h>
104 #include <netinet/tcp.h>
105 #if defined(R__AIX)
106 # define _XOPEN_EXTENDED_SOURCE
107 # include <arpa/inet.h>
108 # undef _XOPEN_EXTENDED_SOURCE
109 # if !defined(_AIX41) && !defined(_AIX43)
110  // AIX 3.2 doesn't have it
111 # define HASNOT_INETATON
112 # endif
113 #else
114 # include <arpa/inet.h>
115 #endif
116 #include <sys/un.h>
117 #include <netdb.h>
118 #include <fcntl.h>
119 #if defined(R__SOLARIS)
120 # include <sys/systeminfo.h>
121 # include <sys/filio.h>
122 # include <sys/sockio.h>
123 # define HASNOT_INETATON
124 # ifndef INADDR_NONE
125 # define INADDR_NONE (UInt_t)-1
126 # endif
127 #endif
128 
129 #if defined(R__SOLARIS)
130 # define HAVE_UTMPX_H
131 # define UTMP_NO_ADDR
132 #endif
133 
134 #if defined(MAC_OS_X_VERSION_10_5)
135 # define HAVE_UTMPX_H
136 # define UTMP_NO_ADDR
137 #endif
138 
139 #if defined(R__FBSD)
140 # include <sys/param.h>
141 # if __FreeBSD_version >= 900007
142 # define HAVE_UTMPX_H
143 # endif
144 #endif
145 
146 #if defined(R__AIX) || defined(R__FBSD) || \
147  defined(R__OBSD) || defined(R__LYNXOS) || \
148  (defined(R__MACOSX) && !defined(MAC_OS_X_VERSION_10_5))
149 # define UTMP_NO_ADDR
150 #endif
151 
152 #if (defined(R__AIX) && !defined(_AIX43)) || \
153  (defined(R__SUNGCC3) && !defined(__arch64__))
154 # define USE_SIZE_T
155 #elif defined(R__GLIBC) || defined(R__FBSD) || \
156  (defined(R__SUNGCC3) && defined(__arch64__)) || \
157  defined(R__OBSD) || defined(MAC_OS_X_VERSION_10_4) || \
158  (defined(R__AIX) && defined(_AIX43)) || \
159  (defined(R__SOLARIS) && defined(_SOCKLEN_T))
160 # define USE_SOCKLEN_T
161 #endif
162 
163 #if defined(R__LYNXOS)
164 extern "C" {
165  extern int putenv(const char *);
166  extern int inet_aton(const char *, struct in_addr *);
167 };
168 #endif
169 
170 #ifdef HAVE_UTMPX_H
171 #include <utmpx.h>
172 #define STRUCT_UTMP struct utmpx
173 #else
174 #include <utmp.h>
175 #define STRUCT_UTMP struct utmp
176 #endif
177 #if !defined(UTMP_FILE) && defined(_PATH_UTMP) // 4.4BSD
178 #define UTMP_FILE _PATH_UTMP
179 #endif
180 #if defined(UTMPX_FILE) // Solaris, SysVr4
181 #undef UTMP_FILE
182 #define UTMP_FILE UTMPX_FILE
183 #endif
184 #ifndef UTMP_FILE
185 #define UTMP_FILE "/etc/utmp"
186 #endif
187 
188 // stack trace code
189 #if (defined(R__LINUX) || defined(R__HURD)) && !defined(R__WINGCC)
190 # if __GLIBC__ == 2 && __GLIBC_MINOR__ >= 1
191 # define HAVE_BACKTRACE_SYMBOLS_FD
192 # endif
193 # define HAVE_DLADDR
194 #endif
195 #if defined(R__MACOSX)
196 # define HAVE_BACKTRACE_SYMBOLS_FD
197 # define HAVE_DLADDR
198 #endif
199 
200 #ifdef HAVE_BACKTRACE_SYMBOLS_FD
201 # include <execinfo.h>
202 #endif
203 #ifdef HAVE_DLADDR
204 # ifndef __USE_GNU
205 # define __USE_GNU
206 # endif
207 # include <dlfcn.h>
208 #endif
209 
210 #ifdef HAVE_BACKTRACE_SYMBOLS_FD
211  // The maximum stack trace depth for systems where we request the
212  // stack depth separately (currently glibc-based systems).
213  static const int kMAX_BACKTRACE_DEPTH = 128;
214 #endif
215 
216 // FPE handling includes
217 #if (defined(R__LINUX) && !defined(R__WINGCC))
218 #include <fpu_control.h>
219 #include <fenv.h>
220 #include <sys/prctl.h> // for prctl() function used in StackTrace()
221 #endif
222 
223 #if defined(R__MACOSX) && defined(__SSE2__)
224 #include <xmmintrin.h>
225 #endif
226 
227 #if defined(R__MACOSX) && !defined(__SSE2__) && !defined(__xlC__) && \
228  !defined(__i386__) && !defined(__x86_64__) && !defined(__arm__) && \
229  !defined(__arm64__)
230 #include <fenv.h>
231 #include <signal.h>
232 #include <ucontext.h>
233 #include <stdlib.h>
234 #include <stdio.h>
235 #include <mach/thread_status.h>
236 
237 #define fegetenvd(x) asm volatile("mffs %0" : "=f" (x));
238 #define fesetenvd(x) asm volatile("mtfsf 255,%0" : : "f" (x));
239 
240 enum {
241  FE_ENABLE_INEXACT = 0x00000008,
242  FE_ENABLE_DIVBYZERO = 0x00000010,
243  FE_ENABLE_UNDERFLOW = 0x00000020,
244  FE_ENABLE_OVERFLOW = 0x00000040,
245  FE_ENABLE_INVALID = 0x00000080,
246  FE_ENABLE_ALL_EXCEPT = 0x000000F8
247 };
248 #endif
249 
250 #if defined(R__MACOSX) && !defined(__SSE2__) && \
251  (defined(__i386__) || defined(__x86_64__) || defined(__arm__) || defined(__arm64__))
252 #include <fenv.h>
253 #endif
254 // End FPE handling includes
255 
256 namespace {
257  // Depending on the platform the struct utmp (or utmpx) has either ut_name or ut_user
258  // which are semantically equivalent. Instead of using preprocessor magic,
259  // which is bothersome for cxx modules use SFINAE.
260 
261  template<typename T>
262  struct ut_name {
263  template<typename U = T, typename std::enable_if<std::is_member_pointer<decltype(&U::ut_name)>::value, int>::type = 0>
264  static char getValue(U* ue, int) {
265  return ue->ut_name[0];
266  }
267 
268  template<typename U = T, typename std::enable_if<std::is_member_pointer<decltype(&U::ut_user)>::value, int>::type = 0>
269  static char getValue(U* ue, long) {
270  return ue->ut_user[0];
271  }
272  };
273 
274  static char get_ut_name(STRUCT_UTMP *ue) {
275  // 0 is an integer literal forcing an overload pickup in case both ut_name and ut_user are present.
276  return ut_name<STRUCT_UTMP>::getValue(ue, 0);
277  }
278 }
279 
280 struct TUtmpContent {
281  STRUCT_UTMP *fUtmpContents;
282  UInt_t fEntries; // Number of entries in utmp file.
283 
284  TUtmpContent() : fUtmpContents(0), fEntries(0) {}
285  ~TUtmpContent() { free(fUtmpContents); }
286 
287  STRUCT_UTMP *SearchUtmpEntry(const char *tty)
288  {
289  // Look for utmp entry which is connected to terminal tty.
290 
291  STRUCT_UTMP *ue = fUtmpContents;
292 
293  UInt_t n = fEntries;
294  while (n--) {
295  if (get_ut_name(ue) && !strncmp(tty, ue->ut_line, sizeof(ue->ut_line)))
296  return ue;
297  ue++;
298  }
299  return 0;
300  }
301 
302  int ReadUtmpFile()
303  {
304  // Read utmp file. Returns number of entries in utmp file.
305 
306  FILE *utmp;
307  struct stat file_stats;
308  size_t n_read, size;
309 
310  fEntries = 0;
311 
313 
314  utmp = fopen(UTMP_FILE, "r");
315  if (!utmp)
316  return 0;
317 
318  if (fstat(fileno(utmp), &file_stats) == -1) {
319  fclose(utmp);
320  return 0;
321  }
322  size = file_stats.st_size;
323  if (size <= 0) {
324  fclose(utmp);
325  return 0;
326  }
327 
328  fUtmpContents = (STRUCT_UTMP *) malloc(size);
329  if (!fUtmpContents) {
330  fclose(utmp);
331  return 0;
332  }
333 
334  n_read = fread(fUtmpContents, 1, size, utmp);
335  if (!ferror(utmp)) {
336  if (fclose(utmp) != EOF && n_read == size) {
337  fEntries = size / sizeof(STRUCT_UTMP);
338  return fEntries;
339  }
340  } else
341  fclose(utmp);
342 
343  free(fUtmpContents);
344  fUtmpContents = 0;
345  return 0;
346  }
347 
348 };
349 
350 const char *kServerPath = "/tmp";
351 const char *kProtocolName = "tcp";
352 
353 //------------------- Unix TFdSet ----------------------------------------------
354 #ifndef HOWMANY
355 # define HOWMANY(x, y) (((x)+((y)-1))/(y))
356 #endif
357 
358 const Int_t kNFDBITS = (sizeof(Long_t) * 8); // 8 bits per byte
359 #ifdef FD_SETSIZE
360 const Int_t kFDSETSIZE = FD_SETSIZE; // Linux = 1024 file descriptors
361 #else
362 const Int_t kFDSETSIZE = 256; // upto 256 file descriptors
363 #endif
364 
365 
366 class TFdSet {
367 private:
368  ULong_t fds_bits[HOWMANY(kFDSETSIZE, kNFDBITS)];
369 public:
370  TFdSet() { memset(fds_bits, 0, sizeof(fds_bits)); }
371  TFdSet(const TFdSet &org) { memcpy(fds_bits, org.fds_bits, sizeof(org.fds_bits)); }
372  TFdSet &operator=(const TFdSet &rhs) { if (this != &rhs) { memcpy(fds_bits, rhs.fds_bits, sizeof(rhs.fds_bits));} return *this; }
373  void Zero() { memset(fds_bits, 0, sizeof(fds_bits)); }
374  void Set(Int_t n)
375  {
376  if (n >= 0 && n < kFDSETSIZE) {
377  fds_bits[n/kNFDBITS] |= (1UL << (n % kNFDBITS));
378  } else {
379  ::Fatal("TFdSet::Set","fd (%d) out of range [0..%d]", n, kFDSETSIZE-1);
380  }
381  }
382  void Clr(Int_t n)
383  {
384  if (n >= 0 && n < kFDSETSIZE) {
385  fds_bits[n/kNFDBITS] &= ~(1UL << (n % kNFDBITS));
386  } else {
387  ::Fatal("TFdSet::Clr","fd (%d) out of range [0..%d]", n, kFDSETSIZE-1);
388  }
389  }
390  Int_t IsSet(Int_t n)
391  {
392  if (n >= 0 && n < kFDSETSIZE) {
393  return (fds_bits[n/kNFDBITS] & (1UL << (n % kNFDBITS))) != 0;
394  } else {
395  ::Fatal("TFdSet::IsSet","fd (%d) out of range [0..%d]", n, kFDSETSIZE-1);
396  return 0;
397  }
398  }
399  ULong_t *GetBits() { return (ULong_t *)fds_bits; }
400 };
401 
402 ////////////////////////////////////////////////////////////////////////////////
403 /// Unix signal handler.
404 
405 static void SigHandler(ESignals sig)
406 {
407  if (gSystem)
408  ((TUnixSystem*)gSystem)->DispatchSignals(sig);
409 }
410 
411 ////////////////////////////////////////////////////////////////////////////////
412 
413 static const char *GetExePath()
414 {
415  TTHREAD_TLS_DECL(TString,exepath);
416  if (exepath == "") {
417 #if defined(R__MACOSX)
418  exepath = _dyld_get_image_name(0);
419 #elif defined(R__LINUX) || defined(R__SOLARIS) || defined(R__FBSD)
420  char buf[kMAXPATHLEN]; // exe path name
421 
422  // get the name from the link in /proc
423 #if defined(R__LINUX)
424  int ret = readlink("/proc/self/exe", buf, kMAXPATHLEN);
425 #elif defined(R__SOLARIS)
426  int ret = readlink("/proc/self/path/a.out", buf, kMAXPATHLEN);
427 #elif defined(R__FBSD)
428  int ret = readlink("/proc/curproc/file", buf, kMAXPATHLEN);
429 #endif
430  if (ret > 0 && ret < kMAXPATHLEN) {
431  buf[ret] = 0;
432  exepath = buf;
433  }
434 #else
435  if (!gApplication)
436  return exepath;
437  TString p = gApplication->Argv(0);
438  if (p.BeginsWith("/"))
439  exepath = p;
440  else if (p.Contains("/")) {
441  exepath = gSystem->WorkingDirectory();
442  exepath += "/";
443  exepath += p;
444  } else {
445  char *exe = gSystem->Which(gSystem->Getenv("PATH"), p, kExecutePermission);
446  if (exe) {
447  exepath = exe;
448  delete [] exe;
449  }
450  }
451 #endif
452  }
453  return exepath;
454 }
455 
456 #if defined(HAVE_DLADDR) && !defined(R__MACOSX)
457 ////////////////////////////////////////////////////////////////////////////////
458 
459 static void SetRootSys()
460 {
461 #ifdef ROOTPREFIX
462  if (gSystem->Getenv("ROOTIGNOREPREFIX")) {
463 #endif
464  void *addr = (void *)SetRootSys;
465  Dl_info info;
466  if (dladdr(addr, &info) && info.dli_fname && info.dli_fname[0]) {
467  char respath[kMAXPATHLEN];
468  if (!realpath(info.dli_fname, respath)) {
469  if (!gSystem->Getenv("ROOTSYS"))
470  ::SysError("TUnixSystem::SetRootSys", "error getting realpath of libCore, please set ROOTSYS in the shell");
471  } else {
472  TString rs = gSystem->DirName(respath);
473  gSystem->Setenv("ROOTSYS", gSystem->DirName(rs));
474  }
475  }
476 #ifdef ROOTPREFIX
477  }
478 #endif
479 }
480 #endif
481 
482 #if defined(R__MACOSX)
483 static TString gLinkedDylibs;
484 
485 ////////////////////////////////////////////////////////////////////////////////
486 
487 static void DylibAdded(const struct mach_header *mh, intptr_t /* vmaddr_slide */)
488 {
489  static int i = 0;
490  static Bool_t gotFirstSo = kFALSE;
491  static TString linkedDylibs;
492 
493  // to copy the local linkedDylibs to the global gLinkedDylibs call this
494  // function with mh==0
495  if (!mh) {
496  gLinkedDylibs = linkedDylibs;
497  return;
498  }
499 
500  TString lib = _dyld_get_image_name(i++);
501 
502  TRegexp sovers = "libCore\\.[0-9]+\\.*[0-9]*\\.so";
503  TRegexp dyvers = "libCore\\.[0-9]+\\.*[0-9]*\\.dylib";
504 
505 #ifdef ROOTPREFIX
506  if (gSystem->Getenv("ROOTIGNOREPREFIX")) {
507 #endif
508 #if TARGET_OS_IPHONE || TARGET_IPHONE_SIMULATOR
509  // first loaded is the app so set ROOTSYS to app bundle
510  if (i == 1) {
511  char respath[kMAXPATHLEN];
512  if (!realpath(lib, respath)) {
513  if (!gSystem->Getenv("ROOTSYS"))
514  ::SysError("TUnixSystem::DylibAdded", "error getting realpath of %s", gSystem->BaseName(lib));
515  } else {
516  TString rs = gSystem->DirName(respath);
517  gSystem->Setenv("ROOTSYS", rs);
518  }
519  }
520 #else
521  if (lib.EndsWith("libCore.dylib") || lib.EndsWith("libCore.so") ||
522  lib.Index(sovers) != kNPOS || lib.Index(dyvers) != kNPOS) {
523  char respath[kMAXPATHLEN];
524  if (!realpath(lib, respath)) {
525  if (!gSystem->Getenv("ROOTSYS"))
526  ::SysError("TUnixSystem::DylibAdded", "error getting realpath of libCore, please set ROOTSYS in the shell");
527  } else {
528  TString rs = gSystem->DirName(respath);
529  gSystem->Setenv("ROOTSYS", gSystem->DirName(rs));
530  }
531  }
532 #endif
533 #ifdef ROOTPREFIX
534  }
535 #endif
536 
537  // when libSystem.B.dylib is loaded we have finished loading all dylibs
538  // explicitly linked against the executable. Additional dylibs
539  // come when they are explicitly linked against loaded so's, currently
540  // we are not interested in these
541  if (lib.EndsWith("/libSystem.B.dylib"))
542  gotFirstSo = kTRUE;
543 
544  // add all libs loaded before libSystem.B.dylib
545  if (!gotFirstSo && (lib.EndsWith(".dylib") || lib.EndsWith(".so"))) {
546  sovers = "\\.[0-9]+\\.*[0-9]*\\.so";
547  Ssiz_t idx = lib.Index(sovers);
548  if (idx != kNPOS) {
549  lib.Remove(idx);
550  lib += ".so";
551  }
552  dyvers = "\\.[0-9]+\\.*[0-9]*\\.dylib";
553  idx = lib.Index(dyvers);
554  if (idx != kNPOS) {
555  lib.Remove(idx);
556  lib += ".dylib";
557  }
558  if (!gSystem->AccessPathName(lib, kReadPermission)) {
559  if (linkedDylibs.Length())
560  linkedDylibs += " ";
561  linkedDylibs += lib;
562  }
563  }
564 }
565 #endif
566 
568 
569 ////////////////////////////////////////////////////////////////////////////////
570 
571 TUnixSystem::TUnixSystem() : TSystem("Unix", "Unix System")
572 { }
573 
574 ////////////////////////////////////////////////////////////////////////////////
575 /// Reset to original state.
576 
578 {
580 
581  delete fReadmask;
582  delete fWritemask;
583  delete fReadready;
584  delete fWriteready;
585  delete fSignals;
586 }
587 
588 ////////////////////////////////////////////////////////////////////////////////
589 /// Initialize Unix system interface.
590 
592 {
593  if (TSystem::Init())
594  return kTRUE;
595 
596  fReadmask = new TFdSet;
597  fWritemask = new TFdSet;
598  fReadready = new TFdSet;
599  fWriteready = new TFdSet;
600  fSignals = new TFdSet;
601 
602  //--- install default handlers
613 
614 #if defined(R__MACOSX)
615  // trap loading of all dylibs to register dylib name,
616  // sets also ROOTSYS if built without ROOTPREFIX
617  _dyld_register_func_for_add_image(DylibAdded);
618 #elif defined(HAVE_DLADDR)
619  SetRootSys();
620 #endif
621 
622  // This is a fallback in case TROOT::GetRootSys() can't determine ROOTSYS
623  gRootDir = "/usr/local/root";
624 
625  return kFALSE;
626 }
627 
628 //---- Misc --------------------------------------------------------------------
629 
630 ////////////////////////////////////////////////////////////////////////////////
631 /// Set the application name (from command line, argv[0]) and copy it in
632 /// gProgName. Copy the application pathname in gProgPath.
633 /// If name is 0 let the system set the actual executable name and path
634 /// (works on MacOS X and Linux).
635 
637 {
638  if (gProgName)
639  delete [] gProgName;
640  if (gProgPath)
641  delete [] gProgPath;
642 
643  if (!name || !*name) {
644  name = GetExePath();
645  gProgName = StrDup(BaseName(name));
646  gProgPath = StrDup(DirName(name));
647  } else {
648  gProgName = StrDup(BaseName(name));
649  char *w = Which(Getenv("PATH"), gProgName);
650  gProgPath = StrDup(DirName(w));
651  delete [] w;
652  }
653 }
654 
655 ////////////////////////////////////////////////////////////////////////////////
656 /// Set DISPLAY environment variable based on utmp entry. Only for UNIX.
657 
659 {
660  if (!Getenv("DISPLAY")) {
661  char *tty = ::ttyname(0); // device user is logged in on
662  if (tty) {
663  tty += 5; // remove "/dev/"
664 
665  TUtmpContent utmp;
666  utmp.ReadUtmpFile();
667 
668  STRUCT_UTMP *utmp_entry = utmp.SearchUtmpEntry(tty);
669  if (utmp_entry) {
670  if (utmp_entry->ut_host[0]) {
671  if (strchr(utmp_entry->ut_host, ':')) {
672  Setenv("DISPLAY", utmp_entry->ut_host);
673  Warning("SetDisplay", "DISPLAY not set, setting it to %s",
674  utmp_entry->ut_host);
675  } else {
676  char disp[64];
677  snprintf(disp, sizeof(disp), "%s:0.0", utmp_entry->ut_host);
678  Setenv("DISPLAY", disp);
679  Warning("SetDisplay", "DISPLAY not set, setting it to %s",
680  disp);
681  }
682  }
683 #ifndef UTMP_NO_ADDR
684  else if (utmp_entry->ut_addr) {
685 
686  struct sockaddr_in addr;
687  addr.sin_family = AF_INET;
688  addr.sin_port = 0;
689  memcpy(&addr.sin_addr, &utmp_entry->ut_addr, sizeof(addr.sin_addr));
690  memset(&addr.sin_zero[0], 0, sizeof(addr.sin_zero));
691  struct sockaddr *sa = (struct sockaddr *) &addr; // input
692 
693  char hbuf[NI_MAXHOST];
694  if (getnameinfo(sa, sizeof(struct sockaddr), hbuf, sizeof(hbuf), nullptr, 0, NI_NAMEREQD) == 0) {
695  char disp[64];
696  snprintf(disp, sizeof(disp), "%s:0.0", hbuf);
697  Setenv("DISPLAY", disp);
698  Warning("SetDisplay", "DISPLAY not set, setting it to %s",
699  disp);
700  }
701  }
702 #endif
703  }
704  }
705  }
706 }
707 
708 ////////////////////////////////////////////////////////////////////////////////
709 /// Return system error string.
710 
712 {
713  Int_t err = GetErrno();
714  if (err == 0 && GetLastErrorString() != "")
715  return GetLastErrorString();
716 
717 #if defined(R__SOLARIS) || defined (R__LINUX) || defined(R__AIX) || \
718  defined(R__FBSD) || defined(R__OBSD) || defined(R__HURD)
719  return strerror(err);
720 #else
721  if (err < 0 || err >= sys_nerr)
722  return Form("errno out of range %d", err);
723  return sys_errlist[err];
724 #endif
725 }
726 
727 ////////////////////////////////////////////////////////////////////////////////
728 /// Return the system's host name.
729 
731 {
732  if (fHostname == "") {
733  char hn[64];
734 #if defined(R__SOLARIS)
735  sysinfo(SI_HOSTNAME, hn, sizeof(hn));
736 #else
737  gethostname(hn, sizeof(hn));
738 #endif
739  fHostname = hn;
740  }
741  return (const char *)fHostname;
742 }
743 
744 //---- EventLoop ---------------------------------------------------------------
745 
746 ////////////////////////////////////////////////////////////////////////////////
747 /// Add a file handler to the list of system file handlers. Only adds
748 /// the handler if it is not already in the list of file handlers.
749 
751 {
753 
755  if (h) {
756  int fd = h->GetFd();
757  if (h->HasReadInterest()) {
758  fReadmask->Set(fd);
759  fMaxrfd = TMath::Max(fMaxrfd, fd);
760  }
761  if (h->HasWriteInterest()) {
762  fWritemask->Set(fd);
763  fMaxwfd = TMath::Max(fMaxwfd, fd);
764  }
765  }
766 }
767 
768 ////////////////////////////////////////////////////////////////////////////////
769 /// Remove a file handler from the list of file handlers. Returns
770 /// the handler or 0 if the handler was not in the list of file handlers.
771 
773 {
774  if (!h) return 0;
775 
777 
779  if (oh) { // found
780  TFileHandler *th;
781  TIter next(fFileHandler);
782  fMaxrfd = -1;
783  fMaxwfd = -1;
784  fReadmask->Zero();
785  fWritemask->Zero();
786  while ((th = (TFileHandler *) next())) {
787  int fd = th->GetFd();
788  if (th->HasReadInterest()) {
789  fReadmask->Set(fd);
790  fMaxrfd = TMath::Max(fMaxrfd, fd);
791  }
792  if (th->HasWriteInterest()) {
793  fWritemask->Set(fd);
794  fMaxwfd = TMath::Max(fMaxwfd, fd);
795  }
796  }
797  }
798  return oh;
799 }
800 
801 ////////////////////////////////////////////////////////////////////////////////
802 /// Add a signal handler to list of system signal handlers. Only adds
803 /// the handler if it is not already in the list of signal handlers.
804 
806 {
808 
811 }
812 
813 ////////////////////////////////////////////////////////////////////////////////
814 /// Remove a signal handler from list of signal handlers. Returns
815 /// the handler or 0 if the handler was not in the list of signal handlers.
816 
818 {
819  if (!h) return 0;
820 
822 
824 
825  Bool_t last = kTRUE;
826  TSignalHandler *hs;
827  TIter next(fSignalHandler);
828 
829  while ((hs = (TSignalHandler*) next())) {
830  if (hs->GetSignal() == h->GetSignal())
831  last = kFALSE;
832  }
833  if (last)
834  ResetSignal(h->GetSignal(), kTRUE);
835 
836  return oh;
837 }
838 
839 ////////////////////////////////////////////////////////////////////////////////
840 /// If reset is true reset the signal handler for the specified signal
841 /// to the default handler, else restore previous behaviour.
842 
844 {
845  if (reset)
846  UnixResetSignal(sig);
847  else
848  UnixSignal(sig, SigHandler);
849 }
850 
851 ////////////////////////////////////////////////////////////////////////////////
852 /// Reset signals handlers to previous behaviour.
853 
855 {
857 }
858 
859 ////////////////////////////////////////////////////////////////////////////////
860 /// If ignore is true ignore the specified signal, else restore previous
861 /// behaviour.
862 
864 {
865  UnixIgnoreSignal(sig, ignore);
866 }
867 
868 ////////////////////////////////////////////////////////////////////////////////
869 /// When the argument is true the SIGALRM signal handler is set so that
870 /// interrupted syscalls will not be restarted by the kernel. This is
871 /// typically used in case one wants to put a timeout on an I/O operation.
872 /// By default interrupted syscalls will always be restarted (for all
873 /// signals). This can be controlled for each a-synchronous TTimer via
874 /// the method TTimer::SetInterruptSyscalls().
875 
877 {
879 }
880 
881 ////////////////////////////////////////////////////////////////////////////////
882 /// Return the bitmap of conditions that trigger a floating point exception.
883 
885 {
886  Int_t mask = 0;
887 
888 #if defined(R__LINUX) && !defined(__powerpc__)
889 #if defined(__GLIBC__) && (__GLIBC__>2 || __GLIBC__==2 && __GLIBC_MINOR__>=1)
890 
891 #if __GLIBC_MINOR__>=3
892 
893  Int_t oldmask = fegetexcept();
894 
895 #else
896  fenv_t oldenv;
897  fegetenv(&oldenv);
898  fesetenv(&oldenv);
899 #if __ia64__
900  Int_t oldmask = ~oldenv;
901 #else
902  Int_t oldmask = ~oldenv.__control_word;
903 #endif
904 #endif
905 
906  if (oldmask & FE_INVALID ) mask |= kInvalid;
907  if (oldmask & FE_DIVBYZERO) mask |= kDivByZero;
908  if (oldmask & FE_OVERFLOW ) mask |= kOverflow;
909  if (oldmask & FE_UNDERFLOW) mask |= kUnderflow;
910 # ifdef FE_INEXACT
911  if (oldmask & FE_INEXACT ) mask |= kInexact;
912 # endif
913 #endif
914 #endif
915 
916 #if defined(R__MACOSX) && defined(__SSE2__)
917  // OS X uses the SSE unit for all FP math by default, not the x87 FP unit
918  Int_t oldmask = ~_MM_GET_EXCEPTION_MASK();
919 
920  if (oldmask & _MM_MASK_INVALID ) mask |= kInvalid;
921  if (oldmask & _MM_MASK_DIV_ZERO ) mask |= kDivByZero;
922  if (oldmask & _MM_MASK_OVERFLOW ) mask |= kOverflow;
923  if (oldmask & _MM_MASK_UNDERFLOW) mask |= kUnderflow;
924  if (oldmask & _MM_MASK_INEXACT ) mask |= kInexact;
925 #endif
926 
927 #if defined(R__MACOSX) && !defined(__SSE2__) && \
928  (defined(__i386__) || defined(__x86_64__) || defined(__arm__) || defined(__arm64__))
929  fenv_t oldenv;
930  fegetenv(&oldenv);
931  fesetenv(&oldenv);
932 #if defined(__arm__)
933  Int_t oldmask = ~oldenv.__fpscr;
934 #elif defined(__arm64__)
935  Int_t oldmask = ~oldenv.__fpcr;
936 #else
937  Int_t oldmask = ~oldenv.__control;
938 #endif
939 
940  if (oldmask & FE_INVALID ) mask |= kInvalid;
941  if (oldmask & FE_DIVBYZERO) mask |= kDivByZero;
942  if (oldmask & FE_OVERFLOW ) mask |= kOverflow;
943  if (oldmask & FE_UNDERFLOW) mask |= kUnderflow;
944  if (oldmask & FE_INEXACT ) mask |= kInexact;
945 #endif
946 
947 #if defined(R__MACOSX) && !defined(__SSE2__) && !defined(__xlC__) && \
948  !defined(__i386__) && !defined(__x86_64__) && !defined(__arm__) && \
949  !defined(__arm64__)
950  Long64_t oldmask;
951  fegetenvd(oldmask);
952 
953  if (oldmask & FE_ENABLE_INVALID ) mask |= kInvalid;
954  if (oldmask & FE_ENABLE_DIVBYZERO) mask |= kDivByZero;
955  if (oldmask & FE_ENABLE_OVERFLOW ) mask |= kOverflow;
956  if (oldmask & FE_ENABLE_UNDERFLOW) mask |= kUnderflow;
957  if (oldmask & FE_ENABLE_INEXACT ) mask |= kInexact;
958 #endif
959 
960  return mask;
961 }
962 
963 ////////////////////////////////////////////////////////////////////////////////
964 /// Set which conditions trigger a floating point exception.
965 /// Return the previous set of conditions.
966 
968 {
969  if (mask) { } // use mask to avoid warning
970 
971  Int_t old = GetFPEMask();
972 
973 #if defined(R__LINUX) && !defined(__powerpc__)
974 #if defined(__GLIBC__) && (__GLIBC__>2 || __GLIBC__==2 && __GLIBC_MINOR__>=1)
975  Int_t newm = 0;
976  if (mask & kInvalid ) newm |= FE_INVALID;
977  if (mask & kDivByZero) newm |= FE_DIVBYZERO;
978  if (mask & kOverflow ) newm |= FE_OVERFLOW;
979  if (mask & kUnderflow) newm |= FE_UNDERFLOW;
980 # ifdef FE_INEXACT
981  if (mask & kInexact ) newm |= FE_INEXACT;
982 # endif
983 
984 #if __GLIBC_MINOR__>=3
985 
986  // clear pending exceptions so feenableexcept does not trigger them
987  feclearexcept(FE_ALL_EXCEPT);
988  fedisableexcept(FE_ALL_EXCEPT);
989  feenableexcept(newm);
990 
991 #else
992 
993  fenv_t cur;
994  fegetenv(&cur);
995 #if defined __ia64__
996  cur &= ~newm;
997 #else
998  cur.__control_word &= ~newm;
999 #endif
1000  fesetenv(&cur);
1001 
1002 #endif
1003 #endif
1004 #endif
1005 
1006 #if defined(R__MACOSX) && defined(__SSE2__)
1007  // OS X uses the SSE unit for all FP math by default, not the x87 FP unit
1008  Int_t newm = 0;
1009  if (mask & kInvalid ) newm |= _MM_MASK_INVALID;
1010  if (mask & kDivByZero) newm |= _MM_MASK_DIV_ZERO;
1011  if (mask & kOverflow ) newm |= _MM_MASK_OVERFLOW;
1012  if (mask & kUnderflow) newm |= _MM_MASK_UNDERFLOW;
1013  if (mask & kInexact ) newm |= _MM_MASK_INEXACT;
1014 
1015  _MM_SET_EXCEPTION_MASK(_MM_GET_EXCEPTION_MASK() & ~newm);
1016 #endif
1017 
1018 #if defined(R__MACOSX) && !defined(__SSE2__) && \
1019  (defined(__i386__) || defined(__x86_64__) || defined(__arm__) || defined(__arm64__))
1020  Int_t newm = 0;
1021  if (mask & kInvalid ) newm |= FE_INVALID;
1022  if (mask & kDivByZero) newm |= FE_DIVBYZERO;
1023  if (mask & kOverflow ) newm |= FE_OVERFLOW;
1024  if (mask & kUnderflow) newm |= FE_UNDERFLOW;
1025  if (mask & kInexact ) newm |= FE_INEXACT;
1026 
1027  fenv_t cur;
1028  fegetenv(&cur);
1029 #if defined(__arm__)
1030  cur.__fpscr &= ~newm;
1031 #elif defined(__arm64__)
1032  cur.__fpcr &= ~newm;
1033 #else
1034  cur.__control &= ~newm;
1035 #endif
1036  fesetenv(&cur);
1037 #endif
1038 
1039 #if defined(R__MACOSX) && !defined(__SSE2__) && !defined(__xlC__) && \
1040  !defined(__i386__) && !defined(__x86_64__) && !defined(__arm__) && \
1041  !defined(__arm64__)
1042  Int_t newm = 0;
1043  if (mask & kInvalid ) newm |= FE_ENABLE_INVALID;
1044  if (mask & kDivByZero) newm |= FE_ENABLE_DIVBYZERO;
1045  if (mask & kOverflow ) newm |= FE_ENABLE_OVERFLOW;
1046  if (mask & kUnderflow) newm |= FE_ENABLE_UNDERFLOW;
1047  if (mask & kInexact ) newm |= FE_ENABLE_INEXACT;
1048 
1049  Long64_t curmask;
1050  fegetenvd(curmask);
1051  curmask = (curmask & ~FE_ENABLE_ALL_EXCEPT) | newm;
1052  fesetenvd(curmask);
1053 #endif
1054 
1055  return old;
1056 }
1057 
1058 ////////////////////////////////////////////////////////////////////////////////
1059 /// Dispatch a single event.
1060 
1062 {
1063  Bool_t pollOnce = pendingOnly;
1064 
1065  while (1) {
1066  // first handle any X11 events
1067  if (gXDisplay && gXDisplay->Notify()) {
1068  if (fReadready->IsSet(gXDisplay->GetFd())) {
1069  fReadready->Clr(gXDisplay->GetFd());
1070  fNfd--;
1071  }
1072  if (!pendingOnly) return;
1073  }
1074 
1075  // check for file descriptors ready for reading/writing
1076  if (fNfd > 0 && fFileHandler && fFileHandler->GetSize() > 0)
1077  if (CheckDescriptors())
1078  if (!pendingOnly) return;
1079  fNfd = 0;
1080  fReadready->Zero();
1081  fWriteready->Zero();
1082 
1083  if (pendingOnly && !pollOnce)
1084  return;
1085 
1086  // check synchronous signals
1087  if (fSigcnt > 0 && fSignalHandler->GetSize() > 0)
1088  if (CheckSignals(kTRUE))
1089  if (!pendingOnly) return;
1090  fSigcnt = 0;
1091  fSignals->Zero();
1092 
1093  // check synchronous timers
1094  Long_t nextto;
1095  if (fTimers && fTimers->GetSize() > 0)
1096  if (DispatchTimers(kTRUE)) {
1097  // prevent timers from blocking file descriptor monitoring
1098  nextto = NextTimeOut(kTRUE);
1099  if (nextto > kItimerResolution || nextto == -1)
1100  return;
1101  }
1102 
1103  // if in pendingOnly mode poll once file descriptor activity
1104  nextto = NextTimeOut(kTRUE);
1105  if (pendingOnly) {
1106  if (fFileHandler && fFileHandler->GetSize() == 0)
1107  return;
1108  nextto = 0;
1109  pollOnce = kFALSE;
1110  }
1111 
1112  // nothing ready, so setup select call
1113  *fReadready = *fReadmask;
1114  *fWriteready = *fWritemask;
1115 
1116  int mxfd = TMath::Max(fMaxrfd, fMaxwfd);
1117  mxfd++;
1118 
1119  // if nothing to select (socket or timer) return
1120  if (mxfd == 0 && nextto == -1)
1121  return;
1122 
1123  fNfd = UnixSelect(mxfd, fReadready, fWriteready, nextto);
1124  if (fNfd < 0 && fNfd != -2) {
1125  int fd, rc;
1126  TFdSet t;
1127  for (fd = 0; fd < mxfd; fd++) {
1128  t.Set(fd);
1129  if (fReadmask->IsSet(fd)) {
1130  rc = UnixSelect(fd+1, &t, 0, 0);
1131  if (rc < 0 && rc != -2) {
1132  SysError("DispatchOneEvent", "select: read error on %d", fd);
1133  fReadmask->Clr(fd);
1134  }
1135  }
1136  if (fWritemask->IsSet(fd)) {
1137  rc = UnixSelect(fd+1, 0, &t, 0);
1138  if (rc < 0 && rc != -2) {
1139  SysError("DispatchOneEvent", "select: write error on %d", fd);
1140  fWritemask->Clr(fd);
1141  }
1142  }
1143  t.Clr(fd);
1144  }
1145  }
1146  }
1147 }
1148 
1149 ////////////////////////////////////////////////////////////////////////////////
1150 /// Sleep milliSec milliseconds.
1151 
1153 {
1154  struct timeval tv;
1155 
1156  tv.tv_sec = milliSec / 1000;
1157  tv.tv_usec = (milliSec % 1000) * 1000;
1158 
1159  select(0, 0, 0, 0, &tv);
1160 }
1161 
1162 ////////////////////////////////////////////////////////////////////////////////
1163 /// Select on file descriptors. The timeout to is in millisec. Returns
1164 /// the number of ready descriptors, or 0 in case of timeout, or < 0 in
1165 /// case of an error, with -2 being EINTR and -3 EBADF. In case of EINTR
1166 /// the errno has been reset and the method can be called again. Returns
1167 /// -4 in case the list did not contain any file handlers or file handlers
1168 /// with file descriptor >= 0.
1169 
1171 {
1172  Int_t rc = -4;
1173 
1174  TFdSet rd, wr;
1175  Int_t mxfd = -1;
1176  TIter next(act);
1177  TFileHandler *h = 0;
1178  while ((h = (TFileHandler *) next())) {
1179  Int_t fd = h->GetFd();
1180  if (fd > -1) {
1181  if (h->HasReadInterest()) {
1182  rd.Set(fd);
1183  mxfd = TMath::Max(mxfd, fd);
1184  }
1185  if (h->HasWriteInterest()) {
1186  wr.Set(fd);
1187  mxfd = TMath::Max(mxfd, fd);
1188  }
1189  h->ResetReadyMask();
1190  }
1191  }
1192  if (mxfd > -1)
1193  rc = UnixSelect(mxfd+1, &rd, &wr, to);
1194 
1195  // Set readiness bits
1196  if (rc > 0) {
1197  next.Reset();
1198  while ((h = (TFileHandler *) next())) {
1199  Int_t fd = h->GetFd();
1200  if (rd.IsSet(fd))
1201  h->SetReadReady();
1202  if (wr.IsSet(fd))
1203  h->SetWriteReady();
1204  }
1205  }
1206 
1207  return rc;
1208 }
1209 
1210 ////////////////////////////////////////////////////////////////////////////////
1211 /// Select on the file descriptor related to file handler h.
1212 /// The timeout to is in millisec. Returns the number of ready descriptors,
1213 /// or 0 in case of timeout, or < 0 in case of an error, with -2 being EINTR
1214 /// and -3 EBADF. In case of EINTR the errno has been reset and the method
1215 /// can be called again. Returns -4 in case the file handler is 0 or does
1216 /// not have a file descriptor >= 0.
1217 
1219 {
1220  Int_t rc = -4;
1221 
1222  TFdSet rd, wr;
1223  Int_t mxfd = -1;
1224  Int_t fd = -1;
1225  if (h) {
1226  fd = h->GetFd();
1227  if (fd > -1) {
1228  if (h->HasReadInterest())
1229  rd.Set(fd);
1230  if (h->HasWriteInterest())
1231  wr.Set(fd);
1232  h->ResetReadyMask();
1233  mxfd = fd;
1234  rc = UnixSelect(mxfd+1, &rd, &wr, to);
1235  }
1236  }
1237 
1238  // Fill output lists, if required
1239  if (rc > 0) {
1240  if (rd.IsSet(fd))
1241  h->SetReadReady();
1242  if (wr.IsSet(fd))
1243  h->SetWriteReady();
1244  }
1245 
1246  return rc;
1247 }
1248 
1249 //---- handling of system events -----------------------------------------------
1250 
1251 ////////////////////////////////////////////////////////////////////////////////
1252 /// Check if some signals were raised and call their Notify() member.
1253 
1255 {
1256  TSignalHandler *sh;
1257  Int_t sigdone = -1;
1258  {
1260 
1261  while ((sh = (TSignalHandler*)it.Next())) {
1262  if (sync == sh->IsSync()) {
1263  ESignals sig = sh->GetSignal();
1264  if ((fSignals->IsSet(sig) && sigdone == -1) || sigdone == sig) {
1265  if (sigdone == -1) {
1266  fSignals->Clr(sig);
1267  sigdone = sig;
1268  fSigcnt--;
1269  }
1270  if (sh->IsActive())
1271  sh->Notify();
1272  }
1273  }
1274  }
1275  }
1276  if (sigdone != -1)
1277  return kTRUE;
1278 
1279  return kFALSE;
1280 }
1281 
1282 ////////////////////////////////////////////////////////////////////////////////
1283 /// Check if children have finished.
1284 
1286 {
1287 #if 0 //rdm
1288  int pid;
1289  while ((pid = UnixWaitchild()) > 0) {
1290  TIter next(zombieHandler);
1291  register UnixPtty *pty;
1292  while ((pty = (UnixPtty*) next()))
1293  if (pty->GetPid() == pid) {
1294  zombieHandler->RemovePtr(pty);
1295  pty->DiedNotify();
1296  }
1297  }
1298 #endif
1299 }
1300 
1301 ////////////////////////////////////////////////////////////////////////////////
1302 /// Check if there is activity on some file descriptors and call their
1303 /// Notify() member.
1304 
1306 {
1307  TFileHandler *fh;
1308  Int_t fddone = -1;
1309  Bool_t read = kFALSE;
1311  while ((fh = (TFileHandler*) it.Next())) {
1312  Int_t fd = fh->GetFd();
1313  if ((fd <= fMaxrfd && fReadready->IsSet(fd) && fddone == -1) ||
1314  (fddone == fd && read)) {
1315  if (fddone == -1) {
1316  fReadready->Clr(fd);
1317  fddone = fd;
1318  read = kTRUE;
1319  fNfd--;
1320  }
1321  if (fh->IsActive())
1322  fh->ReadNotify();
1323  }
1324  if ((fd <= fMaxwfd && fWriteready->IsSet(fd) && fddone == -1) ||
1325  (fddone == fd && !read)) {
1326  if (fddone == -1) {
1327  fWriteready->Clr(fd);
1328  fddone = fd;
1329  read = kFALSE;
1330  fNfd--;
1331  }
1332  if (fh->IsActive())
1333  fh->WriteNotify();
1334  }
1335  }
1336  if (fddone != -1)
1337  return kTRUE;
1338 
1339  return kFALSE;
1340 }
1341 
1342 //---- Directories -------------------------------------------------------------
1343 
1344 ////////////////////////////////////////////////////////////////////////////////
1345 /// Make a Unix file system directory. Returns 0 in case of success and
1346 /// -1 if the directory could not be created.
1347 
1349 {
1350  TSystem *helper = FindHelper(name);
1351  if (helper)
1352  return helper->MakeDirectory(name);
1353 
1354  return UnixMakedir(name);
1355 }
1356 
1357 ////////////////////////////////////////////////////////////////////////////////
1358 /// Open a Unix file system directory. Returns 0 if directory does not exist.
1359 
1361 {
1362  TSystem *helper = FindHelper(name);
1363  if (helper)
1364  return helper->OpenDirectory(name);
1365 
1366  return UnixOpendir(name);
1367 }
1368 
1369 ////////////////////////////////////////////////////////////////////////////////
1370 /// Close a Unix file system directory.
1371 
1373 {
1374  TSystem *helper = FindHelper(0, dirp);
1375  if (helper) {
1376  helper->FreeDirectory(dirp);
1377  return;
1378  }
1379 
1380  if (dirp)
1381  ::closedir((DIR*)dirp);
1382 }
1383 
1384 ////////////////////////////////////////////////////////////////////////////////
1385 /// Get next Unix file system directory entry. Returns 0 if no more entries.
1386 
1387 const char *TUnixSystem::GetDirEntry(void *dirp)
1388 {
1389  TSystem *helper = FindHelper(0, dirp);
1390  if (helper)
1391  return helper->GetDirEntry(dirp);
1392 
1393  if (dirp)
1394  return UnixGetdirentry(dirp);
1395 
1396  return 0;
1397 }
1398 
1399 ////////////////////////////////////////////////////////////////////////////////
1400 /// Change directory. Returns kTRUE in case of success, kFALSE otherwise.
1401 
1403 {
1404  Bool_t ret = (Bool_t) (::chdir(path) == 0);
1405  if (fWdpath != "")
1406  fWdpath = ""; // invalidate path cache
1407  return ret;
1408 }
1409 
1410 ////////////////////////////////////////////////////////////////////////////////
1411 /// Return working directory.
1412 
1414 {
1415  // don't use cache as user can call chdir() directly somewhere else
1416  //if (fWdpath != "")
1417  // return fWdpath.Data();
1418 
1420 
1421  static char cwd[kMAXPATHLEN];
1422  FillWithCwd(cwd);
1423  fWdpath = cwd;
1424 
1425  return fWdpath.Data();
1426 }
1427 
1428 //////////////////////////////////////////////////////////////////////////////
1429 /// Return working directory.
1430 
1432 {
1433  char cwd[kMAXPATHLEN];
1434  FillWithCwd(cwd);
1435  return std::string(cwd);
1436 }
1437 
1438 //////////////////////////////////////////////////////////////////////////////
1439 /// Fill buffer with current working directory.
1440 
1441 void TUnixSystem::FillWithCwd(char *cwd) const
1442 {
1443  if (::getcwd(cwd, kMAXPATHLEN) == 0) {
1444  Error("WorkingDirectory", "getcwd() failed");
1445  }
1446 }
1447 
1448 ////////////////////////////////////////////////////////////////////////////////
1449 /// Return the user's home directory.
1450 
1451 const char *TUnixSystem::HomeDirectory(const char *userName)
1452 {
1453  return UnixHomedirectory(userName);
1454 }
1455 
1456 //////////////////////////////////////////////////////////////////////////////
1457 /// Return the user's home directory.
1458 
1459 std::string TUnixSystem::GetHomeDirectory(const char *userName) const
1460 {
1461  char path[kMAXPATHLEN], mydir[kMAXPATHLEN] = { '\0' };
1462  return std::string(UnixHomedirectory(userName, path, mydir));
1463 }
1464 
1465 ////////////////////////////////////////////////////////////////////////////////
1466 /// Return a user configured or systemwide directory to create
1467 /// temporary files in.
1468 
1469 const char *TUnixSystem::TempDirectory() const
1470 {
1471  const char *dir = gSystem->Getenv("TMPDIR");
1472  if (!dir || gSystem->AccessPathName(dir, kWritePermission))
1473  dir = "/tmp";
1474 
1475  return dir;
1476 }
1477 
1478 ////////////////////////////////////////////////////////////////////////////////
1479 /// Create a secure temporary file by appending a unique
1480 /// 6 letter string to base. The file will be created in
1481 /// a standard (system) directory or in the directory
1482 /// provided in dir. The full filename is returned in base
1483 /// and a filepointer is returned for safely writing to the file
1484 /// (this avoids certain security problems). Returns 0 in case
1485 /// of error.
1486 
1487 FILE *TUnixSystem::TempFileName(TString &base, const char *dir)
1488 {
1489  char *b = ConcatFileName(dir ? dir : TempDirectory(), base);
1490  base = b;
1491  base += "XXXXXX";
1492  delete [] b;
1493 
1494  char *arg = StrDup(base);
1495  int fd = mkstemp(arg);
1496  base = arg;
1497  delete [] arg;
1498 
1499  if (fd == -1) {
1500  SysError("TempFileName", "%s", base.Data());
1501  return 0;
1502  } else {
1503  FILE *fp = fdopen(fd, "w+");
1504  if (fp == 0)
1505  SysError("TempFileName", "converting filedescriptor (%d)", fd);
1506  return fp;
1507  }
1508 }
1509 
1510 ////////////////////////////////////////////////////////////////////////////////
1511 /// Concatenate a directory and a file name.
1512 
1513 const char *TUnixSystem::PrependPathName(const char *dir, TString& name)
1514 {
1515  if (name.IsNull() || name == ".") {
1516  if (dir) {
1517  name = dir;
1518  if (dir[strlen(dir) - 1] != '/')
1519  name += '/';
1520  } else name = "";
1521  return name.Data();
1522  }
1523 
1524  if (!dir || !dir[0]) dir = "/";
1525  else if (dir[strlen(dir) - 1] != '/')
1526  name.Prepend('/');
1527  name.Prepend(dir);
1528 
1529  return name.Data();
1530 }
1531 
1532 //---- Paths & Files -----------------------------------------------------------
1533 
1534 ////////////////////////////////////////////////////////////////////////////////
1535 /// Returns FALSE if one can access a file using the specified access mode.
1536 /// Mode is the same as for the Unix access(2) function.
1537 /// Attention, bizarre convention of return value!!
1538 
1540 {
1541  TSystem *helper = FindHelper(path);
1542  if (helper)
1543  return helper->AccessPathName(path, mode);
1544 
1545  if (::access(StripOffProto(path, "file:"), mode) == 0)
1546  return kFALSE;
1548 
1549  return kTRUE;
1550 }
1551 
1552 ////////////////////////////////////////////////////////////////////////////////
1553 /// Copy a file. If overwrite is true and file already exists the
1554 /// file will be overwritten. Returns 0 when successful, -1 in case
1555 /// of file open failure, -2 in case the file already exists and overwrite
1556 /// was false and -3 in case of error during copy.
1557 
1558 int TUnixSystem::CopyFile(const char *f, const char *t, Bool_t overwrite)
1559 {
1560  if (!AccessPathName(t) && !overwrite)
1561  return -2;
1562 
1563  FILE *from = fopen(f, "r");
1564  if (!from)
1565  return -1;
1566 
1567  FILE *to = fopen(t, "w");
1568  if (!to) {
1569  fclose(from);
1570  return -1;
1571  }
1572 
1573  const int bufsize = 1024;
1574  char buf[bufsize];
1575  int ret = 0;
1576  while (!ret && !feof(from)) {
1577  size_t numread = fread (buf, sizeof(char), bufsize, from);
1578  size_t numwritten = fwrite(buf, sizeof(char), numread, to);
1579  if (numread != numwritten)
1580  ret = -3;
1581  }
1582 
1583  fclose(from);
1584  fclose(to);
1585 
1586  return ret;
1587 }
1588 
1589 ////////////////////////////////////////////////////////////////////////////////
1590 /// Rename a file. Returns 0 when successful, -1 in case of failure.
1591 
1592 int TUnixSystem::Rename(const char *f, const char *t)
1593 {
1594  int ret = ::rename(f, t);
1596  return ret;
1597 }
1598 
1599 ////////////////////////////////////////////////////////////////////////////////
1600 /// Returns TRUE if the url in 'path' points to the local file system.
1601 /// This is used to avoid going through the NIC card for local operations.
1602 
1604 {
1605  TSystem *helper = FindHelper(path);
1606  if (helper)
1607  return helper->IsPathLocal(path);
1608 
1609  return TSystem::IsPathLocal(path);
1610 }
1611 
1612 ////////////////////////////////////////////////////////////////////////////////
1613 /// Get info about a file. Info is returned in the form of a FileStat_t
1614 /// structure (see TSystem.h).
1615 /// The function returns 0 in case of success and 1 if the file could
1616 /// not be stat'ed.
1617 
1618 int TUnixSystem::GetPathInfo(const char *path, FileStat_t &buf)
1619 {
1620  TSystem *helper = FindHelper(path);
1621  if (helper)
1622  return helper->GetPathInfo(path, buf);
1623 
1624  return UnixFilestat(path, buf);
1625 }
1626 
1627 ////////////////////////////////////////////////////////////////////////////////
1628 /// Get info about a file system: id, bsize, bfree, blocks.
1629 /// Id is file system type (machine dependend, see statfs())
1630 /// Bsize is block size of file system
1631 /// Blocks is total number of blocks in file system
1632 /// Bfree is number of free blocks in file system
1633 /// The function returns 0 in case of success and 1 if the file system could
1634 /// not be stat'ed.
1635 
1636 int TUnixSystem::GetFsInfo(const char *path, Long_t *id, Long_t *bsize,
1637  Long_t *blocks, Long_t *bfree)
1638 {
1639  return UnixFSstat(path, id, bsize, blocks, bfree);
1640 }
1641 
1642 ////////////////////////////////////////////////////////////////////////////////
1643 /// Create a link from file1 to file2. Returns 0 when successful,
1644 /// -1 in case of failure.
1645 
1646 int TUnixSystem::Link(const char *from, const char *to)
1647 {
1648  return ::link(from, to);
1649 }
1650 
1651 ////////////////////////////////////////////////////////////////////////////////
1652 /// Create a symlink from file1 to file2. Returns 0 when successful,
1653 /// -1 in case of failure.
1654 
1655 int TUnixSystem::Symlink(const char *from, const char *to)
1656 {
1657 #if defined(R__AIX)
1658  return ::symlink((char*)from, (char*)to);
1659 #else
1660  return ::symlink(from, to);
1661 #endif
1662 }
1663 
1664 ////////////////////////////////////////////////////////////////////////////////
1665 /// Unlink, i.e. remove, a file or directory. Returns 0 when successful,
1666 /// -1 in case of failure.
1667 
1668 int TUnixSystem::Unlink(const char *name)
1669 {
1670  TSystem *helper = FindHelper(name);
1671  if (helper)
1672  return helper->Unlink(name);
1673 
1674 #if defined(R__SEEK64)
1675  struct stat64 finfo;
1676  if (lstat64(name, &finfo) < 0)
1677 #else
1678  struct stat finfo;
1679  if (lstat(name, &finfo) < 0)
1680 #endif
1681  return -1;
1682 
1683  if (S_ISDIR(finfo.st_mode))
1684  return ::rmdir(name);
1685  else
1686  return ::unlink(name);
1687 }
1688 
1689 //---- expand the metacharacters as in the shell -------------------------------
1690 
1691 // expand the metacharacters as in the shell
1692 
1693 const char
1694 #ifdef G__OLDEXPAND
1695  kShellEscape = '\\',
1696  *kShellStuff = "(){}<>\"'",
1697 #endif
1698  *kShellMeta = "~*[]{}?$";
1699 
1700 
1701 #ifndef G__OLDEXPAND
1702 ////////////////////////////////////////////////////////////////////////////////
1703 /// Expand a pathname getting rid of special shell characters like ~.$, etc.
1704 /// For Unix/Win32 compatibility use $(XXX) instead of $XXX when using
1705 /// environment variables in a pathname. If compatibility is not an issue
1706 /// you can use on Unix directly $XXX. Returns kFALSE in case of success
1707 /// or kTRUE in case of error.
1708 
1710 {
1711  const char *p, *patbuf = (const char *)path;
1712 
1713  // skip leading blanks
1714  while (*patbuf == ' ')
1715  patbuf++;
1716 
1717  // any shell meta characters ?
1718  for (p = patbuf; *p; p++)
1719  if (strchr(kShellMeta, *p))
1720  goto expand;
1721 
1722  return kFALSE;
1723 
1724 expand:
1725  // replace $(XXX) by $XXX
1726  path.ReplaceAll("$(","$");
1727  path.ReplaceAll(")","");
1728 
1729  return ExpandFileName(path);
1730 }
1731 #endif
1732 
1733 #ifdef G__OLDEXPAND
1734 ////////////////////////////////////////////////////////////////////////////////
1735 /// Expand a pathname getting rid of special shell characters like ~.$, etc.
1736 /// For Unix/Win32 compatibility use $(XXX) instead of $XXX when using
1737 /// environment variables in a pathname. If compatibility is not an issue
1738 /// you can use on Unix directly $XXX. Returns kFALSE in case of success
1739 /// or kTRUE in case of error.
1740 
1742 {
1743  const char *patbuf = (const char *)patbuf0;
1744  const char *hd, *p;
1745  // char cmd[kMAXPATHLEN],
1746  char stuffedPat[kMAXPATHLEN], name[70];
1747  char *q;
1748  FILE *pf;
1749  int ch;
1750 
1751  // skip leading blanks
1752  while (*patbuf == ' ')
1753  patbuf++;
1754 
1755  // any shell meta characters ?
1756  for (p = patbuf; *p; p++)
1757  if (strchr(kShellMeta, *p))
1758  goto needshell;
1759 
1760  return kFALSE;
1761 
1762 needshell:
1763  // replace $(XXX) by $XXX
1764  patbuf0.ReplaceAll("$(","$");
1765  patbuf0.ReplaceAll(")","");
1766 
1767  // escape shell quote characters
1768  EscChar(patbuf, stuffedPat, sizeof(stuffedPat), (char*)kShellStuff, kShellEscape);
1769 
1770  TString cmd("echo ");
1771 
1772  // emulate csh -> popen executes sh
1773  if (stuffedPat[0] == '~') {
1774  if (stuffedPat[1] != '\0' && stuffedPat[1] != '/') {
1775  // extract user name
1776  for (p = &stuffedPat[1], q = name; *p && *p !='/';)
1777  *q++ = *p++;
1778  *q = '\0';
1779  hd = UnixHomedirectory(name);
1780  if (hd == 0)
1781  cmd += stuffedPat;
1782  else {
1783  cmd += hd;
1784  cmd += p;
1785  }
1786  } else {
1787  hd = UnixHomedirectory(0);
1788  if (hd == 0) {
1790  return kTRUE;
1791  }
1792  cmd += hd;
1793  cmd += &stuffedPat[1];
1794  }
1795  } else
1796  cmd += stuffedPat;
1797 
1798  if ((pf = ::popen(cmd.Data(), "r")) == 0) {
1800  return kTRUE;
1801  }
1802 
1803  // read first argument
1804  patbuf0 = "";
1805  int cnt = 0;
1806 #if defined(R__AIX)
1807 again:
1808 #endif
1809  for (ch = fgetc(pf); ch != EOF && ch != ' ' && ch != '\n'; ch = fgetc(pf)) {
1810  patbuf0.Append(ch);
1811  cnt++;
1812  }
1813 #if defined(R__AIX)
1814  // Work around bug timing problem due to delay in forking a large program
1815  if (cnt == 0 && ch == EOF) goto again;
1816 #endif
1817 
1818  // skip rest of pipe
1819  while (ch != EOF) {
1820  ch = fgetc(pf);
1821  if (ch == ' ' || ch == '\t') {
1822  GetLastErrorString() = "expression ambigous";
1823  ::pclose(pf);
1824  return kTRUE;
1825  }
1826  }
1827 
1828  ::pclose(pf);
1829 
1830  return kFALSE;
1831 }
1832 #endif
1833 
1834 ////////////////////////////////////////////////////////////////////////////////
1835 /// Expand a pathname getting rid of special shell characaters like ~.$, etc.
1836 /// For Unix/Win32 compatibility use $(XXX) instead of $XXX when using
1837 /// environment variables in a pathname. If compatibility is not an issue
1838 /// you can use on Unix directly $XXX. The user must delete returned string.
1839 /// Returns the expanded pathname or 0 in case of error.
1840 /// The user must delete returned string (delete []).
1841 
1842 char *TUnixSystem::ExpandPathName(const char *path)
1843 {
1844  TString patbuf = path;
1845  if (ExpandPathName(patbuf))
1846  return 0;
1847  return StrDup(patbuf.Data());
1848 }
1849 
1850 ////////////////////////////////////////////////////////////////////////////////
1851 /// Set the file permission bits. Returns -1 in case or error, 0 otherwise.
1852 
1853 int TUnixSystem::Chmod(const char *file, UInt_t mode)
1854 {
1855  return ::chmod(file, mode);
1856 }
1857 
1858 ////////////////////////////////////////////////////////////////////////////////
1859 /// Set the process file creation mode mask.
1860 
1862 {
1863  return ::umask(mask);
1864 }
1865 
1866 ////////////////////////////////////////////////////////////////////////////////
1867 /// Set a files modification and access times. If actime = 0 it will be
1868 /// set to the modtime. Returns 0 on success and -1 in case of error.
1869 
1870 int TUnixSystem::Utime(const char *file, Long_t modtime, Long_t actime)
1871 {
1872  if (!actime)
1873  actime = modtime;
1874 
1875  struct utimbuf t;
1876  t.actime = (time_t)actime;
1877  t.modtime = (time_t)modtime;
1878  return ::utime(file, &t);
1879 }
1880 
1881 ////////////////////////////////////////////////////////////////////////////////
1882 /// Find location of file "wfil" in a search path.
1883 /// The search path is specified as a : separated list of directories.
1884 /// Return value is pointing to wfile for compatibility with
1885 /// Which(const char*,const char*,EAccessMode) version.
1886 
1887 const char *TUnixSystem::FindFile(const char *search, TString& wfil, EAccessMode mode)
1888 {
1889  TString show;
1890  if (gEnv->GetValue("Root.ShowPath", 0))
1891  show.Form("Which: %s =", wfil.Data());
1892 
1893  gSystem->ExpandPathName(wfil);
1894 
1895  if (wfil[0] == '/') {
1896 #if defined(R__SEEK64)
1897  struct stat64 finfo;
1898  if (access(wfil.Data(), mode) == 0 &&
1899  stat64(wfil.Data(), &finfo) == 0 && S_ISREG(finfo.st_mode)) {
1900 #else
1901  struct stat finfo;
1902  if (access(wfil.Data(), mode) == 0 &&
1903  stat(wfil.Data(), &finfo) == 0 && S_ISREG(finfo.st_mode)) {
1904 #endif
1905  if (show != "")
1906  Printf("%s %s", show.Data(), wfil.Data());
1907  return wfil.Data();
1908  }
1909  if (show != "")
1910  Printf("%s <not found>", show.Data());
1911  wfil = "";
1912  return 0;
1913  }
1914 
1915  if (search == 0)
1916  search = ".";
1917 
1918  TString apwd(gSystem->WorkingDirectory());
1919  apwd += "/";
1920  for (const char* ptr = search; *ptr;) {
1921  TString name;
1922  if (*ptr != '/' && *ptr !='$' && *ptr != '~')
1923  name = apwd;
1924  const char* posEndOfPart = strchr(ptr, ':');
1925  if (posEndOfPart) {
1926  name.Append(ptr, posEndOfPart - ptr);
1927  ptr = posEndOfPart + 1; // skip ':'
1928  } else {
1929  name.Append(ptr);
1930  ptr += strlen(ptr);
1931  }
1932 
1933  if (!name.EndsWith("/"))
1934  name += '/';
1935  name += wfil;
1936 
1937  gSystem->ExpandPathName(name);
1938 #if defined(R__SEEK64)
1939  struct stat64 finfo;
1940  if (access(name.Data(), mode) == 0 &&
1941  stat64(name.Data(), &finfo) == 0 && S_ISREG(finfo.st_mode)) {
1942 #else
1943  struct stat finfo;
1944  if (access(name.Data(), mode) == 0 &&
1945  stat(name.Data(), &finfo) == 0 && S_ISREG(finfo.st_mode)) {
1946 #endif
1947  if (show != "")
1948  Printf("%s %s", show.Data(), name.Data());
1949  wfil = name;
1950  return wfil.Data();
1951  }
1952  }
1953 
1954  if (show != "")
1955  Printf("%s <not found>", show.Data());
1956  wfil = "";
1957  return 0;
1958 }
1959 
1960 //---- Users & Groups ----------------------------------------------------------
1961 
1962 ////////////////////////////////////////////////////////////////////////////////
1963 /// Returns the user's id. If user = 0, returns current user's id.
1964 
1965 Int_t TUnixSystem::GetUid(const char *user)
1966 {
1967  if (!user || !user[0])
1968  return getuid();
1969  else {
1970  struct passwd *apwd = getpwnam(user);
1971  if (apwd)
1972  return apwd->pw_uid;
1973  }
1974  return 0;
1975 }
1976 
1977 ////////////////////////////////////////////////////////////////////////////////
1978 /// Returns the effective user id. The effective id corresponds to the
1979 /// set id bit on the file being executed.
1980 
1982 {
1983  return geteuid();
1984 }
1985 
1986 ////////////////////////////////////////////////////////////////////////////////
1987 /// Returns the group's id. If group = 0, returns current user's group.
1988 
1990 {
1991  if (!group || !group[0])
1992  return getgid();
1993  else {
1994  struct group *grp = getgrnam(group);
1995  if (grp)
1996  return grp->gr_gid;
1997  }
1998  return 0;
1999 }
2000 
2001 ////////////////////////////////////////////////////////////////////////////////
2002 /// Returns the effective group id. The effective group id corresponds
2003 /// to the set id bit on the file being executed.
2004 
2006 {
2007  return getegid();
2008 }
2009 
2010 ////////////////////////////////////////////////////////////////////////////////
2011 /// Returns all user info in the UserGroup_t structure. The returned
2012 /// structure must be deleted by the user. In case of error 0 is returned.
2013 
2015 {
2016  typedef std::map<Int_t /*uid*/, UserGroup_t> UserInfoCache_t;
2017  static UserInfoCache_t gUserInfo;
2018 
2019  UserInfoCache_t::const_iterator iUserInfo = gUserInfo.find(uid);
2020  if (iUserInfo != gUserInfo.end())
2021  return new UserGroup_t(iUserInfo->second);
2022 
2023  struct passwd *apwd = getpwuid(uid);
2024  if (apwd) {
2025  UserGroup_t *ug = new UserGroup_t;
2026  ug->fUid = apwd->pw_uid;
2027  ug->fGid = apwd->pw_gid;
2028  ug->fUser = apwd->pw_name;
2029  ug->fPasswd = apwd->pw_passwd;
2030  ug->fRealName = apwd->pw_gecos;
2031  ug->fShell = apwd->pw_shell;
2032  UserGroup_t *gr = GetGroupInfo(apwd->pw_gid);
2033  if (gr) ug->fGroup = gr->fGroup;
2034  delete gr;
2035 
2036  gUserInfo[uid] = *ug;
2037  return ug;
2038  }
2039  return 0;
2040 }
2041 
2042 ////////////////////////////////////////////////////////////////////////////////
2043 /// Returns all user info in the UserGroup_t structure. If user = 0, returns
2044 /// current user's id info. The returned structure must be deleted by the
2045 /// user. In case of error 0 is returned.
2046 
2048 {
2049  return GetUserInfo(GetUid(user));
2050 }
2051 
2052 ////////////////////////////////////////////////////////////////////////////////
2053 /// Returns all group info in the UserGroup_t structure. The only active
2054 /// fields in the UserGroup_t structure for this call are:
2055 /// fGid and fGroup
2056 /// The returned structure must be deleted by the user. In case of
2057 /// error 0 is returned.
2058 
2060 {
2061  struct group *grp = getgrgid(gid);
2062  if (grp) {
2063  UserGroup_t *gr = new UserGroup_t;
2064  gr->fUid = 0;
2065  gr->fGid = grp->gr_gid;
2066  gr->fGroup = grp->gr_name;
2067  return gr;
2068  }
2069  return 0;
2070 }
2071 
2072 ////////////////////////////////////////////////////////////////////////////////
2073 /// Returns all group info in the UserGroup_t structure. The only active
2074 /// fields in the UserGroup_t structure for this call are:
2075 /// fGid and fGroup
2076 /// If group = 0, returns current user's group. The returned structure
2077 /// must be deleted by the user. In case of error 0 is returned.
2078 
2080 {
2081  return GetGroupInfo(GetGid(group));
2082 }
2083 
2084 //---- environment manipulation ------------------------------------------------
2085 
2086 ////////////////////////////////////////////////////////////////////////////////
2087 /// Set environment variable.
2088 
2089 void TUnixSystem::Setenv(const char *name, const char *value)
2090 {
2091  ::setenv(name, value, 1);
2092 }
2093 
2094 ////////////////////////////////////////////////////////////////////////////////
2095 /// Get environment variable.
2096 
2097 const char *TUnixSystem::Getenv(const char *name)
2098 {
2099  return ::getenv(name);
2100 }
2101 
2102 ////////////////////////////////////////////////////////////////////////////////
2103 /// Unset environment variable.
2104 
2105 void TUnixSystem::Unsetenv(const char *name)
2106 {
2107  ::unsetenv(name);
2108 }
2109 
2110 //---- Processes ---------------------------------------------------------------
2111 
2112 ////////////////////////////////////////////////////////////////////////////////
2113 /// Execute a command.
2114 
2115 int TUnixSystem::Exec(const char *shellcmd)
2116 {
2117  return ::system(shellcmd);
2118 }
2119 
2120 ////////////////////////////////////////////////////////////////////////////////
2121 /// Open a pipe.
2122 
2123 FILE *TUnixSystem::OpenPipe(const char *command, const char *mode)
2124 {
2125  return ::popen(command, mode);
2126 }
2127 
2128 ////////////////////////////////////////////////////////////////////////////////
2129 /// Close the pipe.
2130 
2131 int TUnixSystem::ClosePipe(FILE *pipe)
2132 {
2133  return ::pclose(pipe);
2134 }
2135 
2136 ////////////////////////////////////////////////////////////////////////////////
2137 /// Get process id.
2138 
2140 {
2141  return ::getpid();
2142 }
2143 
2144 ////////////////////////////////////////////////////////////////////////////////
2145 /// Exit the application.
2146 
2147 void TUnixSystem::Exit(int code, Bool_t mode)
2148 {
2149  // Insures that the files and sockets are closed before any library is unloaded
2150  // and before emptying CINT.
2151  if (gROOT) {
2152  gROOT->EndOfProcessCleanups();
2153  } else if (gInterpreter) {
2154  gInterpreter->ResetGlobals();
2155  }
2156 
2157  if (mode)
2158  ::exit(code);
2159  else
2160  ::_exit(code);
2161 }
2162 
2163 ////////////////////////////////////////////////////////////////////////////////
2164 /// Abort the application.
2165 
2167 {
2168  ::abort();
2169 }
2170 
2171 
2172 #ifdef R__MACOSX
2173 /// Use CoreSymbolication to retrieve the stacktrace.
2174 #include <mach/mach.h>
2175 extern "C" {
2176  // Adapted from https://github.com/mountainstorm/CoreSymbolication
2177  // Under the hood the framework basically just calls through to a set of C++ libraries
2178  typedef struct {
2179  void* csCppData;
2180  void* csCppObj;
2181  } CSTypeRef;
2182  typedef CSTypeRef CSSymbolicatorRef;
2183  typedef CSTypeRef CSSourceInfoRef;
2184  typedef CSTypeRef CSSymbolOwnerRef;
2185  typedef CSTypeRef CSSymbolRef;
2186 
2187  CSSymbolicatorRef CSSymbolicatorCreateWithPid(pid_t pid);
2188  CSSourceInfoRef CSSymbolicatorGetSourceInfoWithAddressAtTime(CSSymbolicatorRef cs, vm_address_t addr, uint64_t time);
2189  CSSymbolRef CSSourceInfoGetSymbol(CSSourceInfoRef info);
2190  const char* CSSymbolGetName(CSSymbolRef sym);
2191  CSSymbolOwnerRef CSSourceInfoGetSymbolOwner(CSSourceInfoRef info);
2192  const char* CSSymbolOwnerGetPath(CSSymbolOwnerRef symbol);
2193  const char* CSSourceInfoGetPath(CSSourceInfoRef info);
2194  int CSSourceInfoGetLineNumber(CSSourceInfoRef info);
2195 }
2196 
2197 void macosx_backtrace() {
2198  void* addrlist[kMAX_BACKTRACE_DEPTH];
2199  // retrieve current stack addresses
2200  int numstacks = backtrace( addrlist, sizeof( addrlist ) / sizeof( void* ));
2201 
2202  CSSymbolicatorRef symbolicator = CSSymbolicatorCreateWithPid(getpid());
2203 
2204  // skip TUnixSystem::Backtrace(), macosx_backtrace()
2205  static const int skipFrames = 2;
2206  for (int i = skipFrames; i < numstacks; ++i) {
2207  CSSourceInfoRef sourceInfo
2208  = CSSymbolicatorGetSourceInfoWithAddressAtTime(symbolicator,
2209  (vm_address_t)addrlist[i],
2210  0x80000000u /*"now"*/);
2211 
2212  CSSymbolOwnerRef symOwner = CSSourceInfoGetSymbolOwner(sourceInfo);
2213  if (const char* libPath = CSSymbolOwnerGetPath(symOwner)) {
2214  printf("[%s]", libPath);
2215  } else {
2216  printf("[<unknown binary>]");
2217  }
2218 
2219  CSSymbolRef sym = CSSourceInfoGetSymbol(sourceInfo);
2220  if (const char* symname = CSSymbolGetName(sym)) {
2221  printf(" %s %s:%d", symname, CSSourceInfoGetPath(sourceInfo),
2222  (int)CSSourceInfoGetLineNumber(sourceInfo));
2223  }
2224  printf("\n");
2225  }
2226 }
2227 #endif // R__MACOSX
2228 
2229 ////////////////////////////////////////////////////////////////////////////////
2230 /// Print a stack trace.
2231 
2233 {
2234  if (!gEnv->GetValue("Root.Stacktrace", 1))
2235  return;
2236 
2237 #ifndef R__MACOSX
2238  TString gdbscript = gEnv->GetValue("Root.StacktraceScript", "");
2239  gdbscript = gdbscript.Strip();
2240  if (gdbscript != "") {
2241  if (AccessPathName(gdbscript, kReadPermission)) {
2242  fprintf(stderr, "Root.StacktraceScript %s does not exist\n", gdbscript.Data());
2243  gdbscript = "";
2244  }
2245  }
2246  if (gdbscript == "") {
2247  gdbscript = "gdb-backtrace.sh";
2248  gSystem->PrependPathName(TROOT::GetEtcDir(), gdbscript);
2249  if (AccessPathName(gdbscript, kReadPermission)) {
2250  fprintf(stderr, "Error in <TUnixSystem::StackTrace> script %s is missing\n", gdbscript.Data());
2251  return;
2252  }
2253  }
2254  gdbscript += " ";
2255 
2256  TString gdbmess = gEnv->GetValue("Root.StacktraceMessage", "");
2257  gdbmess = gdbmess.Strip();
2258 
2259  std::cout.flush();
2260  fflush(stdout);
2261 
2262  std::cerr.flush();
2263  fflush(stderr);
2264 
2265  int fd = STDERR_FILENO;
2266 
2267  const char *message = " Generating stack trace...\n";
2268 
2269  if (fd && message) { } // remove unused warning (remove later)
2270 
2271  if (gApplication && !strcmp(gApplication->GetName(), "TRint"))
2272  Getlinem(kCleanUp, 0);
2273 
2274 #if defined(USE_GDB_STACK_TRACE)
2275  char *gdb = Which(Getenv("PATH"), "gdb", kExecutePermission);
2276  if (!gdb) {
2277  fprintf(stderr, "gdb not found, need it for stack trace\n");
2278  return;
2279  }
2280 
2281  // write custom message file
2282  TString gdbmessf = "gdb-message";
2283  if (gdbmess != "") {
2284  FILE *f = TempFileName(gdbmessf);
2285  fprintf(f, "%s\n", gdbmess.Data());
2286  fclose(f);
2287  }
2288 
2289  // use gdb to get stack trace
2290  gdbscript += GetExePath();
2291  gdbscript += " ";
2292  gdbscript += GetPid();
2293  if (gdbmess != "") {
2294  gdbscript += " ";
2295  gdbscript += gdbmessf;
2296  }
2297  gdbscript += " 1>&2";
2298  Exec(gdbscript);
2299  delete [] gdb;
2300  return;
2301 
2302 #elif defined(R__AIX)
2303  TString script = "procstack ";
2304  script += GetPid();
2305  Exec(script);
2306  return;
2307 #elif defined(R__SOLARIS)
2308  char *cppfilt = Which(Getenv("PATH"), "c++filt", kExecutePermission);
2309  TString script = "pstack ";
2310  script += GetPid();
2311  if (cppfilt) {
2312  script += " | ";
2313  script += cppfilt;
2314  delete [] cppfilt;
2315  }
2316  Exec(script);
2317  return;
2318 #elif defined(HAVE_BACKTRACE_SYMBOLS_FD) && defined(HAVE_DLADDR) // linux + MacOS X >= 10.5
2319  // we could have used backtrace_symbols_fd, except its output
2320  // format is pretty bad, so recode that here :-(
2321 
2322  // take care of demangling
2323  Bool_t demangle = kTRUE;
2324 
2325  // check for c++filt
2326  const char *cppfilt = "c++filt";
2327  const char *cppfiltarg = "";
2328 #ifdef R__B64
2329  const char *format1 = " 0x%016lx in %.200s %s 0x%lx from %.200s\n";
2330 #ifdef R__MACOSX
2331  const char *format2 = " 0x%016lx in %.200s\n";
2332 #else
2333  const char *format2 = " 0x%016lx in %.200s at %.200s from %.200s\n";
2334 #endif
2335  const char *format3 = " 0x%016lx in %.200s from %.200s\n";
2336  const char *format4 = " 0x%016lx in <unknown function>\n";
2337 #else
2338  const char *format1 = " 0x%08lx in %.200s %s 0x%lx from %.200s\n";
2339 #ifdef R__MACOSX
2340  const char *format2 = " 0x%08lx in %.200s\n";
2341 #else
2342  const char *format2 = " 0x%08lx in %.200s at %.200s from %.200s\n";
2343 #endif
2344  const char *format3 = " 0x%08lx in %.200s from %.200s\n";
2345  const char *format4 = " 0x%08lx in <unknown function>\n";
2346 #endif
2347 
2348  char *filter = Which(Getenv("PATH"), cppfilt, kExecutePermission);
2349  if (!filter)
2350  demangle = kFALSE;
2351 
2352 #if (__GNUC__ >= 3)
2353  // try finding supported format option for g++ v3
2354  if (filter) {
2355  FILE *p = OpenPipe(TString::Format("%s --help 2>&1", filter), "r");
2356  TString help;
2357  while (help.Gets(p)) {
2358  if (help.Index("gnu-v3") != kNPOS) {
2359  cppfiltarg = "--format=gnu-v3";
2360  break;
2361  } else if (help.Index("gnu-new-abi") != kNPOS) {
2362  cppfiltarg = "--format=gnu-new-abi";
2363  break;
2364  }
2365  }
2366  ClosePipe(p);
2367  }
2368 #endif
2369  // gdb-backtrace.sh uses gdb to produce a backtrace. See if it is available.
2370  // If it is, use it. If not proceed as before.
2371 #if (defined(R__LINUX) && !defined(R__WINGCC))
2372  // Declare the process that will be generating the stacktrace
2373  // For more see: http://askubuntu.com/questions/41629/after-upgrade-gdb-wont-attach-to-process
2374 #ifdef PR_SET_PTRACER
2375  prctl(PR_SET_PTRACER, getpid(), 0, 0, 0);
2376 #endif
2377 #endif
2378  char *gdb = Which(Getenv("PATH"), "gdb", kExecutePermission);
2379  if (gdb) {
2380  // write custom message file
2381  TString gdbmessf = "gdb-message";
2382  if (gdbmess != "") {
2383  FILE *f = TempFileName(gdbmessf);
2384  fprintf(f, "%s\n", gdbmess.Data());
2385  fclose(f);
2386  }
2387 
2388  // use gdb to get stack trace
2389 #ifdef R__MACOSX
2390  gdbscript += GetExePath();
2391  gdbscript += " ";
2392 #endif
2393  gdbscript += GetPid();
2394  if (gdbmess != "") {
2395  gdbscript += " ";
2396  gdbscript += gdbmessf;
2397  }
2398  gdbscript += " 1>&2";
2399  Exec(gdbscript);
2400  delete [] gdb;
2401  } else {
2402  // addr2line uses debug info to convert addresses into file names
2403  // and line numbers
2404 #ifdef R__MACOSX
2405  char *addr2line = Which(Getenv("PATH"), "atos", kExecutePermission);
2406 #else
2407  char *addr2line = Which(Getenv("PATH"), "addr2line", kExecutePermission);
2408 #endif
2409  if (addr2line) {
2410  // might take some time so tell what we are doing...
2411  if (write(fd, message, strlen(message)) < 0)
2412  Warning("StackTrace", "problems writing line numbers (errno: %d)", TSystem::GetErrno());
2413  }
2414 
2415  // open tmp file for demangled stack trace
2416  TString tmpf1 = "gdb-backtrace";
2417  std::ofstream file1;
2418  if (demangle) {
2419  FILE *f = TempFileName(tmpf1);
2420  if (f) fclose(f);
2421  file1.open(tmpf1);
2422  if (!file1) {
2423  Error("StackTrace", "could not open file %s", tmpf1.Data());
2424  Unlink(tmpf1);
2425  demangle = kFALSE;
2426  }
2427  }
2428 
2429 #ifdef R__MACOSX
2430  if (addr2line)
2431  demangle = kFALSE; // atos always demangles
2432 #endif
2433 
2434  char buffer[4096];
2435  void *trace[kMAX_BACKTRACE_DEPTH];
2436  int depth = backtrace(trace, kMAX_BACKTRACE_DEPTH);
2437  for (int n = 5; n < depth; n++) {
2438  ULong_t addr = (ULong_t) trace[n];
2439  Dl_info info;
2440 
2441  if (dladdr(trace[n], &info) && info.dli_fname && info.dli_fname[0]) {
2442  const char *libname = info.dli_fname;
2443  const char *symname = (info.dli_sname && info.dli_sname[0]) ?
2444  info.dli_sname : "<unknown>";
2445  ULong_t libaddr = (ULong_t) info.dli_fbase;
2446  ULong_t symaddr = (ULong_t) info.dli_saddr;
2447  Bool_t gte = (addr >= symaddr);
2448  ULong_t diff = (gte) ? addr - symaddr : symaddr - addr;
2449  if (addr2line && symaddr) {
2450  Bool_t nodebug = kTRUE;
2451 #ifdef R__MACOSX
2452  if (libaddr) { } // use libaddr
2453 #if defined(MAC_OS_X_VERSION_10_10)
2454  snprintf(buffer, sizeof(buffer), "%s -p %d 0x%016lx", addr2line, GetPid(), addr);
2455 #elif defined(MAC_OS_X_VERSION_10_9)
2456  // suppress deprecation warning with opti
2457  snprintf(buffer, sizeof(buffer), "%s -d -p %d 0x%016lx", addr2line, GetPid(), addr);
2458 #else
2459  snprintf(buffer, sizeof(buffer), "%s -p %d 0x%016lx", addr2line, GetPid(), addr);
2460 #endif
2461 #else
2462  ULong_t offset = (addr >= libaddr) ? addr - libaddr :
2463  libaddr - addr;
2464  TString name = TString(libname);
2465  Bool_t noPath = kFALSE;
2466  Bool_t noShare = kTRUE;
2467  if (name[0] != '/') noPath = kTRUE;
2468  if (name.Contains(".so") || name.Contains(".sl")) noShare = kFALSE;
2469  if (noShare) offset = addr;
2470  if (noPath) name = "`which " + name + "`";
2471  snprintf(buffer, sizeof(buffer), "%s -e %s 0x%016lx", addr2line, name.Data(), offset);
2472 #endif
2473  if (FILE *pf = ::popen(buffer, "r")) {
2474  char buf[2048];
2475  if (fgets(buf, 2048, pf)) {
2476  buf[strlen(buf)-1] = 0; // remove trailing \n
2477  if (strncmp(buf, "??", 2)) {
2478 #ifdef R__MACOSX
2479  snprintf(buffer, sizeof(buffer), format2, addr, buf);
2480 #else
2481  snprintf(buffer, sizeof(buffer), format2, addr, symname, buf, libname);
2482 #endif
2483  nodebug = kFALSE;
2484  }
2485  }
2486  ::pclose(pf);
2487  }
2488  if (nodebug)
2489  snprintf(buffer, sizeof(buffer), format1, addr, symname,
2490  gte ? "+" : "-", diff, libname);
2491  } else {
2492  if (symaddr)
2493  snprintf(buffer, sizeof(buffer), format1, addr, symname,
2494  gte ? "+" : "-", diff, libname);
2495  else
2496  snprintf(buffer, sizeof(buffer), format3, addr, symname, libname);
2497  }
2498  } else {
2499  snprintf(buffer, sizeof(buffer), format4, addr);
2500  }
2501 
2502  if (demangle)
2503  file1 << buffer;
2504  else
2505  if (write(fd, buffer, ::strlen(buffer)) < 0)
2506  Warning("StackTrace", "problems writing buffer (errno: %d)", TSystem::GetErrno());
2507  }
2508 
2509  if (demangle) {
2510  TString tmpf2 = "gdb-backtrace";
2511  FILE *f = TempFileName(tmpf2);
2512  if (f) fclose(f);
2513  file1.close();
2514  snprintf(buffer, sizeof(buffer), "%s %s < %s > %s", filter, cppfiltarg, tmpf1.Data(), tmpf2.Data());
2515  Exec(buffer);
2516  std::ifstream file2(tmpf2);
2517  TString line;
2518  while (file2) {
2519  line = "";
2520  line.ReadString(file2);
2521  if (write(fd, line.Data(), line.Length()) < 0)
2522  Warning("StackTrace", "problems writing line (errno: %d)", TSystem::GetErrno());
2523  }
2524  file2.close();
2525  Unlink(tmpf1);
2526  Unlink(tmpf2);
2527  }
2528 
2529  delete [] addr2line;
2530  }
2531  delete [] filter;
2532 #elif defined(HAVE_EXCPT_H) && defined(HAVE_PDSC_H) && \
2533  defined(HAVE_RLD_INTERFACE_H) // tru64
2534  // Tru64 stack walk. Uses the exception handling library and the
2535  // run-time linker's core functions (loader(5)). FIXME: Tru64
2536  // should have _RLD_DLADDR like IRIX below. Verify and update.
2537 
2538  char buffer [128];
2539  sigcontext context;
2540  int rc = 0;
2541 
2542  exc_capture_context (&context);
2543  while (!rc && context.sc_pc) {
2544  // FIXME: Elf32?
2545  pdsc_crd *func, *base, *crd
2546  = exc_remote_lookup_function_entry(0, 0, context.sc_pc, 0, &func, &base);
2547  Elf32_Addr addr = PDSC_CRD_BEGIN_ADDRESS(base, func);
2548  // const char *name = _rld_address_to_name(addr);
2549  const char *name = "<unknown function>";
2550  sprintf(buffer, " 0x%012lx %.200s + 0x%lx\n",
2551  context.sc_pc, name, context.sc_pc - addr);
2552  write(fd, buffer, ::strlen(buffer));
2553  rc = exc_virtual_unwind(0, &context);
2554  }
2555 #endif
2556 #else //R__MACOSX
2557  macosx_backtrace();
2558 #endif //R__MACOSX
2559 }
2560 
2561 //---- System Logging ----------------------------------------------------------
2562 
2563 ////////////////////////////////////////////////////////////////////////////////
2564 /// Open connection to system log daemon. For the use of the options and
2565 /// facility see the Unix openlog man page.
2566 
2567 void TUnixSystem::Openlog(const char *name, Int_t options, ELogFacility facility)
2568 {
2569  int fac = 0;
2570 
2571  switch (facility) {
2572  case kLogLocal0:
2573  fac = LOG_LOCAL0;
2574  break;
2575  case kLogLocal1:
2576  fac = LOG_LOCAL1;
2577  break;
2578  case kLogLocal2:
2579  fac = LOG_LOCAL2;
2580  break;
2581  case kLogLocal3:
2582  fac = LOG_LOCAL3;
2583  break;
2584  case kLogLocal4:
2585  fac = LOG_LOCAL4;
2586  break;
2587  case kLogLocal5:
2588  fac = LOG_LOCAL5;
2589  break;
2590  case kLogLocal6:
2591  fac = LOG_LOCAL6;
2592  break;
2593  case kLogLocal7:
2594  fac = LOG_LOCAL7;
2595  break;
2596  }
2597 
2598  ::openlog(name, options, fac);
2599 }
2600 
2601 ////////////////////////////////////////////////////////////////////////////////
2602 /// Send mess to syslog daemon. Level is the logging level and mess the
2603 /// message that will be written on the log.
2604 
2605 void TUnixSystem::Syslog(ELogLevel level, const char *mess)
2606 {
2607  // ELogLevel matches exactly the Unix values.
2608  ::syslog(level, "%s", mess);
2609 }
2610 
2611 ////////////////////////////////////////////////////////////////////////////////
2612 /// Close connection to system log daemon.
2613 
2615 {
2616  ::closelog();
2617 }
2618 
2619 //---- Standard output redirection ---------------------------------------------
2620 
2621 ////////////////////////////////////////////////////////////////////////////////
2622 /// Redirect standard output (stdout, stderr) to the specified file.
2623 /// If the file argument is 0 the output is set again to stderr, stdout.
2624 /// The second argument specifies whether the output should be added to the
2625 /// file ("a", default) or the file be truncated before ("w").
2626 /// This function saves internally the current state into a static structure.
2627 /// The call can be made reentrant by specifying the opaque structure pointed
2628 /// by 'h', which is filled with the relevant information. The handle 'h'
2629 /// obtained on the first call must then be used in any subsequent call,
2630 /// included ShowOutput, to display the redirected output.
2631 /// Returns 0 on success, -1 in case of error.
2632 
2633 Int_t TUnixSystem::RedirectOutput(const char *file, const char *mode,
2635 {
2636  // Instance to be used if the caller does not passes 'h'
2637  static RedirectHandle_t loch;
2638 
2639  Int_t rc = 0;
2640 
2641  // Which handle to use ?
2642  RedirectHandle_t *xh = (h) ? h : &loch;
2643 
2644  if (file) {
2645  // Save the paths
2646  Bool_t outdone = kFALSE;
2647  if (xh->fStdOutTty.IsNull()) {
2648  const char *tty = ttyname(STDOUT_FILENO);
2649  if (tty) {
2650  xh->fStdOutTty = tty;
2651  } else {
2652  if ((xh->fStdOutDup = dup(STDOUT_FILENO)) < 0) {
2653  SysError("RedirectOutput", "could not 'dup' stdout (errno: %d)", TSystem::GetErrno());
2654  return -1;
2655  }
2656  outdone = kTRUE;
2657  }
2658  }
2659  if (xh->fStdErrTty.IsNull()) {
2660  const char *tty = ttyname(STDERR_FILENO);
2661  if (tty) {
2662  xh->fStdErrTty = tty;
2663  } else {
2664  if ((xh->fStdErrDup = dup(STDERR_FILENO)) < 0) {
2665  SysError("RedirectOutput", "could not 'dup' stderr (errno: %d)", TSystem::GetErrno());
2666  if (outdone && dup2(xh->fStdOutDup, STDOUT_FILENO) < 0) {
2667  Warning("RedirectOutput", "could not restore stdout (back to original redirected"
2668  " file) (errno: %d)", TSystem::GetErrno());
2669  }
2670  return -1;
2671  }
2672  }
2673  }
2674 
2675  // Make sure mode makes sense; default "a"
2676  const char *m = (mode[0] == 'a' || mode[0] == 'w') ? mode : "a";
2677 
2678  // Current file size
2679  xh->fReadOffSet = 0;
2680  if (m[0] == 'a') {
2681  // If the file exists, save the current size
2682  FileStat_t st;
2683  if (!gSystem->GetPathInfo(file, st))
2684  xh->fReadOffSet = (st.fSize > 0) ? st.fSize : xh->fReadOffSet;
2685  }
2686  xh->fFile = file;
2687 
2688  // Redirect stdout & stderr
2689  if (freopen(file, m, stdout) == 0) {
2690  SysError("RedirectOutput", "could not freopen stdout (errno: %d)", TSystem::GetErrno());
2691  return -1;
2692  }
2693  if (freopen(file, m, stderr) == 0) {
2694  SysError("RedirectOutput", "could not freopen stderr (errno: %d)", TSystem::GetErrno());
2695  if (freopen(xh->fStdOutTty.Data(), "a", stdout) == 0)
2696  SysError("RedirectOutput", "could not restore stdout (errno: %d)", TSystem::GetErrno());
2697  return -1;
2698  }
2699  } else {
2700  // Restore stdout & stderr
2701  fflush(stdout);
2702  if (!(xh->fStdOutTty.IsNull())) {
2703  if (freopen(xh->fStdOutTty.Data(), "a", stdout) == 0) {
2704  SysError("RedirectOutput", "could not restore stdout (errno: %d)", TSystem::GetErrno());
2705  rc = -1;
2706  }
2707  xh->fStdOutTty = "";
2708  } else {
2709  if (close(STDOUT_FILENO) != 0) {
2710  SysError("RedirectOutput",
2711  "problems closing STDOUT_FILENO (%d) before 'dup2' (errno: %d)",
2712  STDOUT_FILENO, TSystem::GetErrno());
2713  rc = -1;
2714  }
2715  if (dup2(xh->fStdOutDup, STDOUT_FILENO) < 0) {
2716  SysError("RedirectOutput", "could not restore stdout (back to original redirected"
2717  " file) (errno: %d)", TSystem::GetErrno());
2718  rc = -1;
2719  }
2720  if (close(xh->fStdOutDup) != 0) {
2721  SysError("RedirectOutput",
2722  "problems closing temporary 'out' descriptor %d (errno: %d)",
2723  TSystem::GetErrno(), xh->fStdOutDup);
2724  rc = -1;
2725  }
2726  }
2727  fflush(stderr);
2728  if (!(xh->fStdErrTty.IsNull())) {
2729  if (freopen(xh->fStdErrTty.Data(), "a", stderr) == 0) {
2730  SysError("RedirectOutput", "could not restore stderr (errno: %d)", TSystem::GetErrno());
2731  rc = -1;
2732  }
2733  xh->fStdErrTty = "";
2734  } else {
2735  if (close(STDERR_FILENO) != 0) {
2736  SysError("RedirectOutput",
2737  "problems closing STDERR_FILENO (%d) before 'dup2' (errno: %d)",
2738  STDERR_FILENO, TSystem::GetErrno());
2739  rc = -1;
2740  }
2741  if (dup2(xh->fStdErrDup, STDERR_FILENO) < 0) {
2742  SysError("RedirectOutput", "could not restore stderr (back to original redirected"
2743  " file) (errno: %d)", TSystem::GetErrno());
2744  rc = -1;
2745  }
2746  if (close(xh->fStdErrDup) != 0) {
2747  SysError("RedirectOutput",
2748  "problems closing temporary 'err' descriptor %d (errno: %d)",
2749  TSystem::GetErrno(), xh->fStdErrDup);
2750  rc = -1;
2751  }
2752  }
2753  // Reset the static instance, if using that
2754  if (xh == &loch)
2755  xh->Reset();
2756  }
2757  return rc;
2758 }
2759 
2760 //---- dynamic loading and linking ---------------------------------------------
2761 
2762 ////////////////////////////////////////////////////////////////////////////////
2763 ///dynamic linking of module
2764 
2765 Func_t TUnixSystem::DynFindSymbol(const char * /*module*/, const char *entry)
2766 {
2767  return TSystem::DynFindSymbol("*", entry);
2768 }
2769 
2770 ////////////////////////////////////////////////////////////////////////////////
2771 /// Load a shared library. Returns 0 on successful loading, 1 in
2772 /// case lib was already loaded and -1 in case lib does not exist
2773 /// or in case of error.
2774 
2775 int TUnixSystem::Load(const char *module, const char *entry, Bool_t system)
2776 {
2777  return TSystem::Load(module, entry, system);
2778 }
2779 
2780 ////////////////////////////////////////////////////////////////////////////////
2781 /// Unload a shared library.
2782 
2783 void TUnixSystem::Unload(const char *module)
2784 {
2785  if (module) { TSystem::Unload(module); }
2786 }
2787 
2788 ////////////////////////////////////////////////////////////////////////////////
2789 /// List symbols in a shared library.
2790 
2791 void TUnixSystem::ListSymbols(const char * /*module*/, const char * /*regexp*/)
2792 {
2793  Error("ListSymbols", "not yet implemented");
2794 }
2795 
2796 ////////////////////////////////////////////////////////////////////////////////
2797 /// List all loaded shared libraries.
2798 
2799 void TUnixSystem::ListLibraries(const char *regexp)
2800 {
2801  TSystem::ListLibraries(regexp);
2802 }
2803 
2804 ////////////////////////////////////////////////////////////////////////////////
2805 /// Get list of shared libraries loaded at the start of the executable.
2806 /// Returns 0 in case list cannot be obtained or in case of error.
2807 
2809 {
2810  static TString linkedLibs;
2811  static Bool_t once = kFALSE;
2812 
2814 
2815  if (!linkedLibs.IsNull())
2816  return linkedLibs;
2817 
2818  if (once)
2819  return 0;
2820 
2821 #if !defined(R__MACOSX)
2822  const char *exe = GetExePath();
2823  if (!exe || !*exe)
2824  return 0;
2825 #endif
2826 
2827 #if defined(R__MACOSX)
2828  DylibAdded(0, 0);
2829  linkedLibs = gLinkedDylibs;
2830 #if 0
2831  FILE *p = OpenPipe(TString::Format("otool -L %s", exe), "r");
2832  TString otool;
2833  while (otool.Gets(p)) {
2834  TString delim(" \t");
2835  TObjArray *tok = otool.Tokenize(delim);
2836  TString dylib = ((TObjString*)tok->At(0))->String();
2837  if (dylib.EndsWith(".dylib") && !dylib.Contains("/libSystem.B.dylib")) {
2838  if (!linkedLibs.IsNull())
2839  linkedLibs += " ";
2840  linkedLibs += dylib;
2841  }
2842  delete tok;
2843  }
2844  if (p) {
2845  ClosePipe(p);
2846  }
2847 #endif
2848 #elif defined(R__LINUX) || defined(R__SOLARIS) || defined(R__AIX)
2849 #if defined(R__WINGCC )
2850  const char *cLDD="cygcheck";
2851  const char *cSOEXT=".dll";
2852  size_t lenexe = strlen(exe);
2853  if (strcmp(exe + lenexe - 4, ".exe")
2854  && strcmp(exe + lenexe - 4, ".dll")) {
2855  // it's not a dll and exe doesn't end on ".exe";
2856  // need to add it for cygcheck to find it:
2857  char* longerexe = new char[lenexe + 5];
2858  strlcpy(longerexe, exe,lenexe+5);
2859  strlcat(longerexe, ".exe",lenexe+5);
2860  delete [] exe;
2861  exe = longerexe;
2862  }
2863  TRegexp sovers = "\\.so\\.[0-9]+";
2864 #else
2865  const char *cLDD="ldd";
2866 #if defined(R__AIX)
2867  const char *cSOEXT=".a";
2868  TRegexp sovers = "\\.a\\.[0-9]+";
2869 #else
2870  const char *cSOEXT=".so";
2871  TRegexp sovers = "\\.so\\.[0-9]+";
2872 #endif
2873 #endif
2874  FILE *p = OpenPipe(TString::Format("%s '%s'", cLDD, exe), "r");
2875  if (p) {
2876  TString ldd;
2877  while (ldd.Gets(p)) {
2878  TString delim(" \t");
2879  TObjArray *tok = ldd.Tokenize(delim);
2880 
2881  // expected format:
2882  // libCore.so => /home/rdm/root/lib/libCore.so (0x40017000)
2883  TObjString *solibName = (TObjString*)tok->At(2);
2884  if (!solibName) {
2885  // case where there is only one name of the list:
2886  // /usr/platform/SUNW,UltraAX-i2/lib/libc_psr.so.1
2887  solibName = (TObjString*)tok->At(0);
2888  }
2889  if (solibName) {
2890  TString solib = solibName->String();
2891  Ssiz_t idx = solib.Index(sovers);
2892  if (solib.EndsWith(cSOEXT) || idx != kNPOS) {
2893  if (idx != kNPOS)
2894  solib.Remove(idx+3);
2895  if (!AccessPathName(solib, kReadPermission)) {
2896  if (!linkedLibs.IsNull())
2897  linkedLibs += " ";
2898  linkedLibs += solib;
2899  }
2900  }
2901  }
2902  delete tok;
2903  }
2904  ClosePipe(p);
2905  }
2906 #endif
2907 
2908  once = kTRUE;
2909 
2910  if (linkedLibs.IsNull())
2911  return 0;
2912 
2913  return linkedLibs;
2914 }
2915 
2916 //---- Time & Date -------------------------------------------------------------
2917 
2918 ////////////////////////////////////////////////////////////////////////////////
2919 /// Get current time in milliseconds since 0:00 Jan 1 1995.
2920 
2922 {
2923  return UnixNow();
2924 }
2925 
2926 ////////////////////////////////////////////////////////////////////////////////
2927 /// Handle and dispatch timers. If mode = kTRUE dispatch synchronous
2928 /// timers else a-synchronous timers.
2929 
2931 {
2932  if (!fTimers) return kFALSE;
2933 
2934  fInsideNotify = kTRUE;
2935 
2937  TTimer *t;
2938  Bool_t timedout = kFALSE;
2939 
2940  while ((t = (TTimer *) it.Next())) {
2941  // NB: the timer resolution is added in TTimer::CheckTimer()
2942  Long64_t now = UnixNow();
2943  if (mode && t->IsSync()) {
2944  if (t->CheckTimer(now))
2945  timedout = kTRUE;
2946  } else if (!mode && t->IsAsync()) {
2947  if (t->CheckTimer(now)) {
2949  timedout = kTRUE;
2950  }
2951  }
2952  }
2954  return timedout;
2955 }
2956 
2957 ////////////////////////////////////////////////////////////////////////////////
2958 /// Add timer to list of system timers.
2959 
2961 {
2962  TSystem::AddTimer(ti);
2963  ResetTimer(ti);
2964 }
2965 
2966 ////////////////////////////////////////////////////////////////////////////////
2967 /// Remove timer from list of system timers.
2968 
2970 {
2971  if (!ti) return 0;
2972 
2974 
2975  TTimer *t = TSystem::RemoveTimer(ti);
2976  if (ti->IsAsync())
2978  return t;
2979 }
2980 
2981 ////////////////////////////////////////////////////////////////////////////////
2982 /// Reset a-sync timer.
2983 
2985 {
2986  if (!fInsideNotify && ti && ti->IsAsync())
2988 }
2989 
2990 //---- RPC ---------------------------------------------------------------------
2991 
2992 ////////////////////////////////////////////////////////////////////////////////
2993 /// Get Internet Protocol (IP) address of host. Returns an TInetAddress
2994 /// object. To see if the hostname lookup was successfull call
2995 /// TInetAddress::IsValid().
2996 
2998 {
2999  UInt_t addr; // good for 4 byte addresses
3000  Bool_t isinaddr = kFALSE;
3001 #ifdef HASNOT_INETATON
3002  isinaddr = (addr = (UInt_t)inet_addr(hostname)) != INADDR_NONE) ? kTRUE : kFALSE;
3003 #else
3004  struct in_addr ad;
3005  isinaddr = inet_aton(hostname, &ad);
3006  if (isinaddr) memcpy(&addr, &ad.s_addr, sizeof(ad.s_addr));
3007 #endif
3008 
3009  std::string host(hostname);
3010  if (isinaddr) {
3011  struct sockaddr_in sin;
3012  sin.sin_family = AF_INET;
3013  sin.sin_port = 0;
3014  memcpy(&sin.sin_addr.s_addr, &addr, sizeof(sin.sin_addr.s_addr));
3015  memset(&sin.sin_zero[0], 0, sizeof(sin.sin_zero));
3016  struct sockaddr *sa = (struct sockaddr *) &sin; /* input */
3017 
3018  char hbuf[NI_MAXHOST];
3019 
3020  int rc = getnameinfo(sa, sizeof(struct sockaddr), hbuf, sizeof(hbuf), nullptr, 0, NI_NAMEREQD);
3021  if (rc != 0 ) {
3022  if (rc == EAI_NONAME) {
3023  if (gDebug > 0)
3024  Error("GetHostByName", "unknown host '%s'", hostname);
3025  return TInetAddress("UnNamedHost", 0, -1);
3026  } else {
3027  Error("GetHostByName", "getnameinfo failed for '%s': '%s'", hostname, gai_strerror(rc));
3028  return TInetAddress();
3029  }
3030  }
3031  host = hbuf;
3032  }
3033 
3034  // Hints structure
3035  struct addrinfo hints;
3036  memset(&hints, 0, sizeof(struct addrinfo));
3037  hints.ai_family = AF_INET; // Ask IPv4
3038  hints.ai_socktype = 0; // Any socket type
3039  hints.ai_flags = AI_CANONNAME; // Get canonical name
3040  hints.ai_protocol = 0; // Any protocol
3041  hints.ai_canonname = nullptr;
3042  hints.ai_addr = nullptr;
3043  hints.ai_next = nullptr;
3044 
3045  struct addrinfo *res;
3046  int rc = getaddrinfo(host.c_str(), nullptr, &hints, &res);
3047  if (rc != 0) {
3048  if (rc == EAI_NONAME) {
3049  if (gDebug > 0)
3050  Error("GetHostByName", "unknown host '%s'", host.c_str());
3051  return TInetAddress("UnNamedHost", 0, -1);
3052  } else {
3053  Error("GetHostByName", "getaddrinfo failed for '%s': '%s'", host.c_str(), gai_strerror(rc));
3054  return TInetAddress();
3055  }
3056  }
3057  if (res[0].ai_canonname) host = res[0].ai_canonname;
3058  // Prepare output
3059  TInetAddress a(host.c_str(),
3060  ntohl(((sockaddr_in *)(res[0].ai_addr))->sin_addr.s_addr),
3061  res[0].ai_family);
3062  struct addrinfo *rp = res[0].ai_next;
3063  for (; rp != NULL; rp = rp->ai_next) {
3064  UInt_t arp = ntohl(((sockaddr_in *)(rp->ai_addr))->sin_addr.s_addr);
3065  std::vector<UInt_t> addrs = a.GetAddresses();
3066  Bool_t newad = kTRUE;
3067  for (UInt_t sad : addrs) {
3068  if (sad == arp) {
3069  newad = kFALSE;
3070  break;
3071  }
3072  }
3073  if (newad) {
3074  a.AddAddress(ntohl(((sockaddr_in *)(rp->ai_addr))->sin_addr.s_addr));
3075  if (rp->ai_canonname) a.AddAlias(rp->ai_canonname);
3076  }
3077  }
3078  // Release memory
3079  freeaddrinfo(res);
3080  // Done
3081  return a;
3082 }
3083 
3084 ////////////////////////////////////////////////////////////////////////////////
3085 /// Get Internet Protocol (IP) address of host and port #.
3086 
3088 {
3089  struct sockaddr_in addr;
3090 #if defined(USE_SIZE_T)
3091  size_t len = sizeof(addr);
3092 #elif defined(USE_SOCKLEN_T)
3093  socklen_t len = sizeof(addr);
3094 #else
3095  int len = sizeof(addr);
3096 #endif
3097 
3098  if (getsockname(sock, (struct sockaddr *)&addr, &len) == -1) {
3099  SysError("GetSockName", "getsockname");
3100  return TInetAddress();
3101  }
3102 
3103  struct sockaddr *sa = (struct sockaddr *) &addr; /* input */
3104  char hbuf[NI_MAXHOST];
3105  int rc = 0;
3106  if ((rc = getnameinfo(sa, sizeof(struct sockaddr), hbuf, sizeof(hbuf),
3107  nullptr, 0, 0)) == 0) {
3108  TInetAddress a = GetHostByName(hbuf);
3109  if (a.IsValid()) {
3110  a.fFamily = addr.sin_family;
3111  a.fPort = ntohs(addr.sin_port);
3112  return a;
3113  }
3114  }
3115  // Failure: return minimal information
3116  UInt_t iaddr;
3117  memcpy(&iaddr, &addr.sin_addr, sizeof(addr.sin_addr));
3118  return TInetAddress("????", ntohl(iaddr), AF_INET, ntohs(addr.sin_port));
3119 }
3120 
3121 ////////////////////////////////////////////////////////////////////////////////
3122 /// Get Internet Protocol (IP) address of remote host and port #.
3123 
3125 {
3126  struct sockaddr_in addr;
3127 #if defined(USE_SIZE_T)
3128  size_t len = sizeof(addr);
3129 #elif defined(USE_SOCKLEN_T)
3130  socklen_t len = sizeof(addr);
3131 #else
3132  int len = sizeof(addr);
3133 #endif
3134 
3135  if (getpeername(sock, (struct sockaddr *)&addr, &len) == -1) {
3136  SysError("GetPeerName", "getpeername");
3137  return TInetAddress();
3138  }
3139 
3140  int rc = 0;
3141  struct sockaddr *sa = (struct sockaddr *) &addr; /* input */
3142  char hbuf[NI_MAXHOST];
3143  if ((rc = getnameinfo(sa, sizeof(struct sockaddr), hbuf, sizeof(hbuf),
3144  nullptr, 0, 0)) == 0) {
3145  TInetAddress a = GetHostByName(hbuf);
3146  if (a.IsValid()) {
3147  a.fFamily = addr.sin_family;
3148  a.fPort = ntohs(addr.sin_port);
3149  return a;
3150  }
3151  }
3152  // Failure: return minimal information
3153  UInt_t iaddr;
3154  memcpy(&iaddr, &addr.sin_addr, sizeof(addr.sin_addr));
3155  return TInetAddress("????", ntohl(iaddr), AF_INET, ntohs(addr.sin_port));
3156 }
3157 
3158 ////////////////////////////////////////////////////////////////////////////////
3159 /// Get port # of internet service.
3160 
3161 int TUnixSystem::GetServiceByName(const char *servicename)
3162 {
3163  struct servent *sp;
3164 
3165  if ((sp = getservbyname(servicename, kProtocolName)) == 0) {
3166  Error("GetServiceByName", "no service \"%s\" with protocol \"%s\"\n",
3167  servicename, kProtocolName);
3168  return -1;
3169  }
3170  return ntohs(sp->s_port);
3171 }
3172 
3173 ////////////////////////////////////////////////////////////////////////////////
3174 /// Get name of internet service.
3175 
3177 {
3178  struct servent *sp;
3179 
3180  if ((sp = getservbyport(htons(port), kProtocolName)) == 0) {
3181  //::Error("GetServiceByPort", "no service \"%d\" with protocol \"%s\"",
3182  // port, kProtocolName);
3183  return Form("%d", port);
3184  }
3185  return sp->s_name;
3186 }
3187 
3188 ////////////////////////////////////////////////////////////////////////////////
3189 /// Connect to service servicename on server servername.
3190 
3191 int TUnixSystem::ConnectService(const char *servername, int port,
3192  int tcpwindowsize, const char *protocol)
3193 {
3194  if (!strcmp(servername, "unix")) {
3195  return UnixUnixConnect(port);
3196  } else if (!gSystem->AccessPathName(servername) || servername[0] == '/') {
3197  return UnixUnixConnect(servername);
3198  }
3199 
3200  if (!strcmp(protocol, "udp")){
3201  return UnixUdpConnect(servername, port);
3202  }
3203 
3204  return UnixTcpConnect(servername, port, tcpwindowsize);
3205 }
3206 
3207 ////////////////////////////////////////////////////////////////////////////////
3208 /// Open a connection to a service on a server. Returns -1 in case
3209 /// connection cannot be opened.
3210 /// Use tcpwindowsize to specify the size of the receive buffer, it has
3211 /// to be specified here to make sure the window scale option is set (for
3212 /// tcpwindowsize > 65KB and for platforms supporting window scaling).
3213 /// Is called via the TSocket constructor.
3214 
3215 int TUnixSystem::OpenConnection(const char *server, int port, int tcpwindowsize, const char *protocol)
3216 {
3217  return ConnectService(server, port, tcpwindowsize, protocol);
3218 }
3219 
3220 ////////////////////////////////////////////////////////////////////////////////
3221 /// Announce TCP/IP service.
3222 /// Open a socket, bind to it and start listening for TCP/IP connections
3223 /// on the port. If reuse is true reuse the address, backlog specifies
3224 /// how many sockets can be waiting to be accepted.
3225 /// Use tcpwindowsize to specify the size of the receive buffer, it has
3226 /// to be specified here to make sure the window scale option is set (for
3227 /// tcpwindowsize > 65KB and for platforms supporting window scaling).
3228 /// Returns socket fd or -1 if socket() failed, -2 if bind() failed
3229 /// or -3 if listen() failed.
3230 
3231 int TUnixSystem::AnnounceTcpService(int port, Bool_t reuse, int backlog,
3232  int tcpwindowsize)
3233 {
3234  return UnixTcpService(port, reuse, backlog, tcpwindowsize);
3235 }
3236 
3237 ////////////////////////////////////////////////////////////////////////////////
3238 /// Announce UDP service.
3239 
3240 int TUnixSystem::AnnounceUdpService(int port, int backlog)
3241 {
3242  return UnixUdpService(port, backlog);
3243 }
3244 
3245 ////////////////////////////////////////////////////////////////////////////////
3246 /// Announce unix domain service on path "kServerPath/<port>"
3247 
3248 int TUnixSystem::AnnounceUnixService(int port, int backlog)
3249 {
3250  return UnixUnixService(port, backlog);
3251 }
3252 
3253 ////////////////////////////////////////////////////////////////////////////////
3254 /// Announce unix domain service on path 'sockpath'
3255 
3256 int TUnixSystem::AnnounceUnixService(const char *sockpath, int backlog)
3257 {
3258  return UnixUnixService(sockpath, backlog);
3259 }
3260 
3261 ////////////////////////////////////////////////////////////////////////////////
3262 /// Accept a connection. In case of an error return -1. In case
3263 /// non-blocking I/O is enabled and no connections are available
3264 /// return -2.
3265 
3267 {
3268  int soc = -1;
3269 
3270  while ((soc = ::accept(sock, 0, 0)) == -1 && GetErrno() == EINTR)
3271  ResetErrno();
3272 
3273  if (soc == -1) {
3274  if (GetErrno() == EWOULDBLOCK)
3275  return -2;
3276  else {
3277  SysError("AcceptConnection", "accept");
3278  return -1;
3279  }
3280  }
3281 
3282  return soc;
3283 }
3284 
3285 ////////////////////////////////////////////////////////////////////////////////
3286 /// Close socket.
3287 
3289 {
3290  if (sock < 0) return;
3291 
3292 #if !defined(R__AIX) || defined(_AIX41) || defined(_AIX43)
3293  if (force)
3294  ::shutdown(sock, 2); // will also close connection of parent
3295 #endif
3296 
3297  while (::close(sock) == -1 && GetErrno() == EINTR)
3298  ResetErrno();
3299 }
3300 
3301 ////////////////////////////////////////////////////////////////////////////////
3302 /// Receive a buffer headed by a length indicator. Length is the size of
3303 /// the buffer. Returns the number of bytes received in buf or -1 in
3304 /// case of error.
3305 
3306 int TUnixSystem::RecvBuf(int sock, void *buf, int length)
3307 {
3308  Int_t header;
3309 
3310  if (UnixRecv(sock, &header, sizeof(header), 0) > 0) {
3311  int count = ntohl(header);
3312 
3313  if (count > length) {
3314  Error("RecvBuf", "record header exceeds buffer size");
3315  return -1;
3316  } else if (count > 0) {
3317  if (UnixRecv(sock, buf, count, 0) < 0) {
3318  Error("RecvBuf", "cannot receive buffer");
3319  return -1;
3320  }
3321  }
3322  return count;
3323  }
3324  return -1;
3325 }
3326 
3327 ////////////////////////////////////////////////////////////////////////////////
3328 /// Send a buffer headed by a length indicator. Returns length of sent buffer
3329 /// or -1 in case of error.
3330 
3331 int TUnixSystem::SendBuf(int sock, const void *buf, int length)
3332 {
3333  Int_t header = htonl(length);
3334 
3335  if (UnixSend(sock, &header, sizeof(header), 0) < 0) {
3336  Error("SendBuf", "cannot send header");
3337  return -1;
3338  }
3339  if (length > 0) {
3340  if (UnixSend(sock, buf, length, 0) < 0) {
3341  Error("SendBuf", "cannot send buffer");
3342  return -1;
3343  }
3344  }
3345  return length;
3346 }
3347 
3348 ////////////////////////////////////////////////////////////////////////////////
3349 /// Receive exactly length bytes into buffer. Use opt to receive out-of-band
3350 /// data or to have a peek at what is in the buffer (see TSocket). Buffer
3351 /// must be able to store at least length bytes. Returns the number of
3352 /// bytes received (can be 0 if other side of connection was closed) or -1
3353 /// in case of error, -2 in case of MSG_OOB and errno == EWOULDBLOCK, -3
3354 /// in case of MSG_OOB and errno == EINVAL and -4 in case of kNoBlock and
3355 /// errno == EWOULDBLOCK. Returns -5 if pipe broken or reset by peer
3356 /// (EPIPE || ECONNRESET).
3357 
3358 int TUnixSystem::RecvRaw(int sock, void *buf, int length, int opt)
3359 {
3360  int flag;
3361 
3362  switch (opt) {
3363  case kDefault:
3364  flag = 0;
3365  break;
3366  case kOob:
3367  flag = MSG_OOB;
3368  break;
3369  case kPeek:
3370  flag = MSG_PEEK;
3371  break;
3372  case kDontBlock:
3373  flag = -1;
3374  break;
3375  default:
3376  flag = 0;
3377  break;
3378  }
3379 
3380  int n;
3381  if ((n = UnixRecv(sock, buf, length, flag)) <= 0) {
3382  if (n == -1 && GetErrno() != EINTR)
3383  Error("RecvRaw", "cannot receive buffer");
3384  return n;
3385  }
3386  return n;
3387 }
3388 
3389 ////////////////////////////////////////////////////////////////////////////////
3390 /// Send exactly length bytes from buffer. Use opt to send out-of-band
3391 /// data (see TSocket). Returns the number of bytes sent or -1 in case of
3392 /// error. Returns -4 in case of kNoBlock and errno == EWOULDBLOCK.
3393 /// Returns -5 if pipe broken or reset by peer (EPIPE || ECONNRESET).
3394 
3395 int TUnixSystem::SendRaw(int sock, const void *buf, int length, int opt)
3396 {
3397  int flag;
3398 
3399  switch (opt) {
3400  case kDefault:
3401  flag = 0;
3402  break;
3403  case kOob:
3404  flag = MSG_OOB;
3405  break;
3406  case kDontBlock:
3407  flag = -1;
3408  break;
3409  case kPeek: // receive only option (see RecvRaw)
3410  default:
3411  flag = 0;
3412  break;
3413  }
3414 
3415  int n;
3416  if ((n = UnixSend(sock, buf, length, flag)) <= 0) {
3417  if (n == -1 && GetErrno() != EINTR)
3418  Error("SendRaw", "cannot send buffer");
3419  return n;
3420  }
3421  return n;
3422 }
3423 
3424 ////////////////////////////////////////////////////////////////////////////////
3425 /// Set socket option.
3426 
3427 int TUnixSystem::SetSockOpt(int sock, int opt, int val)
3428 {
3429  if (sock < 0) return -1;
3430 
3431  switch (opt) {
3432  case kSendBuffer:
3433  if (setsockopt(sock, SOL_SOCKET, SO_SNDBUF, (char*)&val, sizeof(val)) == -1) {
3434  SysError("SetSockOpt", "setsockopt(SO_SNDBUF)");
3435  return -1;
3436  }
3437  break;
3438  case kRecvBuffer:
3439  if (setsockopt(sock, SOL_SOCKET, SO_RCVBUF, (char*)&val, sizeof(val)) == -1) {
3440  SysError("SetSockOpt", "setsockopt(SO_RCVBUF)");
3441  return -1;
3442  }
3443  break;
3444  case kOobInline:
3445  if (setsockopt(sock, SOL_SOCKET, SO_OOBINLINE, (char*)&val, sizeof(val)) == -1) {
3446  SysError("SetSockOpt", "setsockopt(SO_OOBINLINE)");
3447  return -1;
3448  }
3449  break;
3450  case kKeepAlive:
3451  if (setsockopt(sock, SOL_SOCKET, SO_KEEPALIVE, (char*)&val, sizeof(val)) == -1) {
3452  SysError("SetSockOpt", "setsockopt(SO_KEEPALIVE)");
3453  return -1;
3454  }
3455  break;
3456  case kReuseAddr:
3457  if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (char*)&val, sizeof(val)) == -1) {
3458  SysError("SetSockOpt", "setsockopt(SO_REUSEADDR)");
3459  return -1;
3460  }
3461  break;
3462  case kNoDelay:
3463  if (setsockopt(sock, IPPROTO_TCP, TCP_NODELAY, (char*)&val, sizeof(val)) == -1) {
3464  SysError("SetSockOpt", "setsockopt(TCP_NODELAY)");
3465  return -1;
3466  }
3467  break;
3468  case kNoBlock:
3469  if (ioctl(sock, FIONBIO, (char*)&val) == -1) {
3470  SysError("SetSockOpt", "ioctl(FIONBIO)");
3471  return -1;
3472  }
3473  break;
3474  case kProcessGroup:
3475 #ifndef R__WINGCC
3476  if (ioctl(sock, SIOCSPGRP, (char*)&val) == -1) {
3477  SysError("SetSockOpt", "ioctl(SIOCSPGRP)");
3478  return -1;
3479  }
3480 #else
3481  Error("SetSockOpt", "ioctl(SIOCGPGRP) not supported on cygwin/gcc");
3482  return -1;
3483 #endif
3484  break;
3485  case kAtMark: // read-only option (see GetSockOpt)
3486  case kBytesToRead: // read-only option
3487  default:
3488  Error("SetSockOpt", "illegal option (%d)", opt);
3489  return -1;
3490  }
3491  return 0;
3492 }
3493 
3494 ////////////////////////////////////////////////////////////////////////////////
3495 /// Get socket option.
3496 
3497 int TUnixSystem::GetSockOpt(int sock, int opt, int *val)
3498 {
3499  if (sock < 0) return -1;
3500 
3501 #if defined(USE_SOCKLEN_T) || defined(_AIX43)
3502  socklen_t optlen = sizeof(*val);
3503 #elif defined(USE_SIZE_T)
3504  size_t optlen = sizeof(*val);
3505 #else
3506  int optlen = sizeof(*val);
3507 #endif
3508 
3509  switch (opt) {
3510  case kSendBuffer:
3511  if (getsockopt(sock, SOL_SOCKET, SO_SNDBUF, (char*)val, &optlen) == -1) {
3512  SysError("GetSockOpt", "getsockopt(SO_SNDBUF)");
3513  return -1;
3514  }
3515  break;
3516  case kRecvBuffer:
3517  if (getsockopt(sock, SOL_SOCKET, SO_RCVBUF, (char*)val, &optlen) == -1) {
3518  SysError("GetSockOpt", "getsockopt(SO_RCVBUF)");
3519  return -1;
3520  }
3521  break;
3522  case kOobInline:
3523  if (getsockopt(sock, SOL_SOCKET, SO_OOBINLINE, (char*)val, &optlen) == -1) {
3524  SysError("GetSockOpt", "getsockopt(SO_OOBINLINE)");
3525  return -1;
3526  }
3527  break;
3528  case kKeepAlive:
3529  if (getsockopt(sock, SOL_SOCKET, SO_KEEPALIVE, (char*)val, &optlen) == -1) {
3530  SysError("GetSockOpt", "getsockopt(SO_KEEPALIVE)");
3531  return -1;
3532  }
3533  break;
3534  case kReuseAddr:
3535  if (getsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (char*)val, &optlen) == -1) {
3536  SysError("GetSockOpt", "getsockopt(SO_REUSEADDR)");
3537  return -1;
3538  }
3539  break;
3540  case kNoDelay:
3541  if (getsockopt(sock, IPPROTO_TCP, TCP_NODELAY, (char*)val, &optlen) == -1) {
3542  SysError("GetSockOpt", "getsockopt(TCP_NODELAY)");
3543  return -1;
3544  }
3545  break;
3546  case kNoBlock:
3547  int flg;
3548  if ((flg = fcntl(sock, F_GETFL, 0)) == -1) {
3549  SysError("GetSockOpt", "fcntl(F_GETFL)");
3550  return -1;
3551  }
3552  *val = flg & O_NDELAY;
3553  break;
3554  case kProcessGroup:
3555 #if !defined(R__LYNXOS) && !defined(R__WINGCC)
3556  if (ioctl(sock, SIOCGPGRP, (char*)val) == -1) {
3557  SysError("GetSockOpt", "ioctl(SIOCGPGRP)");
3558  return -1;
3559  }
3560 #else
3561  Error("GetSockOpt", "ioctl(SIOCGPGRP) not supported on LynxOS and cygwin/gcc");
3562  return -1;
3563 #endif
3564  break;
3565  case kAtMark:
3566 #if !defined(R__LYNXOS)
3567  if (ioctl(sock, SIOCATMARK, (char*)val) == -1) {
3568  SysError("GetSockOpt", "ioctl(SIOCATMARK)");
3569  return -1;
3570  }
3571 #else
3572  Error("GetSockOpt", "ioctl(SIOCATMARK) not supported on LynxOS");
3573  return -1;
3574 #endif
3575  break;
3576  case kBytesToRead:
3577 #if !defined(R__LYNXOS)
3578  if (ioctl(sock, FIONREAD, (char*)val) == -1) {
3579  SysError("GetSockOpt", "ioctl(FIONREAD)");
3580  return -1;
3581  }
3582 #else
3583  Error("GetSockOpt", "ioctl(FIONREAD) not supported on LynxOS");
3584  return -1;
3585 #endif
3586  break;
3587  default:
3588  Error("GetSockOpt", "illegal option (%d)", opt);
3589  *val = 0;
3590  return -1;
3591  }
3592  return 0;
3593 }
3594 
3595 //////////////////////////////////////////////////////////////////////////
3596 // //
3597 // Static Protected Unix Interface functions. //
3598 // //
3599 //////////////////////////////////////////////////////////////////////////
3600 
3601 //---- signals -----------------------------------------------------------------
3602 
3603 static struct Signalmap_t {
3604  int fCode;
3605  SigHandler_t fHandler;
3606  struct sigaction *fOldHandler;
3607  const char *fSigName;
3608 } gSignalMap[kMAXSIGNALS] = { // the order of the signals should be identical
3609  { SIGBUS, 0, 0, "bus error" }, // to the one in TSysEvtHandler.h
3610  { SIGSEGV, 0, 0, "segmentation violation" },
3611  { SIGSYS, 0, 0, "bad argument to system call" },
3612  { SIGPIPE, 0, 0, "write on a pipe with no one to read it" },
3613  { SIGILL, 0, 0, "illegal instruction" },
3614  { SIGQUIT, 0, 0, "quit" },
3615  { SIGINT, 0, 0, "interrupt" },
3616  { SIGWINCH, 0, 0, "window size change" },
3617  { SIGALRM, 0, 0, "alarm clock" },
3618  { SIGCHLD, 0, 0, "death of a child" },
3619  { SIGURG, 0, 0, "urgent data arrived on an I/O channel" },
3620  { SIGFPE, 0, 0, "floating point exception" },
3621  { SIGTERM, 0, 0, "termination signal" },
3622  { SIGUSR1, 0, 0, "user-defined signal 1" },
3623  { SIGUSR2, 0, 0, "user-defined signal 2" }
3624 };
3625 
3626 
3627 ////////////////////////////////////////////////////////////////////////////////
3628 /// Call the signal handler associated with the signal.
3629 
3630 static void sighandler(int sig)
3631 {
3632  for (int i= 0; i < kMAXSIGNALS; i++) {
3633  if (gSignalMap[i].fCode == sig) {
3634  (*gSignalMap[i].fHandler)((ESignals)i);
3635  return;
3636  }
3637  }
3638 }
3639 
3640 ////////////////////////////////////////////////////////////////////////////////
3641 /// Handle and dispatch signals.
3642 
3644 {
3645  switch (sig) {
3646  case kSigAlarm:
3648  break;
3649  case kSigChild:
3650  CheckChilds();
3651  break;
3652  case kSigBus:
3655  case kSigFloatingException:
3656  Break("TUnixSystem::DispatchSignals", "%s", UnixSigname(sig));
3657  StackTrace();
3658  if (gApplication)
3659  //sig is ESignal, should it be mapped to the correct signal number?
3661  else
3662  //map to the real signal code + set the
3663  //high order bit to indicate a signal (?)
3664  Exit(gSignalMap[sig].fCode + 0x80);
3665  break;
3666  case kSigSystem:
3667  case kSigPipe:
3668  Break("TUnixSystem::DispatchSignals", "%s", UnixSigname(sig));
3669  break;
3670  case kSigWindowChanged:
3671  Gl_windowchanged();
3672  break;
3673  default:
3674  fSignals->Set(sig);
3675  fSigcnt++;
3676  break;
3677  }
3678 
3679  // check a-synchronous signals
3680  if (fSigcnt > 0 && fSignalHandler->GetSize() > 0)
3682 }
3683 
3684 ////////////////////////////////////////////////////////////////////////////////
3685 /// Set a signal handler for a signal.
3686 
3688 {
3689  if (gEnv && !gEnv->GetValue("Root.ErrorHandlers", 1))
3690  return;
3691 
3692  if (gSignalMap[sig].fHandler != handler) {
3693  struct sigaction sigact;
3694 
3695  gSignalMap[sig].fHandler = handler;
3696  gSignalMap[sig].fOldHandler = new struct sigaction();
3697 
3698 #if defined(R__SUN)
3699  sigact.sa_handler = (void (*)())sighandler;
3700 #elif defined(R__SOLARIS)
3701  sigact.sa_handler = sighandler;
3702 #elif defined(R__LYNXOS)
3703 # if (__GNUG__>=3)
3704  sigact.sa_handler = sighandler;
3705 # else
3706  sigact.sa_handler = (void (*)(...))sighandler;
3707 # endif
3708 #else
3709  sigact.sa_handler = sighandler;
3710 #endif
3711  sigemptyset(&sigact.sa_mask);
3712  sigact.sa_flags = 0;
3713 #if defined(SA_RESTART)
3714  sigact.sa_flags |= SA_RESTART;
3715 #endif
3716  if (sigaction(gSignalMap[sig].fCode, &sigact,
3717  gSignalMap[sig].fOldHandler) < 0)
3718  ::SysError("TUnixSystem::UnixSignal", "sigaction");
3719  }
3720 }
3721 
3722 ////////////////////////////////////////////////////////////////////////////////
3723 /// If ignore is true ignore the specified signal, else restore previous
3724 /// behaviour.
3725 
3727 {
3728  TTHREAD_TLS(Bool_t) ignoreSig[kMAXSIGNALS] = { kFALSE };
3729  TTHREAD_TLS_ARRAY(struct sigaction,kMAXSIGNALS,oldsigact);
3730 
3731  if (ignore != ignoreSig[sig]) {
3732  ignoreSig[sig] = ignore;
3733  if (ignore) {
3734  struct sigaction sigact;
3735 #if defined(R__SUN)
3736  sigact.sa_handler = (void (*)())SIG_IGN;
3737 #elif defined(R__SOLARIS)
3738  sigact.sa_handler = (void (*)(int))SIG_IGN;
3739 #else
3740  sigact.sa_handler = SIG_IGN;
3741 #endif
3742  sigemptyset(&sigact.sa_mask);
3743  sigact.sa_flags = 0;
3744  if (sigaction(gSignalMap[sig].fCode, &sigact, &oldsigact[sig]) < 0)
3745  ::SysError("TUnixSystem::UnixIgnoreSignal", "sigaction");
3746  } else {
3747  if (sigaction(gSignalMap[sig].fCode, &oldsigact[sig], 0) < 0)
3748  ::SysError("TUnixSystem::UnixIgnoreSignal", "sigaction");
3749  }
3750  }
3751 }
3752 
3753 ////////////////////////////////////////////////////////////////////////////////
3754 /// When the argument is true the SIGALRM signal handler is set so that
3755 /// interrupted syscalls will not be restarted by the kernel. This is
3756 /// typically used in case one wants to put a timeout on an I/O operation.
3757 /// By default interrupted syscalls will always be restarted (for all
3758 /// signals). This can be controlled for each a-synchronous TTimer via
3759 /// the method TTimer::SetInterruptSyscalls().
3760 
3762 {
3763  if (gSignalMap[kSigAlarm].fHandler) {
3764  struct sigaction sigact;
3765 #if defined(R__SUN)
3766  sigact.sa_handler = (void (*)())sighandler;
3767 #elif defined(R__SOLARIS)
3768  sigact.sa_handler = sighandler;
3769 #elif defined(R__LYNXOS)
3770 # if (__GNUG__>=3)
3771  sigact.sa_handler = sighandler;
3772 # else
3773  sigact.sa_handler = (void (*)(...))sighandler;
3774 # endif
3775 #else
3776  sigact.sa_handler = sighandler;
3777 #endif
3778  sigemptyset(&sigact.sa_mask);
3779  sigact.sa_flags = 0;
3780  if (set) {
3781 #if defined(SA_INTERRUPT) // SunOS
3782  sigact.sa_flags |= SA_INTERRUPT;
3783 #endif
3784  } else {
3785 #if defined(SA_RESTART)
3786  sigact.sa_flags |= SA_RESTART;
3787 #endif
3788  }
3789  if (sigaction(gSignalMap[kSigAlarm].fCode, &sigact, 0) < 0)
3790  ::SysError("TUnixSystem::UnixSigAlarmInterruptsSyscalls", "sigaction");
3791  }
3792 }
3793 
3794 ////////////////////////////////////////////////////////////////////////////////
3795 /// Return the signal name associated with a signal.
3796 
3798 {
3799  return gSignalMap[sig].fSigName;
3800 }
3801 
3802 ////////////////////////////////////////////////////////////////////////////////
3803 /// Restore old signal handler for specified signal.
3804 
3806 {
3807  if (gSignalMap[sig].fOldHandler) {
3808  // restore old signal handler
3809  if (sigaction(gSignalMap[sig].fCode, gSignalMap[sig].fOldHandler, 0) < 0)
3810  ::SysError("TUnixSystem::UnixSignal", "sigaction");
3811  delete gSignalMap[sig].fOldHandler;
3812  gSignalMap[sig].fOldHandler = 0;
3813  gSignalMap[sig].fHandler = 0;
3814  }
3815 }
3816 
3817 ////////////////////////////////////////////////////////////////////////////////
3818 /// Restore old signal handlers.
3819 
3821 {
3822  for (int sig = 0; sig < kMAXSIGNALS; sig++)
3823  UnixResetSignal((ESignals)sig);
3824 }
3825 
3826 //---- time --------------------------------------------------------------------
3827 
3828 ////////////////////////////////////////////////////////////////////////////////
3829 /// Get current time in milliseconds since 0:00 Jan 1 1995.
3830 
3832 {
3833  static std::atomic<time_t> jan95{0};
3834  if (!jan95) {
3835  struct tm tp;
3836  tp.tm_year = 95;
3837  tp.tm_mon = 0;
3838  tp.tm_mday = 1;
3839  tp.tm_hour = 0;
3840  tp.tm_min = 0;
3841  tp.tm_sec = 0;
3842  tp.tm_isdst = -1;
3843 
3844  jan95 = mktime(&tp);
3845  if ((int)jan95 == -1) {
3846  ::SysError("TUnixSystem::UnixNow", "error converting 950001 0:00 to time_t");
3847  return 0;
3848  }
3849  }
3850 
3851  struct timeval t;
3852  gettimeofday(&t, 0);
3853  return Long64_t(t.tv_sec-(Long_t)jan95)*1000 + t.tv_usec/1000;
3854 }
3855 
3856 ////////////////////////////////////////////////////////////////////////////////
3857 /// Set interval timer to time-out in ms milliseconds.
3858 
3860 {
3861  struct itimerval itv;
3862  itv.it_value.tv_sec = 0;
3863  itv.it_value.tv_usec = 0;
3864  itv.it_interval.tv_sec = 0;
3865  itv.it_interval.tv_usec = 0;
3866  if (ms > 0) {
3867  itv.it_value.tv_sec = time_t(ms / 1000);
3868  itv.it_value.tv_usec = time_t((ms % 1000) * 1000);
3869  }
3870  int st = setitimer(ITIMER_REAL, &itv, 0);
3871  if (st == -1)
3872  ::SysError("TUnixSystem::UnixSetitimer", "setitimer");
3873  return st;
3874 }
3875 
3876 //---- file descriptors --------------------------------------------------------
3877 
3878 ////////////////////////////////////////////////////////////////////////////////
3879 /// Wait for events on the file descriptors specified in the readready and
3880 /// writeready masks or for timeout (in milliseconds) to occur. Returns
3881 /// the number of ready descriptors, or 0 in case of timeout, or < 0 in
3882 /// case of an error, with -2 being EINTR and -3 EBADF. In case of EINTR
3883 /// the errno has been reset and the method can be called again.
3884 
3885 int TUnixSystem::UnixSelect(Int_t nfds, TFdSet *readready, TFdSet *writeready,
3886  Long_t timeout)
3887 {
3888  int retcode;
3889 
3890  fd_set *rd = (readready) ? (fd_set*)readready->GetBits() : 0;
3891  fd_set *wr = (writeready) ? (fd_set*)writeready->GetBits() : 0;
3892 
3893  if (timeout >= 0) {
3894  struct timeval tv;
3895  tv.tv_sec = Int_t(timeout / 1000);
3896  tv.tv_usec = (timeout % 1000) * 1000;
3897  retcode = select(nfds, rd, wr, 0, &tv);
3898  } else {
3899  retcode = select(nfds, rd, wr, 0, 0);
3900  }
3901  if (retcode == -1) {
3902  if (GetErrno() == EINTR) {
3903  ResetErrno(); // errno is not self reseting
3904  return -2;
3905  }
3906  if (GetErrno() == EBADF)
3907  return -3;
3908  return -1;
3909  }
3910 
3911  return retcode;
3912 }
3913 
3914 //---- directories -------------------------------------------------------------
3915 
3916 ////////////////////////////////////////////////////////////////////////////////
3917 /// Returns the user's home directory.
3918 
3919 const char *TUnixSystem::UnixHomedirectory(const char *name)
3920 {
3921  static char path[kMAXPATHLEN], mydir[kMAXPATHLEN] = { '\0' };
3922  return UnixHomedirectory(name, path, mydir);
3923 }
3924 
3925 ////////////////////////////////////////////////////////////////////////////
3926 /// Returns the user's home directory.
3927 
3928 const char *TUnixSystem::UnixHomedirectory(const char *name, char *path, char *mydir)
3929 {
3930  struct passwd *pw;
3931  if (name) {
3932  pw = getpwnam(name);
3933  if (pw) {
3934  strncpy(path, pw->pw_dir, kMAXPATHLEN-1);
3935  path[kMAXPATHLEN-1] = '\0';
3936  return path;
3937  }
3938  } else {
3939  if (mydir[0])
3940  return mydir;
3941  pw = getpwuid(getuid());
3942  if (pw && pw->pw_dir) {
3943  strncpy(mydir, pw->pw_dir, kMAXPATHLEN-1);
3944  mydir[kMAXPATHLEN-1] = '\0';
3945  return mydir;
3946  } else if (gSystem->Getenv("HOME")) {
3947  strncpy(mydir, gSystem->Getenv("HOME"), kMAXPATHLEN-1);
3948  mydir[kMAXPATHLEN-1] = '\0';
3949  return mydir;
3950  }
3951  }
3952  return 0;
3953 }
3954 
3955 ////////////////////////////////////////////////////////////////////////////////
3956 /// Make a Unix file system directory. Returns 0 in case of success and
3957 /// -1 if the directory could not be created (either already exists or
3958 /// illegal path name).
3959 
3960 int TUnixSystem::UnixMakedir(const char *dir)
3961 {
3962  return ::mkdir(StripOffProto(dir, "file:"), 0755);
3963 }
3964 
3965 ////////////////////////////////////////////////////////////////////////////////
3966 /// Open a directory.
3967 
3968 void *TUnixSystem::UnixOpendir(const char *dir)
3969 {
3970  struct stat finfo;
3971 
3972  const char *edir = StripOffProto(dir, "file:");
3973 
3974  if (stat(edir, &finfo) < 0)
3975  return 0;
3976 
3977  if (!S_ISDIR(finfo.st_mode))
3978  return 0;
3979 
3980  return (void*) opendir(edir);
3981 }
3982 
3983 #if defined(_POSIX_SOURCE)
3984 // Posix does not require that the d_ino field be present, and some
3985 // systems do not provide it.
3986 # define REAL_DIR_ENTRY(dp) 1
3987 #else
3988 # define REAL_DIR_ENTRY(dp) (dp->d_ino != 0)
3989 #endif
3990 
3991 ////////////////////////////////////////////////////////////////////////////////
3992 /// Returns the next directory entry.
3993 
3994 const char *TUnixSystem::UnixGetdirentry(void *dirp1)
3995 {
3996  DIR *dirp = (DIR*)dirp1;
3997 #ifdef HAS_DIRENT
3998  struct dirent *dp;
3999 #else
4000  struct direct *dp;
4001 #endif
4002 
4003  if (dirp) {
4004  for (;;) {
4005  dp = readdir(dirp);
4006  if (dp == 0)
4007  return 0;
4008  if (REAL_DIR_ENTRY(dp))
4009  return dp->d_name;
4010  }
4011  }
4012  return 0;
4013 }
4014 
4015 //---- files -------------------------------------------------------------------
4016 
4017 ////////////////////////////////////////////////////////////////////////////////
4018 /// Get info about a file. Info is returned in the form of a FileStat_t
4019 /// structure (see TSystem.h).
4020 /// The function returns 0 in case of success and 1 if the file could
4021 /// not be stat'ed.
4022 
4023 int TUnixSystem::UnixFilestat(const char *fpath, FileStat_t &buf)
4024 {
4025  const char *path = StripOffProto(fpath, "file:");
4026  buf.fIsLink = kFALSE;
4027 
4028 #if defined(R__SEEK64)
4029  struct stat64 sbuf;
4030  if (path && lstat64(path, &sbuf) == 0) {
4031 #else
4032  struct stat sbuf;
4033  if (path && lstat(path, &sbuf) == 0) {
4034 #endif
4035  buf.fIsLink = S_ISLNK(sbuf.st_mode);
4036  if (buf.fIsLink) {
4037 #if defined(R__SEEK64)
4038  if (stat64(path, &sbuf) == -1) {
4039 #else
4040  if (stat(path, &sbuf) == -1) {
4041 #endif
4042  return 1;
4043  }
4044  }
4045  buf.fDev = sbuf.st_dev;
4046  buf.fIno = sbuf.st_ino;
4047  buf.fMode = sbuf.st_mode;
4048  buf.fUid = sbuf.st_uid;
4049  buf.fGid = sbuf.st_gid;
4050  buf.fSize = sbuf.st_size;
4051  buf.fMtime = sbuf.st_mtime;
4052 
4053  return 0;
4054  }
4055  return 1;
4056 }
4057 
4058 ////////////////////////////////////////////////////////////////////////////////
4059 /// Get info about a file system: id, bsize, bfree, blocks.
4060 /// Id is file system type (machine dependend, see statfs())
4061 /// Bsize is block size of file system
4062 /// Blocks is total number of blocks in file system
4063 /// Bfree is number of free blocks in file system
4064 /// The function returns 0 in case of success and 1 if the file system could
4065 /// not be stat'ed.
4066 
4067 int TUnixSystem::UnixFSstat(const char *path, Long_t *id, Long_t *bsize,
4068  Long_t *blocks, Long_t *bfree)
4069 {
4070  struct statfs statfsbuf;
4071 #if (defined(R__SOLARIS) && !defined(R__LINUX))
4072  if (statfs(path, &statfsbuf, sizeof(struct statfs), 0) == 0) {
4073  *id = statfsbuf.f_fstyp;
4074  *bsize = statfsbuf.f_bsize;
4075  *blocks = statfsbuf.f_blocks;
4076  *bfree = statfsbuf.f_bfree;
4077 #else
4078  if (statfs((char*)path, &statfsbuf) == 0) {
4079 #ifdef R__OBSD
4080  // Convert BSD filesystem names to Linux filesystem type numbers
4081  // where possible. Linux statfs uses a value of -1 to indicate
4082  // an unsupported field.
4083 
4084  if (!strcmp(statfsbuf.f_fstypename, MOUNT_FFS) ||
4085  !strcmp(statfsbuf.f_fstypename, MOUNT_MFS))
4086  *id = 0x11954;
4087  else if (!strcmp(statfsbuf.f_fstypename, MOUNT_NFS))
4088  *id = 0x6969;
4089  else if (!strcmp(statfsbuf.f_fstypename, MOUNT_MSDOS))
4090  *id = 0x4d44;
4091  else if (!strcmp(statfsbuf.f_fstypename, MOUNT_PROCFS))
4092  *id = 0x9fa0;
4093  else if (!strcmp(statfsbuf.f_fstypename, MOUNT_EXT2FS))
4094  *id = 0xef53;
4095  else if (!strcmp(statfsbuf.f_fstypename, MOUNT_CD9660))
4096  *id = 0x9660;
4097  else if (!strcmp(statfsbuf.f_fstypename, MOUNT_NCPFS))
4098  *id = 0x6969;
4099  else
4100  *id = -1;
4101 #else
4102  *id = statfsbuf.f_type;
4103 #endif
4104  *bsize = statfsbuf.f_bsize;
4105  *blocks = statfsbuf.f_blocks;
4106  *bfree = statfsbuf.f_bavail;
4107 #endif
4108  return 0;
4109  }
4110  return 1;
4111 }
4112 
4113 ////////////////////////////////////////////////////////////////////////////////
4114 /// Wait till child is finished.
4115 
4117 {
4118  int status;
4119  return (int) waitpid(0, &status, WNOHANG);
4120 }
4121 
4122 //---- RPC -------------------------------------------------------------------
4123 
4124 ////////////////////////////////////////////////////////////////////////////////
4125 /// Open a TCP/IP connection to server and connect to a service (i.e. port).
4126 /// Use tcpwindowsize to specify the size of the receive buffer, it has
4127 /// to be specified here to make sure the window scale option is set (for
4128 /// tcpwindowsize > 65KB and for platforms supporting window scaling).
4129 /// Is called via the TSocket constructor. Returns -1 in case of error.
4130 
4131 int TUnixSystem::UnixTcpConnect(const char *hostname, int port,
4132  int tcpwindowsize)
4133 {
4134  short sport;
4135  struct servent *sp;
4136 
4137  if ((sp = getservbyport(htons(port), kProtocolName)))
4138  sport = sp->s_port;
4139  else
4140  sport = htons(port);
4141 
4142  TInetAddress addr = gSystem->GetHostByName(hostname);
4143  if (!addr.IsValid()) return -1;
4144  UInt_t adr = htonl(addr.GetAddress());
4145 
4146  struct sockaddr_in server;
4147  memset(&server, 0, sizeof(server));
4148  memcpy(&server.sin_addr, &adr, sizeof(adr));
4149  server.sin_family = addr.GetFamily();
4150  server.sin_port = sport;
4151 
4152  // Create socket
4153  int sock;
4154  if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
4155  ::SysError("TUnixSystem::UnixTcpConnect", "socket (%s:%d)",
4156  hostname, port);
4157  return -1;
4158  }
4159 
4160  if (tcpwindowsize > 0) {
4161  gSystem->SetSockOpt(sock, kRecvBuffer, tcpwindowsize);
4162  gSystem->SetSockOpt(sock, kSendBuffer, tcpwindowsize);
4163  }
4164 
4165  while (connect(sock, (struct sockaddr*) &server, sizeof(server)) == -1) {
4166  if (GetErrno() == EINTR)
4167  ResetErrno();
4168  else {
4169  ::SysError("TUnixSystem::UnixTcpConnect", "connect (%s:%d)",
4170  hostname, port);
4171  close(sock);
4172  return -1;
4173  }
4174  }
4175  return sock;
4176 }
4177 
4178 
4179 ////////////////////////////////////////////////////////////////////////////////
4180 /// Creates a UDP socket connection
4181 /// Is called via the TSocket constructor. Returns -1 in case of error.
4182 
4183 int TUnixSystem::UnixUdpConnect(const char *hostname, int port)
4184 {
4185  short sport;
4186  struct servent *sp;
4187 
4188  if ((sp = getservbyport(htons(port), kProtocolName)))
4189  sport = sp->s_port;
4190  else
4191  sport = htons(port);
4192 
4193  TInetAddress addr = gSystem->GetHostByName(hostname);
4194  if (!addr.IsValid()) return -1;
4195  UInt_t adr = htonl(addr.GetAddress());
4196 
4197  struct sockaddr_in server;
4198  memset(&server, 0, sizeof(server));
4199  memcpy(&server.sin_addr, &adr, sizeof(adr));
4200  server.sin_family = addr.GetFamily();
4201  server.sin_port = sport;
4202 
4203  // Create socket
4204  int sock;
4205  if ((sock = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
4206  ::SysError("TUnixSystem::UnixUdpConnect", "socket (%s:%d)",
4207  hostname, port);
4208  return -1;
4209  }
4210 
4211  while (connect(sock, (struct sockaddr*) &server, sizeof(server)) == -1) {
4212  if (GetErrno() == EINTR)
4213  ResetErrno();
4214  else {
4215  ::SysError("TUnixSystem::UnixUdpConnect", "connect (%s:%d)",
4216  hostname, port);
4217  close(sock);
4218  return -1;
4219  }
4220  }
4221  return sock;
4222 }
4223 
4224 ////////////////////////////////////////////////////////////////////////////////
4225 /// Connect to a Unix domain socket.
4226 
4228 {
4229  return UnixUnixConnect(TString::Format("%s/%d", kServerPath, port));
4230 }
4231 
4232 ////////////////////////////////////////////////////////////////////////////////
4233 /// Connect to a Unix domain socket. Returns -1 in case of error.
4234 
4235 int TUnixSystem::UnixUnixConnect(const char *sockpath)
4236 {
4237  if (!sockpath || strlen(sockpath) <= 0) {
4238  ::SysError("TUnixSystem::UnixUnixConnect", "socket path undefined");
4239  return -1;
4240  }
4241 
4242  int sock;
4243  struct sockaddr_un unserver;
4244  unserver.sun_family = AF_UNIX;
4245 
4246  if (strlen(sockpath) > sizeof(unserver.sun_path)-1) {
4247  ::Error("TUnixSystem::UnixUnixConnect", "socket path %s, longer than max allowed length (%u)",
4248  sockpath, (UInt_t)sizeof(unserver.sun_path)-1);
4249  return -1;
4250  }
4251  strcpy(unserver.sun_path, sockpath);
4252 
4253  // Open socket
4254  if ((sock = socket(AF_UNIX, SOCK_STREAM, 0)) < 0) {
4255  ::SysError("TUnixSystem::UnixUnixConnect", "socket");
4256  return -1;
4257  }
4258 
4259  while (connect(sock, (struct sockaddr*) &unserver, strlen(unserver.sun_path)+2) == -1) {
4260  if (GetErrno() == EINTR)
4261  ResetErrno();
4262  else {
4263  ::SysError("TUnixSystem::UnixUnixConnect", "connect");
4264  close(sock);
4265  return -1;
4266  }
4267  }
4268  return sock;
4269 }
4270 
4271 ////////////////////////////////////////////////////////////////////////////////
4272 /// Open a socket, bind to it and start listening for TCP/IP connections
4273 /// on the port. If reuse is true reuse the address, backlog specifies
4274 /// how many sockets can be waiting to be accepted. If port is 0 a port
4275 /// scan will be done to find a free port. This option is mutual exlusive
4276 /// with the reuse option.
4277 /// Use tcpwindowsize to specify the size of the receive buffer, it has
4278 /// to be specified here to make sure the window scale option is set (for
4279 /// tcpwindowsize > 65KB and for platforms supporting window scaling).
4280 /// Returns socket fd or -1 if socket() failed, -2 if bind() failed
4281 /// or -3 if listen() failed.
4282 
4283 int TUnixSystem::UnixTcpService(int port, Bool_t reuse, int backlog,
4284  int tcpwindowsize)
4285 {
4286  const short kSOCKET_MINPORT = 5000, kSOCKET_MAXPORT = 15000;
4287  short sport, tryport = kSOCKET_MINPORT;
4288  struct servent *sp;
4289 
4290  if (port == 0 && reuse) {
4291  ::Error("TUnixSystem::UnixTcpService", "cannot do a port scan while reuse is true");
4292  return -1;
4293  }
4294 
4295  if ((sp = getservbyport(htons(port), kProtocolName)))
4296  sport = sp->s_port;
4297  else
4298  sport = htons(port);
4299 
4300  // Create tcp socket
4301  int sock;
4302  if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
4303  ::SysError("TUnixSystem::UnixTcpService", "socket");
4304  return -1;
4305  }
4306 
4307  if (reuse)
4308  gSystem->SetSockOpt(sock, kReuseAddr, 1);
4309 
4310  if (tcpwindowsize > 0) {
4311  gSystem->SetSockOpt(sock, kRecvBuffer, tcpwindowsize);
4312  gSystem->SetSockOpt(sock, kSendBuffer, tcpwindowsize);
4313  }
4314 
4315  struct sockaddr_in inserver;
4316  memset(&inserver, 0, sizeof(inserver));
4317  inserver.sin_family = AF_INET;
4318  inserver.sin_addr.s_addr = htonl(INADDR_ANY);
4319  inserver.sin_port = sport;
4320 
4321  // Bind socket
4322  if (port > 0) {
4323  if (::bind(sock, (struct sockaddr*) &inserver, sizeof(inserver))) {
4324  ::SysError("TUnixSystem::UnixTcpService", "bind");
4325  close(sock);
4326  return -2;
4327  }
4328  } else {
4329  int bret;
4330  do {
4331  inserver.sin_port = htons(tryport);
4332  bret = ::bind(sock, (struct sockaddr*) &inserver, sizeof(inserver));
4333  tryport++;
4334  } while (bret < 0 && GetErrno() == EADDRINUSE && tryport < kSOCKET_MAXPORT);
4335  if (bret < 0) {
4336  ::SysError("TUnixSystem::UnixTcpService", "bind (port scan)");
4337  close(sock);
4338  return -2;
4339  }
4340  }
4341 
4342  // Start accepting connections
4343  if (::listen(sock, backlog)) {
4344  ::SysError("TUnixSystem::UnixTcpService", "listen");
4345  close(sock);
4346  return -3;
4347  }
4348 
4349  return sock;
4350 }
4351 
4352 ////////////////////////////////////////////////////////////////////////////////
4353 /// Open a socket, bind to it and start listening for UDP connections
4354 /// on the port. If reuse is true reuse the address, backlog specifies
4355 /// how many sockets can be waiting to be accepted. If port is 0 a port
4356 /// scan will be done to find a free port. This option is mutual exlusive
4357 /// with the reuse option.
4358 
4359 int TUnixSystem::UnixUdpService(int port, int backlog)
4360 {
4361  const short kSOCKET_MINPORT = 5000, kSOCKET_MAXPORT = 15000;
4362  short sport, tryport = kSOCKET_MINPORT;
4363  struct servent *sp;
4364 
4365  if ((sp = getservbyport(htons(port), kProtocolName)))
4366  sport = sp->s_port;
4367  else
4368  sport = htons(port);
4369 
4370  // Create udp socket
4371  int sock;
4372  if ((sock = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
4373  ::SysError("TUnixSystem::UnixUdpService", "socket");
4374  return -1;
4375  }
4376 
4377  struct sockaddr_in inserver;
4378  memset(&inserver, 0, sizeof(inserver));
4379  inserver.sin_family = AF_INET;
4380  inserver.sin_addr.s_addr = htonl(INADDR_ANY);
4381  inserver.sin_port = sport;
4382 
4383  // Bind socket
4384  if (port > 0) {
4385  if (::bind(sock, (struct sockaddr*) &inserver, sizeof(inserver))) {
4386  ::SysError("TUnixSystem::UnixUdpService", "bind");
4387  close(sock);
4388  return -2;
4389  }
4390  } else {
4391  int bret;
4392  do {
4393  inserver.sin_port = htons(tryport);
4394  bret = ::bind(sock, (struct sockaddr*) &inserver, sizeof(inserver));
4395  tryport++;
4396  } while (bret < 0 && GetErrno() == EADDRINUSE && tryport < kSOCKET_MAXPORT);
4397  if (bret < 0) {
4398  ::SysError("TUnixSystem::UnixUdpService", "bind (port scan)");
4399  close(sock);
4400  return -2;
4401  }
4402  }
4403 
4404  // Start accepting connections
4405  if (::listen(sock, backlog)) {
4406  ::SysError("TUnixSystem::UnixUdpService", "listen");
4407  close(sock);
4408  return -3;
4409  }
4410 
4411  return sock;
4412 }
4413 
4414 ////////////////////////////////////////////////////////////////////////////////
4415 /// Open a socket, bind to it and start listening for Unix domain connections
4416 /// to it. Returns socket fd or -1.
4417 
4418 int TUnixSystem::UnixUnixService(int port, int backlog)
4419 {
4420  int oldumask;
4421 
4422  // Assure that socket directory exists
4423  oldumask = umask(0);
4424  int res = ::mkdir(kServerPath, 0777);
4425  umask(oldumask);
4426 
4427  if (res == -1)
4428  return -1;
4429 
4430  // Socket path
4431  TString sockpath;
4432  sockpath.Form("%s/%d", kServerPath, port);
4433 
4434  // Remove old socket
4435  unlink(sockpath.Data());
4436 
4437  return UnixUnixService(sockpath, backlog);
4438 }
4439 
4440 ////////////////////////////////////////////////////////////////////////////////
4441 /// Open a socket on path 'sockpath', bind to it and start listening for Unix
4442 /// domain connections to it. Returns socket fd or -1.
4443 
4444 int TUnixSystem::UnixUnixService(const char *sockpath, int backlog)
4445 {
4446  if (!sockpath || strlen(sockpath) <= 0) {
4447  ::SysError("TUnixSystem::UnixUnixService", "socket path undefined");
4448  return -1;
4449  }
4450 
4451  struct sockaddr_un unserver;
4452  int sock;
4453 
4454  // Prepare structure
4455  memset(&unserver, 0, sizeof(unserver));
4456  unserver.sun_family = AF_UNIX;
4457 
4458  if (strlen(sockpath) > sizeof(unserver.sun_path)-1) {
4459  ::Error("TUnixSystem::UnixUnixService", "socket path %s, longer than max allowed length (%u)",
4460  sockpath, (UInt_t)sizeof(unserver.sun_path)-1);
4461  return -1;
4462  }
4463  strcpy(unserver.sun_path, sockpath);
4464 
4465  // Create socket
4466  if ((sock = socket(AF_UNIX, SOCK_STREAM, 0)) < 0) {
4467  ::SysError("TUnixSystem::UnixUnixService", "socket");
4468  return -1;
4469  }
4470 
4471  if (::bind(sock, (struct sockaddr*) &unserver, strlen(unserver.sun_path)+2)) {
4472  ::SysError("TUnixSystem::UnixUnixService", "bind");
4473  close(sock);
4474  return -1;
4475  }
4476 
4477  // Start accepting connections
4478  if (::listen(sock, backlog)) {
4479  ::SysError("TUnixSystem::UnixUnixService", "listen");
4480  close(sock);
4481  return -1;
4482  }
4483 
4484  return sock;
4485 }
4486 
4487 ////////////////////////////////////////////////////////////////////////////////
4488 /// Receive exactly length bytes into buffer. Returns number of bytes
4489 /// received. Returns -1 in case of error, -2 in case of MSG_OOB
4490 /// and errno == EWOULDBLOCK, -3 in case of MSG_OOB and errno == EINVAL
4491 /// and -4 in case of kNoBlock and errno == EWOULDBLOCK.
4492 /// Returns -5 if pipe broken or reset by peer (EPIPE || ECONNRESET).
4493 
4494 int TUnixSystem::UnixRecv(int sock, void *buffer, int length, int flag)
4495 {
4496  ResetErrno();
4497 
4498  if (sock < 0) return -1;
4499 
4500  int once = 0;
4501  if (flag == -1) {
4502  flag = 0;
4503  once = 1;
4504  }
4505  if (flag == MSG_PEEK)
4506  once = 1;
4507 
4508  int n, nrecv = 0;
4509  char *buf = (char *)buffer;
4510 
4511  for (n = 0; n < length; n += nrecv) {
4512  if ((nrecv = recv(sock, buf+n, length-n, flag)) <= 0) {
4513  if (nrecv == 0)
4514  break; // EOF
4515  if (flag == MSG_OOB) {
4516  if (GetErrno() == EWOULDBLOCK)
4517  return -2;
4518  else if (GetErrno() == EINVAL)
4519  return -3;
4520  }
4521  if (GetErrno() == EWOULDBLOCK)
4522  return -4;
4523  else {
4524  if (GetErrno() != EINTR)
4525  ::SysError("TUnixSystem::UnixRecv", "recv");
4526  if (GetErrno() == EPIPE || GetErrno() == ECONNRESET)
4527  return -5;
4528  else
4529  return -1;
4530  }
4531  }
4532  if (once)
4533  return nrecv;
4534  }
4535  return n;
4536 }
4537 
4538 ////////////////////////////////////////////////////////////////////////////////
4539 /// Send exactly length bytes from buffer. Returns -1 in case of error,
4540 /// otherwise number of sent bytes. Returns -4 in case of kNoBlock and
4541 /// errno == EWOULDBLOCK. Returns -5 if pipe broken or reset by peer
4542 /// (EPIPE || ECONNRESET).
4543 
4544 int TUnixSystem::UnixSend(int sock, const void *buffer, int length, int flag)
4545 {
4546  if (sock < 0) return -1;
4547 
4548  int once = 0;
4549  if (flag == -1) {
4550  flag = 0;
4551  once = 1;
4552  }
4553 
4554  int n, nsent = 0;
4555  const char *buf = (const char *)buffer;
4556 
4557  for (n = 0; n < length; n += nsent) {
4558  if ((nsent = send(sock, buf+n, length-n, flag)) <= 0) {
4559  if (nsent == 0)
4560  break;
4561  if (GetErrno() == EWOULDBLOCK)
4562  return -4;
4563  else {
4564  if (GetErrno() != EINTR)
4565  ::SysError("TUnixSystem::UnixSend", "send");
4566  if (GetErrno() == EPIPE || GetErrno() == ECONNRESET)
4567  return -5;
4568  else
4569  return -1;
4570  }
4571  }
4572  if (once)
4573  return nsent;
4574  }
4575  return n;
4576 }
4577 
4578 //---- Dynamic Loading ---------------------------------------------------------
4579 
4580 ////////////////////////////////////////////////////////////////////////////////
4581 /// Get shared library search path. Static utility function.
4582 
4583 static const char *DynamicPath(const char *newpath = 0, Bool_t reset = kFALSE)
4584 {
4585  static TString dynpath;
4586  static Bool_t initialized = kFALSE;
4587  if (!initialized) {
4588  // force one time initialization of gROOT before we start
4589  // (otherwise it might be done as a side effect of gEnv->GetValue and
4590  // TROOT's initialization will call this routine).
4591  gROOT;
4592  }
4593 
4594  if (newpath) {
4595  dynpath = newpath;
4596  } else if (reset || !initialized) {
4597  initialized = kTRUE;
4598  TString rdynpath = gEnv->GetValue("Root.DynamicPath", (char*)0);
4599  rdynpath.ReplaceAll(": ", ":"); // in case DynamicPath was extended
4600  if (rdynpath.IsNull()) {
4601  rdynpath = ".:"; rdynpath += TROOT::GetLibDir();
4602  }
4603  TString ldpath;
4604 #if defined (R__AIX)
4605  ldpath = gSystem->Getenv("LIBPATH");
4606 #elif defined(R__MACOSX)
4607  ldpath = gSystem->Getenv("DYLD_LIBRARY_PATH");
4608  if (!ldpath.IsNull())
4609  ldpath += ":";
4610  ldpath += gSystem->Getenv("LD_LIBRARY_PATH");
4611  if (!ldpath.IsNull())
4612  ldpath += ":";
4613  ldpath += gSystem->Getenv("DYLD_FALLBACK_LIBRARY_PATH");
4614 #else
4615  ldpath = gSystem->Getenv("LD_LIBRARY_PATH");
4616 #endif
4617  if (ldpath.IsNull())
4618  dynpath = rdynpath;
4619  else {
4620  dynpath = ldpath; dynpath += ":"; dynpath += rdynpath;
4621  }
4622  if (!dynpath.Contains(TROOT::GetLibDir())) {
4623  dynpath += ":"; dynpath += TROOT::GetLibDir();
4624  }
4625  if (gCling) {
4626  dynpath += ":"; dynpath += gCling->GetSTLIncludePath();
4627  } else
4628  initialized = kFALSE;
4629 
4630 #if defined(R__WINGCC) || defined(R__MACOSX)
4631  if (!dynpath.EndsWith(":")) dynpath += ":";
4632  dynpath += "/usr/local/lib:/usr/X11R6/lib:/usr/lib:/lib:";
4633  dynpath += "/lib/x86_64-linux-gnu:/usr/local/lib64:/usr/lib64:/lib64:";
4634 #else
4635  // trick to get the system search path
4636  std::string cmd("LD_DEBUG=libs LD_PRELOAD=DOESNOTEXIST ls 2>&1");
4637  FILE *pf = popen(cmd.c_str (), "r");
4638  std::string result = "";
4639  char buffer[128];
4640  while (!feof(pf)) {
4641  if (fgets(buffer, 128, pf) != NULL)
4642  result += buffer;
4643  }
4644  pclose(pf);
4645  std::size_t from = result.find("search path=", result.find("(LD_LIBRARY_PATH)"));
4646  std::size_t to = result.find("(system search path)");
4647  if (from != std::string::npos && to != std::string::npos) {
4648  from += 12;
4649  std::string sys_path = result.substr(from, to-from);
4650  sys_path.erase(std::remove_if(sys_path.begin(), sys_path.end(), isspace), sys_path.end());
4651  if (!dynpath.EndsWith(":")) dynpath += ":";
4652  dynpath += sys_path.c_str();
4653  }
4654  dynpath.ReplaceAll("::", ":");
4655 #endif
4656  if (gDebug > 0) std::cout << "dynpath = " << dynpath.Data() << std::endl;
4657  }
4658  return dynpath;
4659 }
4660 
4661 ////////////////////////////////////////////////////////////////////////////////
4662 /// Add a new directory to the dynamic path.
4663 
4664 void TUnixSystem::AddDynamicPath(const char *path)
4665 {
4666  if (path) {
4667  TString oldpath = DynamicPath(0, kFALSE);
4668  oldpath.Append(":");
4669  oldpath.Append(path);
4670  DynamicPath(oldpath);
4671  }
4672 }
4673 
4674 ////////////////////////////////////////////////////////////////////////////////
4675 /// Return the dynamic path (used to find shared libraries).
4676 
4678 {
4679  return DynamicPath(0, kFALSE);
4680 }
4681 
4682 ////////////////////////////////////////////////////////////////////////////////
4683 /// Set the dynamic path to a new value.
4684 /// If the value of 'path' is zero, the dynamic path is reset to its
4685 /// default value.
4686 
4687 void TUnixSystem::SetDynamicPath(const char *path)
4688 {
4689  if (!path)
4690  DynamicPath(0, kTRUE);
4691  else
4692  DynamicPath(path);
4693 }
4694 
4695 ////////////////////////////////////////////////////////////////////////////////
4696 /// Returns the path of a shared library (searches for library in the
4697 /// shared library search path). If no file name extension is provided
4698 /// it first tries .so, .sl, .dl and then .a (for AIX).
4699 
4701 {
4702  char buf[PATH_MAX + 1];
4703  char *res = realpath(sLib.Data(), buf);
4704  if (res) sLib = buf;
4705  TString searchFor = sLib;
4707  return sLib;
4708  }
4709  sLib = searchFor;
4710  const char* lib = sLib.Data();
4711  int len = sLib.Length();
4712  if (len > 3 && (!strcmp(lib+len-3, ".so") ||
4713  !strcmp(lib+len-3, ".dl") ||
4714  !strcmp(lib+len-4, ".dll") ||
4715  !strcmp(lib+len-4, ".DLL") ||
4716  !strcmp(lib+len-6, ".dylib") ||
4717  !strcmp(lib+len-3, ".sl") ||
4718  !strcmp(lib+len-2, ".a"))) {
4720  return sLib;
4721  }
4722  if (!quiet)
4723  Error("FindDynamicLibrary",
4724  "%s does not exist in %s", searchFor.Data(), GetDynamicPath());
4725  return 0;
4726  }
4727  static const char* exts[] = {
4728  ".so", ".dll", ".dylib", ".sl", ".dl", ".a", 0 };
4729  const char** ext = exts;
4730  while (*ext) {
4731  TString fname(sLib);
4732  fname += *ext;
4733  ++ext;
4734  if (gSystem->FindFile(GetDynamicPath(), fname, kReadPermission)) {
4735  sLib.Swap(fname);
4736  return sLib;
4737  }
4738  }
4739 
4740  if (!quiet)
4741  Error("FindDynamicLibrary",
4742  "%s[.so | .dll | .dylib | .sl | .dl | .a] does not exist in %s",
4743  searchFor.Data(), GetDynamicPath());
4744 
4745  return 0;
4746 }
4747 
4748 //---- System, CPU and Memory info ---------------------------------------------
4749 
4750 #if defined(R__MACOSX)
4751 #include <sys/resource.h>
4752 #include <mach/mach.h>
4753 #include <mach/mach_error.h>
4754 
4755 ////////////////////////////////////////////////////////////////////////////////
4756 /// Get system info for Mac OS X.
4757 
4758 static void GetDarwinSysInfo(SysInfo_t *sysinfo)
4759 {
4760  FILE *p = gSystem->OpenPipe("sysctl -n kern.ostype hw.model hw.ncpu hw.cpufrequency "
4761  "hw.busfrequency hw.l2cachesize hw.memsize", "r");
4762  TString s;
4763  s.Gets(p);
4764  sysinfo->fOS = s;
4765  s.Gets(p);
4766  sysinfo->fModel = s;
4767  s.Gets(p);
4768  sysinfo->fCpus = s.Atoi();
4769  s.Gets(p);
4770  Long64_t t = s.Atoll();
4771  sysinfo->fCpuSpeed = Int_t(t / 1000000);
4772  s.Gets(p);
4773  t = s.Atoll();
4774  sysinfo->fBusSpeed = Int_t(t / 1000000);
4775  s.Gets(p);
4776  sysinfo->fL2Cache = s.Atoi() / 1024;
4777  s.Gets(p);
4778  t = s.Atoll();
4779  sysinfo->fPhysRam = Int_t(t / 1024 / 1024);
4780  gSystem->ClosePipe(p);
4781  p = gSystem->OpenPipe("hostinfo", "r");
4782  while (s.Gets(p)) {
4783  if (s.BeginsWith("Processor type: ")) {
4784  TPRegexp("Processor type: ([^ ]+).*").Substitute(s, "$1");
4785  sysinfo->fCpuType = s;
4786  }
4787  }
4788  gSystem->ClosePipe(p);
4789 }
4790 
4791 ////////////////////////////////////////////////////////////////////////////////
4792 /// Get CPU load on Mac OS X.
4793 
4794 static void ReadDarwinCpu(long *ticks)
4795 {
4796  mach_msg_type_number_t count;
4797  kern_return_t kr;
4798  host_cpu_load_info_data_t cpu;
4799 
4800  ticks[0] = ticks[1] = ticks[2] = ticks[3] = 0;
4801 
4802  count = HOST_CPU_LOAD_INFO_COUNT;
4803  kr = host_statistics(mach_host_self(), HOST_CPU_LOAD_INFO, (host_info_t)&cpu, &count);
4804  if (kr != KERN_SUCCESS) {
4805  ::Error("TUnixSystem::ReadDarwinCpu", "host_statistics: %s", mach_error_string(kr));
4806  } else {
4807  ticks[0] = cpu.cpu_ticks[CPU_STATE_USER];
4808  ticks[1] = cpu.cpu_ticks[CPU_STATE_SYSTEM];
4809  ticks[2] = cpu.cpu_ticks[CPU_STATE_IDLE];
4810  ticks[3] = cpu.cpu_ticks[CPU_STATE_NICE];
4811  }
4812 }
4813 
4814 ////////////////////////////////////////////////////////////////////////////////
4815 /// Get CPU stat for Mac OS X. Use sampleTime to set the interval over which
4816 /// the CPU load will be measured, in ms (default 1000).
4817 
4818 static void GetDarwinCpuInfo(CpuInfo_t *cpuinfo, Int_t sampleTime)
4819 {
4820  Double_t avg[3];
4821  if (getloadavg(avg, sizeof(avg)) < 0) {
4822  ::Error("TUnixSystem::GetDarwinCpuInfo", "getloadavg failed");
4823  } else {
4824  cpuinfo->fLoad1m = (Float_t)avg[0];
4825  cpuinfo->fLoad5m = (Float_t)avg[1];
4826  cpuinfo->fLoad15m = (Float_t)avg[2];
4827  }
4828 
4829  Long_t cpu_ticks1[4], cpu_ticks2[4];
4830  ReadDarwinCpu(cpu_ticks1);
4831  gSystem->Sleep(sampleTime);
4832  ReadDarwinCpu(cpu_ticks2);
4833 
4834  Long_t userticks = (cpu_ticks2[0] + cpu_ticks2[3]) -
4835  (cpu_ticks1[0] + cpu_ticks1[3]);
4836  Long_t systicks = cpu_ticks2[1] - cpu_ticks1[1];
4837  Long_t idleticks = cpu_ticks2[2] - cpu_ticks1[2];
4838  if (userticks < 0) userticks = 0;
4839  if (systicks < 0) systicks = 0;
4840  if (idleticks < 0) idleticks = 0;
4841  Long_t totalticks = userticks + systicks + idleticks;
4842  if (totalticks) {
4843  cpuinfo->fUser = ((Float_t)(100 * userticks)) / ((Float_t)totalticks);
4844  cpuinfo->fSys = ((Float_t)(100 * systicks)) / ((Float_t)totalticks);
4845  cpuinfo->fTotal = cpuinfo->fUser + cpuinfo->fSys;
4846  cpuinfo->fIdle = ((Float_t)(100 * idleticks)) / ((Float_t)totalticks);
4847  }
4848 }
4849 
4850 ////////////////////////////////////////////////////////////////////////////////
4851 /// Get VM stat for Mac OS X.
4852 
4853 static void GetDarwinMemInfo(MemInfo_t *meminfo)
4854 {
4855  static Int_t pshift = 0;
4856  static DIR *dirp;
4857  vm_statistics_data_t vm_info;
4858  mach_msg_type_number_t count;
4859  kern_return_t kr;
4860  struct dirent *dp;
4861  Long64_t total, used, free, swap_total, swap_used;
4862 
4863  count = HOST_VM_INFO_COUNT;
4864  kr = host_statistics(mach_host_self(), HOST_VM_INFO, (host_info_t)&vm_info, &count);
4865  if (kr != KERN_SUCCESS) {
4866  ::Error("TUnixSystem::GetDarwinMemInfo", "host_statistics: %s", mach_error_string(kr));
4867  return;
4868  }
4869  if (pshift == 0) {
4870  for (int psize = getpagesize(); psize > 1; psize >>= 1)
4871  pshift++;
4872  }
4873 
4874  used = (Long64_t)(vm_info.active_count + vm_info.inactive_count + vm_info.wire_count) << pshift;
4875  free = (Long64_t)(vm_info.free_count) << pshift;
4876  total = (Long64_t)(vm_info.active_count + vm_info.inactive_count + vm_info.free_count + vm_info.wire_count) << pshift;
4877 
4878  // Swap is available at same time as mem, so grab values here.
4879  swap_used = vm_info.pageouts << pshift;
4880 
4881  // Figure out total swap. This adds up the size of the swapfiles */
4882  dirp = opendir("/private/var/vm");
4883  if (!dirp)
4884  return;
4885 
4886  swap_total = 0;
4887  while ((dp = readdir(dirp)) != 0) {
4888  struct stat sb;
4889  char fname [MAXNAMLEN];
4890  if (strncmp(dp->d_name, "swapfile", 8))
4891  continue;
4892  strlcpy(fname, "/private/var/vm/",MAXNAMLEN);
4893  strlcat (fname, dp->d_name,MAXNAMLEN);
4894  if (stat(fname, &sb) < 0)
4895  continue;
4896  swap_total += sb.st_size;
4897  }
4898  closedir(dirp);
4899 
4900  meminfo->fMemTotal = (Int_t) (total >> 20); // divide by 1024 * 1024
4901  meminfo->fMemUsed = (Int_t) (used >> 20);
4902  meminfo->fMemFree = (Int_t) (free >> 20);
4903  meminfo->fSwapTotal = (Int_t) (swap_total >> 20);
4904  meminfo->fSwapUsed = (Int_t) (swap_used >> 20);
4905  meminfo->fSwapFree = meminfo->fSwapTotal - meminfo->fSwapUsed;
4906 }
4907 
4908 ////////////////////////////////////////////////////////////////////////////////
4909 /// Get process info for this process on Mac OS X.
4910 /// Code largely taken from:
4911 /// http://www.opensource.apple.com/source/top/top-15/libtop.c
4912 /// The virtual memory usage is slightly over estimated as we don't
4913 /// subtract shared regions, but the value makes more sense
4914 /// then pure vsize, which is useless on 64-bit machines.
4915 
4916 static void GetDarwinProcInfo(ProcInfo_t *procinfo)
4917 {
4918 #ifdef _LP64
4919 #define vm_region vm_region_64
4920 #endif
4921 
4922 // taken from <mach/shared_memory_server.h> which is obsoleted in 10.5
4923 #define GLOBAL_SHARED_TEXT_SEGMENT 0x90000000U
4924 #define GLOBAL_SHARED_DATA_SEGMENT 0xA0000000U
4925 #define SHARED_TEXT_REGION_SIZE 0x10000000
4926 #define SHARED_DATA_REGION_SIZE 0x10000000
4927 
4928  struct rusage ru;
4929  if (getrusage(RUSAGE_SELF, &ru) < 0) {
4930  ::SysError("TUnixSystem::GetDarwinProcInfo", "getrusage failed");
4931  } else {
4932  procinfo->fCpuUser = (Float_t)(ru.ru_utime.tv_sec) +
4933  ((Float_t)(ru.ru_utime.tv_usec) / 1000000.);
4934  procinfo->fCpuSys = (Float_t)(ru.ru_stime.tv_sec) +
4935  ((Float_t)(ru.ru_stime.tv_usec) / 1000000.);
4936  }
4937 
4938  task_basic_info_data_t ti;
4939  mach_msg_type_number_t count;
4940  kern_return_t kr;
4941 
4942  task_t a_task = mach_task_self();
4943 
4944  count = TASK_BASIC_INFO_COUNT;
4945  kr = task_info(a_task, TASK_BASIC_INFO, (task_info_t)&ti, &count);
4946  if (kr != KERN_SUCCESS) {
4947  ::Error("TUnixSystem::GetDarwinProcInfo", "task_info: %s", mach_error_string(kr));
4948  } else {
4949  // resident size does not require any calculation. Virtual size
4950  // needs to be adjusted if traversing memory objects do not include the
4951  // globally shared text and data regions
4952  mach_port_t object_name;
4953  vm_address_t address;
4954  vm_region_top_info_data_t info;
4955  vm_size_t vsize, vprvt, rsize, size;
4956  rsize = ti.resident_size;
4957  vsize = ti.virtual_size;
4958  vprvt = 0;
4959  for (address = 0; ; address += size) {
4960  // get memory region
4961  count = VM_REGION_TOP_INFO_COUNT;
4962  if (vm_region(a_task, &address, &size,
4963  VM_REGION_TOP_INFO, (vm_region_info_t)&info, &count,
4964  &object_name) != KERN_SUCCESS) {
4965  // no more memory regions.
4966  break;
4967  }
4968 
4969  if (address >= GLOBAL_SHARED_TEXT_SEGMENT &&
4970  address < (GLOBAL_SHARED_DATA_SEGMENT + SHARED_DATA_REGION_SIZE)) {
4971  // This region is private shared.
4972  // Check if this process has the globally shared
4973  // text and data regions mapped in. If so, adjust
4974  // virtual memory size and exit loop.
4975  if (info.share_mode == SM_EMPTY) {
4976  vm_region_basic_info_data_64_t b_info;
4977  count = VM_REGION_BASIC_INFO_COUNT_64;
4978  if (vm_region_64(a_task, &address,
4979  &size, VM_REGION_BASIC_INFO,
4980  (vm_region_info_t)&b_info, &count,
4981  &object_name) != KERN_SUCCESS) {
4982  break;
4983  }
4984 
4985  if (b_info.reserved) {
4986  vsize -= (SHARED_TEXT_REGION_SIZE + SHARED_DATA_REGION_SIZE);
4987  //break; // only for vsize
4988  }
4989  }
4990  // Short circuit the loop if this isn't a shared
4991  // private region, since that's the only region
4992  // type we care about within the current address range.
4993  if (info.share_mode != SM_PRIVATE) {
4994  continue;
4995  }
4996  }
4997  switch (info.share_mode) {
4998  case SM_COW: {
4999  if (info.ref_count == 1) {
5000  vprvt += size;
5001  } else {
5002  vprvt += info.private_pages_resident * getpagesize();
5003  }
5004  break;
5005  }
5006  case SM_PRIVATE: {
5007  vprvt += size;
5008  break;
5009  }
5010  default:
5011  break;
5012  }
5013  }
5014 
5015  procinfo->fMemResident = (Long_t)(rsize / 1024);
5016  //procinfo->fMemVirtual = (Long_t)(vsize / 1024);
5017  procinfo->fMemVirtual = (Long_t)(vprvt / 1024);
5018  }
5019 }
5020 #endif
5021 
5022 #if defined(R__LINUX)
5023 ////////////////////////////////////////////////////////////////////////////////
5024 /// Get system info for Linux. Only fBusSpeed is not set.
5025 
5026 static void GetLinuxSysInfo(SysInfo_t *sysinfo)
5027 {
5028  TString s;
5029  FILE *f = fopen("/proc/cpuinfo", "r");
5030  if (f) {
5031  while (s.Gets(f)) {
5032  if (s.BeginsWith("model name")) {
5033  TPRegexp("^.+: *(.*$)").Substitute(s, "$1");
5034  sysinfo->fModel = s;
5035  }
5036  if (s.BeginsWith("cpu MHz")) {
5037  TPRegexp("^.+: *([^ ]+).*").Substitute(s, "$1");
5038  sysinfo->fCpuSpeed = s.Atoi();
5039  }
5040  if (s.BeginsWith("cache size")) {
5041  TPRegexp("^.+: *([^ ]+).*").Substitute(s, "$1");
5042  sysinfo->fL2Cache = s.Atoi();
5043  }
5044  if (s.BeginsWith("processor")) {
5045  TPRegexp("^.+: *([^ ]+).*").Substitute(s, "$1");
5046  sysinfo->fCpus = s.Atoi();
5047  sysinfo->fCpus++;
5048  }
5049  }
5050  fclose(f);
5051  }
5052 
5053  f = fopen("/proc/meminfo", "r");
5054  if (f) {
5055  while (s.Gets(f)) {
5056  if (s.BeginsWith("MemTotal")) {
5057  TPRegexp("^.+: *([^ ]+).*").Substitute(s, "$1");
5058  sysinfo->fPhysRam = (s.Atoi() / 1024);
5059  break;
5060  }
5061  }
5062  fclose(f);
5063  }
5064 
5065  f = gSystem->OpenPipe("uname -s -p", "r");
5066  if (f) {
5067  s.Gets(f);
5068  Ssiz_t from = 0;
5069  s.Tokenize(sysinfo->fOS, from);
5070  s.Tokenize(sysinfo->fCpuType, from);
5071  gSystem->ClosePipe(f);
5072  }
5073 }
5074 
5075 ////////////////////////////////////////////////////////////////////////////////
5076 /// Get CPU load on Linux.
5077 
5078 static void ReadLinuxCpu(long *ticks)
5079 {
5080  ticks[0] = ticks[1] = ticks[2] = ticks[3] = 0;
5081 
5082  TString s;
5083  FILE *f = fopen("/proc/stat", "r");
5084  if (!f) return;
5085  s.Gets(f);
5086  // user, user nice, sys, idle
5087  sscanf(s.Data(), "%*s %ld %ld %ld %ld", &ticks[0], &ticks[3], &ticks[1], &ticks[2]);
5088  fclose(f);
5089 }
5090 
5091 ////////////////////////////////////////////////////////////////////////////////
5092 /// Get CPU stat for Linux. Use sampleTime to set the interval over which
5093 /// the CPU load will be measured, in ms (default 1000).
5094 
5095 static void GetLinuxCpuInfo(CpuInfo_t *cpuinfo, Int_t sampleTime)
5096 {
5097  Double_t avg[3] = { -1., -1., -1. };
5098 #ifndef R__WINGCC
5099  if (getloadavg(avg, sizeof(avg)) < 0) {
5100  ::Error("TUnixSystem::GetLinuxCpuInfo", "getloadavg failed");
5101  } else
5102 #endif
5103  {
5104  cpuinfo->fLoad1m = (Float_t)avg[0];
5105  cpuinfo->fLoad5m = (Float_t)avg[1];
5106  cpuinfo->fLoad15m = (Float_t)avg[2];
5107  }
5108 
5109  Long_t cpu_ticks1[4], cpu_ticks2[4];
5110  ReadLinuxCpu(cpu_ticks1);
5111  gSystem->Sleep(sampleTime);
5112  ReadLinuxCpu(cpu_ticks2);
5113 
5114  Long_t userticks = (cpu_ticks2[0] + cpu_ticks2[3]) -
5115  (cpu_ticks1[0] + cpu_ticks1[3]);
5116  Long_t systicks = cpu_ticks2[1] - cpu_ticks1[1];
5117  Long_t idleticks = cpu_ticks2[2] - cpu_ticks1[2];
5118  if (userticks < 0) userticks = 0;
5119  if (systicks < 0) systicks = 0;
5120  if (idleticks < 0) idleticks = 0;
5121  Long_t totalticks = userticks + systicks + idleticks;
5122  if (totalticks) {
5123  cpuinfo->fUser = ((Float_t)(100 * userticks)) / ((Float_t)totalticks);
5124  cpuinfo->fSys = ((Float_t)(100 * systicks)) / ((Float_t)totalticks);
5125  cpuinfo->fTotal = cpuinfo->fUser + cpuinfo->fSys;
5126  cpuinfo->fIdle = ((Float_t)(100 * idleticks)) / ((Float_t)totalticks);
5127  }
5128 }
5129 
5130 ////////////////////////////////////////////////////////////////////////////////
5131 /// Get VM stat for Linux.
5132 
5133 static void GetLinuxMemInfo(MemInfo_t *meminfo)
5134 {
5135  TString s;
5136  FILE *f = fopen("/proc/meminfo", "r");
5137  if (!f) return;
5138  while (s.Gets(f)) {
5139  if (s.BeginsWith("MemTotal")) {
5140  TPRegexp("^.+: *([^ ]+).*").Substitute(s, "$1");
5141  meminfo->fMemTotal = (s.Atoi() / 1024);
5142  }
5143  if (s.BeginsWith("MemFree")) {
5144  TPRegexp("^.+: *([^ ]+).*").Substitute(s, "$1");
5145  meminfo->fMemFree = (s.Atoi() / 1024);
5146  }
5147  if (s.BeginsWith("SwapTotal")) {
5148  TPRegexp("^.+: *([^ ]+).*").Substitute(s, "$1");
5149  meminfo->fSwapTotal = (s.Atoi() / 1024);
5150  }
5151  if (s.BeginsWith("SwapFree")) {
5152  TPRegexp("^.+: *([^ ]+).*").Substitute(s, "$1");
5153  meminfo->fSwapFree = (s.Atoi() / 1024);
5154  }
5155  }
5156  fclose(f);
5157 
5158  meminfo->fMemUsed = meminfo->fMemTotal - meminfo->fMemFree;
5159  meminfo->fSwapUsed = meminfo->fSwapTotal - meminfo->fSwapFree;
5160 }
5161 
5162 ////////////////////////////////////////////////////////////////////////////////
5163 /// Get process info for this process on Linux.
5164 
5165 static void GetLinuxProcInfo(ProcInfo_t *procinfo)
5166 {
5167  struct rusage ru;
5168  if (getrusage(RUSAGE_SELF, &ru) < 0) {
5169  ::SysError("TUnixSystem::GetLinuxProcInfo", "getrusage failed");
5170  } else {
5171  procinfo->fCpuUser = (Float_t)(ru.ru_utime.tv_sec) +
5172  ((Float_t)(ru.ru_utime.tv_usec) / 1000000.);
5173  procinfo->fCpuSys = (Float_t)(ru.ru_stime.tv_sec) +
5174  ((Float_t)(ru.ru_stime.tv_usec) / 1000000.);
5175  }
5176 
5177  procinfo->fMemVirtual = -1;
5178  procinfo->fMemResident = -1;
5179  TString s;
5180  FILE *f = fopen(TString::Format("/proc/%d/statm", gSystem->GetPid()), "r");
5181  if (f) {
5182  s.Gets(f);
5183  fclose(f);
5184  Long_t total, rss;
5185  sscanf(s.Data(), "%ld %ld", &total, &rss);
5186  procinfo->fMemVirtual = total * (getpagesize() / 1024);
5187  procinfo->fMemResident = rss * (getpagesize() / 1024);
5188  }
5189 }
5190 #endif
5191 
5192 ////////////////////////////////////////////////////////////////////////////////
5193 /// Returns static system info, like OS type, CPU type, number of CPUs
5194 /// RAM size, etc into the SysInfo_t structure. Returns -1 in case of error,
5195 /// 0 otherwise.
5196 
5198 {
5199  if (!info) return -1;
5200 
5201  static SysInfo_t sysinfo;
5202 
5203  if (!sysinfo.fCpus) {
5204 #if defined(R__MACOSX)
5205  GetDarwinSysInfo(&sysinfo);
5206 #elif defined(R__LINUX)
5207  GetLinuxSysInfo(&sysinfo);
5208 #endif
5209  }
5210 
5211  *info = sysinfo;
5212 
5213  return 0;
5214 }
5215 
5216 ////////////////////////////////////////////////////////////////////////////////
5217 /// Returns cpu load average and load info into the CpuInfo_t structure.
5218 /// Returns -1 in case of error, 0 otherwise. Use sampleTime to set the
5219 /// interval over which the CPU load will be measured, in ms (default 1000).
5220 
5221 int TUnixSystem::GetCpuInfo(CpuInfo_t *info, Int_t sampleTime) const
5222 {
5223  if (!info) return -1;
5224 
5225 #if defined(R__MACOSX)
5226  GetDarwinCpuInfo(info, sampleTime);
5227 #elif defined(R__LINUX)
5228  GetLinuxCpuInfo(info, sampleTime);
5229 #endif
5230 
5231  return 0;
5232 }
5233 
5234 ////////////////////////////////////////////////////////////////////////////////
5235 /// Returns ram and swap memory usage info into the MemInfo_t structure.
5236 /// Returns -1 in case of error, 0 otherwise.
5237 
5239 {
5240  if (!info) return -1;
5241 
5242 #if defined(R__MACOSX)
5243  GetDarwinMemInfo(info);
5244 #elif defined(R__LINUX)
5245  GetLinuxMemInfo(info);
5246 #endif
5247 
5248  return 0;
5249 }
5250 
5251 ////////////////////////////////////////////////////////////////////////////////
5252 /// Returns cpu and memory used by this process into the ProcInfo_t structure.
5253 /// Returns -1 in case of error, 0 otherwise.
5254 
5256 {
5257  if (!info) return -1;
5258 
5259 #if defined(R__MACOSX)
5260  GetDarwinProcInfo(info);
5261 #elif defined(R__LINUX)
5262  GetLinuxProcInfo(info);
5263 #endif
5264 
5265  return 0;
5266 }
Bool_t IsPathLocal(const char *path)
Returns TRUE if the url in &#39;path&#39; points to the local file system.
Int_t fMemFree
Definition: TSystem.h:193
const char * TempDirectory() const
Return a user configured or systemwide directory to create temporary files in.
Int_t fGid
Definition: TSystem.h:151
int GetPid()
Get process id.
virtual const char * BaseName(const char *pathname)
Base name of a file name. Base name of /user/root is root.
Definition: TSystem.cxx:929
TString fStdErrTty
Definition: TSystem.h:217
int GetFsInfo(const char *path, Long_t *id, Long_t *bsize, Long_t *blocks, Long_t *bfree)
Get info about a file system: id, bsize, bfree, blocks.
virtual Bool_t AccessPathName(const char *path, EAccessMode mode=kFileExists)
Returns FALSE if one can access a file using the specified access mode.
Definition: TSystem.cxx:1265
Float_t fLoad15m
Definition: TSystem.h:179
double read(const std::string &file_name)
reading
void AddTimer(TTimer *ti)
Add timer to list of system timers.
virtual void SetWriteReady()
void ListSymbols(const char *module, const char *re="")
List symbols in a shared library.
virtual int GetPid()
Get process id.
Definition: TSystem.cxx:712
An array of TObjects.
Definition: TObjArray.h:39
void StackTrace()
Print a stack trace.
Bool_t AccessPathName(const char *path, EAccessMode mode=kFileExists)
Returns FALSE if one can access a file using the specified access mode.
int pw_uid
Definition: TWinNTSystem.h:52
virtual Bool_t Notify()
Notify when event occurred on descriptor associated with this handler.
virtual Bool_t IsPathLocal(const char *path)
Returns TRUE if the url in &#39;path&#39; points to the local file system.
Definition: TSystem.cxx:1274
long long Long64_t
Definition: RtypesCore.h:69
Int_t fBusSpeed
Definition: TSystem.h:167
int GetMemInfo(MemInfo_t *info) const
Returns ram and swap memory usage info into the MemInfo_t structure.
Int_t fPhysRam
Definition: TSystem.h:169
Int_t fSigcnt
Definition: TSystem.h:275
const char * GetError()
Return system error string.
Int_t fReadOffSet
Definition: TSystem.h:220
Bool_t IsSync() const
virtual const char * WorkingDirectory()
Return working directory.
Definition: TSystem.cxx:866
void Sleep(UInt_t milliSec)
Sleep milliSec milliseconds.
char * pw_shell
Definition: TWinNTSystem.h:57
Bool_t Init()
Initialize Unix system interface.
const char * FindFile(const char *search, TString &file, EAccessMode mode=kFileExists)
Find location of file &quot;wfil&quot; in a search path.
Float_t fSys
Definition: TSystem.h:181
static void UnixResetSignal(ESignals sig)
Restore old signal handler for specified signal.
Bool_t ExpandPathName(TString &patbuf)
Expand a pathname getting rid of special shell characters like ~.
double write(int n, const std::string &file_name, const std::string &vector_type, int compress=0)
writing
std::string GetWorkingDirectory() const
Return working directory.
virtual ~TUnixSystem()
Reset to original state.
static const char * GetExePath()
R__EXTERN TVirtualMutex * gSystemMutex
Definition: TSystem.h:236
Ssiz_t Length() const
Definition: TString.h:390
TLine * line
void Fatal(const char *location, const char *msgfmt,...)
Collectable string class.
Definition: TObjString.h:32
float Float_t
Definition: RtypesCore.h:53
int gr_gid
Definition: TWinNTSystem.h:64
int GetPathInfo(const char *path, FileStat_t &buf)
Get info about a file.
static int UnixFilestat(const char *path, FileStat_t &buf)
Get info about a file.
Int_t GetFPEMask()
Return the bitmap of conditions that trigger a floating point exception.
static int UnixTcpConnect(const char *hostname, int port, int tcpwindowsize)
Open a TCP/IP connection to server and connect to a service (i.e.
TString fOS
Definition: TSystem.h:162
static int UnixRecv(int sock, void *buf, int len, int flag)
Receive exactly length bytes into buffer.
int GetSockOpt(int sock, int option, int *val)
Get socket option.
Int_t fUid
Definition: TSystem.h:139
TString & ReplaceAll(const TString &s1, const TString &s2)
Definition: TString.h:635
int GetPathInfo(const char *path, Long_t *id, Long_t *size, Long_t *flags, Long_t *modtime)
Get info about a file: id, size, flags, modification time.
Definition: TSystem.cxx:1363
Bool_t DispatchTimers(Bool_t mode)
Handle and dispatch timers.
const char * FindDynamicLibrary(TString &lib, Bool_t quiet=kFALSE)
Returns the path of a shared library (searches for library in the shared library search path)...
void demangle(char *_codeInfo, TString &_str)
demangle symbols
TH1 * h
Definition: legend2.C:5
const Int_t kFDSETSIZE
TString fStdOutTty
Definition: TSystem.h:216
char * gr_name
Definition: TWinNTSystem.h:62
TString fGroup
Definition: TSystem.h:153
int Symlink(const char *from, const char *to)
Create a symlink from file1 to file2.
const Int_t kNFDBITS
This class represents an Internet Protocol (IP) address.
Definition: TInetAddress.h:40
virtual int MakeDirectory(const char *name)
Make a directory.
Definition: TSystem.cxx:822
virtual void AddSignalHandler(TSignalHandler *sh)
Add a signal handler to list of system signal handlers.
Definition: TSystem.cxx:537
TString fWdpath
Definition: TSystem.h:276
int MakeDirectory(const char *name)
Make a Unix file system directory.
Regular expression class.
Definition: TRegexp.h:35
Int_t fStdOutDup
Definition: TSystem.h:218
#define gROOT
Definition: TROOT.h:379
Int_t Select(TList *active, Long_t timeout)
Select on file descriptors.
Int_t GetGid(const char *group=0)
Returns the group&#39;s id. If group = 0, returns current user&#39;s group.
static Long64_t UnixNow()
Get current time in milliseconds since 0:00 Jan 1 1995.
virtual int Load(const char *module, const char *entry="", Bool_t system=kFALSE)
Load a shared library.
Definition: TSystem.cxx:1818
Basic string class.
Definition: TString.h:137
void SetProgname(const char *name)
Set the application name (from command line, argv[0]) and copy it in gProgName.
TSeqCollection * fSignalHandler
Definition: TSystem.h:287
static struct Signalmap_t gSignalMap[kMAXSIGNALS]
TFileHandler * RemoveFileHandler(TFileHandler *fh)
Remove a file handler from the list of file handlers.
int Int_t
Definition: RtypesCore.h:41
virtual const char * DirName(const char *pathname)
Return the directory name in pathname.
Definition: TSystem.cxx:997
bool Bool_t
Definition: RtypesCore.h:59
virtual TTimer * RemoveTimer(TTimer *t)
Remove timer from list of system timers.
Definition: TSystem.cxx:486
TArc * a
Definition: textangle.C:12
const Bool_t kFALSE
Definition: Rtypes.h:92
Int_t Substitute(TString &s, const TString &replace, const TString &mods="", Int_t start=0, Int_t nMatchMax=10)
Substitute replaces the string s by a new string in which matching patterns are replaced by the repla...
Definition: TPRegexp.cxx:469
const char * HostName()
Return the system&#39;s host name.
int SendRaw(int sock, const void *buffer, int length, int flag)
Send exactly length bytes from buffer.
int Umask(Int_t mask)
Set the process file creation mode mask.
#define gInterpreter
Definition: TInterpreter.h:517
virtual char * Which(const char *search, const char *file, EAccessMode mode=kFileExists)
Find location of file in a search path.
Definition: TSystem.cxx:1511
void Break(const char *location, const char *msgfmt,...)
Long_t fMtime
Definition: TSystem.h:142
void Syslog(ELogLevel level, const char *mess)
Send mess to syslog daemon.
virtual FILE * OpenPipe(const char *command, const char *mode)
Open a pipe.
Definition: TSystem.cxx:667
#define REAL_DIR_ENTRY(dp)
virtual void ResetReadyMask()
TString & Prepend(const char *cs)
Definition: TString.h:604
R__EXTERN TApplication * gApplication
Definition: TApplication.h:171
Basic time type with millisecond precision.
Definition: TTime.h:29
static void UnixSigAlarmInterruptsSyscalls(Bool_t set)
When the argument is true the SIGALRM signal handler is set so that interrupted syscalls will not be ...
int ConnectService(const char *server, int port, int tcpwindowsize, const char *protocol="tcp")
Connect to service servicename on server servername.
const char * HomeDirectory(const char *userName=0)
Return the user&#39;s home directory.
const char * kShellMeta
TString fModel
Definition: TSystem.h:163
Bool_t fInsideNotify
Definition: TSystem.h:278
#define malloc
Definition: civetweb.c:818
Long64_t fSize
Definition: TSystem.h:141
Bool_t BeginsWith(const char *s, ECaseCompare cmp=kExact) const
Definition: TString.h:558
void Exit(int code, Bool_t mode=kTRUE)
Exit the application.
int Unlink(const char *name)
Unlink, i.e.
Int_t fUid
Definition: TSystem.h:150
const char * kProtocolName
#define UTMP_FILE
static int UnixSelect(Int_t nfds, TFdSet *readready, TFdSet *writeready, Long_t timeout)
Wait for events on the file descriptors specified in the readready and writeready masks or for timeou...
virtual TFileHandler * RemoveFileHandler(TFileHandler *fh)
Remove a file handler from the list of file handlers.
Definition: TSystem.cxx:569
void Reset()
Definition: TCollection.h:161
virtual int mkdir(const char *name, Bool_t recursive=kFALSE)
Make a file system directory.
Definition: TSystem.cxx:901
void SysError(const char *location, const char *msgfmt,...)
virtual const char * FindFile(const char *search, TString &file, EAccessMode mode=kFileExists)
Find location of file in a search path.
Definition: TSystem.cxx:1501
static Int_t GetErrno()
Static function returning system error number.
Definition: TSystem.cxx:265
Int_t fMode
Definition: TSystem.h:138
TString fHostname
Definition: TSystem.h:277
const char * String
Definition: TXMLSetup.cxx:94
const char * Data() const
Definition: TString.h:349
virtual Bool_t Notify()
Notify when signal occurs.
virtual const char * GetDirEntry(void *dirp)
Get a directory entry. Returns 0 if no more entries.
Definition: TSystem.cxx:848
virtual int Unlink(const char *name)
Unlink, i.e. remove, a file.
Definition: TSystem.cxx:1346
Int_t Exec(const char *shellcmd)
Execute a command.
static TString Format(const char *fmt,...)
Static method which formats a string using a printf style format descriptor and return a TString...
Definition: TString.cxx:2335
void DispatchOneEvent(Bool_t pendingOnly=kFALSE)
Dispatch a single event.
virtual void Sleep(UInt_t milliSec)
Sleep milliSec milli seconds.
Definition: TSystem.cxx:442
Float_t fUser
Definition: TSystem.h:180
Bool_t IsValid() const
Definition: TInetAddress.h:80
void AddSignalHandler(TSignalHandler *sh)
Add a signal handler to list of system signal handlers.
Int_t fSwapFree
Definition: TSystem.h:196
static int UnixSend(int sock, const void *buf, int len, int flag)
Send exactly length bytes from buffer.
Int_t bsize[]
Definition: SparseFit4.cxx:31
const char * PrependPathName(const char *dir, TString &name)
Concatenate a directory and a file name.
Int_t fMaxrfd
Definition: TSystem.h:273
Int_t SetFPEMask(Int_t mask=kDefaultMask)
Set which conditions trigger a floating point exception.
static const char * DynamicPath(const char *newpath=0, Bool_t reset=kFALSE)
Get shared library search path. Static utility function.
TObject * Next()
Return next object in collection.
Int_t fNfd
Signals that were trapped.
Definition: TSystem.h:272
R__EXTERN TFileHandler * gXDisplay
Definition: TSystem.h:550
TString fShell
Definition: TSystem.h:156
static TString * ReadString(TBuffer &b, const TClass *clReq)
Read TString object from buffer.
Definition: TString.cxx:1259
TString fRealName
Definition: TSystem.h:155
static int UnixSetitimer(Long_t ms)
Set interval timer to time-out in ms milliseconds.
virtual const char * Getenv(const char *env)
Get environment variable.
Definition: TSystem.cxx:1627
virtual void ListLibraries(const char *regexp="")
List all loaded shared libraries.
Definition: TSystem.cxx:1999
static void UnixResetSignals()
Restore old signal handlers.
FILE * OpenPipe(const char *shellcmd, const char *mode)
Open a pipe.
TString & Append(const char *cs)
Definition: TString.h:492
virtual const char * PrependPathName(const char *dir, TString &name)
Concatenate a directory and a file name.
Definition: TSystem.cxx:1055
TInetAddress GetHostByName(const char *server)
Get Internet Protocol (IP) address of host.
int AcceptConnection(int sock)
Accept a connection.
Int_t Atoi() const
Return integer value of string.
Definition: TString.cxx:1965
virtual void Unload(const char *module)
Unload a shared library.
Definition: TSystem.cxx:1978
char * pw_name
Definition: TWinNTSystem.h:50
virtual void Error(const char *method, const char *msgfmt,...) const
Issue error message.
Definition: TObject.cxx:925
virtual TInetAddress GetHostByName(const char *server)
Get Internet Protocol (IP) address of host.
Definition: TSystem.cxx:2260
int CopyFile(const char *from, const char *to, Bool_t overwrite=kFALSE)
Copy a file.
void ResetSignals()
Reset signals handlers to previous behaviour.
int SetSockOpt(int sock, int option, int val)
Set socket option.
Int_t fGid
Definition: TSystem.h:140
UInt_t GetAddress() const
Definition: TInetAddress.h:72
ELogLevel
Definition: TSystem.h:66
TSeqCollection * fFileHandler
Definition: TSystem.h:288
A doubly linked list.
Definition: TList.h:47
Float_t fLoad1m
Definition: TSystem.h:177
TString & GetLastErrorString()
Return the thread local storage for the custom last error message.
Definition: TSystem.cxx:2036
char ** Argv() const
Definition: TApplication.h:142
static void SigHandler(ESignals sig)
Unix signal handler.
Int_t fL2Cache
Definition: TSystem.h:168
int GetFd() const
TTimer * RemoveTimer(TTimer *ti)
Remove timer from list of system timers.
virtual Bool_t WriteNotify()
Notify when something can be written to the descriptor associated with this handler.
R__EXTERN const char * gProgName
Definition: TSystem.h:234
int GetCpuInfo(CpuInfo_t *info, Int_t sampleTime=1000) const
Returns cpu load average and load info into the CpuInfo_t structure.
Float_t fCpuUser
Definition: TSystem.h:204
ESignals
char * pw_gecos
Definition: TWinNTSystem.h:55
static const char * UnixHomedirectory(const char *user=0)
Returns the user&#39;s home directory.
Bool_t IsActive() const
TString fUser
Definition: TSystem.h:152
static void sighandler(int sig)
Call the signal handler associated with the signal.
void FreeDirectory(void *dirp)
Close a Unix file system directory.
virtual void Setenv(const char *name, const char *value)
Set environment variable.
Definition: TSystem.cxx:1611
Int_t fCpus
Definition: TSystem.h:165
virtual Bool_t HasWriteInterest()
True if handler is interested in write events.
Bool_t EndsWith(const char *pat, ECaseCompare cmp=kExact) const
Return true if string ends with the specified string.
Definition: TString.cxx:2221
virtual Bool_t Init()
Initialize the OS interface.
Definition: TSystem.cxx:187
int Chmod(const char *file, UInt_t mode)
Set the file permission bits. Returns -1 in case or error, 0 otherwise.
Bool_t fIsLink
Definition: TSystem.h:143
R__EXTERN TSystem * gSystem
Definition: TSystem.h:549
void FillWithCwd(char *cwd) const
Fill buffer with current working directory.
int Utime(const char *file, Long_t modtime, Long_t actime)
Set a files modification and access times.
virtual Int_t GetValue(const char *name, Int_t dflt)
Returns the integer value for a resource.
Definition: TEnv.cxx:482
TInetAddress GetSockName(int sock)
Get Internet Protocol (IP) address of host and port #.
Int_t fSwapUsed
Definition: TSystem.h:195
Bool_t Gets(FILE *fp, Bool_t chop=kTRUE)
Read one line from the stream, including the , or until EOF.
Definition: Stringio.cxx:198
const char * kServerPath
Long_t fMemVirtual
Definition: TSystem.h:207
#define HOWMANY(x, y)
virtual void SetReadReady()
std::string GetHomeDirectory(const char *userName=0) const
Return the user&#39;s home directory.
virtual Long_t NextTimeOut(Bool_t mode)
Time when next timer of mode (synchronous=kTRUE or asynchronous=kFALSE) will time-out (in ms)...
Definition: TSystem.cxx:499
void CloseConnection(int sock, Bool_t force=kFALSE)
Close socket.
void Form(const char *fmt,...)
Formats a string using a printf style format descriptor.
Definition: TString.cxx:2322
void Closelog()
Close connection to system log daemon.
unsigned int UInt_t
Definition: RtypesCore.h:42
TMarker * m
Definition: textangle.C:8
char * Form(const char *fmt,...)
void SetDisplay()
Set DISPLAY environment variable based on utmp entry. Only for UNIX.
static const char * StripOffProto(const char *path, const char *proto)
Definition: TSystem.h:325
Definition: TSocket.h:68
Handles synchronous and a-synchronous timer events.
Definition: TTimer.h:57
Bool_t CheckTimer(const TTime &now)
Check if timer timed out.
Definition: TTimer.cxx:128
Float_t fLoad5m
Definition: TSystem.h:178
Bool_t CheckDescriptors()
Check if there is activity on some file descriptors and call their Notify() member.
TSubString Strip(EStripType s=kTrailing, char c= ' ') const
Return a substring of self stripped at beginning and/or end.
Definition: TString.cxx:1070
Func_t DynFindSymbol(const char *module, const char *entry)
dynamic linking of module
static int UnixWaitchild()
Wait till child is finished.
void * OpenDirectory(const char *name)
Open a Unix file system directory. Returns 0 if directory does not exist.
static int UnixUnixService(int port, int backlog)
Open a socket, bind to it and start listening for Unix domain connections to it.
static const char * UnixSigname(ESignals sig)
Return the signal name associated with a signal.
Bool_t IsNull() const
Definition: TString.h:387
Int_t RedirectOutput(const char *name, const char *mode="a", RedirectHandle_t *h=0)
Redirect standard output (stdout, stderr) to the specified file.
static int UnixFSstat(const char *path, Long_t *id, Long_t *bsize, Long_t *blocks, Long_t *bfree)
Get info about a file system: id, bsize, bfree, blocks.
TString & String()
Definition: TObjString.h:52
const char * GetDynamicPath()
Return the dynamic path (used to find shared libraries).
virtual void FreeDirectory(void *dirp)
Free a directory.
Definition: TSystem.cxx:840
virtual int ClosePipe(FILE *pipe)
Close the pipe.
Definition: TSystem.cxx:676
TGraphErrors * gr
Definition: legend1.C:25
TObjArray * Tokenize(const TString &delim) const
This function is used to isolate sequential tokens in a TString.
Definition: TString.cxx:2241
Int_t GetUid(const char *user=0)
Returns the user&#39;s id. If user = 0, returns current user&#39;s id.
#define Printf
Definition: TGeoToOCC.h:18
int GetProcInfo(ProcInfo_t *info) const
Returns cpu and memory used by this process into the ProcInfo_t structure.
void Unsetenv(const char *name)
Unset environment variable.
UserGroup_t * GetGroupInfo(Int_t gid)
Returns all group info in the UserGroup_t structure.
char * StrDup(const char *str)
Duplicate the string str.
Definition: TString.cxx:2514
#define R__LOCKGUARD2(mutex)
virtual int SetSockOpt(int sock, int kind, int val)
Set socket option.
Definition: TSystem.cxx:2405
static void UnixSignal(ESignals sig, SigHandler_t h)
Set a signal handler for a signal.
static unsigned int total
TString & Remove(Ssiz_t pos)
Definition: TString.h:616
long Long_t
Definition: RtypesCore.h:50
int Ssiz_t
Definition: RtypesCore.h:63
TString fPasswd
Definition: TSystem.h:154
virtual void SysError(const char *method, const char *msgfmt,...) const
Issue system error message.
Definition: TObject.cxx:939
const char * Getenv(const char *name)
Get environment variable.
virtual TSignalHandler * RemoveSignalHandler(TSignalHandler *sh)
Remove a signal handler from list of signal handlers.
Definition: TSystem.cxx:547
static int UnixMakedir(const char *name)
Make a Unix file system directory.
virtual Int_t GetSize() const
Definition: TCollection.h:95
TFdSet * fReadready
Files that should be checked for write events.
Definition: TSystem.h:269
static int UnixUdpService(int port, int backlog)
Open a socket, bind to it and start listening for UDP connections on the port.
R__EXTERN const char * gProgPath
Definition: TSystem.h:235
TString & Swap(TString &other)
Definition: TString.h:647
#define ClassImp(name)
Definition: Rtypes.h:279
void(* SigHandler_t)(ESignals)
Definition: TUnixSystem.h:34
double f(double x)
#define STRUCT_UTMP
Float_t fCpuSys
Definition: TSystem.h:205
Int_t GetEffectiveUid()
Returns the effective user id.
static int UnixUnixConnect(int port)
Connect to a Unix domain socket.
virtual Func_t DynFindSymbol(const char *module, const char *entry)
Find specific entry point in specified library.
Definition: TSystem.cxx:1970
virtual const char * GetName() const
Returns name of object.
Definition: TObject.cxx:416
static int UnixTcpService(int port, Bool_t reuse, int backlog, int tcpwindowsize)
Open a socket, bind to it and start listening for TCP/IP connections on the port. ...
double Double_t
Definition: RtypesCore.h:55
TFdSet * fReadmask
Definition: TSystem.h:267
int RecvRaw(int sock, void *buffer, int length, int flag)
Receive exactly length bytes into buffer.
Long64_t Atoll() const
Return long long value of string.
Definition: TString.cxx:1991
int RecvBuf(int sock, void *buffer, int length)
Receive a buffer headed by a length indicator.
ELogFacility
Definition: TSystem.h:77
Int_t GetFamily() const
Definition: TInetAddress.h:76
int Rename(const char *from, const char *to)
Rename a file. Returns 0 when successful, -1 in case of failure.
int AnnounceTcpService(int port, Bool_t reuse, int backlog, int tcpwindowsize=-1)
Announce TCP/IP service.
int type
Definition: TGX11.cxx:120
R__EXTERN TEnv * gEnv
Definition: TEnv.h:174
virtual const char * ExpandFileName(const char *fname)
Expand a pathname getting rid of special shell characters like ~.
Definition: TSystem.cxx:1072
void CheckChilds()
Check if children have finished.
TString fCpuType
Definition: TSystem.h:164
#define free
Definition: civetweb.c:821
unsigned long ULong_t
Definition: RtypesCore.h:51
static const TString & GetEtcDir()
Get the sysconfig directory in the installation. Static utility function.
Definition: TROOT.cxx:2755
double func(double *x, double *p)
Definition: stressTF1.cxx:213
static void UnixIgnoreSignal(ESignals sig, Bool_t ignore)
If ignore is true ignore the specified signal, else restore previous behaviour.
TFdSet * fSignals
Files with writes waiting.
Definition: TSystem.h:271
Bool_t IsSync() const
Definition: TTimer.h:86
static void * UnixOpendir(const char *name)
Open a directory.
Definition: TSocket.h:67
EAccessMode
Definition: TSystem.h:54
void Reset()
Definition: TSystem.h:223
Bool_t ChangeDirectory(const char *path)
Change directory. Returns kTRUE in case of success, kFALSE otherwise.
const char * GetLinkedLibraries()
Get list of shared libraries loaded at the start of the executable.
char * GetServiceByPort(int port)
Get name of internet service.
Int_t fMemTotal
Definition: TSystem.h:191
int pw_gid
Definition: TWinNTSystem.h:53
#define org(otri, vertexptr)
Definition: triangle.c:1037
int EscChar(const char *src, char *dst, int dstlen, char *specchars, char escchar)
Escape specchars in src with escchar and copy to dst.
Definition: TString.cxx:2549
virtual void HandleException(Int_t sig)
Handle exceptions (kSigBus, kSigSegmentationViolation, kSigIllegalInstruction and kSigFloatingExcepti...
typedef void((*Func_t)())
Int_t fMaxwfd
Definition: TSystem.h:274
TSeqCollection * fTimers
Definition: TSystem.h:286
void ResetSignal(ESignals sig, Bool_t reset=kTRUE)
If reset is true reset the signal handler for the specified signal to the default handler...
void IgnoreSignal(ESignals sig, Bool_t ignore=kTRUE)
If ignore is true ignore the specified signal, else restore previous behaviour.
const Ssiz_t kNPOS
Definition: Rtypes.h:115
static const TString & GetLibDir()
Get the library directory in the installation. Static utility function.
Definition: TROOT.cxx:2713
virtual void AddTimer(TTimer *t)
Add timer to list of system timers.
Definition: TSystem.cxx:476
static const char * UnixGetdirentry(void *dir)
Returns the next directory entry.
R__EXTERN const char * gRootDir
Definition: TSystem.h:233
void ResetTimer(TTimer *ti)
Reset a-sync timer.
void AddDynamicPath(const char *lib)
Add a new directory to the dynamic path.
Short_t Max(Short_t a, Short_t b)
Definition: TMathBase.h:202
ESignals GetSignal() const
Bool_t Contains(const char *pat, ECaseCompare cmp=kExact) const
Definition: TString.h:567
const char * GetDirEntry(void *dirp)
Get next Unix file system directory entry. Returns 0 if no more entries.
int GetSysInfo(SysInfo_t *info) const
Returns static system info, like OS type, CPU type, number of CPUs RAM size, etc into the SysInfo_t s...
Int_t fMemUsed
Definition: TSystem.h:192
you should not use this method at all Int_t Int_t Double_t Double_t Double_t Int_t Double_t Double_t Double_t Double_t b
Definition: TRolke.cxx:630
Int_t fCpuSpeed
Definition: TSystem.h:166
TInetAddress GetPeerName(int sock)
Get Internet Protocol (IP) address of remote host and port #.
void AddFileHandler(TFileHandler *fh)
Add a file handler to the list of system file handlers.
#define NULL
Definition: Rtypes.h:82
Long_t fIno
Definition: TSystem.h:137
#define snprintf
Definition: civetweb.c:822
FILE * TempFileName(TString &base, const char *dir=0)
Create a secure temporary file by appending a unique 6 letter string to base.
char * pw_passwd
Definition: TWinNTSystem.h:51
char * pw_dir
Definition: TWinNTSystem.h:56
virtual void * OpenDirectory(const char *name)
Open a directory. Returns 0 if directory does not exist.
Definition: TSystem.cxx:831
R__EXTERN Int_t gDebug
Definition: Rtypes.h:128
Iterator of ordered collection.
TSignalHandler * RemoveSignalHandler(TSignalHandler *sh)
Remove a signal handler from list of signal handlers.
int AnnounceUnixService(int port, int backlog)
Announce unix domain service on path &quot;kServerPath/&lt;port&gt;&quot;.
virtual Bool_t ReadNotify()
Notify when something can be read from the descriptor associated with this handler.
int ClosePipe(FILE *pipe)
Close the pipe.
void SetDynamicPath(const char *lib)
Set the dynamic path to a new value.
int Link(const char *from, const char *to)
Create a link from file1 to file2.
void Abort(int code=0)
Abort the application.
void Unload(const char *module)
Unload a shared library.
TSystem * FindHelper(const char *path, void *dirptr=0)
Create helper TSystem to handle file and directory operations that might be special for remote file a...
Definition: TSystem.cxx:749
virtual void AddFileHandler(TFileHandler *fh)
Add a file handler to the list of system file handlers.
Definition: TSystem.cxx:559
static void ResetErrno()
Static function resetting system error number.
Definition: TSystem.cxx:281
void SigAlarmInterruptsSyscalls(Bool_t set)
When the argument is true the SIGALRM signal handler is set so that interrupted syscalls will not be ...
Int_t GetEffectiveGid()
Returns the effective group id.
double result[121]
Float_t fTotal
Definition: TSystem.h:182
Bool_t CheckSignals(Bool_t sync)
Check if some signals were raised and call their Notify() member.
static int UnixUdpConnect(const char *hostname, int port)
Creates a UDP socket connection Is called via the TSocket constructor.
int GetServiceByName(const char *service)
Get port # of internet service.
virtual Bool_t ExpandPathName(TString &path)
Expand a pathname getting rid of special shell characters like ~.
Definition: TSystem.cxx:1243
TTime Now()
Get current time in milliseconds since 0:00 Jan 1 1995.
TFdSet * fWriteready
Files with reads waiting.
Definition: TSystem.h:270
Int_t fSwapTotal
Definition: TSystem.h:194
TObject * At(Int_t idx) const
Definition: TObjArray.h:167
void Openlog(const char *name, Int_t options, ELogFacility facility)
Open connection to system log daemon.
R__EXTERN TInterpreter * gCling
Definition: TInterpreter.h:519
Long_t fDev
Definition: TSystem.h:136
Ssiz_t Index(const char *pat, Ssiz_t i=0, ECaseCompare cmp=kExact) const
Definition: TString.h:582
virtual const char * GetSTLIncludePath() const
Definition: TInterpreter.h:137
UserGroup_t * GetUserInfo(Int_t uid)
Returns all user info in the UserGroup_t structure.
Abstract base class defining a generic interface to the underlying Operating System.
Definition: TSystem.h:258
const Bool_t kTRUE
Definition: Rtypes.h:91
float * q
Definition: THbookFile.cxx:87
Int_t fStdErrDup
Definition: TSystem.h:219
Ordered collection.
void DispatchSignals(ESignals sig)
Handle and dispatch signals.
int SendBuf(int sock, const void *buffer, int length)
Send a buffer headed by a length indicator.
TFdSet * fWritemask
Files that should be checked for read events.
Definition: TSystem.h:268
virtual char * ConcatFileName(const char *dir, const char *name)
Concatenate a directory and a file name. User must delete returned string.
Definition: TSystem.cxx:1045
#define sym(otri1, otri2)
Definition: triangle.c:932
void ListLibraries(const char *regexp="")
List all loaded shared libraries.
Float_t fIdle
Definition: TSystem.h:183
const char * WorkingDirectory()
Return working directory.
const Int_t n
Definition: legend1.C:16
TString fFile
Definition: TSystem.h:215
int Load(const char *module, const char *entry="", Bool_t system=kFALSE)
Load a shared library.
char name[80]
Definition: TGX11.cxx:109
Long_t fMemResident
Definition: TSystem.h:206
const char * cnt
Definition: TXMLSetup.cxx:75
Bool_t IsAsync() const
Definition: TTimer.h:87
void Setenv(const char *name, const char *value)
Set environment variable.
int OpenConnection(const char *server, int port, int tcpwindowsize=-1, const char *protocol="tcp")
Open a connection to a service on a server.
virtual Bool_t HasReadInterest()
True if handler is interested in read events.
int AnnounceUdpService(int port, int backlog)
Announce UDP service.
virtual void Warning(const char *method, const char *msgfmt,...) const
Issue warning message.
Definition: TObject.cxx:911