1
   2
   3
   4
   5
   6
   7
   8
   9
  10
  11
  12
  13
  14
  15
  16
  17
  18
  19
  20
  21
  22
  23
  24
  25
  26
  27
  28
  29
  30
  31
  32
  33
  34
  35
  36
  37
  38
  39
  40
  41
  42
  43
  44
  45
  46
  47
  48
  49
  50
  51
  52
  53
  54
  55
  56
  57
  58
  59
  60
  61
  62
  63
  64
  65
  66
  67
  68
  69
  70
  71
  72
  73
  74
  75
  76
  77
  78
  79
  80
  81
  82
  83
  84
  85
  86
  87
  88
  89
  90
  91
  92
  93
  94
  95
  96
  97
  98
  99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 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
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 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
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 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
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 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
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 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
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
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
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
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
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
/* GATE PROJECT LICENSE:
+----------------------------------------------------------------------------+
| Copyright(c) 2018-2025, Stefan Meislinger <sm@opengate.at>                 |
| All rights reserved.                                                       |
|                                                                            |
| Redistribution and use in source and binary forms, with or without         |
| modification, are permitted provided that the following conditions are met:|
|                                                                            |
| 1. Redistributions of source code must retain the above copyright notice,  |
|    this list of conditions and the following disclaimer.                   |
| 2. Redistributions in binary form must reproduce the above copyright       |
|    notice, this list of conditions and the following disclaimer in the     |
|    documentation and/or other materials provided with the distribution.    |
|                                                                            |
| THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"|
| AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE  |
| IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE |
| ARE DISCLAIMED.IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE    |
| LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR        |
| CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF       |
| SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS   |
| INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN    |
| CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)    |
| ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF     |
| THE POSSIBILITY OF SUCH DAMAGE.                                            |
+----------------------------------------------------------------------------+
*/

#include "gate/processes.h"

#include "gate/platforms.h"
#include "gate/debugging.h"
#include "gate/results.h"

#if defined(GATE_SYS_POSIX)

#include <unistd.h>
#include <dirent.h>
#include <sys/wait.h>
#include <sys/resource.h>
#include <sys/types.h>
#include <sys/select.h>
#include <sys/wait.h>
#include <stdio.h>
#include <fcntl.h>
#include <grp.h>

#if defined(GATE_SYS_LINUX)
#	include <pty.h>
#elif defined(GATE_SYS_BSD)
#	include <termios.h>
#	if defined(GATE_SYS_FREEBSD)
#		include <libutil.h>
#	else
#		include <util.h>
#	endif
#elif defined(GATE_SYS_DARWIN)
#	include <util.h>
#	include "gate/platform/darwin/darwin_gate.h"
#endif

#if !defined(GATE_SYS_BSD)
#	include <utmp.h>
#endif
#include <dlfcn.h>
#include <errno.h>

#include "gate/times.h"
#include "gate/threading.h"
#include "gate/platforms.h"
#include "gate/platform/linux/procfs.h"
#include "gate/files.h"


typedef struct gate_process_stream_impl
{
    GATE_INTERFACE_VTBL(gate_process_stream)* vbl;
    gate_atomic_int_t	ref_counter;
    pid_t				target_pid;
    int					fd_stdin_write;
    int					fd_stdout_read;
    int					fd_stderr_read;
    char				peek_buffer[1024];
    gate_size_t			peek_buffer_used;
} gate_process_stream_impl_t;

static void gate_process_stream_release(void* thisptr)
{
    gate_process_stream_impl_t* stream = (gate_process_stream_impl_t*)thisptr;
    if (gate_atomic_int_dec(&stream->ref_counter) == 0)
    {
        if (stream->fd_stdin_write >= 0)
        {
            close(stream->fd_stdin_write);
            stream->fd_stdin_write = -1;
        }
        if (stream->fd_stdout_read >= 0)
        {
            close(stream->fd_stdout_read);
            stream->fd_stdout_read = -1;
        }
        if (stream->fd_stderr_read >= 0)
        {
            close(stream->fd_stderr_read);
            stream->fd_stderr_read = -1;
        }
        gate_mem_dealloc(stream);
    }
}
static char const* gate_process_stream_interface_name(void* thisptr)
{
    (void)thisptr;
    return GATE_INTERFACE_NAME_PROCESSSTREAM;
}
static int gate_process_stream_retain(void* thisptr)
{
    gate_process_stream_impl_t* stream = (gate_process_stream_impl_t*)thisptr;
    return gate_atomic_int_inc(&stream->ref_counter);
}

static gate_result_t is_process_termined(pid_t pid, gate_bool_t* ptr_terminated)
{
    siginfo_t info;
    int result;

    gate_mem_clear(&info, sizeof(info));
    result = waitid(P_PID, pid, &info, WEXITED | WNOHANG | WNOWAIT);
    if (0 == result)
    {
        if ((info.si_code == CLD_EXITED)
            || (info.si_code == CLD_KILLED)
            || (info.si_code == CLD_DUMPED)
            )
        {
            *ptr_terminated = true;
        }
        else
        {
            *ptr_terminated = false;
        }
        return GATE_RESULT_OK;
    }
    else
    {
        /* error */
        return gate_platform_print_last_error(NULL, 0);
    }
}

static gate_bool_t can_read_from_fd(int read_fd)
{
    fd_set read_set;
    struct timeval timeout;
    int result;

    timeout.tv_sec = 0;
    timeout.tv_usec = 0;

    FD_ZERO(&read_set);
    FD_SET(read_fd, &read_set);

    result = select(read_fd + 1, &read_set, NULL, NULL, &timeout);
    if (result < 0)
    {
        /* error */
        return false;
    }
    if (FD_ISSET(read_fd, &read_set))
    {
        return true;
    }
    return false;
}

static int await_read_fd_or_process_exit(pid_t pid, int read_fd)
{
    fd_set read_set;
    fd_set err_set;
    struct timeval timeout;
    int result;

    for (;;)
    {
        timeout.tv_sec = 0;
        timeout.tv_usec = 100000;

        FD_ZERO(&read_set);
        FD_ZERO(&err_set);
        FD_SET(read_fd, &read_set);
        FD_SET(read_fd, &err_set);

        result = select(read_fd + 1, &read_set, NULL, &err_set, &timeout);
        if (result < 0)
        {
            /* error */
            return -1;
        }
        if (FD_ISSET(read_fd, &err_set))
        {
            /* error */
            return -1;
        }
        if (FD_ISSET(read_fd, &read_set))
        {
            /* can read */
            return 1;
        }

        if (pid > 0)
        {
            gate_bool_t is_terminated = false;
            gate_result_t wait_result = is_process_termined(pid, &is_terminated);

            if (GATE_FAILED(wait_result))
            {
                /* failed to detect process state */
                return -1;
            }
            else
            {
                if (is_terminated)
                {
                    /* process terminated, nothing else to read */
                    return 0;
                }

                /* else: continue */
            }
        }
    }
}

static gate_result_t gate_process_stream_read(void* thisptr, char* buffer, gate_size_t bufferlength, gate_size_t* returned)
{
    gate_process_stream_impl_t* stream = (gate_process_stream_impl_t*)thisptr;
    gate_result_t ret = GATE_RESULT_FAILED;
    gate_int32_t errcode;
    ptrdiff_t result;
    int wait_result;<--- Shadowed declaration

    if (stream->peek_buffer_used > 0)
    {
        /* there is something in the peek buffer */

        if (bufferlength >= stream->peek_buffer_used)
        {
            /* we can read the whole peek-buffer */
            gate_mem_copy(buffer, stream->peek_buffer, stream->peek_buffer_used);
            if (returned) *returned = stream->peek_buffer_used;
            stream->peek_buffer_used = 0;
        }
        else
        {
            /* we can only return a subset of the peek buffer */
            gate_mem_copy(buffer, &stream->peek_buffer[0], bufferlength);
            gate_mem_copy(&stream->peek_buffer[0], &stream->peek_buffer[bufferlength], stream->peek_buffer_used - bufferlength);
            stream->peek_buffer_used -= bufferlength;
            if (returned) *returned = bufferlength;
        }
        return GATE_RESULT_OK;
    }

    wait_result = await_read_fd_or_process_exit(stream->target_pid, stream->fd_stdout_read);
    if (wait_result < 0)
    {
        return GATE_RESULT_FAILED;
    }
    else if (wait_result == 0)
    {
        if (returned)
        {
            *returned = 0;
        }
        return GATE_RESULT_OK;
    }

    /* data available to read */
    result = gate_posix_read(stream->fd_stdout_read, buffer, bufferlength);
    if (result < 0)
    {
        errcode = gate_platform_get_last_error();
        if (errcode == EIO)
        {
            gate_bool_t terminated = false;
            gate_result_t wait_result = is_process_termined(stream->target_pid, &terminated);<--- Shadow variable
            if (GATE_SUCCEEDED(wait_result) && terminated)
            {
                /* signal end-of-stream, as process was terminated */
                if (returned)
                {
                    *returned = 0;
                }
                return GATE_RESULT_OK;
            }
        }
        GATE_DEBUG_TRACE_MSG_VALUE("gate_process_stream_read() failed", errcode);
        ret = gate_platform_print_error(errcode, NULL, 0);
    }
    else
    {
        if (returned) *returned = (gate_size_t)result;
        ret = GATE_RESULT_OK;
    }
    return ret;
}
static gate_result_t gate_process_stream_peek(void* thisptr, char* buffer, gate_size_t bufferlength, gate_size_t* returned)
{
    gate_process_stream_impl_t* stream = (gate_process_stream_impl_t*)thisptr;
    gate_size_t copylen;
    ptrdiff_t result;
    gate_int32_t errcode;

    if (stream->peek_buffer_used > 0)
    {
        /* there is already something in the peek buffer */
        copylen = bufferlength < stream->peek_buffer_used ? bufferlength : stream->peek_buffer_used;
        gate_mem_copy(buffer, &stream->peek_buffer[0], copylen);
        if (returned) *returned = copylen;
        return GATE_RESULT_OK;
    }

    if (can_read_from_fd(stream->fd_stdout_read))
    {
        /* read some bytes into peek-buffer */
        copylen = bufferlength < sizeof(stream->peek_buffer) ? bufferlength : sizeof(stream->peek_buffer);
        result = gate_posix_read(stream->fd_stdout_read, &stream->peek_buffer[0], copylen);
        if (result < 0)
        {
            /* read error */
            errcode = gate_platform_get_last_error();
            if (errcode == EIO)
            {
                gate_bool_t terminated = false;
                gate_result_t wait_result = is_process_termined(stream->target_pid, &terminated);
                if (GATE_SUCCEEDED(wait_result) && terminated)
                {
                    /* signal end-of-stream, as process was terminated */
                    if (returned)
                    {
                        *returned = 0;
                    }
                    return GATE_RESULT_ENDOFSTREAM;
                }
            }
            /* otherwise return native error info */
            return gate_platform_print_last_error(NULL, 0);
        }
        else if (result > 0)
        {
            /* peek-buffer is filled, return a copy via caller-supplied buffer */
            stream->peek_buffer_used = copylen;
            gate_mem_copy(buffer, &stream->peek_buffer[0], copylen);
            if (returned) *returned = copylen;
            return GATE_RESULT_OK;
        }
    }

    /* else: nothing available to read*/
    if (returned) *returned = 0;
    return GATE_RESULT_OK;
}
static gate_result_t gate_process_stream_write(void* thisptr, char const* buffer, gate_size_t bufferlength, gate_size_t* written)
{
    gate_process_stream_impl_t* stream = (gate_process_stream_impl_t*)thisptr;
    gate_result_t ret = GATE_RESULT_FAILED;
    gate_int32_t errcode;
    ptrdiff_t result = gate_posix_write(stream->fd_stdin_write, buffer, bufferlength);
    if (result <= 0)
    {
        errcode = gate_platform_get_last_error();
        GATE_DEBUG_TRACE_MSG_VALUE("gate_process_stream_write() failed", errcode);
        ret = gate_platform_print_error(errcode, NULL, 0);
    }
    else
    {
        if (written) *written = (gate_size_t)result;
        ret = GATE_RESULT_OK;
    }
    return ret;
}
static gate_result_t gate_process_stream_flush(void* thisptr)
{
    gate_process_stream_impl_t* stream = (gate_process_stream_impl_t*)thisptr;
    fsync(stream->fd_stdin_write);
    return GATE_RESULT_OK;
}
static gate_result_t gate_process_stream_read_err(void* thisptr, char* buffer, gate_size_t bufferlength, gate_size_t* returned)
{
    gate_process_stream_impl_t* stream = (gate_process_stream_impl_t*)thisptr;
    gate_result_t ret = GATE_RESULT_FAILED;
    gate_int32_t errcode;
    ptrdiff_t result = gate_posix_read(stream->fd_stderr_read, buffer, bufferlength);
    if (result < 0)
    {
        errcode = gate_platform_get_last_error();
        GATE_DEBUG_TRACE_MSG_VALUE("gate_process_stream_read() failed", errcode);
        ret = gate_platform_print_error(errcode, NULL, 0);
    }
    else
    {
        if (returned) *returned = (gate_size_t)result;
        ret = GATE_RESULT_OK;
    }
    return ret;
}
static gate_result_t gate_process_stream_get_resource(void* thisptr, gate_enumint_t resource_type, gate_uintptr_t* resource)
{
    gate_process_stream_impl_t* stream = (gate_process_stream_impl_t*)thisptr;
    gate_result_t ret;
    switch (resource_type)
    {
    case GATE_STREAM_RESOURCE_INPUT:
    {
        *resource = (gate_uintptr_t)stream->fd_stdin_write;
        ret = GATE_RESULT_OK;
        break;
    }
    case GATE_STREAM_RESOURCE_OUTPUT:
    {
        *resource = (gate_uintptr_t)stream->fd_stdout_read;
        ret = GATE_RESULT_OK;
        break;
    }
    case GATE_STREAM_RESOURCE_ERROR:
    {
        *resource = (gate_uintptr_t)stream->fd_stderr_read;
        ret = GATE_RESULT_OK;
        break;
    }
    default:
    {
        ret = GATE_RESULT_NOTSUPPORTED;
        break;
    }
    }
    return ret;
}

static GATE_INTERFACE_VTBL(gate_process_stream) gate_process_stream_vtbl;
static void gate_init_process_stream_vtbl()
{
    if (!gate_process_stream_vtbl.get_interface_name)
    {
        GATE_INTERFACE_VTBL(gate_process_stream) const local_vtbl =
        {
            &gate_process_stream_interface_name,
            &gate_process_stream_release,
            &gate_process_stream_retain,
            &gate_process_stream_read,
            &gate_process_stream_peek,
            &gate_process_stream_write,
            &gate_process_stream_flush,
            &gate_process_stream_get_resource,
            &gate_process_stream_read_err
        };
        gate_process_stream_vtbl = local_vtbl;
    }
}

static gate_process_stream_t* gate_process_stream_create(int fd_stdin_write, int fd_stdout_read, int fd_stderr_read)
{
    gate_process_stream_impl_t* stream = gate_mem_alloc(sizeof(gate_process_stream_impl_t));
    if (stream)
    {
        gate_init_process_stream_vtbl();
        stream->vbl = &gate_process_stream_vtbl;
        gate_atomic_int_set(&stream->ref_counter, 1);
        stream->target_pid = 0;
        stream->fd_stdin_write = fd_stdin_write;
        stream->fd_stdout_read = fd_stdout_read;
        stream->fd_stderr_read = fd_stderr_read;
    }
    return (gate_process_stream_t*)stream;
}


/*
typedef struct rlimit_setting
{
    int				setting;
    struct rlimit	limit;
} rlimit_setting_t;

typedef struct gate_process_exec_config
{
    gate_bool_t			set_uid;
    uid_t				uid;
    gate_bool_t			set_gid;
    gid_t				gid;

    gate_bool_t			new_session;
    gate_bool_t			new_terminal;

    rlimit_setting_t	limits[8];
    gate_size_t			limit_count;

} gate_process_exec_config_t;

gate_result_t gate_process_apply_exec_config(gate_process_exec_config_t const* config)
{
    gate_result_t ret = GATE_RESULT_OK;
    gate_size_t ndx;
    int result;
    char user_name[512];
    gate_size_t user_name_used;

    do
    {
        if(config == NULL) break;

        for(ndx = 0; ndx != config->limit_count; ++ndx)
        {
            if(-1 == setrlimit(config->limits[ndx].setting, &config->limits[ndx].limit))
            {
                ret = GATE_RESULT_PREPARATIONFAILED;
                break;
            }
        }
        GATE_BREAK_IF_FAILED(ret);

        if(config->set_uid && config->set_gid)
        {
            user_name_used = gate_posix_get_user_name(config->set_uid, user_name, sizeof(user_name));
            if(user_name_used != 0)
            {
                result = initgroups(user_name, config->gid);
                if(result != 0)
                {
                    GATE_DEBUG_TRACE("Failed to initialize groups");
                    GATE_DEBUG_TRACE_VALUE(gate_posix_errno(NULL));
                    break;
                }
            }
        }

        if(config->set_gid)
        {
            result = setgid(config->gid);
            if(result != 0)
            {
                GATE_DEBUG_TRACE("setgid() failed");
                GATE_DEBUG_TRACE_VALUE(gate_posix_errno(NULL));
                ret = GATE_RESULT_FAILED;
                break;
            }
        }

        if(config->set_uid)
        {
            result = setuid(config->uid);
            if(result != 0)
            {
                GATE_DEBUG_TRACE("setuid() failed");
                GATE_DEBUG_TRACE_VALUE(gate_posix_errno(NULL));
                ret = GATE_RESULT_FAILED;
                break;
            }
        }

        if(config->new_session)
        {
            result = setsid();
            if(result != 0)
            {
                GATE_DEBUG_TRACE("setsid() failed");
                GATE_DEBUG_TRACE_VALUE(gate_posix_errno(NULL));
                ret = GATE_RESULT_FAILED;
                break;
            }
        }

    } while(0);

    return ret;
}
*/

gate_result_t gate_process_get_id(gate_process_id_t* pid)
{
    gate_result_t ret;
    pid_t p = getpid();
    if (pid == NULL)
    {
        ret = GATE_RESULT_INVALIDARG;
    }
    else
    {
        *pid = (gate_process_id_t)p;
        ret = GATE_RESULT_OK;
    }
    return ret;
}
void gate_process_quit(int exitcode)
{
    _exit(exitcode);
}

#if defined(GATE_SYS_BSD) || defined(GATE_SYS_DARWIN)

#include <stdlib.h>
#include <sys/types.h>
#include <sys/sysctl.h>

#if defined(GATE_SYS_NETBSD)
/* NetBSD is special here and uses kinfo_proc2 for usermode, BSD's kinfo_proc is for kernel-mode only */

#	include <kvm.h>

typedef kvm_t* (*kvm_open_func_t)(char const* execfile, char const* corefile, char* swapfile, int flags, char* errstr);
typedef int	(*kvm_close_func_t)(kvm_t* kd);
typedef struct kinfo_proc2* (*kvm_getproc2_func_t)(kvm_t* kd, int op, int arg, size_t elemsize, int* cnt);

static kvm_open_func_t	kvm_open_func;
static kvm_close_func_t	kvm_close_func;
static kvm_getproc2_func_t	kvm_getproc2_func;

static void* volatile kvm_lib = NULL;

static void close_kvm_lib_atexit()
{
    if (NULL != kvm_lib)
    {
        void* handle = kvm_lib;
        kvm_lib = NULL;
        gate_posix_dlclose(handle);
    }
}

static gate_result_t load_kvm_library()
{
    if (!kvm_lib)
    {
        kvm_lib = gate_posix_dlopen("libkvm.so", RTLD_GLOBAL);
        if (kvm_lib == NULL)
        {
            return GATE_RESULT_NOTAVAILABLE;
        }
        gate_platform_atexit(&close_kvm_lib_atexit);
    }
    if (!kvm_open_func)
    {
        kvm_open_func = (kvm_open_func_t)gate_posix_dlsym(kvm_lib, "kvm_open");
    }
    if (!kvm_close_func)
    {
        kvm_close_func = (kvm_close_func_t)gate_posix_dlsym(kvm_lib, "kvm_close");
    }
    if (!kvm_getproc2_func)
    {
        kvm_getproc2_func = (kvm_getproc2_func_t)gate_posix_dlsym(kvm_lib, "kvm_getproc2");
    }
    return (kvm_open_func && kvm_close_func && kvm_getproc2_func) ? GATE_RESULT_OK : GATE_RESULT_NOTAVAILABLE;
}

static gate_result_t load_process_infobuffer(gate_process_infobuffer_t* target, struct kinfo_proc2 const* src)
{
    target->process.pid = src->p_pid;
    target->process.parent_pid = src->p_ppid;
    target->process.memory_used = src->p_vm_rssize;
    target->process.uptime = src->p_ustart_sec * 1000;
    target->process.cputime = src->p_uutime_sec * 1000;
    target->process.resources = 1;
    gate_str_print_text(target->namebuffer, sizeof(target->namebuffer), src->p_comm, gate_str_length(src->p_comm));
    target->process.name = target->namebuffer;
    gate_str_print_int64(target->ownerbuffer, sizeof(target->ownerbuffer), src->p_ruid);
    target->process.owner = target->ownerbuffer;
    return GATE_RESULT_OK;
}


gate_result_t gate_process_getinfo(gate_process_infobuffer_t* infobuffer, gate_process_id_t proc_id, gate_enumint_t flags)
{
    gate_result_t ret = GATE_RESULT_FAILED;
    kvm_t* kvm = NULL;
    struct kinfo_proc2* procs = NULL;
    int procs_count = 0;
    char errmsg[_POSIX2_LINE_MAX] = GATE_INIT_EMPTY;

    do
    {
        ret = load_kvm_library();
        GATE_BREAK_IF_FAILED(ret);

        kvm = kvm_open_func(NULL, NULL, NULL, O_RDONLY, errmsg);
        if (kvm == NULL)
        {
            GATE_DEBUG_TRACE("kvm_open() failed");
            errmsg[_POSIX2_LINE_MAX - 1] = 0;
            GATE_DEBUG_TRACE(errmsg);
            ret = GATE_RESULT_NOTAVAILABLE;
            break;
        }
        procs = kvm_getproc2_func(kvm, KERN_PROC_PID, (int)proc_id, sizeof(struct kinfo_proc2), &procs_count);
        if ((procs == NULL) || (procs_count == 0))
        {
            GATE_DEBUG_TRACE("kvm_getprocs(KERN_PROC_PID) failed");
            ret = GATE_RESULT_NOMATCH;
            break;
        }

        ret = load_process_infobuffer(infobuffer, procs);
    } while (0);

    if (kvm != NULL)
    {
        kvm_close_func(kvm);
    }

    return ret;
}

#else /* OpenBSD and FreeBSD: */

#include <sys/user.h>

static gate_result_t load_process_infobuffer(gate_process_infobuffer_t* target, struct kinfo_proc const* src)
{
    gate_result_t ret = GATE_RESULT_OK;
    gate_mem_clear(target, sizeof(gate_process_infobuffer_t));
#if defined(GATE_SYS_OPENBSD)
    target->process.pid = src->p_pid;
    target->process.parent_pid = src->p_ppid;
    target->process.memory_used = src->p_vm_rssize;
    target->process.uptime = src->p_uutime_sec * 1000 + src->p_ustime_sec * 1000 + src->p_rtime_sec * 1000;
    target->process.resources = src->p_tid;
    gate_str_print_text(target->namebuffer, sizeof(target->namebuffer), src->p_comm, gate_str_length(src->p_comm));
    target->process.name = target->namebuffer;
    gate_str_print_int64(target->ownerbuffer, sizeof(target->ownerbuffer), src->p_ruid);
    target->process.owner = target->ownerbuffer;
#elif defined(GATE_SYS_DARWIN)
    target->process.pid = src->kp_proc.p_pid;
    target->process.parent_pid = src->kp_eproc.e_ppid;
    target->process.memory_used = 1; /* TODO */
    target->process.uptime = src->kp_proc.p_swtime;
    target->process.cputime = src->kp_proc.p_rtime.tv_sec * 1000 + src->kp_proc.p_rtime.tv_usec / 1000;
    target->process.resources = 1; /* TODO */
    gate_str_print_text(target->namebuffer, sizeof(target->namebuffer), src->kp_proc.p_comm, gate_str_length(src->kp_proc.p_comm));
    target->process.name = target->namebuffer;
    gate_str_print_text(target->ownerbuffer, sizeof(target->ownerbuffer), src->kp_eproc.e_login, gate_str_length(src->kp_eproc.e_login));
    target->process.owner = target->ownerbuffer;
#else
    target->process.pid = src->ki_pid;
    target->process.parent_pid = src->ki_ppid;
    target->process.memory_used = src->ki_size;
    target->process.uptime = src->ki_start.tv_sec * 1000 + src->ki_start.tv_usec / 1000;
    target->process.cputime = src->ki_runtime;
    target->process.resources = src->ki_numthreads;
    gate_str_print_text(target->namebuffer, sizeof(target->namebuffer), src->ki_comm, gate_str_length(src->ki_comm));
    target->process.name = target->namebuffer;
    gate_str_print_text(target->ownerbuffer, sizeof(target->ownerbuffer), src->ki_login, gate_str_length(src->ki_login));
    target->process.owner = target->ownerbuffer;
#endif

    return ret;
}

gate_result_t gate_process_getinfo(gate_process_infobuffer_t* infobuffer, gate_process_id_t proc_id, gate_enumint_t flags)
{
    gate_result_t ret = GATE_RESULT_FAILED;
    int names[] = { CTL_KERN, KERN_PROC, KERN_PROC_PID, (int)proc_id, sizeof(struct kinfo_proc), 1 };
#if defined(GATE_SYS_OPENBSD)
    unsigned name_len = 6;
#else
    unsigned name_len = 4;
#endif
    char buffer[8192 + 4096];
    size_t buffer_len = sizeof(buffer);
    int result;

    do
    {
        result = sysctl(names, name_len, &buffer[0], &buffer_len, NULL, 0);
        if (result < 0)
        {
            GATE_DEBUG_TRACE_PLATFORM_ERROR("sysctl() failed");
            GATE_DEBUG_TRACE_MSG_VALUE("PID", proc_id);
            ret = GATE_RESULT_FAILED;
            break;
        }
        ret = load_process_infobuffer(infobuffer, (struct kinfo_proc const*)buffer);
    } while (0);
    return ret;
}

#endif /* NETBSD or OPEN/FREEBSD variants for gate_process_getinfo() */


#if defined(GATE_SYS_DARWIN)

static gate_bool_t publish_process_info(int pid, gate_process_enum_callback_t callback, void* userparam, gate_enumint_t flags)
{
    gate_process_infobuffer_t info;

    int ppid = 0;
    unsigned int uid = 0;
    unsigned int gid = 0;
    unsigned long long start_time = 0;
    gate_result_t result;

    gate_mem_clear(&info, sizeof(info));

    info.process.pid = pid;

    result = gate_darwin_get_pid_info(pid, &ppid, &uid, &gid, &start_time, info.namebuffer, sizeof(info.namebuffer));
    if (GATE_SUCCEEDED(result))
    {
        info.process.parent_pid = ppid;
        info.process.uptime = (gate_int64_t)start_time;
        info.process.cputime = (gate_int64_t)start_time; /* TODO */
        info.process.name = info.namebuffer;
    }

    if (GATE_FLAG_ENABLED(flags, GATE_PROCESS_ENUM_PATH))
    {
        result = gate_darwin_get_pid_path(pid, info.pathbuffer, sizeof(info.pathbuffer), NULL);
        if (GATE_SUCCEEDED(result))
        {
            info.process.path = info.pathbuffer;
        }
    }

    if (GATE_FLAG_ENABLED(flags, GATE_PROCESS_ENUM_MEMORY))
    {
        /* TODO */
    }

    if (GATE_FLAG_ENABLED(flags, GATE_PROCESS_ENUM_MEMORY))
    {
        /* TODO */
    }

    return callback(&info.process, userparam);
}

static gate_result_t darwin_process_enum(gate_process_enum_callback_t callback, void* userparam, gate_enumint_t flags)
{
    int pids[1024 + 512 + 256];
    gate_size_t pids_used = 0;
    gate_size_t ndx;
    gate_result_t result = gate_darwin_list_pids(&pids[0], sizeof(pids) / sizeof(pids[0]), &pids_used);
    GATE_RETURN_IF_FAILED(result);
    if (callback)
    {
        for (ndx = 0; ndx != pids_used; ++ndx)
        {
            if (!publish_process_info(pids[ndx], callback, userparam, flags))
            {
                break;
            }
        }
    }
    return GATE_RESULT_OK;
}

#elif defined(GATE_SYS_FREEBSD)

typedef struct kinfo_proc* (*kinfo_getallproc_func_t)(int* cntp);

static void* volatile libutil = NULL;

static void close_libutil_atexit()
{
    if (NULL != libutil)
    {
        void* handle = libutil;
        libutil = NULL;
        gate_posix_dlclose(handle);
    }
}

static kinfo_getallproc_func_t load_getallproc()
{
    if (libutil == NULL)
    {
        libutil = gate_posix_dlopen("libutil.so", RTLD_GLOBAL);
        if (NULL == libutil)
        {
            return NULL;
        }
        else
        {
            gate_platform_atexit(&close_libutil_atexit);
        }
    }
    return (kinfo_getallproc_func_t)gate_posix_dlsym(libutil, "kinfo_getallproc");
}

static gate_result_t freebsd_process_enum(gate_process_enum_callback_t callback, void* userparam, gate_enumint_t flags)
{
    int procs_count = 0;
    int ndx;
    gate_process_infobuffer_t infobuffer;
    struct kinfo_proc* procs;
    kinfo_getallproc_func_t kinfo_getallproc_func = load_getallproc();

    if (!kinfo_getallproc_func)
    {
        return GATE_RESULT_NOTSUPPORTED;
    }

    procs = kinfo_getallproc_func(&procs_count);

    if (procs == NULL)
    {
        return GATE_RESULT_FAILED;
    }

    for (ndx = 0; ndx < procs_count; ++ndx)
    {
        gate_result_t result = load_process_infobuffer(&infobuffer, &procs[ndx]);
        if (GATE_FAILED(result))
        {
            continue;
        }
        if (!callback(&infobuffer.process, userparam))
        {
            break;
        }
    }

    free(procs);
    return GATE_RESULT_OK;
}

#elif defined(GATE_SYS_OPENBSD)

static gate_result_t openbsd_process_enum(gate_process_enum_callback_t callback, void* userparam, gate_enumint_t flags)
{
    gate_result_t ret = GATE_RESULT_FAILED;
    int mib[] = { CTL_KERN, KERN_PROC, KERN_PROC_ALL, 0, sizeof(struct kinfo_proc), 0 };
    unsigned mib_len = sizeof(mib) / sizeof(mib[0]);
    gate_process_infobuffer_t info_buffer;
    char buffer[8192 + 4096];
    char* ptr_buffer = &buffer[0];
    size_t bufferlen = 0;
    struct kinfo_proc* procs;
    size_t procs_count;

    do
    {
        /* retrieve required buffer len */
        if (0 != sysctl(mib, mib_len, NULL, &bufferlen, NULL, 0))
        {
            GATE_DEBUG_TRACE_PLATFORM_ERROR("sysctl() failed");
            ret = GATE_RESULT_NOTAVAILABLE;
            break;
        }

        if (bufferlen > sizeof(buffer))
        {
            ptr_buffer = gate_mem_alloc(bufferlen);
            if (ptr_buffer == NULL)
            {
                GATE_DEBUG_TRACE_MSG_VALUE("Out of memory", bufferlen);
                ret = GATE_RESULT_OUTOFMEMORY;
                break;
            }
        }

        procs_count = bufferlen / sizeof(struct kinfo_proc);
        mib[5] = procs_count;

        if (0 != sysctl(mib, mib_len, ptr_buffer, &bufferlen, NULL, 0))
        {
            GATE_DEBUG_TRACE_PLATFORM_ERROR("sysctl() failed");
            ret = GATE_RESULT_FAILED;
            break;
        }

        procs = (struct kinfo_proc*)ptr_buffer;
        while (procs_count-- > 0)
        {
            gate_result_t result = load_process_infobuffer(&info_buffer, procs);
            if (GATE_SUCCEEDED(result) && (callback != NULL))
            {
                if (!callback(&info_buffer.process, userparam))
                {
                    break;
                }
            }
            ++procs;
        }
        ret = GATE_RESULT_OK;
    } while (0);

    if ((ptr_buffer != NULL) && (ptr_buffer != &buffer[0]))
    {
        /* free allocated memory */
        gate_mem_dealloc(ptr_buffer);
    }
    return ret;
}

#elif defined(GATE_SYS_NETBSD)

static gate_result_t netbsd_process_enum(gate_process_enum_callback_t callback, void* userparam, gate_enumint_t flags)
{
    gate_result_t ret = GATE_RESULT_FAILED;
    kvm_t* kvm = NULL;
    struct kinfo_proc2* procs = NULL;
    int procs_count = 0;
    int ndx;
    gate_process_infobuffer_t infobuffer;
    char errbuf[_POSIX2_LINE_MAX];

    do
    {
        ret = load_kvm_library();
        GATE_BREAK_IF_FAILED(ret);

        kvm = kvm_open_func(NULL, NULL, NULL, O_RDONLY, errbuf);
        if (kvm == NULL)
        {
            GATE_DEBUG_TRACE("kvm_open() failed");
            errbuf[_POSIX2_LINE_MAX - 1] = 0;
            GATE_DEBUG_TRACE(errbuf);
            ret = GATE_RESULT_NOTAVAILABLE;
            break;
        }

        procs = kvm_getproc2_func(kvm, KERN_PROC_ALL, 0, sizeof(struct kinfo_proc2), &procs_count);
        if ((procs == NULL) || (procs_count == 0))
        {
            /* finding no processes is an error, we should at least find our own process */
            GATE_DEBUG_TRACE("kvm_getprocs(KERN_PROC_ALL) failed");
            ret = GATE_RESULT_FAILED;<--- Variable 'ret' is reassigned a value before the old one has been used.
        }

        /* success case: iterator over infos */
        ret = GATE_RESULT_OK;<--- Variable 'ret' is reassigned a value before the old one has been used.
        for (ndx = 0; ndx != procs_count; ++ndx, ++procs)
        {
            gate_result_t result = load_process_infobuffer(&infobuffer, procs);
            if (GATE_FAILED(result))
            {
                continue;
            }
            if (callback)
            {
                if (!callback(&infobuffer.process, userparam))
                {
                    break;
                }
            }
        }
    } while (0);

    if (kvm != NULL)
    {
        kvm_close_func(kvm);
    }
    return ret;
}

#endif

#else /* Linux PROCFS */

gate_result_t gate_process_getinfo(gate_process_infobuffer_t* infobuffer, gate_process_id_t proc_id, gate_enumint_t flags)
{
    gate_result_t ret = GATE_RESULT_NOTAVAILABLE;
    gate_size_t namepos;
    gate_procfs_proc_stat_t proc_stat;
    gate_procfs_memstat_t mem_stat;
    gate_uint64_t page_size;
    gate_uint64_t ticks_per_second;
    gate_uint64_t starttime_after_boot_ms;
    gate_int64_t system_up_time_ms;
    gate_posix_user_info_t user_info;
    gate_result_t result;
    int proc_uid;

    gate_mem_clear(infobuffer, sizeof(gate_process_infobuffer_t));

    infobuffer->process.pid = proc_id;

    if (gate_procfs_get_exe_path(proc_id, infobuffer->pathbuffer, sizeof(infobuffer->pathbuffer)))
    {
        infobuffer->process.path = infobuffer->pathbuffer;
        ret = GATE_RESULT_OK;
    }

    if (gate_procfs_load_proc_stat(proc_id, &proc_stat))
    {
        infobuffer->process.parent_pid = proc_stat.ppid;

        if (GATE_FLAG_ENABLED(flags, GATE_PROCESS_ENUM_TIMES))
        {
            ticks_per_second = (gate_uint64_t)sysconf(_SC_CLK_TCK);
            starttime_after_boot_ms = (gate_int64_t)proc_stat.starttime * 1000ULL / ticks_per_second;

            system_up_time_ms = gate_procfs_get_uptime_ms();

            infobuffer->process.uptime = system_up_time_ms - starttime_after_boot_ms;
            if (infobuffer->process.uptime < 0) infobuffer->process.uptime = 0;
            infobuffer->process.cputime = (gate_uint64_t)(proc_stat.utime + proc_stat.stime) * 1000ULL / ticks_per_second;
            if (infobuffer->process.cputime < 0) infobuffer->process.cputime = 0;
        }
        ret = GATE_RESULT_OK;
    }

    if (GATE_FLAG_ENABLED(flags, GATE_PROCESS_ENUM_NAME))
    {
        if (infobuffer->process.path != NULL)
        {
            namepos = gate_str_char_pos_last(infobuffer->process.path, gate_str_length(infobuffer->process.path), '/');
            if (namepos != GATE_STR_NPOS)
            {
                infobuffer->process.name = &infobuffer->process.path[namepos + 1];
            }
        }
        if (infobuffer->process.name == NULL)
        {
            gate_str_print_uint64(infobuffer->namebuffer, sizeof(infobuffer->namebuffer), proc_id);
            infobuffer->process.name = infobuffer->namebuffer;
        }
    }

    if (GATE_FLAG_ENABLED(flags, GATE_PROCESS_ENUM_OWNER))
    {
        if (gate_procfs_get_exe_owner(proc_id, &proc_uid, NULL))
        {
            result = gate_posix_get_user_info(proc_uid, &user_info);
            if (GATE_SUCCEEDED(result))
            {
                gate_str_print_text(infobuffer->ownerbuffer, sizeof(infobuffer->ownerbuffer),
                    user_info.name, gate_str_length(user_info.name));
                infobuffer->process.owner = infobuffer->ownerbuffer;
            }
        }
    }

    if (GATE_FLAG_ENABLED(flags, GATE_PROCESS_ENUM_MEMORY))
    {
        if (gate_procfs_get_memstat(proc_id, &mem_stat))
        {
            page_size = sysconf(_SC_PAGESIZE);
            if (page_size == 0)
            {
                page_size = 4096;
            }
            infobuffer->process.memory_used = (gate_uint64_t)mem_stat.resident * page_size;
        }
    }

    if (GATE_FLAG_ENABLED(flags, GATE_PROCESS_ENUM_RESOURCES))
    {
        infobuffer->process.resources = gate_procfs_get_open_fds(proc_id);
        if (infobuffer->process.resources < 0) infobuffer->process.resources = 0;
    }

    return ret;
}

#endif

gate_result_t gate_process_enum(gate_process_enum_callback_t callback, void* userparam, gate_enumint_t flags)
{
    gate_result_t ret = GATE_RESULT_FAILED;
    DIR* dir;

#if defined(GATE_SYS_DARWIN)
    ret = darwin_process_enum(callback, userparam, flags);
#elif defined(GATE_SYS_BSD)

#if defined(GATE_SYS_FREEBSD)
    ret = freebsd_process_enum(callback, userparam, flags);
#elif defined(GATE_SYS_OPENBSD)
    ret = openbsd_process_enum(callback, userparam, flags);
#elif defined(GATE_SYS_NETBSD)
    ret = netbsd_process_enum(callback, userparam, flags);
#endif

    if (GATE_SUCCEEDED(ret))
    {
        /* we have a result, we are done */
        return GATE_RESULT_OK;
    }
    /* otherwise, continue with linux/procfs approach */

#endif /* GATE_SYS_BSD */

    /* linux procfs: */
    dir = opendir("/proc");

    if (dir != NULL)
    {
        struct dirent* entry;
        while (NULL != (entry = readdir(dir)))
        {
            gate_process_infobuffer_t proc_data;
            gate_uint64_t procid = 0;
            gate_size_t entrylen = gate_str_length(entry->d_name);
            gate_size_t parselen = gate_str_parse_uint64(entry->d_name, entrylen, &procid);
            if (parselen == entrylen)
            {
                /* seems to be a numeric process id */
                ret = gate_process_getinfo(&proc_data, (gate_process_id_t)procid, flags);
                if (GATE_SUCCEEDED(ret))
                {
                    if (false == callback(&proc_data.process, userparam))
                    {
                        break;
                    }
                }
            }
        }
        closedir(dir);
        ret = GATE_RESULT_OK;
    }
    return ret;
}


gate_result_t gate_process_start(gate_string_t const* executablepath,
    gate_string_t const* args, gate_size_t argcount,
    gate_string_t const* workdir, gate_string_t const* envvars, gate_size_t envvarcount, gate_enumint_t flags,
    gate_process_handle_t* result_handle,
    gate_process_id_t* result_pid,
    gate_process_stream_t** result_stream
)
{
    return gate_process_start_ex(executablepath, args, argcount,
        workdir, envvars, envvarcount, flags,
        NULL, NULL, NULL,
        result_handle, result_pid, result_stream);
}


static char* gate_process_build_argarray(gate_string_t const* args, gate_size_t argcount, char** buffer, gate_size_t maxargs)
{
    char* ret;
    char* ptr;
    gate_size_t ndx;
    gate_size_t byte_size = 0;
    gate_size_t len;
    gate_size_t buffer_ndx = 0;

    if (argcount >= maxargs) argcount = maxargs - 1;

    for (ndx = 0; ndx < argcount; ++ndx)
    {
        byte_size += args[ndx].length + 1;
    }
    byte_size += 2;

    ret = gate_mem_alloc(byte_size);
    if (ret != NULL)
    {
        ptr = ret;
        for (ndx = 0; ndx < argcount; ++ndx)
        {
            len = gate_str_print_text(ptr, args[ndx].length + 1, args[ndx].str, args[ndx].length);
            buffer[buffer_ndx++] = ptr;
            ptr += (len + 1);
        }
        ptr[0] = 0;
        buffer[buffer_ndx] = NULL;
    }
    return ret;
}

static int gate_get_open_max(void)
{
#ifdef  OPEN_MAX
    return OPEN_MAX;
#else
    static volatile int cached_max = 0;
    long cnf_open_max;
    if (cached_max == 0)
    {
        cnf_open_max = sysconf(_SC_OPEN_MAX);
        if (cnf_open_max <= 0)
        {
            cached_max = 1024;
        }
        else
        {
            cached_max = (int)cnf_open_max;
        }
    }
    return cached_max;
#endif
}


static void close_private_file_descriptor(gate_bool_t exclude_inheritable_fds, int preserved_fd)
{
    int inheritable_fds[1024];
    gate_size_t inheritable_count = 0;
    int fd_max = gate_get_open_max();
    int fd;
    size_t index;
    gate_bool_t exclude_fd = false;

    inheritable_fds[0] = preserved_fd;
    inheritable_count = 1;

    if (exclude_inheritable_fds)
    {
        inheritable_count = gate_posix_get_inheritable_fds(
            &inheritable_fds[1], sizeof(inheritable_fds) / sizeof(inheritable_fds[0]) - 1);
        ++inheritable_count;
    }


    for (fd = STDERR_FILENO + 1; fd < fd_max; ++fd)
    {
        exclude_fd = false;
        for (index = 0; index != inheritable_count; ++index)
        {
            if (fd == inheritable_fds[index])
            {
                exclude_fd = true;
                break;
            }
        }
        if (!exclude_fd)
        {
            gate_posix_close(fd);
        }
    }
}

static gate_result_t gate_process_switch_user(char const* username)
{
    gate_result_t ret;
    gate_posix_user_info_t user_info;
    int result;

    do
    {
        ret = gate_posix_resolve_user_info(username, &user_info);
        GATE_BREAK_IF_FAILED(ret);

        result = initgroups(user_info.name, user_info.gid);
        if (-1 == result)
        {
            GATE_DEBUG_TRACE_MSG_VALUE("initgroups failed()", gate_posix_errno(NULL));
        }

        result = setgid(user_info.gid);
        if (result != 0)
        {
            GATE_DEBUG_TRACE_MSG_VALUE("setgid failed()", gate_posix_errno(NULL));
            ret = gate_platform_print_last_error(NULL, 0);
            break;
        }

        result = setuid(user_info.uid);
        if (result != 0)
        {
            GATE_DEBUG_TRACE_MSG_VALUE("setuid failed()", gate_posix_errno(NULL));
            ret = gate_platform_print_last_error(NULL, 0);
            break;
        }
        ret = GATE_RESULT_OK;
    } while (0);

    return ret;
}

typedef int(*openpty_func_t)(int* amaster, int* aslave, char const* name, struct termios const* termp, struct winsize const* winp);
typedef int(*login_tty_func_t)(int fd);

static openpty_func_t openpty_func;
static login_tty_func_t login_tty_func;

static gate_bool_t are_pty_functions_loaded()
{
    return (openpty_func != NULL) && (login_tty_func != NULL);
}

static gate_bool_t try_load_pty_functions(void* libhandle)
{
    openpty_func = (openpty_func_t)gate_posix_dlsym(libhandle, "openpty");
    login_tty_func = (login_tty_func_t)gate_posix_dlsym(libhandle, "login_tty");
    return are_pty_functions_loaded();
}

static char const* util_libs[] =
{
    "libutil.so",
    "libutil.so.1"
};
static unsigned const util_libs_count = sizeof(util_libs) / sizeof(util_libs[0]);

static void* volatile pty_lib_handle = NULL;

static void close_pty_lib_atexit()
{
    if (NULL != pty_lib_handle)
    {
        void* handle = pty_lib_handle;
        pty_lib_handle = NULL;
        gate_posix_dlclose(handle);
    }
}

static gate_bool_t load_pty_functions()
{
    if (are_pty_functions_loaded())
    {
        return true;
    }

    openpty_func = (openpty_func_t)gate_posix_global_sym("openpty");
    login_tty_func = (login_tty_func_t)gate_posix_global_sym("login_tty");
    if (are_pty_functions_loaded())
    {
        return true;
    }

    unsigned ndx;
    for (ndx = 0; ndx != util_libs_count; ++ndx)
    {
        void* lib_handle = gate_posix_dlopen(util_libs[ndx], RTLD_GLOBAL);
        if (lib_handle)
        {
            if (try_load_pty_functions(lib_handle))
            {
                pty_lib_handle = lib_handle;
                gate_platform_atexit(&close_pty_lib_atexit);
                return true;
            }
            else
            {
                gate_posix_dlclose(lib_handle);
            }
        }
    }
    return false;
}

static gate_result_t gate_process_exec(gate_string_t const* executablepath, gate_string_t const* args, gate_size_t argcount,
    gate_string_t const* workdir, gate_string_t const* envvars, gate_size_t envvarcount, gate_enumint_t flags,
    char const* sessionlocation,
    char const* username, char const* password, int preserved_fd,
    int* ptr_tty_fd,
    int* new_std_in, int* new_std_out, int* new_std_err
)
{
    gate_result_t ret = GATE_RESULT_FAILED;
    int result;
    char* process_args[256];
    char* process_vars[256];
    char  new_work_dir[GATE_MAX_FILEPATH_LENGTH];
    char  exe_path[GATE_MAX_FILEPATH_LENGTH];
    char* process_args_buffer = NULL;
    char* process_vars_buffer = NULL;

    do
    {
        if (!gate_string_is_empty(workdir))
        {
            GATE_STRING_TO_BUFFER(workdir, new_work_dir);
            if (-1 == chdir(new_work_dir))
            {
                ret = GATE_RESULT_INVALIDINPUT;
                break;
            }
        }

        if (!gate_str_is_empty(username))
        {
            ret = gate_process_switch_user(username);
            GATE_BREAK_IF_FAILED(ret);
        }

        if (GATE_FLAG_ENABLED(flags, GATE_PROCESS_START_NEWSESSION))
        {
            result = setsid();
            if (result != 0)
            {
                GATE_DEBUG_TRACE_MSG_VALUE("setsid() failed", gate_posix_errno(NULL));
                ret = GATE_RESULT_FAILED;
                break;
            }
        }

        process_args_buffer = gate_process_build_argarray(args, argcount, &process_args[1], sizeof(process_args) / sizeof(process_args[0]) - 1);
        process_vars_buffer = gate_process_build_argarray(envvars, envvarcount, process_vars, sizeof(process_vars) / sizeof(process_vars[0]));

        GATE_STRING_TO_BUFFER(executablepath, exe_path);
        process_args[0] = exe_path;

        if (ptr_tty_fd)
        {
            /* login to terminal and set STD* to terminal fd */
            if (login_tty_func(*ptr_tty_fd) == -1)
            {
                GATE_DEBUG_TRACE_MSG_VALUE("login_tty() failed", gate_posix_errno(NULL));
                ret = GATE_RESULT_FAILED;
                break;
            }
        }
        else
        {
            /* redirect parent-pipes to STD* fds */
            if (new_std_in)
            {
                dup2(*new_std_in, STDIN_FILENO);
                close(*new_std_in);
            }
            if (new_std_out)
            {
                dup2(*new_std_out, STDOUT_FILENO);
                close(*new_std_out);
            }
            if (new_std_err)
            {
                dup2(*new_std_err, STDERR_FILENO);
                close(*new_std_err);
            }
        }

        close_private_file_descriptor(!GATE_FLAG_ENABLED(flags, GATE_PROCESS_START_NOINHERIT), preserved_fd);

        if (envvars)
        {
            execve(exe_path, process_args, process_vars);
        }
        else
        {
            execv(exe_path, process_args);
        }

        ret = GATE_RESULT_UNKNOWNERROR;

    } while (0);

    if (process_args_buffer)
    {
        gate_mem_dealloc(process_args_buffer);
    }
    if (process_vars_buffer)
    {
        gate_mem_dealloc(process_vars_buffer);
    }
    return ret;
}


#define INVALID_FD (-1)

static void close_valid_fd(int fd)
{
    if (fd != INVALID_FD)
    {
        close(fd);
    }
}

gate_result_t gate_process_start_ex(gate_string_t const* executablepath,
    gate_string_t const* args, gate_size_t argcount,
    gate_string_t const* workdir, gate_string_t const* envvars, gate_size_t envvarcount, gate_enumint_t flags,
    char const* sessionlocation,
    char const* username, char const* password,
    gate_process_handle_t* result_handle,
    gate_process_id_t* result_pid,
    gate_process_stream_t** result_stream
)
{
    gate_result_t ret = GATE_RESULT_FAILED;
    int failpipes[2] = { INVALID_FD, INVALID_FD };
    int std_in_pipe[2] = { INVALID_FD, INVALID_FD };	/* stdin of child process */
    int std_out_pipe[2] = { INVALID_FD, INVALID_FD };	/* stdout of child process */
    int std_err_pipe[2] = { INVALID_FD, INVALID_FD };	/* stderr of child process */
    pid_t process_id = -1;
    int term_master = INVALID_FD;
    int term_slave = INVALID_FD;
    char term_slave_name[1024];
    char const* ptr_term_slave_name = NULL;
    gate_process_stream_t* proc_stream = NULL;

    int status = 0;
    ssize_t readlen;
    ssize_t writelen;
    gate_result_t process_exec_error = 0;

    do
    {
        if (result_stream)
        {
            if (GATE_FLAG_ENABLED(flags, GATE_PROCESS_START_NEWTERMINAL))
            {
                /* child process will run in a pseudo terminal, parent controls master-side */
                if (!load_pty_functions())
                {
                    ret = GATE_RESULT_NOTSUPPORTED;
                    break;
                }
                if (openpty_func(&term_master, &term_slave, term_slave_name, NULL, NULL) == -1)
                {
                    ret = GATE_RESULT_OUTOFRESOURCES;
                    break;
                }
                ptr_term_slave_name = &term_slave_name[0];

                /* parent process read/write ends are set to terminal-master */
                std_in_pipe[1] = term_master;
                std_out_pipe[0] = dup(term_master);
                std_err_pipe[0] = dup(term_master);
                term_master = INVALID_FD;
            }
            else
            {
                /* child process i/o will be directed to pipes controlled by parent */
                if (pipe(std_in_pipe) != 0)
                {
                    ret = GATE_RESULT_OUTOFRESOURCES;
                    break;
                }
                if (pipe(std_out_pipe) != 0)
                {
                    ret = GATE_RESULT_OUTOFRESOURCES;
                    break;
                }
                if (GATE_FLAG_ENABLED(flags, GATE_PROCESS_START_USESTDERR))
                {
                    if (pipe(std_err_pipe) != 0)
                    {
                        ret = GATE_RESULT_OUTOFRESOURCES;
                        break;
                    }
                }
                else
                {
                    std_err_pipe[0] = dup(std_out_pipe[0]);
                    std_err_pipe[1] = dup(std_out_pipe[1]);
                }
            }

            proc_stream = gate_process_stream_create(std_in_pipe[1], std_out_pipe[0], std_err_pipe[0]);
            if (!proc_stream)
            {
                ret = GATE_RESULT_OUTOFMEMORY;
                break;
            }
            /* fds are now handled by stream object */
            std_in_pipe[1] = INVALID_FD;
            std_out_pipe[0] = INVALID_FD;
            std_err_pipe[0] = INVALID_FD;
        }

        if (pipe(failpipes) != 0)
        {
            ret = GATE_RESULT_OUTOFRESOURCES;
            break;
        }

        process_id = fork();
        if (process_id == -1)
        {
            /* fork has failed */
            ret = GATE_RESULT_EXECUTIONFAILED;
            break;
        }

        if (process_id == 0)
        {
            /* child process */
            close(failpipes[0]);	/* close read descriptor of fail-detector-pipe */
            failpipes[0] = INVALID_FD;
            fcntl(failpipes[1], F_SETFD, FD_CLOEXEC);	/* auto-close on-exec on write descriptor of fail-detector-pipe */

            process_exec_error = gate_process_exec(
                executablepath, args, argcount, workdir, envvars, envvarcount, flags,
                sessionlocation, username, password,
                failpipes[1], 										/* exclude failpipe from auto-close */
                (term_slave != INVALID_FD) ? &term_slave : NULL,	/* use terminal-slave fd if available */
                result_stream ? &std_in_pipe[0] : NULL, 			/* redirect std-in */
                result_stream ? &std_out_pipe[1] : NULL, 			/* redirect std-out */
                result_stream ? &std_err_pipe[1] : NULL				/* redirect std-err */
            );

            writelen = write(failpipes[1], &process_exec_error, sizeof(process_exec_error));
            _exit(GATE_RESULT_TO_EXITCODE(process_exec_error));
            ret = GATE_RESULT_UNKNOWNERROR;
            break;
        }

        /* parent process */
        close_valid_fd(term_slave);
        term_slave = INVALID_FD;

        close(failpipes[1]);	/* close write descriptor of fail-detector-pipe*/
        failpipes[1] = INVALID_FD;

        readlen = read(failpipes[0], &process_exec_error, sizeof(process_exec_error));
        close(failpipes[0]);
        failpipes[0] = INVALID_FD;

        if (readlen > 0)
        {
            /* child process has failed to prepare exec */
            ret = process_exec_error;
        }
        else
        {
            /* when reading from 'failpipe' fails, then everything seems to be OK */

            if (result_stream)
            {
                *result_stream = proc_stream;
                if (proc_stream)
                {
                    ((gate_process_stream_impl_t*)proc_stream)->target_pid = process_id;
                    gate_object_retain(proc_stream);
                }
            }

            if (result_pid != NULL)
            {
                *result_pid = (gate_process_id_t)process_id;
            }
            if (result_handle != NULL)
            {
                *result_handle = (gate_process_handle_t)(gate_intptr_t)process_id;
                process_id = 0; /* protect process_id from being cleaned up */
            }

            ret = GATE_RESULT_OK;
        }
    } while (0);

    if (process_id > 0)
    {
        /* detach process */
        waitpid(process_id, &status, WNOHANG);
    }

    close_valid_fd(failpipes[1]);
    close_valid_fd(failpipes[0]);
    close_valid_fd(std_in_pipe[1]);
    close_valid_fd(std_in_pipe[0]);
    close_valid_fd(std_out_pipe[1]);
    close_valid_fd(std_out_pipe[0]);
    close_valid_fd(std_err_pipe[1]);
    close_valid_fd(std_err_pipe[0]);
    close_valid_fd(term_master);
    close_valid_fd(term_slave);

    if (proc_stream)
    {
        gate_object_release(proc_stream);
    }

    return ret;
}
gate_result_t gate_process_close(gate_process_handle_t* handle)
{
    gate_result_t ret;
    pid_t pid;
    int status;
    pid_t result;

    if (!handle || (*handle == GATE_PROCESS_HANDLE_INVALID))
    {
        ret = GATE_RESULT_OK;
    }
    else
    {
        pid = (pid_t)(gate_intptr_t)*handle;
        result = waitpid(pid, &status, WNOHANG);
        if (result == -1)
        {
            ret = GATE_RESULT_FAILED;
        }
        else
        {
            *handle = GATE_PROCESS_HANDLE_INVALID;
            ret = GATE_RESULT_OK;
        }
    }

    return ret;
}
gate_result_t gate_process_get_exitcode(gate_process_handle_t* handle, int* exitcode)
{
    gate_result_t ret = GATE_RESULT_FAILED;
    pid_t pid;
    siginfo_t si = GATE_INIT_EMPTY;
    int result;
    int status;<--- Unused variable: status
    gate_timecounter_t tcbegin, tcnow;
    gate_int64_t timediff;
    gate_int64_t timeoutus;
    gate_uint32_t sleepcounter;

    if (!handle || (*handle == GATE_PROCESS_HANDLE_INVALID))
    {
        return GATE_RESULT_INVALIDSTATE;
    }

    pid = (pid_t)(gate_intptr_t)*handle;

#if defined(GATE_SYS_OPENBSD)
    result = waitpid(pid, &status, WNOHANG);
    if (-1 == result)
    {
        return GATE_RESULT_FAILED;
    }
    if (!WIFEXITED(status))
    {
        return GATE_RESULT_INVALIDSTATE;
    }
    if (exitcode)
    {
        *exitcode = WEXITSTATUS(status);
    }
    *handle = GATE_PROCESS_HANDLE_INVALID;
    return GATE_RESULT_OK;
#else
    result = waitid(P_PID, pid, &si, WEXITED | WNOWAIT | WNOHANG);
    if (result != 0)
    {
        return GATE_RESULT_NOTAVAILABLE;
    }
    if (si.si_pid != pid)
    {
        return GATE_RESULT_NOTAVAILABLE;
    }
    if (exitcode)
    {
        *exitcode = si.si_status;
    }
    return GATE_RESULT_OK;
#endif
}

gate_result_t gate_process_wait(gate_process_handle_t* handle, gate_uint32_t timeoutms)
{
    gate_result_t ret = GATE_RESULT_FAILED;
    pid_t pid;
    siginfo_t si;
    int result;
    int status;
    gate_timecounter_t tcbegin, tcnow;
    gate_int64_t timediff;
    gate_int64_t timeoutus;
    gate_uint32_t sleepcounter;

    if (!handle || (*handle == GATE_PROCESS_HANDLE_INVALID))
    {
        return GATE_RESULT_INVALIDSTATE;
    }

    pid = (pid_t)(gate_intptr_t)*handle;

    if (timeoutms == GATE_PROCESS_WAIT_INFINITE)
    {
#if defined(GATE_SYS_OPENBSD)
        result = waitpid(pid, &status, 0);
        *handle = GATE_PROCESS_HANDLE_INVALID;
#else
        result = waitid(P_PID, pid, &si, WEXITED | WNOWAIT);
#endif
        if (result == 0)
        {
            ret = GATE_RESULT_OK;
        }
        else
        {
            gate_posix_errno(&ret);
        }
    }
    else
    {
        if (GATE_SUCCEEDED(gate_timecounter_now(&tcbegin)))
        {
            ret = GATE_RESULT_TIMEOUT;
            sleepcounter = 0;
            timeoutus = (gate_int64_t)timeoutms * 1000LL;
            do
            {
#if defined(GATE_SYS_OPENBSD)
                result = waitpid(pid, &status, WNOHANG);
                *handle = GATE_PROCESS_HANDLE_INVALID;
#else
                result = waitid(P_PID, pid, &si, WEXITED | WNOHANG | WNOWAIT);
#endif
                if (result == 0)
                {
                    if (si.si_pid == pid)
                    {
                        if ((si.si_code == CLD_KILLED) || (si.si_code == CLD_EXITED))
                        {
                            ret = GATE_RESULT_OK;
                            break;
                        }
                    }
                }

                {
                    /* reduce long-time polling */
                    gate_thread_sleep((sleepcounter));
                    if (sleepcounter < 100)
                    {
                        ++sleepcounter;
                    }
                }

                if (GATE_FAILED(gate_timecounter_now(&tcnow)))
                {
                    break;
                }
                timediff = gate_timecounter_diff(tcnow, tcbegin);
            } while (timediff < timeoutus);
        }
    }
    return ret;
}
gate_result_t gate_process_wait_pid(gate_process_id_t pid, gate_uint32_t timeoutms)
{
    return GATE_RESULT_NOTIMPLEMENTED;
}
gate_result_t gate_process_terminate(gate_process_handle_t* handle, gate_bool_t system_request)
{
    gate_process_id_t pid;
    if (!handle || (*handle == GATE_PROCESS_HANDLE_INVALID))
    {
        return GATE_RESULT_INVALIDSTATE;
    }
    pid = (gate_process_id_t)(gate_intptr_t)*handle;
    return gate_process_terminate_pid(pid, system_request);
}
gate_result_t gate_process_terminate_pid(gate_process_id_t pid, gate_bool_t system_request)
{
    gate_result_t ret = GATE_RESULT_FAILED;
    pid_t proc_id = (pid_t)pid;
    if (-1 == kill(proc_id, system_request ? SIGTERM : SIGINT))
    {
        gate_posix_errno(&ret);
    }
    else
    {
        ret = GATE_RESULT_OK;
    }
    return ret;
}
gate_result_t gate_process_kill(gate_process_handle_t* handle)
{
    gate_process_id_t pid;
    if (!handle || (*handle == GATE_PROCESS_HANDLE_INVALID))
    {
        return GATE_RESULT_INVALIDSTATE;
    }
    pid = (gate_process_id_t)(gate_intptr_t)*handle;
    return gate_process_kill_pid(pid);
}
gate_result_t gate_process_kill_pid(gate_process_id_t pid)
{
    gate_result_t ret = GATE_RESULT_FAILED;
    pid_t proc_id = (pid_t)pid;
    if (-1 == kill(proc_id, SIGKILL))
    {
        gate_posix_errno(&ret);
    }
    else
    {
        ret = GATE_RESULT_OK;
    }
    return ret;
}
gate_result_t gate_process_suspend(gate_process_handle_t* handle)
{
    gate_process_id_t pid;
    if (!handle || (*handle == GATE_PROCESS_HANDLE_INVALID))
    {
        return GATE_RESULT_INVALIDSTATE;
    }
    pid = (gate_process_id_t)(gate_intptr_t)*handle;
    return gate_process_suspend_pid(pid);
}
gate_result_t gate_process_suspend_pid(gate_process_id_t pid)
{
    gate_result_t ret = GATE_RESULT_FAILED;
    pid_t proc_id = (pid_t)pid;
    if (-1 == kill(proc_id, SIGSTOP))
    {
        gate_posix_errno(&ret);
    }
    else
    {
        ret = GATE_RESULT_OK;
    }
    return ret;
}
gate_result_t gate_process_resume(gate_process_handle_t* handle)
{
    gate_process_id_t pid;
    if (!handle || (*handle == GATE_PROCESS_HANDLE_INVALID))
    {
        return GATE_RESULT_INVALIDSTATE;
    }
    pid = (gate_process_id_t)(gate_intptr_t)*handle;
    return gate_process_resume_pid(pid);
}
gate_result_t gate_process_resume_pid(gate_process_id_t pid)
{
    gate_result_t ret = GATE_RESULT_FAILED;
    pid_t proc_id = (pid_t)pid;
    if (-1 == kill(proc_id, SIGCONT))
    {
        gate_posix_errno(&ret);
    }
    else
    {
        ret = GATE_RESULT_OK;
    }
    return ret;
}

#endif /* GATE_SYS_POSIX */