libqi-api  2.8.7.4
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Pages
os.hpp
Go to the documentation of this file.
1 #pragma once
2 /*
3  * Copyright (c) 2012, 2013 Aldebaran Robotics. All rights reserved.
4  * Use of this source code is governed by a BSD-style license that can be
5  * found in the COPYING file.
6  */
7 
8 #ifndef _QI_OS_HPP_
9 # define _QI_OS_HPP_
10 
11 # include <cstdio>
12 # include <string>
13 # include <map>
14 # include <vector>
15 # include <csignal>
16 # include <type_traits>
17 # include <qi/api.hpp>
18 # include <qi/types.hpp>
19 # include <qi/path.hpp>
20 # include <qi/clock.hpp>
21 # include <qi/uuid.hpp>
22 # include <qi/ptruid.hpp>
23 
24 # include <boost/lexical_cast.hpp>
25 
26 #ifdef _WIN32
27 #ifndef SIGKILL
28 #define SIGKILL 9
29 #endif
30 #endif
31 
32 // `PTRDIFF_MIN` and `PTRDIFF_MAX` may not be defined on some platforms (e.g.
33 // android arm32). As a first step we define the values by hard-coding them, to
34 // avoid relying on another constant. This guarantees that it will work whatever
35 // the presence or absence of other constants (INT32_MAX, etc.).
36 //
37 // TODO: Remove this when alternatively
38 // - qibuild is modified to generate a libqi user CMakeLists.txt that defines
39 // correct constants (`#define __STDC_LIMIT_MACROS`)
40 // - Android NDK is upgraded to use at least Android API level 21.
41 //
42 // The following values are taken from the Android NDK file
43 // 'platforms/android-21/arch-arm/usr/include/stdint.h'.
44 #if !defined(PTRDIFF_MIN)
45 # if defined(__LP64__) && __LP64__
46 # define PTRDIFF_MIN -9223372036854775808LL
47 # else
48 # define PTRDIFF_MIN -2147483648
49 # endif
50 #endif
51 
52 #if !defined(PTRDIFF_MAX)
53 # if defined(__LP64__) && __LP64__
54 # define PTRDIFF_MAX 9223372036854775807LL
55 # else
56 # define PTRDIFF_MAX 2147483647
57 # endif
58 #endif
59 
60 struct stat;
61 
62 namespace qi {
63 
77  namespace os {
94  QI_API FILE* fopen(const char *filename, const char *mode);
111  QI_API int stat(const char *filename, struct stat *pstat);
116  QI_API int checkdbg();
121  QI_API std::string home();
137  QI_API std::string mktmpdir(const char *prefix = "");
145  QI_API std::string tmp();
149  QI_API void symlink(const qi::Path& source, const qi::Path& destination);
154  QI_API std::string gethostname();
165  QI_API int isatty(int fd = 1);
166 
170  QI_API bool fnmatch(const std::string &pattern, const std::string &string);
171 
172  // lib C
176  QI_API char* strdup(const char *src);
184  QI_API int snprintf(char *str, size_t size, const char *format, ...);
185 
199  QI_API std::string getenv(const char *var);
200 
209  QI_API std::string pathsep();
210 
225  QI_API int setenv(const char *var, const char *value);
226 
240  QI_API int unsetenv(const char *var);
241 
250  QI_API std::string timezone();
251 
252  // time
270  QI_API_DEPRECATED_MSG(please use std::this_thread::sleep_for instead)
271  QI_API void sleep(unsigned int seconds);
272 
287  QI_API_DEPRECATED_MSG(please use std::this_thread::sleep_for instead)
288  QI_API void msleep(unsigned int milliseconds);
289 
293  struct QI_API timeval {
296 
297  timeval() : tv_sec(0), tv_usec(0) {}
298  timeval(int64_t sec, int64_t usec) : tv_sec(sec), tv_usec(usec) {}
299  explicit timeval(int64_t usec);
300  explicit timeval(const qi::Duration &);
301  explicit timeval(const qi::SystemClockTimePoint &);
302  };
303 
330  QI_API std::pair<int64_t, int64_t> cputime();
331 
338  const qi::os::timeval &rhs);
345  long us);
352  const qi::os::timeval &rhs);
359  long us);
360 
380  QI_API void *dlopen(const char *filename, int flag = -1);
399  QI_API int dlclose(void *handle);
416  QI_API void *dlsym(void *handle, const char *symbol);
439  QI_API const char *dlerror();
440 
441  // process management
454  QI_API int spawnvp(char *const argv[]);
467  QI_API int spawnlp(const char* argv, ...);
481  QI_API int system(const char *command);
485  QI_API int getpid();
489  QI_API int gettid();
511  QI_API int waitpid(int pid, int* status);
531  QI_API int kill(int pid, int sig);
532 
543  QI_API bool isProcessRunning(int pid, const std::string& fileName = std::string());
544 
561  QI_API unsigned short findAvailablePort(unsigned short port);
571  QI_API std::map<std::string, std::vector<std::string> > hostIPAddrs(bool ipv6Addr = false);
572 
581  QI_API void setCurrentThreadName(const std::string &name);
587  QI_API std::string currentThreadName();
588 
589 
596  public:
597  ScopedThreadName(const std::string& newName) : _oldName(currentThreadName()) {
598  setCurrentThreadName(newName);
599  };
601  setCurrentThreadName(_oldName);
602  }
603  private:
604  std::string _oldName;
605  };
606 
607 
621  QI_API bool setCurrentThreadCPUAffinity(const std::vector<int> &cpus);
626  QI_API long numberOfCPUs();
635  QI_API std::string getMachineId();
639  QI_API const Uuid& getMachineIdAsUuid();
644  QI_API const Uuid& getProcessUuid();
650  QI_API std::string generateUuid();
657  QI_API size_t memoryUsage(unsigned int pid);
658 
661  QI_API PtrUid ptrUid(void* address);
662 
671  template <typename T>
672  inline T getEnvParam(const char* name, T defaultVal)
673  {
674  std::string sval = qi::os::getenv(name);
675  if (sval.empty())
676  return defaultVal;
677  else
678  return boost::lexical_cast<T>(sval);
679  }
680 
682  template<typename N>
683  std::string to_string(N n)
684  {
685  // Prevent the Android version to behave differently than other platforms.
686  // Enums are implicitly convertible to integral types, so we accept them.
687  static_assert(std::is_arithmetic<N>::value || std::is_enum<N>::value,
688  "to_string() accepts only arithmetic types (i.e. integral types and "
689  "floating-point types) and enum types.");
690 
691 #if BOOST_OS_ANDROID && BOOST_COMP_GNUC
692  // workaround android gcc missing std::to_string on arm
693  // http://stackoverflow.com/questions/17950814/how-to-use-stdstoul-and-stdstoull-in-android/18124627#18124627
694  std::ostringstream stream;
695  stream << n;
696  return stream.str();
697 #else
698  return std::to_string(n);
699 #endif
700  }
701  }
702 }
703 
704 #endif // _QI_OS_HPP_
qi::os::timeval operator-(const qi::os::timeval &lhs, const qi::os::timeval &rhs)
Substract two timeval together.
std::string getenv(const char *var)
Get an environment variable.
int gettid()
Get the thread identifier.
int64_t int64_t
Definition: types.hpp:61
timeval(int64_t sec, int64_t usec)
Definition: os.hpp:298
int spawnlp(const char *argv,...)
Create and execute a new process.
#define QI_API
Definition: api.hpp:33
Set the current thread name and restore it after use.
Definition: os.hpp:595
int stat(const char *filename, struct stat *pstat)
Get file status.
int setenv(const char *var, const char *value)
Change or add an environment variable.
bool isProcessRunning(int pid, const std::string &fileName=std::string())
Check whether a process is running, given its file name and pid.
int kill(int pid, int sig)
Send a signal to a process.
std::string generateUuid()
Generate a universally unique identifier.
T getEnvParam(const char *name, T defaultVal)
Returns the value of the environment variableif set, the defaultVal otherwise.
Definition: os.hpp:672
std::string timezone()
Return the timezone.
void msleep(unsigned int milliseconds)
Sleep for the specified number of milliseconds.
int spawnvp(char *const argv[])
Create and execute a new process.
std::pair< int64_t, int64_t > cputime()
Return CPU time used by the calling thread as a pair (userTime, systemTime) in microseconds.
void symlink(const qi::Path &source, const qi::Path &destination)
Create a symlink from source to destination.
int checkdbg()
Check if the current process is running into a debugger.
dll import/export and compiler message
const char * dlerror()
Returns a human readable string of the error code.
int unsetenv(const char *var)
Remove an environment variable.
std::string home()
Return path to the current user's HOME.
QI_API_DEPRECATED int gettimeofday(qi::os::timeval *tp)
The gettimeofday() function shall obtain the current time.
std::string currentThreadName()
returns the current thread name as a std::string
void * dlsym(void *handle, const char *symbol)
Get the address where the symbol is loaded into memory.
NanoSeconds Duration
Definition: clock.hpp:32
ScopedThreadName(const std::string &newName)
Definition: os.hpp:597
const Uuid & getMachineIdAsUuid()
Same as getMachineId but return a uuid and not its string representation.
void sleep(unsigned int seconds)
Sleep for the specified number of seconds.
std::string mktmpdir(const char *prefix="")
Return a writable temporary directory.
std::map< std::string, std::vector< std::string > > hostIPAddrs(bool ipv6Addr=false)
Find all network adapters and corresponding IPs.
bool fnmatch(const std::string &pattern, const std::string &string)
Implement POSIX compliant fnmatch.
SystemClock::time_point SystemClockTimePoint
System clock time point.
Definition: clock.hpp:213
bool setCurrentThreadCPUAffinity(const std::vector< int > &cpus)
Set the CPU affinity for the current thread.
qi::int64_t tv_sec
seconds
Definition: os.hpp:294
std::string tmp()
Return the system's temporary directory.
std::string gethostname()
Get the system's hostname.
long numberOfCPUs()
Get the number of CPUs on the local machin.
qi::int64_t tv_usec
microseconds
Definition: os.hpp:295
#define QI_API_DEPRECATED_MSG(msg__)
Compiler flags to mark a function as deprecated. It will generate a compiler warning.
Definition: macro.hpp:55
The Path class allow handling filesystem path in a cross-platform maner. <includename>qi/path.hpp</includename> The class assume that all string are encoded in UTF-8 if not specified otherwise.
Definition: path.hpp:34
int isatty(int fd=1)
Test if descriptor represents a terminal.
std::string getMachineId()
Returns an unique uuid for the machine.
qi::int64_t ustime()
Elapsed time since program started in microseconds.
struct similar to POSIX timeval
Definition: os.hpp:293
int dlclose(void *handle)
Decrements the reference count on the dynamic library.
std::string pathsep()
Get the path separator.
int waitpid(int pid, int *status)
Wait for process to change state.
size_t memoryUsage(unsigned int pid)
Get the memory usage of a process in kB.
boost::uuids::uuid Uuid
Definition: uuid.hpp:12
qi::os::timeval operator+(const qi::os::timeval &lhs, const qi::os::timeval &rhs)
Add two timeval together.
const Uuid & getProcessUuid()
Returns an unique uuid for the process.
T src(const std::atomic< T > &x)
Definition: atomic.hpp:318
FILE * fopen(const char *filename, const char *mode)
Open a file and returns and handle on it.
PtrUid ptrUid(void *address)
void setCurrentThreadName(const std::string &name)
Set the current thread name to the string in parameter.
int system(const char *command)
Execute a shell command.
std::string to_string(N n)
(Arithmetic or Enum) N
Definition: os.hpp:683
#define QI_API_DEPRECATED
Compiler flags to mark a function as deprecated. It will generate a compiler warning.
Definition: macro.hpp:41
int snprintf(char *str, size_t size, const char *format,...)
Implement POSIX compliant snprintf.
void * dlopen(const char *filename, int flag=-1)
Load a dynamic library.
int getpid()
Get the process identifier.
char * strdup(const char *src)
Implement POSIX compliant strdup.
unsigned short findAvailablePort(unsigned short port)
Find the first available port starting at port number in parameter.