POSIX.C
Go to the documentation of this file.
1 /*---------------------------------------------------------------------------*\
2  ========= |
3  \\ / F ield | OpenFOAM: The Open Source CFD Toolbox
4  \\ / O peration |
5  \\ / A nd | Copyright (C) 2011-2015 OpenFOAM Foundation
6  \\/ M anipulation |
7 -------------------------------------------------------------------------------
8 License
9  This file is part of OpenFOAM.
10 
11  OpenFOAM is free software: you can redistribute it and/or modify it
12  under the terms of the GNU General Public License as published by
13  the Free Software Foundation, either version 3 of the License, or
14  (at your option) any later version.
15 
16  OpenFOAM is distributed in the hope that it will be useful, but WITHOUT
17  ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
18  FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
19  for more details.
20 
21  You should have received a copy of the GNU General Public License
22  along with OpenFOAM. If not, see <http://www.gnu.org/licenses/>.
23 
24 Description
25  POSIX versions of the functions declared in OSspecific.H
26 
27 \*---------------------------------------------------------------------------*/
28 
29 #ifdef solarisGcc
30 # define _SYS_VNODE_H
31 #endif
32 
33 #include "OSspecific.H"
34 #include "POSIX.H"
35 #include "foamVersion.H"
36 #include "fileName.H"
37 #include "fileStat.H"
38 #include "timer.H"
39 #include "IFstream.H"
40 #include "DynamicList.H"
41 
42 #include <fstream>
43 #include <cstdlib>
44 #include <cctype>
45 
46 #include <stdio.h>
47 #include <unistd.h>
48 #include <dirent.h>
49 #include <pwd.h>
50 #include <errno.h>
51 #include <sys/types.h>
52 #include <sys/stat.h>
53 #include <sys/socket.h>
54 #include <netdb.h>
55 #include <dlfcn.h>
56 
57 #include <netinet/in.h>
58 
59 #ifdef USE_RANDOM
60 # include <climits>
61 # if INT_MAX != 2147483647
62 # error "INT_MAX != 2147483647"
63 # error "The random number generator may not work!"
64 # endif
65 #endif
66 
67 // * * * * * * * * * * * * * * Static Data Members * * * * * * * * * * * * * //
68 
69 namespace Foam
70 {
71  defineTypeNameAndDebug(POSIX, 0);
72 }
73 
74 
75 // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
76 
78 {
79  return ::getpid();
80 }
81 
82 
84 {
85  return ::getppid();
86 }
87 
88 
90 {
91  return ::getpgrp();
92 }
93 
94 
95 bool Foam::env(const word& envName)
96 {
97  return ::getenv(envName.c_str()) != NULL;
98 }
99 
100 
102 {
103  char* env = ::getenv(envName.c_str());
104 
105  if (env)
106  {
107  return string(env);
108  }
109  else
110  {
111  // Return null-constructed string rather than string::null
112  // to avoid cyclic dependencies in the construction of globals
113  return string();
114  }
115 }
116 
117 
118 bool Foam::setEnv
119 (
120  const word& envName,
121  const std::string& value,
122  const bool overwrite
123 )
124 {
125  return setenv(envName.c_str(), value.c_str(), overwrite) == 0;
126 }
127 
128 
130 {
131  char buf[128];
132  ::gethostname(buf, sizeof(buf));
133 
134  // implementation as per hostname from net-tools
135  if (full)
136  {
137  struct hostent *hp = ::gethostbyname(buf);
138  if (hp)
139  {
140  return hp->h_name;
141  }
142  }
143 
144  return buf;
145 }
146 
147 
149 {
150  char buf[128];
151  ::gethostname(buf, sizeof(buf));
152 
153  // implementation as per hostname from net-tools
154  struct hostent *hp = ::gethostbyname(buf);
155  if (hp)
156  {
157  char *p = ::strchr(hp->h_name, '.');
158  if (p)
159  {
160  ++p;
161  return p;
162  }
163  }
164 
165  return string::null;
166 }
167 
168 
170 {
171  struct passwd* pw = ::getpwuid(::getuid());
172 
173  if (pw != NULL)
174  {
175  return pw->pw_name;
176  }
177  else
178  {
179  return string::null;
180  }
181 }
182 
183 
185 {
186  return (::geteuid() == 0);
187 }
188 
189 
190 // use $HOME environment variable or passwd info
192 {
193  char* env = ::getenv("HOME");
194 
195  if (env != NULL)
196  {
197  return fileName(env);
198  }
199  else
200  {
201  struct passwd* pw = ::getpwuid(getuid());
202 
203  if (pw != NULL)
204  {
205  return pw->pw_dir;
206  }
207  else
208  {
209  return fileName::null;
210  }
211  }
212 }
213 
214 
216 {
217  struct passwd* pw;
218 
219  if (userName.size())
220  {
221  pw = ::getpwnam(userName.c_str());
222  }
223  else
224  {
225  char* env = ::getenv("HOME");
226 
227  if (env != NULL)
228  {
229  return fileName(env);
230  }
231 
232  pw = ::getpwuid(::getuid());
233  }
234 
235  if (pw != NULL)
236  {
237  return pw->pw_dir;
238  }
239  else
240  {
241  return fileName::null;
242  }
243 }
244 
245 
247 {
248  char buf[256];
249  if (::getcwd(buf, sizeof(buf)))
250  {
251  return buf;
252  }
253  else
254  {
256  << "Couldn't get the current working directory"
257  << exit(FatalError);
258 
259  return fileName::null;
260  }
261 }
262 
263 
264 bool Foam::chDir(const fileName& dir)
265 {
266  return ::chdir(dir.c_str()) == 0;
267 }
268 
269 
271 (
272  const fileName& name,
273  bool mandatory,
274  bool findFirst
275 )
276 {
277  fileNameList results;
278 
279  // Search for user files in
280  // * ~/.OpenFOAM/VERSION
281  // * ~/.OpenFOAM
282  //
283  fileName searchDir = home()/".OpenFOAM";
284  if (isDir(searchDir))
285  {
286  fileName fullName = searchDir/FOAMversion/name;
287  if (isFile(fullName))
288  {
289  results.append(fullName);
290  if (findFirst)
291  {
292  return results;
293  }
294  }
295 
296  fullName = searchDir/name;
297  if (isFile(fullName))
298  {
299  results.append(fullName);
300  if (findFirst)
301  {
302  return results;
303  }
304  }
305  }
306 
307  // Search for group (site) files in
308  // * $WM_PROJECT_SITE/VERSION
309  // * $WM_PROJECT_SITE
310  //
311  searchDir = getEnv("WM_PROJECT_SITE");
312  if (searchDir.size())
313  {
314  if (isDir(searchDir))
315  {
316  fileName fullName = searchDir/FOAMversion/name;
317  if (isFile(fullName))
318  {
319  results.append(fullName);
320  if (findFirst)
321  {
322  return results;
323  }
324  }
325 
326  fullName = searchDir/name;
327  if (isFile(fullName))
328  {
329  results.append(fullName);
330  if (findFirst)
331  {
332  return results;
333  }
334  }
335  }
336  }
337  else
338  {
339  // OR search for group (site) files in
340  // * $WM_PROJECT_INST_DIR/site/VERSION
341  // * $WM_PROJECT_INST_DIR/site
342  //
343  searchDir = getEnv("WM_PROJECT_INST_DIR");
344  if (isDir(searchDir))
345  {
346  fileName fullName = searchDir/"site"/FOAMversion/name;
347  if (isFile(fullName))
348  {
349  results.append(fullName);
350  if (findFirst)
351  {
352  return results;
353  }
354  }
355 
356  fullName = searchDir/"site"/name;
357  if (isFile(fullName))
358  {
359  results.append(fullName);
360  if (findFirst)
361  {
362  return results;
363  }
364  }
365  }
366  }
367 
368  // Search for other (shipped) files in
369  // * $WM_PROJECT_DIR/etc
370  //
371  searchDir = getEnv("WM_PROJECT_DIR");
372  if (isDir(searchDir))
373  {
374  fileName fullName = searchDir/"etc"/name;
375  if (isFile(fullName))
376  {
377  results.append(fullName);
378  if (findFirst)
379  {
380  return results;
381  }
382  }
383  }
384 
385  // Not found
386  if (results.empty())
387  {
388  // Abort if the file is mandatory, otherwise return null
389  if (mandatory)
390  {
391  std::cerr
392  << "--> FOAM FATAL ERROR in Foam::findEtcFiles() :"
393  " could not find mandatory file\n '"
394  << name.c_str() << "'\n\n" << std::endl;
395  ::exit(1);
396  }
397  }
398 
399  // Return list of matching paths or empty list if none found
400  return results;
401 }
402 
403 
405 {
406  fileNameList results(findEtcFiles(name, mandatory, true));
407 
408  if (results.size())
409  {
410  return results[0];
411  }
412  else
413  {
414  return fileName();
415  }
416 }
417 
418 
419 bool Foam::mkDir(const fileName& pathName, mode_t mode)
420 {
421  // empty names are meaningless
422  if (pathName.empty())
423  {
424  return false;
425  }
426 
427  // Construct instance path directory if does not exist
428  if (::mkdir(pathName.c_str(), mode) == 0)
429  {
430  // Directory made OK so return true
431  return true;
432  }
433  else
434  {
435  switch (errno)
436  {
437  case EPERM:
438  {
440  << "The filesystem containing " << pathName
441  << " does not support the creation of directories."
442  << exit(FatalError);
443 
444  return false;
445  }
446 
447  case EEXIST:
448  {
449  // Directory already exists so simply return true
450  return true;
451  }
452 
453  case EFAULT:
454  {
456  << "" << pathName
457  << " points outside your accessible address space."
458  << exit(FatalError);
459 
460  return false;
461  }
462 
463  case EACCES:
464  {
466  << "The parent directory does not allow write "
467  "permission to the process,"<< nl
468  << "or one of the directories in " << pathName
469  << " did not allow search (execute) permission."
470  << exit(FatalError);
471 
472  return false;
473  }
474 
475  case ENAMETOOLONG:
476  {
478  << "" << pathName << " is too long."
479  << exit(FatalError);
480 
481  return false;
482  }
483 
484  case ENOENT:
485  {
486  // Part of the path does not exist so try to create it
487  if (pathName.path().size() && mkDir(pathName.path(), mode))
488  {
489  return mkDir(pathName, mode);
490  }
491  else
492  {
494  << "Couldn't create directory " << pathName
495  << exit(FatalError);
496 
497  return false;
498  }
499  }
500 
501  case ENOTDIR:
502  {
504  << "A component used as a directory in " << pathName
505  << " is not, in fact, a directory."
506  << exit(FatalError);
507 
508  return false;
509  }
510 
511  case ENOMEM:
512  {
514  << "Insufficient kernel memory was available to make "
515  "directory " << pathName << '.'
516  << exit(FatalError);
517 
518  return false;
519  }
520 
521  case EROFS:
522  {
524  << "" << pathName
525  << " refers to a file on a read-only filesystem."
526  << exit(FatalError);
527 
528  return false;
529  }
530 
531  case ELOOP:
532  {
534  << "Too many symbolic links were encountered in resolving "
535  << pathName << '.'
536  << exit(FatalError);
537 
538  return false;
539  }
540 
541  case ENOSPC:
542  {
544  << "The device containing " << pathName
545  << " has no room for the new directory or "
546  << "the user's disk quota is exhausted."
547  << exit(FatalError);
548 
549  return false;
550  }
551 
552  default:
553  {
555  << "Couldn't create directory " << pathName
556  << exit(FatalError);
557 
558  return false;
559  }
560  }
561  }
562 }
563 
564 
565 // Set the file mode
566 bool Foam::chMod(const fileName& name, const mode_t m)
567 {
568  return ::chmod(name.c_str(), m) == 0;
569 }
570 
571 
572 // Return the file mode
573 mode_t Foam::mode(const fileName& name)
574 {
575  fileStat fileStatus(name);
576  if (fileStatus.isValid())
577  {
578  return fileStatus.status().st_mode;
579  }
580  else
581  {
582  return 0;
583  }
584 }
585 
586 
587 // Return the file type: FILE or DIRECTORY
589 {
590  mode_t m = mode(name);
591 
592  if (S_ISREG(m))
593  {
594  return fileName::FILE;
595  }
596  else if (S_ISDIR(m))
597  {
598  return fileName::DIRECTORY;
599  }
600  else
601  {
602  return fileName::UNDEFINED;
603  }
604 }
605 
606 
607 // Does the name exist in the filing system?
608 bool Foam::exists(const fileName& name, const bool checkGzip)
609 {
610  return mode(name) || isFile(name, checkGzip);
611 }
612 
613 
614 // Does the directory exist?
616 {
617  return S_ISDIR(mode(name));
618 }
619 
620 
621 // Does the file exist?
622 bool Foam::isFile(const fileName& name, const bool checkGzip)
623 {
624  return S_ISREG(mode(name)) || (checkGzip && S_ISREG(mode(name + ".gz")));
625 }
626 
627 
628 // Return size of file
630 {
631  fileStat fileStatus(name);
632  if (fileStatus.isValid())
633  {
634  return fileStatus.status().st_size;
635  }
636  else
637  {
638  return -1;
639  }
640 }
641 
642 
643 // Return time of last file modification
645 {
646  fileStat fileStatus(name);
647  if (fileStatus.isValid())
648  {
649  return fileStatus.status().st_mtime;
650  }
651  else
652  {
653  return 0;
654  }
655 }
656 
657 
658 // Read a directory and return the entries as a string list
660 (
661  const fileName& directory,
662  const fileName::Type type,
663  const bool filtergz
664 )
665 {
666  // Initial filename list size
667  // also used as increment if initial size found to be insufficient
668  static const int maxNnames = 100;
669 
670  if (POSIX::debug)
671  {
672  Info<< "readDir(const fileName&, const fileType, const bool filtergz)"
673  << " : reading directory " << directory << endl;
674  }
675 
676  // Setup empty string list MAXTVALUES long
677  fileNameList dirEntries(maxNnames);
678 
679  // Pointers to the directory entries
680  DIR *source;
681  struct dirent *list;
682 
683  // Temporary variables and counters
684  label nEntries = 0;
685 
686  // Attempt to open directory and set the structure pointer
687  if ((source = ::opendir(directory.c_str())) == NULL)
688  {
689  dirEntries.setSize(0);
690 
691  if (POSIX::debug)
692  {
693  Info<< "readDir(const fileName&, const fileType, "
694  "const bool filtergz) : cannot open directory "
695  << directory << endl;
696  }
697  }
698  else
699  {
700  // Read and parse all the entries in the directory
701  while ((list = ::readdir(source)) != NULL)
702  {
703  fileName fName(list->d_name);
704 
705  // ignore files begining with ., i.e. '.', '..' and '.*'
706  if (fName.size() && fName[0] != '.')
707  {
708  word fExt = fName.ext();
709 
710  if
711  (
712  (type == fileName::DIRECTORY)
713  ||
714  (
715  type == fileName::FILE
716  && fName[fName.size()-1] != '~'
717  && fExt != "bak"
718  && fExt != "BAK"
719  && fExt != "old"
720  && fExt != "save"
721  )
722  )
723  {
724  if ((directory/fName).type() == type)
725  {
726  if (nEntries >= dirEntries.size())
727  {
728  dirEntries.setSize(dirEntries.size() + maxNnames);
729  }
730 
731  if (filtergz && fExt == "gz")
732  {
733  dirEntries[nEntries++] = fName.lessExt();
734  }
735  else
736  {
737  dirEntries[nEntries++] = fName;
738  }
739  }
740  }
741  }
742  }
743 
744  // Reset the length of the entries list
745  dirEntries.setSize(nEntries);
746 
747  ::closedir(source);
748  }
749 
750  return dirEntries;
751 }
752 
753 
754 // Copy, recursively if necessary, the source to the destination
755 bool Foam::cp(const fileName& src, const fileName& dest)
756 {
757  // Make sure source exists.
758  if (!exists(src))
759  {
760  return false;
761  }
762 
763  fileName destFile(dest);
764 
765  // Check type of source file.
766  if (src.type() == fileName::FILE)
767  {
768  // If dest is a directory, create the destination file name.
769  if (destFile.type() == fileName::DIRECTORY)
770  {
771  destFile = destFile/src.name();
772  }
773 
774  // Make sure the destination directory exists.
775  if (!isDir(destFile.path()) && !mkDir(destFile.path()))
776  {
777  return false;
778  }
779 
780  // Open and check streams.
781  std::ifstream srcStream(src.c_str());
782  if (!srcStream)
783  {
784  return false;
785  }
786 
787  std::ofstream destStream(destFile.c_str());
788  if (!destStream)
789  {
790  return false;
791  }
792 
793  // Copy character data.
794  char ch;
795  while (srcStream.get(ch))
796  {
797  destStream.put(ch);
798  }
799 
800  // Final check.
801  if (!srcStream.eof() || !destStream)
802  {
803  return false;
804  }
805  }
806  else if (src.type() == fileName::DIRECTORY)
807  {
808  // If dest is a directory, create the destination file name.
809  if (destFile.type() == fileName::DIRECTORY)
810  {
811  destFile = destFile/src.component(src.components().size() -1);
812  }
813 
814  // Make sure the destination directory exists.
815  if (!isDir(destFile) && !mkDir(destFile))
816  {
817  return false;
818  }
819 
820  // Copy files
821  fileNameList contents = readDir(src, fileName::FILE, false);
822  forAll(contents, i)
823  {
824  if (POSIX::debug)
825  {
826  Info<< "Copying : " << src/contents[i]
827  << " to " << destFile/contents[i] << endl;
828  }
829 
830  // File to file.
831  cp(src/contents[i], destFile/contents[i]);
832  }
833 
834  // Copy sub directories.
835  fileNameList subdirs = readDir(src, fileName::DIRECTORY);
836  forAll(subdirs, i)
837  {
838  if (POSIX::debug)
839  {
840  Info<< "Copying : " << src/subdirs[i]
841  << " to " << destFile << endl;
842  }
843 
844  // Dir to Dir.
845  cp(src/subdirs[i], destFile);
846  }
847  }
848 
849  return true;
850 }
851 
852 
853 // Create a softlink. dst should not exist. Returns true if successful.
854 bool Foam::ln(const fileName& src, const fileName& dst)
855 {
856  if (POSIX::debug)
857  {
858  Info<< "Create softlink from : " << src << " to " << dst
859  << endl;
860  }
861 
862  if (exists(dst))
863  {
865  << "destination " << dst << " already exists. Not linking."
866  << endl;
867  return false;
868  }
869 
870  if (src.isAbsolute() && !exists(src))
871  {
873  << "source " << src << " does not exist." << endl;
874  return false;
875  }
876 
877  if (::symlink(src.c_str(), dst.c_str()) == 0)
878  {
879  return true;
880  }
881  else
882  {
884  << "symlink from " << src << " to " << dst << " failed." << endl;
885  return false;
886  }
887 }
888 
889 
890 // Rename srcFile dstFile
891 bool Foam::mv(const fileName& src, const fileName& dst)
892 {
893  if (POSIX::debug)
894  {
895  Info<< "Move : " << src << " to " << dst << endl;
896  }
897 
898  if
899  (
900  dst.type() == fileName::DIRECTORY
901  && src.type() != fileName::DIRECTORY
902  )
903  {
904  const fileName dstName(dst/src.name());
905 
906  return ::rename(src.c_str(), dstName.c_str()) == 0;
907  }
908  else
909  {
910  return ::rename(src.c_str(), dst.c_str()) == 0;
911  }
912 }
913 
914 
915 //- Rename to a corresponding backup file
916 // If the backup file already exists, attempt with "01" .. "99" index
917 bool Foam::mvBak(const fileName& src, const std::string& ext)
918 {
919  if (POSIX::debug)
920  {
921  Info<< "mvBak : " << src << " to extension " << ext << endl;
922  }
923 
924  if (exists(src, false))
925  {
926  const int maxIndex = 99;
927  char index[3];
928 
929  for (int n = 0; n <= maxIndex; n++)
930  {
931  fileName dstName(src + "." + ext);
932  if (n)
933  {
934  sprintf(index, "%02d", n);
935  dstName += index;
936  }
937 
938  // avoid overwriting existing files, except for the last
939  // possible index where we have no choice
940  if (!exists(dstName, false) || n == maxIndex)
941  {
942  return ::rename(src.c_str(), dstName.c_str()) == 0;
943  }
944 
945  }
946  }
947 
948  // fall-through: nothing to do
949  return false;
950 }
951 
952 
953 // Remove a file, returning true if successful otherwise false
954 bool Foam::rm(const fileName& file)
955 {
956  if (POSIX::debug)
957  {
958  Info<< "Removing : " << file << endl;
959  }
960 
961  // Try returning plain file name; if not there, try with .gz
962  if (remove(file.c_str()) == 0)
963  {
964  return true;
965  }
966  else
967  {
968  return ::remove(string(file + ".gz").c_str()) == 0;
969  }
970 }
971 
972 
973 // Remove a dirctory and its contents
974 bool Foam::rmDir(const fileName& directory)
975 {
976  if (POSIX::debug)
977  {
978  Info<< "rmDir(const fileName&) : "
979  << "removing directory " << directory << endl;
980  }
981 
982  // Pointers to the directory entries
983  DIR *source;
984  struct dirent *list;
985 
986  // Attempt to open directory and set the structure pointer
987  if ((source = ::opendir(directory.c_str())) == NULL)
988  {
990  << "cannot open directory " << directory << endl;
991 
992  return false;
993  }
994  else
995  {
996  // Read and parse all the entries in the directory
997  while ((list = ::readdir(source)) != NULL)
998  {
999  fileName fName(list->d_name);
1000 
1001  if (fName != "." && fName != "..")
1002  {
1003  fileName path = directory/fName;
1004 
1005  if (path.type() == fileName::DIRECTORY)
1006  {
1007  if (!rmDir(path))
1008  {
1010  << "failed to remove directory " << fName
1011  << " while removing directory " << directory
1012  << endl;
1013 
1014  ::closedir(source);
1015 
1016  return false;
1017  }
1018  }
1019  else
1020  {
1021  if (!rm(path))
1022  {
1024  << "failed to remove file " << fName
1025  << " while removing directory " << directory
1026  << endl;
1027 
1028  ::closedir(source);
1029 
1030  return false;
1031  }
1032  }
1033  }
1034 
1035  }
1036 
1037  if (!rm(directory))
1038  {
1040  << "failed to remove directory " << directory << endl;
1041 
1042  ::closedir(source);
1043 
1044  return false;
1045  }
1046 
1047  ::closedir(source);
1048 
1049  return true;
1050  }
1051 }
1052 
1053 
1054 unsigned int Foam::sleep(const unsigned int s)
1055 {
1056  return ::sleep(s);
1057 }
1058 
1059 
1060 void Foam::fdClose(const int fd)
1061 {
1062  if (close(fd) != 0)
1063  {
1065  << "close error on " << fd << endl
1066  << abort(FatalError);
1067  }
1068 }
1069 
1070 
1071 bool Foam::ping
1073  const string& destName,
1074  const label destPort,
1075  const label timeOut
1076 )
1077 {
1078  struct hostent *hostPtr;
1079  volatile int sockfd;
1080  struct sockaddr_in destAddr; // will hold the destination addr
1081  u_int addr;
1082 
1083  if ((hostPtr = ::gethostbyname(destName.c_str())) == NULL)
1084  {
1086  << "gethostbyname error " << h_errno << " for host " << destName
1087  << abort(FatalError);
1088  }
1089 
1090  // Get first of the SLL of addresses
1091  addr = (reinterpret_cast<struct in_addr*>(*(hostPtr->h_addr_list)))->s_addr;
1092 
1093  // Allocate socket
1094  sockfd = ::socket(AF_INET, SOCK_STREAM, 0);
1095  if (sockfd < 0)
1096  {
1098  << "socket error"
1099  << abort(FatalError);
1100  }
1101 
1102  // Fill sockaddr_in structure with dest address and port
1103  memset(reinterpret_cast<char *>(&destAddr), '\0', sizeof(destAddr));
1104  destAddr.sin_family = AF_INET;
1105  destAddr.sin_port = htons(ushort(destPort));
1106  destAddr.sin_addr.s_addr = addr;
1107 
1108 
1109  timer myTimer(timeOut);
1110 
1111  if (timedOut(myTimer))
1112  {
1113  // Setjmp from timer jumps back to here
1114  fdClose(sockfd);
1115  return false;
1116  }
1117 
1118  if
1119  (
1120  ::connect
1121  (
1122  sockfd,
1123  reinterpret_cast<struct sockaddr*>(&destAddr),
1124  sizeof(struct sockaddr)
1125  ) != 0
1126  )
1127  {
1128  // Connection refused. Check if network was actually used or not.
1129 
1130  int connectErr = errno;
1131 
1132  fdClose(sockfd);
1133 
1134  if (connectErr == ECONNREFUSED)
1135  {
1136  return true;
1137  }
1138  //perror("connect");
1139 
1140  return false;
1141  }
1142 
1143  fdClose(sockfd);
1144 
1145  return true;
1146 }
1147 
1148 
1149 bool Foam::ping(const string& hostname, const label timeOut)
1150 {
1151  return ping(hostname, 222, timeOut) || ping(hostname, 22, timeOut);
1152 }
1153 
1154 
1155 int Foam::system(const std::string& command)
1156 {
1157  return ::system(command.c_str());
1158 }
1159 
1160 
1161 void* Foam::dlOpen(const fileName& libName, const bool check)
1162 {
1163  if (POSIX::debug)
1164  {
1165  std::cout<< "dlOpen(const fileName&)"
1166  << " : dlopen of " << libName << std::endl;
1167  }
1168 
1169  Foam::string unixLibName(libName);
1170  char const * const soExt = ".so";
1171 
1172 #ifdef DARWIN
1173  char const * const unixExt = ".dylib";
1174  unixLibName.replace(soExt, unixExt);
1175 #else
1176  char const * const unixExt = soExt;
1177 #endif
1178 
1179  // Assume libName is of the form, lib<name>.so
1180  void* handle = ::dlopen(unixLibName.c_str(), RTLD_LAZY|RTLD_GLOBAL);
1181 
1182  if (NULL == handle)
1183  {
1184  // Try assuming libName = name
1185  unixLibName = "lib";
1186  unixLibName += libName;
1187  unixLibName += unixExt;
1188 
1189  handle =
1190  ::dlopen(unixLibName.c_str(), RTLD_LAZY|RTLD_GLOBAL);
1191  }
1192 
1193  if (!handle && check)
1194  {
1196  << "dlopen error : " << ::dlerror()
1197  << endl;
1198  }
1199 
1200  if (POSIX::debug)
1201  {
1202  std::cout
1203  << "dlOpen(const fileName&)"
1204  << " : dlopen of " << libName
1205  << " handle " << handle << std::endl;
1206  }
1207 
1208  return handle;
1209 }
1210 
1211 
1212 bool Foam::dlClose(void* handle)
1213 {
1214  if (POSIX::debug)
1215  {
1216  std::cout
1217  << "dlClose(void*)"
1218  << " : dlclose of handle " << handle << std::endl;
1219  }
1220  return ::dlclose(handle) == 0;
1221 }
1222 
1223 
1224 void* Foam::dlSym(void* handle, const std::string& symbol)
1225 {
1226  if (POSIX::debug)
1227  {
1228  std::cout
1229  << "dlSym(void*, const std::string&)"
1230  << " : dlsym of " << symbol << std::endl;
1231  }
1232  // clear any old errors - see manpage dlopen
1233  (void) ::dlerror();
1234 
1235  // get address of symbol
1236  void* fun = ::dlsym(handle, symbol.c_str());
1237 
1238  // find error (if any)
1239  char *error = ::dlerror();
1240 
1241  if (error)
1242  {
1244  << "Cannot lookup symbol " << symbol << " : " << error
1245  << endl;
1246  }
1247 
1248  return fun;
1249 }
1250 
1251 
1252 bool Foam::dlSymFound(void* handle, const std::string& symbol)
1253 {
1254  if (handle && !symbol.empty())
1255  {
1256  if (POSIX::debug)
1257  {
1258  std::cout
1259  << "dlSymFound(void*, const std::string&)"
1260  << " : dlsym of " << symbol << std::endl;
1261  }
1262 
1263  // clear any old errors - see manpage dlopen
1264  (void) ::dlerror();
1265 
1266  // get address of symbol
1267  (void) ::dlsym(handle, symbol.c_str());
1268 
1269  // symbol can be found if there was no error
1270  return !::dlerror();
1271  }
1272  else
1273  {
1274  return false;
1275  }
1276 }
1277 
1278 
1279 #ifdef DARWIN
1280 
1282 {
1283  DynamicList<fileName> libs;
1284  return libs;
1285 }
1286 
1287 #else
1288 
1289 #include <link.h>
1290 
1291 static int collectLibsCallback
1293  struct dl_phdr_info *info,
1294  size_t size,
1295  void *data
1296 )
1297 {
1299  reinterpret_cast<Foam::DynamicList<Foam::fileName>*>(data);
1300  ptr->append(info->dlpi_name);
1301  return 0;
1302 }
1303 
1304 
1306 {
1307  DynamicList<fileName> libs;
1308  dl_iterate_phdr(collectLibsCallback, &libs);
1309  if (POSIX::debug)
1310  {
1311  std::cout
1312  << "dlLoaded()"
1313  << " : determined loaded libraries :" << libs.size() << std::endl;
1314  }
1315  return libs;
1316 }
1317 
1318 #endif // not DARWIN
1319 
1320 
1321 void Foam::osRandomSeed(const label seed)
1322 {
1323 #ifdef USE_RANDOM
1324  srandom((unsigned int)seed);
1325 #else
1326  srand48(seed);
1327 #endif
1328 }
1329 
1330 
1332 {
1333 #ifdef USE_RANDOM
1334  return random();
1335 #else
1336  return lrand48();
1337 #endif
1338 }
1339 
1340 
1341 Foam::scalar Foam::osRandomDouble()
1342 {
1343 #ifdef USE_RANDOM
1344  return (scalar)random()/INT_MAX;
1345 #else
1346  return drand48();
1347 #endif
1348 }
1349 
1350 
1351 std::string Foam::toUnixPath(const std::string & path)
1352 {
1353  return path;
1354 }
1355 
1356 
1357 // ************************************************************************* //
Foam::osRandomInteger
label osRandomInteger()
Return random integer (uniform distribution between 0 and 2^31)
Definition: POSIX.C:1331
Foam::domainName
string domainName()
Return the system's domain name, as per hostname(1) with the '-d' option.
Definition: POSIX.C:148
Foam::findEtcFile
fileName findEtcFile(const fileName &, bool mandatory=false)
Search for a file using findEtcFiles.
Definition: POSIX.C:404
Foam::env
bool env(const word &)
Return true if environment variable of given name is defined.
Definition: POSIX.C:95
OSspecific.H
Functions used by OpenFOAM that are specific to POSIX compliant operating systems and need to be repl...
Foam::ppid
PID_T ppid()
Return the parent PID of this process.
Definition: POSIX.C:83
p
p
Definition: pEqn.H:62
Foam::word
A class for handling words, derived from string.
Definition: word.H:59
Foam::fileName
A class for handling file names.
Definition: fileName.H:69
Foam::exists
bool exists(const fileName &, const bool checkGzip=true)
Does the name exist (as DIRECTORY or FILE) in the file system?
Definition: POSIX.C:608
forAll
#define forAll(list, i)
Loop across all elements in list.
Definition: UList.H:406
Foam::dlSym
void * dlSym(void *handle, const std::string &symbol)
Lookup a symbol in a dlopened library using handle to library.
Definition: POSIX.C:1224
Foam::DynamicList< Foam::fileName >
Foam::rm
bool rm(const fileName &)
Remove a file, returning true if successful otherwise false.
Definition: POSIX.C:954
Foam::fileName::components
wordList components(const char delimiter='/') const
Return path components as wordList.
Definition: fileName.C:357
Foam::fileName::path
fileName path() const
Return directory path name (part before last /)
Definition: fileName.C:293
Foam::fdClose
void fdClose(const int)
Close file descriptor.
Definition: POSIX.C:1060
Foam::fileName::isAbsolute
bool isAbsolute() const
Return true if file name is absolute.
Definition: fileName.C:57
Foam::fileStat::isValid
bool isValid() const
Did constructor fail.
Definition: fileStat.H:99
Foam::fileName::Type
Type
Enumerations to handle file types and modes.
Definition: fileName.H:82
Foam::fileStat
Wrapper for stat() system call.
Definition: fileStat.H:65
Foam::lastModified
time_t lastModified(const fileName &)
Return time of last file modification.
Definition: POSIX.C:644
random
scalar random
Definition: TABSMDCalcMethod1.H:3
Foam::endl
Ostream & endl(Ostream &os)
Add newline and flush stream.
Definition: Ostream.H:251
Foam::setEnv
bool setEnv(const word &name, const std::string &value, const bool overwrite)
Set an environment variable.
Definition: POSIX.C:119
Foam::fileName::lessExt
fileName lessExt() const
Return file name without extension (part before last .)
Definition: fileName.C:313
Foam::string
A class for handling character strings derived from std::string.
Definition: string.H:74
Foam::ping
bool ping(const string &, const label port, const label timeOut)
Check if machine is up by pinging given port.
Definition: POSIX.C:1072
Foam::osRandomSeed
void osRandomSeed(const label seed)
Seed random number generator.
Definition: POSIX.C:1321
Foam::cp
bool cp(const fileName &src, const fileName &dst)
Copy, recursively if necessary, the source to the destination.
Definition: POSIX.C:755
Foam::dlSymFound
bool dlSymFound(void *handle, const std::string &symbol)
Report if symbol in a dlopened library could be found.
Definition: POSIX.C:1252
Foam::sleep
unsigned int sleep(const unsigned int)
Sleep for the specified number of seconds.
Definition: POSIX.C:1054
Foam::mv
bool mv(const fileName &src, const fileName &dst)
Rename src to dst.
Definition: POSIX.C:891
Foam::mode
mode_t mode(const fileName &)
Return the file mode.
Definition: POSIX.C:573
Foam::chMod
bool chMod(const fileName &, const mode_t)
Set the file mode.
Definition: POSIX.C:566
Foam::fileName::name
word name() const
Return file name (part beyond last /)
Definition: fileName.C:212
Foam::fileName::component
word component(const size_type, const char delimiter='/') const
Return a single component of the path.
Definition: fileName.C:386
Foam::isAdministrator
bool isAdministrator()
Is user administrator.
Definition: POSIX.C:184
fileStat.H
n
label n
Definition: TABSMDCalcMethod2.H:31
Foam::toUnixPath
std::string toUnixPath(const std::string &path)
Convert to unix path separators.
Definition: POSIX.C:1351
Foam::userName
string userName()
Return the user's login name.
Definition: POSIX.C:169
Foam::pid
PID_T pid()
Return the PID of this process.
Definition: POSIX.C:77
Foam::fileName::type
Type type() const
Return the file type: FILE, DIRECTORY or UNDEFINED.
Definition: fileName.C:51
Foam::getEnv
string getEnv(const word &)
Return environment variable of given name.
Definition: POSIX.C:101
Foam::label
intWM_LABEL_SIZE_t label
A label is an int32_t or int64_t as specified by the pre-processor macro WM_LABEL_SIZE.
Definition: label.H:59
Foam::List::append
void append(const T &)
Append an element at the end of the list.
Foam::nl
static const char nl
Definition: Ostream.H:260
Foam::Info
messageStream Info
POSIX.H
Foam::mvBak
bool mvBak(const fileName &, const std::string &ext="bak")
Rename to a corresponding backup file.
Definition: POSIX.C:917
fileName.H
timedOut
#define timedOut(x)
Check it a timeout has occured.
Definition: timer.H:71
Foam::dlOpen
void * dlOpen(const fileName &lib, const bool check=true)
Open a shared library. Return handle to library. Print error message.
Definition: POSIX.C:1161
cp
const volScalarField & cp
Definition: setRegionSolidFields.H:8
IFstream.H
Foam::pgid
PID_T pgid()
Return the group PID of this process.
Definition: POSIX.C:89
Foam::FatalError
error FatalError
Foam::PID_T
pid_t PID_T
Definition: OSspecific.H:51
timer.H
Foam::fileName::ext
word ext() const
Return file name extension (part after last .)
Definition: fileName.C:329
Foam
Namespace for OpenFOAM.
Definition: combustionModel.C:30
Foam::abort
errorManip< error > abort(error &err)
Definition: errorManip.H:131
Foam::isFile
bool isFile(const fileName &, const bool checkGzip=true)
Does the name exist as a FILE in the file system?
Definition: POSIX.C:622
Foam::isDir
bool isDir(const fileName &)
Does the name exist as a DIRECTORY in the file system?
Definition: POSIX.C:615
s
gmvFile<< "tracers "<< particles.size()<< nl;forAllConstIter(Cloud< passiveParticle >, particles, iter){ gmvFile<< iter().position().x()<< " ";}gmvFile<< nl;forAllConstIter(Cloud< passiveParticle >, particles, iter){ gmvFile<< iter().position().y()<< " ";}gmvFile<< nl;forAllConstIter(Cloud< passiveParticle >, particles, iter){ gmvFile<< iter().position().z()<< " ";}gmvFile<< nl;forAll(lagrangianScalarNames, i){ word name=lagrangianScalarNames[i];IOField< scalar > s(IOobject(name, runTime.timeName(), cloud::prefix, mesh, IOobject::MUST_READ, IOobject::NO_WRITE))
Foam::DynamicList::append
DynamicList< T, SizeInc, SizeMult, SizeDiv > & append(const T &)
Append an element at the end of the list.
Foam::exit
errorManipArg< error, int > exit(error &err, const int errNo=1)
Definition: errorManip.H:124
Foam::chDir
bool chDir(const fileName &dir)
Change the current directory to the one given and return true,.
Definition: POSIX.C:264
Foam::List::setSize
void setSize(const label)
Reset size of List.
Foam::findEtcFiles
fileNameList findEtcFiles(const fileName &, bool mandatory=false, bool findFirst=false)
Search for files from user/group/shipped directories.
Definition: POSIX.C:271
Foam::home
fileName home()
Return home directory path name for the current user.
Definition: POSIX.C:191
FatalErrorInFunction
#define FatalErrorInFunction
Report an error message using Foam::FatalError.
Definition: error.H:318
Foam::string::replace
string & replace(const string &oldStr, const string &newStr, size_type start=0)
Replace first occurence of sub-string oldStr with newStr.
Definition: string.C:58
Foam::fileStat::status
const struct stat & status() const
Raw status.
Definition: fileStat.H:93
Foam::List
A 1D array of objects of type <T>, where the size of the vector is known and used for subscript bound...
Definition: HashTable.H:59
Foam::timer
Implements a timeout mechanism via sigalarm.
Definition: timer.H:81
Foam::hostName
string hostName(const bool full=false)
Return the system's host name, as per hostname(1)
Definition: POSIX.C:129
path
fileName path(UMean.rootPath()/UMean.caseName()/"graphs"/UMean.instance())
Foam::dlClose
bool dlClose(void *)
Close a dlopened library using handle. Return true if successful.
Definition: POSIX.C:1212
collectLibsCallback
static int collectLibsCallback(struct dl_phdr_info *info, size_t size, void *data)
Definition: POSIX.C:1292
Foam::ln
bool ln(const fileName &src, const fileName &dst)
Create a softlink. dst should not exist. Returns true if successful.
Definition: POSIX.C:854
Foam::cwd
fileName cwd()
Return current working directory path name.
Definition: POSIX.C:246
DynamicList.H
Foam::dlLoaded
fileNameList dlLoaded()
Return all loaded libraries.
Definition: POSIX.C:1305
Foam::List::size
void size(const label)
Override size to be inconsistent with allocated storage.
Foam::readDir
fileNameList readDir(const fileName &, const fileName::Type=fileName::FILE, const bool filtergz=true)
Read a directory and return the entries as a string list.
Definition: POSIX.C:660
Foam::type
fileName::Type type(const fileName &)
Return the file type: DIRECTORY or FILE.
Definition: POSIX.C:588
Foam::mkDir
bool mkDir(const fileName &, mode_t=0777)
Make a directory and return an error if it could not be created.
Definition: POSIX.C:419
Foam::FOAMversion
const char *const FOAMversion
Foam::defineTypeNameAndDebug
defineTypeNameAndDebug(combustionModel, 0)
Foam::osRandomDouble
scalar osRandomDouble()
Return random double precision (uniform distribution between 0 and 1)
Definition: POSIX.C:1341
WarningInFunction
#define WarningInFunction
Report a warning using Foam::Warning.
Definition: messageStream.H:259
Foam::error
Class to handle errors and exceptions in a simple, consistent stream-based manner.
Definition: error.H:66
Foam::system
int system(const std::string &command)
Execute the specified command.
Definition: POSIX.C:1155
Foam::fileSize
off_t fileSize(const fileName &)
Return size of file.
Definition: POSIX.C:629
Foam::rmDir
bool rmDir(const fileName &)
Remove a dirctory and its contents.
Definition: POSIX.C:974
Foam::name
word name(const complex &)
Return a string representation of a complex.
Definition: complex.C:47
foamVersion.H