libzypp  13.10.6
Random.cc
Go to the documentation of this file.
1 #include <fcntl.h>
2 #include <unistd.h>
3 #include "zypp/base/Random.h"
4 
5 using namespace std;
6 
7 namespace zypp { namespace base {
8 
9  // Taken from KApplication
11 {
12  static bool init = false;
13  if (!init)
14  {
15  unsigned int seed;
16  init = true;
17  int fd = open("/dev/urandom", O_RDONLY|O_CLOEXEC);
18  if (fd < 0 || ::read(fd, &seed, sizeof(seed)) != sizeof(seed))
19  {
20  // No /dev/urandom... try something else.
21  srand(getpid());
22  seed = rand()+time(0);
23  }
24  if (fd >= 0) close(fd);
25  srand(seed);
26  }
27  return rand();
28 }
29 
30 // Taken from KApplication
31 std::string random_string(int length)
32 {
33  if (length <=0 ) return std::string();
34 
35  std::string str; str.resize( length );
36  int i = 0;
37  while (length--)
38  {
39  int r=::random() % 62;
40  r+=48;
41  if (r>57) r+=7;
42  if (r>90) r+=6;
43  str[i++] = char(r);
44  // so what if I work backwards?
45  }
46  return str;
47 }
48 
49 
50 } }
51 
map< string, string > read(const Pathname &_path)
Read sysconfig file path_r and return (key,valye) pairs.
Definition: Sysconfig.cc:34
int random_int()
Definition: Random.cc:10
std::string random_string(int length)
Definition: Random.cc:31
unsigned random()
Return a random number from [0,RAND_MAX[.
Definition: Random.h:28