POSIX.C 25.5 KB
Newer Older
1
2
3
4
/*---------------------------------------------------------------------------*\
  =========                 |
  \\      /  F ield         | OpenFOAM: The Open Source CFD Toolbox
   \\    /   O peration     |
5
    \\  /    A nd           | Copyright (C) 2011-2016 OpenFOAM Foundation
6
7
8
9
10
     \\/     M anipulation  |
-------------------------------------------------------------------------------
License
    This file is part of OpenFOAM.

11
12
13
14
    OpenFOAM is free software: you can redistribute it and/or modify it
    under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.
15
16
17
18
19
20
21

    OpenFOAM is distributed in the hope that it will be useful, but WITHOUT
    ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
    FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
    for more details.

    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
32
33
#endif

#include "OSspecific.H"
34
#include "POSIX.H"
35
36
37
38
#include "foamVersion.H"
#include "fileName.H"
#include "fileStat.H"
#include "timer.H"
39
#include "IFstream.H"
mattijs's avatar
mattijs committed
40
#include "DynamicList.H"
41
42
43
44
45
46
47
48
49
50
51
52
53
54

#include <fstream>
#include <cstdlib>
#include <cctype>

#include <stdio.h>
#include <unistd.h>
#include <dirent.h>
#include <pwd.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/socket.h>
#include <netdb.h>
55
#include <dlfcn.h>
mattijs's avatar
mattijs committed
56
#include <link.h>
57
58
59

#include <netinet/in.h>

mattijs's avatar
mattijs committed
60
#ifdef USE_RANDOM
61
62
63
64
65
    #include <climits>
    #if INT_MAX    != 2147483647
        #error "INT_MAX    != 2147483647"
        #error "The random number generator may not work!"
    #endif
mattijs's avatar
mattijs committed
66
67
#endif

68
69
// * * * * * * * * * * * * * * Static Data Members * * * * * * * * * * * * * //

70
71
72
73
74
namespace Foam
{
    defineTypeNameAndDebug(POSIX, 0);
}

75
76
77
78
79

// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //

pid_t Foam::pid()
{
80
    return ::getpid();
81
82
}

mattijs's avatar
mattijs committed
83

84
85
pid_t Foam::ppid()
{
86
    return ::getppid();
87
88
}

mattijs's avatar
mattijs committed
89

90
91
pid_t Foam::pgid()
{
92
    return ::getpgrp();
93
94
}

mattijs's avatar
mattijs committed
95

96
97
bool Foam::env(const word& envName)
{
98
    return ::getenv(envName.c_str()) != nullptr;
99
100
101
102
103
}


Foam::string Foam::getEnv(const word& envName)
{
104
    char* env = ::getenv(envName.c_str());
105
106
107
108
109
110
111

    if (env)
    {
        return string(env);
    }
    else
    {
112
113
114
        // Return null-constructed string rather than string::null
        // to avoid cyclic dependencies in the construction of globals
        return string();
115
116
117
118
119
120
121
    }
}


bool Foam::setEnv
(
    const word& envName,
122
    const std::string& value,
123
124
125
126
127
128
129
    const bool overwrite
)
{
    return setenv(envName.c_str(), value.c_str(), overwrite) == 0;
}


130
Foam::string Foam::hostName(bool full)
131
{
132
    char buf[128];
133
    ::gethostname(buf, sizeof(buf));
134

135
    // implementation as per hostname from net-tools
136
137
    if (full)
    {
138
        struct hostent *hp = ::gethostbyname(buf);
139
        if (hp)
140
        {
141
            return hp->h_name;
142
143
144
145
        }
    }

    return buf;
146
147
148
}


149
Foam::string Foam::domainName()
150
151
{
    char buf[128];
152
    ::gethostname(buf, sizeof(buf));
153
154

    // implementation as per hostname from net-tools
155
    struct hostent *hp = ::gethostbyname(buf);
156
157
    if (hp)
    {
158
        char *p = ::strchr(hp->h_name, '.');
159
160
161
162
163
164
165
        if (p)
        {
            ++p;
            return p;
        }
    }

166
    return string::null;
167
168
169
}


170
Foam::string Foam::userName()
171
{
172
    struct passwd* pw = ::getpwuid(::getuid());
173

174
    if (pw != nullptr)
175
176
177
178
179
    {
        return pw->pw_name;
    }
    else
    {
180
        return string::null;
181
182
183
184
    }
}


185
186
bool Foam::isAdministrator()
{
187
    return (::geteuid() == 0);
188
189
190
}


191
192
Foam::fileName Foam::home()
{
193
    char* env = ::getenv("HOME");
194

195
    if (env != nullptr)
196
197
198
199
200
    {
        return fileName(env);
    }
    else
    {
201
        struct passwd* pw = ::getpwuid(getuid());
202

203
        if (pw != nullptr)
204
205
206
207
208
209
210
211
212
213
214
        {
            return pw->pw_dir;
        }
        else
        {
            return fileName::null;
        }
    }
}


215
Foam::fileName Foam::home(const string& userName)
216
217
218
219
220
{
    struct passwd* pw;

    if (userName.size())
    {
221
        pw = ::getpwnam(userName.c_str());
222
223
224
    }
    else
    {
225
        char* env = ::getenv("HOME");
226

227
        if (env != nullptr)
228
229
230
231
        {
            return fileName(env);
        }

232
        pw = ::getpwuid(::getuid());
233
234
    }

235
    if (pw != nullptr)
236
237
238
239
240
241
242
243
244
245
246
247
    {
        return pw->pw_dir;
    }
    else
    {
        return fileName::null;
    }
}


Foam::fileName Foam::cwd()
{
248
249
250
251
252
    label pathLengthLimit = POSIX::pathLengthChunk;
    List<char> path(pathLengthLimit);

    // Resize path if getcwd fails with an ERANGE error
    while(pathLengthLimit == path.size())
253
    {
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
        if (::getcwd(path.data(), path.size()))
        {
            return path.data();
        }
        else if(errno == ERANGE)
        {
            // Increment path length upto the pathLengthMax limit
            if
            (
                (pathLengthLimit += POSIX::pathLengthChunk)
             >= POSIX::pathLengthMax
            )
            {
                FatalErrorInFunction
                    << "Attempt to increase path length beyond limit of "
                    << POSIX::pathLengthMax
                    << exit(FatalError);
            }
272

273
274
275
276
277
278
            path.setSize(pathLengthLimit);
        }
        else
        {
            break;
        }
279
    }
280
281
282
283
284
285

    FatalErrorInFunction
        << "Couldn't get the current working directory"
        << exit(FatalError);

    return fileName::null;
286
287
288
289
290
}


bool Foam::chDir(const fileName& dir)
{
291
    return ::chdir(dir.c_str()) == 0;
292
293
294
295
296
297
}


bool Foam::mkDir(const fileName& pathName, mode_t mode)
{
    // empty names are meaningless
298
    if (pathName.empty())
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
    {
        return false;
    }

    // Construct instance path directory if does not exist
    if (::mkdir(pathName.c_str(), mode) == 0)
    {
        // Directory made OK so return true
        return true;
    }
    else
    {
        switch (errno)
        {
            case EPERM:
            {
315
                FatalErrorInFunction
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
                    << "The filesystem containing " << pathName
                    << " does not support the creation of directories."
                    << exit(FatalError);

                return false;
            }

            case EEXIST:
            {
                // Directory already exists so simply return true
                return true;
            }

            case EFAULT:
            {
331
                FatalErrorInFunction
332
333
334
335
336
337
338
339
340
                    << "" << pathName
                    << " points outside your accessible address space."
                    << exit(FatalError);

                return false;
            }

            case EACCES:
            {
341
                FatalErrorInFunction
342
343
344
345
346
347
348
349
350
351
352
                    << "The parent directory does not allow write "
                       "permission to the process,"<< nl
                    << "or one of the directories in " << pathName
                    << " did not allow search (execute) permission."
                    << exit(FatalError);

                return false;
            }

            case ENAMETOOLONG:
            {
353
                FatalErrorInFunction
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
                    << "" << pathName << " is too long."
                    << exit(FatalError);

                return false;
            }

            case ENOENT:
            {
                // Part of the path does not exist so try to create it
                if (pathName.path().size() && mkDir(pathName.path(), mode))
                {
                    return mkDir(pathName, mode);
                }
                else
                {
369
                    FatalErrorInFunction
370
371
372
373
374
375
376
377
378
                        << "Couldn't create directory " << pathName
                        << exit(FatalError);

                    return false;
                }
            }

            case ENOTDIR:
            {
379
                FatalErrorInFunction
380
381
382
383
384
385
386
387
388
                    << "A component used as a directory in " << pathName
                    << " is not, in fact, a directory."
                    << exit(FatalError);

                return false;
            }

            case ENOMEM:
            {
389
                FatalErrorInFunction
390
391
392
393
394
395
396
397
398
                    << "Insufficient kernel memory was available to make "
                       "directory " << pathName << '.'
                    << exit(FatalError);

                return false;
            }

            case EROFS:
            {
399
                FatalErrorInFunction
400
401
402
403
404
405
406
407
408
                    << "" << pathName
                    << " refers to a file on a read-only filesystem."
                    << exit(FatalError);

                return false;
            }

            case ELOOP:
            {
409
                FatalErrorInFunction
410
411
412
413
414
415
416
417
418
                    << "Too many symbolic links were encountered in resolving "
                    << pathName << '.'
                    << exit(FatalError);

                return false;
            }

            case ENOSPC:
            {
419
                FatalErrorInFunction
420
421
422
423
424
425
426
427
428
429
                    << "The device containing " << pathName
                    << " has no room for the new directory or "
                    << "the user's disk quota is exhausted."
                    << exit(FatalError);

                return false;
            }

            default:
            {
430
                FatalErrorInFunction
431
432
433
434
435
436
437
438
439
440
                    << "Couldn't create directory " << pathName
                    << exit(FatalError);

                return false;
            }
        }
    }
}


Mark Olesen's avatar
Mark Olesen committed
441
bool Foam::chMod(const fileName& name, const mode_t m)
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
{
    return ::chmod(name.c_str(), m) == 0;
}


mode_t Foam::mode(const fileName& name)
{
    fileStat fileStatus(name);
    if (fileStatus.isValid())
    {
        return fileStatus.status().st_mode;
    }
    else
    {
        return 0;
    }
}


Foam::fileName::Type Foam::type(const fileName& name)
{
    mode_t m = mode(name);

    if (S_ISREG(m))
    {
        return fileName::FILE;
    }
    else if (S_ISDIR(m))
    {
        return fileName::DIRECTORY;
    }
    else
    {
        return fileName::UNDEFINED;
    }
}


480
bool Foam::exists(const fileName& name, const bool checkGzip)
481
{
482
    return mode(name) || isFile(name, checkGzip);
483
484
485
}


486
bool Foam::isDir(const fileName& name)
487
{
488
    return S_ISDIR(mode(name));
489
490
491
}


Mark Olesen's avatar
Mark Olesen committed
492
bool Foam::isFile(const fileName& name, const bool checkGzip)
493
{
Mark Olesen's avatar
Mark Olesen committed
494
    return S_ISREG(mode(name)) || (checkGzip && S_ISREG(mode(name + ".gz")));
495
496
497
}


498
off_t Foam::fileSize(const fileName& name)
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
{
    fileStat fileStatus(name);
    if (fileStatus.isValid())
    {
        return fileStatus.status().st_size;
    }
    else
    {
        return -1;
    }
}


time_t Foam::lastModified(const fileName& name)
{
    fileStat fileStatus(name);
    if (fileStatus.isValid())
    {
        return fileStatus.status().st_mtime;
    }
    else
    {
        return 0;
    }
}


526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
double Foam::highResLastModified(const fileName& name)
{
    fileStat fileStatus(name);
    if (fileStatus.isValid())
    {
        return
            fileStatus.status().st_mtime
          + 1e-9d*fileStatus.status().st_atim.tv_nsec;
    }
    else
    {
        return 0.0;
    }
}


542
543
544
545
546
547
548
549
550
551
552
Foam::fileNameList Foam::readDir
(
    const fileName& directory,
    const fileName::Type type,
    const bool filtergz
)
{
    // Initial filename list size
    // also used as increment if initial size found to be insufficient
    static const int maxNnames = 100;

553
    if (POSIX::debug)
554
    {
555
556
        InfoInFunction
            << "reading directory " << directory << endl;
557
558
559
560
561
    }

    // Setup empty string list MAXTVALUES long
    fileNameList dirEntries(maxNnames);

562
    // Pointers to the directory entries
563
564
565
566
567
568
569
    DIR *source;
    struct dirent *list;

    // Temporary variables and counters
    label nEntries = 0;

    // Attempt to open directory and set the structure pointer
570
    if ((source = ::opendir(directory.c_str())) == nullptr)
571
572
573
    {
        dirEntries.setSize(0);

574
        if (POSIX::debug)
575
        {
576
577
            InfoInFunction
                << "cannot open directory " << directory << endl;
578
579
580
581
582
        }
    }
    else
    {
        // Read and parse all the entries in the directory
583
        while ((list = ::readdir(source)) != nullptr)
584
585
586
        {
            fileName fName(list->d_name);

587
588
            // ignore files begining with ., i.e. '.', '..' and '.*'
            if (fName.size() && fName[0] != '.')
589
            {
590
                word fExt = fName.ext();
591
592
593
594
595
596
597

                if
                (
                    (type == fileName::DIRECTORY)
                 ||
                    (
                        type == fileName::FILE
598
599
600
601
602
                     && fName[fName.size()-1] != '~'
                     && fExt != "bak"
                     && fExt != "BAK"
                     && fExt != "old"
                     && fExt != "save"
603
604
605
606
607
608
609
610
611
612
                    )
                )
                {
                    if ((directory/fName).type() == type)
                    {
                        if (nEntries >= dirEntries.size())
                        {
                            dirEntries.setSize(dirEntries.size() + maxNnames);
                        }

613
                        if (filtergz && fExt == "gz")
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
                        {
                            dirEntries[nEntries++] = fName.lessExt();
                        }
                        else
                        {
                            dirEntries[nEntries++] = fName;
                        }
                    }
                }
            }
        }

        // Reset the length of the entries list
        dirEntries.setSize(nEntries);

629
        ::closedir(source);
630
631
632
633
634
635
636
637
638
639
640
641
642
643
    }

    return dirEntries;
}


bool Foam::cp(const fileName& src, const fileName& dest)
{
    // Make sure source exists.
    if (!exists(src))
    {
        return false;
    }

644
645
    fileName destFile(dest);

646
647
648
649
650
651
652
653
654
655
    // Check type of source file.
    if (src.type() == fileName::FILE)
    {
        // If dest is a directory, create the destination file name.
        if (destFile.type() == fileName::DIRECTORY)
        {
            destFile = destFile/src.name();
        }

        // Make sure the destination directory exists.
656
        if (!isDir(destFile.path()) && !mkDir(destFile.path()))
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
        {
            return false;
        }

        // Open and check streams.
        std::ifstream srcStream(src.c_str());
        if (!srcStream)
        {
            return false;
        }

        std::ofstream destStream(destFile.c_str());
        if (!destStream)
        {
            return false;
        }

        // Copy character data.
        char ch;
        while (srcStream.get(ch))
        {
            destStream.put(ch);
        }

        // Final check.
        if (!srcStream.eof() || !destStream)
        {
            return false;
        }
    }
    else if (src.type() == fileName::DIRECTORY)
    {
        // If dest is a directory, create the destination file name.
        if (destFile.type() == fileName::DIRECTORY)
        {
            destFile = destFile/src.component(src.components().size() -1);
        }

695
        // Make sure the destination directory exists.
696
        if (!isDir(destFile) && !mkDir(destFile))
697
698
699
700
701
702
703
704
        {
            return false;
        }

        // Copy files
        fileNameList contents = readDir(src, fileName::FILE, false);
        forAll(contents, i)
        {
705
            if (POSIX::debug)
706
            {
707
708
                InfoInFunction
                    << "Copying : " << src/contents[i]
709
710
711
712
713
714
715
716
717
718
719
                    << " to " << destFile/contents[i] << endl;
            }

            // File to file.
            cp(src/contents[i], destFile/contents[i]);
        }

        // Copy sub directories.
        fileNameList subdirs = readDir(src, fileName::DIRECTORY);
        forAll(subdirs, i)
        {
720
            if (POSIX::debug)
721
            {
722
723
                InfoInFunction
                    << "Copying : " << src/subdirs[i]
724
725
726
727
728
729
730
731
732
733
734
735
                    << " to " << destFile << endl;
            }

            // Dir to Dir.
            cp(src/subdirs[i], destFile);
        }
    }

    return true;
}


Mark Olesen's avatar
Mark Olesen committed
736
bool Foam::ln(const fileName& src, const fileName& dst)
737
{
738
    if (POSIX::debug)
739
    {
740
741
        InfoInFunction
            << "Create softlink from : " << src << " to " << dst
742
743
744
            << endl;
    }

Mark Olesen's avatar
Mark Olesen committed
745
    if (exists(dst))
746
    {
747
        WarningInFunction
Mark Olesen's avatar
Mark Olesen committed
748
            << "destination " << dst << " already exists. Not linking."
749
750
751
752
            << endl;
        return false;
    }

753
    if (src.isAbsolute() && !exists(src))
754
    {
755
        WarningInFunction
756
757
758
759
            << "source " << src << " does not exist." << endl;
        return false;
    }

760
    if (::symlink(src.c_str(), dst.c_str()) == 0)
761
762
763
764
765
    {
        return true;
    }
    else
    {
766
        WarningInFunction
Mark Olesen's avatar
Mark Olesen committed
767
            << "symlink from " << src << " to " << dst << " failed." << endl;
768
769
770
771
772
        return false;
    }
}


773
bool Foam::mv(const fileName& src, const fileName& dst)
774
{
775
    if (POSIX::debug)
776
    {
777
778
        InfoInFunction
            << "Move : " << src << " to " << dst << endl;
779
780
781
782
    }

    if
    (
783
784
        dst.type() == fileName::DIRECTORY
     && src.type() != fileName::DIRECTORY
785
786
    )
    {
787
        const fileName dstName(dst/src.name());
788

789
        return ::rename(src.c_str(), dstName.c_str()) == 0;
790
791
792
    }
    else
    {
793
        return ::rename(src.c_str(), dst.c_str()) == 0;
794
795
796
797
    }
}


Mark Olesen's avatar
Mark Olesen committed
798
799
800
801
bool Foam::mvBak(const fileName& src, const std::string& ext)
{
    if (POSIX::debug)
    {
802
803
        InfoInFunction
            << "mvBak : " << src << " to extension " << ext << endl;
Mark Olesen's avatar
Mark Olesen committed
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
    }

    if (exists(src, false))
    {
        const int maxIndex = 99;
        char index[3];

        for (int n = 0; n <= maxIndex; n++)
        {
            fileName dstName(src + "." + ext);
            if (n)
            {
                sprintf(index, "%02d", n);
                dstName += index;
            }

            // avoid overwriting existing files, except for the last
            // possible index where we have no choice
            if (!exists(dstName, false) || n == maxIndex)
            {
824
                return ::rename(src.c_str(), dstName.c_str()) == 0;
Mark Olesen's avatar
Mark Olesen committed
825
826
827
828
829
830
831
832
833
834
            }

        }
    }

    // fall-through: nothing to do
    return false;
}


835
836
bool Foam::rm(const fileName& file)
{
837
    if (POSIX::debug)
838
    {
839
840
        InfoInFunction
            << "Removing : " << file << endl;
841
842
843
844
845
846
847
848
849
    }

    // Try returning plain file name; if not there, try with .gz
    if (remove(file.c_str()) == 0)
    {
        return true;
    }
    else
    {
850
        return ::remove(string(file + ".gz").c_str()) == 0;
851
852
853
854
855
856
    }
}


bool Foam::rmDir(const fileName& directory)
{
857
    if (POSIX::debug)
858
    {
859
        InfoInFunction
860
861
862
            << "removing directory " << directory << endl;
    }

863
    // Pointers to the directory entries
864
865
866
867
    DIR *source;
    struct dirent *list;

    // Attempt to open directory and set the structure pointer
868
    if ((source = ::opendir(directory.c_str())) == nullptr)
869
    {
870
        WarningInFunction
871
872
873
874
875
876
877
            << "cannot open directory " << directory << endl;

        return false;
    }
    else
    {
        // Read and parse all the entries in the directory
878
        while ((list = ::readdir(source)) != nullptr)
879
880
881
882
883
884
885
886
887
888
889
        {
            fileName fName(list->d_name);

            if (fName != "." && fName != "..")
            {
                fileName path = directory/fName;

                if (path.type() == fileName::DIRECTORY)
                {
                    if (!rmDir(path))
                    {
890
                        WarningInFunction
891
892
893
894
                            << "failed to remove directory " << fName
                            << " while removing directory " << directory
                            << endl;

895
                        ::closedir(source);
896
897
898
899
900
901
902
903

                        return false;
                    }
                }
                else
                {
                    if (!rm(path))
                    {
904
                        WarningInFunction
905
906
907
908
                            << "failed to remove file " << fName
                            << " while removing directory " << directory
                            << endl;

909
                        ::closedir(source);
910
911
912
913
914
915
916
917
918
919

                        return false;
                    }
                }
            }

        }

        if (!rm(directory))
        {
920
            WarningInFunction
921
922
                << "failed to remove directory " << directory << endl;

923
            ::closedir(source);
924
925
926
927

            return false;
        }

928
        ::closedir(source);
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944

        return true;
    }
}


unsigned int Foam::sleep(const unsigned int s)
{
    return ::sleep(s);
}


void Foam::fdClose(const int fd)
{
    if (close(fd) != 0)
    {
945
946
        FatalErrorInFunction
            << "close error on " << fd << endl
947
948
949
950
951
952
953
            << abort(FatalError);
    }
}


bool Foam::ping
(
954
    const string& destName,
955
956
957
958
959
960
961
962
963
    const label destPort,
    const label timeOut
)
{
    struct hostent *hostPtr;
    volatile int sockfd;
    struct sockaddr_in destAddr;      // will hold the destination addr
    u_int addr;

964
    if ((hostPtr = ::gethostbyname(destName.c_str())) == nullptr)
965
    {
966
967
        FatalErrorInFunction
            << "gethostbyname error " << h_errno << " for host " << destName
968
969
970
971
            << abort(FatalError);
    }

    // Get first of the SLL of addresses
972
    addr = (reinterpret_cast<struct in_addr*>(*(hostPtr->h_addr_list)))->s_addr;
973
974

    // Allocate socket
975
    sockfd = ::socket(AF_INET, SOCK_STREAM, 0);
976
977
    if (sockfd < 0)
    {
978
979
        FatalErrorInFunction
            << "socket error"
980
981
982
983
            << abort(FatalError);
    }

    // Fill sockaddr_in structure with dest address and port
984
    memset(reinterpret_cast<char *>(&destAddr), '\0', sizeof(destAddr));
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
    destAddr.sin_family = AF_INET;
    destAddr.sin_port = htons(ushort(destPort));
    destAddr.sin_addr.s_addr = addr;


    timer myTimer(timeOut);

    if (timedOut(myTimer))
    {
        // Setjmp from timer jumps back to here
        fdClose(sockfd);
        return false;
    }

    if
    (
1001
        ::connect
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
        (
            sockfd,
            reinterpret_cast<struct sockaddr*>(&destAddr),
            sizeof(struct sockaddr)
        ) != 0
    )
    {
        // Connection refused. Check if network was actually used or not.

        int connectErr = errno;

        fdClose(sockfd);

        if (connectErr == ECONNREFUSED)
        {
            return true;
        }
        //perror("connect");

        return false;
    }

    fdClose(sockfd);

    return true;
}


1030
bool Foam::ping(const string& hostname, const label timeOut)
1031
1032
1033
1034
1035
{
    return ping(hostname, 222, timeOut) || ping(hostname, 22, timeOut);
}


1036
int Foam::system(const std::string& command)
1037
1038
1039
1040
1041
{
    return ::system(command.c_str());
}


1042
void* Foam::dlOpen(const fileName& lib, const bool check)
1043
{
mattijs's avatar
mattijs committed
1044
1045
    if (POSIX::debug)
    {
mattijs's avatar
mattijs committed
1046
1047
        std::cout<< "dlOpen(const fileName&)"
            << " : dlopen of " << lib << std::endl;
mattijs's avatar
mattijs committed
1048
    }
mattijs's avatar
mattijs committed
1049
1050
    void* handle = ::dlopen(lib.c_str(), RTLD_LAZY|RTLD_GLOBAL);

1051
1052
    if (!handle && check)
    {
1053
        WarningInFunction
1054
1055
1056
1057
            << "dlopen error : " << ::dlerror()
            << endl;
    }

mattijs's avatar
mattijs committed
1058
1059
1060
1061
1062
1063
1064
1065
1066
    if (POSIX::debug)
    {
        std::cout
            << "dlOpen(const fileName&)"
            << " : dlopen of " << lib
            << " handle " << handle << std::endl;
    }

    return handle;
1067
1068
1069
1070
1071
}


bool Foam::dlClose(void* handle)
{
mattijs's avatar
mattijs committed
1072
1073
    if (POSIX::debug)
    {
mattijs's avatar
mattijs committed
1074
1075
1076
        std::cout
            << "dlClose(void*)"
            << " : dlclose of handle " << handle << std::endl;
mattijs's avatar
mattijs committed
1077
    }
1078
    return ::dlclose(handle) == 0;
1079
1080
1081
}


1082
void* Foam::dlSym(void* handle, const std::string& symbol)
1083
{
mattijs's avatar
mattijs committed
1084
1085
    if (POSIX::debug)
    {
mattijs's avatar
mattijs committed
1086
1087
1088
        std::cout
            << "dlSym(void*, const std::string&)"
            << " : dlsym of " << symbol << std::endl;
mattijs's avatar
mattijs committed
1089
    }
1090
1091
1092
1093
    // clear any old errors - see manpage dlopen
    (void) ::dlerror();

    // get address of symbol
1094
    void* fun = ::dlsym(handle, symbol.c_str());
1095

1096
1097
1098
1099
    // find error (if any)
    char *error = ::dlerror();

    if (error)
1100
    {
1101
        WarningInFunction
1102
1103
1104
            << "Cannot lookup symbol " << symbol << " : " << error
            << endl;
    }
1105

1106
1107
1108
1109
    return fun;
}


1110
1111
1112
1113
bool Foam::dlSymFound(void* handle, const std::string& symbol)
{
    if (handle && !symbol.empty())
    {
mattijs's avatar
mattijs committed
1114
1115
        if (POSIX::debug)
        {
mattijs's avatar
mattijs committed
1116
1117
1118
            std::cout
                << "dlSymFound(void*, const std::string&)"
                << " : dlsym of " << symbol << std::endl;
mattijs's avatar
mattijs committed
1119
1120
        }

1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
        // clear any old errors - see manpage dlopen
        (void) ::dlerror();

        // get address of symbol
        (void) ::dlsym(handle, symbol.c_str());

        // symbol can be found if there was no error
        return !::dlerror();
    }
    else
    {
        return false;
    }
}


mattijs's avatar
mattijs committed
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
static int collectLibsCallback
(
    struct dl_phdr_info *info,
    size_t size,
    void *data
)
{
    Foam::DynamicList<Foam::fileName>* ptr =
        reinterpret_cast<Foam::DynamicList<Foam::fileName>*>(data);
    ptr->append(info->dlpi_name);
    return 0;
}


Foam::fileNameList Foam::dlLoaded()
{
    DynamicList<fileName> libs;
    dl_iterate_phdr(collectLibsCallback, &libs);
    if (POSIX::debug)
    {
        std::cout
            << "dlLoaded()"
mattijs's avatar
mattijs committed
1159
            << " : determined loaded libraries :" << libs.size() << std::endl;
mattijs's avatar
mattijs committed
1160
1161
1162
1163
1164
    }
    return libs;
}


mattijs's avatar
mattijs committed
1165
1166
void Foam::osRandomSeed(const label seed)
{
1167
    #ifdef USE_RANDOM
mattijs's avatar
mattijs committed
1168
    srandom((unsigned int)seed);
1169
    #else
mattijs's avatar
mattijs committed
1170
    srand48(seed);
1171
    #endif
mattijs's avatar
mattijs committed
1172
1173
1174
1175
1176
}


Foam::label Foam::osRandomInteger()
{
1177
    #ifdef USE_RANDOM
mattijs's avatar
mattijs committed
1178
    return random();
1179
    #else
mattijs's avatar
mattijs committed
1180
    return lrand48();
1181
    #endif
mattijs's avatar
mattijs committed
1182
1183
1184
1185
1186
}


Foam::scalar Foam::osRandomDouble()
{
1187
    #ifdef USE_RANDOM
mattijs's avatar
mattijs committed
1188
    return (scalar)random()/INT_MAX;
1189
    #else
mattijs's avatar
mattijs committed
1190
    return drand48();
1191
    #endif
mattijs's avatar
mattijs committed
1192
1193
1194
}


1195
// ************************************************************************* //