POSIX.C 28.6 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()) != NULL;
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
175
176
177
178
179

    if (pw != NULL)
    {
        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
196
197
198
199
200

    if (env != NULL)
    {
        return fileName(env);
    }
    else
    {
201
        struct passwd* pw = ::getpwuid(getuid());
202
203
204
205
206
207
208
209
210
211
212
213
214

        if (pw != NULL)
        {
            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
228
229
230
231

        if (env != NULL)
        {
            return fileName(env);
        }

232
        pw = ::getpwuid(::getuid());
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
    }

    if (pw != NULL)
    {
        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
298
299
300
Foam::fileNameList Foam::findEtcFiles
(
    const fileName& name,
    bool mandatory,
    bool findFirst
)
301
{
302
303
304
    fileNameList results;

    // Search for user files in
305
306
307
    // * ~/.OpenFOAM/VERSION
    // * ~/.OpenFOAM
    //
308
    fileName searchDir = home()/".OpenFOAM";
309
    if (isDir(searchDir))
310
    {
311
        fileName fullName = searchDir/FOAMversion/name;
312
        if (isFile(fullName))
313
        {
314
            results.append(fullName);
315
316
            if (findFirst)
            {
317
                return results;
318
            }
319
320
321
        }

        fullName = searchDir/name;
322
        if (isFile(fullName))
323
        {
324
            results.append(fullName);
325
326
            if (findFirst)
            {
327
                return results;
328
            }
329
330
331
        }
    }

332
    // Search for group (site) files in
333
334
335
336
337
    // * $WM_PROJECT_SITE/VERSION
    // * $WM_PROJECT_SITE
    //
    searchDir = getEnv("WM_PROJECT_SITE");
    if (searchDir.size())
338
    {
339
        if (isDir(searchDir))
340
        {
341
342
343
            fileName fullName = searchDir/FOAMversion/name;
            if (isFile(fullName))
            {
344
                results.append(fullName);
345
346
                if (findFirst)
                {
347
                    return results;
348
                }
349
350
351
352
353
            }

            fullName = searchDir/name;
            if (isFile(fullName))
            {
354
                results.append(fullName);
355
356
                if (findFirst)
                {
357
                    return results;
358
                }
359
            }
360
        }
361
362
363
364
365
366
367
368
369
    }
    else
    {
        // OR search for group (site) files in
        // * $WM_PROJECT_INST_DIR/site/VERSION
        // * $WM_PROJECT_INST_DIR/site
        //
        searchDir = getEnv("WM_PROJECT_INST_DIR");
        if (isDir(searchDir))
370
        {
371
372
373
            fileName fullName = searchDir/"site"/FOAMversion/name;
            if (isFile(fullName))
            {
374
                results.append(fullName);
375
376
                if (findFirst)
                {
377
                    return results;
378
                }
379
380
381
382
383
            }

            fullName = searchDir/"site"/name;
            if (isFile(fullName))
            {
384
                results.append(fullName);
385
386
                if (findFirst)
                {
387
                    return results;
388
                }
389
            }
390
391
392
        }
    }

393
    // Search for other (shipped) files in
394
395
    // * $WM_PROJECT_DIR/etc
    //
396
    searchDir = getEnv("WM_PROJECT_DIR");
397
    if (isDir(searchDir))
398
    {
399
        fileName fullName = searchDir/"etc"/name;
400
        if (isFile(fullName))
401
        {
402
            results.append(fullName);
403
404
            if (findFirst)
            {
405
                return results;
406
            }
407
408
409
        }
    }

410
    // Not found
411
    if (results.empty())
412
    {
413
414
415
416
417
418
419
420
421
        // Abort if the file is mandatory, otherwise return null
        if (mandatory)
        {
            std::cerr
                << "--> FOAM FATAL ERROR in Foam::findEtcFiles() :"
                   " could not find mandatory file\n    '"
                << name.c_str() << "'\n\n" << std::endl;
            ::exit(1);
        }
422
423
    }

424
425
426
427
428
429
430
    // Return list of matching paths or empty list if none found
    return results;
}


Foam::fileName Foam::findEtcFile(const fileName& name, bool mandatory)
{
431
    fileNameList results(findEtcFiles(name, mandatory, true));
432
433
434
435
436
437
438
439
440

    if (results.size())
    {
        return results[0];
    }
    else
    {
        return fileName();
    }
441
442
443
444
445
446
}


bool Foam::mkDir(const fileName& pathName, mode_t mode)
{
    // empty names are meaningless
447
    if (pathName.empty())
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
    {
        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:
            {
464
                FatalErrorInFunction
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
                    << "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:
            {
480
                FatalErrorInFunction
481
482
483
484
485
486
487
488
489
                    << "" << pathName
                    << " points outside your accessible address space."
                    << exit(FatalError);

                return false;
            }

            case EACCES:
            {
490
                FatalErrorInFunction
491
492
493
494
495
496
497
498
499
500
501
                    << "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:
            {
502
                FatalErrorInFunction
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
                    << "" << 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
                {
518
                    FatalErrorInFunction
519
520
521
522
523
524
525
526
527
                        << "Couldn't create directory " << pathName
                        << exit(FatalError);

                    return false;
                }
            }

            case ENOTDIR:
            {
528
                FatalErrorInFunction
529
530
531
532
533
534
535
536
537
                    << "A component used as a directory in " << pathName
                    << " is not, in fact, a directory."
                    << exit(FatalError);

                return false;
            }

            case ENOMEM:
            {
538
                FatalErrorInFunction
539
540
541
542
543
544
545
546
547
                    << "Insufficient kernel memory was available to make "
                       "directory " << pathName << '.'
                    << exit(FatalError);

                return false;
            }

            case EROFS:
            {
548
                FatalErrorInFunction
549
550
551
552
553
554
555
556
557
                    << "" << pathName
                    << " refers to a file on a read-only filesystem."
                    << exit(FatalError);

                return false;
            }

            case ELOOP:
            {
558
                FatalErrorInFunction
559
560
561
562
563
564
565
566
567
                    << "Too many symbolic links were encountered in resolving "
                    << pathName << '.'
                    << exit(FatalError);

                return false;
            }

            case ENOSPC:
            {
568
                FatalErrorInFunction
569
570
571
572
573
574
575
576
577
578
                    << "The device containing " << pathName
                    << " has no room for the new directory or "
                    << "the user's disk quota is exhausted."
                    << exit(FatalError);

                return false;
            }

            default:
            {
579
                FatalErrorInFunction
580
581
582
583
584
585
586
587
588
589
                    << "Couldn't create directory " << pathName
                    << exit(FatalError);

                return false;
            }
        }
    }
}


Mark Olesen's avatar
Mark Olesen committed
590
bool Foam::chMod(const fileName& name, const mode_t m)
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
{
    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;
    }
}


629
bool Foam::exists(const fileName& name, const bool checkGzip)
630
{
631
    return mode(name) || isFile(name, checkGzip);
632
633
634
}


635
bool Foam::isDir(const fileName& name)
636
{
637
    return S_ISDIR(mode(name));
638
639
640
}


Mark Olesen's avatar
Mark Olesen committed
641
bool Foam::isFile(const fileName& name, const bool checkGzip)
642
{
Mark Olesen's avatar
Mark Olesen committed
643
    return S_ISREG(mode(name)) || (checkGzip && S_ISREG(mode(name + ".gz")));
644
645
646
}


647
off_t Foam::fileSize(const fileName& name)
648
649
650
651
652
653
654
655
656
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
{
    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;
    }
}


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;

686
    if (POSIX::debug)
687
    {
688
689
        InfoInFunction
            << "reading directory " << directory << endl;
690
691
692
693
694
    }

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

695
    // Pointers to the directory entries
696
697
698
699
700
701
702
    DIR *source;
    struct dirent *list;

    // Temporary variables and counters
    label nEntries = 0;

    // Attempt to open directory and set the structure pointer
703
    if ((source = ::opendir(directory.c_str())) == NULL)
704
705
706
    {
        dirEntries.setSize(0);

707
        if (POSIX::debug)
708
        {
709
710
            InfoInFunction
                << "cannot open directory " << directory << endl;
711
712
713
714
715
        }
    }
    else
    {
        // Read and parse all the entries in the directory
716
        while ((list = ::readdir(source)) != NULL)
717
718
719
        {
            fileName fName(list->d_name);

720
721
            // ignore files begining with ., i.e. '.', '..' and '.*'
            if (fName.size() && fName[0] != '.')
722
            {
723
                word fExt = fName.ext();
724
725
726
727
728
729
730

                if
                (
                    (type == fileName::DIRECTORY)
                 ||
                    (
                        type == fileName::FILE
731
732
733
734
735
                     && fName[fName.size()-1] != '~'
                     && fExt != "bak"
                     && fExt != "BAK"
                     && fExt != "old"
                     && fExt != "save"
736
737
738
739
740
741
742
743
744
745
                    )
                )
                {
                    if ((directory/fName).type() == type)
                    {
                        if (nEntries >= dirEntries.size())
                        {
                            dirEntries.setSize(dirEntries.size() + maxNnames);
                        }

746
                        if (filtergz && fExt == "gz")
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
                        {
                            dirEntries[nEntries++] = fName.lessExt();
                        }
                        else
                        {
                            dirEntries[nEntries++] = fName;
                        }
                    }
                }
            }
        }

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

762
        ::closedir(source);
763
764
765
766
767
768
769
770
771
772
773
774
775
776
    }

    return dirEntries;
}


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

777
778
    fileName destFile(dest);

779
780
781
782
783
784
785
786
787
788
    // 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.
789
        if (!isDir(destFile.path()) && !mkDir(destFile.path()))
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
        {
            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);
        }

828
        // Make sure the destination directory exists.
829
        if (!isDir(destFile) && !mkDir(destFile))
830
831
832
833
834
835
836
837
        {
            return false;
        }

        // Copy files
        fileNameList contents = readDir(src, fileName::FILE, false);
        forAll(contents, i)
        {
838
            if (POSIX::debug)
839
            {
840
841
                InfoInFunction
                    << "Copying : " << src/contents[i]
842
843
844
845
846
847
848
849
850
851
852
                    << " 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)
        {
853
            if (POSIX::debug)
854
            {
855
856
                InfoInFunction
                    << "Copying : " << src/subdirs[i]
857
858
859
860
861
862
863
864
865
866
867
868
                    << " to " << destFile << endl;
            }

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

    return true;
}


Mark Olesen's avatar
Mark Olesen committed
869
bool Foam::ln(const fileName& src, const fileName& dst)
870
{
871
    if (POSIX::debug)
872
    {
873
874
        InfoInFunction
            << "Create softlink from : " << src << " to " << dst
875
876
877
            << endl;
    }

Mark Olesen's avatar
Mark Olesen committed
878
    if (exists(dst))
879
    {
880
        WarningInFunction
Mark Olesen's avatar
Mark Olesen committed
881
            << "destination " << dst << " already exists. Not linking."
882
883
884
885
            << endl;
        return false;
    }

886
    if (src.isAbsolute() && !exists(src))
887
    {
888
        WarningInFunction
889
890
891
892
            << "source " << src << " does not exist." << endl;
        return false;
    }

893
    if (::symlink(src.c_str(), dst.c_str()) == 0)
894
895
896
897
898
    {
        return true;
    }
    else
    {
899
        WarningInFunction
Mark Olesen's avatar
Mark Olesen committed
900
            << "symlink from " << src << " to " << dst << " failed." << endl;
901
902
903
904
905
        return false;
    }
}


906
bool Foam::mv(const fileName& src, const fileName& dst)
907
{
908
    if (POSIX::debug)
909
    {
910
911
        InfoInFunction
            << "Move : " << src << " to " << dst << endl;
912
913
914
915
    }

    if
    (
916
917
        dst.type() == fileName::DIRECTORY
     && src.type() != fileName::DIRECTORY
918
919
    )
    {
920
        const fileName dstName(dst/src.name());
921

922
        return ::rename(src.c_str(), dstName.c_str()) == 0;
923
924
925
    }
    else
    {
926
        return ::rename(src.c_str(), dst.c_str()) == 0;
927
928
929
930
    }
}


Mark Olesen's avatar
Mark Olesen committed
931
932
933
934
bool Foam::mvBak(const fileName& src, const std::string& ext)
{
    if (POSIX::debug)
    {
935
936
        InfoInFunction
            << "mvBak : " << src << " to extension " << ext << endl;
Mark Olesen's avatar
Mark Olesen committed
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
    }

    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)
            {
957
                return ::rename(src.c_str(), dstName.c_str()) == 0;
Mark Olesen's avatar
Mark Olesen committed
958
959
960
961
962
963
964
965
966
967
            }

        }
    }

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


968
969
bool Foam::rm(const fileName& file)
{
970
    if (POSIX::debug)
971
    {
972
973
        InfoInFunction
            << "Removing : " << file << endl;
974
975
976
977
978
979
980
981
982
    }

    // Try returning plain file name; if not there, try with .gz
    if (remove(file.c_str()) == 0)
    {
        return true;
    }
    else
    {
983
        return ::remove(string(file + ".gz").c_str()) == 0;
984
985
986
987
988
989
    }
}


bool Foam::rmDir(const fileName& directory)
{
990
    if (POSIX::debug)
991
    {
992
        InfoInFunction
993
994
995
            << "removing directory " << directory << endl;
    }

996
    // Pointers to the directory entries
997
998
999
1000
    DIR *source;
    struct dirent *list;

    // Attempt to open directory and set the structure pointer
1001
    if ((source = ::opendir(directory.c_str())) == NULL)
1002
    {
1003
        WarningInFunction
1004
1005
1006
1007
1008
1009
1010
            << "cannot open directory " << directory << endl;

        return false;
    }
    else
    {
        // Read and parse all the entries in the directory
1011
        while ((list = ::readdir(source)) != NULL)
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
        {
            fileName fName(list->d_name);

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

                if (path.type() == fileName::DIRECTORY)
                {
                    if (!rmDir(path))
                    {
1023
                        WarningInFunction
1024
1025
1026
1027
                            << "failed to remove directory " << fName
                            << " while removing directory " << directory
                            << endl;

1028
                        ::closedir(source);
1029
1030
1031
1032
1033
1034
1035
1036

                        return false;
                    }
                }
                else
                {
                    if (!rm(path))
                    {
1037
                        WarningInFunction
1038
1039
1040
1041
                            << "failed to remove file " << fName
                            << " while removing directory " << directory
                            << endl;

1042
                        ::closedir(source);
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052

                        return false;
                    }
                }
            }

        }

        if (!rm(directory))
        {
1053
            WarningInFunction
1054
1055
                << "failed to remove directory " << directory << endl;

1056
            ::closedir(source);
1057
1058
1059
1060

            return false;
        }

1061
        ::closedir(source);
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077

        return true;
    }
}


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


void Foam::fdClose(const int fd)
{
    if (close(fd) != 0)
    {
1078
1079
        FatalErrorInFunction
            << "close error on " << fd << endl
1080
1081
1082
1083
1084
1085
1086
            << abort(FatalError);
    }
}


bool Foam::ping
(
1087
    const string& destName,
1088
1089
1090
1091
1092
1093
1094
1095
1096
    const label destPort,
    const label timeOut
)
{
    struct hostent *hostPtr;
    volatile int sockfd;
    struct sockaddr_in destAddr;      // will hold the destination addr
    u_int addr;

1097
    if ((hostPtr = ::gethostbyname(destName.c_str())) == NULL)
1098
    {
1099
1100
        FatalErrorInFunction
            << "gethostbyname error " << h_errno << " for host " << destName
1101
1102
1103
1104
            << abort(FatalError);
    }

    // Get first of the SLL of addresses
1105
    addr = (reinterpret_cast<struct in_addr*>(*(hostPtr->h_addr_list)))->s_addr;
1106
1107

    // Allocate socket
1108
    sockfd = ::socket(AF_INET, SOCK_STREAM, 0);
1109
1110
    if (sockfd < 0)
    {
1111
1112
        FatalErrorInFunction
            << "socket error"
1113
1114
1115
1116
            << abort(FatalError);
    }

    // Fill sockaddr_in structure with dest address and port
1117
    memset(reinterpret_cast<char *>(&destAddr), '\0', sizeof(destAddr));
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
    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
    (
1134
        ::connect
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
        (
            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;
}


1163
bool Foam::ping(const string& hostname, const label timeOut)
1164
1165
1166
1167
1168
{
    return ping(hostname, 222, timeOut) || ping(hostname, 22, timeOut);
}


1169
int Foam::system(const std::string& command)
1170
1171
1172
1173
1174
{
    return ::system(command.c_str());
}


1175
void* Foam::dlOpen(const fileName& lib, const bool check)
1176
{
mattijs's avatar
mattijs committed
1177
1178
    if (POSIX::debug)
    {
mattijs's avatar
mattijs committed
1179
1180
        std::cout<< "dlOpen(const fileName&)"
            << " : dlopen of " << lib << std::endl;
mattijs's avatar
mattijs committed
1181
    }
mattijs's avatar
mattijs committed
1182
1183
    void* handle = ::dlopen(lib.c_str(), RTLD_LAZY|RTLD_GLOBAL);

1184
1185
    if (!handle && check)
    {
1186
        WarningInFunction
1187
1188
1189
1190
            << "dlopen error : " << ::dlerror()
            << endl;
    }

mattijs's avatar
mattijs committed
1191
1192
1193
1194
1195
1196
1197
1198
1199
    if (POSIX::debug)
    {
        std::cout
            << "dlOpen(const fileName&)"
            << " : dlopen of " << lib
            << " handle " << handle << std::endl;
    }

    return handle;
1200
1201
1202
1203
1204
}


bool Foam::dlClose(void* handle)
{
mattijs's avatar
mattijs committed
1205
1206
    if (POSIX::debug)
    {
mattijs's avatar
mattijs committed
1207
1208
1209
        std::cout
            << "dlClose(void*)"
            << " : dlclose of handle " << handle << std::endl;
mattijs's avatar
mattijs committed
1210
    }
1211
    return ::dlclose(handle) == 0;
1212
1213
1214
}


1215
void* Foam::dlSym(void* handle, const std::string& symbol)
1216
{
mattijs's avatar
mattijs committed
1217
1218
    if (POSIX::debug)
    {
mattijs's avatar
mattijs committed
1219
1220
1221
        std::cout
            << "dlSym(void*, const std::string&)"
            << " : dlsym of " << symbol << std::endl;
mattijs's avatar
mattijs committed
1222
    }
1223
1224
1225
1226
    // clear any old errors - see manpage dlopen
    (void) ::dlerror();

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

1229
1230
1231
1232
    // find error (if any)
    char *error = ::dlerror();

    if (error)
1233
    {
1234
        WarningInFunction
1235
1236
1237
            << "Cannot lookup symbol " << symbol << " : " << error
            << endl;
    }
1238

1239
1240
1241
1242
    return fun;
}


1243
1244
1245
1246
bool Foam::dlSymFound(void* handle, const std::string& symbol)
{
    if (handle && !symbol.empty())
    {
mattijs's avatar
mattijs committed
1247
1248
        if (POSIX::debug)
        {
mattijs's avatar
mattijs committed
1249
1250
1251
            std::cout
                << "dlSymFound(void*, const std::string&)"
                << " : dlsym of " << symbol << std::endl;
mattijs's avatar
mattijs committed
1252
1253
        }

1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
        // 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
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
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
1292
            << " : determined loaded libraries :" << libs.size() << std::endl;
mattijs's avatar
mattijs committed
1293
1294
1295
1296
1297
    }
    return libs;
}


mattijs's avatar
mattijs committed
1298
1299
void Foam::osRandomSeed(const label seed)
{
1300
    #ifdef USE_RANDOM
mattijs's avatar
mattijs committed
1301
    srandom((unsigned int)seed);
1302
    #else
mattijs's avatar
mattijs committed
1303
    srand48(seed);
1304
    #endif
mattijs's avatar
mattijs committed
1305
1306
1307
1308
1309
}


Foam::label Foam::osRandomInteger()
{
1310
    #ifdef USE_RANDOM
mattijs's avatar
mattijs committed
1311
    return random();
1312
    #else
mattijs's avatar
mattijs committed
1313
    return lrand48();
1314
    #endif
mattijs's avatar
mattijs committed
1315
1316
1317
1318
1319
}


Foam::scalar Foam::osRandomDouble()
{
1320
    #ifdef USE_RANDOM
mattijs's avatar
mattijs committed
1321
    return (scalar)random()/INT_MAX;
1322
    #else
mattijs's avatar
mattijs committed
1323
    return drand48();
1324
    #endif
mattijs's avatar
mattijs committed
1325
1326
1327
}


1328
// ************************************************************************* //