summaryrefslogtreecommitdiff
path: root/doc/ref/posix.texi
blob: 601c337477b1e168c93bd70dc4a1009859c80859 (plain)
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
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
@c -*-texinfo-*-
@c This is part of the GNU Guile Reference Manual.
@c Copyright (C)  1996, 1997, 2000, 2001, 2002, 2003, 2004, 2006, 2007,
@c   2008, 2009, 2010, 2011, 2012, 2013, 2014, 2017, 2021 Free Software Foundation, Inc.
@c Copyright (C)  2021 Maxime Devos <maximedevos@telenet.be>
@c See the file guile.texi for copying conditions.

@node POSIX
@section @acronym{POSIX} System Calls and Networking
@cindex POSIX

@menu
* Conventions::                 Conventions employed by the POSIX interface.
* Ports and File Descriptors::  Scheme ``ports'' and Unix file descriptors
                                  have different representations.
* File System::                 stat, chown, chmod, etc.
* User Information::            Retrieving a user's GECOS (/etc/passwd) entry.
* Time::                        gettimeofday, localtime, strftime, etc.
* Runtime Environment::         Accessing and modifying Guile's environment.
* Processes::                   getuid, getpid, etc.
* Signals::                     sigaction, kill, pause, alarm, setitimer, etc.
* Terminals and Ptys::          ttyname, tcsetpgrp, etc.
* Pipes::                       Communicating data between processes.
* Networking::                  gethostbyaddr, getnetent, socket, bind, listen.
* System Identification::       Obtaining information about the system.
* Locales::                     setlocale, etc.
* Encryption::
@end menu

@node Conventions
@subsection @acronym{POSIX} Interface Conventions

These interfaces provide access to operating system facilities.
They provide a simple wrapping around the underlying C interfaces
to make usage from Scheme more convenient.  They are also used
to implement the Guile port of scsh (@pxref{The Scheme shell (scsh)}).

Generally there is a single procedure for each corresponding Unix
facility.  There are some exceptions, such as procedures implemented for
speed and convenience in Scheme with no primitive Unix equivalent,
e.g.@: @code{copy-file}.

The interfaces are intended as far as possible to be portable across
different versions of Unix.  In some cases procedures which can't be
implemented on particular systems may become no-ops, or perform limited
actions.  In other cases they may throw errors.

General naming conventions are as follows:

@itemize @bullet
@item
The Scheme name is often identical to the name of the underlying Unix
facility.
@item
Underscores in Unix procedure names are converted to hyphens.
@item
Procedures which destructively modify Scheme data have exclamation
marks appended, e.g., @code{recv!}.
@item
Predicates (returning only @code{#t} or @code{#f}) have question marks
appended, e.g., @code{access?}.
@item
Some names are changed to avoid conflict with dissimilar interfaces
defined by scsh, e.g., @code{primitive-fork}.
@item
Unix preprocessor names such as @code{EPERM} or @code{R_OK} are converted
to Scheme variables of the same name (underscores are not replaced
with hyphens).
@end itemize

Unexpected conditions are generally handled by raising exceptions.
There are a few procedures which return a special value if they don't
succeed, e.g., @code{getenv} returns @code{#f} if it the requested
string is not found in the environment.  These cases are noted in
the documentation.

For ways to deal with exceptions, see @ref{Exceptions}.

@cindex @code{errno}
Errors which the C library would report by returning a null pointer or
through some other means are reported by raising a @code{system-error}
exception with @code{scm-error} (@pxref{Error Reporting}).  The
@var{data} parameter is a list containing the Unix @code{errno} value
(an integer).  For example,

@example
(define (my-handler key func fmt fmtargs data)
  (display key) (newline)
  (display func) (newline)
  (apply format #t fmt fmtargs) (newline)
  (display data) (newline))

(catch 'system-error
  (lambda () (dup2 -123 -456))
  my-handler)

@print{}
system-error
dup2
Bad file descriptor
(9)
@end example


@sp 1
@defun system-error-errno arglist
@cindex @code{errno}
Return the @code{errno} value from a list which is the arguments to an
exception handler.  If the exception is not a @code{system-error},
then the return is @code{#f}.  For example,

@example
(catch
 'system-error
 (lambda ()
   (mkdir "/this-ought-to-fail-if-I'm-not-root"))
 (lambda stuff
   (let ((errno (system-error-errno stuff)))
     (cond
      ((= errno EACCES)
       (display "You're not allowed to do that."))
      ((= errno EEXIST)
       (display "Already exists."))
      (#t
       (display (strerror errno))))
     (newline))))
@end example
@end defun


@node Ports and File Descriptors
@subsection Ports and File Descriptors
@cindex file descriptor

Conventions generally follow those of scsh, @ref{The Scheme shell (scsh)}.

Each open file port has an associated operating system file descriptor.
File descriptors are generally not useful in Scheme programs; however
they may be needed when interfacing with foreign code and the Unix
environment.

A file descriptor can be extracted from a port and a new port can be
created from a file descriptor.  However a file descriptor is just an
integer and the garbage collector doesn't recognize it as a reference
to the port.  If all other references to the port were dropped, then
it's likely that the garbage collector would free the port, with the
side-effect of closing the file descriptor prematurely.

To assist the programmer in avoiding this problem, each port has an
associated @dfn{revealed count} which can be used to keep track of how many
times the underlying file descriptor has been stored in other places.
If a port's revealed count is greater than zero, the file descriptor
will not be closed when the port is garbage collected.  A programmer
can therefore ensure that the revealed count will be greater than
zero if the file descriptor is needed elsewhere.

For the simple case where a file descriptor is ``imported'' once to become
a port, it does not matter if the file descriptor is closed when the
port is garbage collected.  There is no need to maintain a revealed
count.  Likewise when ``exporting'' a file descriptor to the external
environment, setting the revealed count is not required provided the
port is kept open (i.e., is pointed to by a live Scheme binding) while
the file descriptor is in use.

To correspond with traditional Unix behaviour, three file descriptors
(0, 1, and 2) are automatically imported when a program starts up and
assigned to the initial values of the current/standard input, output,
and error ports, respectively.  The revealed count for each is
initially set to one, so that dropping references to one of these
ports will not result in its garbage collection: it could be retrieved
with @code{fdopen} or @code{fdes->ports}.

Guile's ports can be buffered.  This means that writing a byte to a file
port goes to the internal buffer first, and only when the buffer is full
(or the user invokes @code{force-output} on the port) is the data
actually written to the file descriptor.  Likewise on input, bytes are
read in from the file descriptor in blocks and placed in a buffer.
Reading a character via @code{read-char} first goes to the buffer,
filling it as needed.  Usually read buffering is more or less
transparent, but write buffering can sometimes cause writes to be
delayed unexpectedly, if you forget to call @code{force-output}.
@xref{Buffering}, for more on how to control port buffers.

Note however that some procedures (e.g., @code{recv!}) will accept ports
as arguments, but will actually operate directly on the file descriptor
underlying the port.  Any port buffering is ignored, including the
buffer which implements @code{peek-char} and @code{unread-char}.

@deffn {Scheme Procedure} port-revealed port
@deffnx {C Function} scm_port_revealed (port)
Return the revealed count for @var{port}.
@end deffn

@deffn {Scheme Procedure} set-port-revealed! port rcount
@deffnx {C Function} scm_set_port_revealed_x (port, rcount)
Sets the revealed count for a @var{port} to @var{rcount}.
The return value is unspecified.
@end deffn

@deffn {Scheme Procedure} fileno port
@deffnx {C Function} scm_fileno (port)
Return the integer file descriptor underlying @var{port}.  Does
not change its revealed count.
@end deffn

@deffn {Scheme Procedure} port->fdes port
Returns the integer file descriptor underlying @var{port}.  As a
side effect the revealed count of @var{port} is incremented.
@end deffn

@deffn {Scheme Procedure} fdopen fdes modes
@deffnx {C Function} scm_fdopen (fdes, modes)
Return a new port based on the file descriptor @var{fdes}.  Modes are
given by the string @var{modes}.  The revealed count of the port is
initialized to zero.  The @var{modes} string is the same as that
accepted by @code{open-file} (@pxref{File Ports, open-file}).
@end deffn

@deffn {Scheme Procedure} fdes->ports fdes
@deffnx {C Function} scm_fdes_to_ports (fdes)
Return a list of existing ports which have @var{fdes} as an
underlying file descriptor, without changing their revealed
counts.
@end deffn

@deffn {Scheme Procedure} fdes->inport fdes
Returns an existing input port which has @var{fdes} as its underlying file
descriptor, if one exists, and increments its revealed count.
Otherwise, returns a new input port with a revealed count of 1.
@end deffn

@deffn {Scheme Procedure} fdes->outport fdes
Returns an existing output port which has @var{fdes} as its underlying file
descriptor, if one exists, and increments its revealed count.
Otherwise, returns a new output port with a revealed count of 1.
@end deffn

@deffn {Scheme Procedure} primitive-move->fdes port fdes
@deffnx {C Function} scm_primitive_move_to_fdes (port, fdes)
Moves the underlying file descriptor for @var{port} to the integer
value @var{fdes} without changing the revealed count of @var{port}.
Any other ports already using this descriptor will be automatically
shifted to new descriptors and their revealed counts reset to zero.
The return value is @code{#f} if the file descriptor already had the
required value or @code{#t} if it was moved.
@end deffn

@deffn {Scheme Procedure} move->fdes port fdes
Moves the underlying file descriptor for @var{port} to the integer
value @var{fdes} and sets its revealed count to one.  Any other ports
already using this descriptor will be automatically
shifted to new descriptors and their revealed counts reset to zero.
The return value is unspecified.
@end deffn

@deffn {Scheme Procedure} release-port-handle port
Decrements the revealed count for a port.
@end deffn

@deffn {Scheme Procedure} fsync port_or_fd
@deffnx {C Function} scm_fsync (port_or_fd)
Copies any unwritten data for the specified output file descriptor to disk.
If @var{port_or_fd} is a port, its buffer is flushed before the underlying
file descriptor is fsync'd.
The return value is unspecified.
@end deffn

@deffn {Scheme Procedure} open path flags [mode]
@deffnx {C Function} scm_open (path, flags, mode)
Open the file named by @var{path} for reading and/or writing.
@var{flags} is an integer specifying how the file should be opened.
@var{mode} is an integer specifying the permission bits of the file,
if it needs to be created, before the umask (@pxref{Processes}) is
applied.  The default is 666 (Unix itself has no default).

@var{flags} can be constructed by combining variables using @code{logior}.
Basic flags are:

@defvar O_RDONLY
Open the file read-only.
@end defvar
@defvar O_WRONLY
Open the file write-only.
@end defvar
@defvar O_RDWR
Open the file read/write.
@end defvar
@defvar O_APPEND
Append to the file instead of truncating.
@end defvar
@defvar O_CREAT
Create the file if it does not already exist.
@end defvar

@xref{File Status Flags,,,libc,The GNU C Library Reference Manual},
for additional flags.
@end deffn

@deffn {Scheme Procedure} open-fdes path flags [mode]
@deffnx {C Function} scm_open_fdes (path, flags, mode)
Similar to @code{open} but return a file descriptor instead of
a port.
@end deffn

@deffn {Scheme Procedure} close fd_or_port
@deffnx {C Function} scm_close (fd_or_port)
Similar to @code{close-port} (@pxref{Ports, close-port}),
but also works on file descriptors.  A side
effect of closing a file descriptor is that any ports using that file
descriptor are moved to a different file descriptor and have
their revealed counts set to zero.
@end deffn

@deffn {Scheme Procedure} close-fdes fd
@deffnx {C Function} scm_close_fdes (fd)
A simple wrapper for the @code{close} system call.  Close file
descriptor @var{fd}, which must be an integer.  Unlike @code{close},
the file descriptor will be closed even if a port is using it.  The
return value is unspecified.
@end deffn

@deffn {Scheme Procedure} pipe [flags]
@deffnx {C Function} scm_pipe ()
@cindex pipe
Return a newly created pipe: a pair of ports which are linked together
on the local machine.  The @acronym{CAR} is the input port and the
@acronym{CDR} is the output port.  Data written (and flushed) to the
output port can be read from the input port.  Pipes are commonly used
for communication with a newly forked child process.  The need to flush
the output port can be avoided by making it unbuffered using
@code{setvbuf} (@pxref{Buffering}).

Optionally, on systems that support it such as GNU/Linux and
GNU/Hurd, @var{flags} can specify a bitwise-or of the following
constants:

@table @code
@item O_CLOEXEC
Mark the returned file descriptors as close-on-exec;
@item O_DIRECT
Create a pipe that performs input/output in ``packet"
mode---see @command{man 2 pipe} for details;
@item O_NONBLOCK
Set the @code{O_NONBLOCK} status flag (non-blocking input and
output) on the file descriptors.
@end table

On systems that do @emph{not} support it, passing a non-zero
@var{flags} value triggers a @code{system-error} exception.

@defvar PIPE_BUF
A write of up to @code{PIPE_BUF} many bytes to a pipe is atomic,
meaning when done it goes into the pipe instantaneously and as a
contiguous block (@pxref{Pipe Atomicity,, Atomicity of Pipe I/O, libc,
The GNU C Library Reference Manual}).
@end defvar

Note that the output port is likely to block if too much data has been
written but not yet read from the input port.  Typically the capacity
is @code{PIPE_BUF} bytes.
@end deffn

The next group of procedures perform a @code{dup2}
system call, if @var{newfd} (an
integer) is supplied, otherwise a @code{dup}.  The file descriptor to be
duplicated can be supplied as an integer or contained in a port.  The
type of value returned varies depending on which procedure is used.

All procedures also have the side effect when performing @code{dup2} that any
ports using @var{newfd} are moved to a different file descriptor and have
their revealed counts set to zero.

@deffn {Scheme Procedure} dup->fdes fd_or_port [fd]
@deffnx {C Function} scm_dup_to_fdes (fd_or_port, fd)
Return a new integer file descriptor referring to the open file
designated by @var{fd_or_port}, which must be either an open
file port or a file descriptor.
@end deffn

@deffn {Scheme Procedure} dup->inport port/fd [newfd]
Returns a new input port using the new file descriptor.
@end deffn

@deffn {Scheme Procedure} dup->outport port/fd [newfd]
Returns a new output port using the new file descriptor.
@end deffn

@deffn {Scheme Procedure} dup port/fd [newfd]
Returns a new port if @var{port/fd} is a port, with the same mode as the
supplied port, otherwise returns an integer file descriptor.
@end deffn

@deffn {Scheme Procedure} dup->port port/fd mode [newfd]
Returns a new port using the new file descriptor.  @var{mode} supplies a
mode string for the port (@pxref{File Ports, open-file}).
@end deffn

@deffn {Scheme Procedure} duplicate-port port modes
Returns a new port which is opened on a duplicate of the file
descriptor underlying @var{port}, with mode string @var{modes}
as for @ref{File Ports, open-file}.  The two ports
will share a file position and file status flags.

Unexpected behaviour can result if both ports are subsequently used
and the original and/or duplicate ports are buffered.
The mode string can include @code{0} to obtain an unbuffered duplicate
port.

This procedure is equivalent to @code{(dup->port @var{port} @var{modes})}.
@end deffn

@deffn {Scheme Procedure} redirect-port old_port new_port
@deffnx {C Function} scm_redirect_port (old_port, new_port)
This procedure takes two ports and duplicates the underlying file
descriptor from @var{old_port} into @var{new_port}.  The
current file descriptor in @var{new_port} will be closed.
After the redirection the two ports will share a file position
and file status flags.

The return value is unspecified.

Unexpected behaviour can result if both ports are subsequently used
and the original and/or duplicate ports are buffered.

This procedure does not have any side effects on other ports or
revealed counts.
@end deffn

@deffn {Scheme Procedure} dup2 oldfd newfd
@deffnx {C Function} scm_dup2 (oldfd, newfd)
A simple wrapper for the @code{dup2} system call.
Copies the file descriptor @var{oldfd} to descriptor
number @var{newfd}, replacing the previous meaning
of @var{newfd}.  Both @var{oldfd} and @var{newfd} must
be integers.
Unlike for @code{dup->fdes} or @code{primitive-move->fdes}, no attempt
is made to move away ports which are using @var{newfd}.
The return value is unspecified.
@end deffn

@deffn {Scheme Procedure} port-for-each proc
@deffnx {C Function} scm_port_for_each (SCM proc)
@deffnx {C Function} scm_c_port_for_each (void (*proc)(void *, SCM), void *data)
Apply @var{proc} to each port in the Guile port table
(FIXME: what is the Guile port table?)
in turn.  The return value is unspecified.  More specifically,
@var{proc} is applied exactly once to every port that exists in the
system at the time @code{port-for-each} is invoked.  Changes to the
port table while @code{port-for-each} is running have no effect as far
as @code{port-for-each} is concerned.

The C function @code{scm_port_for_each} takes a Scheme procedure
encoded as a @code{SCM} value, while @code{scm_c_port_for_each} takes
a pointer to a C function and passes along a arbitrary @var{data}
cookie.
@end deffn

@deffn {Scheme Procedure} fcntl port/fd cmd [value]
@deffnx {C Function} scm_fcntl (object, cmd, value)
Apply @var{cmd} on @var{port/fd}, either a port or file descriptor.
The @var{value} argument is used by the @code{SET} commands described
below, it's an integer value.

Values for @var{cmd} are:

@defvar F_DUPFD
Duplicate the file descriptor, the same as @code{dup->fdes} above
does.
@end defvar

@defvar F_GETFD
@defvarx F_SETFD
Get or set flags associated with the file descriptor.  The only flag
is the following,

@defvar FD_CLOEXEC
``Close on exec'', meaning the file descriptor will be closed on an
@code{exec} call (a successful such call).  For example to set that
flag,

@example
(fcntl port F_SETFD FD_CLOEXEC)
@end example

Or better, set it but leave any other possible future flags unchanged,

@example
(fcntl port F_SETFD (logior FD_CLOEXEC
                            (fcntl port F_GETFD)))
@end example
@end defvar
@end defvar

@defvar F_GETFL
@defvarx F_SETFL
Get or set flags associated with the open file.  These flags are
@code{O_RDONLY} etc described under @code{open} above.

A common use is to set @code{O_NONBLOCK} on a network socket.  The
following sets that flag, and leaves other flags unchanged.

@example
(fcntl sock F_SETFL (logior O_NONBLOCK
                            (fcntl sock F_GETFL)))
@end example
@end defvar

@defvar F_GETOWN
@defvarx F_SETOWN
Get or set the process ID of a socket's owner, for @code{SIGIO} signals.
@end defvar
@end deffn

@deffn {Scheme Procedure} flock file operation
@deffnx {C Function} scm_flock (file, operation)
@cindex file locking
Apply or remove an advisory lock on an open file.
@var{operation} specifies the action to be done:

@defvar LOCK_SH
Shared lock.  More than one process may hold a shared lock
for a given file at a given time.
@end defvar
@defvar LOCK_EX
Exclusive lock.  Only one process may hold an exclusive lock
for a given file at a given time.
@end defvar
@defvar LOCK_UN
Unlock the file.
@end defvar
@defvar LOCK_NB
Don't block when locking.  This is combined with one of the other
operations using @code{logior} (@pxref{Bitwise Operations}).  If
@code{flock} would block an @code{EWOULDBLOCK} error is thrown
(@pxref{Conventions}).
@end defvar

The return value is not specified. @var{file} may be an open
file descriptor or an open file descriptor port.

Note that @code{flock} does not lock files across NFS.
@end deffn

@deffn {Scheme Procedure} select reads writes excepts [secs [usecs]]
@deffnx {C Function} scm_select (reads, writes, excepts, secs, usecs)
This procedure has a variety of uses: waiting for the ability
to provide input, accept output, or the existence of
exceptional conditions on a collection of ports or file
descriptors, or waiting for a timeout to occur.

When an error occurs, this procedure throws a @code{system-error}
exception (@pxref{Conventions, @code{system-error}}).  Note that
@code{select} may return early for other reasons, for example due to
pending interrupts.  @xref{Asyncs}, for more on interrupts.

@var{reads}, @var{writes} and @var{excepts} can be lists or
vectors, with each member a port or a file descriptor.
The value returned is a list of three corresponding
lists or vectors containing only the members which meet the
specified requirement.  The ability of port buffers to
provide input or accept output is taken into account.
Ordering of the input lists or vectors is not preserved.

The optional arguments @var{secs} and @var{usecs} specify the
timeout.  Either @var{secs} can be specified alone, as
either an integer or a real number, or both @var{secs} and
@var{usecs} can be specified as integers, in which case
@var{usecs} is an additional timeout expressed in
microseconds.  If @var{secs} is omitted or is @code{#f} then
select will wait for as long as it takes for one of the other
conditions to be satisfied.

The scsh version of @code{select} differs as follows:
Only vectors are accepted for the first three arguments.
The @var{usecs} argument is not supported.
Multiple values are returned instead of a list.
Duplicates in the input vectors appear only once in output.
An additional @code{select!} interface is provided.
@end deffn

While it is sometimes necessary to operate at the level of file
descriptors, this is an operation whose correctness can only be
considered as part of a whole program.  So for example while the effects
of @code{(string-set! x 34 #\y)} are limited to the bits of code that
can access @var{x}, @code{(close-fdes 34)} mutates the state of the
entire process.  In particular if another thread is using file
descriptor 34 then their state might be corrupted; and another thread
which opens a file might cause file descriptor 34 to be re-used, so that
corruption could manifest itself in a strange way.

@cindex fdes finalizers
@cindex file descriptor finalizers
@cindex finalizers, file descriptor
However when working with file descriptors, it's common to want to
associate information with the file descriptor, perhaps in a side table.
To support this use case and to allow user code to remove an association
when a file descriptor is closed, Guile offers @dfn{fdes finalizers}.

As the name indicates, fdes finalizers are finalizers -- they can run in
response to garbage collection, and they can also run in response to
explicit calls to @code{close-port}, @code{close-fdes}, or the like.  As
such they inherit many of the pitfalls of finalizers: they may be
invoked from concurrent threads, or not at all.  @xref{Foreign Object
Memory Management}, for more on finalizers.

To use fdes finalizers, import their module;

@example
(use-modules (ice-9 fdes-finalizers))
@end example

@deffn {Scheme Procedure} add-fdes-finalizer! fdes finalizer
@deffnx {Scheme Procedure} remove-fdes-finalizer! fdes finalizer
Add or remove a finalizer for @var{fdes}.  A finalizer is a procedure
that is called by Guile when a file descriptor is closed.  The file
descriptor being closed is passed as the one argument to the finalizer.
If a finalizer has been added multiple times to a file descriptor, to
remove it would require that number of calls to
@code{remove-fdes-finalizer!}.

The finalizers added to a file descriptor are called by Guile in an
unspecified order, and their return values are ignored.
@end deffn


@node File System
@subsection File System
@cindex file system

These procedures allow querying and setting file system attributes
(such as owner,
permissions, sizes and types of files); deleting, copying, renaming and
linking files; creating and removing directories and querying their
contents; syncing the file system and creating special files.

@deffn {Scheme Procedure} access? path how
@deffnx {C Function} scm_access (path, how)
Test accessibility of a file under the real UID and GID of the calling
process.  The return is @code{#t} if @var{path} exists and the
permissions requested by @var{how} are all allowed, or @code{#f} if
not.

@var{how} is an integer which is one of the following values, or a
bitwise-OR (@code{logior}) of multiple values.

@defvar R_OK
Test for read permission.
@end defvar
@defvar W_OK
Test for write permission.
@end defvar
@defvar X_OK
Test for execute permission.
@end defvar
@defvar F_OK
Test for existence of the file.  This is implied by each of the other
tests, so there's no need to combine it with them.
@end defvar

It's important to note that @code{access?} does not simply indicate
what will happen on attempting to read or write a file.  In normal
circumstances it does, but in a set-UID or set-GID program it doesn't
because @code{access?} tests the real ID, whereas an open or execute
attempt uses the effective ID.

A program which will never run set-UID/GID can ignore the difference
between real and effective IDs, but for maximum generality, especially
in library functions, it's best not to use @code{access?} to predict
the result of an open or execute, instead simply attempt that and
catch any exception.

The main use for @code{access?} is to let a set-UID/GID program
determine what the invoking user would have been allowed to do,
without the greater (or perhaps lesser) privileges afforded by the
effective ID.  For more on this, see @ref{Testing File Access,,, libc,
The GNU C Library Reference Manual}.
@end deffn

@findex fstat
@deffn {Scheme Procedure} stat object [exception-on-error?]
@deffnx {C Function} scm_stat (object, exception_on_error)
Return an object containing various information about the file
determined by @var{object}.  @var{object} can be a string containing
a file name or a port or integer file descriptor which is open
on a file (in which case @code{fstat} is used as the underlying
system call).

If the optional @var{exception_on_error} argument is true, which
is the default, an exception will be raised if the underlying
system call returns an error, for example if the file is not
found or is not readable. Otherwise, an error will cause
@code{stat} to return @code{#f}.

The object returned by @code{stat} can be passed as a single
parameter to the following procedures, all of which return
integers:

@deffn {Scheme Procedure} stat:dev st
The device number containing the file.
@end deffn
@deffn {Scheme Procedure} stat:ino st
The file serial number, which distinguishes this file from all
other files on the same device.
@end deffn
@deffn {Scheme Procedure} stat:mode st
The mode of the file.  This is an integer which incorporates file type
information and file permission bits.  See also @code{stat:type} and
@code{stat:perms} below.
@end deffn
@deffn {Scheme Procedure} stat:nlink st
The number of hard links to the file.
@end deffn
@deffn {Scheme Procedure} stat:uid st
The user ID of the file's owner.
@end deffn
@deffn {Scheme Procedure} stat:gid st
The group ID of the file.
@end deffn
@deffn {Scheme Procedure} stat:rdev st
Device ID; this entry is defined only for character or block special
files.  On some systems this field is not available at all, in which
case @code{stat:rdev} returns @code{#f}.
@end deffn
@deffn {Scheme Procedure} stat:size st
The size of a regular file in bytes.
@end deffn
@deffn {Scheme Procedure} stat:atime st
The last access time for the file, in seconds.
@end deffn
@deffn {Scheme Procedure} stat:mtime st
The last modification time for the file, in seconds.
@end deffn
@deffn {Scheme Procedure} stat:ctime st
The last modification time for the attributes of the file, in seconds.
@end deffn
@deffn {Scheme Procedure} stat:atimensec st
@deffnx {Scheme Procedure} stat:mtimensec st
@deffnx {Scheme Procedure} stat:ctimensec st
The fractional part of a file's access, modification, or attribute modification
time, in nanoseconds. Nanosecond timestamps are only available on some operating
systems and file systems. If Guile cannot retrieve nanosecond-level timestamps
for a file, these fields will be set to 0.
@end deffn
@deffn {Scheme Procedure} stat:blksize st
The optimal block size for reading or writing the file, in bytes.  On
some systems this field is not available, in which case
@code{stat:blksize} returns a sensible suggested block size.
@end deffn
@deffn {Scheme Procedure} stat:blocks st
The amount of disk space that the file occupies measured in units of
512 byte blocks.  On some systems this field is not available, in
which case @code{stat:blocks} returns @code{#f}.
@end deffn

In addition, the following procedures return the information
from @code{stat:mode} in a more convenient form:

@deffn {Scheme Procedure} stat:type st
A symbol representing the type of file.  Possible values are
@samp{regular}, @samp{directory}, @samp{symlink},
@samp{block-special}, @samp{char-special}, @samp{fifo}, @samp{socket},
and @samp{unknown}.
@end deffn
@deffn {Scheme Procedure} stat:perms st
An integer representing the access permission bits.
@end deffn
@end deffn

@deffn {Scheme Procedure} lstat path
@deffnx {C Function} scm_lstat (path)
Similar to @code{stat}, but does not follow symbolic links, i.e.,
it will return information about a symbolic link itself, not the
file it points to.  @var{path} must be a string.
@end deffn

@deffn {Scheme Procedure} statat dir filename [flags]
@deffnx {C Function} scm_statat dir filename flags
Like @code{stat}, but resolve @var{filename} relative to the directory
referred to by the file port @var{dir} instead.  The optional argument
@var{flags} argument can be @code{AT_SYMLINK_NOFOLLOW}, in which case
@var{filename} will not be dereferenced even if it is a symbolic link.
@end deffn

@deffn {Scheme Procedure} readlink path
@deffnx {C Function} scm_readlink (path)
Return the value of the symbolic link named by @var{path} (a string, or
a port if supported by the system), i.e., the file that the link points
to.

To read a symbolic link represented by a port, the symbolic link must
have been opened with the @code{O_NOFOLLOW} and @code{O_PATH} flags.
@code{(provided? 'readlink-port)} reports whether ports are supported.
@end deffn

@findex fchown
@findex lchown
@deffn {Scheme Procedure} chown object owner group
@deffnx {C Function} scm_chown (object, owner, group)
Change the ownership and group of the file referred to by @var{object}
to the integer values @var{owner} and @var{group}.  @var{object} can
be a string containing a file name or, if the platform supports
@code{fchown} (@pxref{File Owner,,,libc,The GNU C Library Reference
Manual}), a port or integer file descriptor which is open on the file.
The return value is unspecified.

If @var{object} is a symbolic link, either the
ownership of the link or the ownership of the referenced file will be
changed depending on the operating system (lchown is
unsupported at present).  If @var{owner} or @var{group} is specified
as @code{-1}, then that ID is not changed.
@end deffn

@findex fchownat
@deffn {Scheme Procedure} chownat dir name owner group [flags]
@deffnx {C Function} scm_chownat (dir, name, owner, group, flags)
Like @code{chown}, but modify the owner and/or group of
the file named @var{name} in the directory referred to
by the file port @var{dir} instead.  The optional argument
@var{flags} is a bitmask.  If @code{AT_SYMLINK_NOFOLLOW} is
present, then @var{name} will not be dereferenced if it is a
symbolic link.
@end deffn

@findex fchmod
@deffn {Scheme Procedure} chmod object mode
@deffnx {C Function} scm_chmod (object, mode)
Changes the permissions of the file referred to by @var{object}.
@var{object} can be a string containing a file name or a port or integer file
descriptor which is open on a file (in which case @code{fchmod} is used
as the underlying system call).
@var{mode} specifies
the new permissions as a decimal number, e.g., @code{(chmod "foo" #o755)}.
The return value is unspecified.
@end deffn

@deffn {Scheme Procedure} utime object [actime [modtime [actimens [modtimens [flags]]]]]
@deffnx {C Function} scm_utime (object, actime, modtime, actimens, modtimens, flags)
@code{utime} sets the access and modification times for the
file named by @var{object}.  If @var{actime} or @var{modtime} is
not supplied, then the current time is used.  @var{actime} and
@var{modtime} must be integer time values as returned by the
@code{current-time} procedure.

@var{object} must be a file name or a port (if supported by the system).

The optional @var{actimens} and @var{modtimens} are nanoseconds
to add @var{actime} and @var{modtime}. Nanosecond precision is
only supported on some combinations of file systems and operating
systems.
@lisp
(utime "foo" (- (current-time) 3600))
@end lisp
will set the access time to one hour in the past and the
modification time to the current time.

@vindex AT_SYMLINK_NOFOLLOW
Last, @var{flags} may be either @code{0} or the
@code{AT_SYMLINK_NOFOLLOW} constant, to set the time of
@var{object} even if it is a symbolic link.
@end deffn

On GNU/Linux systems, at least when using the Linux kernel 5.10.46,
if @var{object} is a port, it may not be a symbolic link,
even if @code{AT_SYMLINK_NOFOLLOW} is set.  This is either a bug
in Linux or Guile's wrappers.  The exact cause is unclear.

@findex unlink
@deffn {Scheme Procedure} delete-file str
@deffnx {C Function} scm_delete_file (str)
Deletes (or ``unlinks'') the file whose path is specified by
@var{str}.
@end deffn

@findex unlinkat
@deffn {Scheme Procedure} delete-file-at dir str [flags]
@deffnx {C Function} scm_delete_file_at (dir, str, flags)
Like @code{unlink}, but resolve @var{str} relative to the
directory referred to by the file port @var{dir} instead.

The optional @var{flags} argument can be @code{AT_REMOVEDIR},
in which case @code{delete-file-at} will act like @code{rmdir} instead
of @code{delete-file}.  Why doesn't POSIX have a @code{rmdirat} function
for this instead?  No idea!
@end deffn

@deffn {Scheme Procedure} copy-file oldfile newfile
@deffnx {C Function} scm_copy_file (oldfile, newfile)
Copy the file specified by @var{oldfile} to @var{newfile}.
The return value is unspecified.
@end deffn

@deffn {Scheme Procedure} sendfile out in count [offset]
@deffnx {C Function} scm_sendfile (out, in, count, offset)
Send @var{count} bytes from @var{in} to @var{out}, both of which
must be either open file ports or file descriptors.  When
@var{offset} is omitted, start reading from @var{in}'s current
position; otherwise, start reading at @var{offset}.  Return
the number of bytes actually sent.

When @var{in} is a port, it is often preferable to specify @var{offset},
because @var{in}'s offset as a port may be different from the offset of
its underlying file descriptor.

On systems that support it, such as GNU/Linux, this procedure uses the
@code{sendfile} libc function, which usually corresponds to a system
call.  This is faster than doing a series of @code{read} and
@code{write} system calls.  A typical application is to send a file over
a socket.

In some cases, the @code{sendfile} libc function may return
@code{EINVAL} or @code{ENOSYS}.  In that case, Guile's @code{sendfile}
procedure automatically falls back to doing a series of @code{read} and
@code{write} calls.

In other cases, the libc function may send fewer bytes than
@var{count}---for instance because @var{out} is a slow or limited
device, such as a pipe.  When that happens, Guile's @code{sendfile}
automatically retries until exactly @var{count} bytes were sent or an
error occurs.
@end deffn

@findex rename
@deffn {Scheme Procedure} rename-file oldname newname
@deffnx {C Function} scm_rename (oldname, newname)
Renames the file specified by @var{oldname} to @var{newname}.
The return value is unspecified.
@end deffn

@findex renameat
@deffn {Scheme Procedure} rename-file-at olddir oldname newdir newname
@deffnx {C Function} scm_renameat (olddir, oldname, newdir, newname)
Like @code{rename-file}, but when @var{olddir} or @var{newdir} is true,
resolve @var{oldname} or @var{newname} relative to the directory
specified by the file port @var{olddir} or @var{newdir} instead of the
current working directory.
@end deffn

@deffn {Scheme Procedure} link oldpath newpath
@deffnx {C Function} scm_link (oldpath, newpath)
Creates a new name @var{newpath} in the file system for the
file named by @var{oldpath}.  If @var{oldpath} is a symbolic
link, the link may or may not be followed depending on the
system.
@end deffn

@deffn {Scheme Procedure} symlink oldpath newpath
@deffnx {C Function} scm_symlink (oldpath, newpath)
Create a symbolic link named @var{newpath} with the value (i.e., pointing to)
@var{oldpath}.  The return value is unspecified.
@end deffn

@deffn {Scheme Procedure} symlinkat dir oldpath newpath
@deffnx {C Function} scm_symlinkat (dir, oldpath, newpath)
Like @code{symlink}, but resolve @var{newpath} relative to
the directory referred to by the file port @var{dir}.
@end deffn

@deffn {Scheme Procedure} mkdir path [mode]
@deffnx {C Function} scm_mkdir (path, mode)
Create a new directory named by @var{path}.  If @var{mode} is omitted
then the permissions of the directory are set to @code{#o777}
masked with the current umask (@pxref{Processes, @code{umask}}).
Otherwise they are set to the value specified with @var{mode}
masked with the current umask.
The return value is unspecified.
@end deffn

@deffn {Scheme Procedure} mkdirat dir path [mode]
@deffnx {C Function} scm_mkdirat (dir, path, mode)
Like @code{mkdir}, but resolve @var{path} relative to the directory
referred to by the file port @var{dir} instead.
@end deffn

@deffn {Scheme Procedure} rmdir path
@deffnx {C Function} scm_rmdir (path)
Remove the existing directory named by @var{path}.  The directory must
be empty for this to succeed.  The return value is unspecified.
@end deffn

@deffn {Scheme Procedure} opendir dirname
@deffnx {C Function} scm_opendir (dirname)
@cindex directory contents
Open the directory specified by @var{dirname} and return a directory
stream.

Before using this and the procedures below, make sure to see the
higher-level procedures for directory traversal that are available
(@pxref{File Tree Walk}).
@end deffn

@deffn {Scheme Procedure} directory-stream? object
@deffnx {C Function} scm_directory_stream_p (object)
Return a boolean indicating whether @var{object} is a directory
stream as returned by @code{opendir}.
@end deffn

@deffn {Scheme Procedure} readdir stream
@deffnx {C Function} scm_readdir (stream)
Return (as a string) the next directory entry from the directory stream
@var{stream}.  If there is no remaining entry to be read then the
end of file object is returned.
@end deffn

@deffn {Scheme Procedure} rewinddir stream
@deffnx {C Function} scm_rewinddir (stream)
Reset the directory port @var{stream} so that the next call to
@code{readdir} will return the first directory entry.
@end deffn

@deffn {Scheme Procedure} closedir stream
@deffnx {C Function} scm_closedir (stream)
Close the directory stream @var{stream}.
The return value is unspecified.
@end deffn

Here is an example showing how to display all the entries in a
directory:

@lisp
(define dir (opendir "/usr/lib"))
(do ((entry (readdir dir) (readdir dir)))
    ((eof-object? entry))
  (display entry)(newline))
(closedir dir)
@end lisp

@deffn {Scheme Procedure} sync
@deffnx {C Function} scm_sync ()
Flush the operating system disk buffers.
The return value is unspecified.
@end deffn

@deffn {Scheme Procedure} mknod path type perms dev
@deffnx {C Function} scm_mknod (path, type, perms, dev)
@cindex device file
Creates a new special file, such as a file corresponding to a device.
@var{path} specifies the name of the file.  @var{type} should be one
of the following symbols: @samp{regular}, @samp{directory},
@samp{symlink}, @samp{block-special}, @samp{char-special},
@samp{fifo}, or @samp{socket}.  @var{perms} (an integer) specifies the
file permissions.  @var{dev} (an integer) specifies which device the
special file refers to.  Its exact interpretation depends on the kind
of special file being created.

E.g.,
@lisp
(mknod "/dev/fd0" 'block-special #o660 (+ (* 2 256) 2))
@end lisp

The return value is unspecified.
@end deffn

@deffn {Scheme Procedure} tmpnam
@deffnx {C Function} scm_tmpnam ()
@cindex temporary file
Return an auto-generated name of a temporary file, a file which
doesn't already exist.  The name includes a path, it's usually in
@file{/tmp} but that's system dependent.

Care must be taken when using @code{tmpnam}.  In between choosing the
name and creating the file another program might use that name, or an
attacker might even make it a symlink pointing at something important
and causing you to overwrite that.

The safe way is to create the file using @code{open} with
@code{O_EXCL} to avoid any overwriting.  A loop can try again with
another name if the file exists (error @code{EEXIST}).
@code{mkstemp} below does that.
@end deffn

@deffn {Scheme Procedure} mkstemp tmpl [mode]
@cindex temporary file
Create a new unique file in the file system and return a new buffered
port open for reading and writing to the file.

@var{tmpl} is a string specifying where the file should be created: it
must end with @samp{XXXXXX}.  The name of the newly created file will be
the same as @var{tmpl}, but with those @samp{X}s changed, and can be
determined by calling @code{port-filename} on the returned port.

Note that the newly created file is not deleted automatically by Guile;
probably the caller should arrange to call @code{delete-file} when the
file is no longer needed.

POSIX doesn't specify the permissions mode of the file.  On GNU and most
systems it's @code{#o600}; an application can use @code{chmod} to relax
that if desired.  For example @code{#o666} less @code{umask}, which is
usual for ordinary file creation,

@example
(let ((port (mkstemp "/tmp/myfile-XXXXXX")))
  (chmod port (logand #o666 (lognot (umask))))
  ...)
@end example

The optional @var{mode} argument specifies a mode with which to open the
new file, as a string in the same format that @code{open-file} takes.
It defaults to @code{"w+"}.
@end deffn

@deffn {Scheme Procedure} tmpfile
@deffnx {C Function} scm_tmpfile ()
Return an input/output port to a unique temporary file
named using the path prefix @code{P_tmpdir} defined in
@file{stdio.h}.
The file is automatically deleted when the port is closed
or the program terminates.
@end deffn

@deffn {Scheme Procedure} mkdtemp tmpl
@deffnx {C Function} scm_mkdtemp (tmpl)
@cindex temporary directory
Create a new directory named in accordance with the template string
@var{tmpl}.

@var{tmpl} is a string specifying the directory's name. The last six
characters of @var{tmpl} must be @samp{XXXXXX}. Upon successful
execution, the name of the new directory is returned which has the same
form as @var{tmpl} but with the @samp{XXXXXX} characters modified to
ensure the directory name is unique.

The permissions of the directory created are OS dependent, but, are
usually @code{#o700}.

An error may be thrown if the template has the wrong format or if the
directory cannot be created.
@end deffn

@deffn {Scheme Procedure} dirname filename
@deffnx {C Function} scm_dirname (filename)
Return the directory name component of the file name
@var{filename}. If @var{filename} does not contain a directory
component, @code{.} is returned.
@end deffn

@deffn {Scheme Procedure} basename filename [suffix]
@deffnx {C Function} scm_basename (filename, suffix)
Return the base name of the file name @var{filename}. The
base name is the file name without any directory components.
If @var{suffix} is provided, and is equal to the end of
@var{basename}, it is removed also.

@lisp
(basename "/tmp/test.xml" ".xml")
@result{} "test"
@end lisp
@end deffn

@deffn {Scheme Procedure} canonicalize-path path
@deffnx {C Function} scm_canonicalize_path (path)
Return the canonical (absolute) path of @var{path}.
A canonical path has no @code{.} or @code{..} components,
nor any repeated path separators (@code{/}) nor symlinks.

Raises an error if any component of @var{path} does not
exist.

@lisp
(canonicalize-path "test.xml")
@result{} "/tmp/test.xml"
@end lisp
@end deffn

@deffn {Scheme Procedure} file-exists? filename
Return @code{#t} if the file named @var{filename} exists, @code{#f} if
not.
@end deffn

@cindex file name separator
@cindex absolute file name

Many operating systems, such as GNU, use @code{/} (forward slash) to
separate the components of a file name; any file name starting with
@code{/} is considered an @dfn{absolute file name}.  These conventions
are specified by the POSIX Base Definitions, which refer to conforming
file names as ``pathnames''.  Some operating systems use a different
convention; in particular, Windows uses @code{\} (backslash) as the file
name separator, and also has the notion of @dfn{volume names} like
@code{C:\} for absolute file names.  The following procedures and
variables provide support for portable file name manipulations.

@deffn {Scheme Procedure} system-file-name-convention
Return either @code{posix} or @code{windows}, depending on
what kind of system this Guile is running on.
@end deffn

@deffn {Scheme Procedure} file-name-separator? c
Return true if character @var{c} is a file name separator on the host
platform.
@end deffn

@deffn {Scheme Procedure} absolute-file-name? file-name
Return true if @var{file-name} denotes an absolute file name on the host
platform.
@end deffn

@defvr {Scheme Variable} file-name-separator-string
The preferred file name separator.

Note that on MinGW builds for Windows, both @code{/} and @code{\} are
valid separators.  Thus, programs should not assume that
@code{file-name-separator-string} is the @emph{only} file name
separator---e.g., when extracting the components of a file name.
@end defvr


@node User Information
@subsection User Information
@cindex user information
@cindex password file
@cindex group file

The facilities in this section provide an interface to the user and
group database.
They should be used with care since they are not reentrant.

The following functions accept an object representing user information
and return a selected component:

@deffn {Scheme Procedure} passwd:name pw
The name of the userid.
@end deffn
@deffn {Scheme Procedure} passwd:passwd pw
The encrypted passwd.
@end deffn
@deffn {Scheme Procedure} passwd:uid pw
The user id number.
@end deffn
@deffn {Scheme Procedure} passwd:gid pw
The group id number.
@end deffn
@deffn {Scheme Procedure} passwd:gecos pw
The full name.
@end deffn
@deffn {Scheme Procedure} passwd:dir pw
The home directory.
@end deffn
@deffn {Scheme Procedure} passwd:shell pw
The login shell.
@end deffn
@sp 1

@deffn {Scheme Procedure} getpwuid uid
Look up an integer userid in the user database.
@end deffn

@deffn {Scheme Procedure} getpwnam name
Look up a user name string in the user database.
@end deffn

@deffn {Scheme Procedure} setpwent
Initializes a stream used by @code{getpwent} to read from the user database.
The next use of @code{getpwent} will return the first entry.  The
return value is unspecified.
@end deffn

@deffn {Scheme Procedure} getpwent
Read the next entry in the user database stream.  The return is a
passwd user object as above, or @code{#f} when no more entries.
@end deffn

@deffn {Scheme Procedure} endpwent
Closes the stream used by @code{getpwent}.  The return value is unspecified.
@end deffn

@deffn {Scheme Procedure} setpw [arg]
@deffnx {C Function} scm_setpwent (arg)
If called with a true argument, initialize or reset the password data
stream.  Otherwise, close the stream.  The @code{setpwent} and
@code{endpwent} procedures are implemented on top of this.
@end deffn

@deffn {Scheme Procedure} getpw [user]
@deffnx {C Function} scm_getpwuid (user)
Look up an entry in the user database.  @var{user} can be an integer,
a string, or omitted, giving the behaviour of getpwuid, getpwnam
or getpwent respectively.
@end deffn

The following functions accept an object representing group information
and return a selected component:

@deffn {Scheme Procedure} group:name gr
The group name.
@end deffn
@deffn {Scheme Procedure} group:passwd gr
The encrypted group password.
@end deffn
@deffn {Scheme Procedure} group:gid gr
The group id number.
@end deffn
@deffn {Scheme Procedure} group:mem gr
A list of userids which have this group as a supplementary group.
@end deffn
@sp 1

@deffn {Scheme Procedure} getgrgid gid
Look up an integer group id in the group database.
@end deffn

@deffn {Scheme Procedure} getgrnam name
Look up a group name in the group database.
@end deffn

@deffn {Scheme Procedure} setgrent
Initializes a stream used by @code{getgrent} to read from the group database.
The next use of @code{getgrent} will return the first entry.
The return value is unspecified.
@end deffn

@deffn {Scheme Procedure} getgrent
Return the next entry in the group database, using the stream set by
@code{setgrent}.
@end deffn

@deffn {Scheme Procedure} endgrent
Closes the stream used by @code{getgrent}.
The return value is unspecified.
@end deffn

@deffn {Scheme Procedure} setgr [arg]
@deffnx {C Function} scm_setgrent (arg)
If called with a true argument, initialize or reset the group data
stream.  Otherwise, close the stream.  The @code{setgrent} and
@code{endgrent} procedures are implemented on top of this.
@end deffn

@deffn {Scheme Procedure} getgr [group]
@deffnx {C Function} scm_getgrgid (group)
Look up an entry in the group database.  @var{group} can be an integer,
a string, or omitted, giving the behaviour of getgrgid, getgrnam
or getgrent respectively.
@end deffn

In addition to the accessor procedures for the user database, the
following shortcut procedure is also available.

@deffn {Scheme Procedure} getlogin
@deffnx {C Function} scm_getlogin ()
Return a string containing the name of the user logged in on
the controlling terminal of the process, or @code{#f} if this
information cannot be obtained.
@end deffn


@node Time
@subsection Time
@cindex time

@deffn {Scheme Procedure} current-time
@deffnx {C Function} scm_current_time ()
Return the number of seconds since 1970-01-01 00:00:00 @acronym{UTC},
excluding leap seconds.
@end deffn

@deffn {Scheme Procedure} gettimeofday
@deffnx {C Function} scm_gettimeofday ()
Return a pair containing the number of seconds and microseconds
since 1970-01-01 00:00:00 @acronym{UTC}, excluding leap seconds.  Note:
whether true microsecond resolution is available depends on the
operating system.
@end deffn

The following procedures either accept an object representing a broken down
time and return a selected component, or accept an object representing
a broken down time and a value and set the component to the value.
The numbers in parentheses give the usual range.

@deffn {Scheme Procedure} tm:sec tm
@deffnx {Scheme Procedure} set-tm:sec tm val
Seconds (0-59).
@end deffn
@deffn {Scheme Procedure} tm:min tm
@deffnx {Scheme Procedure} set-tm:min tm val
Minutes (0-59).
@end deffn
@deffn {Scheme Procedure} tm:hour tm
@deffnx {Scheme Procedure} set-tm:hour tm val
Hours (0-23).
@end deffn
@deffn {Scheme Procedure} tm:mday tm
@deffnx {Scheme Procedure} set-tm:mday tm val
Day of the month (1-31).
@end deffn
@deffn {Scheme Procedure} tm:mon tm
@deffnx {Scheme Procedure} set-tm:mon tm val
Month (0-11).
@end deffn
@deffn {Scheme Procedure} tm:year tm
@deffnx {Scheme Procedure} set-tm:year tm val
Year (70-), the year minus 1900.
@end deffn
@deffn {Scheme Procedure} tm:wday tm
@deffnx {Scheme Procedure} set-tm:wday tm val
Day of the week (0-6) with Sunday represented as 0.
@end deffn
@deffn {Scheme Procedure} tm:yday tm
@deffnx {Scheme Procedure} set-tm:yday tm val
Day of the year (0-364, 365 in leap years).
@end deffn
@deffn {Scheme Procedure} tm:isdst tm
@deffnx {Scheme Procedure} set-tm:isdst tm val
Daylight saving indicator (0 for ``no'', greater than 0 for ``yes'', less than
0 for ``unknown'').
@end deffn
@deffn {Scheme Procedure} tm:gmtoff tm
@deffnx {Scheme Procedure} set-tm:gmtoff tm val
Time zone offset in seconds west of @acronym{UTC} (-46800 to 43200).
For example on East coast USA (zone @samp{EST+5}) this would be 18000
(ie.@: @m{5\times60\times60,5*60*60}) in winter, or 14400
(ie.@: @m{4\times60\times60,4*60*60}) during daylight savings.

Note @code{tm:gmtoff} is not the same as @code{tm_gmtoff} in the C
@code{tm} structure.  @code{tm_gmtoff} is seconds east and hence the
negative of the value here.
@end deffn
@deffn {Scheme Procedure} tm:zone tm
@deffnx {Scheme Procedure} set-tm:zone tm val
Time zone label (a string), not necessarily unique.
@end deffn
@sp 1

@deffn {Scheme Procedure} localtime time [zone]
@deffnx {C Function} scm_localtime (time, zone)
@cindex local time
Return an object representing the broken down components of
@var{time}, an integer like the one returned by
@code{current-time}.  The time zone for the calculation is
optionally specified by @var{zone} (a string), otherwise the
@env{TZ} environment variable or the system default is used.
@end deffn

@deffn {Scheme Procedure} gmtime time
@deffnx {C Function} scm_gmtime (time)
Return an object representing the broken down components of
@var{time}, an integer like the one returned by
@code{current-time}.  The values are calculated for @acronym{UTC}.
@end deffn

@deffn {Scheme Procedure} mktime sbd-time [zone]
@deffnx {C Function} scm_mktime (sbd_time, zone)
For a broken down time object @var{sbd-time}, return a pair the
@code{car} of which is an integer time like @code{current-time}, and
the @code{cdr} of which is a new broken down time with normalized
fields.

@var{zone} is a timezone string, or the default is the @env{TZ}
environment variable or the system default (@pxref{TZ Variable,,
Specifying the Time Zone with @env{TZ}, libc, GNU C Library Reference
Manual}).  @var{sbd-time} is taken to be in that @var{zone}.

The following fields of @var{sbd-time} are used: @code{tm:year},
@code{tm:mon}, @code{tm:mday}, @code{tm:hour}, @code{tm:min},
@code{tm:sec}, @code{tm:isdst}.  The values can be outside their usual
ranges.  For example @code{tm:hour} normally goes up to 23, but a
value say 33 would mean 9 the following day.

@code{tm:isdst} in @var{sbd-time} says whether the time given is with
daylight savings or not.  This is ignored if @var{zone} doesn't have
any daylight savings adjustment amount.

The broken down time in the return normalizes the values of
@var{sbd-time} by bringing them into their usual ranges, and using the
actual daylight savings rule for that time in @var{zone} (which may
differ from what @var{sbd-time} had).  The easiest way to think of
this is that @var{sbd-time} plus @var{zone} converts to the integer
UTC time, then a @code{localtime} is applied to get the normal
presentation of that time, in @var{zone}.
@end deffn

@deffn {Scheme Procedure} tzset
@deffnx {C Function} scm_tzset ()
Initialize the timezone from the @env{TZ} environment variable
or the system default.  It's not usually necessary to call this procedure
since it's done automatically by other procedures that depend on the
timezone.
@end deffn

@deffn {Scheme Procedure} strftime format tm
@deffnx {C Function} scm_strftime (format, tm)
@cindex time formatting
Return a string which is broken-down time structure @var{tm} formatted
according to the given @var{format} string.

@var{format} contains field specifications introduced by a @samp{%}
character.  See @ref{Formatting Calendar Time,,, libc, The GNU C
Library Reference Manual}, or @samp{man 3 strftime}, for the available
formatting.

@lisp
(strftime "%c" (localtime (current-time)))
@result{} "Mon Mar 11 20:17:43 2002"
@end lisp

If @code{setlocale} has been called (@pxref{Locales}), month and day
names are from the current locale and in the locale character set.
@end deffn

@deffn {Scheme Procedure} strptime format string
@deffnx {C Function} scm_strptime (format, string)
@cindex time parsing
Performs the reverse action to @code{strftime}, parsing
@var{string} according to the specification supplied in
@var{format}.  The interpretation of month and day names is
dependent on the current locale.  The value returned is a pair.
The @acronym{CAR} has an object with time components
in the form returned by @code{localtime} or @code{gmtime},
but the time zone components
are not usefully set.
The @acronym{CDR} reports the number of characters from @var{string}
which were used for the conversion.
@end deffn

@defvar internal-time-units-per-second
The value of this variable is the number of time units per second
reported by the following procedures.
@end defvar

@deffn {Scheme Procedure} times
@deffnx {C Function} scm_times ()
Return an object with information about real and processor
time.  The following procedures accept such an object as an
argument and return a selected component:

@deffn {Scheme Procedure} tms:clock tms
The current real time, expressed as time units relative to an
arbitrary base.
@end deffn
@deffn {Scheme Procedure} tms:utime tms
The CPU time units used by the calling process.
@end deffn
@deffn {Scheme Procedure} tms:stime tms
The CPU time units used by the system on behalf of the calling
process.
@end deffn
@deffn {Scheme Procedure} tms:cutime tms
The CPU time units used by terminated child processes of the
calling process, whose status has been collected (e.g., using
@code{waitpid}).
@end deffn
@deffn {Scheme Procedure} tms:cstime tms
Similarly, the CPU times units used by the system on behalf of
terminated child processes.
@end deffn
@end deffn

@deffn {Scheme Procedure} get-internal-real-time
@deffnx {C Function} scm_get_internal_real_time ()
Return the number of time units since the interpreter was
started.
@end deffn

@deffn {Scheme Procedure} get-internal-run-time
@deffnx {C Function} scm_get_internal_run_time ()
Return the number of time units of processor time used by the
interpreter.  Both @emph{system} and @emph{user} time are
included but subprocesses are not.
@end deffn

@node Runtime Environment
@subsection Runtime Environment

@deffn {Scheme Procedure} program-arguments
@deffnx {Scheme Procedure} command-line
@deffnx {Scheme Procedure} set-program-arguments
@deffnx {C Function} scm_program_arguments ()
@deffnx {C Function} scm_set_program_arguments_scm (lst)
@cindex command line
@cindex program arguments
Get the command line arguments passed to Guile, or set new arguments.

The arguments are a list of strings, the first of which is the invoked
program name.  This is just @nicode{"guile"} (or the executable path)
when run interactively, or it's the script name when running a script
with @option{-s} (@pxref{Invoking Guile}).

@example
guile -L /my/extra/dir -s foo.scm abc def

(program-arguments) @result{} ("foo.scm" "abc" "def")
@end example

@code{set-program-arguments} allows a library module or similar to
modify the arguments, for example to strip options it recognises,
leaving the rest for the mainline.

The argument list is held in a fluid, which means it's separate for
each thread.  Neither the list nor the strings within it are copied at
any point and normally should not be mutated.

The two names @code{program-arguments} and @code{command-line} are an
historical accident, they both do exactly the same thing.  The name
@code{scm_set_program_arguments_scm} has an extra @code{_scm} on the
end to avoid clashing with the C function below.
@end deffn

@deftypefn {C Function} void scm_set_program_arguments (int argc, char **argv, char *first)
@cindex command line
@cindex program arguments
Set the list of command line arguments for @code{program-arguments}
and @code{command-line} above.

@var{argv} is an array of null-terminated strings, as in a C
@code{main} function.  @var{argc} is the number of strings in
@var{argv}, or if it's negative then a @code{NULL} in @var{argv} marks
its end.

@var{first} is an extra string put at the start of the arguments, or
@code{NULL} for no such extra.  This is a convenient way to pass the
program name after advancing @var{argv} to strip option arguments.
Eg.@:

@example
@{
  char *progname = argv[0];
  for (argv++; argv[0] != NULL && argv[0][0] == '-'; argv++)
    @{
      /* munch option ... */
    @}
  /* remaining args for scheme level use */
  scm_set_program_arguments (-1, argv, progname);
@}
@end example

This sort of thing is often done at startup under
@code{scm_boot_guile} with options handled at the C level removed.
The given strings are all copied, so the C data is not accessed again
once @code{scm_set_program_arguments} returns.
@end deftypefn

@deffn {Scheme Procedure} getenv name
@deffnx {C Function} scm_getenv (name)
@cindex environment
Looks up the string @var{name} in the current environment.  The return
value is @code{#f} unless a string of the form @code{NAME=VALUE} is
found, in which case the string @code{VALUE} is returned.
@end deffn

@deffn {Scheme Procedure} setenv name value
Modifies the environment of the current process, which is
also the default environment inherited by child processes.

If @var{value} is @code{#f}, then @var{name} is removed from the
environment.  Otherwise, the string @var{name}=@var{value} is added
to the environment, replacing any existing string with name matching
@var{name}.

The return value is unspecified.
@end deffn

@deffn {Scheme Procedure} unsetenv name
Remove variable @var{name} from the environment.  The
name can not contain a @samp{=} character.
@end deffn

@deffn {Scheme Procedure} environ [env]
@deffnx {C Function} scm_environ (env)
If @var{env} is omitted, return the current environment (in the
Unix sense) as a list of strings.  Otherwise set the current
environment, which is also the default environment for child
processes, to the supplied list of strings.  Each member of
@var{env} should be of the form @var{name}=@var{value} and values of
@var{name} should not be duplicated.  If @var{env} is supplied
then the return value is unspecified.
@end deffn

@deffn {Scheme Procedure} putenv str
@deffnx {C Function} scm_putenv (str)
Modifies the environment of the current process, which is
also the default environment inherited by child processes.

If @var{str} is of the form @code{NAME=VALUE} then it will be written
directly into the environment, replacing any existing environment string
with
name matching @code{NAME}.  If @var{str} does not contain an equal
sign, then any existing string with name matching @var{str} will
be removed.

The return value is unspecified.
@end deffn


@node Processes
@subsection Processes
@cindex processes
@cindex child processes

@findex cd
@deffn {Scheme Procedure} chdir str
@deffnx {C Function} scm_chdir (str)
@cindex current directory
Change the current working directory to @var{str}.  @var{str} can be a
string containing a file name, or a port if supported by the system.
@code{(provided? 'chdir-port)} reports whether ports are supported.
The return value is unspecified.
@end deffn

@findex pwd
@deffn {Scheme Procedure} getcwd
@deffnx {C Function} scm_getcwd ()
Return the name of the current working directory.
@end deffn

@deffn {Scheme Procedure} umask [mode]
@deffnx {C Function} scm_umask (mode)
If @var{mode} is omitted, returns a decimal number representing the
current file creation mask.  Otherwise the file creation mask is set
to @var{mode} and the previous value is returned. @xref{Setting
Permissions,,Assigning File Permissions,libc,The GNU C Library
Reference Manual}, for more on how to use umasks.

E.g., @code{(umask #o022)} sets the mask to octal 22/decimal 18.
@end deffn

@deffn {Scheme Procedure} chroot path
@deffnx {C Function} scm_chroot (path)
Change the root directory to that specified in @var{path}.
This directory will be used for path names beginning with
@file{/}.  The root directory is inherited by all children
of the current process.  Only the superuser may change the
root directory.
@end deffn

@deffn {Scheme Procedure} getpid
@deffnx {C Function} scm_getpid ()
Return an integer representing the current process ID.
@end deffn

@deffn {Scheme Procedure} getgroups
@deffnx {C Function} scm_getgroups ()
Return a vector of integers representing the current
supplementary group IDs.
@end deffn

@deffn {Scheme Procedure} getppid
@deffnx {C Function} scm_getppid ()
Return an integer representing the process ID of the parent
process.
@end deffn

@deffn {Scheme Procedure} getuid
@deffnx {C Function} scm_getuid ()
Return an integer representing the current real user ID.
@end deffn

@deffn {Scheme Procedure} getgid
@deffnx {C Function} scm_getgid ()
Return an integer representing the current real group ID.
@end deffn

@deffn {Scheme Procedure} geteuid
@deffnx {C Function} scm_geteuid ()
Return an integer representing the current effective user ID.
If the system does not support effective IDs, then the real ID
is returned.  @code{(provided? 'EIDs)} reports whether the
system supports effective IDs.
@end deffn

@deffn {Scheme Procedure} getegid
@deffnx {C Function} scm_getegid ()
Return an integer representing the current effective group ID.
If the system does not support effective IDs, then the real ID
is returned.  @code{(provided? 'EIDs)} reports whether the
system supports effective IDs.
@end deffn

@deffn {Scheme Procedure} setgroups vec
@deffnx {C Function} scm_setgroups (vec)
Set the current set of supplementary group IDs to the integers in the
given vector @var{vec}.  The return value is unspecified.

Generally only the superuser can set the process group IDs
(@pxref{Setting Groups, Setting the Group IDs,, libc, The GNU C
Library Reference Manual}).
@end deffn

@deffn {Scheme Procedure} setuid id
@deffnx {C Function} scm_setuid (id)
Sets both the real and effective user IDs to the integer @var{id}, provided
the process has appropriate privileges.
The return value is unspecified.
@end deffn

@deffn {Scheme Procedure} setgid id
@deffnx {C Function} scm_setgid (id)
Sets both the real and effective group IDs to the integer @var{id}, provided
the process has appropriate privileges.
The return value is unspecified.
@end deffn

@deffn {Scheme Procedure} seteuid id
@deffnx {C Function} scm_seteuid (id)
Sets the effective user ID to the integer @var{id}, provided the process
has appropriate privileges.  If effective IDs are not supported, the
real ID is set instead---@code{(provided? 'EIDs)} reports whether the
system supports effective IDs.
The return value is unspecified.
@end deffn

@deffn {Scheme Procedure} setegid id
@deffnx {C Function} scm_setegid (id)
Sets the effective group ID to the integer @var{id}, provided the process
has appropriate privileges.  If effective IDs are not supported, the
real ID is set instead---@code{(provided? 'EIDs)} reports whether the
system supports effective IDs.
The return value is unspecified.
@end deffn

@deffn {Scheme Procedure} getpgrp
@deffnx {C Function} scm_getpgrp ()
Return an integer representing the current process group ID.
This is the @acronym{POSIX} definition, not @acronym{BSD}.
@end deffn

@deffn {Scheme Procedure} setpgid pid pgid
@deffnx {C Function} scm_setpgid (pid, pgid)
Move the process @var{pid} into the process group @var{pgid}.  @var{pid} or
@var{pgid} must be integers: they can be zero to indicate the ID of the
current process.
Fails on systems that do not support job control.
The return value is unspecified.
@end deffn

@deffn {Scheme Procedure} setsid
@deffnx {C Function} scm_setsid ()
Creates a new session.  The current process becomes the session leader
and is put in a new process group.  The process will be detached
from its controlling terminal if it has one.
The return value is an integer representing the new process group ID.
@end deffn

@deffn {Scheme Procedure} getsid pid
@deffnx {C Function} scm_getsid (pid)
Returns the session ID of process @var{pid}.  (The session
ID of a process is the process group ID of its session leader.)
@end deffn

@deffn {Scheme Procedure} waitpid pid [options]
@deffnx {C Function} scm_waitpid (pid, options)
This procedure collects status information from a child process which
has terminated or (optionally) stopped.  Normally it will
suspend the calling process until this can be done.  If more than one
child process is eligible then one will be chosen by the operating system.

The value of @var{pid} determines the behaviour:

@table @asis
@item @var{pid} greater than 0
Request status information from the specified child process.
@item @var{pid} equal to -1 or @code{WAIT_ANY}
@vindex WAIT_ANY
Request status information for any child process.
@item @var{pid} equal to 0 or @code{WAIT_MYPGRP}
@vindex WAIT_MYPGRP
Request status information for any child process in the current process
group.
@item @var{pid} less than -1
Request status information for any child process whose process group ID
is @minus{}@var{pid}.
@end table

The @var{options} argument, if supplied, should be the bitwise OR of the
values of zero or more of the following variables:

@defvar WNOHANG
Return immediately even if there are no child processes to be collected.
@end defvar

@defvar WUNTRACED
Report status information for stopped processes as well as terminated
processes.
@end defvar

The return value is a pair containing:

@enumerate
@item
The process ID of the child process, or 0 if @code{WNOHANG} was
specified and no process was collected.
@item
The integer status value (@pxref{Process Completion Status,,, libc, The
GNU C Library Reference Manual}).
@end enumerate
@end deffn

The following three
functions can be used to decode the integer status value returned by
@code{waitpid}.

@deffn {Scheme Procedure} status:exit-val status
@deffnx {C Function} scm_status_exit_val (status)
Return the exit status value, as would be set if a process
ended normally through a call to @code{exit} or @code{_exit},
if any, otherwise @code{#f}.
@end deffn

@deffn {Scheme Procedure} status:term-sig status
@deffnx {C Function} scm_status_term_sig (status)
Return the signal number which terminated the process, if any,
otherwise @code{#f}.
@end deffn

@deffn {Scheme Procedure} status:stop-sig status
@deffnx {C Function} scm_status_stop_sig (status)
Return the signal number which stopped the process, if any,
otherwise @code{#f}.
@end deffn

@deffn {Scheme Procedure} system [cmd]
@deffnx {C Function} scm_system (cmd)
Execute @var{cmd} using the operating system's ``command
processor''.  Under Unix this is usually the default shell
@code{sh}.  The value returned is @var{cmd}'s exit status as
returned by @code{waitpid}, which can be interpreted using the
functions above.

If @code{system} is called without arguments, return a boolean
indicating whether the command processor is available.
@end deffn

@deffn {Scheme Procedure} system* arg1 arg2 @dots{}
@deffnx {C Function} scm_system_star (args)
Execute the command indicated by @var{arg1} @var{arg2} @enddots{}.  The
first element must be a string indicating the command to be executed,
and the remaining items must be strings representing each of the
arguments to that command.

This function returns the exit status of the command as provided by
@code{waitpid}.  This value can be handled with @code{status:exit-val}
and the related functions.

@code{system*} is similar to @code{system}, but accepts only one
string per-argument, and performs no shell interpretation.  The
command is executed using fork and execlp.  Accordingly this function
may be safer than @code{system} in situations where shell
interpretation is not required.

Example: (system* "echo" "foo" "bar")
@end deffn

@deffn {Scheme Procedure} quit [status]
@deffnx {Scheme Procedure} exit [status]
Terminate the current process with proper unwinding of the Scheme stack.
The exit status zero if @var{status} is not supplied.  If @var{status}
is supplied, and it is an integer, that integer is used as the exit
status.  If @var{status} is @code{#t} or @code{#f}, the exit status is
@var{EXIT_SUCCESS} or @var{EXIT_FAILURE}, respectively.

The procedure @code{exit} is an alias of @code{quit}.  They have the
same functionality.
@end deffn

@defvr {Scheme Variable} EXIT_SUCCESS
@defvrx {Scheme Variable} EXIT_FAILURE
These constants represent the standard exit codes for success (zero) or
failure (one.)
@end defvr

@deffn {Scheme Procedure} primitive-exit [status]
@deffnx {Scheme Procedure} primitive-_exit [status]
@deffnx {C Function} scm_primitive_exit (status)
@deffnx {C Function} scm_primitive__exit (status)
Terminate the current process without unwinding the Scheme stack.  The
exit status is @var{status} if supplied, otherwise zero.

@code{primitive-exit} uses the C @code{exit} function and hence runs
usual C level cleanups (flush output streams, call @code{atexit}
functions, etc, see @ref{Normal Termination,,, libc, The GNU C Library
Reference Manual})).

@code{primitive-_exit} is the @code{_exit} system call
(@pxref{Termination Internals,,, libc, The GNU C Library Reference
Manual}).  This terminates the program immediately, with neither
Scheme-level nor C-level cleanups.

The typical use for @code{primitive-_exit} is from a child process
created with @code{primitive-fork}.  For example in a Gdk program the
child process inherits the X server connection and a C-level
@code{atexit} cleanup which will close that connection.  But closing
in the child would upset the protocol in the parent, so
@code{primitive-_exit} should be used to exit without that.
@end deffn

@deffn {Scheme Procedure} execl filename arg @dots{}
@deffnx {C Function} scm_execl (filename, args)
Executes the file named by @var{filename} as a new process image.
The remaining arguments are supplied to the process; from a C program
they are accessible as the @code{argv} argument to @code{main}.
Conventionally the first @var{arg} is the same as @var{filename}.
All arguments must be strings.

If @var{arg} is missing, @var{filename} is executed with a null
argument list, which may have system-dependent side-effects.

This procedure is currently implemented using the @code{execv} system
call, but we call it @code{execl} because of its Scheme calling interface.
@end deffn

@deffn {Scheme Procedure} execlp filename arg @dots{}
@deffnx {C Function} scm_execlp (filename, args)
Similar to @code{execl}, however if
@var{filename} does not contain a slash
then the file to execute will be located by searching the
directories listed in the @code{PATH} environment variable.

This procedure is currently implemented using the @code{execvp} system
call, but we call it @code{execlp} because of its Scheme calling interface.
@end deffn

@deffn {Scheme Procedure} execle filename env arg @dots{}
@deffnx {C Function} scm_execle (filename, env, args)
Similar to @code{execl}, but the environment of the new process is
specified by @var{env}, which must be a list of strings as returned by the
@code{environ} procedure.

This procedure is currently implemented using the @code{execve} system
call, but we call it @code{execle} because of its Scheme calling interface.
@end deffn

@deffn {Scheme Procedure} primitive-fork
@deffnx {C Function} scm_fork ()
Creates a new ``child'' process by duplicating the current ``parent'' process.
In the child the return value is 0.  In the parent the return value is
the integer process ID of the child.

Note that it is unsafe to fork a process that has multiple threads
running, as only the thread that calls @code{primitive-fork} will
persist in the child.  Any resources that other threads held, such as
locked mutexes or open file descriptors, are lost.  Indeed,
@acronym{POSIX} specifies that only async-signal-safe procedures are
safe to call after a multithreaded fork, which is a very limited set.
Guile issues a warning if it detects a fork from a multi-threaded
program.

If you are going to @code{exec} soon after forking, the procedures in
@code{(ice-9 popen)} may be useful to you, as they fork and exec within
an async-signal-safe function carefully written to ensure robust program
behavior, even in the presence of threads.  @xref{Pipes}, for more.

This procedure has been renamed from @code{fork} to avoid a naming conflict
with the scsh fork.
@end deffn

@deffn {Scheme Procedure} nice incr
@deffnx {C Function} scm_nice (incr)
@cindex process priority
Increment the priority of the current process by @var{incr}.  A higher
priority value means that the process runs less often.
The return value is unspecified.
@end deffn

@deffn {Scheme Procedure} setpriority which who prio
@deffnx {C Function} scm_setpriority (which, who, prio)
@vindex PRIO_PROCESS
@vindex PRIO_PGRP
@vindex PRIO_USER
Set the scheduling priority of the process, process group
or user, as indicated by @var{which} and @var{who}. @var{which}
is one of the variables @code{PRIO_PROCESS}, @code{PRIO_PGRP}
or @code{PRIO_USER}, and @var{who} is interpreted relative to
@var{which} (a process identifier for @code{PRIO_PROCESS},
process group identifier for @code{PRIO_PGRP}, and a user
identifier for @code{PRIO_USER}.  A zero value of @var{who}
denotes the current process, process group, or user.
@var{prio} is a value in the range [@minus{}20,20].  The default
priority is 0; lower priorities (in numerical terms) cause more
favorable scheduling.  Sets the priority of all of the specified
processes.  Only the super-user may lower priorities.  The return
value is not specified.
@end deffn

@deffn {Scheme Procedure} getpriority which who
@deffnx {C Function} scm_getpriority (which, who)
@vindex PRIO_PROCESS
@vindex PRIO_PGRP
@vindex PRIO_USER
Return the scheduling priority of the process, process group
or user, as indicated by @var{which} and @var{who}. @var{which}
is one of the variables @code{PRIO_PROCESS}, @code{PRIO_PGRP}
or @code{PRIO_USER}, and @var{who} should be interpreted depending on
@var{which} (a process identifier for @code{PRIO_PROCESS},
process group identifier for @code{PRIO_PGRP}, and a user
identifier for @code{PRIO_USER}).  A zero value of @var{who}
denotes the current process, process group, or user.  Return
the highest priority (lowest numerical value) of any of the
specified processes.
@end deffn

@cindex affinity, CPU

@deffn {Scheme Procedure} getaffinity pid
@deffnx {C Function} scm_getaffinity (pid)
Return a bitvector representing the CPU affinity mask for
process @var{pid}.  Each CPU the process has affinity with
has its corresponding bit set in the returned bitvector.
The number of bits set is a good estimate of how many CPUs
Guile can use without stepping on other processes' toes.

Currently this procedure is only defined on GNU variants
(@pxref{CPU Affinity, @code{sched_getaffinity},, libc, The
GNU C Library Reference Manual}).
@end deffn

@deffn {Scheme Procedure} setaffinity pid mask
@deffnx {C Function} scm_setaffinity (pid, mask)
Install the CPU affinity mask @var{mask}, a bitvector, for
the process or thread with ID @var{pid}.  The return value
is unspecified.

Currently this procedure is only defined on GNU variants
(@pxref{CPU Affinity, @code{sched_setaffinity},, libc, The
GNU C Library Reference Manual}).
@end deffn

@xref{Threads}, for information on how get the number of processors
available on a system.


@node Signals
@subsection Signals
@cindex signal

The following procedures raise, handle and wait for signals.

Scheme code signal handlers are run via an async (@pxref{Asyncs}), so
they're called in the handler's thread at the next safe opportunity.
Generally this is after any currently executing primitive procedure
finishes (which could be a long time for primitives that wait for an
external event).

@deffn {Scheme Procedure} kill pid sig
@deffnx {C Function} scm_kill (pid, sig)
Sends a signal to the specified process or group of processes.

@var{pid} specifies the processes to which the signal is sent:

@table @asis
@item @var{pid} greater than 0
The process whose identifier is @var{pid}.
@item @var{pid} equal to 0
All processes in the current process group.
@item @var{pid} less than -1
The process group whose identifier is -@var{pid}
@item @var{pid} equal to -1
If the process is privileged, all processes except for some special
system processes.  Otherwise, all processes with the current effective
user ID.
@end table

@var{sig} should be specified using a variable corresponding to
the Unix symbolic name, e.g.,

@defvar SIGHUP
Hang-up signal.
@end defvar

@defvar SIGINT
Interrupt signal.
@end defvar

A full list of signals on the GNU system may be found in @ref{Standard
Signals,,,libc,The GNU C Library Reference Manual}.
@end deffn

@deffn {Scheme Procedure} raise sig
@deffnx {C Function} scm_raise (sig)
Sends a specified signal @var{sig} to the current process, where
@var{sig} is as described for the @code{kill} procedure.
@end deffn

@deffn {Scheme Procedure} sigaction signum [handler [flags [thread]]]
@deffnx {C Function} scm_sigaction (signum, handler, flags)
@deffnx {C Function} scm_sigaction_for_thread (signum, handler, flags, thread)
Install or report the signal handler for a specified signal.

@var{signum} is the signal number, which can be specified using the value
of variables such as @code{SIGINT}.

If @var{handler} is omitted, @code{sigaction} returns a pair: the
@acronym{CAR} is the current signal hander, which will be either an
integer with the value @code{SIG_DFL} (default action) or
@code{SIG_IGN} (ignore), or the Scheme procedure which handles the
signal, or @code{#f} if a non-Scheme procedure handles the signal.
The @acronym{CDR} contains the current @code{sigaction} flags for the
handler.

If @var{handler} is provided, it is installed as the new handler for
@var{signum}.  @var{handler} can be a Scheme procedure taking one
argument, or the value of @code{SIG_DFL} (default action) or
@code{SIG_IGN} (ignore), or @code{#f} to restore whatever signal handler
was installed before @code{sigaction} was first used.  When a scheme
procedure has been specified, that procedure will run in the given
@var{thread}.  When no thread has been given, the thread that made this
call to @code{sigaction} is used.

@var{flags} is a @code{logior} (@pxref{Bitwise Operations}) of the
following (where provided by the system), or @code{0} for none.

@defvar SA_NOCLDSTOP
By default, @code{SIGCHLD} is signalled when a child process stops
(ie.@: receives @code{SIGSTOP}), and when a child process terminates.
With the @code{SA_NOCLDSTOP} flag, @code{SIGCHLD} is only signalled
for termination, not stopping.

@code{SA_NOCLDSTOP} has no effect on signals other than
@code{SIGCHLD}.
@end defvar

@defvar SA_RESTART
If a signal occurs while in a system call, deliver the signal then
restart the system call (as opposed to returning an @code{EINTR} error
from that call).
@end defvar

Guile handles signals asynchronously.  When it receives a signal, the
synchronous signal handler just records the fact that a signal was
received and sets a flag to tell the relevant Guile thread that it has a
pending signal.  When the Guile thread checks the pending-interrupt
flag, it will arrange to run the asynchronous part of the signal
handler, which is the handler attached by @code{sigaction}.

This strategy has some perhaps-unexpected interactions with the
@code{SA_RESTART} flag, though: because the synchronous handler doesn't
do very much, and notably it doesn't run the Guile handler, it's
impossible to interrupt a thread stuck in a long-running system call via
a signal handler that is installed with @code{SA_RESTART}: the
synchronous handler just records the pending interrupt, but then the
system call resumes and Guile doesn't have a chance to actually check
the flag and run the asynchronous handler.  That's just how it is.

The return value is a pair with information about the old handler as
described above.

This interface does not provide access to the ``signal blocking''
facility.  Maybe this is not needed, since the thread support may
provide solutions to the problem of consistent access to data
structures.
@end deffn

@deffn {Scheme Procedure} restore-signals
@deffnx {C Function} scm_restore_signals ()
Return all signal handlers to the values they had before any call to
@code{sigaction} was made.  The return value is unspecified.
@end deffn

@deffn {Scheme Procedure} alarm i
@deffnx {C Function} scm_alarm (i)
Set a timer to raise a @code{SIGALRM} signal after the specified
number of seconds (an integer).  It's advisable to install a signal
handler for
@code{SIGALRM} beforehand, since the default action is to terminate
the process.

The return value indicates the time remaining for the previous alarm,
if any.  The new value replaces the previous alarm.  If there was
no previous alarm, the return value is zero.
@end deffn

@deffn {Scheme Procedure} pause
@deffnx {C Function} scm_pause ()
Pause the current process (thread?) until a signal arrives whose
action is to either terminate the current process or invoke a
handler procedure.  The return value is unspecified.
@end deffn

@deffn {Scheme Procedure} sleep secs
@deffnx {Scheme Procedure} usleep usecs
@deffnx {C Function} scm_sleep (secs)
@deffnx {C Function} scm_usleep (usecs)
Wait the given period @var{secs} seconds or @var{usecs} microseconds
(both integers).  If a signal arrives the wait stops and the return
value is the time remaining, in seconds or microseconds respectively.
If the period elapses with no signal the return is zero.

On most systems the process scheduler is not microsecond accurate and
the actual period slept by @code{usleep} might be rounded to a system
clock tick boundary, which might be 10 milliseconds for instance.

See @code{scm_std_sleep} and @code{scm_std_usleep} for equivalents at
the C level (@pxref{Blocking}).
@end deffn

@deffn {Scheme Procedure} getitimer which_timer
@deffnx {Scheme Procedure} setitimer which_timer interval_seconds interval_microseconds value_seconds value_microseconds
@deffnx {C Function} scm_getitimer (which_timer)
@deffnx {C Function} scm_setitimer (which_timer, interval_seconds, interval_microseconds, value_seconds, value_microseconds)
Get or set the periods programmed in certain system timers.

These timers have two settings.  The first setting, the interval, is the
value at which the timer will be reset when the current timer expires.
The second is the current value of the timer, indicating when the next
expiry will be signalled.

@var{which_timer} is one of the following values:

@defvar ITIMER_REAL
A real-time timer, counting down elapsed real time.  At zero it raises
@code{SIGALRM}.  This is like @code{alarm} above, but with a higher
resolution period.
@end defvar

@defvar ITIMER_VIRTUAL
A virtual-time timer, counting down while the current process is
actually using CPU.  At zero it raises @code{SIGVTALRM}.
@end defvar

@defvar ITIMER_PROF
A profiling timer, counting down while the process is running (like
@code{ITIMER_VIRTUAL}) and also while system calls are running on the
process's behalf.  At zero it raises a @code{SIGPROF}.

This timer is intended for profiling where a program is spending its
time (by looking where it is when the timer goes off).
@end defvar

@code{getitimer} returns the restart timer value and its current value,
as a list containing two pairs.  Each pair is a time in seconds and
microseconds: @code{((@var{interval_secs} . @var{interval_usecs})
(@var{value_secs} . @var{value_usecs}))}.

@code{setitimer} sets the timer values similarly, in seconds and
microseconds (which must be integers).  The interval value can be zero
to have the timer run down just once.  The return value is the timer's
previous setting, in the same form as @code{getitimer} returns.

@example
(setitimer ITIMER_REAL
           5 500000     ;; Raise SIGALRM every 5.5 seconds
           2 0)         ;; with the first SIGALRM in 2 seconds
@end example

Although the timers are programmed in microseconds, the actual
accuracy might not be that high.

Note that @code{ITIMER_PROF} and @code{ITIMER_VIRTUAL} are not
functional on all platforms and may always error when called.
@code{(provided? 'ITIMER_PROF)} and @code{(provided? 'ITIMER_VIRTUAL)}
can be used to test if the those itimers are supported on the given
host.  @code{ITIMER_REAL} is supported on all platforms that support
@code{setitimer}.
@end deffn


@node Terminals and Ptys
@subsection Terminals and Ptys

@deffn {Scheme Procedure} isatty? port
@deffnx {C Function} scm_isatty_p (port)
@cindex terminal
Return @code{#t} if @var{port} is using a serial non--file
device, otherwise @code{#f}.
@end deffn

@deffn {Scheme Procedure} ttyname port
@deffnx {C Function} scm_ttyname (port)
@cindex terminal
Return a string with the name of the serial terminal device
underlying @var{port}.
@end deffn

@deffn {Scheme Procedure} ctermid
@deffnx {C Function} scm_ctermid ()
@cindex terminal
Return a string containing the file name of the controlling
terminal for the current process.
@end deffn

@deffn {Scheme Procedure} tcgetpgrp port
@deffnx {C Function} scm_tcgetpgrp (port)
@cindex process group
Return the process group ID of the foreground process group
associated with the terminal open on the file descriptor
underlying @var{port}.

If there is no foreground process group, the return value is a
number greater than 1 that does not match the process group ID
of any existing process group.  This can happen if all of the
processes in the job that was formerly the foreground job have
terminated, and no other job has yet been moved into the
foreground.
@end deffn

@deffn {Scheme Procedure} tcsetpgrp port pgid
@deffnx {C Function} scm_tcsetpgrp (port, pgid)
@cindex process group
Set the foreground process group ID for the terminal used by the file
descriptor underlying @var{port} to the integer @var{pgid}.
The calling process
must be a member of the same session as @var{pgid} and must have the same
controlling terminal.  The return value is unspecified.
@end deffn

@node Pipes
@subsection Pipes
@cindex pipe

The following procedures are similar to the @code{popen} and
@code{pclose} system routines.  The code is in a separate ``popen''
module@footnote{This module is only available on systems where the
@code{popen} feature is provided (@pxref{Common Feature Symbols}).}:

@lisp
(use-modules (ice-9 popen))
@end lisp

@findex popen
@deffn {Scheme Procedure} open-pipe command mode
@deffnx {Scheme Procedure} open-pipe* mode prog [args...]
Execute a command in a subprocess, with a pipe to it or from it, or
with pipes in both directions.

@code{open-pipe} runs the shell @var{command} using @samp{/bin/sh -c}.
@code{open-pipe*} executes @var{prog} directly, with the optional
@var{args} arguments (all strings).

@var{mode} should be one of the following values.  @code{OPEN_READ} is
an input pipe, ie.@: to read from the subprocess.  @code{OPEN_WRITE}
is an output pipe, ie.@: to write to it.

@defvar OPEN_READ
@defvarx OPEN_WRITE
@defvarx OPEN_BOTH
@end defvar

For an input pipe, the child's standard output is the pipe and
standard input is inherited from @code{current-input-port}.  For an
output pipe, the child's standard input is the pipe and standard
output is inherited from @code{current-output-port}.  In all cases
the child's standard error is inherited from
@code{current-error-port} (@pxref{Default Ports}).

If those @code{current-X-ports} are not files of some kind, and hence
don't have file descriptors for the child, then @file{/dev/null} is
used instead.

Care should be taken with @code{OPEN_BOTH}, a deadlock will occur if
both parent and child are writing, and waiting until the write completes
before doing any reading.  Each direction has @code{PIPE_BUF} bytes of
buffering (@pxref{Buffering}), which will be enough for small writes,
but not for say putting a big file through a filter.
@end deffn

@deffn {Scheme Procedure} open-input-pipe command
Equivalent to @code{open-pipe} with mode @code{OPEN_READ}.

@lisp
(let* ((port (open-input-pipe "date --utc"))
       (str  (read-line port))) ; from (ice-9 rdelim)
  (close-pipe port)
  str)
@result{} "Mon Mar 11 20:10:44 UTC 2002"
@end lisp
@end deffn

@deffn {Scheme Procedure} open-output-pipe command
Equivalent to @code{open-pipe} with mode @code{OPEN_WRITE}.

@lisp
(let ((port (open-output-pipe "lpr")))
  (display "Something for the line printer.\n" port)
  (if (not (eqv? 0 (status:exit-val (close-pipe port))))
      (error "Cannot print")))
@end lisp
@end deffn

@deffn {Scheme Procedure} open-input-output-pipe command
Equivalent to @code{open-pipe} with mode @code{OPEN_BOTH}.
@end deffn

@findex pclose
@deffn {Scheme Procedure} close-pipe port
Close a pipe created by @code{open-pipe}, wait for the process to
terminate, and return the wait status code.  The status is as per
@code{waitpid} and can be decoded with @code{status:exit-val} etc
(@pxref{Processes})
@end deffn

@sp 1
@code{waitpid WAIT_ANY} should not be used when pipes are open, since
it can reap a pipe's child process, causing an error from a subsequent
@code{close-pipe}.

@code{close-port} (@pxref{Ports}) can close a pipe, but it doesn't reap
the child process.

The garbage collector will close a pipe no longer in use, and reap the
child process with @code{waitpid}.  If the child hasn't yet terminated
the garbage collector doesn't block, but instead checks again in the
next GC.

Many systems have per-user and system-wide limits on the number of
processes, and a system-wide limit on the number of pipes, so pipes
should be closed explicitly when no longer needed, rather than letting
the garbage collector pick them up at some later time.

@deffn {Scheme Procedure} pipeline @var{commands}
Execute a pipeline of @var{commands}, where each command is a
list of a program and its arguments as strings, returning an input
port to the end of the pipeline, an output port to the beginning of the
pipeline and a list of PIDs of the processes executing the @var{commands}.

@example
(let ((commands '(("git" "ls-files")
                  ("tar" "-cf-" "-T-")
                  ("sha1sum" "-")))
      (success? (lambda (pid)
                  (zero?
                   (status:exit-val (cdr (waitpid pid)))))))
  (receive (from to pids) (pipeline commands)
    (let* ((sha1 (read-delimited " " from))
           (index (list-index (negate success?) (reverse pids))))
      (close to)
      (close from)
      (if (not index)
          sha1
          (string-append "pipeline failed in command: "
                         (string-join (list-ref commands index)))))))
@result{} "52f99d234503fca8c84ef94b1005a3a28d8b3bc1"
@end example
@end deffn

@node Networking
@subsection Networking
@cindex network

@menu
* Network Address Conversion::  
* Network Databases::           
* Network Socket Address::      
* Network Sockets and Communication::  
* Internet Socket Examples::    
@end menu

@node Network Address Conversion
@subsubsection Network Address Conversion
@cindex network address

This section describes procedures which convert internet addresses
between numeric and string formats.

@subsubheading IPv4 Address Conversion
@cindex IPv4

An IPv4 Internet address is a 4-byte value, represented in Guile as an
integer in host byte order, so that say ``0.0.0.1'' is 1, or
``1.0.0.0'' is 16777216.

Some underlying C functions use network byte order for addresses,
Guile converts as necessary so that at the Scheme level its host byte
order everywhere.

@defvar INADDR_ANY
For a server, this can be used with @code{bind} (@pxref{Network
Sockets and Communication}) to allow connections from any interface on
the machine.
@end defvar

@defvar INADDR_BROADCAST
The broadcast address on the local network.
@end defvar

@defvar INADDR_LOOPBACK
The address of the local host using the loopback device, ie.@:
@samp{127.0.0.1}.
@end defvar

@c  INADDR_NONE is defined in the code, but serves no purpose.
@c  inet_addr() returns it as an error indication, but that function
@c  isn't provided, for the good reason that inet_aton() does the same
@c  job and gives an unambiguous error indication.  (INADDR_NONE is a
@c  valid 4-byte value, in glibc it's the same as INADDR_BROADCAST.)
@c
@c  @defvar INADDR_NONE
@c  No address.
@c  @end defvar

@deffn {Scheme Procedure} inet-netof address
@deffnx {C Function} scm_inet_netof (address)
Return the network number part of the given IPv4
Internet address.  E.g.,

@lisp
(inet-netof 2130706433) @result{} 127
@end lisp
@end deffn

@deffn {Scheme Procedure} inet-lnaof address
@deffnx {C Function} scm_lnaof (address)
Return the local-address-with-network part of the given
IPv4 Internet address, using the obsolete class A/B/C system.
E.g.,

@lisp
(inet-lnaof 2130706433) @result{} 1
@end lisp
@end deffn

@deffn {Scheme Procedure} inet-makeaddr net lna
@deffnx {C Function} scm_inet_makeaddr (net, lna)
Make an IPv4 Internet address by combining the network number
@var{net} with the local-address-within-network number
@var{lna}.  E.g.,

@lisp
(inet-makeaddr 127 1) @result{} 2130706433
@end lisp
@end deffn

@subsubheading IPv6 Address Conversion
@cindex IPv6

An IPv6 Internet address is a 16-byte value, represented in Guile as
an integer in host byte order, so that say ``::1'' is 1.  The following
constants are defined for convenience.

@defvar IN6ADDR_ANY
For a server, this can be used with @code{bind} (@pxref{Network Sockets
and Communication}) to allow connections from any IPv6 interface on the
machine.
@end defvar

@defvar IN6ADDR_LOOPBACK
The address of the local host using the loopback device, ie.@:
@samp{::1}.
@end defvar

The procedures below convert an IPv6 @emph{or} an IPv4 address to and
from its textual representation.

@deffn {Scheme Procedure} inet-ntop family address
@deffnx {C Function} scm_inet_ntop (family, address)
Convert a network address from an integer to a printable string.
@var{family} can be @code{AF_INET} or @code{AF_INET6}.  E.g.,

@lisp
(inet-ntop AF_INET 2130706433) @result{} "127.0.0.1"
(inet-ntop AF_INET6 (- (expt 2 128) 1))
  @result{} "ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff"
@end lisp
@end deffn

@deffn {Scheme Procedure} inet-pton family address
@deffnx {C Function} scm_inet_pton (family, address)
Convert a string containing a printable network address to an integer
address.  @var{family} can be @code{AF_INET} or @code{AF_INET6}.
E.g.,

@lisp
(inet-pton AF_INET "127.0.0.1") @result{} 2130706433
(inet-pton AF_INET6 "::1") @result{} 1
@end lisp
@end deffn


@node Network Databases
@subsubsection Network Databases
@cindex network database

This section describes procedures which query various network databases.
Care should be taken when using the database routines since they are not
reentrant.

@subsubheading @code{getaddrinfo}

@cindex @code{addrinfo} object type
@cindex host name lookup
@cindex service name lookup

The @code{getaddrinfo} procedure maps host and service names to socket addresses
and associated information in a protocol-independent way.

@deffn {Scheme Procedure} getaddrinfo name service [hint_flags [hint_family [hint_socktype [hint_protocol]]]]
@deffnx {C Function} scm_getaddrinfo (name, service, hint_flags, hint_family, hint_socktype, hint_protocol)
Return a list of @code{addrinfo} structures containing
a socket address and associated information for host @var{name}
and/or @var{service} to be used in creating a socket with
which to address the specified service.

@example
(let* ((ai (car (getaddrinfo "www.gnu.org" "http")))
       (s  (socket (addrinfo:fam ai) (addrinfo:socktype ai)
                   (addrinfo:protocol ai))))
  (connect s (addrinfo:addr ai))
  s)
@end example

When @var{service} is omitted or is @code{#f}, return
network-level addresses for @var{name}.  When @var{name}
is @code{#f} @var{service} must be provided and service
locations local to the caller are returned.

Additional hints can be provided.  When specified,
@var{hint_flags} should be a bitwise-or of zero or more
constants among the following:

@table @code
@item AI_PASSIVE
Socket address is intended for @code{bind}.

@item AI_CANONNAME
Request for canonical host name, available via
@code{addrinfo:canonname}.  This makes sense mainly when
DNS lookups are involved.

@item AI_NUMERICHOST
Specifies that @var{name} is a numeric host address string
(e.g., @code{"127.0.0.1"}), meaning that name resolution
will not be used.

@item AI_NUMERICSERV
Likewise, specifies that @var{service} is a numeric port
string (e.g., @code{"80"}).

@item AI_ADDRCONFIG
Return only addresses configured on the local system  It is
highly recommended to provide this flag when the returned
socket addresses are to be used to make connections;
otherwise, some of the returned addresses could be unreachable
or use a protocol that is not supported.

@item AI_V4MAPPED
When looking up IPv6 addresses, return mapped IPv4 addresses if
there is no IPv6 address available at all.

@item AI_ALL
If this flag is set along with @code{AI_V4MAPPED} when looking up IPv6
addresses, return all IPv6 addresses as well as all IPv4 addresses, the latter
mapped to IPv6 format.
@end table

When given, @var{hint_family} should specify the requested
address family, e.g., @code{AF_INET6}.  Similarly,
@var{hint_socktype} should specify the requested socket type
(e.g., @code{SOCK_DGRAM}), and @var{hint_protocol} should
specify the requested protocol (its value is interpreted
as in calls to @code{socket}).

On error, an exception with key @code{getaddrinfo-error} is
thrown, with an error code (an integer) as its argument:

@example
(catch 'getaddrinfo-error
  (lambda ()
    (getaddrinfo "www.gnu.org" "gopher"))
  (lambda (key errcode)
    (cond ((= errcode EAI_SERVICE)
	   (display "doesn't know about Gopher!\n"))
	  ((= errcode EAI_NONAME)
	   (display "www.gnu.org not found\\n"))
	  (else
	   (format #t "something wrong: ~a\n"
		   (gai-strerror errcode))))))
@end example

Error codes are:

@table @code
@item EAI_AGAIN
The name or service could not be resolved at this time. Future
attempts may succeed.

@item EAI_BADFLAGS
@var{hint_flags} contains an invalid value.

@item EAI_FAIL
A non-recoverable error occurred when attempting to
resolve the name.

@item EAI_FAMILY
@var{hint_family} was not recognized.

@item EAI_NONAME
Either @var{name} does not resolve for the supplied parameters,
or neither @var{name} nor @var{service} were supplied.

@item EAI_NODATA
This non-POSIX error code can be returned on some systems (GNU
and Darwin, at least), for example when @var{name} is known
but requests that were made turned out no data.  Error handling
code should be prepared to handle it when it is defined.

@item EAI_SERVICE
@var{service} was not recognized for the specified socket type.

@item EAI_SOCKTYPE
@var{hint_socktype} was not recognized.

@item EAI_SYSTEM
A system error occurred.  In C, the error code can be found in
@code{errno}; this value is not accessible from Scheme, but in
practice it provides little information about the actual error
cause.
@c See <http://bugs.gnu.org/13958>.
@end table

Users are encouraged to read the
@url{http://www.opengroup.org/onlinepubs/9699919799/functions/getaddrinfo.html,
"POSIX specification} for more details.
@end deffn

The following procedures take an @code{addrinfo} object as returned by
@code{getaddrinfo}:

@deffn {Scheme Procedure} addrinfo:flags ai
Return flags for @var{ai} as a bitwise or of @code{AI_} values (see above).
@end deffn

@deffn {Scheme Procedure} addrinfo:fam ai
Return the address family of @var{ai} (a @code{AF_} value).
@end deffn

@deffn {Scheme Procedure} addrinfo:socktype ai
Return the socket type for @var{ai} (a @code{SOCK_} value).
@end deffn

@deffn {Scheme Procedure} addrinfo:protocol ai
Return the protocol of @var{ai}.
@end deffn

@deffn {Scheme Procedure} addrinfo:addr ai
Return the socket address associated with @var{ai} as a @code{sockaddr}
object (@pxref{Network Socket Address}).
@end deffn

@deffn {Scheme Procedure} addrinfo:canonname ai
Return a string for the canonical name associated with @var{ai} if
the @code{AI_CANONNAME} flag was supplied.
@end deffn

@subsubheading The Host Database
@cindex @file{/etc/hosts}
@cindex network database

A @dfn{host object} is a structure that represents what is known about a
network host, and is the usual way of representing a system's network
identity inside software.

The following functions accept a host object and return a selected
component:

@deffn {Scheme Procedure} hostent:name host
The ``official'' hostname for @var{host}.
@end deffn
@deffn {Scheme Procedure} hostent:aliases host
A list of aliases for @var{host}.
@end deffn
@deffn {Scheme Procedure} hostent:addrtype host
The host address type, one of the @code{AF} constants, such as
@code{AF_INET} or @code{AF_INET6}.
@end deffn
@deffn {Scheme Procedure} hostent:length host
The length of each address for @var{host}, in bytes.
@end deffn
@deffn {Scheme Procedure} hostent:addr-list host
The list of network addresses associated with @var{host}.  For
@code{AF_INET} these are integer IPv4 address (@pxref{Network Address
Conversion}).
@end deffn

The following procedures can be used to search the host database.  However,
@code{getaddrinfo} should be preferred over them since it's more generic and
thread-safe.

@deffn {Scheme Procedure} gethost [host]
@deffnx {Scheme Procedure} gethostbyname hostname
@deffnx {Scheme Procedure} gethostbyaddr address
@deffnx {C Function} scm_gethost (host)
Look up a host by name or address, returning a host object.  The
@code{gethost} procedure will accept either a string name or an integer
address; if given no arguments, it behaves like @code{gethostent} (see
below).  If a name or address is supplied but the address can not be
found, an error will be thrown to one of the keys:
@code{host-not-found}, @code{try-again}, @code{no-recovery} or
@code{no-data}, corresponding to the equivalent @code{h_error} values.
Unusual conditions may result in errors thrown to the
@code{system-error} or @code{misc_error} keys.

@lisp
(gethost "www.gnu.org")
@result{} #("www.gnu.org" () 2 4 (3353880842))

(gethostbyname "www.emacs.org")
@result{} #("emacs.org" ("www.emacs.org") 2 4 (1073448978))
@end lisp
@end deffn

The following procedures may be used to step through the host
database from beginning to end.

@deffn {Scheme Procedure} sethostent [stayopen]
Initialize an internal stream from which host objects may be read.  This
procedure must be called before any calls to @code{gethostent}, and may
also be called afterward to reset the host entry stream.  If
@var{stayopen} is supplied and is not @code{#f}, the database is not
closed by subsequent @code{gethostbyname} or @code{gethostbyaddr} calls,
possibly giving an efficiency gain.
@end deffn

@deffn {Scheme Procedure} gethostent
Return the next host object from the host database, or @code{#f} if
there are no more hosts to be found (or an error has been encountered).
This procedure may not be used before @code{sethostent} has been called.
@end deffn

@deffn {Scheme Procedure} endhostent
Close the stream used by @code{gethostent}.  The return value is unspecified.
@end deffn

@deffn {Scheme Procedure} sethost [stayopen]
@deffnx {C Function} scm_sethost (stayopen)
If @var{stayopen} is omitted, this is equivalent to @code{endhostent}.
Otherwise it is equivalent to @code{sethostent stayopen}.
@end deffn

@subsubheading The Network Database
@cindex network database

The following functions accept an object representing a network
and return a selected component:

@deffn {Scheme Procedure} netent:name net
The ``official'' network name.
@end deffn
@deffn {Scheme Procedure} netent:aliases net
A list of aliases for the network.
@end deffn
@deffn {Scheme Procedure} netent:addrtype net
The type of the network number.  Currently, this returns only
@code{AF_INET}.
@end deffn
@deffn {Scheme Procedure} netent:net net
The network number.
@end deffn

The following procedures are used to search the network database:

@deffn {Scheme Procedure} getnet [net]
@deffnx {Scheme Procedure} getnetbyname net-name
@deffnx {Scheme Procedure} getnetbyaddr net-number
@deffnx {C Function} scm_getnet (net)
Look up a network by name or net number in the network database.  The
@var{net-name} argument must be a string, and the @var{net-number}
argument must be an integer.  @code{getnet} will accept either type of
argument, behaving like @code{getnetent} (see below) if no arguments are
given.
@end deffn

The following procedures may be used to step through the network
database from beginning to end.

@deffn {Scheme Procedure} setnetent [stayopen]
Initialize an internal stream from which network objects may be read.  This
procedure must be called before any calls to @code{getnetent}, and may
also be called afterward to reset the net entry stream.  If
@var{stayopen} is supplied and is not @code{#f}, the database is not
closed by subsequent @code{getnetbyname} or @code{getnetbyaddr} calls,
possibly giving an efficiency gain.
@end deffn

@deffn {Scheme Procedure} getnetent
Return the next entry from the network database.
@end deffn

@deffn {Scheme Procedure} endnetent
Close the stream used by @code{getnetent}.  The return value is unspecified.
@end deffn

@deffn {Scheme Procedure} setnet [stayopen]
@deffnx {C Function} scm_setnet (stayopen)
If @var{stayopen} is omitted, this is equivalent to @code{endnetent}.
Otherwise it is equivalent to @code{setnetent stayopen}.
@end deffn

@subsubheading The Protocol Database
@cindex @file{/etc/protocols}
@cindex protocols
@cindex network protocols

The following functions accept an object representing a protocol
and return a selected component:

@deffn {Scheme Procedure} protoent:name protocol
The ``official'' protocol name.
@end deffn
@deffn {Scheme Procedure} protoent:aliases protocol
A list of aliases for the protocol.
@end deffn
@deffn {Scheme Procedure} protoent:proto protocol
The protocol number.
@end deffn

The following procedures are used to search the protocol database:

@deffn {Scheme Procedure} getproto [protocol]
@deffnx {Scheme Procedure} getprotobyname name
@deffnx {Scheme Procedure} getprotobynumber number
@deffnx {C Function} scm_getproto (protocol)
Look up a network protocol by name or by number.  @code{getprotobyname}
takes a string argument, and @code{getprotobynumber} takes an integer
argument.  @code{getproto} will accept either type, behaving like
@code{getprotoent} (see below) if no arguments are supplied.
@end deffn

The following procedures may be used to step through the protocol
database from beginning to end.

@deffn {Scheme Procedure} setprotoent [stayopen]
Initialize an internal stream from which protocol objects may be read.  This
procedure must be called before any calls to @code{getprotoent}, and may
also be called afterward to reset the protocol entry stream.  If
@var{stayopen} is supplied and is not @code{#f}, the database is not
closed by subsequent @code{getprotobyname} or @code{getprotobynumber} calls,
possibly giving an efficiency gain.
@end deffn

@deffn {Scheme Procedure} getprotoent
Return the next entry from the protocol database.
@end deffn

@deffn {Scheme Procedure} endprotoent
Close the stream used by @code{getprotoent}.  The return value is unspecified.
@end deffn

@deffn {Scheme Procedure} setproto [stayopen]
@deffnx {C Function} scm_setproto (stayopen)
If @var{stayopen} is omitted, this is equivalent to @code{endprotoent}.
Otherwise it is equivalent to @code{setprotoent stayopen}.
@end deffn

@subsubheading The Service Database
@cindex @file{/etc/services}
@cindex services
@cindex network services

The following functions accept an object representing a service
and return a selected component:

@deffn {Scheme Procedure} servent:name serv
The ``official'' name of the network service.
@end deffn
@deffn {Scheme Procedure} servent:aliases serv
A list of aliases for the network service.
@end deffn
@deffn {Scheme Procedure} servent:port serv
The Internet port used by the service.
@end deffn
@deffn {Scheme Procedure} servent:proto serv
The protocol used by the service.  A service may be listed many times
in the database under different protocol names.
@end deffn

The following procedures are used to search the service database:

@deffn {Scheme Procedure} getserv [name [protocol]]
@deffnx {Scheme Procedure} getservbyname name protocol
@deffnx {Scheme Procedure} getservbyport port protocol
@deffnx {C Function} scm_getserv (name, protocol)
Look up a network service by name or by service number, and return a
network service object.  The @var{protocol} argument specifies the name
of the desired protocol; if the protocol found in the network service
database does not match this name, a system error is signalled.

The @code{getserv} procedure will take either a service name or number
as its first argument; if given no arguments, it behaves like
@code{getservent} (see below).

@lisp
(getserv "imap" "tcp")
@result{} #("imap2" ("imap") 143 "tcp")

(getservbyport 88 "udp")
@result{} #("kerberos" ("kerberos5" "krb5") 88 "udp")
@end lisp
@end deffn

The following procedures may be used to step through the service
database from beginning to end.

@deffn {Scheme Procedure} setservent [stayopen]
Initialize an internal stream from which service objects may be read.  This
procedure must be called before any calls to @code{getservent}, and may
also be called afterward to reset the service entry stream.  If
@var{stayopen} is supplied and is not @code{#f}, the database is not
closed by subsequent @code{getservbyname} or @code{getservbyport} calls,
possibly giving an efficiency gain.
@end deffn

@deffn {Scheme Procedure} getservent
Return the next entry from the services database.
@end deffn

@deffn {Scheme Procedure} endservent
Close the stream used by @code{getservent}.  The return value is unspecified.
@end deffn

@deffn {Scheme Procedure} setserv [stayopen]
@deffnx {C Function} scm_setserv (stayopen)
If @var{stayopen} is omitted, this is equivalent to @code{endservent}.
Otherwise it is equivalent to @code{setservent stayopen}.
@end deffn


@node Network Socket Address
@subsubsection Network Socket Address
@cindex socket address
@cindex network socket address
@tpindex Socket address

A @dfn{socket address} object identifies a socket endpoint for
communication.  In the case of @code{AF_INET} for instance, the socket
address object comprises the host address (or interface on the host)
and a port number which specifies a particular open socket in a
running client or server process.  A socket address object can be
created with,

@deffn {Scheme Procedure} make-socket-address AF_INET ipv4addr port
@deffnx {Scheme Procedure} make-socket-address AF_INET6 ipv6addr port [flowinfo [scopeid]]
@deffnx {Scheme Procedure} make-socket-address AF_UNIX path
@deffnx {C Function} scm_make_socket_address (family, address, arglist)
Return a new socket address object.  The first argument is the address
family, one of the @code{AF} constants, then the arguments vary
according to the family.

For @code{AF_INET} the arguments are an IPv4 network address number
(@pxref{Network Address Conversion}), and a port number.

For @code{AF_INET6} the arguments are an IPv6 network address number
and a port number.  Optional @var{flowinfo} and @var{scopeid}
arguments may be given (both integers, default 0).

For @code{AF_UNIX} the argument is a filename (a string).

The C function @code{scm_make_socket_address} takes the @var{family}
and @var{address} arguments directly, then @var{arglist} is a list of
further arguments, being the port for IPv4, port and optional flowinfo
and scopeid for IPv6, or the empty list @code{SCM_EOL} for Unix
domain.
@end deffn

@noindent
The following functions access the fields of a socket address object,

@deffn {Scheme Procedure} sockaddr:fam sa
Return the address family from socket address object @var{sa}.  This
is one of the @code{AF} constants (e.g.@: @code{AF_INET}).
@end deffn

@deffn {Scheme Procedure} sockaddr:path sa
For an @code{AF_UNIX} socket address object @var{sa}, return the
filename.
@end deffn

@deffn {Scheme Procedure} sockaddr:addr sa
For an @code{AF_INET} or @code{AF_INET6} socket address object
@var{sa}, return the network address number.
@end deffn

@deffn {Scheme Procedure} sockaddr:port sa
For an @code{AF_INET} or @code{AF_INET6} socket address object
@var{sa}, return the port number.
@end deffn

@deffn {Scheme Procedure} sockaddr:flowinfo sa
For an @code{AF_INET6} socket address object @var{sa}, return the
flowinfo value.
@end deffn

@deffn {Scheme Procedure} sockaddr:scopeid sa
For an @code{AF_INET6} socket address object @var{sa}, return the
scope ID value.
@end deffn

@tpindex @code{struct sockaddr}
@tpindex @code{sockaddr}
The functions below convert to and from the C @code{struct sockaddr}
(@pxref{Address Formats,,, libc, The GNU C Library Reference Manual}).
That structure is a generic type, an application can cast to or from
@code{struct sockaddr_in}, @code{struct sockaddr_in6} or @code{struct
sockaddr_un} according to the address family.

In a @code{struct sockaddr} taken or returned, the byte ordering in
the fields follows the C conventions (@pxref{Byte Order,, Byte Order
Conversion, libc, The GNU C Library Reference Manual}).  This means
network byte order for @code{AF_INET} host address
(@code{sin_addr.s_addr}) and port number (@code{sin_port}), and
@code{AF_INET6} port number (@code{sin6_port}).  But at the Scheme
level these values are taken or returned in host byte order, so the
port is an ordinary integer, and the host address likewise is an
ordinary integer (as described in @ref{Network Address Conversion}).

@deftypefn {C Function} {struct sockaddr *} scm_c_make_socket_address (SCM family, SCM address, SCM args, size_t *outsize)
Return a newly-@code{malloc}ed @code{struct sockaddr} created from
arguments like those taken by @code{scm_make_socket_address} above.

The size (in bytes) of the @code{struct sockaddr} return is stored
into @code{*@var{outsize}}.  An application must call @code{free} to
release the returned structure when no longer required.
@end deftypefn

@deftypefn {C Function} SCM scm_from_sockaddr (const struct sockaddr *address, unsigned address_size)
Return a Scheme socket address object from the C @var{address}
structure.  @var{address_size} is the size in bytes of @var{address}.
@end deftypefn

@deftypefn {C Function} {struct sockaddr *} scm_to_sockaddr (SCM address, size_t *address_size)
Return a newly-@code{malloc}ed @code{struct sockaddr} from a Scheme
level socket address object.

The size (in bytes) of the @code{struct sockaddr} return is stored
into @code{*@var{outsize}}.  An application must call @code{free} to
release the returned structure when no longer required.
@end deftypefn


@node Network Sockets and Communication
@subsubsection Network Sockets and Communication
@cindex socket
@cindex network socket

Socket ports can be created using @code{socket} and @code{socketpair}.
The ports are initially unbuffered, to make reading and writing to the
same port more reliable.  A buffer can be added to the port using
@code{setvbuf} (@pxref{Buffering}).

Most systems have limits on how many files and sockets can be open, so
it's strongly recommended that socket ports be closed explicitly when
no longer required (@pxref{Ports}).

Some of the underlying C functions take values in network byte order,
but the convention in Guile is that at the Scheme level everything is
ordinary host byte order and conversions are made automatically where
necessary.

@deffn {Scheme Procedure} socket family style proto
@deffnx {C Function} scm_socket (family, style, proto)
Return a new socket port of the type specified by @var{family},
@var{style} and @var{proto}.  All three parameters are integers.  The
possible values for @var{family} are as follows, where supported by
the system,

@defvar PF_UNIX
@defvarx PF_INET
@defvarx PF_INET6
@end defvar

The possible values for @var{style} are as follows, again where
supported by the system,

@defvar SOCK_STREAM
@defvarx SOCK_DGRAM
@defvarx SOCK_RAW
@defvarx SOCK_RDM
@defvarx SOCK_SEQPACKET
@end defvar

@var{proto} can be obtained from a protocol name using
@code{getprotobyname} (@pxref{Network Databases}).  A value of zero
means the default protocol, which is usually right.

A socket cannot by used for communication until it has been connected
somewhere, usually with either @code{connect} or @code{accept} below.
@end deffn

@deffn {Scheme Procedure} socketpair family style proto
@deffnx {C Function} scm_socketpair (family, style, proto)
Return a pair, the @code{car} and @code{cdr} of which are two unnamed
socket ports connected to each other.  The connection is full-duplex,
so data can be transferred in either direction between the two.

@var{family}, @var{style} and @var{proto} are as per @code{socket}
above.  But many systems only support socket pairs in the
@code{PF_UNIX} family.  Zero is likely to be the only meaningful value
for @var{proto}.
@end deffn

@deffn {Scheme Procedure} getsockopt sock level optname
@deffnx {Scheme Procedure} setsockopt sock level optname value
@deffnx {C Function} scm_getsockopt (sock, level, optname)
@deffnx {C Function} scm_setsockopt (sock, level, optname, value)
Get or set an option on socket port @var{sock}.  @code{getsockopt}
returns the current value.  @code{setsockopt} sets a value and the
return is unspecified.

@var{level} is an integer specifying a protocol layer, either
@code{SOL_SOCKET} for socket level options, or a protocol number from
the @code{IPPROTO} constants or @code{getprotoent} (@pxref{Network
Databases}).

@defvar SOL_SOCKET
@defvarx IPPROTO_IP
@defvarx IPPROTO_IPV6
@defvarx IPPROTO_TCP
@defvarx IPPROTO_UDP
@end defvar

@var{optname} is an integer specifying an option within the protocol
layer.

For @code{SOL_SOCKET} level the following @var{optname}s are defined
(when provided by the system).  For their meaning see
@ref{Socket-Level Options,,, libc, The GNU C Library Reference
Manual}, or @command{man 7 socket}.

@defvar SO_DEBUG
@defvarx SO_REUSEADDR
@defvarx SO_STYLE
@defvarx SO_TYPE
@defvarx SO_ERROR
@defvarx SO_DONTROUTE
@defvarx SO_BROADCAST
@defvarx SO_SNDBUF
@defvarx SO_RCVBUF
@defvarx SO_KEEPALIVE
@defvarx SO_OOBINLINE
@defvarx SO_NO_CHECK
@defvarx SO_PRIORITY
@defvarx SO_REUSEPORT
@defvarx SO_RCVTIMEO
@defvarx SO_SNDTIMEO
The @var{value} taken or returned is an integer.
@end defvar

@defvar SO_LINGER
The @var{value} taken or returned is a pair of integers
@code{(@var{ENABLE} . @var{TIMEOUT})}.  On old systems without timeout
support (ie.@: without @code{struct linger}), only @var{ENABLE} has an
effect but the value in Guile is always a pair.
@end defvar

@c  Note that we refer only to ``man ip'' here.  On GNU/Linux it's
@c  ``man 7 ip'' but on NetBSD it's ``man 4 ip''.
@c 
For IP level (@code{IPPROTO_IP}) the following @var{optname}s are
defined (when provided by the system).  See @command{man ip} for what
they mean.

@defvar IP_MULTICAST_IF
This sets the source interface used by multicast traffic.
@end defvar

@defvar IP_MULTICAST_TTL
This sets the default TTL for multicast traffic. This defaults
to 1 and should be increased to allow traffic to pass beyond the
local network.
@end defvar

@defvar IP_ADD_MEMBERSHIP
@defvarx IP_DROP_MEMBERSHIP
These can be used only with @code{setsockopt}, not @code{getsockopt}.
@var{value} is a pair @code{(@var{MULTIADDR} . @var{INTERFACEADDR})}
of integer IPv4 addresses (@pxref{Network Address Conversion}).
@var{MULTIADDR} is a multicast address to be added to or dropped from
the interface @var{INTERFACEADDR}.  @var{INTERFACEADDR} can be
@code{INADDR_ANY} to have the system select the interface.
@var{INTERFACEADDR} can also be an interface index number, on systems
supporting that.
@end defvar

Last, for IPv6 level (@code{IPPROTO_IPV6}), the following @var{optname}s
are defined.  See @command{man 7 ipv6} for details.

@defvar IPV6_V6ONLY
Determines whether an @code{AF_INET6} socket is restricted to
transmitting IPv6 packets only, or whether it can also transmit packets
for an IPv4-mapped IPv6 address.
@end defvar

@end deffn

For @code{IPPROTO_TCP} level the following @var{optname}s are defined
(when provided by the system).  For their meaning see @command{man 7
tcp}.

@defvar TCP_NODELAY
@defvarx TCP_CORK
The @var{value} taken or returned is an integer.
@end defvar

@deffn {Scheme Procedure} shutdown sock how
@deffnx {C Function} scm_shutdown (sock, how)
Sockets can be closed simply by using @code{close-port}.  The
@code{shutdown} procedure allows reception or transmission on a
connection to be shut down individually, according to the parameter
@var{how}:

@table @asis
@item 0
Stop receiving data for this socket.  If further data arrives, reject it.
@item 1
Stop trying to transmit data from this socket.  Discard any
data waiting to be sent.  Stop looking for acknowledgement of
data already sent; don't retransmit it if it is lost.
@item 2
Stop both reception and transmission.
@end table

The return value is unspecified.
@end deffn

@deffn {Scheme Procedure} connect sock sockaddr
@deffnx {Scheme Procedure} connect sock AF_INET ipv4addr port
@deffnx {Scheme Procedure} connect sock AF_INET6 ipv6addr port [flowinfo [scopeid]]
@deffnx {Scheme Procedure} connect sock AF_UNIX path
@deffnx {C Function} scm_connect (sock, fam, address, args)
Initiate a connection on socket port @var{sock} to a given address.  The
destination is either a socket address object, or arguments the same as
@code{make-socket-address} would take to make such an object
(@pxref{Network Socket Address}).  Return true unless the socket was
configured as non-blocking and the connection could not be made
immediately.

@example
(connect sock AF_INET INADDR_LOOPBACK 23)
(connect sock (make-socket-address AF_INET INADDR_LOOPBACK 23))
@end example
@end deffn

@deffn {Scheme Procedure} bind sock sockaddr
@deffnx {Scheme Procedure} bind sock AF_INET ipv4addr port
@deffnx {Scheme Procedure} bind sock AF_INET6 ipv6addr port [flowinfo [scopeid]]
@deffnx {Scheme Procedure} bind sock AF_UNIX path
@deffnx {C Function} scm_bind (sock, fam, address, args)
Bind socket port @var{sock} to the given address.  The address is
either a socket address object, or arguments the same as
@code{make-socket-address} would take to make such an object
(@pxref{Network Socket Address}).  The return value is unspecified.

Generally a socket is only explicitly bound to a particular address
when making a server, i.e.@: to listen on a particular port.  For an
outgoing connection the system will assign a local address
automatically, if not already bound.

@example
(bind sock AF_INET INADDR_ANY 12345)
(bind sock (make-socket-address AF_INET INADDR_ANY 12345))
@end example
@end deffn

@deffn {Scheme Procedure} listen sock backlog
@deffnx {C Function} scm_listen (sock, backlog)
Enable @var{sock} to accept connection
requests.  @var{backlog} is an integer specifying
the maximum length of the queue for pending connections.
If the queue fills, new clients will fail to connect until
the server calls @code{accept} to accept a connection from
the queue.

The return value is unspecified.
@end deffn

@deffn {Scheme Procedure} accept sock [flags]
@deffnx {C Function} scm_accept (sock)
Accept a connection from socket port @var{sock} which has been enabled
for listening with @code{listen} above.

If there are no incoming connections in the queue, there are two
possible behaviors, depending on whether @var{sock} has been configured
for non-blocking operation or not:

@itemize
@item
If there is no connection waiting and the socket was set to non-blocking
mode with the @code{O_NONBLOCK} port option (@pxref{Ports and File
Descriptors,@code{fcntl}}), return @code{#f} directly.

@item
Otherwise wait until a connection is available.
@end itemize

The return value is a pair.  The @code{car} is a new socket port,
connected and ready to communicate.  The @code{cdr} is a socket address
object (@pxref{Network Socket Address}) which is where the remote
connection is from (like @code{getpeername} below).

@var{flags}, if given, may include @code{SOCK_CLOEXEC} or
@code{SOCK_NONBLOCK}, which like @code{O_CLOEXEC} and @code{O_NONBLOCK}
apply to the newly accepted socket.

All communication takes place using the new socket returned.  The
given @var{sock} remains bound and listening, and @code{accept} may be
called on it again to get another incoming connection when desired.
@end deffn

@deffn {Scheme Procedure} getsockname sock
@deffnx {C Function} scm_getsockname (sock)
Return a socket address object which is the where @var{sock} is bound
locally.  @var{sock} may have obtained its local address from
@code{bind} (above), or if a @code{connect} is done with an otherwise
unbound socket (which is usual) then the system will have assigned an
address.

Note that on many systems the address of a socket in the
@code{AF_UNIX} namespace cannot be read.
@end deffn

@deffn {Scheme Procedure} getpeername sock
@deffnx {C Function} scm_getpeername (sock)
Return a socket address object which is where @var{sock} is connected
to, i.e.@: the remote endpoint.

Note that on many systems the address of a socket in the
@code{AF_UNIX} namespace cannot be read.
@end deffn

@deffn {Scheme Procedure} recv! sock buf [flags]
@deffnx {C Function} scm_recv (sock, buf, flags)
Receive data from a socket port.
@var{sock} must already
be bound to the address from which data is to be received.
@var{buf} is a bytevector into which
the data will be written.  The size of @var{buf} limits
the amount of
data which can be received: in the case of packet
protocols, if a packet larger than this limit is encountered
then some data
will be irrevocably lost.

@vindex MSG_OOB
@vindex MSG_PEEK
@vindex MSG_DONTROUTE
The optional @var{flags} argument is a value or bitwise OR of
@code{MSG_OOB}, @code{MSG_PEEK}, @code{MSG_DONTROUTE} etc.

The value returned is the number of bytes read from the
socket.

Note that the data is read directly from the socket file
descriptor:
any unread buffered port data is ignored.
@end deffn

@deffn {Scheme Procedure} send sock message [flags]
@deffnx {C Function} scm_send (sock, message, flags)
@vindex MSG_OOB
@vindex MSG_PEEK
@vindex MSG_DONTROUTE
Transmit bytevector @var{message} on socket port @var{sock}.
@var{sock} must already be bound to a destination address.  The value
returned is the number of bytes transmitted---it's possible for this
to be less than the length of @var{message} if the socket is set to be
non-blocking.  The optional @var{flags} argument is a value or bitwise
OR of @code{MSG_OOB}, @code{MSG_PEEK}, @code{MSG_DONTROUTE} etc.

Note that the data is written directly to the socket
file descriptor:
any unflushed buffered port data is ignored.
@end deffn

@deffn {Scheme Procedure} recvfrom! sock buf [flags [start [end]]]
@deffnx {C Function} scm_recvfrom (sock, buf, flags, start, end)
Receive data from socket port @var{sock}, returning the originating
address as well as the data.  This function is usually for datagram
sockets, but can be used on stream-oriented sockets too.

The data received is stored in bytevector @var{buf}, using
either the whole bytevector or just the region between the optional
@var{start} and @var{end} positions.  The size of @var{buf}
limits the amount of data that can be received.  For datagram
protocols if a packet larger than this is received then excess
bytes are irrevocably lost.

The return value is a pair.  The @code{car} is the number of bytes
read.  The @code{cdr} is a socket address object (@pxref{Network
Socket Address}) which is where the data came from, or @code{#f} if
the origin is unknown.

@vindex MSG_OOB
@vindex MSG_PEEK
@vindex MSG_DONTROUTE
The optional @var{flags} argument is a or bitwise-OR (@code{logior})
of @code{MSG_OOB}, @code{MSG_PEEK}, @code{MSG_DONTROUTE} etc.

Data is read directly from the socket file descriptor, any buffered
port data is ignored.

@c  This was linux kernel 2.6.15 and glibc 2.3.6, not sure what any
@c  specs are supposed to say about recvfrom threading.
@c
On a GNU/Linux system @code{recvfrom!} is not multi-threading, all
threads stop while a @code{recvfrom!} call is in progress.  An
application may need to use @code{select}, @code{O_NONBLOCK} or
@code{MSG_DONTWAIT} to avoid this.
@end deffn

@deffn {Scheme Procedure} sendto sock message sockaddr [flags]
@deffnx {Scheme Procedure} sendto sock message AF_INET ipv4addr port [flags]
@deffnx {Scheme Procedure} sendto sock message AF_INET6 ipv6addr port [flowinfo [scopeid [flags]]]
@deffnx {Scheme Procedure} sendto sock message AF_UNIX path [flags]
@deffnx {C Function} scm_sendto (sock, message, fam, address, args_and_flags)
Transmit bytevector @var{message} as a datagram socket port
@var{sock}.  The destination is specified either as a socket address
object, or as arguments the same as would be taken by
@code{make-socket-address} to create such an object (@pxref{Network
Socket Address}).

The destination address may be followed by an optional @var{flags}
argument which is a @code{logior} (@pxref{Bitwise Operations}) of
@code{MSG_OOB}, @code{MSG_PEEK}, @code{MSG_DONTROUTE} etc.

The value returned is the number of bytes transmitted --
it's possible for
this to be less than the length of @var{message} if the
socket is
set to be non-blocking.
Note that the data is written directly to the socket
file descriptor:
any unflushed buffered port data is ignored.
@end deffn


@node Internet Socket Examples
@subsubsection Network Socket Examples
@cindex network examples
@cindex socket examples

The following give examples of how to use network sockets.

@subsubheading Internet Socket Client Example

@cindex socket client example
The following example demonstrates an Internet socket client.
It connects to the HTTP daemon running on the local machine and
returns the contents of the root index URL.

@example
(let ((s (socket PF_INET SOCK_STREAM 0)))
  (connect s AF_INET (inet-pton AF_INET "127.0.0.1") 80)
  (display "GET / HTTP/1.0\r\n\r\n" s)

  (do ((line (read-line s) (read-line s)))
      ((eof-object? line))
    (display line)
    (newline)))
@end example


@subsubheading Internet Socket Server Example

@cindex socket server example
The following example shows a simple Internet server which listens on
port 2904 for incoming connections and sends a greeting back to the
client.

@example
(let ((s (socket PF_INET SOCK_STREAM 0)))
  (setsockopt s SOL_SOCKET SO_REUSEADDR 1)
  ;; @r{Specific address?}
  ;; @r{(bind s AF_INET (inet-pton AF_INET "127.0.0.1") 2904)}
  (bind s AF_INET INADDR_ANY 2904)
  (listen s 5)

  (simple-format #t "Listening for clients in pid: ~S" (getpid))
  (newline)

  (while #t
    (let* ((client-connection (accept s))
           (client-details (cdr client-connection))
           (client (car client-connection)))
      (simple-format #t "Got new client connection: ~S"
                     client-details)
      (newline)
      (simple-format #t "Client address: ~S"
                     (gethostbyaddr
                      (sockaddr:addr client-details)))
      (newline)
      ;; @r{Send back the greeting to the client port}
      (display "Hello client\r\n" client)
      (close client))))
@end example


@node System Identification
@subsection System Identification
@cindex system name

This section lists the various procedures Guile provides for accessing
information about the system it runs on.

@deffn {Scheme Procedure} uname
@deffnx {C Function} scm_uname ()
Return an object with some information about the computer
system the program is running on.

The following procedures accept an object as returned by @code{uname}
and return a selected component (all of which are strings).

@deffn {Scheme Procedure} utsname:sysname un
The name of the operating system.
@end deffn
@deffn {Scheme Procedure} utsname:nodename un
The network name of the computer.
@end deffn
@deffn {Scheme Procedure} utsname:release un
The current release level of the operating system implementation.
@end deffn
@deffn {Scheme Procedure} utsname:version un
The current version level within the release of the operating system.
@end deffn
@deffn {Scheme Procedure} utsname:machine un
A description of the hardware.
@end deffn
@end deffn

@deffn {Scheme Procedure} gethostname
@deffnx {C Function} scm_gethostname ()
@cindex host name
Return the host name of the current processor.
@end deffn

@deffn {Scheme Procedure} sethostname name
@deffnx {C Function} scm_sethostname (name)
Set the host name of the current processor to @var{name}. May
only be used by the superuser.  The return value is not
specified.
@end deffn

@node Locales
@subsection Locales
@cindex locale

@deffn {Scheme Procedure} setlocale category [locale]
@deffnx {C Function} scm_setlocale (category, locale)
Get or set the current locale, used for various internationalizations.
Locales are strings, such as @samp{sv_SE}.

If @var{locale} is given then the locale for the given @var{category}
is set and the new value returned.  If @var{locale} is not given then
the current value is returned.  @var{category} should be one of the
following values (@pxref{Locale Categories, Categories of Activities
that Locales Affect,, libc, The GNU C Library Reference Manual}):

@defvar LC_ALL
@defvarx LC_COLLATE
@defvarx LC_CTYPE
@defvarx LC_MESSAGES
@defvarx LC_MONETARY
@defvarx LC_NUMERIC
@defvarx LC_TIME
@end defvar

@cindex @code{LANG}
A common usage is @samp{(setlocale LC_ALL "")}, which initializes all
categories based on standard environment variables (@code{LANG} etc).
For full details on categories and locale names @pxref{Locales,,
Locales and Internationalization, libc, The GNU C Library Reference
Manual}.

Note that @code{setlocale} affects locale settings for the whole
process.  @xref{i18n Introduction, locale objects and
@code{make-locale}}, for a thread-safe alternative.
@end deffn

@node Encryption
@subsection Encryption
@cindex encryption

Please note that the procedures in this section are not suited for
strong encryption, they are only interfaces to the well-known and
common system library functions of the same name.  They are just as good
(or bad) as the underlying functions, so you should refer to your system
documentation before using them (@pxref{crypt,, Encrypting Passwords,
libc, The GNU C Library Reference Manual}).

@deffn {Scheme Procedure} crypt key salt
@deffnx {C Function} scm_crypt (key, salt)
Encrypt @var{key}, with the addition of @var{salt} (both strings),
using the @code{crypt} C library call.
@end deffn

Although @code{getpass} is not an encryption procedure per se, it
appears here because it is often used in combination with @code{crypt}:

@deffn {Scheme Procedure} getpass prompt
@deffnx {C Function} scm_getpass (prompt)
@cindex password
Display @var{prompt} to the standard error output and read
a password from @file{/dev/tty}.  If this file is not
accessible, it reads from standard input.  The password may be
up to 127 characters in length.  Additional characters and the
terminating newline character are discarded.  While reading
the password, echoing and the generation of signals by special
characters is disabled.
@end deffn


@c Local Variables:
@c TeX-master: "guile.texi"
@c End: