QNX® Neutrino® Realtime Operating System

QNX® Neutrino® Realtime Operating System
®
®
QNX Neutrino Realtime Operating System
Library Reference
For QNX ® Neutrino® 6.5.0
© 2012, QNX Software Systems Limited
© 1996–2012, QNX Software Systems Limited. All rights reserved.
QNX Software Systems Limited
1001 Farrar Road
Kanata, Ontario
Canada
K2K 0B3
Voice: +1 613 591-0931
Fax: +1 613 591-3579
Email: [email protected]
Web: http://www.qnx.com/
Electronic edition published 2012.
QNX, Momentics, Neutrino, Aviage, Photon, Photon microGUI, and Foundry27 are trademarks of QNX Software Systems Limited, which are registered trademarks and/or
used in certain jurisdictions. All other trademarks belong to their respective owners.
Contents
About This Reference
Typographical conventions
Note to Windows users
Technical support xlvii
xliii
xlv
xlvi
What’s in a Function Description?
1
Synopsis:
3
Arguments:
3
Library:
3
Description:
4
Returns:
4
Errors:
4
See also:
4
Examples:
4
Classification:
4
Function safety:
7
Manifests
9
QNX Neutrino Functions and Macros
13
abort()
17
abs()
19
accept()
21
access()
24
acos(), acosf(), acosl()
27
acosh(), acoshf(), acoshl()
29
addrinfo
31
aio_cancel()
32
aio_error()
34
aio_fsync()
36
aio_read()
38
aio_return()
41
43
aio_suspend()
aio_write()
45
aiocb
48
June 19, 2012
Contents
iii
© 2012, QNX Software Systems Limited
alarm()
50
alloca()
53
alphasort()
55
_amblksiz
57
_argc
59
_argv
60
asctime(), asctime_r()
61
asin(), asinf(), asinl()
63
asinh(), asinhf(), asinhl()
65
assert()
67
asyncmsg_channel_create()
69
72
asyncmsg_channel_destroy()
asyncmsg_connect_attach()
74
76
asyncmsg_connect_attr()
asyncmsg_connect_detach()
78
_asyncmsg_connection_attr
asyncmsg_flush()
82
84
asyncmsg_free()
asyncmsg_get()
85
87
asyncmsg_malloc()
asyncmsg_put(), asyncmsg_putv()
atan(), atanf(), atanl()
91
atan2(), atan2f()
93
atanh(), atanhf(), atanhl()
95
atexit()
97
atof()
99
atoh() 101
atoi() 103
atol(), atoll() 105
atomic_add() 107
atomic_add_value() 109
atomic_clr() 111
atomic_clr_value() 113
atomic_set() 115
atomic_set_value() 117
atomic_sub() 119
atomic_sub_value() 121
atomic_toggle() 123
atomic_toggle_value() 125
_auxv 127
basename() 128
iv
Contents
80
89
June 19, 2012
© 2012, QNX Software Systems Limited
bcmp() 130
bcopy() 132
bind() 134
bindresvport() 136
brk() 138
bsearch() 140
bt_get_backtrace() 143
bt_init_accessor() 145
bt_load_memmap() 147
bt_release_accessor() 149
bt_set_flags() 151
bt_sprn_memmap() 153
bt_sprnf_addrs() 155
bt_translate_addrs() 157
bt_unload_memmap() 159
_btext 160
btowc() 161
bzero() 162
cabs(), cabsf() 164
cache_fini() 166
CACHE_FLUSH() 167
cache_init() 169
CACHE_INVAL() 173
calloc() 175
cbrt(), cbrtf() 178
ceil(), ceilf() 180
cfgetispeed() 182
cfgetospeed() 184
cfgopen() 186
cfmakeraw() 189
cfree() 191
cfsetispeed() 192
cfsetospeed() 194
ChannelCreate(), ChannelCreate_r() 196
ChannelDestroy(), ChannelDestroy_r() 202
chdir() 204
chmod() 206
chown() 209
chroot() 212
chsize() 214
clearenv() 216
June 19, 2012
Contents
v
© 2012, QNX Software Systems Limited
clearerr() 218
clock() 220
clock_getcpuclockid() 222
clock_getres() 224
clock_gettime() 226
clock_nanosleep() 229
clock_settime() 232
ClockAdjust(), ClockAdjust_r() 235
ClockCycles() 238
ClockId(), ClockId_r() 240
ClockPeriod(), ClockPeriod_r() 242
ClockTime(), ClockTime_r() 245
close() 248
closedir() 250
closelog() 252
_cmdfd() 253
_cmdname() 254
confstr() 256
connect() 260
ConnectAttach(), ConnectAttach_r() 263
ConnectClientInfo(), ConnectClientInfo_r() 267
ConnectDetach(), ConnectDetach_r() 270
ConnectFlags(), ConnectFlags_r() 272
ConnectServerInfo(), ConnectServerInfo_r() 274
copysign(), copysignf() 277
cos(), cosf(), cosl() 279
cosh(), coshf(), coshl() 281
creat(), creat64() 283
crypt() 286
ctermid() 288
ctime(), ctime_r() 290
daemon() 292
daylight 294
DebugBreak() 295
DebugKDBreak() 296
DebugKDOutput() 297
delay() 298
devctl() 300
difftime() 309
dircntl() 311
dirent 313
vi
Contents
June 19, 2012
© 2012, QNX Software Systems Limited
dirname() 315
dispatch_block() 317
dispatch_context_alloc() 320
dispatch_context_free() 322
dispatch_create() 324
dispatch_create_channel() 327
dispatch_destroy() 329
dispatch_handler() 331
dispatch_timeout() 334
dispatch_unblock() 336
div() 338
dladdr() 340
dlclose() 342
dlerror() 344
dlopen() 345
dlsym() 352
dn_comp() 355
dn_expand() 357
drand48() 359
ds_clear() 360
ds_create() 362
ds_deregister() 364
ds_flags() 366
ds_get() 368
ds_register() 370
ds_set() 371
dup() 373
dup2() 375
eaccess() 377
_edata 379
encrypt() 380
_end 381
endfsent() 382
endgrent() 383
endhostent() 384
ENDIAN_BE16() 385
ENDIAN_BE32() 387
ENDIAN_BE64() 389
ENDIAN_LE16() 391
ENDIAN_LE32() 393
ENDIAN_LE64() 395
June 19, 2012
Contents
vii
© 2012, QNX Software Systems Limited
ENDIAN_RET16() 397
ENDIAN_RET32() 399
ENDIAN_RET64() 401
ENDIAN_SWAP16() 403
ENDIAN_SWAP32() 405
ENDIAN_SWAP64() 407
endnetent() 409
endprotoent() 410
endpwent() 411
endservent() 412
endspent() 413
endutent() 414
environ 415
eof() 416
erand48() 418
erf(), erff() 419
erfc(), erfcf(), erfcl() 421
err(), errx() 423
errno 426
_etext 434
execl() 435
execle() 440
execlp() 445
execlpe() 450
execv() 454
execve() 459
execvp() 464
execvpe() 469
_exit() 473
exit() 476
exp(), expf(), expl() 478
expm1(), expm1f() 480
fabs(), fabsf() 482
fcfgopen() 484
fchdir() 486
fchmod() 488
fchown() 491
fclose() 494
fcloseall() 496
fcntl() 498
fdatasync() 505
viii
Contents
June 19, 2012
© 2012, QNX Software Systems Limited
fdopen() 507
feof() 509
ferror() 511
fflush() 513
ffs() 516
fgetc() 517
fgetchar() 519
fgetpos() 521
fgets() 523
fgetspent() 525
fgetwc() 527
fgetws() 529
fileno() 531
flink() 533
flock() 535
flockfile() 538
floor(), floorf() 540
flushall() 542
fmod(), fmodf(), fmodl() 543
fnmatch() 545
fopen(), fopen64() 548
fork() 552
forkpty() 555
fp_exception_mask() 557
fp_exception_value() 560
fp_precision() 562
fp_rounding() 564
fp_setenv() 566
fpathconf() 569
fprintf() 572
fputc() 574
fputchar() 577
fputs() 579
fputwc() 581
fputws() 583
fread() 585
free() 587
freeaddrinfo() 589
freeifaddrs() 590
freopen(), freopen64() 591
frexp(), frexpf() 595
June 19, 2012
Contents
ix
© 2012, QNX Software Systems Limited
fscanf() 597
fseek(), fseeko(), fseeko64() 599
fsetpos() 603
fstat(), fstat64() 605
fstatvfs(), fstatvfs64() 608
fsync() 612
ftell(), ftello(), ftello64() 614
ftime() 616
ftruncate(), ftruncate64() 618
ftrylockfile() 620
ftw(), ftw64() 621
funlockfile() 623
futime() 624
fwide() 626
fwprintf() 628
fwrite() 630
fwscanf() 632
gai_strerror() 634
gamma(), gamma_r(), gammaf(), gammaf_r()
getaddrinfo() 638
getc() 644
getc_unlocked() 646
getchar() 647
getchar_unlocked() 649
getcwd() 650
getdomainname() 652
getdtablesize() 654
getegid() 655
getenv() 657
geteuid() 659
getfsfile() 661
getfsent() 663
getfsspec() 666
getgid() 668
getgrent() 670
getgrgid() 672
getgrgid_r() 674
getgrnam() 676
getgrnam_r() 678
getgrouplist() 680
getgroups() 683
x
Contents
636
June 19, 2012
© 2012, QNX Software Systems Limited
gethostbyaddr() 685
gethostbyaddr_r() 688
gethostbyname(), gethostbyname2() 691
gethostbyname_r() 694
gethostent() 697
gethostent_r() 699
gethostname() 702
getifaddrs() 704
GETIOVBASE() 706
GETIOVLEN() 707
getitimer() 708
getlogin() 710
getlogin_r() 711
getnameinfo() 713
getnetbyaddr() 717
getnetbyname() 719
getnetent() 721
getopt() 722
getpagesize() 726
getpagesizes(), getpagesizes64() 727
getpass() 729
getpeereid() 731
getpeername() 733
getpgid() 735
getpgrp() 737
getpid() 739
getppid() 740
getprio() 741
getprotobyname() 743
getprotobynumber() 745
getprotoent() 747
getpwent() 749
getpwent_r() 751
getpwnam() 753
getpwnam_r() 755
getpwuid() 757
getpwuid_r() 759
getrlimit(), getrlimit64() 761
getrusage() 764
gets() 768
getservbyname() 770
June 19, 2012
Contents
xi
© 2012, QNX Software Systems Limited
getservbyport() 772
getservent() 774
getsid() 775
getsockname() 777
getsockopt() 779
getspent(), getspent_r() 787
getspnam(), getspnam_r() 790
getsubopt() 793
gettimeofday() 797
getuid() 799
getutent() 800
getutid() 802
getutline() 804
getw() 806
getwc() 808
getwchar() 810
getwd() 812
glob() 814
globfree() 818
gmtime() 819
gmtime_r() 821
h_errno 823
hcreate() 825
hdestroy() 827
herror() 828
hostent 830
hsearch() 831
hstrerror() 834
htonl() 836
htons() 837
hwi_find_item() 838
hwi_find_tag() 840
hwi_off2tag() 842
hwi_tag2off() 843
hypot(), hypotf() 844
ICMP 846
ICMP6 847
if_freenameindex() 849
if_indextoname() 850
if_nameindex() 851
if_nametoindex() 852
xii
Contents
June 19, 2012
© 2012, QNX Software Systems Limited
853
ilogb(), ilogbf() 854
in8() 856
in8s() 857
in16(), inbe16(), inle16() 859
in16s() 861
in32(), inbe32(), inle32() 863
in32s() 865
index() 867
inet_addr() 868
inet_aton() 870
inet_lnaof() 872
inet_makeaddr() 873
inet_net_ntop() 875
inet_netof() 878
inet_net_pton() 879
inet_network() 881
inet_ntoa() 882
inet_ntoa_r() 884
inet_ntop() 886
inet_pton() 889
INET6 893
inet6_option_alloc() 896
inet6_option_append() 898
inet6_option_find() 900
inet6_option_init() 902
inet6_option_next() 904
inet6_option_space() 906
inet6_rthdr_add() 908
inet6_rthdr_getaddr() 910
inet6_rthdr_getflags() 912
inet6_rthdr_init() 914
inet6_rthdr_lasthop() 916
inet6_rthdr_reverse() 918
inet6_rthdr_segments() 920
inet6_rthdr_space() 922
initgroups() 924
initstate() 926
input_line() 928
insque() 930
InterruptAttach(), InterruptAttach_r()
ifaddrs
June 19, 2012
932
Contents
xiii
© 2012, QNX Software Systems Limited
InterruptAttachEvent(), InterruptAttachEvent_r()
InterruptDetach(), InterruptDetach_r() 942
InterruptDisable() 944
InterruptEnable() 946
InterruptHookIdle() 947
InterruptHookTrace() 950
InterruptLock() 952
InterruptMask() 954
InterruptStatus() 956
InterruptUnlock() 957
InterruptUnmask() 958
InterruptWait(), InterruptWait_r() 960
_intr_v86() 962
_io_connect 966
_io_connect_ftype_reply 971
_io_connect_link_reply 972
ioctl(), ioctl_socket() 974
iofdinfo() 984
iofunc_attr_init() 986
iofunc_attr_lock() 988
iofunc_attr_t 990
iofunc_attr_trylock() 995
iofunc_attr_unlock() 997
iofunc_check_access() 998
iofunc_chmod() 1001
iofunc_chmod_default() 1004
iofunc_chown() 1006
iofunc_chown_default() 1009
iofunc_client_info() 1011
iofunc_close_dup() 1013
iofunc_close_dup_default() 1015
iofunc_close_ocb() 1017
iofunc_close_ocb_default() 1019
iofunc_devctl() 1021
iofunc_devctl_default() 1024
iofunc_fdinfo() 1026
iofunc_fdinfo_default() 1028
iofunc_func_init() 1031
iofunc_link() 1033
iofunc_lock() 1036
iofunc_lock_calloc() 1038
xiv
Contents
938
June 19, 2012
© 2012, QNX Software Systems Limited
iofunc_lock_default() 1040
iofunc_lock_free() 1042
iofunc_lock_ocb_default() 1043
iofunc_lseek() 1045
iofunc_lseek_default() 1048
iofunc_mknod() 1050
iofunc_mmap() 1053
iofunc_mmap_default() 1056
iofunc_notify() 1058
iofunc_notify_remove() 1063
iofunc_notify_trigger() 1065
iofunc_ocb_attach() 1067
iofunc_ocb_calloc() 1069
iofunc_ocb_detach() 1071
iofunc_ocb_free() 1073
iofunc_ocb_t 1075
iofunc_open() 1077
iofunc_open_default() 1081
iofunc_openfd() 1083
iofunc_openfd_default() 1086
iofunc_pathconf() 1088
iofunc_pathconf_default() 1090
iofunc_read_default() 1092
iofunc_read_verify() 1094
iofunc_readlink() 1097
iofunc_rename() 1099
iofunc_space_verify() 1102
iofunc_stat() 1105
iofunc_stat_default() 1107
iofunc_sync() 1109
iofunc_sync_default() 1111
iofunc_sync_verify() 1113
iofunc_time_update() 1115
iofunc_unblock() 1117
iofunc_unblock_default() 1119
iofunc_unlink() 1121
iofunc_unlock_ocb_default() 1124
iofunc_utime() 1126
iofunc_utime_default() 1129
iofunc_write_default() 1131
iofunc_write_verify() 1133
June 19, 2012
Contents
xv
© 2012, QNX Software Systems Limited
ionotify() 1136
IP 1141
IPsec 1145
ipsec_dump_policy() 1151
ipsec_get_policylen() 1153
ipsec_set_policy() 1155
ipsec_strerror() 1159
IP6 1161
iruserok(), iruserok_sa() 1168
isalnum() 1170
isalpha() 1172
isascii() 1174
isatty() 1176
iscntrl() 1178
isdigit() 1180
isfdtype() 1182
isfinite() 1184
isgraph() 1186
isinf() 1188
islower() 1190
isnan() 1192
isprint() 1194
ispunct() 1196
isspace() 1198
isupper() 1200
iswalnum() 1202
iswalpha() 1203
iswcntrl() 1204
iswctype() 1205
iswdigit() 1207
iswgraph() 1208
iswlower() 1209
iswprint() 1210
iswpunct() 1211
iswspace() 1212
iswupper() 1213
iswxdigit() 1214
isxdigit() 1215
itoa() 1217
j0(), j0f() 1219
j1(), j1f() 1221
xvi
Contents
June 19, 2012
© 2012, QNX Software Systems Limited
jn(), jnf() 1222
jrand48() 1224
kill() 1225
killpg() 1227
labs() 1229
lchown() 1231
lcong48() 1234
ldexp(), ldexpf(), ldexpl() 1235
ldiv() 1237
lfind() 1239
lgamma(), lgamma_r(), lgammaf(), lgammaf_r() 1242
link() 1245
lio_listio() 1248
listen() 1252
llabs() 1254
localeconv() 1255
localtime() 1259
localtime_r() 1261
lockf() 1263
log(), logf(), logl() 1266
log10(), log10f(), log10l() 1268
log1p(), log1pf(), log1pl() 1270
logb(), logbf() 1272
login_tty() 1274
longjmp() 1276
lrand48() 1278
lsearch() 1279
lseek(), lseek64() 1282
lstat(), lstat64() 1285
ltoa(), lltoa() 1287
ltrunc() 1289
main() 1292
mallinfo() 1294
malloc() 1296
mallopt() 1302
max() 1308
mblen() 1309
mbrlen() 1311
mbrtowc() 1313
mbsinit() 1315
mbsrtowcs() 1317
June 19, 2012
Contents
xvii
© 2012, QNX Software Systems Limited
mbstowcs() 1319
mbtowc() 1321
mcheck() 1324
mem_offset(), mem_offset64() 1326
memalign() 1329
memccpy() 1331
memchr() 1333
memcmp() 1335
memcpy() 1337
memcpyv() 1339
memicmp() 1341
memmove() 1343
memset() 1345
message_attach() 1347
message_connect() 1353
message_detach() 1356
min() 1358
mkdir() 1359
mkfifo() 1362
mknod() 1364
mkstemp() 1367
mktemp() 1369
mktime() 1371
mlock() 1373
mlockall() 1375
mmap(), mmap64() 1377
mmap_device_io() 1386
mmap_device_memory() 1388
modem_open() 1391
modem_read() 1395
modem_script() 1398
modem_write() 1404
modf(), modff() 1406
mount() 1408
mount_parse_generic_args() 1411
mprobe() 1414
mprotect() 1416
mq_close() 1418
mq_getattr() 1420
mq_notify() 1423
mq_open() 1425
xviii
Contents
June 19, 2012
© 2012, QNX Software Systems Limited
mq_receive() 1429
mq_send() 1431
mq_setattr() 1433
mq_timedreceive(), mq_timedreceive_monotonic() 1435
mq_timedsend(), mq_timedsend_monotonic() 1438
mq_unlink() 1441
mrand48() 1443
_msg_info 1444
MsgCurrent(), MsgCurrent_r() 1446
MsgDeliverEvent(), MsgDeliverEvent_r() 1448
MsgError(), MsgError_r() 1454
MsgInfo(), MsgInfo_r() 1456
MsgKeyData(), MsgKeyData_r() 1458
MsgRead(), MsgRead_r() 1464
MsgReadv(), MsgReadv_r() 1467
MsgReceive(), MsgReceive_r() 1470
MsgReceivePulse(), MsgReceivePulse_r() 1474
MsgReceivePulsev(), MsgReceivePulsev_r() 1477
MsgReceivev(), MsgReceivev_r() 1480
MsgReply(), MsgReply_r() 1483
MsgReplyv(), MsgReplyv_r() 1486
MsgSend(), MsgSend_r() 1489
MsgSendnc(), MsgSendnc_r() 1493
MsgSendPulse(), MsgSendPulse_r() 1496
MsgSendsv(), MsgSendsv_r() 1500
MsgSendsvnc(), MsgSendsvnc_r() 1503
MsgSendv(), MsgSendv_r() 1506
MsgSendvnc(), MsgSendvnc_r() 1509
MsgSendvs(), MsgSendvs_r() 1512
MsgSendvsnc(), MsgSendvsnc_r() 1515
MsgVerifyEvent(), MsgVerifyEvent_r() 1518
MsgWrite(), MsgWrite_r() 1520
MsgWritev(), MsgWritev_r() 1523
msync() 1526
munlock() 1529
munlockall() 1531
munmap() 1533
munmap_device_io() 1535
munmap_device_memory() 1537
munmap_flags() 1539
name_attach() 1541
June 19, 2012
Contents
xix
© 2012, QNX Software Systems Limited
name_close() 1547
name_detach() 1549
name_open() 1551
nanosleep() 1553
nanospin() 1555
nanospin_calibrate() 1557
nanospin_count() 1559
nanospin_ns() 1561
nanospin_ns_to_count() 1563
nap() 1565
napms() 1566
nbaconnect() 1567
nbaconnect_result() 1569
ncurses 1571
ND_NODE_CMP() 1572
netent 1574
netmgr_ndtostr() 1575
netmgr_remote_nd() 1579
netmgr_strtond() 1581
nextafter(), nextafterf() 1583
nftw(), nftw64() 1585
nice() 1588
nrand48() 1590
nsec2timespec() 1591
ntohl() 1592
ntohs() 1593
offsetof() 1594
open(), open64() 1596
opendir() 1602
openfd() 1604
openlog() 1606
openpty() 1608
out8() 1610
out8s() 1611
out16(), outbe16(), outle16() 1613
out16s() 1615
out32(), outbe32(), outle32() 1617
out32s() 1619
pathconf() 1621
pathfind(), pathfind_r() 1624
pathmgr_symlink() 1627
xx
Contents
June 19, 2012
© 2012, QNX Software Systems Limited
pathmgr_unlink() 1629
pause() 1630
pccard_arm() 1632
pccard_attach() 1635
pccard_detach() 1637
pccard_info() 1639
pccard_lock() 1641
pccard_raw_read() 1643
pccard_unlock() 1645
pci_attach() 1647
pci_attach_device() 1649
pci_detach() 1657
pci_detach_device() 1659
pci_find_class() 1661
pci_find_device() 1663
pci_irq_routing_options() 1665
pci_map_irq() 1667
pci_present() 1669
pci_read_config() 1671
pci_read_config8() 1673
pci_read_config16() 1675
pci_read_config32() 1677
pci_rescan_bus() 1679
pci_write_config() 1680
pci_write_config8() 1682
pci_write_config16() 1684
pci_write_config32() 1686
pclose() 1688
perror() 1690
pipe() 1692
poll() 1694
popen() 1699
posix_mem_offset(), posix_mem_offset64() 1702
posix_memalign() 1704
posix_spawn(), posix_spawnp() 1706
posix_spawn_file_actions_addclose() 1716
posix_spawn_file_actions_adddup2() 1718
posix_spawn_file_actions_addopen() 1720
posix_spawn_file_actions_destroy() 1723
posix_spawn_file_actions_init() 1725
posix_spawnattr_addpartid() 1727
June 19, 2012
Contents
xxi
© 2012, QNX Software Systems Limited
posix_spawnattr_addpartition() 1729
posix_spawnattr_destroy() 1732
posix_spawnattr_getcred() 1734
posix_spawnattr_getflags() 1736
posix_spawnattr_getnode() 1739
posix_spawnattr_getpartid() 1741
posix_spawnattr_getpgroup() 1744
posix_spawnattr_getrunmask() 1746
posix_spawnattr_getschedparam() 1748
posix_spawnattr_getschedpolicy() 1750
posix_spawnattr_getsigdefault() 1752
posix_spawnattr_getsigignore() 1754
posix_spawnattr_getsigmask() 1756
posix_spawnattr_getstackmax() 1758
posix_spawnattr_getxflags() 1760
posix_spawnattr_init() 1763
posix_spawnattr_setcred() 1765
posix_spawnattr_setflags() 1768
posix_spawnattr_setnode() 1771
posix_spawnattr_setpgroup() 1773
posix_spawnattr_setrunmask() 1775
posix_spawnattr_setschedparam() 1777
posix_spawnattr_setschedpolicy() 1779
posix_spawnattr_setsigdefault() 1781
posix_spawnattr_setsigignore() 1783
posix_spawnattr_setsigmask() 1785
posix_spawnattr_setstackmax() 1787
posix_spawnattr_setxflags() 1789
posix_typed_mem_get_info() 1792
posix_typed_mem_open() 1794
pow(), powf(), powl() 1798
pread(), pread64() 1800
printf() 1802
procmgr_daemon() 1809
procmgr_event_notify() 1811
procmgr_event_notify_add() 1816
procmgr_event_notify_delete() 1821
procmgr_event_trigger() 1823
procmgr_guardian() 1825
procmgr_session() 1828
__progname 1830
xxii
Contents
June 19, 2012
© 2012, QNX Software Systems Limited
protoent 1831
pthread_abort() 1832
pthread_atfork() 1834
pthread_attr_destroy() 1836
pthread_attr_getdetachstate() 1838
pthread_attr_getguardsize() 1840
pthread_attr_getinheritsched() 1842
pthread_attr_getschedparam() 1844
pthread_attr_getschedpolicy() 1846
pthread_attr_getscope() 1848
pthread_attr_getstackaddr() 1850
pthread_attr_getstacklazy() 1852
pthread_attr_getstackprealloc() 1854
pthread_attr_getstacksize() 1856
pthread_attr_init() 1858
pthread_attr_setdetachstate() 1860
pthread_attr_setguardsize() 1862
pthread_attr_setinheritsched() 1864
pthread_attr_setschedparam() 1866
pthread_attr_setschedpolicy() 1868
pthread_attr_setscope() 1870
pthread_attr_setstackaddr() 1872
pthread_attr_setstacklazy() 1874
pthread_attr_setstackprealloc() 1876
pthread_attr_setstacksize() 1878
pthread_barrier_destroy() 1880
pthread_barrier_init() 1881
pthread_barrier_wait() 1883
pthread_barrierattr_destroy() 1885
pthread_barrierattr_getpshared() 1887
pthread_barrierattr_init() 1889
pthread_barrierattr_setpshared() 1890
pthread_cancel() 1892
pthread_cleanup_pop() 1894
pthread_cleanup_push() 1895
pthread_cond_broadcast() 1897
pthread_cond_destroy() 1899
pthread_cond_init() 1900
pthread_cond_signal() 1902
pthread_cond_timedwait() 1904
pthread_cond_wait() 1907
June 19, 2012
Contents
xxiii
© 2012, QNX Software Systems Limited
pthread_condattr_destroy() 1910
pthread_condattr_getclock() 1911
pthread_condattr_getpshared() 1913
pthread_condattr_init() 1915
pthread_condattr_setclock() 1917
pthread_condattr_setpshared() 1919
pthread_create() 1921
pthread_detach() 1925
pthread_equal() 1926
pthread_exit() 1927
pthread_getconcurrency() 1929
pthread_getcpuclockid() 1930
pthread_getname_np() 1932
pthread_getschedparam() 1934
pthread_getspecific() 1936
pthread_join() 1938
pthread_key_create() 1940
pthread_key_delete() 1943
pthread_kill() 1945
pthread_mutex_destroy() 1947
pthread_mutex_getprioceiling() 1949
pthread_mutex_init() 1951
pthread_mutex_lock() 1953
pthread_mutex_setprioceiling() 1956
pthread_mutex_timedlock(), pthread_mutex_timedlock_monotonic() 1958
pthread_mutex_trylock() 1961
pthread_mutex_unlock() 1963
pthread_mutex_wakeup_np() 1965
pthread_mutexattr_destroy() 1967
pthread_mutexattr_getprioceiling() 1968
pthread_mutexattr_getprotocol() 1970
pthread_mutexattr_getpshared() 1972
pthread_mutexattr_getrecursive() 1974
pthread_mutexattr_gettype() 1976
pthread_mutexattr_getwakeup_np() 1978
pthread_mutexattr_init() 1980
pthread_mutexattr_setprioceiling() 1982
pthread_mutexattr_setprotocol() 1984
pthread_mutexattr_setpshared() 1986
pthread_mutexattr_setrecursive() 1988
pthread_mutexattr_settype() 1990
xxiv
Contents
June 19, 2012
© 2012, QNX Software Systems Limited
pthread_mutexattr_setwakeup_np() 1992
pthread_once() 1994
pthread_rwlock_destroy() 1996
pthread_rwlock_init() 1998
pthread_rwlock_rdlock() 2000
pthread_rwlock_timedrdlock() 2002
pthread_rwlock_timedwrlock() 2004
pthread_rwlock_tryrdlock() 2006
pthread_rwlock_trywrlock() 2008
pthread_rwlock_unlock() 2010
pthread_rwlock_wrlock() 2012
pthread_rwlockattr_destroy() 2014
pthread_rwlockattr_getpshared() 2016
pthread_rwlockattr_init() 2018
pthread_rwlockattr_setpshared() 2019
pthread_self() 2021
pthread_setcancelstate() 2022
pthread_setcanceltype() 2024
pthread_setconcurrency() 2026
pthread_setname_np() 2028
pthread_setschedparam() 2030
pthread_setschedprio() 2032
pthread_setspecific() 2034
pthread_sigmask() 2036
pthread_sleepon_broadcast() 2038
pthread_sleepon_lock() 2040
pthread_sleepon_signal() 2042
pthread_sleepon_timedwait() 2044
pthread_sleepon_unlock() 2047
pthread_sleepon_wait() 2048
pthread_spin_destroy() 2051
pthread_spin_init() 2053
pthread_spin_lock() 2055
pthread_spin_trylock() 2057
pthread_spin_unlock() 2059
pthread_testcancel() 2060
pthread_timedjoin(), pthread_timedjoin_monotonic() 2061
_pulse 2063
pulse_attach() 2065
pulse_detach() 2068
putc() 2070
June 19, 2012
Contents
xxv
© 2012, QNX Software Systems Limited
putc_unlocked() 2072
putchar() 2073
putchar_unlocked() 2075
putenv() 2076
puts() 2079
putspent() 2081
pututline() 2084
putw() 2086
putwc() 2088
putwchar() 2090
pwrite(), pwrite64() 2092
qnx_crypt() 2095
qsort() 2097
Raccept() 2099
raise() 2101
rand() 2103
rand_r() 2105
random() 2106
Rbind() 2108
rcmd(), rcmd_af() 2110
Rconnect() 2112
rdchk() 2114
re_comp() 2116
re_exec() 2118
read() 2120
read_main_config_file() 2124
readblock() 2127
readcond() 2129
readdir() 2134
readdir_r() 2138
readlink() 2140
readv() 2142
realloc() 2145
realpath() 2149
recv() 2151
recvfrom() 2153
recvmsg() 2156
regcomp() 2159
regerror() 2164
regexec() 2166
regfree() 2169
xxvi
Contents
June 19, 2012
© 2012, QNX Software Systems Limited
remainder(), remainderf(), remainderl() 2171
remove() 2173
remque() 2175
rename() 2176
res_init() 2179
res_mkquery() 2182
res_query() 2184
res_querydomain() 2186
res_search() 2188
res_send() 2190
resmgr_attach() 2192
resmgr_block() 2200
resmgr_connect_funcs_t 2203
resmgr_context_alloc() 2205
resmgr_context_free() 2207
resmgr_context_t 2209
resmgr_detach() 2211
resmgr_devino() 2214
resmgr_handle_grow() 2216
resmgr_handle_tune() 2217
resmgr_handler() 2219
resmgr_io_funcs_t 2221
resmgr_iofuncs() 2224
resmgr_msg_again() 2226
resmgr_msgread() 2228
resmgr_msgreadv() 2230
resmgr_msgreply() 2232
resmgr_msgreplyv() 2234
resmgr_msgwrite() 2237
resmgr_msgwritev() 2239
_RESMGR_NPARTS() 2241
resmgr_ocb() 2243
resmgr_open_bind() 2245
resmgr_pathname() 2247
_RESMGR_PTR() 2249
_RESMGR_STATUS() 2251
resmgr_unbind() 2252
rewind() 2254
rewinddir() 2256
Rgetsockname() 2258
rindex() 2260
June 19, 2012
Contents
xxvii
© 2012, QNX Software Systems Limited
rint(), rintf(), rintl() 2261
Rlisten() 2263
rmdir() 2265
round(), roundf(), roundl() 2267
ROUTE 2269
Rrcmd() 2275
rresvport(), rresvport_af() 2277
Rselect() 2279
rsrcdbmgr_attach() 2281
rsrcdbmgr_create() 2288
rsrcdbmgr_destroy() 2291
rsrcdbmgr_detach() 2293
rsrcdbmgr_devno_attach() 2295
rsrcdbmgr_devno_detach() 2298
rsrcdbmgr_query_name() 2300
ruserok() 2303
sbrk() 2305
scalb() 2308
scalbn(), scalbnf() 2310
_scalloc() 2312
scandir() 2313
scanf() 2315
sched_getparam() 2321
sched_get_priority_adjust() 2324
sched_get_priority_max() 2326
sched_get_priority_min() 2328
sched_getscheduler() 2330
sched_param 2332
sched_rr_get_interval() 2337
sched_setparam() 2339
sched_setscheduler() 2341
sched_yield() 2343
SchedCtl(), SchedCtl_r() 2345
SchedGet(), SchedGet_r() 2370
SchedInfo(), SchedInfo_r() 2372
SchedSet(), SchedSet_r() 2375
SchedYield(), SchedYield_r() 2378
searchenv() 2380
seed48() 2382
seekdir() 2383
select() 2385
xxviii
Contents
June 19, 2012
© 2012, QNX Software Systems Limited
select_attach() 2390
select_detach() 2393
select_query() 2395
sem_close() 2398
sem_destroy() 2400
sem_getvalue() 2402
sem_init() 2404
sem_open() 2407
sem_post() 2411
sem_timedwait(), sem_timedwait_monotonic() 2413
sem_trywait() 2416
sem_unlink() 2418
sem_wait() 2420
send() 2422
sendmsg() 2425
sendto() 2428
servent 2432
setbuf() 2433
setbuffer() 2435
setdomainname() 2437
setegid() 2439
setenv() 2441
seteuid() 2443
setgid() 2445
setfsent() 2447
setgrent() 2449
setgroups() 2450
sethostent() 2452
sethostname() 2453
SETIOV() 2455
setitimer() 2456
setjmp() 2459
setkey() 2461
setlinebuf() 2462
setlocale() 2464
setlogmask() 2466
setnetent() 2468
setpgid() 2469
setpgrp() 2471
setprio() 2472
setprotoent() 2474
June 19, 2012
Contents
xxix
© 2012, QNX Software Systems Limited
setpwent() 2476
setregid() 2477
setreuid() 2479
setrlimit(), setrlimit64() 2481
setservent() 2485
setsid() 2486
setsockopt() 2488
setspent() 2490
setstate() 2491
settimeofday() 2493
setuid() 2495
setutent() 2497
setvbuf() 2498
_sfree() 2500
shm_ctl() 2502
shm_ctl_special() 2509
shm_open() 2514
shm_unlink() 2519
shutdown() 2521
shutdown_system() 2523
sigaction() 2527
sigaddset() 2532
sigblock() 2534
sigdelset() 2536
sigemptyset() 2538
sigevent 2540
sigfillset() 2545
sigismember() 2546
siglongjmp() 2548
sigmask() 2550
signal() 2552
SignalAction(), SignalAction_r() 2555
SignalKill(), SignalKill_r() 2562
SignalProcmask(), SignalProcmask_r() 2566
SignalSuspend(), SignalSuspend_r() 2569
SignalWaitinfo(), SignalWaitinfo_r() 2571
sigpause() 2573
sigpending() 2575
sigprocmask() 2577
sigqueue() 2580
sigsetjmp() 2582
xxx
Contents
June 19, 2012
© 2012, QNX Software Systems Limited
sigsetmask() 2584
sigsuspend() 2586
sigtimedwait() 2588
sigunblock() 2590
sigwait() 2592
sigwaitinfo() 2594
sin(), sinf(), sinl() 2596
sinh(), sinhf(), sinhl() 2598
sleep() 2600
_sleepon_broadcast() 2602
_sleepon_destroy() 2604
_sleepon_init() 2606
_sleepon_lock() 2607
_sleepon_signal() 2609
_sleepon_unlock() 2611
_sleepon_wait() 2612
slogb() 2614
slogf() 2616
slogi() 2619
_smalloc() 2621
snmp_close() 2623
snmp_free_pdu() 2625
snmp_open() 2626
snmp_pdu 2628
snmp_pdu_create() 2631
snmp_read() 2633
snmp_select_info() 2634
snmp_send() 2637
snmp_session 2639
snmp_timeout() 2642
snprintf() 2643
sockatmark() 2646
socket() 2648
socketpair() 2651
SOCKSinit() 2654
sopen() 2656
sopenfd() 2660
spawn() 2662
spawnl() 2671
spawnle() 2675
spawnlp() 2679
June 19, 2012
Contents
xxxi
© 2012, QNX Software Systems Limited
spawnlpe() 2683
spawnp() 2687
spawnv() 2692
spawnve() 2696
spawnvp() 2700
spawnvpe() 2704
sprintf() 2708
sqrt(), sqrtf(), sqrtl() 2710
srand() 2712
srand48() 2714
srandom() 2715
_srealloc() 2717
sscanf() 2719
stat(), stat64() 2721
statvfs(), statvfs64() 2727
stderr 2731
stdin 2732
stdout 2733
straddstr() 2734
strcasecmp() 2736
strcat() 2738
strchr() 2740
strcmp() 2742
strcmpi() 2744
strcoll() 2746
strcpy() 2748
strcspn() 2750
strdup() 2752
strerror() 2754
strerror_r() 2756
strftime() 2758
stricmp() 2762
strlcat(), strlcpy() 2764
strlen() 2767
strlwr() 2769
strncasecmp() 2771
strncat() 2773
strncmp() 2775
strncpy() 2777
strnicmp() 2779
strnset() 2781
xxxii
Contents
June 19, 2012
© 2012, QNX Software Systems Limited
strpbrk() 2783
strptime() 2785
strrchr() 2790
strrev() 2792
strsep() 2794
strset() 2796
strsignal() 2798
strspn() 2799
strstr() 2801
strtod(), strtof(), strtold() 2803
strtoimax(), strtoumax() 2806
strtok() 2808
strtok_r() 2810
strtol(), strtoll() 2812
strtoul(), strtoull() 2814
strupr() 2816
strxfrm() 2818
swab() 2820
swprintf() 2822
swscanf() 2824
symlink() 2826
sync() 2828
SyncCondvarSignal(), SyncCondvarSignal_r() 2829
SyncCondvarWait(), SyncCondvarWait_r() 2831
SyncCtl(), SyncCtl_r() 2834
SyncDestroy(), SyncDestroy_r() 2837
SyncMutexEvent(), SyncMutexEvent_r() 2839
SyncMutexLock(), SyncMutexLock_r() 2841
SyncMutexRevive(), SyncMutexRevive_r() 2844
SyncMutexUnlock(), SyncMutexUnlock_r() 2846
SyncSemPost(), SyncSemPost_r() 2848
SyncSemWait(), SyncSemWait_r() 2850
SyncTypeCreate(), SyncTypeCreate_r() 2852
sysconf() 2855
sysctl() 2858
syslog() 2863
sysmgr_reboot() 2865
SYSPAGE_CPU_ENTRY() 2866
SYSPAGE_ENTRY() 2868
_syspage_ptr 2870
system() 2871
June 19, 2012
Contents
xxxiii
© 2012, QNX Software Systems Limited
tan(), tanf(), tanl() 2873
tanh(), tanhf(), tanhl() 2875
tcdrain() 2877
tcdropline() 2879
tcflow() 2881
tcflush() 2883
tcgetattr() 2885
tcgetpgrp() 2887
tcgetsid() 2889
tcgetsize() 2891
tcinject() 2893
tcischars() 2895
TCP 2896
tcsendbreak() 2898
tcsetattr() 2900
tcsetpgrp() 2903
tcsetsid() 2905
tcsetsize() 2907
tell(), tell64() 2909
telldir() 2911
tempnam() 2913
termios 2915
thread_pool_control() 2918
thread_pool_create() 2920
thread_pool_destroy() 2926
thread_pool_limits() 2928
thread_pool_start() 2930
ThreadCancel(), ThreadCancel_r() 2932
ThreadCreate(), ThreadCreate_r() 2935
ThreadCtl(), ThreadCtl_r() 2940
ThreadDestroy(), ThreadDestroy_r() 2949
ThreadDetach(), ThreadDetach_r() 2951
ThreadJoin(), ThreadJoin_r() 2953
time() 2955
timer_create() 2957
timer_delete() 2961
timer_getexpstatus() 2963
timer_getoverrun() 2965
timer_gettime() 2967
timer_settime() 2969
timer_timeout(), timer_timeout_r() 2972
xxxiv
Contents
June 19, 2012
© 2012, QNX Software Systems Limited
TimerAlarm(), TimerAlarm_r() 2978
TimerCreate(), TimerCreate_r() 2981
TimerDestroy(), TimerDestroy_r() 2984
TimerInfo(), TimerInfo_r() 2986
TimerSettime(), TimerSettime_r() 2989
TimerTimeout(), TimerTimeout_r() 2992
times() 2998
timespec 3000
timespec2nsec() 3001
timezone 3002
tm 3003
tmpfile(), tmpfile64() 3004
tmpnam() 3006
tolower() 3008
toupper() 3010
towctrans() 3012
towlower() 3014
towupper() 3015
trace_func_enter() 3016
trace_func_exit() 3018
trace_here() 3020
trace_logb() 3022
trace_logbc() 3024
trace_logf() 3026
trace_logi() 3028
trace_nlogf() 3030
trace_vnlogf() 3032
TraceEvent() 3034
traceparser() 3046
traceparser_cs() 3048
traceparser_cs_range() 3051
traceparser_debug() 3053
traceparser_destroy() 3055
traceparser_get_info() 3056
traceparser_init() 3059
truncate() 3061
ttyname() 3064
ttyname_r() 3066
tzname 3068
tzset() 3069
ualarm() 3071
June 19, 2012
Contents
xxxv
© 2012, QNX Software Systems Limited
UDP 3074
ultoa(), ulltoa() 3076
umask() 3078
umount() 3080
UNALIGNED_PUT16()
UNALIGNED_PUT32()
UNALIGNED_PUT64()
UNALIGNED_RET16()
UNALIGNED_RET32()
UNALIGNED_RET64()
uname() 3089
ungetc() 3091
ungetwc() 3093
UNIX 3095
unlink() 3097
unsetenv() 3099
usleep() 3101
utime() 3103
utimes() 3105
utmp 3108
utmpname() 3110
utoa() 3111
va_arg() 3113
va_copy() 3117
va_end() 3119
va_start() 3120
valloc() 3122
verr(), verrx() 3124
vfork() 3126
vfprintf() 3128
vfscanf() 3130
vfwprintf() 3132
vfwscanf() 3134
vprintf() 3136
vscanf() 3138
vslogf() 3140
vsnprintf() 3142
vsprintf() 3144
vsscanf() 3146
vswprintf() 3148
vswscanf() 3150
xxxvi
Contents
3081
3082
3083
3085
3086
3087
June 19, 2012
© 2012, QNX Software Systems Limited
vsyslog() 3152
vwarn(), vwarnx() 3154
vwprintf() 3156
vwscanf() 3158
wait() 3160
wait3() 3163
wait4() 3165
waitid() 3168
waitpid() 3170
warn(), warnx() 3172
wcrtomb() 3174
wcscat() 3176
wcschr() 3177
wcscmp() 3178
wcscoll() 3179
wcscpy() 3180
wcscspn() 3182
wcsftime() 3183
wcslen() 3185
wcsncat() 3186
wcsncmp() 3188
wcsncpy() 3190
wcspbrk() 3192
wcsrchr() 3193
wcsrtombs() 3194
wcsspn() 3196
wcsstr() 3197
wcstod(), wcstof(), wcstold() 3198
wcstoimax(), wcstoumax() 3200
wcstok() 3202
wcstol(), wcstoll() 3204
wcstombs() 3206
wcstoul(), wcstoull() 3208
wcsxfrm() 3210
wctob() 3212
wctomb() 3213
wctrans() 3215
wctype() 3217
wmemchr() 3219
wmemcmp() 3221
wmemcpy() 3223
June 19, 2012
Contents
xxxvii
© 2012, QNX Software Systems Limited
wmemmove() 3225
wmemset() 3227
wordexp() 3229
wordfree() 3230
wprintf() 3231
write() 3232
writeblock() 3237
writev() 3239
wscanf() 3241
y0(), y0f() 3242
y1(), y1f() 3243
yn(), ynf() 3245
A
SOCKS — A Basic Firewall 3247
About SOCKS 3249
How to SOCKSify a client 3249
What SOCKS expects 3250
B
Summary of Safety Information 3251
Cancellation points 3253
Interrupt handlers 3257
Signal handlers 3260
Multithreaded programs 3272
C
What’s New in this Reference? 3275
What’s new in QNX Neutrino 6.5.0 Service Pack 1? 3277
New entries 3277
Changed content 3277
Errata 3280
What’s new in QNX Neutrino 6.5.0? 3282
New entries 3282
Changed content 3285
Errata 3295
What’s new in QNX Neutrino 6.4.1? 3297
New entries 3297
Deprecated content 3299
Changed content 3299
Errata 3303
What’s new in QNX Neutrino 6.4.0? 3304
New entries 3304
Deprecated content 3307
xxxviii
Contents
June 19, 2012
© 2012, QNX Software Systems Limited
Changed content 3307
Errata 3310
What’s new in QNX Neutrino 6.3.2? 3313
Errata 3313
What’s new in the QNX Neutrino Core OS 6.3.2? 3313
New entries 3314
Changed content 3314
What’s new in QNX Neutrino 6.3.0 Service Pack 2? 3315
New entries 3315
Changed content 3316
Errata 3316
What’s new in QNX Neutrino 6.3.0 Service Pack 1? 3316
New entries 3317
Changed content 3317
Errata 3318
What’s new in QNX Neutrino 6.3.0? 3319
New entries 3319
Deprecated content 3321
What’s new in QNX Neutrino 6.2.1? 3321
New entries 3321
Changed content 3322
Errata 3322
What’s new in QNX Neutrino 6.2? 3323
New entries 3324
Deprecated content 3326
Errata 3326
What’s new in QNX Neutrino 6.1.0? 3326
New entries 3326
Deprecated content 3327
Glossary 3329
Index 3349
June 19, 2012
Contents
xxxix
List of Figures
Mapping memory with mmap(). 1379
A hierarchy of processes. 1449
A deadlock when sending messages improperly among processes. 1449
MsgSendv(), client to process manager. 1459
MsgReplyv(), process manager to client. 1459
MsgSendv(), client to filesystem manager 1459
Components of a fully qualified pathname. 1575
Specifying a guardian for child processes. 1825
Conditions that satisfy an input request. 2130
Most of the spawn*() functions do a lot of work before a message is sent to
procnto. 2664
June 19, 2012
List of Figures
xli
About This Reference
June 19, 2012
About This Reference
xliii
Typographical conventions
© 2012, QNX Software Systems Limited
The Library Reference describes the C functions, data types, and protocols that are
included as part of the QNX Neutrino RTOS.
For information about:
See:
An overview of what you’ll find in each
entry
What’s in a Function Description?
Descriptions of the manifests that you
can use for compile-time changes or
inspection
Manifests
The SOCKS package
SOCKS — A Basic Firewall
A summary of functions that are
cancellation points, that you can safely
call from an interrupt handler, that you
can safely call from a signal handler,
and that you can’t safely call from a
multithreaded program.
Summary of Safety Information
Changes to this reference
What’s New in this Reference?
Terms used in QNX documentation
Glossary
For information about programming in Neutrino, see Getting Started with QNX
Neutrino: A Guide for Realtime Programmers and the Neutrino Programmer’s Guide.
For information about licensing, see:
• the QNX Development Suite License Guide at
http://licensing.qnx.com/license-guide/
• the Third Party License Terms List at
http://licensing.qnx.com/third-party-terms/
• the matrix of all the versions of all our legal documents at
http://licensing.qnx.com/document-archive/
Typographical conventions
Throughout this manual, we use certain typographical conventions to distinguish
technical terms. In general, the conventions we use conform to those found in IEEE
POSIX publications. The following table summarizes our conventions:
Reference
Example
Code examples
if( stream == NULL )
continued. . .
June 19, 2012
About This Reference
xlv
Typographical conventions
© 2012, QNX Software Systems Limited
Reference
Example
Command options
-lR
Commands
make
Environment variables
PATH
File and pathnames
/dev/null
Function names
exit()
Keyboard chords
Ctrl-Alt-Delete
Keyboard input
something you type
Keyboard keys
Enter
Program output
login:
Programming constants
NULL
Programming data types
unsigned short
Programming literals
0xFF, "message string"
Variable names
stdin
User-interface components
Cancel
We use an arrow (→) in directions for accessing menu items, like this:
You’ll find the Other... menu item under Perspective→Show View.
We use notes, cautions, and warnings to highlight important messages:
Notes point out something important or useful.
!
CAUTION: Cautions tell you about commands or procedures that may have
unwanted or undesirable side effects.
WARNING: Warnings tell you about commands or procedures that could be
dangerous to your files, your hardware, or even yourself.
Note to Windows users
In our documentation, we use a forward slash (/) as a delimiter in all pathnames,
including those pointing to Windows files.
We also generally follow POSIX/UNIX filesystem conventions.
xlvi
About This Reference
June 19, 2012
© 2012, QNX Software Systems Limited
Technical support
Technical support
To obtain technical support for any QNX product, visit the Support area on our
website (www.qnx.com). You’ll find a wide range of support options, including
community forums.
June 19, 2012
About This Reference
xlvii
What’s in a Function Description?
June 19, 2012
What’s in a Function Description?
1
© 2012, QNX Software Systems Limited
The description of each function in this refernce contains the following sections:
• Synopsis
• Arguments
• Library
• Description
• Returns
• Errors
• See also
• Examples
• Classification
• Function safety
Synopsis:
This section gives the header files that should be included within a source file that
references the function or macro. It also shows an appropriate declaration for the
function or for a function that could be substituted for a macro. This declaration isn’t
included in your program; only the header file(s) should be included.
When a pointer argument is passed to a function that doesn’t modify the item indicated
by that pointer, the argument is shown with const before the argument. For example,
the following indicates that the array pointed at by string isn’t changed:
const char *string
Arguments:
This section gives a brief description of the arguments to the function.
Library:
The section indicates the library that you need to bind with your application in order to
use the function.
To link against a library, use the -l option to qcc, omitting the lib prefix and any
extension from the library’s name. For example, to link against libsocket, specify
-l socket. For more information, see the Compiling and Debugging chapter of the
Neutrino Programmer’s Guide.
June 19, 2012
What’s in a Function Description?
3
© 2012, QNX Software Systems Limited
Description:
This section describes the function or macro.
Returns:
This section gives the return value (if any) for the function or macro.
Errors:
This section describes the special values that the function might assign to the global
variable errno.
This section doesn’t necessarily list all of the values that the function could set errno
to.
See also:
This optional section provides a list of related functions or macros as well as pertinent
docs to look for more information.
Examples:
This optional section gives one or more examples of the use of the function. The
examples are often just code snippets, not complete programs.
Classification:
This section tells where the function or macro is commonly found, which may be
helpful when porting code from one environment to another. Here are the classes:
ANSI
These functions or macros are defined by the ANSI C99
standard.
Large-file support
These functions support 64-bit offsets.
POSIX 1003.1
These functions are specified in the document Information
technology — Portable Operating System Interface (IEEE Std
1003.1, 2004 Edition).
This standard incorporates the POSIX 1003.2-1992 and
1003.1-1996 standards, the approved drafts (POSIX 1003.1a,
POSIX 1003.1d, POSIX 1003.1g and POSIX 1003.1j) and the
Standard Unix specification. A joint technical working group
— the Austin Common Standards Revision Group (CSRG) —
was formed to merge these standards.
4
What’s in a Function Description?
June 19, 2012
© 2012, QNX Software Systems Limited
For an up-to-date status of the many POSIX drafts/standards documents, see the PASC
(Portable Applications Standards Committee of the IEEE Computer Society) report at
http://www.pasc.org/standing/sd11.html.
A classification of “POSIX 1003.1” can be followed by one or
more codes that indicate which option or options the functions
belong to. The codes include the following:
Code Meaning
ADV Advisory Information
AIO Asynchronous Input/Output
BAR Barriers
CPT Process CPU-Time Clocks
CS
Clock Selection
CX
Extension to the ISO C standard
FSC File Synchronization
MF
Memory Mapped Files
ML
Process Memory Locking
MLR Range Memory Locking
MPR Memory Protection
MSG Message Passing
OB
Obsolescent
PS
Process Scheduling
RTS Realtime Signals Extension
SEM Semaphores
SHM Shared Memory Objects
SIO
Synchronous Input/Output
SPI
Spin Locks
TCT Thread CPU-Time Clocks
THR Threads
TMO Timeouts
TMR Timers
continued. . .
June 19, 2012
What’s in a Function Description?
5
© 2012, QNX Software Systems Limited
Code Meaning
TPI
Thread Priority Inheritance
TPP Thread Priority Protection
TPS Thread Execution Scheduling
TSA Thread Stack Address Attribute
TSF Thread-Safe Functions
TSH Thread Process-Shared Synchronization
TSS Thread Stack Size Attribute
TYM Typed Memory Objects
XSI
X/Open Systems Interfaces Extension
XSR XSI Streams
If two codes are separated by a space, you need to use both
options; if the codes are separated by a vertical bar (|), the
functionality is supported if you use either option.
For more information, see the Standard for Information
Technology — Portable Operating System Interface: Base
Definitions.
QNX 4
These functions or macros are neither ANSI nor POSIX. They
perform a function related to the QNX OS version 4. They may
be found in other implementations of C for personal computers
with the QNX 4 OS. Use these functions with caution if
portability is a consideration.
Any QNX 4 functions in the C library are provided only to make it easier to port QNX
4 programs. Don’t use these in QNX Neutrino programs.
6
QNX Neutrino
These functions or macros are neither ANSI nor POSIX. They
perform a function related to the QNX Neutrino OS. They may
be found in other implementations of C for personal computers
with the QNX OS. Use these functions with caution if
portability is a consideration.
RFC 2292
Based on W. Stevens and M. Thomas, Advanced Sockets API
for IPv6, RFC 2292, February 1998.
SNMP
Simple Network Management Protocol is a
network-management protocol whose base document is RFC
1067. It’s used to query and modify network device states.
SOCKS
These functions are part of the SOCKS package consisting of a
proxy server, client programs, and a library (libsocks) for
What’s in a Function Description?
June 19, 2012
© 2012, QNX Software Systems Limited
adapting other applications into new client programs. For more
information, see the appendix SOCKS — A Basic Firewall.
Unix
These Unix-class functions reside on some Unix systems, but
are outside of the POSIX or ANSI standards.
We’ve created the following Unix categories to differentiate:
Legacy Unix
Functions included for backwards compatibility
only. New applications shouldn’t use these
functions.
Unix
Other Unix functions.
Function safety:
This section summarizes whether or not it’s safe to use the C library functions in
certain situations:
Cancellation point
Indicates whether calling a function may or may not cause the
thread to be terminated if a cancellation is pending.
Interrupt handler
An interrupt-safe function behaves as documented even if used
in an interrupt handler. Functions flagged as interrupt-unsafe
shouldn’t be used in interrupt handlers.
Signal handler
A signal-safe function behaves as documented even if called
from a signal handler even if the signal interrupts a
signal-unsafe function.
Some of the signal-safe functions modify errno on failure. If
you use any of these in a signal handler, asynchronous signals
may have the side effect of modifying errno in an unpredictable
way. If any of the code that can be interrupted checks the value
of errno (this also applies to library calls, so you should assume
that most library calls may internally check errno), make sure
that your signal handler saves errno on entry and restores it on
exit.
All of the above also applies to signal-unsafe functions, with
one exception: if a signal handler calls a signal-unsafe function,
make sure that signal doesn’t interrupt a signal-unsafe function.
Thread
June 19, 2012
A thread-safe function behaves as documented even if called in
a multi-threaded environment. Most functions in the QNX
Neutrino libraries are thread-safe.
What’s in a Function Description?
7
© 2012, QNX Software Systems Limited
• The “safety” designations documented in this manual are valid for the current
release and could change in future versions.
• It isn’t safe to use floating-point operations in Interrupt Service Routines (ISRs) or
signal handlers.
For a summary, see the Summary of Safety Information appendix.
8
What’s in a Function Description?
June 19, 2012
Manifests
June 19, 2012
Manifests
9
© 2012, QNX Software Systems Limited
Manifests are used by C/C++ for compile-time changes or inspection. Here are the
defined items:
Manifest
Header file to include
Description
__BEGIN_DECLS
sys/platform.h
Denotes start of C code for a C++ compiled program.
__BIGENDIAN__
sys/platform.h
Code is compiled for a big-endian target.
__CHAR_SIGNED__
sys/platform.h
Code is compiled with the char type defaulting to
signed.
__CHAR_UNSIGNED__
sys/platform.h
Code is compiled with the char type defaulting to
unsigned.
__END_DECLS
sys/platform.h
Denotes end of C code for a C++ compiled program
__INT_BITS__
sys/platform.h
The number of bits in the int datatype.
__LITTLEENDIAN__
sys/platform.h
Code is compiled for a little-endian target.
__LONG_BITS__
sys/platform.h
The number of bits in the long datatype.
_NTO_VERSION
sys/neutrino.h
A version number times 100 (e.g. 2.00 is 200).
__PTR_BITS__
sys/platform.h
The number of bits in a void pointer.
__OPTIMIZE__
sys/platform.h
Code is compiled for optimization.
__QNX__
N/A
The target is for a QNX operating system (QNX 4 or
QNX Neutrino).
__QNXNTO__
N/A
The target is the QNX Neutrino operating system.
June 19, 2012
Manifests
11
QNX Neutrino Functions and Macros
June 19, 2012
QNX Neutrino Functions and Macros
13
© 2012, QNX Software Systems Limited
The functions and macros in the C library are described here in alphabetical order.
June 19, 2012
QNX Neutrino Functions and Macros
15
abort()
© 2012, QNX Software Systems Limited
Raise the SIGABRT signal to terminate program execution
Synopsis:
#include <stdlib.h>
void abort( void );
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
The abort() function causes abnormal process termination to occur by means of the
function call raise(SIGABRT), unless the signal SIGABRT is caught and the signal
handler doesn’t return. If the signal SIGABRT is caught and the signal handler returns,
the signal handler is removed and raise(SIGABRT) is called again. Note that prior to
calling raise(), abort() ensures that SIGABRT isn’t ignored or blocked.
Returns:
The abort() function doesn’t return to its caller.
Examples:
#include <stdlib.h>
int main( void )
{
int major_error = 1;
if( major_error )
abort();
/* You’ll never get here. */
return EXIT_SUCCESS;
}
Classification:
ANSI, POSIX 1003.1
Safety
Cancellation point
No
Interrupt handler
No
Signal handler
Read the Caveats
continued. . .
June 19, 2012
QNX Neutrino Functions and Macros
17
abort()
© 2012, QNX Software Systems Limited
Safety
Thread
Yes
Caveats:
A strictly-conforming POSIX application can’t assume that the abort() function is safe
to use in a signal handler on other platforms.
See also:
atexit(), close(), execl(), execle(), execlp(), execlpe(), execv(), execve(), execvp(),
execvpe(), _exit(), exit(), getenv(), main(), putenv(), sigaction(), signal(), spawn*()
functions, system(), wait(), waitpid()
18
QNX Neutrino Functions and Macros
June 19, 2012
abs()
© 2012, QNX Software Systems Limited
Return the absolute value of an integer
Synopsis:
#include <stdlib.h>
int abs( int j );
Arguments:
j
The number you want the absolute value of.
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
The abs() function returns the absolute value of the integer argument j. If the result
can’t be represented as an int, a warning occurs.
Returns:
The absolute value of its argument.
Examples:
#include <stdio.h>
#include <stdlib.h>
int main( void )
{
printf( "%d %d %d\n", abs (-5), abs (0), abs (5));
return EXIT_SUCCESS;
}
produces the following output:
5 0 5
Classification:
ANSI, POSIX 1003.1
Safety
Cancellation point
No
Interrupt handler
Yes
continued. . .
June 19, 2012
QNX Neutrino Functions and Macros
19
abs()
© 2012, QNX Software Systems Limited
Safety
Signal handler
Yes
Thread
Yes
See also:
cabs(), fabs(), labs(), llabs()
20
QNX Neutrino Functions and Macros
June 19, 2012
accept()
© 2012, QNX Software Systems Limited
Accept a connection on a socket
Synopsis:
#include <sys/types.h>
#include <sys/socket.h>
int accept( int s,
struct sockaddr * addr,
socklen_t * addrlen );
Arguments:
s
A socket that’s been created with socket().
addr
A result parameter that’s filled in with the address of the connecting
entity, as known to the communications layer. The exact format of the
addr parameter is determined by the domain in which the connection was
made.
addrlen
A value-result parameter. It should initially contain the amount of space
pointed to by addr; on return it contains the actual length (in bytes) of the
address returned. This call is used with connection-based socket types,
currently with SOCK_STREAM.
Library:
libsocket
Use the -l socket option to qcc to link against this library.
Description:
The accept() function:
1
Extracts the first connection request on the queue of pending connections.
2
Creates a new socket with the same properties of s, where s is a socket that’s
been created with socket(), bound to an address with bind(), and is listening for
connections after a listen().
3
Allocates a new file descriptor for the socket.
If no pending connections are present on the queue, and the socket isn’t marked as
nonblocking, accept() blocks the caller until a connection is present. If the socket is
marked as nonblocking and no pending connections are present on the queue, accept()
returns an error as described below. The accepted socket may not be used to accept
more connections. The original socket s remains open.
If you do a select() for read on an unconnected socket (on which a listen() has been
done), the select() indicates when a connect request has occurred. In this way, an
accept() can be made that won’t block. For more information, see select().
June 19, 2012
QNX Neutrino Functions and Macros
21
accept()
© 2012, QNX Software Systems Limited
For certain protocols that require an explicit confirmation, accept() can be thought of
as merely dequeuing the next connection request and not implying confirmation.
Confirmation can be implied by a normal read or write on the new file descriptor, and
rejection can be implied by closing the new socket.
You can obtain user-connection request data without confirming the connection by:
• Issuing a recvmsg() call with a msg_iovlen of 0 and a nonzero msg_controllen
Or
• Issuing a getsockopt() request.
Similarly, you can provide user-connection rejection information by issuing a
sendmsg() call with only the control information, or by calling setsockopt().
Returns:
A descriptor for the accepted socket, or -1 if an error occurs (errno is set).
Errors:
EAGAIN
Insufficient resources to create the new socket.
EBADF
Invalid descriptor s.
EFAULT
The addr parameter isn’t in a writable part of the user address
space.
EINVAL
You called accept() on a socket that you hadn’t called listen()
on.
EOPNOTSUPP
The referenced socket isn’t a SOCK_STREAM socket.
ESRCH
Can’t find the socket manager.
EWOULDBLOCK
The socket is marked nonblocking and no connections are
present to be accepted.
Classification:
POSIX 1003.1
Safety
22
Cancellation point
Yes
Interrupt handler
No
Signal handler
No
Thread
Yes
QNX Neutrino Functions and Macros
June 19, 2012
accept()
© 2012, QNX Software Systems Limited
See also:
bind(), close(), connect(), listen(), select(), socket()
June 19, 2012
QNX Neutrino Functions and Macros
23
access()
© 2012, QNX Software Systems Limited
Check to see if a file or directory can be accessed
Synopsis:
#include <unistd.h>
int access( const char * path,
int amode );
Arguments:
path
The path to the file or directory that you want to access.
amode
The access mode you want to check. This must be either:
• F_OK — test for file existence.
or a bitwise ORing of the following access permissions to be checked, as
defined in the header <unistd.h>:
• R_OK — test for read permission.
• W_OK — test for write permission.
• X_OK — for a directory, test for search permission. Otherwise, test for
execute permission.
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
The access() function checks to see if the file or directory specified by path exists and
if it can be accessed with the file access permissions given by amode. However, unlike
other functions (open() for example), it uses the real user ID and real group ID in place
of the effective user and group IDs.
Returns:
0
The file or directory exists and can be accessed with the specified mode.
-1
An error occurred (errno is set).
Errors:
24
EACCES
The permissions specified by amode are denied, or search permission is
denied on a component of the path prefix.
EINVAL
An invalid value was specified for amode.
ELOOP
Too many levels of symbolic links or prefixes.
QNX Neutrino Functions and Macros
June 19, 2012
access()
© 2012, QNX Software Systems Limited
ENAMETOOLONG
ENOENT
The length of the path string exceeds PATH_MAX, or a pathname
component is longer than NAME_MAX.
A component of the path isn’t valid.
ENOSYS
The access() function isn’t implemented for the filesystem specified in
path.
ENOTDIR
A component of the path prefix isn’t a directory.
EROFS
Write access was requested for a file residing on a read-only file
system.
Examples:
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
int main( int argc, char **argv )
{
if( argc!= 2 ) {
fprintf( stderr,
"use: readable <filename>\n" );
return EXIT_FAILURE;
}
if( !access( argv[1], R_OK ) ) {
printf( "ok to read %s\n", argv[1] );
return EXIT_SUCCESS;
} else {
perror( argv[1] );
return EXIT_FAILURE;
}
}
Classification:
POSIX 1003.1
Safety
June 19, 2012
Cancellation point
No
Interrupt handler
No
Signal handler
Yes
Thread
Yes
QNX Neutrino Functions and Macros
25
access()
© 2012, QNX Software Systems Limited
See also:
chmod(), eaccess, errno, fstat(), open(), stat()
26
QNX Neutrino Functions and Macros
June 19, 2012
acos(), acosf(), acosl()
© 2012, QNX Software Systems Limited
Compute the arccosine of an angle
Synopsis:
#include <math.h>
double acos( double x );
float acosf( float x );
long double acosl( long double x );
Arguments:
x
The cosine for which you want to find the angle.
Library:
libm
Use the -l m option to qcc to link against this library.
Description:
These functions compute the arccosine (specified in radians) of x.
Returns:
The arccosine in the range (0, π). For finite values not in the range [-1,1], these
functions return NaN. The return value for +/-Inf is NaN.
If an error occurs, these functions return 0, but this is also a valid mathematical result.
If you want to check for errors, set errno to 0, call the function, and then check errno
again. These functions don’t change errno if no errors occurred.
Examples:
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
int main( void )
{
printf( "%f\n", acos(.5) );
return EXIT_SUCCESS;
}
produces the output:
1.047197
June 19, 2012
QNX Neutrino Functions and Macros
27
acos(), acosf(), acosl()
© 2012, QNX Software Systems Limited
Classification:
ANSI, POSIX 1003.1
Safety
Cancellation point
No
Interrupt handler
No
Signal handler
No
Thread
Yes
See also:
asin(), atan(), atan2()
28
QNX Neutrino Functions and Macros
June 19, 2012
acosh(), acoshf(), acoshl()
© 2012, QNX Software Systems Limited
Compute the inverse hyperbolic cosine
Synopsis:
#include <math.h>
double acosh( double x );
float acoshf( float x );
long double acoshl( long double x );
Arguments:
x
The value for which you want to compute the inverse hyperbolic cosine.
Library:
libm
Use the -l m option to qcc to link against this library.
Description:
These functions compute the inverse hyperbolic cosine (specified in radians) of x.
Returns:
The inverse hyperbolic cosine of x (specified in radians). For finite values of x < 1,
these functions return NaN. The return value when x is -Inf is NaN.
Examples:
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
int main( void )
{
printf( "%f\n", acosh( 1.5 ) );
return EXIT_SUCCESS;
}
produces the output:
0.962424
Classification:
ANSI, POSIX 1003.1
June 19, 2012
QNX Neutrino Functions and Macros
29
acosh(), acoshf(), acoshl()
© 2012, QNX Software Systems Limited
Safety
Cancellation point
No
Interrupt handler
No
Signal handler
No
Thread
Yes
See also:
asinh(), atanh(), cosh(), errno
30
QNX Neutrino Functions and Macros
June 19, 2012
addrinfo
© 2012, QNX Software Systems Limited
TCP/IP address information
Synopsis:
struct addrinfo {
int ai_flags;
int ai_family;
int ai_socktype;
int ai_protocol;
size_t ai_addrlen;
char * ai_canonname;
struct sockaddr * ai_addr;
struct addrinfo * ai_next
};
Description:
The addrinfo structure describes address information for use with TCP/IP. To get
this information, call getaddrinfo(); to free a linked list of these structures, call
freeaddrinfo().
The addrinfo structure includes these members:
ai_flags
Flags. Includes AI_PASSIVE, AI_CANONNAME, and
AI_NUMERICHOST. For a complete list, see <netdb.h>.
ai_family
Protocol family. Includes PF_UNSPEC and PF_INET. For a
complete list, see <sys/socket.h>.
ai_socktype
Socket type. Includes SOCK_STREAM and SOCK_DGRAM. For a
complete list, see <sys/socket.h>.
ai_protocol
Protocol. Includes IPPROTO_TCP and IPPROTO_UDP. For a
complete list, see <netinet/in.h>.
ai_addrlen
The length of the ai_addr member.
ai_canonname
The canonical name for nodename.
ai_addr
Binary socket address.
ai_next
A pointer to the next addrinfo structure in the linked list.
Classification:
POSIX 1003.1
See also:
freeaddrinfo(), gai_strerror(), getaddrinfo()
June 19, 2012
QNX Neutrino Functions and Macros
31
aio_cancel()
© 2012, QNX Software Systems Limited
Cancel an asynchronous I/O operation
Synopsis:
#include <aio.h>
int aio_cancel( int fd,
struct aiocb * aiocbptr );
Arguments:
fd
The file descriptor for which you want to cancel asynchronous I/O
requests.
aiocbptr
A pointer to an asynchronous I/O control block of type aiocb for the
request you want to cancel, or NULL if you want to cancel all requests
against the file descriptor.
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
The aio_cancel() function attempts to cancel one or more asynchronous I/O requests
currently outstanding against a file descriptor.
Normal asynchronous notification occurs for asynchronous I/O operations that are
successfully canceled. If there are requests that can’t be canceled, then the normal
asynchronous completion process takes place for those requests when they’re
completed.
The error status that’s associated with requested operations that are successfully
canceled is set to ECANCELED, and the return status is -1. The aio_cancel() function
doesn’t modify the aiocb structures for requested operations that aren’t successfully
canceled.
If aiocbptr isn’t NULL, aio_cancel() ignores the fildes argument and attempts to
cancel the I/O operation specified by the aiocb control block. The operation isn’t
cancelled if it’s already in progress.
Returns:
AIO_CANCELED
The requested operation(s) were canceled.
AIO_NOTCANCELED
At least one of the requested operations couldn’t be canceled
because it was in progress.
32
QNX Neutrino Functions and Macros
June 19, 2012
aio_cancel()
© 2012, QNX Software Systems Limited
A return value of AIO_NOTCANCELED doesn’t indicate the state of any other
operations referenced in the call to aio_cancel(). To determine their status, use
aio_error().
AIO_ALLDONE
All of the operations have already been completed.
-1
An error occurred; errno is set.
Errors:
EBADF
The filedes argument isn’t a valid file descriptor.
EINVAL
The control block that aiocbptr points to isn’t valid (i.e. it hasn’t yet been
used in any call to aio_read() or aio_write()).
Classification:
POSIX 1003.1 AIO
Safety
Cancellation point
No
Interrupt handler
No
Signal handler
Yes
Thread
Yes
Caveats:
The first time you call an aio_* function, a thread pool is created, making your
process multithreaded if it isn’t already. The thread pool isn’t destroyed until your
process ends.
See also:
aio_error(), aio_fsync(), aio_read(), aio_return(), aio_suspend(), aio_write(), aiocb
June 19, 2012
QNX Neutrino Functions and Macros
33
aio_error()
© 2012, QNX Software Systems Limited
Get the error status for an asynchronous I/O operation
Synopsis:
#include <aio.h>
int aio_error( const struct aiocb * aiocbptr );
Arguments:
aiocbptr
A pointer to an asynchronous I/O control block of type aiocb that you
want the error status for.
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
The aio_error() function returns the error status associated with the aiocb structure
referenced by the aiocbptr argument. The error status for an asynchronous I/O
operation is the errno value that’s set by the corresponding read(), write(), or fsync()
operation. If the operation hasn’t yet been completed, the error status is
EINPROGRESS.
Returns:
One of:
• 0 if the operation was completed successfully
• the error status set by read(), write(), or fsync() if the operation wasn’t completed
successfully
• EINPROGRESS if the operation hasn’t yet been completed
Errors:
EINVAL
The aiocbptr argument doesn’t refer to an asynchronous operation whose
return status hasn’t yet been retrieved.
Classification:
POSIX 1003.1 AIO
34
QNX Neutrino Functions and Macros
June 19, 2012
aio_error()
© 2012, QNX Software Systems Limited
Safety
Cancellation point
No
Interrupt handler
No
Signal handler
Yes
Thread
Yes
Caveats:
The first time you call an aio_* function, a thread pool is created, making your
process multithreaded if it isn’t already. The thread pool isn’t destroyed until your
process ends.
See also:
aio_cancel(), aio_fsync(), aio_read(), aio_return(), aio_suspend(), aio_write(),
aiocb
June 19, 2012
QNX Neutrino Functions and Macros
35
aio_fsync()
© 2012, QNX Software Systems Limited
Asynchronously synchronize a file
Synopsis:
#include <aio.h>
int aio_fsync( int op,
struct aiocb * aiocbptr );
Arguments:
op
One of the following:
• O_DSYNC — complete all queued operations as if done by calling
fdatasync() (i.e. as defined for synchronized I/O data integrity
completion).
• O_SYNC — complete all queued operations as if done by calling
fsync() (i.e. as defined for synchronized I/O file integrity completion).
aiocbptr
A pointer to an asynchronous I/O control block of type aiocb for which
you want to asynchronously force all queued I/O operations to the
synchronized I/O completion state.
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
The aio_fsync() function asynchronously forces all I/O operations associated with the
file indicated by the file descriptor to the synchronized I/O completion state.
If the function succeeds, only the I/O operations that were queued at the time of the
call are guaranteed to have been completed. The completion of subsequent I/O on the
file descriptor isn’t guaranteed to be completed in a synchronized fashion. If the
operation that aio_fsync() queues fails, outstanding I/O operations aren’t guaranteed
to have been completed.
You can pass the aiocbptr argument to aio_error() or aio_return() to determine the
error status and return status for the asynchronous operation.
Returns:
0 if the I/O operation was successfully queued, or -1 if an error occurred (errno is set).
36
QNX Neutrino Functions and Macros
June 19, 2012
aio_fsync()
© 2012, QNX Software Systems Limited
Errors:
EAGAIN
EBADF
The requested asynchronous operation wasn’t queued due to temporary
resource limitations.
The aio_fildes member of the aiocb structure referenced by the aiocbptr
argument isn’t a valid file descriptor that’s open for writing.
EINVAL
Synchronized I/O isn’t supported for this file.
EINVAL
The op argument was something other than O_DSYNC or O_SYNC.
If any of the queued I/O operations failed, aio_fsync() returns the error condition
defined for read() and write(). The error is returned in the error status for the
asynchronous fsync() operation, which you can retrieve by using aio_error().
Classification:
POSIX 1003.1 AIO
Safety
Cancellation point
No
Interrupt handler
No
Signal handler
Yes
Thread
Yes
Caveats:
The first time you call an aio_* function, a thread pool is created, making your
process multithreaded if it isn’t already. The thread pool isn’t destroyed until your
process ends.
See also:
aio_cancel(), aio_error(), aio_read(), aio_return(), aio_suspend(), aio_write(),
aiocb, fdatasync(), fsync(), read(), write()
June 19, 2012
QNX Neutrino Functions and Macros
37
aio_read()
© 2012, QNX Software Systems Limited
Asynchronously read from a file
Synopsis:
#include <aio.h>
int aio_read( struct aiocb * aiocbptr );
Arguments:
aiocbptr
A pointer to an asynchronous I/O control block of type aiocb that
defines how much data to read, and from where.
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
The aio_read() function asynchronously reads aiocbptr->aio_nbytes from the file
associated with aiocbptr->aio_fildes into the buffer pointed to by aiocbptr->aio_buf .
It returns when the read request has been initiated or queued to the file or device (even
when the data can’t be delivered immediately).
The asynchronous operation is submitted at the scheduling priority of the thread minus
aiocbp->aio_reqprio.
You can pass the aiocbptr argument to aio_error() and aio_return(), to determine the
error status and return status of the asynchronous operation while it’s proceeding. If an
error condition is encountered during queuing, the function call returns without having
initiated or queued the request. The requested operation takes place at the absolute
position in the file as given by aio_offset, as if lseek() were called immediately prior to
the operation with an offset equal to aio_offset and a whence of SEEK_SET. After a
successful call to enqueue an asynchronous I/O operation, the value of the file offset
for the file is unspecified.
This function ignores the aiocbptr->aio_lio_opcode field.
If the buffer pointed to by aiocbptr->aio_buf or the control block pointed to by
aiocbptr becomes an illegal address before the asynchronous I/O is completed, then
the behavior is undefined.
Simultaneous asynchronous operations using the same aiocbptr produce undefined
results.
If synchronized I/O is enabled on the file associated with aiocbptr->aio_fildes, this
function behaves in accordance with the definitions of synchronized I/O data integrity
completion and synchronized I/O file integrity completion.
38
QNX Neutrino Functions and Macros
June 19, 2012
aio_read()
© 2012, QNX Software Systems Limited
If a system action changes the process memory space while an asynchronous I/O is
outstanding to the address range being changed, the results of that action are
undefined.
The following conditions may be detected synchronously at the time of the call to
aio_read(), or asynchronously. If any of these conditions are detected synchronously,
aio_read() returns -1 and sets errno to the corresponding value. If any of these
conditions are detected asynchronously, the return status of the asynchronous
operation is set to -1, and the error status of the asynchronous operation is set to the
corresponding value:
EBADF
The aiocbptr->aio_fildes argument isn’t a valid file descriptor that’s open
for reading.
EINVAL
The file offset value implied by aiocbptr->aio_offset would be invalid,
aiocbptr->aio_reqprio isn’t a valid value, or aiocbptr->aio_nbytes is
invalid.
If aio_read() successfully queues the I/O operation, but the operation is subsequently
canceled or encounters an error, the return status of the asynchronous operation is one
of the values normally returned by read(). In addition, the error status of the
asynchronous operation is set to one of the error statuses normally set read(), or one of
the following:
EBADF
The aiocbptr->aio_fildes isn’t a valid file descriptor that’s open for
reading.
ECANCELED
The requested I/O was canceled before the I/O was completed, due
to an explicit aio_cancel(), request.
EINVAL
The file offset value implied by aiocbptr->aio_offset would be
invalid.
The following condition may be detected synchronously or asynchronously:
EOVERFLOW
The file is a regular file, aiocbptr->aio_nbytes is greater than 0, and
the starting offset in aiocbptr->aio_offset is before the end of the
file and is at or beyond the offset maximum in the open file
description associated with aiocbptr->aio_fildes.
Returns:
0 if the I/O operation was successfully queued, or -1 if an error occurred (errno is set).
June 19, 2012
QNX Neutrino Functions and Macros
39
aio_read()
© 2012, QNX Software Systems Limited
Errors:
EAGAIN
The requested asynchronous I/O operation wasn’t queued because of
system resource limitations.
Classification:
POSIX 1003.1 AIO
Safety
Cancellation point
No
Interrupt handler
No
Signal handler
Yes
Thread
Yes
Caveats:
The first time you call an aio_* function, a thread pool is created, making your
process multithreaded if it isn’t already. The thread pool isn’t destroyed until your
process ends.
See also:
aio_cancel(), aio_error(), aio_fsync(), aio_return(), aio_suspend(), aio_write(),
read()
40
QNX Neutrino Functions and Macros
June 19, 2012
aio_return()
© 2012, QNX Software Systems Limited
Get the return status for an asynchronous I/O operation
Synopsis:
#include <aio.h>
ssize_t aio_return( struct aiocb * aiocbptr );
Arguments:
aiocbptr
A pointer to an asynchronous I/O control block of type aiocb whose
return status you want to get.
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
The aio_return() function returns the return status associated with the aiocb structure
referenced by the aiocbptr argument. The return status for an asynchronous I/O
operation is the value that’s returned by the corresponding read(), write(), or fsync()
operation.
You can call aio_return() exactly once to retrieve the return status of a given
asynchronous operation; if you use the same aiocb structure for the same operation in
a call to aio_return() or aio_error(), an error may be returned.
Returns:
The value that’s returned by the corresponding read(), write(), or fsync() operation.
Errors:
EINVAL
The aiocbptr argument doesn’t refer to an asynchronous operation whose
return status hasn’t yet been retrieved.
Classification:
POSIX 1003.1 AIO
Safety
Cancellation point
No
Interrupt handler
No
Signal handler
Yes
continued. . .
June 19, 2012
QNX Neutrino Functions and Macros
41
aio_return()
© 2012, QNX Software Systems Limited
Safety
Thread
Yes
Caveats:
The first time you call an aio_* function, a thread pool is created, making your
process multithreaded if it isn’t already. The thread pool isn’t destroyed until your
process ends.
See also:
aio_cancel(), aio_error(), aio_fsync(), aio_read(), aio_suspend(), aio_write(),
aiocb, fsync(), read(), write(),
42
QNX Neutrino Functions and Macros
June 19, 2012
aio_suspend()
© 2012, QNX Software Systems Limited
Wait for asynchronous I/O operations to be completed
Synopsis:
#include <aio.h>
int aio_suspend( const struct aiocb * const list[],
int nent,
const struct timespec * timeout );
Arguments:
list
A list of aiocb structures describing the asynchronous operations you
want to wait for. Each aiocb structure must have been used in initiating
an asynchronous I/O request via aio_read(), aio_write(), or lio_listio().
The list may contain NULL pointers, which aio_suspend() ignores.
nent
The number of entries in the list.
timeout
NULL, or a pointer to a timespec structure that specifies the maximum
length of time you want to wait for.
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
The aio_suspend() function suspends the calling thread until at least one of the
asynchronous I/O operations referenced by the list argument has been completed, until
a signal interrupts the function, or, if timeout isn’t NULL, until the time interval
specified by timeout has passed.
If any of the aiocb structures in the list correspond to completed asynchronous I/O
operations (i.e. the error status for the operation isn’t EINPROGRESS) at the time of
the call, aio_suspend() returns without suspending the calling thread.
Returns:
0 if one or more of the asynchronous I/O operations have been completed, otherwise
-1 (errno is set).
You can determine which asynchronous I/O operations were completed by scanning
the associated error and return status, using aio_error() and aio_return().
June 19, 2012
QNX Neutrino Functions and Macros
43
aio_suspend()
© 2012, QNX Software Systems Limited
Errors:
EAGAIN
EINTR
No asynchronous I/O operation indicated in the list was completed in the
time interval indicated by timeout.
A signal interrupted the aio_suspend() function. Note that, since each
asynchronous I/O operation may possibly provoke a signal when it’s
completed, this error return may be caused by the completion of one (or
more) of the very I/O operations you’re waiting on.
Classification:
POSIX 1003.1 AIO
Safety
Cancellation point
Yes
Interrupt handler
No
Signal handler
Yes
Thread
Yes
Caveats:
The first time you call an aio_* function, a thread pool is created, making your
process multithreaded if it isn’t already. The thread pool isn’t destroyed until your
process ends.
See also:
aio_cancel(), aio_error(), aio_fsync(), aio_read(), aio_return(), aio_write(), aiocb,
lio_listio()
44
QNX Neutrino Functions and Macros
June 19, 2012
aio_write()
© 2012, QNX Software Systems Limited
Asynchronously write to a file
Synopsis:
#include <aio.h>
int aio_write( struct aiocb * aiocbptr );
Arguments:
aiocbptr
A pointer to an asynchronous I/O control block of type aiocb that
defines how much data to write, and where to write it.
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
The aio_write() function asynchronously writes aiocbptr->aio_nbytes to the file
associated with aiocbptr->aio_fildes from the buffer that aiocbptr->aio_buf points to.
The function returns when the write request has been initiated or, at a minimum,
queued to the file or device.
The asynchronous operation is submitted at the scheduling priority of the thread minus
aiocbptr->aio_reqprio.
You can use the aiocbptr argument as an argument to aio_error() and aio_return() to
determine the error status and return status of the asynchronous operation while it’s in
progress.
If O_APPEND isn’t set for the file descriptor aio_fildes, then the requested operation
takes place at the absolute position in the file as given by aio_offset, as if lseek() were
called immediately before the operation with an offset of aio_offset and a whence of
SEEK_SET.
If O_APPEND is set for the file descriptor, write operations append to the file in the
same order as the calls were made.
If synchronized I/O is enabled on the file associated with aiocbptr->aio_fildes, this
function behaves in accordance with the definitions of synchronized I/O data integrity
completion and synchronized I/O file integrity completion.
The following conditions may be detected synchronously at the time of the call to
aio_write(), or asynchronously. If any of these conditions are detected synchronously,
aio_write() returns -1 and sets errno to the corresponding value. If any of these
conditions are detected asynchronously, the return status of the asynchronous
operation is set to -1, and the error status of the asynchronous operation is set to the
corresponding value:
June 19, 2012
QNX Neutrino Functions and Macros
45
aio_write()
© 2012, QNX Software Systems Limited
EBADF
The aiocbptr->aio_fildes argument isn’t a valid file descriptor that’s open
for writing.
EINVAL
The file offset value implied by aiocbptr->aio_offset would be invalid,
aiocbptr->aio_reqprio isn’t a valid value, or aiocbptr->aio_nbytes is
invalid.
If aio_write() successfully queues the I/O operation, but the operation is subsequently
canceled or encounters an error, the return status of the asynchronous operation is one
of the values normally returned by write(). In addition, the error status of the
asynchronous operation is set to one of the error statuses normally set by write(), or
one of the following:
EBADF
The aiocbptr->aio_fildes isn’t a valid file descriptor that’s open for
writing.
ECANCELED
The requested I/O was canceled before the I/O was completed, due
to an explicit aio_cancel(), request.
EINVAL
The file offset value implied by aiocbptr->aio_offset would be
invalid.
The following condition may be detected synchronously or asynchronously:
EOVERFLOW
The file is a regular file, aiocbptr->aio_nbytes is greater than 0, and
the starting offset in aiocbptr->aio_offset is at or beyond the offset
maximum in the open file description associated with
aiocbptr->aio_fildes.
Returns:
0 if the I/O operation was successfully queued, or -1 if an error occurred (errno is set).
Errors:
EAGAIN
The requested asynchronous I/O operation wasn’t queued because of
system resource limitations.
Classification:
POSIX 1003.1 AIO
Safety
Cancellation point
No
continued. . .
46
QNX Neutrino Functions and Macros
June 19, 2012
aio_write()
© 2012, QNX Software Systems Limited
Safety
Interrupt handler
No
Signal handler
Yes
Thread
Yes
Caveats:
The first time you call an aio_* function, a thread pool is created, making your
process multithreaded if it isn’t already. The thread pool isn’t destroyed until your
process ends.
See also:
aio_cancel(), aio_error(), aio_fsync(), aio_read(), aio_return(), aio_suspend(),
aiocb, write()
June 19, 2012
QNX Neutrino Functions and Macros
47
aiocb
© 2012, QNX Software Systems Limited
Asynchronous I/O control block
Synopsis:
#include <aio.h>
struct aiocb {
int
aio_fildes
off_t
aio_offset
volatile void *aio_buf
size_t
aio_nbytes
int
aio_reqprio
struct sigevent aio_sigevent
int
aio_lio_opcode
}
Description:
aio_fildes
The file descriptor to use in an asynchronous I/O operation.
The aio_* functions work with Transparent Distributed Processing; the file descriptor
can be one that you’ve opened across Qnet.
aio_offset
The file offset.
aio_buf
A pointer to a buffer.
aio_nbytes
The length of a transfer.
aio_reqprio
The request priority offset.
aio_sigevent
A pointer to a sigevent structure that specifies the signal
number and value.
aio_lio_opcode
The operation to be performed; one of the following:
• LIO_NOP — a lio_listio() element operation option indicating
that no transfer is requested.
• LIO_NOWAIT — a lio_listio() synchronization operation
indicating that the calling thread is to continue execution while
the lio_listio() operation is being performed, and no
notification is given when the operation is complete.
• LIO_READ — a lio_listio() element operation option
requesting a read.
• LIO_WAIT — a lio_listio() synchronization operation
indicating that the calling thread is to suspend until the
lio_listio() operation is complete.
• LIO_WRITE — a lio_listio() element operation option
requesting a write.
48
QNX Neutrino Functions and Macros
June 19, 2012
© 2012, QNX Software Systems Limited
aiocb
Classification:
POSIX 1003.1 AIO
Caveats:
The first time you call an aio_* function, a thread pool is created, making your
process multithreaded if it isn’t already. The thread pool isn’t destroyed until your
process ends.
See also:
aio_cancel(), aio_error(), aio_fsync(), aio_read(), aio_return(), aio_suspend(),
aio_write(), lio_listio()
June 19, 2012
QNX Neutrino Functions and Macros
49
alarm()
© 2012, QNX Software Systems Limited
Schedule an alarm
Synopsis:
#include <unistd.h>
unsigned int alarm( unsigned int seconds );
Arguments:
seconds
The number of seconds of realtime to let elapse before raising the alarm,
or zero to cancel any previous alarm() requests.
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
The alarm() function causes the system to send the calling process a SIGALRM signal
after a specified number of realtime seconds have elapsed. To add a handler for the
signal, call signal() or SignalAction().
• Because of the nature of time measurement, the signal might actually get sent later
than the specified time. For more information, see the Tick, Tock: Understanding
the Neutrino Microkernel’s Concept of Time chapter of the QNX Neutrino
Programmer’s Guide.
• Processor scheduling delays may cause the process to handle the signal after the
desired time.
The alarm() requests aren’t stacked; you can schedule only a single SIGALRM
generation in this manner. If the SIGALRM hasn’t yet been generated, alarm()
reschedules the time at which the SIGALRM is generated.
Returns:
The number of seconds before the calling process is scheduled to receive a SIGALRM
from the system, or zero if there was no previous alarm() request.
If an error occurs, an (unsigned)-1 is returned (errno is set).
Errors:
EAGAIN
50
All timers are in use. You’ll have to wait for a process to release one.
QNX Neutrino Functions and Macros
June 19, 2012
alarm()
© 2012, QNX Software Systems Limited
Examples:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main()
{
unsigned int
timeleft;
printf( "Set the alarm and sleep\n" );
alarm( 10 );
sleep( 5 );
/* go to sleep for 5 seconds */
/*
* To get the time left before the SIGALRM is
* to arrive, one must cancel the initial timer,
* which returns the amount of time it had
* remaining.
*/
timeleft = alarm( 0 );
printf( "Time left before cancel, and rearm: %d\n",
timeleft );
/*
* Start a new timer that kicks us when timeleft
* seconds have passed.
*/
alarm( timeleft );
/*
* Wait until we receive the SIGALRM signal; any
* signal kills us, though, since we don’t have
* a signal handler.
*/
printf( "Hanging around, waiting to die\n" );
pause();
return EXIT_SUCCESS;
}
Classification:
POSIX 1003.1
Safety
June 19, 2012
Cancellation point
No
Interrupt handler
No
Signal handler
Yes
Thread
Yes
QNX Neutrino Functions and Macros
51
alarm()
© 2012, QNX Software Systems Limited
Caveats:
Requests from alarm(), TimerAlarm(), and ualarm() aren’t “stacked;” only a single
SIGALRM generator can be scheduled with these functions. If the SIGALRM signal
hasn’t been generated, the next call to alarm(), TimerAlarm(), or ualarm() reschedules
it.
See also:
errno, pause(), signal(), SignalAction(), sleep(), TimerAlarm(), timer_create(),
timer_delete(), timer_gettime(), timer_settime(), ualarm()
Tick, Tock: Understanding the Neutrino Microkernel’s Concept of Time chapter of the
QNX Neutrino Programmer’s Guide
52
QNX Neutrino Functions and Macros
June 19, 2012
alloca()
© 2012, QNX Software Systems Limited
Allocate automatic space from the stack
Synopsis:
#include <alloca.h>
void* alloca( size_t size );
Arguments:
size
The number of bytes of memory to allocate.
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
The alloca() function allocates space for an object of size bytes from the stack. The
allocated space is automatically discarded when the current function exits.
• Don’t use this function in an expression that’s an argument to a function.
• By default, alloca() is implemented as __builtin_alloca(). If you compile with the
-fno-builtin option, you’ll use the libc version of alloca(), which is a cover
for malloc() and behaves in a slightly different manner:
- It keeps track of all blocks allocated with alloca() and reclaims any that are
found to be deeper in the stack than the current invocation. It therefore doesn’t
reclaim storage as soon as it becomes invalid, but it will do so eventually.
- As a special case, alloca(0) reclaims storage without allocating any. You can
use this feature to force garbage collection.
Returns:
A pointer to the start of the allocated memory, or NULL if an error occurred (errno is
set).
Examples:
#include
#include
#include
#include
<stdio.h>
<string.h>
<malloc.h>
<stdlib.h>
FILE *open_err_file( char *name )
{
char *buffer;
/* allocate temporary buffer for file name */
buffer = (char *)alloca( strlen( name ) + 5 );
June 19, 2012
QNX Neutrino Functions and Macros
53
alloca()
© 2012, QNX Software Systems Limited
if( buffer ) {
FILE *fp;
sprintf( buffer, "%s.err", name );
fp = fopen( buffer, "w" );
return fp;
}
return (FILE *)NULL;
}
int main( void )
{
FILE *fp;
fp = open_err_file( "alloca_test" );
if( fp == NULL ) {
printf( "Unable to open error file\n" );
} else {
fprintf( fp, "Hello from the alloca test.\n" );
fclose( fp );
}
return EXIT_SUCCESS;
}
Classification:
Unix
Safety
Cancellation point
No
Interrupt handler
No
Signal handler
Yes
Thread
Yes
Caveats:
Don’t use alloca() as an argument to a function.
See also:
calloc(), malloc()
54
QNX Neutrino Functions and Macros
June 19, 2012
alphasort()
© 2012, QNX Software Systems Limited
Compare two directory entries
Synopsis:
#include <sys/types.h>
#include <sys/dir.h>
struct direct {
unsigned long d_fileno;
unsigned short d_reclen;
unsigned short d_namlen;
char d_name[1];
};
int alphasort( struct direct **d1,
struct direct **d2);
Arguments:
d1, d2
Pointers to the struct direct directory entries that you want to
compare.
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
This function is in libc.a, but not in libc.so (in order to save space).
Description:
The alphasort() function alphabetically compares two directory entries. You can use it
as the compar argument to scandir().
Returns:
<0
The d1 entry precedes the d2 entry alphabetically.
0
The entries are equivalent.
>0
The d1 entry follows the d2 entry alphabetically.
Classification:
Legacy Unix
June 19, 2012
QNX Neutrino Functions and Macros
55
alphasort()
© 2012, QNX Software Systems Limited
Safety
Cancellation point
No
Interrupt handler
Yes
Signal handler
Yes
Thread
Yes
See also:
closedir(), opendir(), readdir(), rewinddir(), scandir(), seekdir(), telldir()
56
QNX Neutrino Functions and Macros
June 19, 2012
_amblksiz
© 2012, QNX Software Systems Limited
The increment for the break pointer
Synopsis:
#include <stdlib.h>
unsigned int _amblksiz
Description:
The _amblksiz global variable is the basic unit that’s used for heap allocations to get
memory from the system using mmap(). All underlying mmap() operations made by
the heap allocator get memory as multiples of _amblksiz. By default, _amblksiz is set
to 8 × PSIZ, or 32 KB. Its value must be a multiple of 4 KB, and currently is limited to
being less than 256 KB.
In the current implementation of the allocator, requests for memory larger than 32 KB
are automatically serviced by calling mmap() directly, while smaller allocations are
serviced by a split-coalesce mechanism inside the allocator.
The value of _amblksiz affects all allocations that are smaller than 32 KB and require
a core allocation. Memory that has become free will eventually return to the system
when all memory associated with a specific core allocation has been released back to
the allocator. Even when a block has been fully released to the allocator, it’s possible
for the allocator, for efficiency purposes, to retain some blocks locally within the heap
(without releasing memory to the system immediately). This is done to avoid
thrashing behavior, when requests to allocate and free memory cause the the allocator
to constantly request and release memory to and from the system.
There are several ways that you can change _amblksiz:
• Redefine _amblksiz as a global in your code. Doing this overrides the definition
from the library:
unsigned _amblksiz = 8*PSIZ;
No checking is done, but the value specified here must be a multiple of 4 KB. You
can reset _amblksiz to a new value at any time, and this takes effect from that point
onwards.
!
CAUTION: It isn’t safe for a multithreaded program to dynamically change this
value. Multithreaded applications should set this value as a global at compile time, and
use the below mechanisms for safely manipulating _amblksiz.
• Set the MALLOC_ARENA_SIZE environment variable to the value you want to
assign to _amblksiz. This is evaluated when malloc() is first initialised, so it’s done
before any allocations. The value specified is rounded up to the nearest multiple of
4 KB. Values above 0x40000 (256 KB) or below 4 KB aren’t accepted at this time.
• Call mallopt(MALLOC_ARENA_SIZE, size). This sets _amblksiz to the value
specified by size. This is evaluated when you call mallopt(). The value specified is
June 19, 2012
QNX Neutrino Functions and Macros
57
_amblksiz
© 2012, QNX Software Systems Limited
rounded up to the nearest multiple of 4 KB. Values above 0x40000 (256 KB) or
below 4 KB aren’t accepted at this time.
If size is specified as zero, mallopt() returns the current value of _amblksiz.
Classification:
QNX Neutrino
See also:
malloc(), mallopt(), mmap()
The Heap Analysis: Making Memory Errors a Thing of the Past chapter of the
Neutrino Programmer’s Guide.
58
QNX Neutrino Functions and Macros
June 19, 2012
_argc
© 2012, QNX Software Systems Limited
The number of arguments passed to main()
Synopsis:
int _argc
Description:
This global variable holds the number of arguments passed to main().
This variable isn’t defined in any header file. If you want to refer to it, you need to add
your own extern statement.
Classification:
QNX Neutrino
See also:
_argv, _auxv, getopt(), main()
June 19, 2012
QNX Neutrino Functions and Macros
59
_argv
© 2012, QNX Software Systems Limited
A pointer to the vector of arguments passed to main()
Synopsis:
char ** _argv;
Description:
This global variable holds a pointer to a vector containing the actual arguments passed
to main().
This variable isn’t defined in any header file. If you want to refer to it, you need to add
your own extern statement.
Classification:
QNX Neutrino
See also:
_argc, _auxv, getopt(), main()
60
QNX Neutrino Functions and Macros
June 19, 2012
asctime(), asctime_r()
© 2012, QNX Software Systems Limited
Convert time information to a string
Synopsis:
#include <time.h>
char* asctime( const struct tm* timeptr );
char* asctime_r( const struct tm* timeptr,
char* buf );
Arguments:
timeptr
A pointer to a tm structure that contains the time that you want to convert
to a string.
buf
(asctime_r() only) A buffer in which asctime_r() can store the resulting
string. This buffer must be large enough to hold at least 26 characters.
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
The asctime() and asctime_r() functions convert the time information in the structure
pointed to by timeptr into a string containing exactly 26 characters, in the form:
Tue May
7 10:40:27 2002\n\0
The asctime() function places the result string in a static buffer that’s reused every
time you call asctime() or ctime(). Calling gmtime() or localtime() could also change
the date in this static buffer.
The result string for asctime_r() is contained in the buffer pointed to by buf .
All fields have a constant width. The newline character (’\n’) and a NUL character
(’\0’) occupy the last two positions of the string.
Returns:
A pointer to the character string result, or NULL if an error occurred.
Classification:
asctime() is ANSI, POSIX 1003.1; asctime_r() is POSIX 1003.1 TSF
June 19, 2012
QNX Neutrino Functions and Macros
61
asctime(), asctime_r()
© 2012, QNX Software Systems Limited
asctime()
Safety
Cancellation point
No
Interrupt handler
No
Signal handler
No
Thread
No
asctime_r()
Safety
Cancellation point
No
Interrupt handler
No
Signal handler
Yes
Thread
Yes
Caveats:
The asctime() and ctime() functions place their results in a static buffer that’s reused
for each call to asctime() or ctime().
See also:
clock(), ctime(), difftime(), gmtime(), localtime(), localtime_r(), mktime(), strftime(),
time(), tm, tzset()
62
QNX Neutrino Functions and Macros
June 19, 2012
asin(), asinf(), asinl()
© 2012, QNX Software Systems Limited
Compute the arcsine of an angle
Synopsis:
#include <math.h>
double asin( double x );
float asinf( float x );
long double asinl( long double x );
Arguments:
x
The sine for which you want to find the angle.
Library:
libm
Use the -l m option to qcc to link against this library.
Description:
These functions compute the value of the arcsine (specified in radians) of x.
Returns:
The arcsine, in the range (-π/2, π/2). For finite values not in the range [-1,1], these
functions return NaN. The return value for +/-Inf is NaN.
If an error occurs, these functions return 0, but this is also a valid mathematical result.
If you want to check for errors, set errno to 0, call the function, and then check errno
again. These functions don’t change errno if no errors occurred.
Examples:
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
int main( void )
{
printf( "%f\n", asin(.5) );
return EXIT_SUCCESS;
}
produces the output:
0.523599
June 19, 2012
QNX Neutrino Functions and Macros
63
asin(), asinf(), asinl()
© 2012, QNX Software Systems Limited
Classification:
ANSI, POSIX 1003.1
Safety
Cancellation point
No
Interrupt handler
No
Signal handler
No
Thread
Yes
See also:
acos(), atan(), atan2(), errno
64
QNX Neutrino Functions and Macros
June 19, 2012
asinh(), asinhf(), asinhl()
© 2012, QNX Software Systems Limited
Compute the inverse hyperbolic sine
Synopsis:
#include <math.h>
double asinh( double x );
float asinhf( float x );
long double asinhl( long double x );
Arguments:
x
The value for which you want to compute the inverse hyperbolic sine.
Library:
libm
Use the -l m option to qcc to link against this library.
Description:
These functions compute the inverse hyperbolic sine of x.
Returns:
The inverse hyperbolic sine (specified in radians) of x.
Examples:
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
int main( void )
{
printf( "%f\n", asinh( 0.5 ) );
return EXIT_SUCCESS;
}
produces the output:
0.481212
Classification:
ANSI, POSIX 1003.1
Safety
Cancellation point
No
continued. . .
June 19, 2012
QNX Neutrino Functions and Macros
65
asinh(), asinhf(), asinhl()
© 2012, QNX Software Systems Limited
Safety
Interrupt handler
No
Signal handler
No
Thread
Yes
See also:
acosh(), atanh(), sinh(), errno
66
QNX Neutrino Functions and Macros
June 19, 2012
assert()
© 2012, QNX Software Systems Limited
Print a diagnostic message and optionally terminate the program
Synopsis:
#include <assert.h>
void assert( int expression );
Arguments:
expression
Zero if you want to terminate the program; a nonzero value if you
don’t.
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
The assert() macro prints a diagnostic message on the stderr stream, and terminates
the program, using abort(), if expression is false (0).
The diagnostic message includes the expression, the name of the source file (the value
of __FILE__) and the line number of the failed assertion (the value of __LINE__).
No action is taken if expression is true (nonzero).
You typically use the assert() macro while developing a program, to identify program
logic errors. You should choose the expression so that it’s true when the program is
functioning as intended.
After the program has been debugged, you can use the special “no debug” identifier,
NDEBUG, to remove calls to assert() from the program when it’s recompiled. If you
use the -D option to qcc or a #define directive to define NDEBUG (with any value),
the C preprocessor ignores all assert() calls in the program source.
To remove the calls to assert(), you must define NDEBUG in the code before including
the <assert.h> header file (i.e. #include <assert.h>).
If you define NDEBUG, the preprocessor also ignores the expression you pass to
assert(). For example, if your code includes:
assert((fd = open("filename", O_RDWR)) != -1);
and you define NDEBUG, the preprocessor ignores the entire call to assert(), including
the call to open().
June 19, 2012
QNX Neutrino Functions and Macros
67
assert()
© 2012, QNX Software Systems Limited
Examples:
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
void process_string( char *string )
{
/* use assert to check argument */
assert( string != NULL );
assert( *string != ’\0’ );
/* rest of code follows here */
}
int main( void )
{
process_string( "hello" );
process_string( "" );
return EXIT_SUCCESS;
}
Classification:
ANSI, POSIX 1003.1
Safety
Cancellation point
No
Interrupt handler
No
Signal handler
No
Thread
Yes
Caveats:
assert() is a macro.
See also:
abort(), stderr
68
QNX Neutrino Functions and Macros
June 19, 2012
asyncmsg_channel_create()
© 2012, QNX Software Systems Limited
Create an asynchronous message channel
!
CAUTION: Asynchronous messaging is an experimental feature; for information
about the use of experimental software, see the Commercial Software License
Agreement (CSLA) or Partner Software License Agreement (PSLA) in the Licensing
area of our website, http://www.qnx.com/legal/licensing/.
Asynchronous messaging doesn’t work with Transparent Distributed Processing (i.e. it
doesn’t work across Qnet).
The prototypes for this function and the callback changed in QNX Neutrino 6.4.1 to
include the recvbuf_callback_handle and handle arguments respectively.
Synopsis:
#include <sys/neutrino.h>
#include <sys/asyncmsg.h>
int asyncmsg_channel_create (
unsigned flags,
mode_t mode,
size_t buffer_size,
unsigned max_num_buffer,
const struct sigevent *ev,
int (*recvbuf_callback) (
size_t bufsize,
unsigned num_bufs,
void *bufs[],
int flags,
void *handle ),
void *recvbuf_callback_handle );
Arguments:
flags
Flags that specify the attributes of the channel:
• _NTO_CHF_ASYNC_NONBLOCK — make asyncmsg_get()
nonblocking when no messages are available.
This function automatically sets _NTO_CHF_ASYNC.
mode
The permissions for the channel. For more information, see
“Access permissions” in the documentation for stat().
buffer_size
The size, in bytes, of each buffer used to store messages.
max_num_buffer
The maximum number of buffers to allocate, or 0 if you don’t
want the function to allocate any buffers.
ev
NULL, or a pointer to a sigevent structure that specifies an
event that you want to be delivered when a message becomes
available to be received on a previously empty queue.
June 19, 2012
QNX Neutrino Functions and Macros
69
asyncmsg_channel_create()
recvbuf_callback
© 2012, QNX Software Systems Limited
NULL, or a pointer to a callback function that the library can use
to allocate a buffer for an incoming message, or to free buffers
when the channel is destroyed. If the callback is NULL, the
library uses malloc() and free() instead. For more information,
see “Callback function,” below.
recvbuf_callback_handle
NULL, or a pointer to arbitrary data that you want to pass to the
callback function.
Library:
libasyncmsg
Use the -l asyncmsg option to qcc to link against this library.
Description:
The asyncmsg_channel_create() function creates an asynchronous message channel.
Callback function
If the recvbuf_callback argument isn’t NULL, the asynchronous-messaging library
calls this function when you call:
asyncmsg_get()
The callback is invoked once for each buffer being received, and
the flags argument is set to ASYNCMSG_RECVBUF_ALLOC. The
callback is expected to allocate space for the message, put a
pointer to the buffer in the bufs table, and then return 1 if you want
the library to receive another buffer, or 0 if you want it to stop.
asyncmsg_channel_destroy()
In this case, the callback is invoked one or more times to free the
outstanding receive buffers; the flags argument is set to
ASYNCMSG_RECVBUF_FREE, and the return value is ignored.
The arguments to the callback are as follows:
size_t bufsize
The buffer size for the message currently being received,
including the headers.
unsigned num_bufs
• When the callback is invoked because you called
asyncmsg_get(), this argument is 1 (the callback is called once
for each buffer received).
• When the callback is invoked because you called
asyncmsg_channel_destroy(), this argument is the number of
buffers to free.
70
QNX Neutrino Functions and Macros
June 19, 2012
asyncmsg_channel_create()
© 2012, QNX Software Systems Limited
void* bufs[]
A table of pointers to the receive buffers. The number of buffers is
given by num_bufs.
ASYNCMSG_RECVBUF_ALLOC when asyncmsg_get() invokes
the callback, and ASYNCMSG_RECVBUF_FREE when
asyncmsg_channel_destroy() invokes it.
int flags
NULL, or a pointer to arbitrary data (specified with the
recvbuf_callback_handle argument to
asyncmsg_channel_create()) that you want to pass to the callback
function.
handle
Returns:
The channel ID of the newly created channel, or -1 if an error has occurred (errno is
set).
Errors:
EAGAIN
All kernel channel objects are in use.
EINVAL
An attempt was made to attach to a synchronous message channel.
Classification:
QNX Neutrino
Safety
Cancellation point
No
Interrupt handler
No
Signal handler
No
Thread
Yes
See also:
asyncmsg_channel_destroy(), asyncmsg_connect_attach(),
asyncmsg_connect_attr(), asyncmsg_connect_detach(), asyncmsg_flush(),
asyncmsg_free(), asyncmsg_get(), asyncmsg_malloc(), asyncmsg_put(),
asyncmsg_putv(), ChannelCreate(), sigevent
Asynchronous Messaging technote
June 19, 2012
QNX Neutrino Functions and Macros
71
asyncmsg_channel_destroy()
© 2012, QNX Software Systems Limited
Destroy an asynchronous message channel
!
CAUTION: Asynchronous messaging is an experimental feature; for information
about the use of experimental software, see the Commercial Software License
Agreement (CSLA) or Partner Software License Agreement (PSLA) in the Licensing
area of our website, http://www.qnx.com/legal/licensing/.
Synopsis:
#include <sys/asyncmsg.h>
int asyncmsg_channel_destroy( int chid );
Arguments:
chid
The ID of the channel to destroy.
Library:
libasyncmsg
Use the -l asyncmsg option to qcc to link against this library.
Description:
The asyncmsg_channel_destroy() function destroys the asynchronous message
channel specified by chid. If you provided a callback function when you called
asyncmsg_channel_create(), asyncmsg_channel_destroy() invokes the callback to
free any outstanding receive buffers; otherwise, asyncmsg_channel_destroy() uses
free().
Returns:
EOK, or -1 if an error occurred (errno is set).
Errors:
EINVAL
The channel specified by chid doesn’t exist.
Classification:
QNX Neutrino
Safety
Cancellation point
No
Interrupt handler
No
Signal handler
No
continued. . .
72
QNX Neutrino Functions and Macros
June 19, 2012
asyncmsg_channel_destroy()
© 2012, QNX Software Systems Limited
Safety
Thread
Yes
See also:
asyncmsg_channel_create(), asyncmsg_connect_attach(), asyncmsg_connect_attr(),
asyncmsg_connect_detach(), asyncmsg_flush(), asyncmsg_free(), asyncmsg_get(),
asyncmsg_malloc(), asyncmsg_put(), asyncmsg_putv()
ChannelDestroy()
Asynchronous Messaging Technote
June 19, 2012
QNX Neutrino Functions and Macros
73
asyncmsg_connect_attach()
© 2012, QNX Software Systems Limited
Establish a connection to be used for asynchronous messages between a process and a channel
!
CAUTION: Asynchronous messaging is an experimental feature; for information
about the use of experimental software, see the Commercial Software License
Agreement (CSLA) or Partner Software License Agreement (PSLA) in the Licensing
area of our website, http://www.qnx.com/legal/licensing/.
Synopsis:
#include <sys/asyncmsg.h>
int asyncmsg_connect_attach (
uint32_t nd,
pid_t pid,
int chid,
unsigned index,
unsigned flags,
const struct _asyncmsg_connection_attr * attr);
Arguments:
nd
The node descriptor of the node on which the process that owns the channel
is running.
pid
The process ID of the owner of the channel.
chid
The channel ID, returned by asyncmsg_channel_create(), of the channel to
connect to the process.
index
The lowest acceptable connection ID.
flags
Flags that specify the type and attributes of the connection:
_NTO_COF_NOSHARE
The calling application wants to use its own buffer; otherwise, the
application gets the buffer from the asyncmsg_malloc() call, fills it in
and sends it by calling the asyncmsg_put() function.
_NTO_COF_NONBLOCK
Don’t block waiting if all the send headers are in use.
attr
A pointer to an _asyncmsg_connection_attr structure that specifies the
connection attributes.
Library:
libasyncmsg
Use the -l asyncmsg option to qcc to link against this library.
74
QNX Neutrino Functions and Macros
June 19, 2012
asyncmsg_connect_attach()
© 2012, QNX Software Systems Limited
Description:
Returns:
The asyncmsg_connect_attach() function establishes a connection between the calling
process and a channel identified by the arguments nd, pid and chid. The system returns
the first available connection ID starting at the value specified by the index argument.
A connection ID, or -1 if an error occurred (errno is set).
Errors:
EAGAIN
All kernel channel objects are in use.
ESRCH
The node indicated by nd, the process indicated by pid or the channel
indicated by chid does not exist.
Classification:
QNX Neutrino
Safety
Cancellation point
No
Interrupt handler
No
Signal handler
No
Thread
Yes
See also:
asyncmsg_channel_create(), asyncmsg_channel_destroy(),
asyncmsg_connect_attr(), asyncmsg_connect_detach(), asyncmsg_flush(),
asyncmsg_free(), asyncmsg_get(), asyncmsg_malloc(), asyncmsg_put(),
asyncmsg_putv()
ConnectAttach()
Asynchronous Messaging Technote
June 19, 2012
QNX Neutrino Functions and Macros
75
asyncmsg_connect_attr()
© 2012, QNX Software Systems Limited
Examine or change connection attributes for asynchronous messaging
!
CAUTION: Asynchronous messaging is an experimental feature; for information
about the use of experimental software, see the Commercial Software License
Agreement (CSLA) or Partner Software License Agreement (PSLA) in the Licensing
area of our website, http://www.qnx.com/legal/licensing/.
Synopsis:
#include <sys/asyncmsg.h>
int asyncmsg_connect_attr (
int coid,
struct _asyncmsg_connection_attr *old_attr,
const struct _asyncmsg_connection_attr *new_attr);
Arguments:
coid
The connection ID.
old_attr
NULL, or a pointer to a _asyncmsg_connection_attr structure
where the function can store the current attributes for the connection.
new_attr
NULL, or a pointer to a _asyncmsg_connection_attr structure that
specifies the attributes to set for the connection.
Library:
libasyncmsg
Use the -l asyncmsg option to qcc to link against this library.
Description:
You can use asyncmsg_connect_attr() to get or set the attributes to the connection
used for asynchronous messaging:
• If old_attr isn’t NULL, the function stores the current connection attributes in the
structure that it points to.
• If new_attr isn’t NULL, the function sets the connection attributes to the contents
of the buffer it points to.
Returns:
EOK, or -1 if an error occurred (errno is set).
Errors:
EINVAL
76
The connection specified by coid doesn’t exist.
QNX Neutrino Functions and Macros
June 19, 2012
asyncmsg_connect_attr()
© 2012, QNX Software Systems Limited
Classification:
QNX Neutrino
Safety
Cancellation point
No
Interrupt handler
No
Signal handler
No
Thread
Yes
See also:
asyncmsg_channel_create(), asyncmsg_channel_destroy(),
asyncmsg_connect_attach(), asyncmsg_connect_detach(),
_asyncmsg_connection_attr, asyncmsg_flush(), asyncmsg_free(),
asyncmsg_get(), asyncmsg_malloc(), asyncmsg_put(), asyncmsg_putv()
Asynchronous Messaging Technote
June 19, 2012
QNX Neutrino Functions and Macros
77
asyncmsg_connect_detach()
© 2012, QNX Software Systems Limited
Break a connection used for asynchronous messages between a process and a channel
!
CAUTION: Asynchronous messaging is an experimental feature; for information
about the use of experimental software, see the Commercial Software License
Agreement (CSLA) or Partner Software License Agreement (PSLA) in the Licensing
area of our website, http://www.qnx.com/legal/licensing/.
Synopsis:
#include <sys/asyncmsg.h>
int asyncmsg_connect_detach( int coid );
Arguments:
coid
The connection ID of the connection you want to break.
Library:
libasyncmsg
Use the -l asyncmsg option to qcc to link against this library.
Description:
The asyncmsg_connect_detach() function breaks the connection specified by the
connection ID coid argument. All the messages buffered on the sender side will be
discarded. If you want to ensure that all the messages sent have been delivered, call
asyncmsg_flush() before calling this function.
Returns:
EOK, or -1 if an error occurred (errno is set).
Errors:
EINVAL
The connection specified by coid doesn’t exist.
Classification:
QNX Neutrino
Safety
78
Cancellation point
No
Interrupt handler
No
Signal handler
No
Thread
Yes
QNX Neutrino Functions and Macros
June 19, 2012
© 2012, QNX Software Systems Limited
asyncmsg_connect_detach()
See also:
asyncmsg_channel_create(), asyncmsg_channel_destroy(),
asyncmsg_connect_attach(), asyncmsg_connect_attr(), asyncmsg_flush(),
asyncmsg_free(), asyncmsg_get(), asyncmsg_malloc(), asyncmsg_put(),
asyncmsg_putv()
ConnectDetach()
Asynchronous Messaging Technote
June 19, 2012
QNX Neutrino Functions and Macros
79
_asyncmsg_connection_attr
© 2012, QNX Software Systems Limited
Attributes for a connection used for asynchronous messages
!
CAUTION: Asynchronous messaging is an experimental feature; for information
about the use of experimental software, see the Commercial Software License
Agreement (CSLA) or Partner Software License Agreement (PSLA) in the Licensing
area of our website, http://www.qnx.com/legal/licensing/.
Synopsis:
#include <sys/asyncmsg.h>
struct _asyncmsg_connection_attr {
int (*call_back) (int err,
void* buf ,
unsigned handle);
size_t buffer_size;
unsigned max_num_buffer;
unsigned trigger_num_msg;
struct itimertrigger_timer;
};
Description:
The _asyncmsg_connection_attr structure describes connection attributes for
use with asynchronous messaging.
The _asyncmsg_connection_attr structure includes these members:
call_back
Callback function for notification. The arguments are:
• err — the error status of the package.
• buf — a pointer to the package buffer.
• handle — a handle associated with the callback function.
If call_back isn’t NULL, this function is called when an error
occurs during send (after asyncmsg_put() returns) with an
error number in err and the faulted buffer in buf . If you use
your own buffer, this function is also called when a buffer is
empty, with err set to EOK.
80
buffer_size
The message buffer size.
max_num_buffer
The maximum number of buffers allowed for this connection.
trigger_num_msg
Uses the number of the pending message as triggering criteria.
trigger_timer
Uses the time passed since the last kernel call as triggering
criteria.
QNX Neutrino Functions and Macros
June 19, 2012
© 2012, QNX Software Systems Limited
_asyncmsg_connection_attr
Classification:
QNX Neutrino
See also:
asyncmsg_connect_attach(), asyncmsg_connect_attr()
Asynchronous Messaging Technote
June 19, 2012
QNX Neutrino Functions and Macros
81
asyncmsg_flush()
© 2012, QNX Software Systems Limited
Flush the asynchronous messages sent through a connection
!
CAUTION: Asynchronous messaging is an experimental feature; for information
about the use of experimental software, see the Commercial Software License
Agreement (CSLA) or Partner Software License Agreement (PSLA) in the Licensing
area of our website, http://www.qnx.com/legal/licensing/.
Synopsis:
#include <sys/asyncmsg.h>
int asyncmsg_flush( int coid,
int mode );
Arguments:
coid
The connection ID of the connection you want to flush.
mode
0, or ASYNCMSG_FLUSH_NONBLOCK if you don’t want the function to
block.
Library:
libasyncmsg
Use the -l asyncmsg option to qcc to link against this library.
Description:
The asyncmsg_flush() function flushes the messages sent through the connection
specified by the connection ID coid argument.
If you don’t specify a mode of ASYNCMSG_FLUSH_NONBLOCK, the function
doesn’t return until all the existing messages are delivered to the receive side.
Returns:
EOK, or -1 if an error occurred (errno is set).
Errors:
EBADF
The connection specified by coid doesn’t exist.
Classification:
QNX Neutrino
82
QNX Neutrino Functions and Macros
June 19, 2012
asyncmsg_flush()
© 2012, QNX Software Systems Limited
Safety
Cancellation point
No
Interrupt handler
No
Signal handler
No
Thread
Yes
See also:
asyncmsg_channel_create(), asyncmsg_channel_destroy(),
asyncmsg_connect_attach(), asyncmsg_connect_attr(), asyncmsg_connect_detach(),
asyncmsg_free(), asyncmsg_get(), asyncmsg_malloc(), asyncmsg_put(),
asyncmsg_putv()
Asynchronous Messaging Technote
June 19, 2012
QNX Neutrino Functions and Macros
83
asyncmsg_free()
© 2012, QNX Software Systems Limited
Free a message buffer used for asynchronous messaging
!
CAUTION: Asynchronous messaging is an experimental feature; for information
about the use of experimental software, see the Commercial Software License
Agreement (CSLA) or Partner Software License Agreement (PSLA) in the Licensing
area of our website, http://www.qnx.com/legal/licensing/.
Synopsis:
#include <sys/asyncmsg.h>
void asyncmsg_free( void *buf );
Arguments:
buf
A pointer to the buffer to free.
Library:
libasyncmsg
Use the -l asyncmsg option to qcc to link against this library.
Description:
The asyncmsg_free() function frees a message buffer that comes from the
asyncmsg_get() call.
Classification:
QNX Neutrino
Safety
Cancellation point
No
Interrupt handler
No
Signal handler
No
Thread
Yes
See also:
asyncmsg_channel_create(), asyncmsg_channel_destroy(),
asyncmsg_connect_attach(), asyncmsg_connect_attr(), asyncmsg_connect_detach(),
asyncmsg_flush(), asyncmsg_get(), asyncmsg_malloc(), asyncmsg_put(),
asyncmsg_putv()
Asynchronous Messaging Technote
84
QNX Neutrino Functions and Macros
June 19, 2012
asyncmsg_get()
© 2012, QNX Software Systems Limited
Receive an asynchronous message
!
CAUTION:
Asynchronous messaging is an experimental feature; for information about the use of
experimental software, see the Commercial Software License Agreement (CSLA) or
Partner Software License Agreement (PSLA) in the Licensing area of our website,
http://www.qnx.com/legal/licensing/.
Synopsis:
#include <sys/asyncmsg.h>
struct _asyncmsg_get_header *asyncmsg_get( int chid );
Arguments:
chid
The channel ID.
Library:
libasyncmsg
Use the -l asyncmsg option to qcc to link against this library.
Description:
The asyncmsg_get() function receives up to five asynchronous messages from the
channel identified by the chid argument. In order to receive more messages, you must
call this function in a loop until the function returns NULL and sets errno to EAGAIN
to signify that you’ve drained the queue of messages.
Threads that receive asynchronous messages don’t inherit the sender’s priority.
If you provided a callback function when you called asyncmsg_channel_create(),
asyncmsg_get() invokes the callback to allocate space for the message; otherwise
asyncmsg_get() invokes malloc().
_asyncmsg_get_header structure
The asyncmsg_get() function stores each asynchronous message in an
_asyncmsg_get_header structure:
struct _asyncmsg_get_header {
struct _msg_info info;
int err;
iov_t *iov;
int parts;
struct _asyncmsg_get_header *next;
unsigned reserve[2];
};
The members include:
June 19, 2012
QNX Neutrino Functions and Macros
85
asyncmsg_get()
© 2012, QNX Software Systems Limited
info
err
A _msg_info structure, just as for synchronous messages.
The error status of this message.
iov
A pointer to the IOV (Input/Output Vector) for the message body.
parts
The size of the iov array.
next
A pointer to the next message returned by asyncmsg_get().
Returns:
A pointer to a linked list of _asyncmsg_get_header structures containing the
messages received, or NULL if an error occurred (errno is set).
You should free this list of headers when you’re finished with them.
Errors:
EBADF
The channel specified by chid doesn’t exist.
EFAULT
A fault occurred when the kernel tried to access the buffers provided.
EMSGSIZE
The buffer provided isn’t big enough to hold the received message.
EAGAIN
No message is available at this time.
Classification:
QNX Neutrino
Safety
Cancellation point
No
Interrupt handler
No
Signal handler
No
Thread
Yes
See also:
asyncmsg_channel_create(), asyncmsg_channel_destroy(),
asyncmsg_connect_attach(), asyncmsg_connect_attr(), asyncmsg_connect_detach(),
asyncmsg_flush(), asyncmsg_free(), asyncmsg_malloc(), asyncmsg_put(),
asyncmsg_putv()
Asynchronous Messaging technote
86
QNX Neutrino Functions and Macros
June 19, 2012
asyncmsg_malloc()
© 2012, QNX Software Systems Limited
Allocate a message buffer for sending an asynchronous message
!
CAUTION:
Asynchronous messaging is an experimental feature; for information about the use of
experimental software, see the Commercial Software License Agreement (CSLA) or
Partner Software License Agreement (PSLA) in the Licensing area of our website,
http://www.qnx.com/legal/licensing/.
Synopsis:
#include <sys/asyncmsg.h>
void *asyncmsg_malloc( size_t size );
Arguments:
size
The size of the message.
Library:
libasyncmsg
Use the -l asyncmsg option to qcc to link against this library.
Description:
The asyncmsg_malloc() function allocates a message buffer for sending.
Because the malloc() implementation uses signed, 32-bit integers to represent the size
internally, you can’t allocate more than 2 GB in a single allocation. If the size is
greater than 2 GB, asyncmsg_malloc() indicates an error of ENOMEM.
Returns:
EOK, or -1 if an error occurred (errno is set).
Errors:
There’s not enough memory.
ENOMEM
Classification:
QNX Neutrino
Safety
Cancellation point
No
continued. . .
June 19, 2012
QNX Neutrino Functions and Macros
87
asyncmsg_malloc()
© 2012, QNX Software Systems Limited
Safety
Interrupt handler
No
Signal handler
No
Thread
Yes
See also:
asyncmsg_channel_create(), asyncmsg_channel_destroy(),
asyncmsg_connect_attach(), asyncmsg_connect_attr(), asyncmsg_connect_detach(),
asyncmsg_flush(), asyncmsg_free(), asyncmsg_get(), asyncmsg_put(),
asyncmsg_putv()
Asynchronous Messaging Technote
88
QNX Neutrino Functions and Macros
June 19, 2012
© 2012, QNX Software Systems Limited
asyncmsg_put(), asyncmsg_putv()
Send an asynchronous message to a connection
!
CAUTION: Asynchronous messaging is an experimental feature; for information
about the use of experimental software, see the Commercial Software License
Agreement (CSLA) or Partner Software License Agreement (PSLA) in the Licensing
area of our website, http://www.qnx.com/legal/licensing/.
Synopsis:
#include <sys/asyncmsg.h>
int asyncmsg_put( int coid,
const void *buff ,
size_t size,
unsigned handle),
int (*call_back) (
int err,
void* buf ,
unsigned handle ));
int asyncmsg_putv( int coid,
const iov_t* iov,
int parts,
unsigned handle,
int (*call_back) (
int err,
void* buf ,
unsigned handle ));
Arguments:
coid
The ID of the connection to send the message to.
buff
(asyncmsg_put() only) A pointer to the buffer that holds the message.
size
(asyncmsg_put() only) The size of the message.
iov
(asyncmsg_putv() only) A pointer to an array of IOV buffers that hold
message.
parts
(asyncmsg_putv() only) The number of elements in the IOV array.
handle
A user-defined handle that’s passed to the call_back function to allow
for quick identification of the message’s package.
call_back
NULL, or a function to call when a message is processed. If this
argument is NULL, the call_back specified in the
_asyncmsg_connection_attr passed to
asyncmsg_connect_attach() is called.
June 19, 2012
QNX Neutrino Functions and Macros
89
asyncmsg_put(), asyncmsg_putv()
© 2012, QNX Software Systems Limited
Library:
libasyncmsg
Use the -l asyncmsg option to qcc to link against this library.
Description:
The asyncmsg_put() and asyncmsg_putv() functions send an asynchronous message to
the connection identified by the coid argument:
• For asyncmsg_put(), buff points to the message, and size specifies its length.
• For asyncmsg_putv(), the message is stored in an I/O vector pointed to by iov, and
parts specifies the number of entries in the array.
You can use the handle, which is passed to the call_back function, to help you identify
the message.
Returns:
EOK, or -1 if an error occurred (errno is set).
Errors:
EBADF
The connection specified by coid doesn’t exist.
EFAULT
A fault occurred when the kernel tried to access the buffers provided.
EAGAIN
The send queue is full.
Classification:
QNX Neutrino
Safety
Cancellation point
No
Interrupt handler
No
Signal handler
No
Thread
Yes
See also:
asyncmsg_channel_create(), asyncmsg_channel_destroy(),
asyncmsg_connect_attach(), asyncmsg_connect_attr(),
_asyncmsg_connection_attr, asyncmsg_connect_detach(), asyncmsg_flush(),
asyncmsg_free(), asyncmsg_get(), asyncmsg_malloc()
Asynchronous Messaging technote
90
QNX Neutrino Functions and Macros
June 19, 2012
atan(), atanf(), atanl()
© 2012, QNX Software Systems Limited
Compute the arctangent of an angle
Synopsis:
#include <math.h>
double atan( double x );
float atanf( float x );
long double atanl( long double x );
Arguments:
x
The tangent for which you want to find the angle.
Library:
libm
Use the -l m option to qcc to link against this library.
Description:
These functions compute the arctangent (specified in radians) of x.
Returns:
The arctangent, in the range (-π/2, π/2). For finite values of |x| > 1, these functions
return NaN. The return value for +/-Inf is NaN.
If an error occurs, these functions return 0, but this is also a valid mathematical result.
If you want to check for errors, set errno to 0, call the function, and then check errno
again. These functions don’t change errno if no errors occurred.
Examples:
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
int main( void )
{
printf( "%f\n", atan(.5) );
return EXIT_SUCCESS;
}
produces the output:
0.463648
June 19, 2012
QNX Neutrino Functions and Macros
91
atan(), atanf(), atanl()
© 2012, QNX Software Systems Limited
Classification:
ANSI, POSIX 1003.1
Safety
Cancellation point
No
Interrupt handler
No
Signal handler
No
Thread
Yes
See also:
acos(), asin(), atan2()
92
QNX Neutrino Functions and Macros
June 19, 2012
atan2(), atan2f()
© 2012, QNX Software Systems Limited
Compute the arctangent, determining the quadrant
Synopsis:
#include <math.h>
double atan2( double y,
double x );
float atan2f( float y,
float x );
Arguments:
x, y
The value (y/x) for which you want to find the angle.
Library:
libm
Use the -l m option to qcc to link against this library.
Description:
These functions compute the value of the arctangent (specified in radians) of y/x, using
the signs of both arguments to determine the quadrant of the return value. A domain
error occurs if both arguments are zero.
Returns:
The arctangent of y/x, in the range (-π, π).
If an error occurs, these functions return 0, but this is also a valid mathematical result.
If you want to check for errors, set errno to 0, call the function, and then check errno
again. These functions don’t change errno if no errors occurred.
Examples:
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
int main( void )
{
printf( "%f\n", atan2( .5, 1. ) );
return EXIT_SUCCESS;
}
produces the output:
0.463648
June 19, 2012
QNX Neutrino Functions and Macros
93
atan2(), atan2f()
© 2012, QNX Software Systems Limited
Classification:
ANSI, POSIX 1003.1
Safety
Cancellation point
No
Interrupt handler
No
Signal handler
No
Thread
Yes
See also:
acos(), asin(), atan(), errno
94
QNX Neutrino Functions and Macros
June 19, 2012
atanh(), atanhf(), atanhl()
© 2012, QNX Software Systems Limited
Compute an inverse hyperbolic tangent
Synopsis:
#include <math.h>
double atanh( double x );
float atanhf( float x );
long double atanhl( long double x );
Arguments:
x
The value for which you want to compute the inverse hyperbolic tangent.
Library:
libm
Use the -l m option to qcc to link against this library.
Description:
These functions compute the inverse hyperbolic tangent (specified in radians) of x.
Returns:
The inverse hyperbolic tangent of x.
Examples:
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
int main( void )
{
printf( "%f\n", atanh( 0.5 ) );
return EXIT_SUCCESS;
}
produces the output:
0.549306
Classification:
ANSI, POSIX 1003.1
Safety
Cancellation point
No
continued. . .
June 19, 2012
QNX Neutrino Functions and Macros
95
atanh(), atanhf(), atanhl()
© 2012, QNX Software Systems Limited
Safety
Interrupt handler
No
Signal handler
No
Thread
Yes
See also:
acosh(), asinh(), errno, tanh()
96
QNX Neutrino Functions and Macros
June 19, 2012
atexit()
© 2012, QNX Software Systems Limited
Register functions to be called during normal program termination
Synopsis:
#include <stdlib.h>
int atexit( register void (*func)(void) );
Arguments:
func
A pointer to the function you want to be called when the program terminates
normally. This function has no arguments and doesn’t return a value; its
prototype should be:
void func( void );
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
The atexit() function registers a function to be called when the program terminates
normally. If you register more than one function with atexit(), they’re executed in a
“last-in, first-out” order. Normal termination occurs either by a call to exit() or a return
from main().
You can register a total of 32 functions with atexit().
The functions registered with atexit() aren’t called when the program terminates with a
call to _exit().
Returns:
0 for success, or nonzero if an error occurs.
Examples:
#include <stdio.h>
#include <stdlib.h>
void func1( void )
{
printf( "last.\n" );
}
void func2( void )
{
printf( "this " );
}
June 19, 2012
QNX Neutrino Functions and Macros
97
atexit()
© 2012, QNX Software Systems Limited
void func3( void )
{
printf( "Do " );
}
int main( void )
{
atexit( func1 );
atexit( func2 );
atexit( func3 );
printf( "Do this first.\n" );
return EXIT_SUCCESS;
}
produces the output:
Do this first.
Do this last.
Classification:
ANSI, POSIX 1003.1
Safety
Cancellation point
No
Interrupt handler
No
Signal handler
No
Thread
Yes
See also:
abort(), _exit(), exit()
98
QNX Neutrino Functions and Macros
June 19, 2012
atof()
© 2012, QNX Software Systems Limited
Convert a string into a double
Synopsis:
#include <stdlib.h>
double atof( const char* ptr );
Arguments:
ptr
A pointer to the string to parse.
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
The atof() function converts the string pointed to by ptr to a double. Calling it is
equivalent to calling strtod() like this:
strtod( ptr, (char**)NULL )
Returns:
The converted double, or 0.0 if an error occurs.
Errors:
If an error occurs, errno is set to ERANGE.
Examples:
#include <stdlib.h>
#include <stdio.h>
int main( void )
{
double x;
x = atof( "3.1415926" );
printf( "x = %f\n", x );
return EXIT_SUCCESS;
}
Classification:
ANSI, POSIX 1003.1
June 19, 2012
QNX Neutrino Functions and Macros
99
atof()
© 2012, QNX Software Systems Limited
Safety
Cancellation point
No
Interrupt handler
No
Signal handler
No
Thread
Yes
See also:
errno, sscanf(), strtod()
100
QNX Neutrino Functions and Macros
June 19, 2012
atoh()
© 2012, QNX Software Systems Limited
Convert a string containing a hexadecimal number into an unsigned number
Synopsis:
#include <stdlib.h>
unsigned atoh( const char* ptr );
Arguments:
ptr
A pointer to the string to parse.
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
The atoh() function converts the string pointed to by ptr to unsigned representation,
assuming the string contains a hexadecimal (base 16) number.
Returns:
The converted value.
Examples:
#include <stdlib.h>
#include <stdio.h>
int main( void )
{
unsigned x;
x = atoh( "F1A6" );
printf( "number is %x\n", x );
return EXIT_SUCCESS;
}
Classification:
QNX 4
Safety
June 19, 2012
Cancellation point
No
Interrupt handler
Yes
Signal handler
Yes
Thread
Yes
QNX Neutrino Functions and Macros
101
atoh()
© 2012, QNX Software Systems Limited
See also:
sscanf()
102
QNX Neutrino Functions and Macros
June 19, 2012
atoi()
© 2012, QNX Software Systems Limited
Convert a string into an integer
Synopsis:
#include <stdlib.h>
int atoi( const char* ptr );
Arguments:
ptr
A pointer to the string to parse.
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
The atoi() function converts the string pointed to by ptr to an int.
Returns:
The converted integer.
Examples:
#include <stdlib.h>
#include <stdio.h>
int main( void )
{
int x;
x = atoi( "-289" );
printf( "x = %d\n", x );
return EXIT_SUCCESS;
}
produces the output:
x = -289
Classification:
ANSI, POSIX 1003.1
Safety
June 19, 2012
Cancellation point
No
Interrupt handler
Yes
Signal handler
Yes
Thread
Yes
QNX Neutrino Functions and Macros
103
atoi()
© 2012, QNX Software Systems Limited
See also:
atol(), itoa(), ltoa(), sscanf(), strtol(), strtoul(), ultoa(), utoa()
104
QNX Neutrino Functions and Macros
June 19, 2012
atol(), atoll()
© 2012, QNX Software Systems Limited
Convert a string into a long integer
Synopsis:
#include <stdlib.h>
long atol( const char* ptr );
long long atoll( const char* ptr );
Arguments:
ptr
A pointer to the string to parse.
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
The atol() function converts the string pointed to by ptr to a long integer; atoll()
converts the string pointed to by nptr to a long long integer.
Returns:
atol()
A long integer.
atoll()
A long long integer.
Examples:
#include <stdlib.h>
#include <stdio.h>
int main( void )
{
long x;
x = atol( "-289" );
printf( "x = %d\n", x );
return EXIT_SUCCESS;
}
produces the output:
x = -289
June 19, 2012
QNX Neutrino Functions and Macros
105
atol(), atoll()
© 2012, QNX Software Systems Limited
Classification:
ANSI, POSIX 1003.1
Safety
Cancellation point
No
Interrupt handler
Yes
Signal handler
Yes
Thread
Yes
See also:
atoi(), itoa(), ltoa(), sscanf(), strtol(), strtoul(), ultoa(), utoa()
106
QNX Neutrino Functions and Macros
June 19, 2012
atomic_add()
© 2012, QNX Software Systems Limited
Safely add to a variable
Synopsis:
#include <atomic.h>
void atomic_add( volatile unsigned * loc,
unsigned incr );
Arguments:
loc
A pointer to the value that you want to add to.
incr
The number that you want to add.
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
The atomic_add() function is a thread-safe way of doing an (*loc) += incr
operation, even in a symmetric-multiprocessing system.
The atomic_*() functions are guaranteed to complete without being preempted by
another thread. When modifying a variable shared between a thread and an interrupt,
you must either disable interrupts or use the atomic_*() functions.
The atomic_*() functions are useful for modifying variables that are referenced by
more than one thread (that aren’t necessarily in the same process) without having to
use a mutex.
!
CAUTION: Perform atomic operations only on objects that were allocated in normal
memory mappings. On certain processors (e.g. some PPC ones), atomic operations
will cause a fault if the object is allocated in uncached memory.
Examples:
To safely increment a counter shared between multiple threads:
#include <atomic.h>
...
volatile unsigned count;
...
atomic_add( &count, 1 );
June 19, 2012
QNX Neutrino Functions and Macros
107
atomic_add()
© 2012, QNX Software Systems Limited
Classification:
QNX Neutrino
Safety
Cancellation point
No
Interrupt handler
Yes
Signal handler
Yes
Thread
Yes
See also:
atomic_add_value(), atomic_clr(), atomic_clr_value(), atomic_set(),
atomic_set_value(), atomic_sub(), atomic_sub_value(), atomic_toggle(),
atomic_toggle_value()
108
QNX Neutrino Functions and Macros
June 19, 2012
atomic_add_value()
© 2012, QNX Software Systems Limited
Safely add to a variable, returning the previous value
Synopsis:
#include <atomic.h>
unsigned atomic_add_value( volatile unsigned * loc,
unsigned incr );
Arguments:
loc
A pointer to the value that you want to add to.
incr
The number that you want to add.
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
The atomic_add_value() function is a thread-safe way of doing an (*loc) += incr
operation, even in a symmetric-multiprocessing system.
The atomic_add_value() function may be slower than atomic_add().
The atomic_*() functions are guaranteed to complete without being preempted by
another thread. When modifying a variable shared between a thread and an interrupt,
you must either disable interrupts or use the atomic_*() functions.
The atomic_*() functions are also useful for modifying variables that are referenced
by more than one thread (that aren’t necessarily in the same process) without having to
use a mutex.
!
CAUTION: Perform atomic operations only on objects that were allocated in normal
memory mappings. On certain processors (e.g. some PPC ones), atomic operations
will cause a fault if the object is allocated in uncached memory.
Returns:
The previous value of loc’s contents.
Examples:
To safely increment a counter shared between multiple threads:
#include <atomic.h>
...
June 19, 2012
QNX Neutrino Functions and Macros
109
atomic_add_value()
© 2012, QNX Software Systems Limited
volatile unsigned count;
unsigned previous;
...
previous = atomic_add_value( &count, 1 );
Classification:
QNX Neutrino
Safety
Cancellation point
No
Interrupt handler
Yes
Signal handler
Yes
Thread
Yes
See also:
atomic_add(), atomic_clr(), atomic_clr_value(), atomic_set(), atomic_set_value(),
atomic_sub(), atomic_sub_value(), atomic_toggle(), atomic_toggle_value()
110
QNX Neutrino Functions and Macros
June 19, 2012
atomic_clr()
© 2012, QNX Software Systems Limited
Safely clear a variable
Synopsis:
#include <atomic.h>
void atomic_clr( volatile unsigned * loc,
unsigned bits );
Arguments:
loc
A pointer to the value that you want to clear bits in.
bits
The bits that you want to clear.
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
The atomic_clr() function is a thread-safe way of doing an (*loc) &= ˜bits
operation.
The atomic_*() functions are guaranteed to complete without being preempted by
another thread, even in a symmetric-multiprocessing system. When modifying a
variable shared between a thread and an interrupt, you must either disable interrupts or
use the atomic_*() functions.
The atomic_*() functions are also useful for modifying variables that are referenced
by more than one thread (that aren’t necessarily in the same process) without having to
use a mutex.
!
CAUTION: Perform atomic operations only on objects that were allocated in normal
memory mappings. On certain processors (e.g. some PPC ones), atomic operations
will cause a fault if the object is allocated in uncached memory.
Examples:
To safely clear the 0x10101010 bits in a flag:
#include <atomic.h>
...
volatile unsigned flags;
...
atomic_clr( &flags, 0x10101010 );
June 19, 2012
QNX Neutrino Functions and Macros
111
atomic_clr()
© 2012, QNX Software Systems Limited
Classification:
QNX Neutrino
Safety
Cancellation point
No
Interrupt handler
Yes
Signal handler
Yes
Thread
Yes
See also:
atomic_add(), atomic_add_value(), atomic_set(), atomic_set_value(), atomic_sub(),
atomic_sub_value(), atomic_toggle(), atomic_toggle_value()
112
QNX Neutrino Functions and Macros
June 19, 2012
atomic_clr_value()
© 2012, QNX Software Systems Limited
Safely clear a variable, returning the previous value
Synopsis:
#include <atomic.h>
unsigned atomic_clr_value( volatile unsigned * loc,
unsigned bits );
Arguments:
loc
A pointer to the value that you want to clear bits in.
bits
The bits that you want to clear.
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
The atomic_clr_value() function is a thread-safe way of doing an (*loc) &= ˜bits
operation.
The atomic_clr_value() function may be slower than atomic_clr().
The atomic_*() functions are guaranteed to complete without being preempted by
another thread, even in a symmetric-multiprocessing system. When modifying a
variable shared between a thread and an interrupt, you must either disable interrupts or
use the atomic_*() functions.
The atomic_*() functions are also useful for modifying variables that are referenced
by more than one thread (that aren’t necessarily in the same process) without having to
use a mutex.
!
CAUTION: Perform atomic operations only on objects that were allocated in normal
memory mappings. On certain processors (e.g. some PPC ones), atomic operations
will cause a fault if the object is allocated in uncached memory.
Returns:
The previous value of loc’s contents.
Examples:
To safely clear the 0x10101010 bits in a flag:
#include <atomic.h>
...
June 19, 2012
QNX Neutrino Functions and Macros
113
atomic_clr_value()
© 2012, QNX Software Systems Limited
volatile unsigned flags;
unsigned previous;
...
previous = atomic_clr_value( &flags, 0x10101010 );
Classification:
QNX Neutrino
Safety
Cancellation point
No
Interrupt handler
Yes
Signal handler
Yes
Thread
Yes
See also:
atomic_add(), atomic_add_value(), atomic_clr(), atomic_set(), atomic_set_value(),
atomic_sub(), atomic_sub_value(), atomic_toggle(), atomic_toggle_value()
114
QNX Neutrino Functions and Macros
June 19, 2012
atomic_set()
© 2012, QNX Software Systems Limited
Safely set bits in a variable
Synopsis:
#include <atomic.h>
void atomic_set( volatile unsigned * loc,
unsigned bits );
Arguments:
loc
A pointer to the location whose bits you want to set.
bits
The bits that you want to set.
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
The atomic_set() function is a thread-safe way of doing an (*loc) |= bits
operation.
The atomic_*() functions are guaranteed to complete without being preempted by
another thread, even in a symmetric-multiprocessing system. When modifying a
variable shared between a thread and an interrupt, you must either disable interrupts or
use the atomic_*() functions.
The atomic_*() functions are also useful for modifying variables that are referenced
by more than one thread (that aren’t necessarily in the same process) without having to
use a mutex.
!
CAUTION: Perform atomic operations only on objects that were allocated in normal
memory mappings. On certain processors (e.g. some PPC ones), atomic operations
will cause a fault if the object is allocated in uncached memory.
Examples:
To safely set the 1 bit in a flag:
#include <atomic.h>
...
volatile unsigned flags;
...
atomic_set( &flags, 0x01 );
June 19, 2012
QNX Neutrino Functions and Macros
115
atomic_set()
© 2012, QNX Software Systems Limited
Classification:
QNX Neutrino
Safety
Cancellation point
No
Interrupt handler
Yes
Signal handler
Yes
Thread
Yes
See also:
atomic_add(), atomic_add_value(), atomic_clr(), atomic_clr_value(),
atomic_set_value(), atomic_sub(), atomic_sub_value(), atomic_toggle(),
atomic_toggle_value()
116
QNX Neutrino Functions and Macros
June 19, 2012
atomic_set_value()
© 2012, QNX Software Systems Limited
Safely set bits in a variable, returning the previous value
Synopsis:
#include <atomic.h>
unsigned atomic_set_value( volatile unsigned * loc,
unsigned bits );
Arguments:
loc
A pointer to the location whose bits you want to set.
bits
The bits that you want to set.
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
The atomic_set_value() function is a thread-safe way of doing an (*loc) |= bits
operation.
The atomic_set_value() function may be slower than atomic_set().
The atomic_*() functions are guaranteed to complete without being preempted by
another thread, even in a symmetric-multiprocessing system. When modifying a
variable shared between a thread and an interrupt, you must either disable interrupts or
use the atomic_*() functions.
The atomic_*() functions are also useful for modifying variables that are referenced
by more than one thread (that aren’t necessarily in the same process) without having to
use a mutex.
!
CAUTION: Perform atomic operations only on objects that were allocated in normal
memory mappings. On certain processors (e.g. some PPC ones), atomic operations
will cause a fault if the object is allocated in uncached memory.
Returns:
The previous value of loc’s contents.
Examples:
To safely set the 1 bit in a flag:
#include <atomic.h>
...
June 19, 2012
QNX Neutrino Functions and Macros
117
atomic_set_value()
© 2012, QNX Software Systems Limited
volatile unsigned flags;
unsigned previous;
...
previous = atomic_set_value( &flags, 0x01 );
Classification:
QNX Neutrino
Safety
Cancellation point
No
Interrupt handler
Yes
Signal handler
Yes
Thread
Yes
See also:
atomic_add(), atomic_add_value(), atomic_clr(), atomic_clr_value(), atomic_set(),
atomic_sub(), atomic_sub_value(), atomic_toggle(), atomic_toggle_value()
118
QNX Neutrino Functions and Macros
June 19, 2012
atomic_sub()
© 2012, QNX Software Systems Limited
Safely subtract from a variable
Synopsis:
#include <atomic.h>
void atomic_sub( volatile unsigned * loc,
unsigned decr );
Arguments:
loc
A pointer to the value that you want to subtract from.
decr
The number that you want to subtract.
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
The atomic_sub() function is a thread-safe way of doing a (*loc) -= decr
operation, even in a symmetric-multiprocessing system.
The atomic_*() functions are guaranteed to complete without being preempted by
another thread. When modifying a variable shared between a thread and an interrupt,
you must either disable interrupts or use the atomic_*() functions.
The atomic_*() functions are also useful for modifying variables that are referenced
by more than one thread (that aren’t necessarily in the same process) without having to
use a mutex.
!
CAUTION: Perform atomic operations only on objects that were allocated in normal
memory mappings. On certain processors (e.g. some PPC ones), atomic operations
will cause a fault if the object is allocated in uncached memory.
Examples:
Safely subtract 1 from a counter:
#include <atomic.h>
...
volatile unsigned count;
...
atomic_sub( &count, 1 );
June 19, 2012
QNX Neutrino Functions and Macros
119
atomic_sub()
© 2012, QNX Software Systems Limited
Classification:
QNX Neutrino
Safety
Cancellation point
No
Interrupt handler
Yes
Signal handler
Yes
Thread
Yes
See also:
atomic_add(), atomic_add_value(), atomic_clr(), atomic_clr_value(), atomic_set(),
atomic_set_value(), atomic_sub_value(), atomic_toggle(), atomic_toggle_value()
120
QNX Neutrino Functions and Macros
June 19, 2012
atomic_sub_value()
© 2012, QNX Software Systems Limited
Safely subtract from a variable, returning the previous value
Synopsis:
#include <atomic.h>
unsigned atomic_sub_value( volatile unsigned * loc,
unsigned decr );
Arguments:
loc
A pointer to the value that you want to subtract from.
decr
The number that you want to subtract.
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
The atomic_sub_value() function is a thread-safe way of doing a (*loc) -= decr
operation, even in a symmetric-multiprocessing system.
The atomic_sub_value() function may be slower than atomic_sub().
The atomic_*() functions are guaranteed to complete without being preempted by
another thread. When modifying a variable shared between a thread and an interrupt,
you must either disable interrupts or use the atomic_*() functions.
The atomic_*() functions are also useful for modifying variables that are referenced
by more than one thread (that aren’t necessarily in the same process) without having to
use a mutex.
!
CAUTION: Perform atomic operations only on objects that were allocated in normal
memory mappings. On certain processors (e.g. some PPC ones), atomic operations
will cause a fault if the object is allocated in uncached memory.
Returns:
The previous value of loc’s contents.
Examples:
Safely subtract 1 from a counter:
#include <atomic.h>
...
June 19, 2012
QNX Neutrino Functions and Macros
121
atomic_sub_value()
© 2012, QNX Software Systems Limited
volatile unsigned count;
unsigned previous;
...
previous = atomic_sub_value( &count, 1 );
Classification:
QNX Neutrino
Safety
Cancellation point
No
Interrupt handler
Yes
Signal handler
Yes
Thread
Yes
See also:
atomic_add(), atomic_add_value(), atomic_clr(), atomic_clr_value(), atomic_set(),
atomic_set_value(), atomic_sub(), atomic_toggle(), atomic_toggle_value()
122
QNX Neutrino Functions and Macros
June 19, 2012
atomic_toggle()
© 2012, QNX Software Systems Limited
Safely toggle a variable
Synopsis:
#include <atomic.h>
void atomic_toggle( volatile unsigned * loc,
unsigned bits );
Arguments:
loc
A pointer to the location whose bits you want to toggle.
bits
The bits that you want to change.
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
The atomic_toggle() function is a thread-safe way of doing an (*loc) ˆ= bits
operation.
The atomic_*() functions are guaranteed to complete without being preempted by
another thread, even in a symmetric-multiprocessing system. When modifying a
variable shared between a thread and an interrupt, you must either disable interrupts or
use the atomic_*() functions.
The atomic_*() functions are also useful for modifying variables that are referenced
by more than one thread (that aren’t necessarily in the same process) without having to
use a mutex.
!
CAUTION: Perform atomic operations only on objects that were allocated in normal
memory mappings. On certain processors (e.g. some PPC ones), atomic operations
will cause a fault if the object is allocated in uncached memory.
Examples:
To safely toggle the 0xdeadbeef bits in a flag:
#include <atomic.h>
...
volatile unsigned flags;
...
atomic_toggle( &flags, 0xdeadbeef );
June 19, 2012
QNX Neutrino Functions and Macros
123
atomic_toggle()
© 2012, QNX Software Systems Limited
Classification:
QNX Neutrino
Safety
Cancellation point
No
Interrupt handler
Yes
Signal handler
Yes
Thread
Yes
See also:
atomic_add(), atomic_add_value(), atomic_clr(), atomic_clr_value(), atomic_set(),
atomic_set_value(), atomic_sub(), atomic_sub_value(), atomic_toggle_value()
124
QNX Neutrino Functions and Macros
June 19, 2012
atomic_toggle_value()
© 2012, QNX Software Systems Limited
Safely toggle a variable, returning the previous value
Synopsis:
#include <atomic.h>
unsigned atomic_toggle_value(
volatile unsigned * loc,
unsigned bits );
Arguments:
loc
A pointer to the location whose bits you want to toggle.
bits
The bits that you want to change.
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
The atomic_toggle_value() function is a thread-safe way of doing an
(*loc) ˆ= bits operation.
The atomic_toggle_value() function may be slower than atomic_toggle().
The atomic_*() functions are guaranteed to complete without being preempted by
another thread, even in a symmetric-multiprocessing system. When modifying a
variable shared between a thread and an interrupt, you must either disable interrupts or
use the atomic_*() functions.
The atomic_*() functions are also useful for modifying variables that are referenced
by more than one thread (that aren’t necessarily in the same process) without having to
use a mutex.
!
CAUTION: Perform atomic operations only on objects that were allocated in normal
memory mappings. On certain processors (e.g. some PPC ones), atomic operations
will cause a fault if the object is allocated in uncached memory.
Returns:
The previous value of loc’s contents.
Examples:
To safely toggle the 0xdeadbeef bits in a flag:
June 19, 2012
QNX Neutrino Functions and Macros
125
atomic_toggle_value()
© 2012, QNX Software Systems Limited
#include <atomic.h>
...
volatile unsigned flags;
unsigned previous;
...
previous = atomic_toggle_value( &flags, 0xdeadbeef );
Classification:
QNX Neutrino
Safety
Cancellation point
No
Interrupt handler
Yes
Signal handler
Yes
Thread
Yes
See also:
atomic_add(), atomic_add_value(), atomic_clr(), atomic_clr_value(), atomic_set(),
atomic_set_value(), atomic_sub(), atomic_sub_value(), atomic_toggle()
126
QNX Neutrino Functions and Macros
June 19, 2012
© 2012, QNX Software Systems Limited
_auxv
A pointer to a vector of auxiliary arguments to main()
Synopsis:
auxv_t * _auxv;
Description:
This global variable holds a pointer to a vector of auxiliary arguments to main(). For
more information, see <sys/auxv.h>.
This variable isn’t defined in any header file. If you want to refer to it, you need to add
your own extern statement.
Classification:
QNX Neutrino
See also:
_argc, _argv, getopt(), main()
June 19, 2012
QNX Neutrino Functions and Macros
127
basename()
© 2012, QNX Software Systems Limited
Find the part of a string after the last slash (/)
Synopsis:
#include <libgen.h>
char* basename( char* path );
Arguments:
path
The string to parse.
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
The basename() function takes the pathname pointed to by path and returns a pointer
to the final component of the pathname, deleting any trailing “/” characters.
The basename() function returns:
A pointer to the string “/”
If the string consists entirely of the “/” character
A pointer to the string “.”
If path is a NULL pointer, or points to an empty string
Together the dirname() and basename() functions yield a complete pathname. The
expression dirname(path) obtains the pathname of the directory where
basename(path) is found.
The basename() function might modify the string pointed to by path, and can return a
pointer to static storage.
Returns:
A pointer to the final component of path.
Examples:
#include <stdio.h>
#include <libgen.h>
#include <stdlib.h>
int main( int argc, char** argv )
{
int x;
for( x = 1; x < argc; x++ ) {
128
QNX Neutrino Functions and Macros
June 19, 2012
basename()
© 2012, QNX Software Systems Limited
printf( "%s\n", basename( argv[x] ) );
}
return EXIT_SUCCESS;
}
The table below shows the output of the program, given the input:
Input
Output
“/usr/lib”
“lib”
“/usr/”
“usr”
“/”
“/”
Classification:
POSIX 1003.1 XSI
Safety
Cancellation point
No
Interrupt handler
Yes
Signal handler
Yes
Thread
Yes
See also:
dirname()
June 19, 2012
QNX Neutrino Functions and Macros
129
bcmp()
© 2012, QNX Software Systems Limited
Compare a given number of characters in two strings
Synopsis:
#include <strings.h>
int bcmp( const void *s1,
const void *s2,
size_t n );
Arguments:
s1, s2
The strings you want to compare.
n
The number of bytes to compare.
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
The bcmp() function compares the byte string pointed to by s1 to the string pointed to
by s2. The number of bytes to compare is specified by n. NUL characters may be
included in the comparison.
This function is similar to the ANSI memcmp() function, but tests only for equality.
New code should use the ANSI function.
Returns:
0
The byte strings are identical.
1
The byte strings aren’t identical.
Examples:
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
int main( void )
{
if( bcmp( "Hello there", "Hello world", 6 ) ) {
printf( "Not equal\n" );
} else {
printf( "Equal\n" );
}
return EXIT_SUCCESS;
}
produces the output:
Equal
130
QNX Neutrino Functions and Macros
June 19, 2012
bcmp()
© 2012, QNX Software Systems Limited
Classification:
POSIX 1003.1 XSI
Safety
Cancellation point
No
Interrupt handler
Yes
Signal handler
Yes
Thread
Yes
See also:
bcopy(), bzero(), memcmp(), strcmp()
June 19, 2012
QNX Neutrino Functions and Macros
131
bcopy()
© 2012, QNX Software Systems Limited
Copy a number of characters in one string to another
Synopsis:
#include <strings.h>
void bcopy( const void *src,
void *dst,
size_t n );
Arguments:
src
The string you want to copy.
dst
An existing array into which you want to copy the string.
n
The number of bytes to copy.
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
The bcopy() function copies the byte string pointed to by src (including any NUL
characters) into the array pointed to by dst. The number of bytes to copy is specified
by n. Copying of overlapping objects is guaranteed to work properly.
This function is similar to the ANSI memmove() function, but the order of arguments
is different. New code should use the ANSI function.
Examples:
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
int main( void )
{
auto char buffer[80];
bcopy( "Hello ", buffer, 6 );
bcopy( "world", &buffer[6], 6 );
printf( "%s\n", buffer );
return EXIT_SUCCESS;
}
produces the output:
Hello world
132
QNX Neutrino Functions and Macros
June 19, 2012
bcopy()
© 2012, QNX Software Systems Limited
Classification:
POSIX 1003.1 XSI
Safety
Cancellation point
No
Interrupt handler
Yes
Signal handler
Yes
Thread
Yes
See also:
bcmp(), bzero(), memmove(), strcpy()
June 19, 2012
QNX Neutrino Functions and Macros
133
bind()
© 2012, QNX Software Systems Limited
Bind a name to a socket
Synopsis:
#include <sys/types.h>
#include <sys/socket.h>
int bind( int s,
const struct sockaddr * name,
socklen_t namelen );
Arguments:
s
The file descriptor to be bound.
name
A pointer to the sockaddr structure that holds the address to be bound
to the socket. The socket length and format depend upon its address
family.
namelen
The length of the sockaddr structure pointed to by name.
Library:
libsocket
Use the -l socket option to qcc to link against this library.
Description:
When a socket is created with socket(), it exists in a namespace (address family) but
has no name assigned to it. The bind() function assigns a name to that unnamed socket.
The bind() function assigns a local address. Use connect() to assign a remote address.
The rules used for binding names vary between communication domains.
Before calling bind() on an AF_INET socket, set the af_family member of the
sockaddr structure to AF_INET. Up until QNX Neutrino 6.4.0, a value of 0 was
accepted and assumed to be this value.
Returns:
134
0
Success.
-1
An error occurred (errno is set).
QNX Neutrino Functions and Macros
June 19, 2012
bind()
© 2012, QNX Software Systems Limited
Errors:
EACCES
EADDRINUSE
The requested address is protected, and the current user has
inadequate permission to access it.
The specified address is already in use.
EADDRNOTAVAIL
The specified address isn’t available from the local machine.
EBADF
Invalid descriptor s.
EFAULT
The name parameter isn’t in a valid part of the user address space.
EINVAL
The socket is already bound to an address.
ENOTSOCK
The given file descriptor isn’t for a socket.
Classification:
POSIX 1003.1
Safety
Cancellation point
No
Interrupt handler
No
Signal handler
No
Thread
Yes
See also:
ICMP, IP, TCP, and UDP protocols
connect(), getpeereid(), getsockname(), listen(), socket()
June 19, 2012
QNX Neutrino Functions and Macros
135
bindresvport()
© 2012, QNX Software Systems Limited
Bind a socket to a privileged IP port
Synopsis:
#include <sys/types.h>
#include <netinet/in.h>
int bindresvport( int sd,
struct sockaddr_in * sin );
Arguments:
sd
The socket descriptor to bind to the port.
sin
A pointer to a sockaddr_in structure that specifies the privileged IP port.
Library:
libsocket
Use the -l socket option to qcc to link against this library.
Description:
The bindresvport() function binds a socket descriptor to a privileged IP port (i.e. a port
number in the range 0-1023).
Only root can bind to a privileged port; this call fails for any other user.
Returns:
0
Success.
-1
An error occurred (errno is set).
Errors:
136
EACCES
You must be root to call bindresvport().
EADDRINUSE
The specified address is already in use.
EADDRNOTAVAIL
The specified address isn’t available from the local machine.
EBADF
Invalid descriptor sd.
EFAULT
The sin parameter isn’t a valid pointer to a sockaddr_in
structure.
EINVAL
The socket is already bound to a port.
EPFNOSUPPORT
The protocol family isn’t supported.
QNX Neutrino Functions and Macros
June 19, 2012
bindresvport()
© 2012, QNX Software Systems Limited
Classification:
Unix
Safety
Cancellation point
No
Interrupt handler
No
Signal handler
No
Thread
No
See also:
connect(), getsockname(), listen(), socket()
June 19, 2012
QNX Neutrino Functions and Macros
137
brk()
© 2012, QNX Software Systems Limited
Change the amount of space allocated for the calling process’s data segment
Synopsis:
#include <unistd.h>
int brk( void* endds );
Arguments:
endds
A pointer to the new end of the data segment.
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
This function is in libc.a, but not in libc.so (in order to save space).
Description:
The brk() function is used to change dynamically the amount of space allocated for the
calling process’s data segment (see the exec* functions).
The change is made by resetting the process’s break value and allocating the
appropriate amount of space. The break value is the address of the first location
beyond the end of the data segment. The amount of allocated space increases as the
break value increases. Newly allocated space is set to zero. If, however, the same
memory space is reallocated to the same process, its contents are undefined.
When a program begins execution using execve(), the break is set at the highest
location defined by the program and data storage areas.
You can call getrlimit() to determine the maximum permissible size of the data
segment; it isn’t possible to set the break beyond the rlim_max value returned from
getrlimit():
end + rlim.rlim_max
Returns:
0
Success.
-1
An error occurred (errno is set).
Errors:
ENOMEM
This could mean:
• The data segment size limit, as set by setrlimit(), would be exceeded.
138
QNX Neutrino Functions and Macros
June 19, 2012
brk()
© 2012, QNX Software Systems Limited
• The maximum possible size of a data segment (compiled into the
system) would be exceeded.
• Out of address space; the new break value would extend into an area
of the address space defined by some previously established
mapping (see mmap()).
EAGAIN
The total amount of system memory available for private pages is
temporarily insufficient. This may occur even though the space
requested was less than the maximum data segment size.
Classification:
Legacy Unix
Safety
Cancellation point
No
Interrupt handler
No
Signal handler
No
Thread
Yes
Caveats:
Don’t use brk() and sbrk() with any other memory functions (such as malloc(),
mmap(), and free()). The brk() function assumes that the heap is contiguous; in
Neutrino, memory is returned to the system by the heap, causing the heap to become
sparse. The Neutrino malloc() function is based on mmap(), and not on brk().
The brk() function has been used in specialized cases where no other memory
allocation function provided the same capability. Use mmap() instead because it can
be used portably with all other memory allocation functions and with any function that
uses other allocation functions.
The value of the argument to brk() is rounded up for alignment with eight-byte
boundaries.
See also:
_btext, _edata, _end, _etext, execl(), execle(), execlp(), execlpe(), execv(), execve(),
execvp(), execvpe(), free(), getrlimit(), malloc(), mmap(), sbrk()
June 19, 2012
QNX Neutrino Functions and Macros
139
bsearch()
© 2012, QNX Software Systems Limited
Perform a binary search on a sorted array
Synopsis:
#include <stdlib.h>
void *bsearch( const void *key,
const void *base,
size_t num,
size_t width,
int (*compar)( const void *pkey,
const void *pbase) );
Arguments:
key
The object to search for.
base
A pointer to the first element in the array.
num
The number of elements in the array.
width
The size of an element, in bytes.
compare
A pointer to a user-supplied function that lfind() calls to compare an
array element with the key.
The arguments to the comparison function are:
• pkey — the same pointer as key
• pbase — a pointer to an element in the array.
The comparison function must return an integer less than, equal to, or
greater than zero if the key object is less than, equal to, or greater than the
element in the array.
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
The bsearch() function performs a binary search on the sorted array of num elements
pointed to by base, for an item that matches the object pointed to by key.
Returns:
A pointer to a matching member of the array, or NULL if a matching object couldn’t be
found.
140
QNX Neutrino Functions and Macros
June 19, 2012
bsearch()
© 2012, QNX Software Systems Limited
If there are multiple values in the array that match the key, the return value could be
any of these duplicate values.
Examples:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
static const char *keywords[] = {
"auto",
"break",
"case",
"char",
/* ... */
"while"
};
#define NUM_KW
sizeof(keywords) / sizeof(char *)
int kw_compare( const void *p1, const void *p2 )
{
const char *p1c = (const char *) p1;
const char **p2c = (const char **) p2;
return( strcmp( p1c, *p2c ) );
}
int keyword_lookup( const char *name )
{
const char **key;
key = (char const **) bsearch( name, keywords,
NUM_KW, sizeof( char * ), kw_compare );
if( key == NULL ) return( -1 );
return key - keywords;
}
int main( void )
{
printf( "%d\n", keyword_lookup( "case" ) );
printf( "%d\n", keyword_lookup( "crigger" ) );
printf( "%d\n", keyword_lookup( "auto" ) );
return EXIT_SUCCESS;
}
This program produces the following output:
2
-1
0
June 19, 2012
QNX Neutrino Functions and Macros
141
bsearch()
© 2012, QNX Software Systems Limited
Classification:
ANSI, POSIX 1003.1
Safety
Cancellation point
No
Interrupt handler
Yes
Signal handler
Yes
Thread
Yes
See also:
lfind(), lsearch(), qsort()
142
QNX Neutrino Functions and Macros
June 19, 2012
bt_get_backtrace()
© 2012, QNX Software Systems Limited
Collect a backtrace
The backtrace library is an unsupported feature, due to its fragility. For more
information, see Backtraces in the QNX Neutrino technotes.
Synopsis:
#include <backtrace.h>
int bt_get_backtrace( bt_accessor_t *acc,
bt_addr_t *addrs,
int len );
Arguments:
acc
A pointer to a bt_accessor_t structure. This is an opaque structure that
holds the identity of the thread to backtrace.
addrs
An array of bt_addr_t members where the function can store the
addresses; addrs[0] is the top of stack.
len
The maximum number of addresses to collect and store in addrs.
Library:
libbacktrace
Use the -l backtrace option to qcc to link against this library.
Description:
The bt_get_backtrace() function collects a backtrace up to len deep. The behavior
depends on how you initialized the accessor when you called bt_init_accessor():
• If BT_SELF, the library uses direct memory access to gather the information from
the stack.
• If BT_THREAD, or for BT_PROCESS where the process ID and thread ID are for
the calling thread, the library uses direct memory access.
• For BT_THREAD where the thread ID isn’t for the calling thread, or for
BT_PROCESS with the process ID of the calling process and the thread ID other
than that of the calling thread, the library stops the thread, fetches the thread
context and registers, uses direct memory access, and the restarts the thread.
• For BT_PROCESS where the process ID isn’t that of the calling process, the library
stops the thread, fetches the thread context and registers, uses /proc/pid/as to
access memory, and then restarts the thread.
Note the following:
June 19, 2012
QNX Neutrino Functions and Macros
143
bt_get_backtrace()
© 2012, QNX Software Systems Limited
• When you’re backtracing within the same process, if bt_get_backtrace() attempts
to access a non-existent memory location, signals are masked, and SIGSEGV is
trapped to avoid crashing the program.
• QNX Neutrino 6.3.0 and earlier can’t stop a single thread, so in this case stopping a
thread really means stopping all threads in the process.
• QNX Neutrino 6.3.2 and later can stop a single thread.
• If other applications and processes start and stop threads, it may interfere with
bt_get_backtrace().
Returns:
The number of addresses stored in addrs.
Classification:
QNX Neutrino
Safety
Cancellation point
No
Interrupt handler
No
Signal handler
Yes
Thread
Yes
See also:
bt_init_accessor(), bt_load_memmap(), bt_release_accessor(), bt_set_flags(),
bt_sprn_memmap(), bt_sprnf_addrs(), bt_translate_addrs(), bt_unload_memmap()
Backtraces in the QNX Neutrino technotes
pidin backtrace in the Utilities Reference
144
QNX Neutrino Functions and Macros
June 19, 2012
bt_init_accessor()
© 2012, QNX Software Systems Limited
Initialize a backtrace accessor
The backtrace library is an unsupported feature, due to its fragility. For more
information, see Backtraces in the QNX Neutrino technotes.
Synopsis:
#include <backtrace.h>
int bt_init_accessor( bt_accessor_t *acc,
bt_acc_type_t type, ...);
Arguments:
acc
A pointer to a bt_accessor_t structure. This is an opaque structure that
holds the identity of the thread to backtrace.
type
The type of backtrace to perform; one of:
• BT_SELF — backtrace the calling thread.
• BT_THREAD — backtrace a specified thread in the current process.
• BT_PROCESS — backtrace a specified thread in another process.
Additional arguments are required for BT_THREAD and BT_PROCESS, as
described below.
Library:
libbacktrace
Use the -l backtrace option to qcc to link against this library.
Description:
The bt_init_accessor() function initializes the accessor with the identity of the thread
to backtrace:
• To backtrace the calling thread, use:
bt_init_accessor(bt_accessor_t *acc, BT_SELF);
• To backtrace a thread in the current process, use:
bt_init_accessor(bt_accessor_t *acc, BT_THREAD, pthread_t tid);
• To backtrace a thread in any process, use:
bt_init_accessor(bt_accessor_t *acc, BT_PROCESS, pid_t pid, pthread_t tid)
June 19, 2012
QNX Neutrino Functions and Macros
145
bt_init_accessor()
© 2012, QNX Software Systems Limited
The bt_acc_self global variable is a preinitialized accessor used to backtrace the
current thread. Don’t call bt_init_accessor() or bt_release_accessor() for this
variable.
Returns:
0
Success.
-1
An error occurred (errno is set).
Errors:
EINVAL
The acc argument is NULL, or the type is invalid.
Classification:
QNX Neutrino
Safety
Cancellation point
No
Interrupt handler
No
Signal handler
Yes
Thread
Yes
See also:
bt_get_backtrace(), bt_load_memmap(), bt_release_accessor(), bt_set_flags(),
bt_sprn_memmap(), bt_sprnf_addrs(), bt_translate_addrs(), bt_unload_memmap()
Backtraces in the QNX Neutrino technotes
pidin backtrace in the Utilities Reference
146
QNX Neutrino Functions and Macros
June 19, 2012
bt_load_memmap()
© 2012, QNX Software Systems Limited
Load a memory map associated with a backtrace
The backtrace library is an unsupported feature, due to its fragility. For more
information, see Backtraces in the QNX Neutrino technotes.
Synopsis:
#include <backtrace.h>
int bt_load_memmap( bt_accessor_t *acc,
bt_memmap_t * memmap );
Arguments:
acc
A pointer to a bt_accessor_t structure. This is an opaque structure
that holds the identity of the thread to backtrace.
memmap
A pointer to a location where the function can store the memory map.
Library:
libbacktrace
Use the -l backtrace option to qcc to link against this library.
Description:
The bt_load_memmap() function reads the memory map information from the process
represented by acc, and saves the information in memmap.
Returns:
0
Success.
-1
An error occurred (errno is set).
Errors:
EINVAL
The acc or memmap argument is NULL.
ENOMEM
There wasn’t enough memory to load the memory map.
This function can also set errno to any of the values that devctl() and open() can.
Classification:
QNX Neutrino
June 19, 2012
QNX Neutrino Functions and Macros
147
bt_load_memmap()
© 2012, QNX Software Systems Limited
Safety
Cancellation point
No
Interrupt handler
No
Signal handler
No
Thread
Yes
See also:
bt_get_backtrace(), bt_init_accessor(), bt_release_accessor(), bt_set_flags(),
bt_sprn_memmap(), bt_sprnf_addrs(), bt_translate_addrs(), bt_unload_memmap()
Backtraces in the QNX Neutrino technotes
pidin backtrace in the Utilities Reference
148
QNX Neutrino Functions and Macros
June 19, 2012
bt_release_accessor()
© 2012, QNX Software Systems Limited
Release an accessor for a backtrace
The backtrace library is an unsupported feature, due to its fragility. For more
information, see Backtraces in the QNX Neutrino technotes.
Synopsis:
#include <backtrace.h>
int bt_release_accessor(bt_accessor_t *acc);
Arguments:
acc
A pointer to a bt_accessor_t structure. This is an opaque structure that
holds the identity of the thread to backtrace.
Library:
libbacktrace
Use the -l backtrace option to qcc to link against this library.
Description:
The bt_release_accessor() function releases all resources that acc keeps track of.
Don’t release an accessor while another function is using it.
Don’t call bt_init_accessor() or bt_release_accessor() for the bt_acc_self global
variable.
Returns:
0
Success.
-1
An error occurred (errno is set).
Errors:
EINVAL
The acc argument is NULL.
Classification:
QNX Neutrino
Safety
Cancellation point
No
continued. . .
June 19, 2012
QNX Neutrino Functions and Macros
149
bt_release_accessor()
© 2012, QNX Software Systems Limited
Safety
Interrupt handler
Yes
Signal handler
Yes
Thread
Yes
See also:
bt_get_backtrace(), bt_init_accessor(), bt_load_memmap(), bt_set_flags(),
bt_sprn_memmap(), bt_sprnf_addrs(), bt_translate_addrs(), bt_unload_memmap()
Backtraces in the QNX Neutrino technotes
pidin backtrace in the Utilities Reference
150
QNX Neutrino Functions and Macros
June 19, 2012
bt_set_flags()
© 2012, QNX Software Systems Limited
Set or clear the flags for backtracing
The backtrace library is an unsupported feature, due to its fragility. For more
information, see Backtraces in the QNX Neutrino technotes.
Synopsis:
#include <backtrace.h>
int bt_set_flags( bt_accessor_t *acc,
unsigned flags,
int onoff );
Arguments:
acc
A pointer to a bt_accessor_t structure. This is an opaque structure that
holds the identity of the thread to backtrace.
flags
A bitwise ORing of the flags you want to set:
• BTF_LIVE_BACKTRACE — typically bt_get_backtrace() freezes a
thread before gathering the backtrace. If you set this flag,
bt_get_backtrace() doesn’t freeze the thread. This can be useful if you
want to freeze many threads at the same time, and then collect the
backtrace for all threads, thus providing a coherent snapshot for all of the
threads.
onoff
Zero to clear the specified flags, or a nonzero value to set the flags.
Library:
libbacktrace
Use the -l backtrace option to qcc to link against this library.
Description:
The bt_set_flags() function lets you turn the specified flags on or off.
Returns:
0
Success.
-1
An error occurred (errno is set).
Errors:
EINVAL
June 19, 2012
The flags argument specifies an invalid flag.
QNX Neutrino Functions and Macros
151
bt_set_flags()
© 2012, QNX Software Systems Limited
Classification:
QNX Neutrino
Safety
Cancellation point
No
Interrupt handler
Yes
Signal handler
Yes
Thread
Yes
See also:
bt_get_backtrace(), bt_init_accessor(), bt_load_memmap(), bt_release_accessor(),
bt_sprn_memmap(), bt_sprnf_addrs(), bt_translate_addrs(), bt_unload_memmap()
Backtraces in the QNX Neutrino technotes
pidin backtrace in the Utilities Reference
152
QNX Neutrino Functions and Macros
June 19, 2012
bt_sprn_memmap()
© 2012, QNX Software Systems Limited
Format the memory map information for a backtrace
The backtrace library is an unsupported feature, due to its fragility. For more
information, see Backtraces in the QNX Neutrino technotes.
Synopsis:
#include <backtrace.h>
int bt_sprn_memmap( bt_memmap_t *memmap,
char *out,
size_t outlen );
Arguments:
memmap
A pointer to memory-map information for the process you’ve collected
backtracing for. Use bt_load_memmap() to initialize this variable.
out
A string where the function can store the formatted memory map.
outlen
The size of out.
Library:
libbacktrace
Use the -l backtrace option to qcc to link against this library.
Description:
The bt_sprn_memmap() function formats the memory map information into out.
TBD: The exact format may change.
Returns:
0
Success.
-1
An error occurred (errno is set).
Classification:
QNX Neutrino
Safety
June 19, 2012
Cancellation point
No
Interrupt handler
No
Signal handler
Yes
Thread
Yes
QNX Neutrino Functions and Macros
153
bt_sprn_memmap()
© 2012, QNX Software Systems Limited
See also:
bt_get_backtrace(), bt_init_accessor(), bt_load_memmap(), bt_release_accessor(),
bt_set_flags(), bt_sprnf_addrs(), bt_translate_addrs(), bt_unload_memmap()
Backtraces in the QNX Neutrino technotes
pidin backtrace in the Utilities Reference
154
QNX Neutrino Functions and Macros
June 19, 2012
bt_sprnf_addrs()
© 2012, QNX Software Systems Limited
Format the addresses from a backtrace
The backtrace library is an unsupported feature, due to its fragility. For more
information, see Backtraces in the QNX Neutrino technotes.
Synopsis:
#include <backtrace.h>
int bt_sprnf_addrs( bt_memmap_t *memmap,
bt_addr_t *addrs,
int addrslen,
char *fmt,
char *out,
size_t outlen,
char *separator );
Arguments:
memmap
NULL, or a pointer to memory-map information for the process you’ve
collected backtracing for. Use bt_load_memmap() to initialize this
variable.
addrs
An array of addresses that you want to format.
addrslen
The number of entries in the addrs array.
fmt
The format to use for each entry; see below.
out
A pointer to a buffer where the function can store the formatted output.
outlen
The length of the out, in bytes.
separator
NULL, or a pointer to a separator to write between the formatted
addresses.
Library:
libbacktrace
Use the -l backtrace option to qcc to link against this library.
Description:
The bt_sprnf_addrs() function formats the addresses in the addrs using fmt as the
format for each entry, and storing the formatted addresses in the out buffer. If
separator isn’t NULL, the function writes it in out between each formatted address.
The memmap is optional, but if specified, it allows access to more formatting styles.
The format for each entry (fmt), is analogous to printf() formats:
• %% — a literal %.
June 19, 2012
QNX Neutrino Functions and Macros
155
bt_sprnf_addrs()
© 2012, QNX Software Systems Limited
• %a — an address in memory.
• %l — an address relative to the start of the file it belongs to (i.e. this corresponds to
the address in the object file).
• %o — an address offset from the beginning of the object files. (i.e. %a == %l + %o).
• %f — an object file that the address belongs to (e.g. /some/dir/libc.so).
• %I — a numerical index that corresponds to the numerical index in the memory
map printouts (i.e. if the memory map is printed, then using %I instead of %f in the
backtrace minimizes the size of the backtrace).
For the %l, %o, %f, and %I formats, memmap must not be NULL.
Returns:
The number of addresses from addr that could be completely formatted and written in
out.
Classification:
QNX Neutrino
Safety
Cancellation point
No
Interrupt handler
No
Signal handler
No
Thread
Yes
See also:
bt_get_backtrace(), bt_init_accessor(), bt_load_memmap(), bt_release_accessor(),
bt_set_flags(), bt_sprn_memmap(), bt_translate_addrs(), bt_unload_memmap()
Backtraces in the QNX Neutrino technotes
pidin backtrace in the Utilities Reference
156
QNX Neutrino Functions and Macros
June 19, 2012
bt_translate_addrs()
© 2012, QNX Software Systems Limited
Translate the addresses from a backtrace
The backtrace library is an unsupported feature, due to its fragility. For more
information, see Backtraces in the QNX Neutrino technotes.
Synopsis:
#include <backtrace.h>
void bt_translate_addrs( bt_memmap_t *memmap,
bt_addr_t *addrs,
int addrslen,
bt_addr_t *reladdrs,
bt_addr_t *offsets,
int *index,
char **filenames );
Arguments:
memmap
A pointer to memory-map information for the process you’ve collected
backtracing for. Use bt_load_memmap() to initialize this variable.
addrs
An array of addresses that you want to translate.
addrslen
The number of entries in the addrs array, as well as the number of entries
in the reladdrs, offsets, index, and filenames arrays (if non-NULL).
reladdrs
NULL, or an array where the function can store the addresses as
specified in the object files.
offsets
NULL, or an array where the function can store the difference between
the in-file address and in-memory address (i.e. offsets[0] = addr[0] mod_addr[0]).
index
NULL, or an array where the function can store the memory map index
for each address.
filenames
NULL, or an array where the function can store the object file name for
each address.
The file names aren’t copied from the memory map, so they’re valid only until you
unload the memory map.
Library:
libbacktrace
Use the -l backtrace option to qcc to link against this library.
June 19, 2012
QNX Neutrino Functions and Macros
157
bt_translate_addrs()
© 2012, QNX Software Systems Limited
Description:
The bt_translate_addrs() function translates all process addresses in addrs. You can
pass a NULL pointer for any of the result arrays that you don’t need.
Programs typically use bt_sprnf_addrs() instead of bt_translate_addrs().
Classification:
QNX Neutrino
Safety
Cancellation point
No
Interrupt handler
No
Signal handler
Yes
Thread
Yes
See also:
bt_get_backtrace(), bt_init_accessor(), bt_load_memmap(), bt_release_accessor(),
bt_set_flags(), bt_sprn_memmap(), bt_sprnf_addrs(), bt_unload_memmap()
Backtraces in the QNX Neutrino technotes
pidin backtrace in the Utilities Reference
158
QNX Neutrino Functions and Macros
June 19, 2012
bt_unload_memmap()
© 2012, QNX Software Systems Limited
Unload a memory map associated with a backtrace
The backtrace library is an unsupported feature, due to its fragility. For more
information, see Backtraces in the QNX Neutrino technotes.
Synopsis:
#include <backtrace.h>
void bt_unload_memmap( bt_memmap_t *memmap );
Arguments:
memmap
A pointer to the memory map that you want to unload.
Library:
libbacktrace
Use the -l backtrace option to qcc to link against this library.
Description:
The bt_unload_memmap() function releases the memory that memmap holds. Don’t
use memmap after invoking this function.
Classification:
QNX Neutrino
Safety
Cancellation point
No
Interrupt handler
No
Signal handler
No
Thread
Yes
See also:
bt_get_backtrace(), bt_init_accessor(), bt_load_memmap(), bt_release_accessor(),
bt_set_flags(), bt_sprn_memmap(), bt_sprnf_addrs(), bt_translate_addrs()
Backtraces in the QNX Neutrino technotes
pidin backtrace in the Utilities Reference
June 19, 2012
QNX Neutrino Functions and Macros
159
_btext
© 2012, QNX Software Systems Limited
The beginning of the text segment
Synopsis:
N/A
Description:
This linker symbol defines the beginning of the text segment. This variable isn’t
defined in any header file.
Classification:
QNX Neutrino
See also:
brk(), _edata, _end, _etext, sbrk()
160
QNX Neutrino Functions and Macros
June 19, 2012
btowc()
© 2012, QNX Software Systems Limited
Convert a single-byte character to a wide character
Synopsis:
#include <wchar.h>
wint_t btowc( int c );
Arguments:
c
The single-byte character that you want to convert.
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
The btowc() function converts the given character (if it’s a valid one-byte character in
the initial shift state) into a wide character.
This function is the single-byte version of mbtowc().
Returns:
The wide-character representation of the character, or WEOF if c has the value EOF or
(unsigned char) c isn’t a valid one-byte character in the initial conversion state.
Classification:
ANSI, POSIX 1003.1
Safety
Cancellation point
No
Interrupt handler
No
Signal handler
Yes
Thread
Yes
See also:
mbtowc()
June 19, 2012
QNX Neutrino Functions and Macros
161
bzero()
© 2012, QNX Software Systems Limited
Set the first part of an object to null bytes
Synopsis:
#include <strings.h>
void bzero( void *dst,
size_t n );
Arguments:
dst
An existing object that you want to fill with zeroes.
n
The number of bytes to fill.
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
The bzero() function fills the first n bytes of the object pointed to by dst with zero
(NUL) bytes.
This function is similar to the ANSI memset() function. New code should use the
ANSI function.
Examples:
#include <stdlib.h>
#include <string.h>
int main( void )
{
char buffer[80];
bzero( buffer, 80 );
return EXIT_SUCCESS;
}
Classification:
POSIX 1003.1 XSI
Safety
Cancellation point
No
Interrupt handler
Yes
continued. . .
162
QNX Neutrino Functions and Macros
June 19, 2012
bzero()
© 2012, QNX Software Systems Limited
Safety
Signal handler
Yes
Thread
Yes
See also:
bcmp(), bcopy(), memset(), strset()
June 19, 2012
QNX Neutrino Functions and Macros
163
cabs(), cabsf()
© 2012, QNX Software Systems Limited
Compute the absolute value of a complex number
Synopsis:
#include <math.h>
struct __cabsargs {
double x;
/* real part
*/
double y;
/* imaginary part */
};
double cabs( struct __cabsargs value );
struct __cabsfargs {
float x;
/* real part
*/
float y;
/* imaginary part */
};
float cabsf( struct __cabsfargs value );
Arguments:
value
The complex value that you want to get the absolute value of.
Library:
libm
Use the -l m option to qcc to link against this library.
Description:
These functions compute the absolute value of the complex number specified by value,
using a calculation equivalent to:
sqrt( ( value.x * value.x ) + ( value.y * value.y ) );
Returns:
The absolute value of value.
Examples:
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
struct __cabsargs c = { -3.0, 4.0 };
int main( void )
{
printf( "%f\n", cabs( c ) );
return EXIT_SUCCESS;
}
164
QNX Neutrino Functions and Macros
June 19, 2012
cabs(), cabsf()
© 2012, QNX Software Systems Limited
produces the output:
5.000000
Classification:
ANSI, POSIX 1003.1
Safety
Cancellation point
No
Interrupt handler
No
Signal handler
No
Thread
Yes
See also:
abs(), fabs(), labs(), llabs()
June 19, 2012
QNX Neutrino Functions and Macros
165
cache_fini()
© 2012, QNX Software Systems Limited
Free cache-coherency resources when the driver is unloaded
Synopsis:
int cache_fini(struct cache_ctrl *cinfo);
Arguments:
cinfo
A pointer to the structure that was originally passed to cache_init(). See the
cache_init() function.
Library:
libcache
Use the -l cache option to qcc to link against this library.
Description:
Call the cache_fini() function to free up any resources that were allocated by the
cache_init() function. The cinfo is a pointer to the structure that was originally passed
to cache_init().
This function was added in QNX Momentics 6.3.0 SP2.
Returns:
0
Classification:
QNX Neutrino
Safety
Cancellation point
Yes
Interrupt handler
No
Signal handler
Yes
Thread
Yes
See also:
CACHE_FLUSH(), cache_init(), CACHE_INVAL()
166
QNX Neutrino Functions and Macros
June 19, 2012
CACHE_FLUSH()
© 2012, QNX Software Systems Limited
Flush cache lines associated with a data buffer
Synopsis:
#include <sys/cache.h>
CACHE_FLUSH(struct cache_ctrl *cinfo,
void *vaddr,
uint64_t paddr,
size_t len);
Arguments:
cinfo
A pointer the the structure that was initially passed to cache_init().
vaddr
The virtual address of the buffer; this is a pointer to the data in the driver’s
virtual address space.
paddr
The physical address of the buffer: this is typically in the same address
space that the external device will use to reference the data. The physical
address is obtained by calling mem_offset64(). Since this function is fairly
costly, drivers typically allocate a pool of data buffers at initialization (e.g.
by calling mmap() with the MAP_PHYS and MAP_ANON flags), and
predetermine the physical addresses of the data.
len
The number of bytes in the buffer, for which cached data should be flushed
to memory.
Library:
libcache
Use the -l cache option to qcc to link against this library.
Description:
This macro is used to flush any cache lines associated with a data buffer out to
memory. This routine ensures that any modifications that have been made to the data
by the CPU will be reflected by the contents of memory, and thus an external device
reading the data won’t retrieve stale data. For more information about cache
coherency, see the entry for cache_init().
This macro was added in QNX Momentics 6.3.0 SP2.
Before using the CACHE_*() macros on ARM and MIPS platforms, the calling thread
must obtain I/O privileges by calling ThreadCtl(), specifying the _NTO_TCTL_IO flag:
ThreadCtl( _NTO_TCTL_IO, 0 );
Failing to do so may result in a SIGILL (illegal instruction) signal.
June 19, 2012
QNX Neutrino Functions and Macros
167
CACHE_FLUSH()
© 2012, QNX Software Systems Limited
Environment variables:
The following environment variables, if they exist, affect the behavior of this function:
CACHE_NOP
Instructs the library that the CACHE_FLUSH() and
CACHE_INVAL() macros should have no effect.
CACHE_MSYNC
Instructs the library that the CACHE_FLUSH() and
CACHE_INVAL() macros should use the msync() C library call to
perform cache synchronization.
Classification:
QNX Neutrino
Safety
Cancellation point
No
Interrupt handler
Yes
Signal handler
Yes
Thread
Yes
Caveats:
CACHE_FLUSH() is implemented as a macro.
See also:
cache_fini(), cache_init(), CACHE_INVAL()
168
QNX Neutrino Functions and Macros
June 19, 2012
cache_init()
© 2012, QNX Software Systems Limited
Register with the cache-coherency library
Synopsis:
#include <sys/cache.h>
int cache_init(int flags,
struct cache_ctrl *cinfo,
const char *dllname);
Arguments:
flags
Zero, or flags that control the behavior of the cache-coherency library.
The only flag currently defined is:
• CACHE_INIT_FLAG_IGNORE_SCAN — Specify that memory
accesses to and from the device aren’t snooped, whether or not the
data caches in the system are reported as snooping or not. This might
be required for devices in the system that bypass the bus-snooping
mechanism, or as a workaround for hardware bugs.
cinfo
A pointer to a cache_ctrl structure that contains state information. The
library uses this structure to store various information that uses when
performing synchronization operations. The driver should allocate and
initialize this structure. All of the members of the structure should be
initialized with zeros, with the exception of the fd field. For more
information regarding the members of this structure, see the description
section.
dllname
The path of a DLL to load that provides cache-synchronization routines
or NULL to use the default routines.
Library:
libcache
Use the -l cache option to qcc to link against this library.
Description:
The cache_init() function initializes the cache coherency library (libcache). Your
driver must call cache_init() before using the library.
This function was added in QNX Momentics 6.3.0 SP2.
Members of the cache_ctrl structure
The cache_ctrl structure includes at least the following members:
June 19, 2012
QNX Neutrino Functions and Macros
169
cache_init()
© 2012, QNX Software Systems Limited
cache_line_size
When this function returns, this field will specify the size, in
bytes, of a cache line’s worth of data. If the system implements
a bus-snooping protocol, this field may contain zero.
cache_flush_rate
Provides a runtime indication to the driver, of the cost of
flushing the cache:
CACHE_OP_RATE_SNOOP
Due to a bus-snooping mechanism, a cache flush
operation has negligible cost.
CACHE_OP_RATE_INLINE
Cache flush operations are implemented with
CPU-specific inline routines, and are inexpensive.
CACHE_OP_RATE_CALLOUT
Cache flush operations are implemented by calling an
external function, which incurs a small CPU overhead.
CACHE_OP_RATE_MSYNC
Cache flush operations are implemented by calling
msync(). Since this function is implemented with a system
call, the operation will be very expensive. It is very
unlikely that the library will end up calling msync(), but in
the event that it does, the driver could potentially achieve
better performance by mapping data buffers as
noncacheable, so that it can avoid having to perform cache
synchronization operations.
cache_invalidate_rate
Provides a runtime indication to the driver of the cost of
invalidating the cache. The defined values for this field are
similar to those defined for the cache_flush_rate field.
fd
The driver should set this field to NOFD.
Other fields in the structure should not be referenced or modified.
Cache coherency
Device drivers for hardware that performs Direct Memory Access (DMA) use this
cache coherency library. These devices are either bus-mastering devices that can
directly read or modify memory, or devices that use a DMA controller to transfer data
between the device and memory. The key factor is that memory may be accessed by
an agent other than the CPU(s).
On some systems, cache coherency is performed by a bus-snooping protocol that is
implemented in hardware. In such systems, the CPU(s) snoop all transactions on the
memory bus and automatically keep their caches in sync with the memory.
170
QNX Neutrino Functions and Macros
June 19, 2012
© 2012, QNX Software Systems Limited
cache_init()
For example, if an external agent modifies data at a given memory location, the CPU
will observe the memory write cycle, and if it has a cached copy of the data at that
memory location, it will invalidate the corresponding cache entry. The next time the
CPU tries to examine the memory location, it will fetch the modified data from
memory, instead of retrieving stale data from the cache.
Similarly, special action is taken if an external agent attempts to read a memory
location, and a CPU has modified the memory location, but the modified copy of the
data is in its cache, and hasn’t yet been written to memory. In this case, the read cycle
is suspended while the CPU copies the updated version of the data out to memory.
Once memory has been updated with the modified version, the read cycle can
continue, and the external agent gets the updated copy of the data.
On other systems, where there is no such snooping protocol implemented in hardware,
cache coherency between the CPU and external devices must be maintained by driver
software. These are typically single-CPU systems, since on SMP systems,
bus-snooping is the usual mechanism of keeping the CPUs in sync with each other. To
work on these systems, special action needs to be taken by driver software, to ensure
data coherency between the CPU and external devices.
A driver ensures data coherency for systems that don’t have a bus-snooping protocol in
different ways. The first one is the “big hammer” approach that simply disables
caching for any memory location that can be accessed by both the CPU and the
external device. This approach, however, has a severe performance penalty; for some
network devices on certain systems, the throughput reduces to roughly half of the
original value.
You can solve the above throughput problem by using cacheable data buffers, but
perform synchronization operations on the data buffers at strategic points in the driver.
For example, in the case of packet transmission for a network device, the driver must
ensure that any data pertaining to the packet had been flushed out to memory, before
allowing the DMA agent to begin copying the data. In the case of packet reception, the
driver should invalidate any cached data pertaining to the packet buffer, before letting
the DMA agent transfer data into the receive buffer. This eliminates the possibility that
the CPU could write a cached portion of the data out to the memory buffer, after the
network device had updated the buffer with new packet data.
The driver can perform cache flushing and invalidation operations in one of two ways.
It can issue special CPU-dependent instructions that operate on the cache, or it can use
the cache-coherency library (libcache). The latter approach is preferable, since it
makes your driver portable. The library performs the correct thing based on the type of
CPU it’s running on. For maximum portability, the library must be used whether the
system has a bus-snooping protocol or not. If the system implements a bus-snooping
protocol, the library determines this, and ensures that there are no unnecessary
synchronization operations being performed.
June 19, 2012
QNX Neutrino Functions and Macros
171
cache_init()
© 2012, QNX Software Systems Limited
Returns:
0
-1
Success.
Failure and errno is set. If this function fails, it isn’t safe for devices to DMA
to or from cacheable buffers. Additionally, calling other functions with the
cache_ctrl structure that was provided will have unpredictable results.
Classification:
QNX Neutrino
Safety
Cancellation point
Yes
Interrupt handler
No
Signal handler
Yes
Thread
Yes
Caveats:
The cache-invalidation operation could have certain negative side effects, which the
driver must take measures to avoid. If a data buffer partially shares a cache line with
some other piece of data (including another data buffer), data corruption could occur.
Since the invalidation is performed with cache-line granularity, invalidating data at the
start or end of the buffer could potentially invalidate important data, such as program
variables, which means that changes made to the data by the CPU could be
inadvertently lost.
You can avoid this by padding the data buffers. The driver should pad the start of the
buffer, so that it starts on the next cache line boundary. It should also pad the buffer
out to the end of the last cache line of the buffer. To do this, the driver can use the
cache_line_size field of the cache_ctrl structure. Note that this value could be zero
(e.g. if there is a cache-coherency protocol implemented in hardware), in which case
the driver doesn’t need to do any padding.
See also:
cache_fini(), CACHE_FLUSH(), CACHE_INVAL()
172
QNX Neutrino Functions and Macros
June 19, 2012
CACHE_INVAL()
© 2012, QNX Software Systems Limited
Invalidate cache lines associated with a data buffer
Synopsis:
#include <sys/cache.h>
CACHE_INVAL(struct cache_ctrl *cinfo,
void *vaddr,
uint64_t paddr,
size_t len);
Arguments:
cinfo
A pointer the the structure that was initially passed to cache_init().
vaddr
The virtual address of the buffer; this is a pointer to the data in the driver’s
virtual address space.
paddr
The physical address of the buffer: this is typically in the same address
space that the external device will use to reference the data. The physical
address is obtained by calling mem_offset64(). Since this function is fairly
costly, drivers typically allocate a pool of data buffers at initialization (e.g.
by calling mmap() with the MAP_PHYS and MAP_ANON flags), and pre
determine the physical addresses of the data.
len
The number of bytes in the buffer, for which the associated cache lines
should be invalidated.
Library:
libcache
Use the -l cache option to qcc to link against this library.
Description:
This macro is used to invalidate any cache lines associated with a data buffer. This
routine ensures that any subsequent modifications that are made to the data by an
external device will be not be corrupted by the CPU writing back cached data to the
memory, and ensures that once the data has been modified, the CPU will fetch the
updated data from memory, instead of retrieving stale data from the cache.
This macro was added in QNX Momentics 6.3.0 SP2.
Before using the CACHE_*() macros on ARM and MIPS platforms, the calling thread
must obtain I/O privileges by calling ThreadCtl(), specifying the _NTO_TCTL_IO flag:
ThreadCtl( _NTO_TCTL_IO, 0 );
Failing to do so may result in a SIGILL (illegal instruction) signal.
June 19, 2012
QNX Neutrino Functions and Macros
173
CACHE_INVAL()
© 2012, QNX Software Systems Limited
Environment variables:
The following environment variables, if they exist, affect the behavior of this function:
CACHE_NOP
Instructs the library that the CACHE_FLUSH() and
CACHE_INVAL() macros should have no effect.
CACHE_MSYNC
Instructs the library that the CACHE_FLUSH() and
CACHE_INVAL() macros should use the msync() C library call to
perform cache synchronization.
Classification:
QNX Neutrino
Safety
Cancellation point
No
Interrupt handler
Yes
Signal handler
Yes
Thread
Yes
Caveats:
CACHE_INVAL() is implemented as a macro.
See also:
cache_fini(), CACHE_FLUSH(), cache_init()
174
QNX Neutrino Functions and Macros
June 19, 2012
calloc()
© 2012, QNX Software Systems Limited
Allocate space for an array
Synopsis:
#include <stdlib.h>
void* calloc ( size_t n,
size_t size );
Arguments:
n
The number of array elements to allocate.
size
The size, in bytes, of one array element.
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
The calloc() function allocates space from the heap for an array of n objects, each of
size bytes, and initializes them to 0. Use free() or realloc() to free the block of memory.
Because the malloc() implementation uses signed, 32-bit integers to represent the size
internally, you can’t allocate more than 2 GB in a single allocation. If the size is
greater than 2 GB, calloc() indicates an error of ENOMEM.
If n or size is zero, the default behavior is to return a non-NULL pointer that’s valid
only to a corresponding call to free() or realloc(). Don’t assume that this pointer points
to any valid memory. You can control this behavior via the MALLOC_OPTIONS
environmental variable; if the value of MALLOC_OPTIONS contains a V, calloc()
returns a NULL pointer. This environment variable also affects malloc() and realloc().
This is known as the “System V” behavior.
Returns:
A pointer to the start of the allocated memory, or NULL if an error occurred (errno is
set).
Errors:
June 19, 2012
ENOMEM
Not enough memory.
EOK
No error.
QNX Neutrino Functions and Macros
175
calloc()
© 2012, QNX Software Systems Limited
Examples:
#include <stdlib.h>
#include <stdio.h>
int main( void )
{
char* buffer;
buffer = (char* )calloc( 80, sizeof(char) );
if( buffer == NULL ) {
printf( "Can’t allocate memory for buffer!\n" );
return EXIT_FAILURE;
}
free( buffer );
return EXIT_SUCCESS;
}
Environment variables:
MALLOC_OPTIONS
Control the way calloc(), malloc(), and realloc() behave if you specify a size of
0 (or a value of 0 for the n argument to calloc()). The V (“System V”) and R
(“use the realloc() behavior of QNX Neutrino 6.4.0 and earlier”) columns below
indicate how the functions behave if the value of MALLOC_OPTIONS
includes that letter:
Function
Default
calloc(n, 0)
Non-NULL NULL No effect
malloc(0)
Non-NULL NULL No effect
realloc(NULL, 0)
Non-NULL NULL No effect
V
R
realloc(non-NULL, 0) Non-NULL NULL NULL
In all the above cases, if the function returns a non-NULL pointer, it’s valid only
for a corresponding call to free() or realloc().
Classification:
ANSI, POSIX 1003.1
Safety
Cancellation point
No
Interrupt handler
No
Signal handler
No
continued. . .
176
QNX Neutrino Functions and Macros
June 19, 2012
calloc()
© 2012, QNX Software Systems Limited
Safety
Thread
Yes
See also:
free(), malloc(), realloc(), sbrk()
June 19, 2012
QNX Neutrino Functions and Macros
177
cbrt(), cbrtf()
© 2012, QNX Software Systems Limited
Compute the cube root of a number
Synopsis:
#include <math.h>
double cbrt ( double x );
float cbrtf ( float x );
Arguments:
x
The number whose cube root you want to calculate.
Library:
libm
Use the -l m option to qcc to link against this library.
Description:
The cbrt() and cbrtf() functions compute the cube root of x.
Returns:
The cube root of x. If x is NAN, cbrt() returns NAN.
Examples:
#include
#include
#include
#include
<stdio.h>
<inttypes.h>
<math.h>
<fpstatus.h>
int main(int argc, char** argv) {
double a, b;
a = 27.0;
b = cbrt(a);
printf("The cube root of %f is %f \n", a, b);
return(0);
}
produces the output:
The cube root of 27.000000 is 3.000000
Classification:
ANSI, POSIX 1003.1
178
QNX Neutrino Functions and Macros
June 19, 2012
cbrt(), cbrtf()
© 2012, QNX Software Systems Limited
Safety
Cancellation point
No
Interrupt handler
No
Signal handler
No
Thread
Yes
See also:
sqrt()
June 19, 2012
QNX Neutrino Functions and Macros
179
ceil(), ceilf()
© 2012, QNX Software Systems Limited
Round up a value to the next integer
Synopsis:
#include <math.h>
double ceil( double x );
float ceilf( float x );
Arguments:
x
The value you want to round.
Library:
libm
Use the -l m option to qcc to link against this library.
Description:
The ceil() and ceilf() functions round the value of x up to the next integer (rounding
towards the “ceiling”).
Returns:
The smallest integer ≥ x.
If an error occurs, these functions return 0, but this is also a valid mathematical result.
If you want to check for errors, set errno to 0, call the function, and then check errno
again. These functions don’t change errno if no errors occurred.
Examples:
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
int main( void )
{
printf( "%f %f %f %f %f\n", ceil( -2.1 ),
ceil( -2. ), ceil( 0.0 ), ceil( 2. ),
ceil( 2.1 ) );
return EXIT_SUCCESS;
}
produces the output:
-2.000000 -2.000000 0.000000 2.000000 3.000000
180
QNX Neutrino Functions and Macros
June 19, 2012
ceil(), ceilf()
© 2012, QNX Software Systems Limited
Classification:
ANSI, POSIX 1003.1
Safety
Cancellation point
No
Interrupt handler
No
Signal handler
No
Thread
Yes
See also:
floor(), fmod(), round()
June 19, 2012
QNX Neutrino Functions and Macros
181
cfgetispeed()
© 2012, QNX Software Systems Limited
Return the input baud rate that’s stored in a termios structure
Synopsis:
#include <termios.h>
speed_t cfgetispeed(
const struct termios* termios_p );
Arguments:
termios_p
A pointer to a termios structure that describes the terminal’s control
attributes.
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
The cfgetispeed() function returns the input baud rate that’s stored in the termios
structure pointed to by termios_p.
You can get a valid termios control structure for an opened device by calling
tcgetattr().
Returns:
The input baud rate stored in *termios_p, or -1 if an error occurs (errno is set).
Errors:
EINVAL
One of the arguments is invalid.
ENOTTY
This function isn’t supported by the system.
Examples:
#include
#include
#include
#include
#include
<termios.h>
<fcntl.h>
<unistd.h>
<stdlib.h>
<stdio.h>
int main( void )
{
int fd;
struct termios termios_p;
speed_t speed;
fd = open( "/dev/ser1", O_RDWR );
tcgetattr( fd, &termios_p);
/*
*
182
Get input baud rate
QNX Neutrino Functions and Macros
June 19, 2012
cfgetispeed()
© 2012, QNX Software Systems Limited
*/
speed = cfgetispeed( &termios_p);
printf( "Input baud: %ld\n", speed );
close( fd );
return EXIT_SUCCESS;
}
Classification:
POSIX 1003.1
Safety
Cancellation point
No
Interrupt handler
No
Signal handler
Yes
Thread
Yes
See also:
errno, cfgetospeed(), cfsetispeed(), cfsetospeed(), tcgetattr(), tcsetattr(), termios
June 19, 2012
QNX Neutrino Functions and Macros
183
cfgetospeed()
© 2012, QNX Software Systems Limited
Return the output baud rate that’s stored in a termios structure
Synopsis:
#include <termios.h>
speed_t cfgetospeed(
const struct termios* termios_p );
Arguments:
termios_p
A pointer to a termios structure that describes the terminal’s control
attributes.
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
The cfgetospeed() function returns the output baud rate that’s stored in the termios
structure pointed to by termios_p.
You can get a valid termios control structure for an opened device by calling
tcgetattr().
Returns:
The output baud rate stored in *termios_p, or -1 if an error occurs (errno is set).
Errors:
EINVAL
One of the arguments is invalid.
ENOTTY
This function isn’t supported by the system.
Examples:
#include
#include
#include
#include
#include
<termios.h>
<fcntl.h>
<unistd.h>
<stdlib.h>
<stdio.h>
int main( void )
{
int fd;
struct termios termios_p;
speed_t speed;
fd = open( "/dev/ser1", O_RDWR );
tcgetattr( fd, &termios_p);
/*
*
184
Get output baud rate
QNX Neutrino Functions and Macros
June 19, 2012
cfgetospeed()
© 2012, QNX Software Systems Limited
*/
speed = cfgetospeed( &termios_p);
printf( "Output baud: %ld\n", speed );
close( fd );
return EXIT_SUCCESS;
}
Classification:
POSIX 1003.1
Safety
Cancellation point
No
Interrupt handler
No
Signal handler
Yes
Thread
Yes
See also:
errno, cfgetispeed(), cfsetispeed(), cfsetospeed(), tcgetattr(), tcsetattr(), termios
June 19, 2012
QNX Neutrino Functions and Macros
185
cfgopen()
© 2012, QNX Software Systems Limited
Open a configuration file
Synopsis:
#include <cfgopen.h>
int cfgopen( const char * path,
unsigned flags,
const char * historical,
char * namebuf ,
int nblen );
Arguments:
path
The name of the configuration file that you want to open.
flags
Flags that control the opening; see below.
historical
A optional file to open as a last resort if none of the criteria for finding
the path is met. This string works like a path search order, and lets you
search more than one location. You can also specify %H to substitute the
hostname value into the string. Specify NULL to ignore this option.
namebuf
A buffer to save the pathname in. Specify NULL to ignore this option.
nblen
The length of the buffer pointed to by namebuf . Specify 0 to ignore this
option.
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
This function is in libc.a, but not in libc.so (in order to save space).
Description:
The cfgopen() function opens the configuration file named by path. This function is a
cover function for open() that searches several default system locations for your files,
based on specified characteristics.
The value of flags correspond to, and have similar limitations of, the standard open()
flags. The flags value is constructed by the bitwise ORing of values from the following
list, defined in the <cfgopen.h> header file. Applications must specify exactly one of
these file-access modes in the value of flag:
186
CFGFILE_RDONLY
Open for reading only.
CFGFILE_RDWR
Open for reading and writing.
QNX Neutrino Functions and Macros
June 19, 2012
cfgopen()
© 2012, QNX Software Systems Limited
CFGFILE_WRONLY
Open for writing only.
You can also include any combination of these bits in the value of flag:
CFGFILE_APPEND
If set, the file offset is set to the end of the file prior to each
write.
CFGFILE_CREAT
If the file doesn’t exist, it’s created with mode 0644, the file’s
user ID is set to the effective user ID of the process, and the
group ID is set to the effective group ID of the process or the
group ID of the file’s parent directory (see chmod()).
CFGFILE_EXCL
If CFGFILE_EXCL and CFGFILE_CREAT are set, and the file
exists, cfgopen() fails. The check for the existence of the file
and the creation of the file if it doesn’t exist is atomic with
respect to other processes attempting the same operation with
the same filename. Specifying CFGFILE_EXCL without
CFGFILE_CREAT has no effect.
CFGFILE_TRUNC
If the file exists and is a regular file, and the file is successfully
opened CFGFILE_WRONLY or CFGFILE_RDWR, the file
length is truncated to zero and the mode and owner are left
unchanged. CFGFILE_TRUNC has no effect on FIFO or block
or character special files or directories. Using
CFGFILE_TRUNC with CFGFILE_RDONLY has no effect.
Search condition flags
In order to hint to the function where it should access or construct (in the case of
CFGFILE_CREAT) path, there are several bits that you can specify and OR into flags.
When specified, the bits are accessed using the following search order:
1
CFGFILE_USER_NODE
$HOME/.cfg/node_name/path
2
CFGFILE_USER
$HOME/.cfg/path
3
CFGFILE_NODE
/etc/host_cfg/node_name/path
4
CFGFILE_GLOBAL
path
where node_name is the value you get by calling confstr() for CS_HOSTNAME.
June 19, 2012
QNX Neutrino Functions and Macros
187
cfgopen()
© 2012, QNX Software Systems Limited
If the directory /etc/host_cfg doesn’t exist on the system, the following flags are
transformed automatically:
• CFGFILE_USER_NODE becomes CFGFILE_USER
• CFGFILE_NODE becomes CFGFILE_GLOBAL
When creating a file or opening a file for writing, you can specify only one of the
above location flags. Set CFGFILE_NOFD when you need only the pathname, not the
file descriptor. If a directory path doesn’t exist when a file is opened for creation,
cfgopen() attempts to create the path.
Returns:
A valid file descriptor if CFGFILE_NOFD isn’t specified, a nonnegative value if
CFGFILE_NOFD is specified, or -1 if an error occurs.
Classification:
QNX Neutrino
Safety
Cancellation point
Yes
Interrupt handler
No
Signal handler
Yes
Thread
Yes
See also:
confstr(), fcfgopen(), open()
mib.txt, snmpd.conf in the Utilities Reference
188
QNX Neutrino Functions and Macros
June 19, 2012
cfmakeraw()
© 2012, QNX Software Systems Limited
Set terminal attributes
Synopsis:
#include <termios.h>
int cfmakeraw( struct termios * termios_p );
Arguments:
termios_p
A pointer to a termios structure that describes the terminal’s control
attributes.
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
The cfmakeraw() function sets the terminal attributes as follows:
termios_p->c_iflag
termios_p->c_oflag
termios_p->c_lflag
termios_p->c_cflag
termios_p->c_cflag
&=
&=
&=
&=
|=
˜(IGNBRK|BRKINT|PARMRK|ISTRIP|INLCR|IGNCR|ICRNL|IXON);
˜OPOST;
˜(ECHO|ECHONL|ICANON|ISIG|IEXTEN);
˜(CSIZE|PARENB);
CS8;
You can get a valid termios control structure for an opened device by calling
tcgetattr().
Returns:
0
Success.
-1
An error occurred (errno indicates the reason).
Classification:
Unix
Safety
June 19, 2012
Cancellation point
No
Interrupt handler
No
Signal handler
Yes
Thread
Yes
QNX Neutrino Functions and Macros
189
cfmakeraw()
© 2012, QNX Software Systems Limited
See also:
errno, cfgetispeed(), cfgetospeed(), cfsetispeed(), cfsetospeed(), tcgetattr(), tcsetattr(),
termios
190
QNX Neutrino Functions and Macros
June 19, 2012
cfree()
© 2012, QNX Software Systems Limited
Free allocated memory
Synopsis:
#include <malloc.h>
int cfree( void *ptr );
Arguments:
ptr
A pointer to the block of memory that you want to free. It’s safe to call cfree()
with a NULL pointer.
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
The cfree() function deallocates the memory block specified by ptr, which was
previously returned by a call to calloc(), malloc() or realloc().
Returns:
1
Classification:
Unix
Safety
Cancellation point
No
Interrupt handler
No
Signal handler
No
Thread
Yes
Caveats:
Calling cfree() on a pointer already deallocated by a call to cfree(), free(), or realloc()
could corrupt the memory allocator’s data structures.
See also:
alloca(), calloc(), free(), malloc(), realloc(), sbrk()
June 19, 2012
QNX Neutrino Functions and Macros
191
cfsetispeed()
© 2012, QNX Software Systems Limited
Set the input baud rate in a termios structure
Synopsis:
#include <termios.h>
int cfsetispeed( struct termios* termios_p,
speed_t speed );
Arguments:
termios_p
A pointer to a termios structure that describes the terminal’s control
attributes.
speed
The new speed. Valid values for speed are defined in <termios.h>.
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
The cfsetispeed() function sets the input baud rate within the termios structure
pointed to by termios_p to be speed.
You can get a valid termios control structure for an opened device by calling
tcgetattr().
• The new baud rate isn’t effective until you call tcsetattr() with this modified
termios structure.
• Attempts to set baud rates to values that aren’t supported by the hardware are
ignored, and cause tcsetattr() to return an error, but cfsetispeed() doesn’t indicate
an error.
• Attempts to set input baud rates to a value that’s different from the output baud
rate, when the hardware doesn’t support split baud rates, cause the input baud rate
to be ignored, but no error is generated.
Returns:
192
0
Success.
-1
An error occurred (errno is set).
QNX Neutrino Functions and Macros
June 19, 2012
cfsetispeed()
© 2012, QNX Software Systems Limited
Errors:
EINVAL
ENOTTY
One of the arguments is invalid.
This function isn’t supported by the system.
Examples:
#include
#include
#include
#include
<termios.h>
<fcntl.h>
<unistd.h>
<stdlib.h>
int main( void )
{
int fd;
struct termios termios_p;
speed_t speed;
fd = open( "/dev/ser1", O_RDWR );
tcgetattr( fd, &termios_p);
/*
*
Set input baud rate
*/
speed = 9600;
cfsetispeed( &termios_p, speed );
tcsetattr( fd, TCSADRAIN, &termios_p);
close( fd );
return EXIT_SUCCESS;
}
Classification:
POSIX 1003.1
Safety
Cancellation point
No
Interrupt handler
No
Signal handler
Yes
Thread
Yes
See also:
errno, cfgetispeed(), cfgetospeed(), cfsetospeed(), tcgetattr(), tcsetattr(), termios
June 19, 2012
QNX Neutrino Functions and Macros
193
cfsetospeed()
© 2012, QNX Software Systems Limited
Set the output baud rate in a termios structure
Synopsis:
#include <termios.h>
int cfsetospeed( struct termios *termios_p,
speed_t speed );
Arguments:
termios_p
A pointer to a termios structure that describes the terminal’s control
attributes.
speed
The new speed. Valid values for speed are defined in <termios.h>.
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
The cfsetospeed() function sets the output baud rate within the termios structure
pointed to by termios_p to be speed.
You can get a valid termios control structure for an opened device by calling
tcgetattr().
• The new baud rate isn’t effective until you call tcsetattr(), with this modified
termios structure.
• Attempts to set baud rates to values that aren’t supported by the hardware are
ignored, and cause tcsetattr() to return an error, but cfsetospeed() doesn’t indicate
an error.
Setting the output baud rate to B0 causes the connection to be dropped. If termios_p
represents a modem, the modem control lines will be turned off.
Returns:
0
Success.
-1
An error occurred (errno indicates the reason).
Errors:
194
EINVAL
One of the arguments is invalid.
ENOTTY
This function isn’t supported by the system.
QNX Neutrino Functions and Macros
June 19, 2012
cfsetospeed()
© 2012, QNX Software Systems Limited
Examples:
#include
#include
#include
#include
<termios.h>
<fcntl.h>
<unistd.h>
<stdlib.h>
int main( void )
{
int fd;
struct termios termios_p;
speed_t speed;
fd = open( "/dev/ser1", O_RDWR );
tcgetattr( fd, &termios_p);
/*
*
Set output baud rate
*/
speed = B9600;
cfsetospeed( &termios_p, speed );
tcsetattr( fd, TCSADRAIN, &termios_p);
close( fd );
return EXIT_SUCCESS;
}
Classification:
POSIX 1003.1
Safety
Cancellation point
No
Interrupt handler
No
Signal handler
Yes
Thread
Yes
See also:
errno, cfgetispeed(), cfgetospeed(), cfsetispeed(), tcgetattr(), tcsetattr(), termios
June 19, 2012
QNX Neutrino Functions and Macros
195
ChannelCreate(), ChannelCreate_r()
© 2012, QNX Software Systems Limited
Create a communications channel
Synopsis:
#include <sys/neutrino.h>
int ChannelCreate( unsigned flags );
int ChannelCreate_r( unsigned flags );
Arguments:
flags
Flags that can be used to request notification pulses from the kernel or
request other changes in behavior; a combination of the following:
• _NTO_CHF_COID_DISCONNECT
• _NTO_CHF_DISCONNECT
• _NTO_CHF_FIXED_PRIORITY
• _NTO_CHF_NET_MSG
• _NTO_CHF_REPLY_LEN
• _NTO_CHF_SENDER_LEN
• _NTO_CHF_THREAD_DEATH
• _NTO_CHF_UNBLOCK
For more information, see below.
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
The ChannelCreate() and ChannelCreate_r() kernel calls create a channel that can be
used to receive messages and pulses. Once created, the channel is owned by the
process and isn’t bound to the creating thread.
These functions are identical, except in the way they indicate errors. See the Returns
section for details.
Threads wishing to communicate with the channel attach to it by calling
ConnectAttach(). The threads may be in the same process, or in another process on the
same node (or a remote node if the network manager is running).
196
QNX Neutrino Functions and Macros
June 19, 2012
© 2012, QNX Software Systems Limited
ChannelCreate(), ChannelCreate_r()
If a process wants other processes to communicate with it, it typically uses
name_attach() to create a channel and associate a name with it, and the sender process
uses name_open() to locate that name and create a connection to it.
Once attached, these threads use MsgSendv() or MsgSendPulse() to enqueue messages
and pulses on the channel. Messages and pulses are enqueued in priority order.
To dequeue and read messages and pulses from a channel, use MsgReceivev(). Any
number of threads may call MsgReceivev() at the same time, in which case they block
and queue (if no messages or pulses are waiting) for a message or pulse to arrive. A
multi-threaded I/O manager typically creates multiple threads and has them all
RECEIVE-blocked on the channel.
The return value of ChannelCreate() is a channel ID, an int taken from a channel
vector on the process. Most managers use a single channel for most, if not all, their
communications with clients. Additional channels can be used as special channels for
information.
By default, when a message is received from a channel, the thread priority of the
receiver is set to match that of the thread that sent the message. This basic priority
inheritance prevents priority inversion. If a message arrives at a channel and there’s no
thread waiting to receive it, the system boosts (if necessary) all threads in the process
that have received a message from the channel in the past. This boost prevents a
priority inversion of the client in the case where all threads are currently working on
behalf of other clients, perhaps at a lower priority. When a thread is first created, it
isn’t associated with a channel until it does a MsgReceivev() on it. In the case of
multiple channels, a thread is associated with the last channel it received from.
After receiving a message, a thread can dissociate itself from the channel by calling
MsgReceivev() with a -1 for the channel ID. Priority inheritance can be disabled by
setting _NTO_CHF_FIXED_PRIORITY in the flags argument. In this case a thread’s
priority isn’t affected by messages it receives on a channel.
A manager typically involves the following loop. There may be one or more threads in
the loop at a time. Typically your program calls ChannelCreate() only once, and all
threads block on that channel.
iov_t iov;
...
SETIOV( &iov, &msg, sizeof( msg ) );
...
chid = ChannelCreate(flags);
...
for(;;) {
/*
Here’s a one-part message; you could just as
easily receive a 20-part message by filling in the
iov appropriately.
*/
rcvid = MsgReceivev(chid, &iov, 1, &info);
/* msg is filled in by MsgReceivev() */
switch(msg.type) {
June 19, 2012
QNX Neutrino Functions and Macros
197
ChannelCreate(), ChannelCreate_r()
© 2012, QNX Software Systems Limited
...
}
/* iov could be filled in again to point to a new message */
MsgReplyv(rcvid, status, iov, 1);
}
Some of the channel flags in the flags argument request changes from the default
behavior; others request notification pulses from the kernel. The pulses are received by
MsgReceivev() on the channel and are described by a _pulse structure.
The channel flags and (where appropriate) associated values for the pulse’s code and
value are described below.
_NTO_CHF_COID_DISCONNECT
Pulse code:
_PULSE_CODE_COIDDEATH
Pulse value:
Connection ID (coid) of a connection that was attached to a
destroyed channel.
Deliver a pulse to this channel for each connection that belongs to the calling process
when the channel that the connection is attached to is destroyed. Only one channel per
process can have this flag set.
If a channel has one or both of _NTO_CHF_COID_DISCONNECT or
_NTO_CHF_THREAD_DEATH set, neither flag may be set for any other channel in the
process.
If a server exits or closes its channel at more or less the same time that the client closes
a connection to the channel, the kernel might or might not send a
_PULSE_CODE_COIDDEATH pulse to the client. If the client then opens a new
connection to another server before getting the pulse, the pulse will seem to indicate
that it’s the new server that has died. Your code for handling the
_PULSE_CODE_COIDDEATH pulse needs to include something like this:
void
got_pulse(struct _pulse *pulse) {
if(pulse->type == _PULSE_CODE_COIDDEATH) {
int coid = pulse->value.sival_int;
if(ConnectServerInfo(0, coid, NULL) != coid) {
// server’s really gone, so clean up the connection state
} else {
// stale pulse; probably can ignore it
}
}
}
198
QNX Neutrino Functions and Macros
June 19, 2012
ChannelCreate(), ChannelCreate_r()
© 2012, QNX Software Systems Limited
_NTO_CHF_DISCONNECT
Pulse code:
_PULSE_CODE_DISCONNECT
Pulse value:
None
Deliver a pulse when all connections from a process are detached (e.g. close(),
ConnectDetach(), name_close()). If a process dies without detaching all its
connections, the kernel detaches them from it. When this flag is set, the server must
call ConnectDetach( scoid ) where scoid is the server connection ID in the pulse
message. Failure to do so leaves an invalid server connection ID that can’t be reused.
Over time, the server may run out of available IDs. If this flag isn’t set, the kernel
removes the server connection ID automatically, making it available for reuse.
_NTO_CHF_FIXED_PRIORITY
Suppress priority inheritance when receiving messages. Receiving threads won’t
change their priorities to those of the sending threads. If you’re using adaptive
partitioning, the receiving threads won’t run in the sending threads’ partitions.
_NTO_CHF_NET_MSG
Reserved for the io_pkt* resource manager.
_NTO_CHF_REPLY_LEN
Request that the length of the reply be included in the dstmsglen member of the
_msg_info structure that MsgReceivev() fills in. The dstmsglen member is valid only
if you set this channel flag when you create the channel.
_NTO_CHF_SENDER_LEN
Request that the length of the source message be included in the srcmsglen member of
the _msg_info, structure that MsgReceivev() fills in. The srcmsglen member is valid
only if you set this channel flag when you create the channel.
_NTO_CHF_THREAD_DEATH
Pulse code:
_PULSE_CODE_THREADDEATH
Pulse value:
Thread ID (tid)
Deliver a pulse on the death of any thread in the process that owns the channel. Only
one channel per process can have this flag set.
If a channel has one or both of _NTO_CHF_COID_DISCONNECT or
_NTO_CHF_THREAD_DEATH set, neither flag may be set for any other channel in the
process.
June 19, 2012
QNX Neutrino Functions and Macros
199
ChannelCreate(), ChannelCreate_r()
© 2012, QNX Software Systems Limited
_NTO_CHF_UNBLOCK
Pulse code:
_PULSE_CODE_UNBLOCK
Pulse value:
Receive ID (rcvid)
In most cases, you’ll set the _NTO_CHF_UNBLOCK flag.
Deliver a pulse when a thread that’s REPLY-blocked on a channel attempts to unblock
before its message is replied to. This occurs between the time of a MsgReceivev() and
a MsgReplyv() by the server. The sending thread may be unblocked because of a signal
or a kernel timeout.
If the sending thread unblocks, MsgReplyv() fails. The manager may not be in a
position to handle this failure. It’s also possible that the client will die because of the
signal and never send another message. If the manager is holding onto resources for
the client (such as an open file), it may want to receive notification that the client
wants to break out of its MsgSendv().
Setting the _NTO_CHF_UNBLOCK bit in flags prevents a thread that’s in the
REPLY-blocked state from unblocking. Instead, a pulse is sent to the channel,
informing the manager that the client wishes to unblock. In the case of a signal, the
signal will be pending on the client thread. When the manager replies, the client is
unblocked and at that point, any pending signals are acted upon. From the client’s
point of view, its MsgSendv() will have completed normally and any signal will have
arrived on the opcode following the successful kernel call.
When the manager receives the pulse, it can do one of these things:
• If it believes that it will be replying shortly, it can discard the pulse, resulting in a
small latency in the unblocking, or it can signal the client. A short blocking request
to a filesystem often takes this approach.
• If the reply is going to take some time or an unknown amount of time, the manager
should cancel the current operation and reply back with an error or whatever data is
available at this time in the reply message to the client thread. A request to a device
manager waiting for input would take this approach.
Blocking states
These calls don’t block.
Returns:
The only difference between these functions is the way they indicate errors:
200
ChannelCreate()
The channel ID of the newly created channel. If an error occurs,
the function returns -1 and sets errno.
QNX Neutrino Functions and Macros
June 19, 2012
ChannelCreate(), ChannelCreate_r()
© 2012, QNX Software Systems Limited
ChannelCreate_r()
Errors:
The channel ID of the newly created channel. This function
does NOT set errno. If an error occurs, the function returns the
negative of a value from the Errors section.
EAGAIN
All kernel channel objects are in use.
EBUSY
The _NTO_CHF_COID_DISCONNECT or the
_NTO_CHF_THREAD_DEATH flag was given and another channel
belonging to this process already has the same flag set.
Classification:
QNX Neutrino
Safety
Cancellation point
No
Interrupt handler
No
Signal handler
Yes
Thread
Yes
See also:
ChannelDestroy(), close(), ConnectAttach(), ConnectDetach(), _msg_info,
MsgReceivev(), MsgReplyv(), MsgSendv(), MsgSendPulse(), name_attach(),
name_close(), name_open(), _pulse
Message Passing chapter of Getting Started with QNX Neutrino
June 19, 2012
QNX Neutrino Functions and Macros
201
ChannelDestroy(), ChannelDestroy_r()
© 2012, QNX Software Systems Limited
Destroy a communications channel
Synopsis:
#include <sys/neutrino.h>
int ChannelDestroy( int chid );
int ChannelDestroy_r( int chid );
Arguments:
chid
The channel ID, returned by ChannelCreate(), of the channel that you want
to destroy.
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
These kernel calls remove a channel specified by the channel ID chid argument. Once
destroyed, any attempt to receive messages or pulses on the channel will fail. Any
threads that are blocked on the channel by calling MsgReceivev() or MsgSendv() will
be unblocked and return with an error.
The ChannelDestroy() and ChannelDestroy_r() functions are identical except in the
way they indicate errors. See the Returns section for details.
When the channel is destroyed, all server connection IDs become invalid. The client
connections are also marked invalid but remain in existence until the client removes
them by calling ConnectDetach(). An attempt by the client to use one of these invalid
connections using MsgSendv() or MsgSendPulse() will return with an error.
A server typically destroys its channels prior to its termination. If it fails to do so, the
kernel destroys them automatically when the process dies.
Blocking states
These calls don’t block.
Returns:
The only difference between these functions is the way they indicate errors:
ChannelDestroy()
If an error occurs, the function returns -1 and sets errno. Any
other value returned indicates success.
ChannelDestroy_r() EOK is returned on success. This function does NOT set errno.
If an error occurs, the function may return any value in the
Errors section.
202
QNX Neutrino Functions and Macros
June 19, 2012
ChannelDestroy(), ChannelDestroy_r()
© 2012, QNX Software Systems Limited
Errors:
EINVAL
The channel specified by chid doesn’t exist.
Classification:
QNX Neutrino
Safety
Cancellation point
No
Interrupt handler
No
Signal handler
Yes
Thread
Yes
See also:
ChannelCreate(), MsgReceivev()
Message Passing chapter of Getting Started with QNX Neutrino
June 19, 2012
QNX Neutrino Functions and Macros
203
chdir()
© 2012, QNX Software Systems Limited
Change the current working directory
Synopsis:
#include <unistd.h>
int chdir( const char* path );
Arguments:
path
The new current working directory.
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
The chdir() function changes the current working directory to path, which can be
relative to the current working directory or an absolute path name.
Returns:
0
Success.
-1
An error occurred (errno is set).
Errors:
EACCES
Search permission is denied for a component of path.
ELOOP
Too many levels of symbolic links or prefixes.
ENAMETOOLONG
The path argument is longer than PATH_MAX, or a pathname
component is longer than NAME_MAX.
204
ENOENT
The specified path doesn’t exist, or path is an empty string.
ENOMEM
There wasn’t enough memory to allocate a control structure.
ENOSYS
The chdir() function isn’t implemented for the filesystem specified in
path.
ENOTDIR
A component of path is not a directory.
QNX Neutrino Functions and Macros
June 19, 2012
chdir()
© 2012, QNX Software Systems Limited
Examples:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main( int argc, char* argv[] )
{
if( argc != 2 ) {
fprintf( stderr, "Use: cd <directory>\n" );
return EXIT_FAILURE;
}
if( chdir( argv[1] ) == 0 ) {
printf( "Directory changed to %s\n", argv[1] );
return EXIT_SUCCESS;
} else {
perror( argv[1] );
return EXIT_FAILURE;
}
}
Classification:
POSIX 1003.1
Safety
Cancellation point
No
Interrupt handler
No
Signal handler
Yes
Thread
Yes
Caveats:
There’s only one current working directory per process. In a multithreaded
application, any thread calling chdir() will change the current working directory for all
threads in that process.
See also:
errno, fchdir(), getcwd(), mkdir(), rmdir()
June 19, 2012
QNX Neutrino Functions and Macros
205
chmod()
© 2012, QNX Software Systems Limited
Change the permissions for a file
Synopsis:
#include <sys/types.h>
#include <sys/stat.h>
int chmod( const char * path,
mode_t mode );
Arguments:
path
The name of the file whose permissions you want to change.
mode
The new permissions for the file. For more information, see “Access
permissions” in the documentation for stat().
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
The chmod() function changes S_ISUID, S_ISGID, S_ISVTX and the file permission
bits of the file specified by the pathname pointed to by path to the corresponding bits
in the mode argument. The application must ensure that the effective user ID of the
process matches the owner of the file or the process has appropriate privileges to do
this.
If a directory is writable and the sticky bit (S_ISVTX) is set on the directory, a process
can remove or rename a file within that directory only if one or more of the following
is also true:
• The effective user ID of the process matches the file’s owner ID.
• The effective user ID of the process matches the directory’s owner ID.
• The file is writable by the effective user ID of the process.
• The user is a superuser (effective user ID of 0).
If a directory has the set-group ID bit set, a file created in that directory will have the
same group ID as that directory. Otherwise, the newly created file’s group ID is set to
the effective group ID of the creating process.
If the calling process doesn’t have appropriate privileges, and if the group ID of the
file doesn’t match the effective group ID, and the file is a regular file, bit S_ISGID
(set-group-ID on execution) in the file’s mode is cleared on a successful return from
chmod().
If the effective user ID of the calling process is equal to the file owner, or the calling
process has appropriate privileges (for example, it belongs to the superuser), chmod()
206
QNX Neutrino Functions and Macros
June 19, 2012
chmod()
© 2012, QNX Software Systems Limited
sets S_ISUID, S_ISGID and the file permission bits, defined in the <sys/stat.h>
header file, from the corresponding bits in the mode argument. These bits define
access permissions for the user associated with the file, the group associated with the
file and all others.
This call has no effect on file descriptors for files that are already open.
If chmod() succeeds, the st_ctime field of the file is marked for update.
Returns:
0
Success.
-1
An error occurred (errno is set).
Errors:
EACCES
Search permission is denied on a component of the path prefix.
ELOOP
Too many levels of symbolic links or prefixes.
ENAMETOOLONG
The length of the path string exceeds PATH_MAX, or a pathname
component is longer than NAME_MAX.
ENOTDIR
A component of the path prefix isn’t a directory.
ENOENT
The file doesn’t exist, or the path arguments points to an empty string.
ENOSYS
The chmod() function isn’t implemented for the filesystem specified in
path.
EPERM
The effective user ID doesn’t match the owner of the file, and the
calling process doesn’t have appropriate privileges.
EROFS
The file resides on a read-only filesystem.
Examples:
/*
* Change the permissions of a list of files
* to by read/write by the owner only
*/
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
int main( int argc, char **argv )
{
int i;
int ecode = 0;
for( i = 1; i < argc; i++ ) {
if( chmod( argv[i], S_IRUSR | S_IWUSR ) == -1 ) {
perror( argv[i] );
June 19, 2012
QNX Neutrino Functions and Macros
207
chmod()
© 2012, QNX Software Systems Limited
ecode++;
}
}
return ecode;
}
Classification:
POSIX 1003.1
Safety
Cancellation point
No
Interrupt handler
No
Signal handler
Yes
Thread
Yes
See also:
chown(), errno, fchmod(), fchown(), fstat(), open(), stat()
208
QNX Neutrino Functions and Macros
June 19, 2012
chown()
© 2012, QNX Software Systems Limited
Change the user ID and group ID of a file
Synopsis:
#include <sys/types.h>
#include <unistd.h>
int chown( const char * path,
uid_t owner,
gid_t group );
Arguments:
path
The name of the file whose ownership you want to change.
owner
The user ID of the new owner.
group
The group ID of the new owner.
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
The chown() function changes the user ID and group ID of the file specified by path to
be the numeric values contained in owner and group, respectively.
If the named file is a symbolic link, chown() changes the ownership of the file or
directory to which the symbolic link refers; lchown() changes the ownership of the
symbolic link file itself.
Only processes with an effective user ID equal to the user ID of the file or with
appropriate privileges (for example, the superuser) may change the ownership of a file.
In QNX Neutrino, the _POSIX_CHOWN_RESTRICTED flag (tested via the
_PC_CHOWN_RESTRICTED flag in pathconf()), is enforced for path. This means that
only the superuser may change the ownership or the group of a file to anyone. Normal
users can’t give a file away to another user by changing the file ownership, nor to
another group by changing the group ownership.
If the path argument refers to a regular file, the set-user-ID (S_ISUID) and
set-group-ID (S_ISGID) bits of the file mode are cleared, if the function is successful.
If chown() succeeds, the st_ctime field of the file is marked for update.
Returns:
0
Success.
-1 (no changes were made in the user ID and group ID of the file).
An error occurred (errno is set).
June 19, 2012
QNX Neutrino Functions and Macros
209
chown()
© 2012, QNX Software Systems Limited
Errors:
EACCES
Search permission is denied on a component of the path prefix.
ELOOP
Too many levels of symbolic links or prefixes.
ENAMETOOLONG
The length of the path string exceeds PATH_MAX, or a pathname
component is longer than NAME_MAX.
ENOENT
A component of the path prefix doesn’t exist, or the path arguments
points to an empty string.
ENOSYS
The chown() function isn’t implemented for the filesystem specified in
path.
ENOTDIR
A component of the path prefix isn’t a directory.
EPERM
The effective user ID doesn’t match the owner of the file, or the calling
process doesn’t have appropriate privileges.
EROFS
The named file resides on a read-only filesystem.
Examples:
/*
* Change the ownership of a list of files
* to the current user/group
*/
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
int main( int argc, char** argv )
{
int i;
int ecode = 0;
for( i = 1; i < argc; i++ ) {
if( chown( argv[i], getuid(), getgid() ) == -1 ) {
perror( argv[i] );
ecode++;
}
}
exit( ecode );
}
Classification:
POSIX 1003.1
210
QNX Neutrino Functions and Macros
June 19, 2012
chown()
© 2012, QNX Software Systems Limited
Safety
Cancellation point
No
Interrupt handler
No
Signal handler
Yes
Thread
Yes
See also:
chmod(), errno, fchown(), fstat(), lchown(), open(), stat()
June 19, 2012
QNX Neutrino Functions and Macros
211
chroot()
© 2012, QNX Software Systems Limited
Change the root directory
Synopsis:
#include <unistd.h>
int chroot( const char *path );
Arguments:
path
The name of the new root directory. This can include a network root (e.g.
/net/node_name).
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
The chroot() function causes the path directory to become the root directory, the
starting point for path searches for path names beginning with /. The user’s working
directory is unaffected.
The .. entry in the root directory is interpreted to mean the root directory itself. Thus,
you can’t use .. to access files outside the subtree rooted at the root directory.
Returns:
0
Success.
-1
An error occurred; errno is set.
Errors:
212
EACCES
Search permission is denied for a component of path.
EBADF
The descriptor isn’t valid.
EFAULT
The path argument points to an illegal address.
EINTR
A signal was caught during the chroot() function.
EIO
An I/O error occurred while reading from or writing to the
filesystem.
ELOOP
Too many symbolic links were encountered in translating path.
EMULTIHOP
Components of path require hopping to multiple remote machines,
and the filesystem type doesn’t allow it.
QNX Neutrino Functions and Macros
June 19, 2012
chroot()
© 2012, QNX Software Systems Limited
ENAMETOOLONG
ENOENT
The length of the path argument exceeds {PATH_MAX}, or the
length of a path component exceeds {NAME_MAX} while
{_POSIX_NO_TRUNC} is in effect.
The named directory doesn’t exist or is a null pathname.
ENOLINK
The path points to a remote machine and the link to that machine is
no longer active.
ENOTDIR
Any component of the path name isn’t a directory.
EPERM
The effective user of the calling process isn’t the superuser.
Classification:
Legacy Unix
Safety
Cancellation point
No
Interrupt handler
No
Signal handler
No
Thread
Yes
See also:
chdir()
June 19, 2012
QNX Neutrino Functions and Macros
213
chsize()
© 2012, QNX Software Systems Limited
Change the size of a file
Synopsis:
#include <unistd.h>
int chsize( int filedes,
long size );
Arguments:
filedes
A file descriptor for the file whose size you want to change.
size
The new size of the file, in bytes.
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
The chsize() function extends or truncates the file specified by filedes to size bytes The
file is padded with NUL (’\0’) characters if it needs to be extended.
The chsize() function ignores advisory locks that may have been set with the fcntl()
function.
Returns:
0
Success.
-1
An error occurred.
Errors:
EBADF
The filedes argument isn’t a valid file descriptor, or the file isn’t opened
for writing.
ENOSPC
There isn’t enough space left on the device to extend the file.
ENOSYS
The chsize() function isn’t implemented for the filesystem specified by
filedes.
Examples:
#include
#include
#include
#include
#include
214
<stdlib.h>
<stdio.h>
<unistd.h>
<fcntl.h>
<sys/stat.h>
QNX Neutrino Functions and Macros
June 19, 2012
chsize()
© 2012, QNX Software Systems Limited
int main( void )
{
int filedes;
filedes= open( "file", O_RDWR | O_CREAT,
S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP );
if( filedes!= -1 ) {
if( chsize( filedes, 32 * 1024L ) != 0 ) {
printf( "Error extending file\n" );
}
close( filedes);
return EXIT_SUCCESS;
}
return EXIT_FAILURE;
}
Classification:
QNX 4
Safety
Cancellation point
Yes
Interrupt handler
No
Signal handler
Yes
Thread
Yes
See also:
close(), creat(), errno, ftruncate(), open()
June 19, 2012
QNX Neutrino Functions and Macros
215
clearenv()
© 2012, QNX Software Systems Limited
Clear the environment
Synopsis:
#include <stdlib.h>
int clearenv( void );
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
The clearenv() function clears the environment area; no environment variables are
defined immediately after the clearenv() call.
Note that clearenv() clears the following environment variables, which may then affect
the operation of other library functions such as spawnp():
• PATH
• SHELL
• TERM
• TERMINFO
• LINES
• COLUMNS
• TZ
Returns:
0
Success.
-1
An error occurred (errno is set).
Errors:
ENOMEM
Not enough memory to allocate a control structure.
Examples:
Clear the entire environment and set up a new TZ environment variable:
#include <stdio.h>
#include <stdlib.h>
int main( void )
{
216
QNX Neutrino Functions and Macros
June 19, 2012
clearenv()
© 2012, QNX Software Systems Limited
if( clearenv() != 0 ) {
puts( "Unable to clear the environment" );
return EXIT_FAILURE;
}
setenv( "TZ", "EST5EDT", 0 );
return EXIT_SUCCESS;
}
Classification:
QNX 4
Safety
Cancellation point
No
Interrupt handler
No
Signal handler
No
Thread
Yes
Caveats:
The clearenv() function manipulates the environment pointed to by the global environ
variable.
See also:
environ, errno, execl(), execle(), execlp(), execlpe(), execv(), execve(), execvp(),
execvpe(), getenv(), putenv(), searchenv(), setenv(), spawn(), spawnl(), spawnle(),
spawnlp(), spawnlpe(), spawnp(), spawnv(), spawnve(), spawnvp(), spawnvpe(),
system(), unsetenv()
June 19, 2012
QNX Neutrino Functions and Macros
217
clearerr()
© 2012, QNX Software Systems Limited
Clear a stream’s end-of-file and error flags
Synopsis:
#include <stdio.h>
void clearerr( FILE *fp );
Arguments:
fp
The stream for which you want to clear the flags.
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
The clearerr() function clears the end-of-file and error flags for the stream specified by
fp.
These indicators are also cleared when the file is opened, or by an explicit call to
clearerr() or rewind().
Examples:
#include <stdio.h>
#include <stdlib.h>
int main( void )
{
FILE *fp;
int c;
c = ’J’;
fp = fopen( "file", "w"
if( fp != NULL ) {
fputc( c, fp );
if( ferror( fp ) ) {
clearerr( fp );
fputc( c, fp );
}
}
);
/* if error
*/
/* clear the error */
/* and retry it
*/
fclose( fp );
return EXIT_SUCCESS;
}
Classification:
ANSI, POSIX 1003.1
218
QNX Neutrino Functions and Macros
June 19, 2012
clearerr()
© 2012, QNX Software Systems Limited
Safety
Cancellation point
No
Interrupt handler
No
Signal handler
No
Thread
Yes
See also:
feof(), ferror(), fopen(), perror(), rewind()
June 19, 2012
QNX Neutrino Functions and Macros
219
clock()
© 2012, QNX Software Systems Limited
Return the number of clock ticks used by the program
Synopsis:
#include <time.h>
clock_t clock( void );
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
The clock() function returns the number of clock ticks of processor time used by the
program since it started executing. You can convert the number of ticks into seconds
by dividing by the value CLOCKS_PER_SEC.
In a multithreaded program, clock() returns the time used by all threads in the
application; clock() returns the time since the program started, not the time since a
specific thread started.
Returns:
The number of clock ticks, or (clock_t) -1 if the number of ticks couldn’t be
determined or exceeds the maximum value that the clock_t type can represent.
Examples:
#include
#include
#include
#include
<stdio.h>
<math.h>
<time.h>
<stdlib.h>
void compute( void )
{
int i, j;
double x;
x = 0.0;
for( i = 1; i <= 100; i++ ) {
for( j = 1; j <= 100; j++ ) {
x += sqrt( (double) i * j );
}
}
printf( "%16.7f\n", x );
}
int main( void )
{
clock_t start_time, end_time;
start_time = clock();
compute();
220
QNX Neutrino Functions and Macros
June 19, 2012
clock()
© 2012, QNX Software Systems Limited
end_time = clock();
printf( "Execution time was %lu seconds\n",
(long) ((end_time - start_time) / CLOCKS_PER_SEC) );
return EXIT_SUCCESS;
}
Classification:
ANSI, POSIX 1003.1
Safety
Cancellation point
No
Interrupt handler
No
Signal handler
Yes
Thread
Yes
See also:
asctime(), asctime_r(), ctime(), difftime(), gmtime(), localtime(), localtime_r(),
mktime(), strftime(), time(), tzset()
Clocks, Timers, and Getting a Kick Every So Often chapter of Getting Started with
QNX Neutrino
June 19, 2012
QNX Neutrino Functions and Macros
221
clock_getcpuclockid()
© 2012, QNX Software Systems Limited
Return the clock ID of the CPU-time clock from a specified process
Synopsis:
#include <sys/types.h>
#include <time.h>
#include <errno.h>
extern int clock_getcpuclockid(
pid_t pid,
clockid_t* clock_id );
Arguments:
pid
The process ID for the process whose clock ID you want to get.
clock_id
A pointer to a clockid_t object where the function can store the clock
ID.
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
The clock_getcpuclockid() function gets the clock ID of the CPU-time clock of the
process specified by pid and stores it in the object pointed to by clock_id. The
CPU-time clock represents the amount of time the process has spent actually running.
If pid is zero, the clock ID of the CPU-time clock of the process marking the call is
returned in clock_id.
A process always has permission to obtain the CPU-time clock ID of another process.
Returns:
0
Success.
ESRCH
No process can be found corresponding to the specified pid.
Examples:
#include
#include
#include
#include
<stdio.h>
<stdlib.h>
<time.h>
<errno.h>
int main( int argc, const char *argv[] )
{
clockid_t clk_id;
struct timespec tspec;
int pid;
222
QNX Neutrino Functions and Macros
June 19, 2012
clock_getcpuclockid()
© 2012, QNX Software Systems Limited
/* Get the amount of time that the kernel has spent running. */
pid = 1;
if (clock_getcpuclockid( pid, &clk_id) == 0)
{
if (clock_gettime( clk_id, &tspec ) != 0)
{
perror ("clock_gettime():");
}
else
{
printf ("CPU time for pid %d is %d seconds, %ld nanoseconds.\n",
pid, tspec.tv_sec, tspec.tv_nsec);
}
}
else
{
printf ("clock_getcpuclockid(): no process with ID %d.\n", pid);
}
return EXIT_SUCCESS;
}
Classification:
POSIX 1003.1 CPT
Safety
Cancellation point
No
Interrupt handler
No
Signal handler
Yes
Thread
Yes
See also:
clock_getres(), clock_gettime(), ClockId(), clock_settime(), pthread_getcpuclockid(),
timer_create()
Clocks, Timers, and Getting a Kick Every So Often chapter of Getting Started with
QNX Neutrino
June 19, 2012
QNX Neutrino Functions and Macros
223
clock_getres()
© 2012, QNX Software Systems Limited
Get the resolution of the clock
Synopsis:
#include <time.h>
int clock_getres( clockid_t clock_id,
struct timespec * res );
Arguments:
clock_id
The ID of the clock whose resolution you want to get; one of:
• CLOCK_REALTIME — the standard POSIX-defined clock. Timers
based on this clock wake up the processor if it’s in a power-saving
mode.
• CLOCK_SOFTTIME — this clock is active only when the processor
isn’t in a power-saving mode. For example, an application using a
CLOCK_SOFTTIME timer to sleep wouldn’t wake up the processor
when the application was due to wake up. This will allow the
processor to enter a power-saving mode.
While the processor isn’t in a power-saving mode,
CLOCK_SOFTTIME behaves the same as CLOCK_REALTIME.
• CLOCK_MONOTONIC — this clock always increases at a constant
rate and can’t be adjusted.
res
A pointer to a timespec structure in which clock_getres() can store the
resolution. The function sets the tv_sec member to 0, and the tv_nsec
member to be the resolution of the clock, in nanoseconds.
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
The clock_getres() function gets the resolution of the clock specified by clock_id and
puts it into the buffer pointed to by res.
Returns:
224
0
Success
-1
An error occurred (errno is set).
QNX Neutrino Functions and Macros
June 19, 2012
clock_getres()
© 2012, QNX Software Systems Limited
Errors:
EFAULT
EINVAL
A fault occurred trying to access the buffers provided.
Invalid clock_id.
Examples:
/*
* This program prints out the clock resolution.
*/
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main( void )
{
struct timespec res;
if ( clock_getres( CLOCK_REALTIME, &res) == -1 ) {
perror( "clock get resolution" );
return EXIT_FAILURE;
}
printf( "Resolution is %ld micro seconds.\n",
res.tv_nsec / 1000 );
return EXIT_SUCCESS;
}
Classification:
POSIX 1003.1 TMR
Safety
Cancellation point
No
Interrupt handler
No
Signal handler
Yes
Thread
Yes
See also:
clock_gettime(), clock_settime(), ClockPeriod(), timespec
Clocks, Timers, and Getting a Kick Every So Often chapter of Getting Started with
QNX Neutrino
June 19, 2012
QNX Neutrino Functions and Macros
225
clock_gettime()
© 2012, QNX Software Systems Limited
Get the current time of a clock
Synopsis:
#include <time.h>
int clock_gettime( clockid_t clock_id,
struct timespec * tp );
Arguments:
clock_id
The ID of the clock whose time you want to get; one of:
• CLOCK_REALTIME — the standard POSIX-defined clock. Timers
based on this clock wake up the processor if it’s in a power-saving
mode.
• CLOCK_SOFTTIME — this clock is active only when the processor
isn’t in a power-saving mode. For example, an application using a
CLOCK_SOFTTIME timer to sleep wouldn’t wake up the processor
when the application was due to wake up. This will allow the
processor to enter a power-saving mode.
While the processor isn’t in a power-saving mode,
CLOCK_SOFTTIME behaves the same as CLOCK_REALTIME.
• CLOCK_MONOTONIC — this clock always increases at a constant
rate and can’t be adjusted.
• A clock ID returned by clock_getcpuclockid() or
pthread_getcpuclockid(), representing the amount of time the process
or thread has spent actually running.
tp
A pointer to a timespec structure where clock_gettime() can store the
time. This function sets the members as follows:
• tv_sec — the number of seconds since 1970.
• tv_nsec — the number of nanoseconds expired in the current second.
This value increases by some multiple of nanoseconds, based on the
system clock’s resolution.
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
The clock_gettime() function gets the current time of the clock specified by clock_id,
and puts it into the buffer pointed to by tp.
226
QNX Neutrino Functions and Macros
June 19, 2012
clock_gettime()
© 2012, QNX Software Systems Limited
Returns:
0
Success.
-1
An error occurred (errno is set).
Errors:
EFAULT
A fault occurred trying to access the buffers provided.
EINVAL
Invalid clock_id.
ESRCH
The process associated with this request doesn’t exist.
Examples:
/*
* This program calculates the time required to
* execute the program specified as its first argument.
* The time is printed in seconds, on standard out.
*/
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <time.h>
#define BILLION
1000000000L;
int main( int argc, char** argv )
{
struct timespec start, stop;
double accum;
if( clock_gettime( CLOCK_REALTIME, &start) == -1 ) {
perror( "clock gettime" );
return EXIT_FAILURE;
}
system( argv[1] );
if( clock_gettime( CLOCK_REALTIME, &stop) == -1 ) {
perror( "clock gettime" );
return EXIT_FAILURE;
}
accum = ( stop.tv_sec - start.tv_sec )
+ (double)( stop.tv_nsec - start.tv_nsec )
/ (double)BILLION;
printf( "%lf\n", accum );
return EXIT_SUCCESS;
}
Classification:
POSIX 1003.1 TMR
June 19, 2012
QNX Neutrino Functions and Macros
227
clock_gettime()
© 2012, QNX Software Systems Limited
Safety
Cancellation point
No
Interrupt handler
No
Signal handler
Yes
Thread
Yes
See also:
clock_getcpuclockid(), clock_getres(), clock_settime(), errno,
pthread_getcpuclockid(), timespec
Clocks, Timers, and Getting a Kick Every So Often chapter of Getting Started with
QNX Neutrino
228
QNX Neutrino Functions and Macros
June 19, 2012
clock_nanosleep()
© 2012, QNX Software Systems Limited
High resolution sleep with specifiable clock
Synopsis:
#include <time.h>
int clock_nanosleep( clockid_t clock_id,
int flags,
const struct timespec * rqtp,
struct timespec * rmtp );
Arguments:
clock_id
The ID of the clock to use to measure the time. The possible clock types
are:
• CLOCK_REALTIME — the standard POSIX-defined clock. Timers
based on this clock wake up the processor if it’s in a power-saving
mode.
• CLOCK_SOFTTIME — this clock is active only when the processor
isn’t in a power-saving mode. For example, an application using a
CLOCK_SOFTTIME timer to sleep wouldn’t wake up the processor
when the application was due to wake up. This will allow the
processor to enter a power-saving mode.
While the processor isn’t in a power-saving mode,
CLOCK_SOFTTIME behaves the same as CLOCK_REALTIME.
• CLOCK_MONOTONIC — this clock always increases at a constant
rate and can’t be adjusted.
The clock_nanosleep() function fails if the clock_id argument refers to
the CPU-time clock of the calling thread.
flags
Flags that specify when the current thread is to be suspended from
execution:
• when the time interval specified by the rqtp argument has elapsed
(TIMER_ABSTIME is not set).
• when the time value of the clock specified by clock_id reaches the
absolute time specified by the rqtp argument (TIMER_ABSTIME is
set).
If, at the time of the call, the time value specified by rqtp is less than
or equal to the time value of the specified clock, then
clock_nanosleep() returns immediately, and the calling process isn’t
suspended.
• when a signal is delivered to the calling thread, and the signal’s action
is to invoke a signal-catching function or terminate the process.
Calling clock_nanosleep() with TIMER_ABSTIME not set, and clock_id
set to CLOCK_REALTIME is the equivalent to calling nanosleep() with
the same rqtp and rmtp arguments.
June 19, 2012
QNX Neutrino Functions and Macros
229
clock_nanosleep()
© 2012, QNX Software Systems Limited
rqtp
A pointer to a timespec structure that specifies the time interval
between the requested time and the time actually slept.
rmtp
NULL, or a pointer to a timespec in which the function can store the
amount of time remaining in an interval.
For the relative clock_nanosleep() function, if rmtp isn’t NULL, the
timespec structure referenced by it is updated to contain the amount of
time remaining in the interval (the requested time minus the time actually
slept). If it’s NULL, the remaining time isn’t returned.
The absolute clock_nanosleep() function has no effect on the structure
referenced by rmtp.
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
The clock_nanosleep() function suspends the current thread from execution until:
• If TIMER_ABSTIME is set, the time value of the clock specified by clock_id
reaches the absolute time specified by the rqtp argument.
Or:
• If TIMER_ABSTIME is not set, the time interval specified by the rqtp argument has
elapsed.
Or:
• A signal is delivered to the calling thread, and the signal’s action is to invoke a
signal-catching function or terminate the process.
The nanosleep() function always uses CLOCK_REALTIME.
The suspension time may be longer than requested because the argument value is
rounded up to an integer multiple of the sleep resolution (see the Tick, Tock:
Understanding the Neutrino Microkernel’s Concept of Time chapter of the QNX
Neutrino Programmer’s Guide) or because of scheduling and other system activity.
Except for the case of being interrupted by a signal, the suspension time for:
• the relative clock_nanosleep() function (TIMER_ABSTIME not set) — isn’t less
than the time interval specified by rqtp, as measured by the corresponding clock
• the absolute clock_nanosleep() function (TIMER_ABSTIME set) — is in effect at
least until the value of the corresponding clock reaches the absolute time specified
by rqtp, except for the case of being interrupted by a signal.
Using the clock_nanosleep() function has no effect on the action or blockage of any
signal.
230
QNX Neutrino Functions and Macros
June 19, 2012
clock_nanosleep()
© 2012, QNX Software Systems Limited
Returns:
Errors:
Zero if the requested time has elapsed, or a corresponding error value if
clock_nanosleep() has been interrupted by a signal, or fails.
EINTR
The call was interrupted by a signal.
EINVAL
The rqtp argument specified a nanosecond value less than zero or
greater than or equal to 1000 million; or TIMER_ABSTIME is specified
in flags and the rqtp argument is outside the range for the clock
specified by clock_id; or the clock_id argument doesn’t specify a
known clock, or specifies the CPU-time clock of the calling thread.
ENOTSUP
The clock_id argument specifies a clock for which clock_nanosleep()
isn’t supported, such as a CPU-time clock.
Classification:
POSIX 1003.1 CS
Safety
Cancellation point
Yes
Interrupt handler
No
Signal handler
Yes
Thread
Yes
See also:
clock_settime(), nanosleep(), sleep(), timespec
Clocks, Timers, and Getting a Kick Every So Often chapter of Getting Started with
QNX Neutrino
Tick, Tock: Understanding the Neutrino Microkernel’s Concept of Time chapter of the
QNX Neutrino Programmer’s Guide
June 19, 2012
QNX Neutrino Functions and Macros
231
clock_settime()
© 2012, QNX Software Systems Limited
Set a clock
Synopsis:
#include <time.h>
int clock_settime( clockid_t id,
const struct timespec * tp );
Arguments:
id
The clock ID, CLOCK_REALTIME or CLOCK_MONOTONIC, that maintains the
system time, or the clock ID that’s returned by ClockId().
tp
A pointer to a timespec structure containing at least the following members:
• tv_sec — the number of seconds since 1970.
• tv_nsec — the number of nanoseconds in the current second. This value
increases by some multiple of nanoseconds, based on the system clock’s
resolution.
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
The clock_settime() function sets the clock specified by id to the time specified in the
buffer pointed to by tp.
• Be careful if you set the date during the period that a time zone is switching from
daylight saving time (DST) to standard time. When a time zone changes to
standard time, the local time goes back one hour (for example, 2:00 a.m. becomes
1:00 a.m.). The local time during this hour is ambiguous (e.g. 1:14 a.m. occurs
twice in the morning that the time zone switches to standard time). To avoid
problems, use UTC time to set the date in this period.
• You can’t set the time when the id is CLOCK_MONOTONIC.
• You need to have superuser privileges to set the clock.
Returns:
232
0
Success
-1
An error occurred (errno is set).
QNX Neutrino Functions and Macros
June 19, 2012
clock_settime()
© 2012, QNX Software Systems Limited
Errors:
EINVAL
One of the following occurred:
• The id is invalid.
• The number of nanoseconds specified by the tv_nsec member is less
than zero or greater than or equal to 1000 million.
• The tv_sec member is -1 (which could happen if you set it to the result
from mktime() without checking to see if the call succeeded).
EPERM
You don’t have sufficient privilege to change the time.
Examples:
/*
This program sets the clock forward 1 day. */
#include
#include
#include
#include
<stdio.h>
<stdlib.h>
<unistd.h>
<time.h>
int main( void )
{
struct timespec stime;
if( clock_gettime( CLOCK_REALTIME, &stime) == -1 ) {
perror( "getclock" );
return EXIT_FAILURE;
}
stime.tv_sec += (60*60)*24L; /* Add one day */
stime.tv_nsec = 0;
if( clock_settime( CLOCK_REALTIME, &stime) == -1 ) {
perror( "setclock" );
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
Classification:
POSIX 1003.1 TMR
Safety
June 19, 2012
Cancellation point
No
Interrupt handler
No
Signal handler
Yes
Thread
Yes
QNX Neutrino Functions and Macros
233
clock_settime()
© 2012, QNX Software Systems Limited
See also:
clock_getres(), clock_gettime(), errno, mktime(), timespec
Clocks, Timers, and Getting a Kick Every So Often chapter of Getting Started with
QNX Neutrino
234
QNX Neutrino Functions and Macros
June 19, 2012
© 2012, QNX Software Systems Limited
ClockAdjust(), ClockAdjust_r()
Adjust the time of a clock
Synopsis:
#include <sys/neutrino.h>
int ClockAdjust( clockid_t id,
const struct _clockadjust * new,
struct _clockadjust * old );
int ClockAdjust_r( clockid_t id,
const struct _clockadjust * new,
struct _clockadjust * old );
Arguments:
id
The ID of the clock you want to adjust. This must be CLOCK_REALTIME;
this clock maintains the system time.
new
NULL or a pointer to a _clockadjust structure that specifies how to adjust
the clock. Any previous adjustment is replaced.
The _clockadjust structure contains at least the following members:
• long tick_nsec_inc — the adjustment to be made on each clock tick, in
nanoseconds.
• unsigned long tick_count — the number of clock ticks over which to
apply the adjustment.
old
If not NULL, a pointer to a _clockadjust structure where the function can
store the current adjustment (before being changed by a non-NULL new).
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
These kernel calls let you gradually adjust the time of the clock specified by id. You
can use these functions to speed up or slow down the system clock to synchronize it
with another time source – without causing major discontinuities in the time flow.
The ClockAdjust() and ClockAdjust_r() functions are identical except in the way they
indicate errors. See the Returns section for details.
The total time adjustment, in nanoseconds, is:
(new->tick_count * new->tick_nsec_inc)
If the current clock is ahead of the desired time, you can specify a negative
tick_nsec_inc to slow down the clock. This is preferable to setting the time backwards
June 19, 2012
QNX Neutrino Functions and Macros
235
ClockAdjust(), ClockAdjust_r()
© 2012, QNX Software Systems Limited
with the ClockTime() kernel call, since some programs may malfunction if time goes
backwards.
Picking small values for tick_nsec_inc and large values for tick_count adjusts the time
slowly, while the opposite approach adjusts it rapidly. As a rule of thumb, don’t try to
set a tick_nsec_inc that exceeds the basic clock tick as set by the ClockPeriod() kernel
call. This would change the clock rate by more than 100% and if the adjustment is
negative, it could make the clock go backwards.
You can cancel any adjustment in progress by setting tick_count and tick_nsec_inc to
0.
Superuser privileges are required to adjust the clock.
Blocking states:
These calls don’t block.
Returns:
The only difference between these functions is the way they indicate errors:
ClockAdjust()
If an error occurs, the function returns -1 and sets errno. Any
other value returned indicates success.
ClockAdjust_r()
EOK is returned on success. This function does NOT set errno.
If an error occurs, the function may return any value in the
Errors section.
Errors:
EFAULT
A fault occurred when the kernel tried to access the buffers provided.
EINVAL
The clock ID isn’t valid.
EPERM
The process tried to adjust the time without having superuser capabilities.
Classification:
QNX Neutrino
Safety
236
Cancellation point
No
Interrupt handler
No
Signal handler
Yes
Thread
Yes
QNX Neutrino Functions and Macros
June 19, 2012
© 2012, QNX Software Systems Limited
ClockAdjust(), ClockAdjust_r()
See also:
ClockPeriod(), ClockTime()
Clocks, Timers, and Getting a Kick Every So Often chapter of Getting Started with
QNX Neutrino
June 19, 2012
QNX Neutrino Functions and Macros
237
ClockCycles()
© 2012, QNX Software Systems Limited
Get the number of clock cycles
Synopsis:
#include <sys/neutrino.h>
#include <inttypes.h>
uint64_t ClockCycles( void );
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
The ClockCycles() kernel call returns the current value of a free-running 64-bit cycle
counter. This is implemented on each processor as a high-performance mechanism for
timing short intervals.
Several CPU architectures have an instruction that reads such a free-running counter
(e.g., x86 has the RDTSC instruction). For processors that don’t implement such an
instruction in hardware, the kernel emulates one. This provides a lower time resolution
than if the instruction is provided (e.g., 838.095345 nanoseconds on an IBM
PC-compatible system).
In all cases, the SYSPAGE_ENTRY(qtime)->cycles_per_sec field gives the
number of ClockCycles() increments in one second.
!
CAUTION: The cycle counter wraps every number of seconds as calculated by:
(˜(uint64_t)0) / SYSPAGE_ENTRY(qtime)->cycles_per_sec
Symmetric MultiProcessing systems
This function, depending on the CPU architecture, returns a value from a register
that’s unique to each CPU in an SMP system — for instance, the TSC (Time Stamp
Counter) on an x86. These registers aren’t synchronized between the CPUs. So if you
call ClockCycles(), and then the thread migrates to another CPU and you call
ClockCycles() again, you can’t subtract the two values to get a meaningful time
duration.
If you wish to use ClockCycles() on an SMP machine, you must use the following call
to “lock” the thread to a single CPU:
ThreadCtl(_NTO_TCTL_RUNMASK, ...)
For more information, see the entry for ThreadCtl().
238
QNX Neutrino Functions and Macros
June 19, 2012
ClockCycles()
© 2012, QNX Software Systems Limited
Blocking states:
Examples:
This call doesn’t block.
See SYSPAGE_ENTRY().
Classification:
QNX Neutrino
Safety
Cancellation point
No
Interrupt handler
Yes
Signal handler
Yes
Thread
Yes
See also:
SYSPAGE_ENTRY(), ThreadCtl()
Clocks, Timers, and Getting a Kick Every So Often chapter of Getting Started with
QNX Neutrino
June 19, 2012
QNX Neutrino Functions and Macros
239
ClockId(), ClockId_r()
© 2012, QNX Software Systems Limited
Get the CPU-time clock ID for a given process and thread
Synopsis:
#include <sys/neutrino.h>
#include <inttypes.h>
extern int ClockId( pid_t pid,
int tid );
extern int ClockId_r( pid_t pid,
int tid );
Arguments:
pid
The ID of the process that you want to get the clock ID for. If this argument is
zero, the ID of the process making the call is assumed.
tid
The ID of the thread that you want to get the clock ID for, or 0 to get clock ID
for the process as a whole.
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
The ClockId() and ClockId_r() kernel calls retrieve an integer CPU-time clock ID that
you can pass as a clockid_t to ClockTime(). When you pass this clock ID to
ClockTime(), that function returns (in the location pointed to by old) the number of
nanoseconds that the specified thread of the specified process has executed.
The ClockId() and ClockId_r() functions are identical except in the way they indicate
errors. See the Returns section for details.
Instead of using these kernel calls directly, consider calling clock_getcpuclockid() or
pthread_getcpuclockid().
If the tid is zero, ClockTime() gives you the number of nanoseconds that the process as
a whole has executed. On an SMP box, this number may exceed the realtime number
of nanoseconds that have elapsed because multiple threads in the process can run on
several CPUs at the same time.
Blocking states:
This call doesn’t block.
240
QNX Neutrino Functions and Macros
June 19, 2012
ClockId(), ClockId_r()
© 2012, QNX Software Systems Limited
Returns:
ClockId()
An integer that can be passed to ClockTime(). If an error occurs, the
function returns -1 and sets errno.
An integer that can be passed to ClockTime(). This function does
NOT set errno. If an error occurs, the function returns the negative
of a value from the Errors section.
ClockId_r()
Errors:
ESRCH
The pid and/or tid don’t exist.
Examples:
Here’s how you can determine how busy a system is:
id = ClockId(1, 1);
for( ;; ) {
ClockTime(id, NULL, &start);
sleep(1);
ClockTime(id, NULL, &stop);
printf("load = %f%%\n", (1000000000.0 - (stop-start)) / 10000000.0);
}
Classification:
QNX Neutrino
Safety
Cancellation point
No
Interrupt handler
No
Signal handler
Yes
Thread
Yes
See also:
ClockTime(), clock_getcpuclockid(), pthread_getcpuclockid()
Clocks, Timers, and Getting a Kick Every So Often chapter of Getting Started with
QNX Neutrino
June 19, 2012
QNX Neutrino Functions and Macros
241
ClockPeriod(), ClockPeriod_r()
© 2012, QNX Software Systems Limited
Get or set a clock period
Synopsis:
#include <sys/neutrino.h>
int ClockPeriod( clockid_t id,
const struct _clockperiod * new,
struct _clockperiod * old,
int reserved );
int ClockPeriod_r( clockid_t id,
const struct _clockperiod * new,
struct _clockperiod * old,
int reserved );
Arguments:
id
The clock ID of the clock. This must be CLOCK_REALTIME, which is
the ID of the clock that maintains the system time.
new
NULL, or a pointer to a _clockperiod structure that contains the period
to set the clock to. This structure contains at least the following
members:
• unsigned long nsec — the period of the clock, in nanoseconds.
• long fract — reserved for future fractional nanoseconds. Set this
member to zero.
old
NULL, or a pointer to a _clockperiod structure where the function can
store the current period (before being changed by a non-NULL new).
reserved
Set this argument to 0.
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
You can use the ClockPeriod() and ClockPeriod_r() kernel calls to get or set the clock
period of the clock.
If you want to get the clock period, consider calling clock_getres() instead of using
these kernel calls directly.
These functions are identical except in the way they indicate errors. See the Returns
section for details.
242
QNX Neutrino Functions and Macros
June 19, 2012
ClockPeriod(), ClockPeriod_r()
© 2012, QNX Software Systems Limited
• You need to have superuser privileges to set the clock period.
• If you’re using adaptive partitioning, and you change the tick size of the system at
runtime, do so before defining the adaptive partitioning scheduler’s window size.
That’s because Neutrino converts the window size from milliseconds to clock ticks
for internal use. For more information, see the Adaptive Partitioning User’s Guide.
All the timer_*() calls operate with an accuracy no better than the clock period. Every
moment within the Neutrino microkernel is referred to as a tick. A tick’s initial length
is determined by the clock rate of your processor:
CPU clock speed:
Default value:
≥ 40MHz
1 millisecond
< 40MHz
10 milliseconds
Since a very small tick size imposes an interrupt load on the system, and can consume
all available processor cycles, the kernel call limits how small a period can be
specified. The lowest clock period that can currently be set on any machine is 10
microseconds.
If an attempt is made to set a value that the kernel believes to be unsafe, the call fails
with an EINVAL. The timeslice rate (for “round-robin” and “other” scheduling
policies) is always four times the clock period (this isn’t changeable).
Blocking states
These calls don’t block.
Returns:
The only difference between these functions is the way they indicate errors:
ClockPeriod()
If an error occurs, this function returns -1 is and sets errno. Any
other value returned indicates success.
ClockPeriod_r()
EOK is returned on success. This function does NOT set errno.
If an error occurs, the function can return any value in the Errors
section.
Errors:
June 19, 2012
EFAULT
A fault occurred when the kernel tried to access the buffers provided.
EINVAL
Invalid clock ID. A period was set which wasn’t in a range considered
safe.
QNX Neutrino Functions and Macros
243
ClockPeriod(), ClockPeriod_r()
EPERM
© 2012, QNX Software Systems Limited
The process tried to change the period of the clock without having
superuser capabilities.
Classification:
QNX Neutrino
Safety
Cancellation point
No
Interrupt handler
No
Signal handler
Yes
Thread
Yes
See also:
clock_getres(), ClockAdjust()
Clocks, Timers, and Getting a Kick Every So Often chapter of Getting Started with
QNX Neutrino
244
QNX Neutrino Functions and Macros
June 19, 2012
ClockTime(), ClockTime_r()
© 2012, QNX Software Systems Limited
Get or set a clock
Synopsis:
#include <sys/neutrino.h>
int ClockTime( clockid_t id,
const uint64_t * new,
uint64_t * old );
int ClockTime_r( clockid_t id,
const uint64_t * new,
uint64_t * old );
Arguments:
id
The clock ID. This must be CLOCK_REALTIME or CLOCK_MONOTONIC,
which is the ID of the clock that maintains the system time, or a CPU-time
clock ID returned by ClockId().
new
NULL, or a pointer to the absolute time, in nanoseconds, to set the clock to.
This is used only if id is CLOCK_REALTIME.
old
NULL, or a pointer to a location where the function can store the current time
(before being changed by a non-NULL new).
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
You can use these kernel calls to:
• get or set the system clock if id is CLOCK_REALTIME
• get the system clock if id is CLOCK_MONOTONIC
• get the CPU-time clock for a process or a particular thread in a process, if the ID is
one that you obtained by calling ClockId(). On an SMP box, the time for a process
may exceed the realtime number of nanoseconds that have elapsed because
multiple threads in the process can run on several CPUs at the same time.
The ClockTime() and ClockTime_r() functions are identical except in the way they
indicate errors. See the Returns section for details.
June 19, 2012
QNX Neutrino Functions and Macros
245
ClockTime(), ClockTime_r()
© 2012, QNX Software Systems Limited
Instead of using these kernel calls directly, consider calling clock_gettime() or
clock_settime().
If new isn’t NULL, then it contains the absolute time, in nanoseconds, to set the system
clock to. This affects the software clock maintained by the system. It doesn’t change
any underlying hardware clock that maintains the time when the system’s power is
turned off.
You need to have superuser privileges to set the clock. You can set the time only when
the id is CLOCK_REALTIME.
If you call ClockTime() to set the time of day, the kernel checks to see if the
SYSPAGE_ENTRY(qtime)->boot_time field is zero. If it is, the kernel sets it to the
appropriate value. There’s a -T option for all startup programs that prevents the setting
of this field, so that the kernel will set it the first time you call ClockTime() to change
the time of day. This is useful if the RTC hardware isn’t in UTC.
Once set, the system time increments by some number of nanoseconds, based on the
resolution of the system clock. You can query or change this resolution by using the
ClockPeriod() kernel call.
Blocking states
These calls don’t block.
Returns:
The only difference between these functions is the way they indicate errors:
ClockTime()
If an error occurs, the function returns -1 and sets errno. Any
other value returned indicates success.
ClockTime_r()
EOK is returned on success. This function does NOT set errno. If
an error occurs, the function returns a value in the Errors section.
Errors:
246
EFAULT
A fault occurred when the kernel tried to access the buffers provided.
EINVAL
The clock ID isn’t valid, or you tried to set the time for an ID other than
CLOCK_REALTIME.
EPERM
The process tried to change the time without having superuser
capabilities.
ESRCH
The process associated with this request doesn’t exist.
QNX Neutrino Functions and Macros
June 19, 2012
ClockTime(), ClockTime_r()
© 2012, QNX Software Systems Limited
Classification:
QNX Neutrino
Safety
Cancellation point
No
Interrupt handler
No
Signal handler
Yes
Thread
Yes
See also:
clock_gettime(), clock_settime(), ClockAdjust(), ClockPeriod(), SYSPAGE_ENTRY()
Clocks, Timers, and Getting a Kick Every So Often chapter of Getting Started with
QNX Neutrino
June 19, 2012
QNX Neutrino Functions and Macros
247
close()
© 2012, QNX Software Systems Limited
Close a file
Synopsis:
#include <unistd.h>
int close( int filedes );
Arguments:
filedes
The file descriptor of the file you want to close. This can be a file descriptor
returned by a successful call to accept(), creat(), dup(), dup2(), fcntl(),
modem_open(), open(), shm_open(), socket() or sopen().
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
The close() function closes the file specified by the given file descriptor.
Returns:
Zero for success, or -1 if an error occurs (errno is set).
Errors:
EBADF
Invalid file descriptor filedes.
EINTR
The close() call was interrupted by a signal.
EIO
An I/O error occurred while updating the directory information.
ENOSPC
A previous buffered write call has failed.
ENOSYS
The close() function isn’t implemented for the filesystem specified by
filedes.
Examples:
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>
int main( void )
{
int filedes;
filedes = open( "file", O_RDONLY );
if( filedes != -1 ) {
/* process file */
close( filedes );
248
QNX Neutrino Functions and Macros
June 19, 2012
close()
© 2012, QNX Software Systems Limited
return EXIT_SUCCESS;
}
return EXIT_FAILURE;
}
Classification:
POSIX 1003.1
Safety
Cancellation point
Yes
Interrupt handler
No
Signal handler
Yes
Thread
Yes
See also:
accept(), creat(), dup(), dup2(), errno, fcntl(), modem_open(), open(), shm_open(),
socket(), sopen()
June 19, 2012
QNX Neutrino Functions and Macros
249
closedir()
© 2012, QNX Software Systems Limited
Close a directory
Synopsis:
#include <dirent.h>
int closedir( DIR * dirp );
Arguments:
dirp
A directory pointer for the directory you want to close.
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
The closedir() function closes the directory specified by dirp, and frees the memory
allocated by opendir().
The result of using a directory stream after calling one of the exec*() or spawn*()
family of functions is undefined. After a call to the fork() function, either the parent or
the child (but not both) may continue processing the directory stream using the
readdir() and rewinddir() functions. If both the parent and child processes use these
functions, the result is undefined. Either or both processes may call the closedir()
function.
Returns:
0
Success.
-1
An error occurred (errno is set).
Errors:
EBADF
The dirp argument doesn’t refer to an open directory stream.
EINTR
The closedir() call was interrupted by a signal.
Examples:
Get a list of files contained in the directory /home/kenny:
#include <stdio.h>
#include <dirent.h>
#include <stdlib.h>
int main( void )
{
250
QNX Neutrino Functions and Macros
June 19, 2012
closedir()
© 2012, QNX Software Systems Limited
DIR *dirp;
struct dirent *direntp;
dirp = opendir( "/home/kenny" );
if( dirp != NULL ) {
for(;;) {
direntp = readdir( dirp );
if( direntp == NULL ) {
break;
}
printf( "%s\n", direntp->d_name );
}
closedir( dirp );
return EXIT_SUCCESS;
}
return EXIT_FAILURE;
}
Classification:
POSIX 1003.1
Safety
Cancellation point
Yes
Interrupt handler
No
Signal handler
No
Thread
Yes
See also:
dirent, errno, opendir(), readdir(), readdir_r(), rewinddir(), seekdir(), telldir()
June 19, 2012
QNX Neutrino Functions and Macros
251
closelog()
© 2012, QNX Software Systems Limited
Close the system log
Synopsis:
#include <syslog.h>
void closelog( void );
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
The closelog() function closes the connection to syslogd.
Classification:
POSIX 1003.1 XSI
Safety
Cancellation point
Yes
Interrupt handler
No
Signal handler
No
Thread
Yes
See also:
openlog(), setlogmask(), syslog(), vsyslog()
logger, syslogd in the Utilities Reference
252
QNX Neutrino Functions and Macros
June 19, 2012
_cmdfd()
© 2012, QNX Software Systems Limited
Return a file descriptor for the executable file
Synopsis:
#include <process.h>
int _cmdfd( void );
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
This function returns a file descriptor for the executable file.
Returns:
A file descriptor for the executable file.
Classification:
QNX Neutrino
Safety
Cancellation point
No
Interrupt handler
No
Signal handler
No
Thread
Yes
See also:
_cmdname(), __progname
June 19, 2012
QNX Neutrino Functions and Macros
253
_cmdname()
© 2012, QNX Software Systems Limited
Find the path used to invoke the current process
Synopsis:
#include <process.h>
char * _cmdname( char * buff );
Arguments:
buff
NULL, or a pointer to a buffer in which the function can store the path. To
determine the size required for the buffer, call fpathconf() or pathconf() with
an argument of _PC_PATH_MAX, then add 1 for the terminating null
character.
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
The _cmdname() function determines the full path that the current process was
invoked from. If buff isn’t NULL, _cmdname() copies the path into the buffer that buff
points to.
Returns:
A pointer to the pathname used to load the process, or NULL if an error occurred.
Don’t change the string that the returned value points to if you passed NULL for the
buff parameter.
Examples:
#include
#include
#include
#include
#include
<stdlib.h>
<stdio.h>
<unistd.h>
<limits.h>
<process.h>
int main( void )
{
size_t maximum_path;
char *buff;
maximum_path = (size_t) pathconf( "/", _PC_PATH_MAX );
buff = (char* )malloc( maximum_path );
if( _cmdname( buff ) ) {
printf( "I’m \"%s\".\n", buff );
} else {
perror( "_cmdname() failed" );
free (buff);
return EXIT_FAILURE;
254
QNX Neutrino Functions and Macros
June 19, 2012
_cmdname()
© 2012, QNX Software Systems Limited
}
free (buff);
return EXIT_SUCCESS;
}
If this code is compiled into an executable named foo:
# ls -F /home/xyzzy/bin/foo
foo*
# /home/xyzzy/bin/foo
I’m "/home/xyzzy/bin/foo".
Classification:
QNX 4
Safety
Cancellation point
No
Interrupt handler
No
Signal handler
No
Thread
Yes
See also:
basename(), _cmdfd(), __progname
June 19, 2012
QNX Neutrino Functions and Macros
255
confstr()
© 2012, QNX Software Systems Limited
Get configuration-defined string values
Synopsis:
#include <unistd.h>
size_t confstr( int name,
char * buf ,
size_t len );
Arguments:
name
The system variable to query; see below.
buf
A pointer to a buffer in which the function can store the value of the system
variable.
len
The length of the buffer, in bytes.
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
The confstr() function lets applications get or set configuration-defined string values.
This is similar to the sysconf() function, but you use it to get string values, rather than
numeric values. By default, the function queries and returns values in the system.
The name argument represents the system variable to query. The values are defined in
<confname.h>; at least the following name values are valid:
_CS_ARCHITECTURE
The name of the instruction set architecture for this node’s
CPU(s).
_CS_DOMAIN
The domain name.
_CS_HOSTNAME
The name of this node in the network.
A hostname can consist only of letters, numbers, and hyphens, and must not start or
end with a hyphen. For more information, see RFC 952.
_CS_HW_PROVIDER
The name of the hardware manufacturer.
_CS_HW_SERIAL
256
QNX Neutrino Functions and Macros
Serial number associated with the hardware.
June 19, 2012
confstr()
© 2012, QNX Software Systems Limited
_CS_LIBPATH
A value similar to the LD_LIBRARY_PATH environment
variable that finds all standard libraries.
_CS_LOCALE
The name of the current locale.
_CS_MACHINE
This node’s hardware type.
_CS_PATH
A value similar to the PATH environment variable that finds all
standard utilities.
_CS_RELEASE
The current OS release level.
_CS_RESOLVE
The contents of the resolv.conf file, excluding the domain
name.
_CS_SRPC_DOMAIN
The secure RPC domain.
_CS_SYSNAME
The operating system name.
_CS_TIMEZONE
Time zone string (TZ style)
_CS_VERSION
The current OS version number.
The configuration-defined value is returned in the buffer pointed to by buf , and will be
≤ len bytes long, including the terminating NULL.
To find out the length of a configuration-defined value, call confstr() with buf set to
NULL and len set to 0.
To set a configuration value:
1
OR the name of the value (e.g. _CS_HOSTNAME) with _CS_SET.
2
Put the new value in a NULL-terminated string.
3
Set the value of len to 0.
Returns:
A nonzero value (if a “get” is done, the value is the length of the configuration-defined
value), or 0 if an error occurs (errno is set).
You can compare the confstr() return value against len to see if the
configuration-defined value was truncated when retrieving a value (you can’t do this
when setting a value).
Errors:
EINVAL
June 19, 2012
The name argument isn’t a valid configuration-defined value.
QNX Neutrino Functions and Macros
257
confstr()
© 2012, QNX Software Systems Limited
Examples:
Print information similar to that returned by the uname() function:
#include <unistd.h>
#include <stdio.h>
#include <limits.h>
#define BUFF_SIZE (256 + 1)
int main( void )
{
char buff[BUFF_SIZE];
if( confstr( _CS_SYSNAME, buff, BUFF_SIZE ) > 0 ) {
printf( "System name: %s\n", buff );
}
if( confstr( _CS_HOSTNAME, buff, BUFF_SIZE ) > 0 ) {
printf( "Host name: %s\n", buff );
}
if( confstr( _CS_RELEASE, buff, BUFF_SIZE ) > 0 ) {
printf( "Release: %s\n", buff );
}
if( confstr( _CS_VERSION, buff, BUFF_SIZE ) > 0 ) {
printf( "Version: %s\n", buff );
}
if( confstr( _CS_MACHINE, buff, BUFF_SIZE ) > 0 ) {
printf( "Machine: %s\n", buff );
}
if( confstr( _CS_SET | _CS_HOSTNAME, "myhostname", 0 ) != 0 ) {
printf( "Hostname set to: %s\n", "myhostname" );
}
return 0;
}
Classification:
POSIX 1003.1
Safety
258
Cancellation point
No
Interrupt handler
No
Signal handler
Yes
Thread
Yes
QNX Neutrino Functions and Macros
June 19, 2012
confstr()
© 2012, QNX Software Systems Limited
Caveats:
The confstr() function is part of a draft standard; its interface and/or behavior may
change in the future.
See also:
pathconf(), sysconf()
confstr, getconf, setconf in the Utilities Reference
“Configuration strings” in the Configuring Your Environment chapter of the Neutrino
User’s Guide
June 19, 2012
QNX Neutrino Functions and Macros
259
connect()
© 2012, QNX Software Systems Limited
Initiate a connection on a socket
Synopsis:
#include <sys/types.h>
#include <sys/socket.h>
int connect( int s,
const struct sockaddr * name,
socklen_t namelen );
Arguments:
s
The descriptor of the socket on which to initiate the connection.
name
The name of the socket to connect to for a SOCK_STREAM connection.
namelen
The length of the name, in bytes.
Library:
libsocket
Use the -l socket option to qcc to link against this library.
Description:
The connect() function establishes the connection according to the socket type
specified by s:
SOCK_DGRAM
Specifies the peer that the socket is to be associated with. This
address is the one that datagrams are to be sent to, and the only
one that datagrams are to be received from.
SOCK_STREAM
This call attempts to make a connection to another socket. The
other socket is specified by name, which is an address in the
communications space of that socket. Each communications
space interprets name in its own way.
Stream sockets may successfully connect only once, whereas datagram sockets may
use connect() multiple times to change their association. Datagram sockets may
dissolve the association by connecting to an invalid address, such as a null address.
Returns:
260
0
Success.
-1
An error occurred (errno is set).
QNX Neutrino Functions and Macros
June 19, 2012
connect()
© 2012, QNX Software Systems Limited
Errors:
EADDRINUSE
EADDRNOTAVAIL
The address is already in use.
The specified address isn’t available on this machine.
EAFNOSUPPORT
Addresses in the specified address family cannot be used with
this socket.
EALREADY
The socket is nonblocking; a previous connection attempt
hasn’t yet been completed.
EBADF
Invalid descriptor s.
ECONNABORTED
The connect() was terminated under software control.
ECONNREFUSED
The attempt to connect was forcefully rejected.
EFAULT
The name parameter specifies an area outside the process
address space.
EHOSTUNREACH
No route to host; the host system can’t be reached.
EINPROGRESS
The socket is nonblocking; the connection can’t be completed
immediately. It’s possible to do a select() for completion by
selecting the socket for writing.
EISCONN
The socket is already connected.
ENETUNREACH
The network isn’t reachable from this host.
ETIMEDOUT
The attempt to establish a connection timed out; no connection
was made.
Protocols such as TCP do not allow further connection requests on a socket after an
ECONNREFUSED error. In such a situation, the socket must be closed and a new one
created before a subsequent attempt for connection is made.
Classification:
POSIX 1003.1
Safety
June 19, 2012
Cancellation point
Yes
Interrupt handler
No
Signal handler
No
Thread
Yes
QNX Neutrino Functions and Macros
261
connect()
© 2012, QNX Software Systems Limited
See also:
ICMP, IP, TCP, and UDP protocols
accept(), bind(), getsockname(), nbaconnect(), select(), socket()
262
QNX Neutrino Functions and Macros
June 19, 2012
© 2012, QNX Software Systems Limited
ConnectAttach(), ConnectAttach_r()
Establish a connection between a process and a channel
Synopsis:
#include <sys/neutrino.h>
#include <sys/netmgr.h>
int ConnectAttach( uint32_t nd,
pid_t pid,
int chid,
unsigned index,
int flags );
int ConnectAttach_r( uint32_t nd,
pid_t pid,
int chid,
unsigned index,
int flags );
Arguments:
nd
The node descriptor of the node (e.g. ND_LOCAL_NODE for the local node)
on which the process that owns the channel is running; see “Node
descriptors,” below.
pid
The process ID of the owner of the channel. If pid is zero, the calling
process is assumed.
chid
The channel ID, returned by ChannelCreate(), of the channel to connect to
the process.
index
The lowest acceptable connection ID.
Treating a connection as a file descriptor can lead to unexpected behavior. Therefore,
you should OR _NTO_SIDE_CHANNEL into index when you create a connection. If
you do this, the connection ID is returned from a different space than file descriptors;
the ID is greater than any valid file descriptor.
Once created there’s no difference in the use of the messaging primitives on this ID.
The C library creates connections at various times without _NTO_SIDE_CHANNEL
(e.g. during open()), however, it’s unlikely that any applications would want to call it
this way.
flags
If flags contains _NTO_COF_CLOEXEC, the connection is closed when your
process calls an exec*() function to start a new process.
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
June 19, 2012
QNX Neutrino Functions and Macros
263
ConnectAttach(), ConnectAttach_r()
© 2012, QNX Software Systems Limited
Description:
The ConnectAttach() and ConnectAttach_r() kernel calls establish a connection
between the calling process and the channel specified by chid owned by the process
specified by pid on the node specified by nd. Any function that passes a node
descriptor can use either the value 0 or the constant ND_LOCAL_NODE to refer to the
local node.
These functions are identical except in the way they indicate errors. See the Returns
section for details.
If a process wants other processes to communicate with it, it typically uses
name_attach() to create a channel and associate a name with it, and the sender process
uses name_open() to locate that name and create a connection to it.
The return value is a connection ID, which is a small int representing the connection.
The system returns the first available connection ID starting at the value specified by
the index argument. Any thread in the calling process can use either MsgSendv() to
send messages or MsgSendPulse() to send pulses over the connection. The connection
ID is used directly as a POSIX file descriptor (fd) when communicating with I/O
Resource managers such as a filesystem manager.
If you don’t OR _NTO_SIDE_CHANNEL into index, this behavior might result:
• If file descriptor 0 is in use, file descriptor 1 isn’t in use, and you call
ConnectAttach() with 0 specified for index, a connection ID of 1 is returned.
File descriptor 1 (i.e. connection ID 1) is used as stdout, which is what printf()
writes to. If your process makes any calls to printf(), NULL-terminated character
strings are sent to the channel that you’ve connected to. Similar situations can
happen with connection IDs 0 (stdin) and 2 (stderr).
• Depending on how a child process is created, it may inherit the parent’s file
descriptors.
Since connections are treated like file descriptors, a connection created by the
parent without _NTO_SIDE_CHANNEL in index and without
_NTO_COF_CLOEXEC in flags, causes a child process to inherit that connection
during process creation. This inheritance is done during process creation by
duplicating file descriptors.
During duplication, an _IO_DUP message (with 0x115) as the first 2 bytes) is sent
to the receiver on the other side of the connection. The receiver won’t be expecting
this message.
If index has _NTO_SIDE_CHANNEL set, the index is ignored and the connection ID
returned is the first available index in the _NTO_SIDE_CHANNEL space.
If a process creates multiple connections to the same channel, the system maintains a
link count and shares internal kernel object resources for efficiency.
264
QNX Neutrino Functions and Macros
June 19, 2012
ConnectAttach(), ConnectAttach_r()
© 2012, QNX Software Systems Limited
Connections are owned by the process and may be used simultaneously by any thread
in the process. You can detach a connection by calling ConnectDetach(). If any
threads are blocked on the channel (via MsgSendv()) at the time the connection is
detached, the send fails and returns with an error.
Connections and connection IDs persist until you call ConnectDetach(), even if the
other process dies.
The connection is strictly local (i.e. it doesn’t resolve across the network) and is
resolved on the first use of the connection ID.
Blocking states
These calls don’t block.
Node descriptors
The nd (node descriptor) is a temporary numeric description of a remote node. For
more information, see the Qnet Networking chapter of the System Architecture guide.
To:
Use this function:
Compare two nd objects
ND_NODE_CMP()
Convert a nd to text
netmgr_ndtostr()
Convert text to a nd
netmgr_strtond()
Returns:
The only difference between these functions is the way they indicate errors:
ConnectAttach()
A connection ID that’s used by the message primitives. If an
error occurs, the function returns -1 and sets errno.
ConnectAttach_r()
A connection ID that’s used by the message primitives. This
function does NOT set errno. If an error occurs, the function
returns the negative of a value from the Errors section.
Errors:
EAGAIN
Insufficent resources.
EINVAL
One of the following:
• The value of index is outside the range of valid connection IDs.
This error applies only to file descriptors, not side channels
(there’s no limit on the range for side channels).
• The combination of bits in the flags argument is invalid.
June 19, 2012
QNX Neutrino Functions and Macros
265
ConnectAttach(), ConnectAttach_r()
EMFILE
ENOREMOTE
© 2012, QNX Software Systems Limited
The process has no unused file descriptors, or no file descriptors
greater than or equal to index are available.
The node indicated by nd doesn’t exist.
ENXIO
The process indicated by pid is no longer valid. It’s going away, has
core dumped, or become a zombie.
ESRCH
The process indicated by pid, or the channel indicated by chid,
doesn’t exist.
Classification:
QNX Neutrino
Safety
Cancellation point
Yes
Interrupt handler
No
Signal handler
Yes
Thread
Yes
See also:
ChannelCreate(), ConnectDetach(), execl(), execle(), execlp(), execlpe(), execv(),
execve(), execvp(), execvpe(), MsgSendPulse(), MsgSendv(), name_attach(),
name_open(), netmgr_remote_nd()
Message Passing chapter of Getting Started with QNX Neutrino
266
QNX Neutrino Functions and Macros
June 19, 2012
© 2012, QNX Software Systems Limited
ConnectClientInfo(), ConnectClientInfo_r()
Store information about a client connection
Synopsis:
#include <sys/neutrino.h>
int ConnectClientInfo( int scoid,
struct _client_info * info
int ngroups );
int ConnectClientInfo_r( int scoid,
struct _client_info * info
int ngroups );
Arguments:
scoid
A server connection ID that identifies the client process that you want to
get information about. This client is typically a process that’s made a
connection to the server to try to access a resource. You can get it from
the _msg_info argument to MsgReceivev() or MsgInfo().
info
A pointer to a _client_info structure that the function can fill with
information about the client. For more information, see below.
ngroups
The size of the caller’s grouplist in the credential part of the
_client_info structure. If you make it smaller than NGROUPS_MAX,
you might get information only about a subset of the groups.
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
These calls get information about a client connection identified by scoid, and store it
in the buffer that info points to.
The ConnectClientInfo() and ConnectClientInfo_r() functions are identical except in
the way they indicate errors. See the Returns section for details.
A server uses these functions to determine whether or not a client has permission to
access a resource. For example, in a resource manager, it would be called on an open()
connection request.
_client_info structure
The _client_info structure has at least the following members:
June 19, 2012
uint32_t nd
The client’s node ID.
pid_t pid
The client’s process ID.
QNX Neutrino Functions and Macros
267
ConnectClientInfo(), ConnectClientInfo_r()
© 2012, QNX Software Systems Limited
pid_t sid
Used internally by Qnet.
struct _cred_info cred
The user and group ID credentials; see below.
uint32_t nd
The nd (node descriptor) is a temporary numeric description of a remote node;
ND_LOCAL_NODE (or 0) is the descriptor for the local node. For more information,
see the Qnet Networking chapter of the System Architecture guide.
To:
Use this function:
Compare two nd objects
ND_NODE_CMP()
Convert a nd to text
netmgr_ndtostr()
Convert text to a nd
netmgr_strtond()
_cred_info structure
The cred member of the _client_info is a _cred_info structure that includes at
least the following members:
uid_t ruid
The real user ID of the sending process.
uid_t euid
The effective user ID of the sending process.
uid_t suid
The saved user ID of the sending process.
gid_t rgid
The real group ID of the sending process.
gid_t egid
The effective group ID of the sending process.
gid_t sgid
The saved group ID of the sending process.
uint32_t ngroups
The number of groups actually stored in grouplist.
gid_t grouplist[NGROUPS_MAX]
The supplementary group IDs of the sending process.
The ngroups argument to ConnectClientInfo() indicates the size of the grouplist array.
If the group array size is zero, the ngroups member of the _cred_info is set to the
number of groups available.
268
QNX Neutrino Functions and Macros
June 19, 2012
ConnectClientInfo(), ConnectClientInfo_r()
© 2012, QNX Software Systems Limited
Returns:
The only difference between these functions is the way they indicate errors:
ConnectClientInfo()
If an error occurs, the function returns -1 and sets errno. Any other value
returned indicates success.
ConnectClientInfo_r()
EOK is returned on success. This function does NOT set errno. If an error
occurs, the function can return any value in the Errors section.
Errors:
EFAULT
A fault occurred when the kernel tried to access the buffers provided.
EINVAL
Process doesn’t have a connection scoid.
Classification:
QNX Neutrino
Safety
Cancellation point
No
Interrupt handler
No
Signal handler
Yes
Thread
Yes
See also:
ConnectServerInfo(), _msg_info, MsgInfo(), MsgReceivev(), ND_NODE_CMP(),
netmgr_ndtostr(), netmgr_remote_nd(), netmgr_strtond()
June 19, 2012
QNX Neutrino Functions and Macros
269
ConnectDetach(), ConnectDetach_r()
© 2012, QNX Software Systems Limited
Break a connection between a process and a channel
Synopsis:
#include <sys/neutrino.h>
int ConnectDetach( int coid );
int ConnectDetach_r( int coid );
Arguments:
coid
The connection ID of the connection you want to break.
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
The ConnectDetach() and ConnectDetach_r() kernel calls detach the connection
specified by the coid argument. If any threads are blocked on the connection
(MsgSendv()) at the time the connection is detached, the send fails and returns with an
error.
These functions are identical except in the way they indicate errors. See the Returns
section for details.
Blocking states
These calls don’t block.
Returns:
The only difference between these functions is the way they indicate errors:
ConnectDetach()
If an error occurs, the function returns -1 and sets errno. Any
other value returned indicates success.
ConnectDetach_r() EOK is returned on success. This function does NOT set errno.
If an error occurs, the function returns a value in the Errors
section.
Errors:
EINVAL
270
The connection specified by coid doesn’t exist.
QNX Neutrino Functions and Macros
June 19, 2012
© 2012, QNX Software Systems Limited
ConnectDetach(), ConnectDetach_r()
Classification:
QNX Neutrino
Safety
Cancellation point
Yes
Interrupt handler
No
Signal handler
Yes
Thread
Yes
See also:
ConnectAttach(), MsgSendv()
Message Passing chapter of Getting Started with QNX Neutrino
June 19, 2012
QNX Neutrino Functions and Macros
271
ConnectFlags(), ConnectFlags_r()
© 2012, QNX Software Systems Limited
Modify the flags associated with a connection
Synopsis:
#include <sys/neutrino.h>
int ConnectFlags( pid_t pid,
int coid,
unsigned mask,
unsigned bits );
int ConnectFlags_r( pid_t pid,
int coid,
unsigned mask,
unsigned bits );
Arguments:
pid
The ID of the process that the connection ID belongs to, or 0 for the current
process.
coid
The ID of the connection whose flags you want to modify.
mask
A bitmap that indicates which bits are to be modified in the flags.
bits
The new value of the flags. The flags currently defined include:
• _NTO_COF_CLOEXEC — close the connection if the process calls an
exec*() function to start a new process.
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
The ConnectFlags() and ConnectFlags_r() kernel calls modify flags associated with
the specified connection. These kernel calls don’t block.
These functions are identical except in the way they indicate errors. See the Returns
section for details.
You need to initialize the bits that correspond to the flag in both the mask and bits
arguments:
• If the bit in the mask is 1, and the bit in the bits is 1, the function turns the flag on.
• If the bit in the mask is 1, and the bit in the bits is 0, the function turns the flag off.
• If bit in the mask is 0, the function doesn’t change the current value of the flag.
272
QNX Neutrino Functions and Macros
June 19, 2012
ConnectFlags(), ConnectFlags_r()
© 2012, QNX Software Systems Limited
Returns:
The only difference between these functions is the way they indicate errors:
ConnectFlags()
The previous value of the flags associated with the connection.
If an error occurs, the function returns -1 and sets errno.
ConnectFlags_r()
The previous value of the flags associated with the connection.
This function does NOT set errno. If an error occurs, the
negative of a value from the Errors section is returned.
Errors:
EBADF
The coid isn’t a valid connection ID for the process.
ESRCH
The process ID is invalid.
Classification:
QNX Neutrino
Safety
Cancellation point
No
Interrupt handler
No
Signal handler
Yes
Thread
Yes
See also:
ConnectAttach(), fcntl()
June 19, 2012
QNX Neutrino Functions and Macros
273
ConnectServerInfo(), ConnectServerInfo_r()
© 2012, QNX Software Systems Limited
Get information about a server connection
Synopsis:
#include <sys/neutrino.h>
int ConnectServerInfo( pid_t pid,
int coid,
struct _server_info* info );
int ConnectServerInfo_r( pid_t pid,
int coid,
struct _server_info* info );
Arguments:
pid
The process ID of the owner of the connection.
coid
The connection ID of the connection.
info
NULL, or a pointer to a _server_info structure where the function can
store information about the connection. For more information, see below.
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
The ConnectServerInfo() and ConnectServerInfo_r() kernel calls get information
about the connection coid owned by process pid, and store it in the structure pointed to
by info. If the process doesn’t have a connection coid, the call scans for the next
higher connection and returns it if present. Otherwise, -1 is returned. If you wish to
check for the existence of an exact connection, you must compare the returned
connection with the coid you requested.
These functions are identical except in the way they indicate errors. See the Returns
section for details.
If the info argument is NULL, ConnectServerInfo() ignores connections with dead
servers and skips to the next coid. If info is non-NULL, the function fills in the
_server_info structure; for connections with dead servers, it turns on the
_NTO_COF_DEAD bit in the flags field of the structure.
_server_info structure
The _server_info structure that info points to includes at least the following
members:
uint32_t nd
274
QNX Neutrino Functions and Macros
The server’s node descriptor, a temporary numeric description of a
remote node; ND_LOCAL_NODE (or 0) is the descriptor for the
June 19, 2012
© 2012, QNX Software Systems Limited
ConnectServerInfo(), ConnectServerInfo_r()
local node. For more information, see the Qnet Networking
chapter of the System Architecture guide.
To:
Use this function:
Compare two nd objects ND_NODE_CMP()
Convert a nd to text
netmgr_ndtostr()
Convert text to a nd
netmgr_strtond()
pid_t pid
The server’s process ID.
int32_t chid
The server’s channel ID.
int32_t scoid
The server’s connection ID.
int32_t coid
The client’s connection ID.
int16_t flags
Flags that indicate the properties of the connection. The bits
include:
• _NTO_COF_CLOEXEC — the connection will be closed when
your process calls an exec*() function to start a new process.
• _NTO_COF_DEAD — the connection is to a dead server.
• _NTO_COF_NOSHARE — some internal data structures aren’t
shared. For asynchronous messaging, this indicates that the
application wants to use its own buffer; see
asyncmsg_connect_attach().
• _NTO_COF_NONBLOCK — don’t block waiting if all the send
headers are in use; for asynchronous messaging.
• _NTO_COF_ASYNC — the connection is for asynchronous
messaging.
• _NTO_COF_GLOBAL — the connection is to a global channel.
Returns:
The only difference between these functions is the way they indicate errors:
ConnectServerInfo()
A matched coid. If an error occurs, the function returns -1 and sets errno.
ConnectServerInfo_r()
A matched coid. This function does NOT set errno. If an error occurs, the
function returns the negative of a value from the Errors section.
June 19, 2012
QNX Neutrino Functions and Macros
275
ConnectServerInfo(), ConnectServerInfo_r()
© 2012, QNX Software Systems Limited
Errors:
EFAULT
EINVAL
A fault occurred when the kernel tried to access the buffers provided.
Process pid doesn’t have a connection >= coid.
ESRCH
The process indicated by pid doesn’t exist.
Classification:
QNX Neutrino
Safety
Cancellation point
Yes
Interrupt handler
No
Signal handler
Yes
Thread
Yes
See also:
asyncmsg_connect_attach(), ConnectAttach(), ConnectClientInfo(), MsgInfo(),
MsgReceivev(), ND_NODE_CMP(), netmgr_ndtostr(), netmgr_remote_nd(),
netmgr_strtond()
276
QNX Neutrino Functions and Macros
June 19, 2012
copysign(), copysignf()
© 2012, QNX Software Systems Limited
Copy the sign bit from one number to another
Synopsis:
#include <math.h>
double copysign ( double x,
double y);
float copysignf ( float x,
float y );
Arguments:
x
The number to use the magnitude of.
y
The number to use the sign of.
Library:
libm
Use the -l m option to qcc to link against this library.
Description:
The copysign() and copysignf() functions return the magnitude of x and the sign bit of
y.
If x is NAN, the function produces NAN with the sign of y.
Returns:
The magnitude of x and the sign bit of y.
Examples:
#include
#include
#include
#include
#include
<stdio.h>
<errno.h>
<inttypes.h>
<math.h>
<fpstatus.h>
int main(int argc, char** argv)
{
double a, b, c;
a = 27.0;
b = -5;
c = copysign(a, b);
printf("The magnitude of %f and sign of %f gives %f\n",
a, b, c);
return(0);
}
produces the output:
The magnitude of 27.000000 and sign of -5.000000 gives -27.000000
June 19, 2012
QNX Neutrino Functions and Macros
277
copysign(), copysignf()
© 2012, QNX Software Systems Limited
Classification:
ANSI, POSIX 1003.1
Safety
278
Cancellation point
No
Interrupt handler
No
Signal handler
No
Thread
Yes
QNX Neutrino Functions and Macros
June 19, 2012
cos(), cosf(), cosl()
© 2012, QNX Software Systems Limited
Compute the cosine of an angle
Synopsis:
#include <math.h>
double cos( double x );
float cosf( float x );
long double cosl( long double x );
Arguments:
x
The angle, in radians, for which you want to compute the cosine.
Library:
libm
Use the -l m option to qcc to link against this library.
Description:
These functions compute the cosine of x (specified in radians).
An argument with a large magnitude may yield results with little or no significance.
Returns:
The cosine of x. When x is +/-Inf, these functions return NaN.
If an error occurs, these functions return 0, but this is also a valid mathematical result.
If you want to check for errors, set errno to 0, call the function, and then check errno
again. These functions don’t change errno if no errors occurred.
Examples:
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
int main( void )
{
double value;
value = cos( M_PI );
printf( "value = %f\n", value );
return EXIT_SUCCESS;
}
produces the output:
June 19, 2012
QNX Neutrino Functions and Macros
279
cos(), cosf(), cosl()
© 2012, QNX Software Systems Limited
value = -1.000000
Classification:
ANSI, POSIX 1003.1
Safety
Cancellation point
No
Interrupt handler
No
Signal handler
No
Thread
Yes
See also:
acos(), errno, sin(), tan()
280
QNX Neutrino Functions and Macros
June 19, 2012
cosh(), coshf(), coshl()
© 2012, QNX Software Systems Limited
Compute the hyperbolic cosine
Synopsis:
#include <math.h>
double cosh( double x );
float coshf( float x );
long double coshl( long double x );
Arguments:
x
The angle, in radians, for which you want to compute the hyperbolic cosine.
Library:
libm
Use the -l m option to qcc to link against this library.
Description:
These functions compute the hyperbolic cosine (specified in radians) of x. A range
error occurs if the magnitude of x is too large.
Returns:
The hyperbolic cosine of x.
If an error occurs, these functions return 0, but this is also a valid mathematical result.
If you want to check for errors, set errno to 0, call the function, and then check errno
again. These functions don’t change errno if no errors occurred.
Examples:
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
int main( void )
{
printf( "%f\n", cosh(.5) );
return EXIT_SUCCESS;
}
produces the output:
1.127626
June 19, 2012
QNX Neutrino Functions and Macros
281
cosh(), coshf(), coshl()
© 2012, QNX Software Systems Limited
Classification:
ANSI, POSIX 1003.1
Safety
Cancellation point
No
Interrupt handler
No
Signal handler
No
Thread
Yes
See also:
errno, sinh(), tanh()
282
QNX Neutrino Functions and Macros
June 19, 2012
creat(), creat64()
© 2012, QNX Software Systems Limited
Create and open a file (low-level)
Synopsis:
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
int creat( const char* path,
mode_t mode );
int creat64( const char* path,
mode_t mode );
Arguments:
path
The path of the file you want to open.
mode
The access permissions that you want to use. For more information, see
“Access permissions” in the documentation for stat().
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
The creat() and creat64() functions create and open the file specified by path with the
given mode.
Calling creat() is the same as:
open( path, O_WRONLY | O_CREAT | O_TRUNC, mode );
Similarly, calling creat64() is the same as:
open64( path, O_WRONLY | O_CREAT | O_TRUNC | O_LARGEFILE, mode );
If path exists and is writable, it’s truncated to contain no data, and the existing mode
setting isn’t changed.
If path doesn’t exist, it’s created with the access permissions specified by the mode
argument. The access permissions for the file or directory are specified as a
combination of the bits defined in <sys/stat.h>.
Returns:
A file descriptor on success, or -1 if an error occurs (errno is set).
June 19, 2012
QNX Neutrino Functions and Macros
283
creat(), creat64()
© 2012, QNX Software Systems Limited
Errors:
EACCES
Indicates one of the following permission problems:
• Search permission is denied for one of the components in the path.
• The file specified by path exists, and the permissions specified by
mode are denied.
• The file specified by path doesn’t exist, and the file couldn’t be
created because write permission is denied for the parent directory.
EBADFSYS
While attempting to open path, the file itself or a component of its
path prefix was found to be corrupted. A system failure — from
which no automatic recovery is possible — occurred while the file
was being written to or while the directory was being updated. The
filesystem must be repaired before proceeding.
EBUSY
The file specified by path is a block special device that’s already open
for writing, or path names a file on a filesystem mounted on a block
special device that is already open for writing.
EINTR
The call to creat() was interrupted by a signal.
EISDIR
The file specified by path is a directory and the file creation flags
specify write-only or read/write access.
ELOOP
Too many levels of symbolic links.
EMFILE
This process is using too many file descriptors.
ENAMETOOLONG
The length of path exceeds PATH_MAX, or a pathname component is
longer than NAME_MAX.
284
ENFILE
Too many files are currently open in the system.
ENOENT
Either the path prefix doesn’t exist, or the path argument points to an
empty string.
ENOSPC
The directory or filesystem that would contain the new file doesn’t
have enough space available to create a new file.
ENOSYS
The creat() function isn’t implemented for the filesystem specified by
path.
ENOTDIR
A component of the path prefix isn’t a directory.
EROFS
The file specified by path resides on a read-only filesystem.
QNX Neutrino Functions and Macros
June 19, 2012
creat(), creat64()
© 2012, QNX Software Systems Limited
Examples:
#include
#include
#include
#include
<sys/types.h>
<sys/stat.h>
<fcntl.h>
<stdlib.h>
int main( void )
{
int filedes;
filedes = creat( "file",
S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP );
if( filedes != -1 ) {
/* process file */
close( filedes );
return EXIT_SUCCESS;
}
return EXIT_FAILURE;
}
Classification:
creat() is POSIX 1003.1; creat64() is Large-file support
Safety
Cancellation point
Yes
Interrupt handler
No
Signal handler
Yes
Thread
Yes
See also:
chsize(), close(), dup(), dup2(), eof(), errno, execl(), execle(), execlp(), execlpe(),
execv(), execve(), execvp(), execvpe(), fcntl(), fileno(), fstat(), isatty(), lseek(), open(),
read(), sopen(), stat(), tell(), write(), umask()
June 19, 2012
QNX Neutrino Functions and Macros
285
crypt()
© 2012, QNX Software Systems Limited
Encrypt a password
Synopsis:
#include <unistd.h>
char * crypt( const char * key,
const char * salt );
Arguments:
key
A NUL-terminated string (normally a password typed by a user).
salt
A two-character string chosen from the set [a-zA-Z0-9./]. This function
doesn’t validate the values for salt, and values outside this range may cause
undefined behavior. This string is used to perturb the algorithm in one of 4096
different ways.
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
This function is in libc.a, but not in libc.so (in order to save space).
Description:
The crypt() function performs password encryption. It’s based on the Data Encryption
Standard algorithm, and also includes code to deter key search attempts.
This function checks only the first eight characters of key.
You can obtain a 56-bit key by taking the lowest 7 bits of key. The 56-bit key is used to
repeatedly encrypt a constant string (usually all zeroes).
Returns:
A pointer to the 13-character encrypted value, or NULL on failure. The first two
characters of the encrypted value are the salt itself.
Classification:
POSIX 1003.1 XSI
Safety
Cancellation point
No
continued. . .
286
QNX Neutrino Functions and Macros
June 19, 2012
crypt()
© 2012, QNX Software Systems Limited
Safety
Interrupt handler
No
Signal handler
No
Thread
No
Caveats:
The return value points to static data that’s overwritten by each call to crypt().
See also:
encrypt(), getpass(), qnx_crypt(), setkey()
login in the Utilities Reference
For license information, see the Third Party License Terms List at
http://licensing.qnx.com/third-party-terms/.
June 19, 2012
QNX Neutrino Functions and Macros
287
ctermid()
© 2012, QNX Software Systems Limited
Generate the path name of the current controlling terminal
Synopsis:
#include <stdio.h>
char * ctermid( char * s );
Arguments:
s
NULL, or a pointer to a buffer in which the function can store the path name of
the controlling terminal. This string should be at least L_ctermid characters long
(see <stdio.h>).
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
The ctermid() function generates a string that contains the path name of the current
controlling terminal for the calling process.
If the argument s is NULL, the string is built in a static buffer, and the function returns
a pointer to the buffer.
Returns:
A pointer to the path name of the controlling terminal, or a pointer to a null string if
the function can’t locate the controlling terminal.
Examples:
#include <stdio.h>
#include <stdlib.h>
int main( void )
{
printf( "Controlling terminal is %s\n", ctermid( NULL ) );
return EXIT_SUCCESS;
}
Classification:
POSIX 1003.1
Safety
Cancellation point
No
continued. . .
288
QNX Neutrino Functions and Macros
June 19, 2012
ctermid()
© 2012, QNX Software Systems Limited
Safety
Interrupt handler
No
Signal handler
No
Thread
Read the Caveats
Caveats:
The ctermid() function isn’t thread-safe if the s argument is NULL.
See also:
setsid(), ttyname()
June 19, 2012
QNX Neutrino Functions and Macros
289
ctime(), ctime_r()
© 2012, QNX Software Systems Limited
Convert calendar time to local time
Synopsis:
#include <time.h>
char* ctime( const time_t* timer );
char* ctime_r( const time_t* timer,
char* buf );
Arguments:
timer
A pointer to a time_t object that contains the time that you want to convert
to a string.
buf
(ctime_r() only) A buffer in which ctime_r() can store the resulting string.
This buffer must be large enough to hold at least 26 characters.
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
The ctime() and ctime_r() functions convert the time pointed to by timer to local time
and formats it as a string containing exactly 26 characters in the form:
Tue May
7 10:40:27 2002\n\0
This function:
Is equivalent to calling:
ctime()
asctime( localtime ( timer ) );
ctime_r()
asctime_r( localtime ( timer ), buf )
The ctime() function places the result string in a static buffer that’s reused each time
you call ctime() or asctime(). Calling gmtime() or localtime() could also change the
date in this static buffer.
The result string for ctime_r() is contained in the buffer pointed to by buf .
All fields have a constant width. The newline character ’\n’ and NUL character ’\0’
occupy the last two positions of the string.
Whenever the ctime() or ctime_r() functions are called, the tzset() function is also
called.
290
QNX Neutrino Functions and Macros
June 19, 2012
ctime(), ctime_r()
© 2012, QNX Software Systems Limited
The calendar time is usually obtained by using the time() function. That time is
Coordinated Universal Time (UTC) (formerly known as Greenwich Mean Time
(GMT)).
You typically set the time on the computer with the date command to reflect
Coordinated Universal Time (UTC), and then use the TZ environment variable or
_CS_TIMEZONE configuration string to establish the local time zone. For more
information, see “Setting the time zone” in the Configuring Your Environment chapter
of the Neutrino User’s Guide.
Returns:
A pointer to the string containing the formatted local time, or NULL if an error occurs.
Classification:
ctime() is ANSI, POSIX 1003.1; ctime_r() is POSIX 1003.1 TSF
ctime()
Safety
Cancellation point
No
Interrupt handler
No
Signal handler
Yes
Thread
No
ctime_r()
Safety
Cancellation point
No
Interrupt handler
No
Signal handler
Yes
Thread
Yes
Caveats:
The asctime() and ctime() functions place their results in a static buffer that’s reused
for each call to asctime() or ctime().
See also:
asctime(), asctime_r(), clock(), difftime(), gmtime(), localtime(), localtime_r(),
mktime(), strftime(), time(), tzset()
“Setting the time zone” in the Configuring Your Environment chapter of the Neutrino
User’s Guide
June 19, 2012
QNX Neutrino Functions and Macros
291
daemon()
© 2012, QNX Software Systems Limited
Run a process in the background
Synopsis:
#include <stdlib.h>
int daemon( int nochdir,
int noclose );
Arguments:
nochdir
If this argument is 0, the current working directory is changed to the root
directory (/).
noclose
If this argument is 0, standard input, standard output, and standard error
are redirected to /dev/null.
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
The daemon() function allows programs to detach themselves from the controlling
terminal and run in the background as system daemons.
This function calls fork() and setsid().
The controlling terminal behaves as in Unix System V, Release 4. An open() on a
terminal device not already associated with another session causes the device to
become the controlling terminal for that process.
The High Availability Manager can see death messages only from self-attached
entities, processes that terminate abnormally, and tasks that are running in session 1.
The daemon() function doesn’t put the caller into that session; either make your
process into a self-attached entity, or use procmgr_daemon() instead if you want to
use your application with the HAM.
The HAM automatically switches to monitoring the new process that daemon()
creates, if the original process was a self-attached entity. For more information, see the
High Availability Framework Developer’s Guide.
Returns:
Zero for success, or -1 if an error occurs (errno is set).
292
QNX Neutrino Functions and Macros
June 19, 2012
daemon()
© 2012, QNX Software Systems Limited
Classification:
Legacy Unix
Safety
Cancellation point
No
Interrupt handler
No
Signal handler
Yes
Thread
No
Caveats:
Currently, daemon() is supported only in single-threaded applications. If you create a
thread and then call daemon(), the function returns -1 and sets errno to ENOSYS.
See also:
fork(), procmgr_daemon(), setsid()
June 19, 2012
QNX Neutrino Functions and Macros
293
daylight
© 2012, QNX Software Systems Limited
Indicator of support for daylight saving time in the locale
Synopsis:
#include <time.h>
unsigned int daylight;
Description:
This global variable has a value of 1 when daylight saving time is supported in this
locale, and 0 otherwise. Whenever you call a time function, tzset() is called to set the
variable, based on the current time zone.
Classification:
POSIX 1003.1 XSI
See also:
timezone, tzname, tzset()
“Setting the time zone” in the Configuring Your Environment chapter of the Neutrino
User’s Guide
294
QNX Neutrino Functions and Macros
June 19, 2012
DebugBreak()
© 2012, QNX Software Systems Limited
Enter the process debugger
Synopsis:
#include <sys/neutrino.h>
void DebugBreak( void );
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
The DebugBreak() kernel call activates the process debugger if you’re debugging the
calling process. If not, it sends a SIGTRAP signal to the process.
Blocking states
None.
Classification:
QNX Neutrino
Safety
Cancellation point
No
Interrupt handler
No
Signal handler
Yes
Thread
Yes
Caveats:
If you call DebugBreak() from an interrupt handler, it’ll activate the kernel debugger
(if it’s present in your boot image) or send the process a SIGTRAP signal.
See also:
DebugKDBreak(), DebugKDOutput()
June 19, 2012
QNX Neutrino Functions and Macros
295
DebugKDBreak()
© 2012, QNX Software Systems Limited
Enter the kernel debugger
Synopsis:
#include <sys/neutrino.h>
void DebugKDBreak( void );
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
The DebugKDBreak() kernel call activates the kernel debugger if it’s present in your
boot image. If not, nothing happens.
Blocking states
None.
Classification:
QNX Neutrino
Safety
Cancellation point
No
Interrupt handler
No
Signal handler
Yes
Thread
Yes
See also:
DebugBreak(), DebugKDOutput()
296
QNX Neutrino Functions and Macros
June 19, 2012
DebugKDOutput()
© 2012, QNX Software Systems Limited
Print text with the kernel debugger
Synopsis:
#include <sys/neutrino.h>
void DebugKDOutput( const char* str,
size_t size );
Arguments:
str
The string that you want to print.
size
The number of characters to print.
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
The DebugKDBreak() kernel call causes the kernel debugger to print size characters
from str if the kernel debugger is present in your boot image. If it isn’t in your boot
image, nothing happens.
When, where, and how the kernel debugger displays this message depends on which
host debugger you’re using.
Blocking states
None.
Classification:
QNX Neutrino
Safety
Cancellation point
No
Interrupt handler
No
Signal handler
Yes
Thread
Yes
See also:
DebugBreak(), DebugKDBreak()
June 19, 2012
QNX Neutrino Functions and Macros
297
delay()
© 2012, QNX Software Systems Limited
Suspends a calling thread for a given length of time
Synopsis:
#include <unistd.h>
unsigned int delay( unsigned int duration );
Arguments:
duration
The number of milliseconds for which to suspend the calling thread from
execution.
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
The delay() function suspends the calling thread for duration milliseconds.
The suspension time may be greater than the requested amount, due to the nature of
time measurement (see the Tick, Tock: Understanding the Neutrino Microkernel’s
Concept of Time chapter of the QNX Neutrino Programmer’s Guide), or due to the
scheduling of other, higher-priority threads by the system.
Returns:
0 for success, or the number of unslept milliseconds if interrupted by a signal.
Errors:
If an error occurs, errno is set to:
EAGAIN
No timer resources were available to satisfy the request.
Examples:
#include <unistd.h>
#include <stdlib.h>
void play_sound( void )
{
...
}
void stop_sound( void )
{
...
}
int main( void )
298
QNX Neutrino Functions and Macros
June 19, 2012
delay()
© 2012, QNX Software Systems Limited
{
play_sound();
delay( 500 );
stop_sound();
/* delay for 1/2 second */
return EXIT_SUCCESS;
}
Classification:
QNX 4
Safety
Cancellation point
Yes
Interrupt handler
No
Signal handler
Yes
Thread
Yes
See also:
alarm(), errno, nanosleep(), nap(), napms(), sleep(), usleep()
Clocks, Timers, and Getting a Kick Every So Often chapter of Getting Started with
QNX Neutrino
Tick, Tock: Understanding the Neutrino Microkernel’s Concept of Time chapter of the
QNX Neutrino Programmer’s Guide
June 19, 2012
QNX Neutrino Functions and Macros
299
devctl()
© 2012, QNX Software Systems Limited
Control a device
Synopsis:
#include <sys/types.h>
#include <unistd.h>
#include <devctl.h>
int devctl( int filedes,
int dcmd,
void * dev_data_ptr,
size_t n_bytes,
int * dev_info_ptr );
int devctlv( int filedes,
int dcmd,
int sparts,
int rparts,
const iov_t *sv,
const iov_t *rv,
int *dev_info_ptr);
Arguments:
filedes
A file descriptor that you obtained by opening the device.
dcmd
A device-specific command for the process managing the open
device. The set of valid device-control commands, the associated
data interpretation, the returned dev_info_ptr values, and the effect
of the command on the device all depend on the device driver.
For:
See:
General information
“Device-control commands,”
below
Commands for manipulating
processes
“Controlling processes via the
/proc filesystem” in the
Processes chapter of the QNX
Neutrino Programmer’s Guide
Specific commands
dev_data_ptr
<sys/dcmd_*.h> header files
(devctl() only) Depending on the command, this argument is one
of:
• a pointer to a buffer containing data to be passed to the driver
• a receiving area for data coming from the driver
• both of the above
• NULL.
300
QNX Neutrino Functions and Macros
June 19, 2012
devctl()
© 2012, QNX Software Systems Limited
n_bytes
(devctl() only) The size of the data to be sent to the driver, or the
maximum size of the data to be received from the driver.
sparts
(devctlv() only) The number of elements in the sv array.
rparts
(devctlv() only) The number of elements in the rv array.
sv
(devctlv() only) An array of buffers that hold the data to send to the
driver.
rv
(devctlv() only) An array of buffers in which the driver can store
data to return to the caller.
dev_info_ptr
NULL, or a pointer to a location that the device to can use to return
additional status information instead of just success or failure. The
data returned via dev_info_ptr depends on the device driver.
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
The devctl() function sends the device-specific command dcmd to the process
managing the device opened as filedes. For example, you can send commands to
specify properties for devices such as keyboards, sound cards or serial ports.
The devctlv() function is similar to devctl(), but uses I/O vectors for passing data to
and from the driver.
Device-control commands
Use these macros to set up the device-control commands:
__DIOF(class, cmd, data)
Get information from the device.
__DION(class, cmd)
A command with no associated data.
__DIOT(class, cmd, data)
Pass information to the device.
__DIOTF(class, cmd, data)
Pass some information to the device, and get some from it.
The arguments to these macros are:
June 19, 2012
QNX Neutrino Functions and Macros
301
devctl()
© 2012, QNX Software Systems Limited
class
The major category for the command. The device-control commands are
divided into the following classes to make organization easier:
• _DCMD_ALL — Common (all I/O servers).
• _DCMD_CAM — Low-level (Common Access Method) devices, such as
disks or CD-ROMs.
• _DCMD_CHR — Character devices.
• _DCMD_FSYS, _DCMD_BLK — Filesystem/block I/O managers.
• _DCMD_INPUT — Input devices.
• _DCMD_IP — Internet Protocol.
• _DCMD_MEM — Memory card.
• _DCMD_MISC — Miscellaneous commands.
• _DCMD_MIXER — Mixer (Audio).
• _DCMD_NET — Network devices.
• _DCMD_PHOTON — Photon.
• _DCMD_PROC — Process manager.
cmd
The specific command in the class.
data
The type of data to pass to and/or from the device. The dev_data_ptr
argument to devctl() must be a pointer to this type of data, and n_bytes is
usually the size of this type of data.
The size of the structure that’s passed as the last field to the __DIO* macros must be
less than 2ˆ14 == 16 KB. Anything larger than this interferes with the upper two
directional bits.
Resource managers can use the following macros, which are defined in <devctl.h>,
when handling commands:
get_device_command(cmd)
Extract the class and the specific device command from cmd (i.e. strip off the
data type and the direction).
get_device_direction(cmd)
Get the direction of the command (DEVDIR_TO, DEVDIR_FROM,
DEVDIR_TOFROM, or DEVDIR_NONE).
Returns:
302
EOK
Success.
EAGAIN
The devctl() command couldn’t be completed because the device driver
was in use by another process, or the driver was unable to carry out the
request due to an outstanding command in progress.
QNX Neutrino Functions and Macros
June 19, 2012
devctl()
© 2012, QNX Software Systems Limited
EBADF
Invalid open file descriptor, filedes.
EINTR
The devctl() function was interrupted by a signal.
EINVAL
The device driver detected an error in dev_data_ptr or n_bytes.
EIO
The devctl() function couldn’t complete because of a hardware error.
ENOSYS
The device doesn’t support the dcmd command.
ENOTTY
The dcmd argument isn’t a valid command for this device.
EPERM
The process doesn’t have sufficient permission to carry out the
requested command.
Examples:
Example 1: Setting RTS on a serial port
Here’s a quick example of setting and unsetting RTS (Request to Send) on a serial port:
/* For "devctl()" */
#include <devctl.h>
#include <sys/dcmd_chr.h>
/* For "open()" */
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
/* For Errors */
#include <stdlib.h>
#include <stdio.h>
int check_RTS(int fd);
int main(void)
{
int data = 0, fd, error;
if((fd = open ("/dev/ser2", O_RDONLY)) == -1)
{
fprintf(stderr,
"Error with open() on /dev/ser2. Make sure it exists.\n");
perror (NULL);
exit(EXIT_FAILURE);
}
check_RTS(fd);
/* Let’s turn ON RTS now. */
data = _CTL_RTS_CHG | _CTL_RTS;
if (error = devctl (fd, DCMD_CHR_SERCTL, &data,
sizeof(data), NULL))
{
fprintf(stderr, "Error setting RTS: %s\n",
strerror ( error ));
exit(EXIT_FAILURE);
}
June 19, 2012
QNX Neutrino Functions and Macros
303
devctl()
© 2012, QNX Software Systems Limited
/* RTS should now be ON. */
check_RTS(fd);
sleep (2);
/* Now let’s turn RTS OFF. */
data = _CTL_RTS_CHG | 0;
if (error = devctl (fd, DCMD_CHR_SERCTL, &data,
sizeof(data), NULL))
{
fprintf(stderr, "Error setting RTS: %s\n",
strerror ( error ));
exit(EXIT_FAILURE);
}
/* RTS should now be OFF. */
check_RTS(fd);
close(fd);
return (1);
}
int check_RTS(int fd)
{
int data = 0, error;
/*
Let’s see if RTS is set, tell devctl() we’re requesting
line status information and devctl() then assigns data
the line status information for us. Too easy.
*/
if (error = devctl (fd, DCMD_CHR_LINESTATUS, &data,
sizeof(data), NULL))
{
fprintf(stderr, "Error setting RTS: %s\n",
strerror ( error ));
exit(EXIT_FAILURE);
}
if (data & _LINESTATUS_SER_RTS)
printf("RTS is SET!\n");
else
printf("RTS is NOT set\n");
return(1);
}
The two main areas of interest are the setting of data and the devctl() call. The data
variable is used for both sending and receiving data.
When setting RTS, data is assigned a value that’s sent to the device via devctl().
304
QNX Neutrino Functions and Macros
June 19, 2012
devctl()
© 2012, QNX Software Systems Limited
If data equals:
RTS is turned:
_CTL_RTS_CHG | _CTL_RTS
ON
_CTL_RTS_CHG
OFF
When checking to see if RTS is set, we call devctl() with dcmd set to the
DCMD_CHR_LINESTATUS macro and data containing any value (zero is clean). The
devctl() function returns with data containing the Line Status value. This then can be
used to determine what lines are set on that device. In our example, we check against
_LINESTATUS_SER_RTS.
To find out what values to use with different DCMD_* commands, look in the
appropriate <sys/dcmd_*.h>header file. For example, you’ll find macros for the
following values under DCMD_CHR_LINESTATUS in <sys/dcmd_chr.h>:
• Serial Port (DTR, RTS, CTS, DSR, RI, CD)
• Keyboard (Scroll/Caps/Num Lock, Shift, CTRL, ALT)
• Parallel Port (No Error, Selected, Paper Out, No Tack, Not Busy)
The value that’s in the header is a “bitwise &” with the value in data to see if the value
is high for that line.
Example 2: Cycling through Caps Lock, Num Lock, and Scroll Lock
In the following example, we open the device /dev/kbd and we start applying
changes to the Caps Lock, Scroll Lock, and Num Lock properties.
The key lines in this example are the same as in the last example; they focus around
the data variable. This value is just a simple integer value that’s passed into the
devctl() function. The data variable is assigned its values by simply performing a
bitwise OR to the predefined values in the </usr/include/sys/dcmd_chr.h>
header. Note the values used in the bitwise OR:
• _CONCTL_NUM_CHG (Console Control Num Lock Change) ORed together with
_CONCTL_NUM (Console Control Num Lock) turns on Num Lock.
• _CONCTL_NUM_CHG on its own turns off Num Lock.
If data equals:
Num Lock is turned:
_CONCTL_NUM_CHG | _CONCTL_NUM
ON
_CONCTL_NUM_CHG
OFF
This also applies for the other either/or values in the <dcmd_chr.h> header.
/* For "devctl()" */
#include <devctl.h>
June 19, 2012
QNX Neutrino Functions and Macros
305
devctl()
© 2012, QNX Software Systems Limited
#include <sys/dcmd_chr.h>
/* For "open()" */
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
/* For Errors */
#include <stdlib.h>
#include <stdio.h>
int main(void)
{
int data, fd, toggle = 1, error;
/* Open the device we wish to manipulate. */
if((fd = open ("/dev/kbd", O_RDONLY)) == -1)
{
fprintf(stderr,
"Error with open() on /dev/kbd. Make sure it exists.\n");
perror (NULL);
exit(EXIT_FAILURE);
}
while(1)
{
switch(toggle)
{
case 1:
{
/*
Turn on Num Lock and make sure that
Caps and Scroll lock are turned off.
*/
data = (_CONCTL_NUM_CHG | _CONCTL_NUM) | _CONCTL_CAPS_CHG |
_CONCTL_SCROLL_CHG;
break;
}
case 2:
{
/*
Turn off Num Lock and now turn on Caps Lock
(Scroll lock is already off).
*/
data = _CONCTL_NUM_CHG | (_CONCTL_CAPS_CHG | _CONCTL_CAPS);
break;
}
case 3:
{
/*
Turn off Caps lock and turn on Scroll lock
(Num lock is already off).
*/
data = _CONCTL_CAPS_CHG | (_CONCTL_SCROLL_CHG | _CONCTL_SCROLL);
toggle = 0;
break;
}
}
/* Explanation below. */
if (error = devctl (fd, DCMD_CHR_SERCTL, &data,
sizeof(data), NULL))
306
QNX Neutrino Functions and Macros
June 19, 2012
devctl()
© 2012, QNX Software Systems Limited
{
fprintf(stderr, "Error setting KBD: %s\n",
strerror ( error ));
exit(EXIT_FAILURE);
}
sleep(1);
toggle++;
}
return (1);
}
Here’s a quick explanation of the above devctl() call:
devctl (fd, DCMD_CHR_SERCTL, &data, sizeof(data), NULL)
The first parameter, fd, is the file descriptor of the device that’s being changed. The
second parameter is the device class that’s being changed. In this case, it’s a character
device DCMD_CHR, with a “subclass” of _SERCTL. The third parameter is the data
variable; this is the ORed value.
Example 3: Duration example
In this code, tcdropline(), which is used to disconnect a communications line, uses
devctl() (this is the actual source code, tcdropline() is a standard library function):
#include
#include
#include
#include
<termios.h>
<devctl.h>
<errno.h>
<sys/dcmd_chr.h>
int tcdropline(int fd, int duration) {
int error;
duration = ((duration ? duration : 300) << 16) |
_SERCTL_DTR_CHG | 0;
if(error = devctl(fd, DCMD_CHR_SERCTL, &duration,
sizeof duration, 0) == -1) {
if(error == ENOSYS) {
errno = ENOTTY;
}
return -1;
}
return 0;
}
Classification:
QNX Neutrino
Safety
Cancellation point
Yes
continued. . .
June 19, 2012
QNX Neutrino Functions and Macros
307
devctl()
© 2012, QNX Software Systems Limited
Safety
Interrupt handler
No
Signal handler
Yes
Thread
Yes
Caveats:
When devctl() fails, the effect of the failed command depends on the device driver. The
corresponding data might be transferred, partially transferred, or not transferred at all.
The devctl() function was originally part of the POSIX 1003.1d draft standard; but it
was deprecated in the IEEE Approved Draft 10 standard.
See also:
close(), GETIOVBASE(), GETIOVLEN(), ioctl(), open(), read(), SETIOV(), write()
“Controlling processes via the /proc filesystem” in the Processes chapter of the QNX
Neutrino Programmer’s Guide
308
QNX Neutrino Functions and Macros
June 19, 2012
difftime()
© 2012, QNX Software Systems Limited
Calculate the difference between two times
Synopsis:
#include <time.h>
double difftime( time_t time1,
time_t time0 );
Arguments:
time1, time0
The times to compare, expressed as time_t objects.
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
The difftime() function calculates the difference between the calendar times specified
by time1 and time0:
time1 - time0
Returns:
The difference between the two times (in seconds).
Examples:
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
void compute( void )
{
int i, j;
for( i = 1; i <= 20; i++ ) {
for( j = 1; j <= 20; j++ ) {
printf( "%3d ", i * j );
}
printf( "\n" );
}
}
int main( void )
{
time_t start_time, end_time;
start_time = time( NULL );
compute();
end_time = time( NULL );
printf( "Elapsed time: %f seconds\n",
difftime( end_time, start_time ) );
return EXIT_SUCCESS;
}
June 19, 2012
QNX Neutrino Functions and Macros
309
difftime()
© 2012, QNX Software Systems Limited
Classification:
ANSI, POSIX 1003.1
Safety
Cancellation point
No
Interrupt handler
No
Signal handler
No
Thread
Yes
See also:
asctime(), clock(), ctime(), gmtime(), localtime(), mktime(), strftime(), time(), tzset()
310
QNX Neutrino Functions and Macros
June 19, 2012
dircntl()
© 2012, QNX Software Systems Limited
Control an open directory
Synopsis:
#include <dirent.h>
int dircntl( DIR * dir,
int cmd,
... );
Arguments:
dir
Provide control for this directory.
cmd
At least the following values are defined in <dirent.h>:
• D_GETFLAG — retrieve the flags associated with the directory referenced
by dir. For more information, see “Flag values,” below.
• D_SETFLAG — set the flags associated with the directory referenced by
dir to the value given as an additional argument. The new value can be
any combination of the flags described in “Flag values,” below.
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
The dircntl() function provides control over the open directory referenced by the dir
argument. This function behaves in a manner similar to the file control function,
fcntl().
Flag values
D_FLAG_FILTER
Filter out duplicate name entries that may occur due to the
union filesystem during a readdir() operation.
D_FLAG_STAT
Indicate to servers that they should attempt to return extra stat()
information as part of the readdir() operation.
Returns:
The return value depends on the value of cmd:
June 19, 2012
D_GETFLAG
The flags associated with the directory.
D_SETFLAG
0.
Any other value
-1 (errno is set to ENOSYS).
QNX Neutrino Functions and Macros
311
dircntl()
© 2012, QNX Software Systems Limited
Examples:
#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
int main(int argc, char **argv) {
DIR *dp;
int ret;
if(!(dp = opendir("/"))) {
exit(EXIT_FAILURE);
}
/* Display the flags that are set on the
directory by default*/
if((ret = dircntl(dp, D_GETFLAG)) == -1) {
exit(EXIT_FAILURE);
}
if(ret & D_FLAG_FILTER) {
printf("Directory names are filtered\n");
} else {
printf("Directory names are not filtered\n");
}
if(ret & D_FLAG_STAT) {
printf("Servers asked for extra stat information\n");
} else {
printf("Servers not asked for extra stat information\n");
}
closedir(dp);
return 0;
}
Classification:
QNX Neutrino
Safety
Cancellation point
No
Interrupt handler
No
Signal handler
No
Thread
Yes
See also:
fcntl(), opendir(), readdir()
312
QNX Neutrino Functions and Macros
June 19, 2012
dirent
© 2012, QNX Software Systems Limited
Data structure for a directory entry
Synopsis:
#include <dirent.h>
struct dirent {
#if _FILE_OFFSET_BITS - 0 == 64
ino_t
d_ino;
/* File serial number. */
off_t
d_offset;
#elif !defined(_FILE_OFFSET_BITS) || _FILE_OFFSET_BITS == 32
#if defined(__LITTLEENDIAN__)
ino_t
d_ino;
/* File serial number. */
ino_t
d_ino_hi;
off_t
d_offset;
off_t
d_offset_hi;
#elif defined(__BIGENDIAN__)
ino_t
d_ino_hi;
ino_t
d_ino;
/* File serial number. */
off_t
d_offset_hi;
off_t
d_offset;
#else
#error endian not configured for system
#endif
#else
#error _FILE_OFFSET_BITS value is unsupported
#endif
_Int16t
d_reclen;
_Int16t
d_namelen;
char
d_name[1];
};
Description:
The dirent structure describes an entry in a directory. The members include:
June 19, 2012
d_ino
A mountpoint-unique file serial number. This serial number is often
used in various disk-checking utilities for such operations as
determining infinite-loop directory links. (Note that the inode value
cannot be zero, which would indicate that the inode represents an
unused entry.)
d_offset
In some filesystems, this member identifies the directory entry itself;
in others, it’s the offset of the next directory entry. For a disk-based
filesystem, this value might be the actual offset into the on-disk
directory structure.
d_reclen
The size of this directory entry and any other associated information
(such as an optional struct stat structure appended to the struct
dirent entry).
d_namelen
The size of the d_name member. Since the size is calculated using
strlen(), the \0 string terminator, which must be present, isn’t counted.
d_name
The actual name of that directory entry.
QNX Neutrino Functions and Macros
313
dirent
© 2012, QNX Software Systems Limited
The struct dirent structure includes space only for the first four bytes of the
pathname. If you create an instance of this structure, you must provide space for the
name, including the terminating null character:
struct dirent *entry;
entry = malloc( offsetof(struct dirent, d_name) + NAME_MAX + 1 );
or:
struct {
struct dirent ent;
char namebuf[NAME_MAX + 1 + offsetof(struct dirent, d_name) sizeof( struct dirent)];
} entry
Classification:
POSIX 1003.1
See also:
readdir(), readdir_r(), scandir()
314
QNX Neutrino Functions and Macros
June 19, 2012
dirname()
© 2012, QNX Software Systems Limited
Find the parent directory part of a file pathname
Synopsis:
#include <libgen.h>
char *dirname( char *path );
Arguments:
path
The string to parse.
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
The dirname() function takes a pointer to a character string that contains a pathname,
and returns a pointer to a string that’s a pathname of the parent directory of that file.
Trailing “/” characters in the path aren’t counted as part of the path.
If the path doesn’t contain a “/” character, or path is a NULL pointer or points to an
empty string, then dirname() function returns a pointer to the string "." (dot).
Together the dirname() and basename() functions yield a complete pathname. The
expression dirname(path) obtains the pathname of the directory where
basename(path) is found.
The dirname() function might modify the string pointed to by path, and can return a
pointer to static storage.
Returns:
A pointer to a string that’s the parent directory of path. If path is a NULL pointer or
points to an empty string, a pointer to a string "." is returned.
Examples:
String input
String output
“/usr/lib”
“/usr”
“/usr/”
“/”
“/ ”
“/”
continued. . .
June 19, 2012
QNX Neutrino Functions and Macros
315
dirname()
© 2012, QNX Software Systems Limited
String input
String output
“.”
“.”
“..”
“.”
The following code fragment reads a pathname, changes the current working directory
to the parent directory, and opens the file:
char path[BUFF_SIZE], *pathcopy;
int fd;
fgets(path, BUFF_SIZE, stdin);
pathcopy = strdup(path);
chdir(dirname(pathcopy));
fd = open(basename(path), O_RDONLY);
Classification:
POSIX 1003.1 XSI
Safety
Cancellation point
No
Interrupt handler
No
Signal handler
Yes
Thread
Yes
See also:
basename()
316
QNX Neutrino Functions and Macros
June 19, 2012
dispatch_block()
© 2012, QNX Software Systems Limited
Block while waiting for an event
Synopsis:
#include <sys/iofunc.h>
#include <sys/dispatch.h>
dispatch_context_t * dispatch_block
( dispatch_context_t * ctp );
Arguments:
ctp
A pointer to a dispatch_context_t structure that defines the dispatch
context.
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
The dispatch_block() function blocks while waiting for an event (e.g. message or
signal) that’s registered using one of the attach functions, message_attach(),
pulse_attach(), resmgr_attach(), or select_attach(). (The sigwait_attach() function
isn’t currently implemented.)
If the type of blocking is:
dispatch_block() does a:
message (resmgr, message, select)
MsgReceive()
signal
SignalWaitinfo()
This function is part of the dispatch layer of a resource manager. For more
information, see “Layers in a resource manager” in the Bones of a Resource Manager
chapter of Writing a Resource Manager.
Returns:
A dispatch context that’s passed in by dispatch_context_alloc(). or NULL if an error
occurs (errno is set).
Errors can occur when the blocking kernel call returns with an error, for example, due
to the delivery of a signal.
In the case of a timeout, a valid ctp is returned, but either the
ctp->message_context.rcvid or ctp->sigwait_context.signo is set to -1.
If a non-NULL context pointer is returned, it could be different from the one passed in,
as it’s possible for the ctp to be reallocated to a larger size. In this case, the old ctp is
June 19, 2012
QNX Neutrino Functions and Macros
317
dispatch_block()
© 2012, QNX Software Systems Limited
no longer valid. However, if NULL is returned (for example, because a signal
interrupted the MsgReceive()), the old context pointer is still valid. Typically, a
resource manager would target signals to a thread dedicated to handling signals.
However, if a signal can be targeted to the thread doing dispatch_block(), you could
use the following code in this situation:
dispatch_context_t
*ctp, *new_ctp;
ctp = dispatch_context_alloc( ... );
while (1) {
new_ctp = dispatch_block( ctp );
if ( new_ctp ) {
ctp = new_ctp
}
else {
/* handle the error condition */
.
.
.
}
}
Errors:
EFAULT
A fault occurred when the kernel tried to access the buffers.
EINTR
The call was interrupted by a signal.
EINVAL
Invalid arguments passed to dispatch_block().
ENOMEM
Insufficient memory to allocate internal data structures.
See also the error constants returned in MsgReceive() and SignalWaitinfo().
Examples:
#include <sys/dispatch.h>
int main( int argc, char **argv ) {
dispatch_context_t
*ctp;
.
.
.
for(;;) {
if( ctp = dispatch_block( ctp ) ) {
dispatch_handler( ctp );
}
}
}
For examples using the dispatch interface, see dispatch_create(), message_attach(),
resmgr_attach(), and thread_pool_create().
318
QNX Neutrino Functions and Macros
June 19, 2012
dispatch_block()
© 2012, QNX Software Systems Limited
Classification:
QNX Neutrino
Safety
Cancellation point
Yes
Interrupt handler
No
Signal handler
Yes
Thread
Yes
See also:
dispatch_context_alloc(), dispatch_create(), dispatch_create_channel(),
dispatch_handler(), dispatch_timeout(), dispatch_unblock()
“Layers in a resource manager” in the Bones of a Resource Manager chapter of
Writing a Resource Manager
June 19, 2012
QNX Neutrino Functions and Macros
319
dispatch_context_alloc()
© 2012, QNX Software Systems Limited
Return a dispatch context
Synopsis:
#include <sys/iofunc.h>
#include <sys/dispatch.h>
dispatch_context_t * dispatch_context_alloc
( dispatch_t * dpp );
Arguments:
dpp
A dispatch handle created by dispatch_create().
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
The dispatch_context_alloc() function returns a dispatch context pointer. The function
is passed in the handle dpp from dispatch_create(). The dispatch context is used by
dispatch to do its work. It’s passed as an argument to dispatch_block() and
dispatch_handler().
The dispatch_context_alloc() function fails if you haven’t attached any events to
dispatch yet (e.g. you didn’t call message_attach(), resmgr_attach(), or
select_attach()). The dispatch library can’t allocate a proper context until it knows
what kind of events you want to block.
This function is part of the dispatch layer of a resource manager. For more
information, see “Layers in a resource manager” in the Bones of a Resource Manager
chapter of Writing a Resource Manager.
Returns:
A pointer to a dispatch context, or NULL if an error occurs (errno is set).
Errors:
EINVAL
No events were attached.
ENOMEM
Insufficient memory to allocate context.
Examples:
#include <sys/dispatch.h>
#include <stdio.h>
#include <stdlib.h>
int main( int argc, char **argv ) {
320
QNX Neutrino Functions and Macros
June 19, 2012
dispatch_context_alloc()
© 2012, QNX Software Systems Limited
dispatch_t
dispatch_context_t
*dpp;
*ctp;
if( ( dpp = dispatch_create() ) == NULL ) {
fprintf( stderr, "%s: Unable to allocate \
dispatch handle.\n",argv[0] );
return EXIT_FAILURE;
}
&vellip;
ctp = dispatch_context_alloc( dpp );
&vellip;
return EXIT_SUCCESS;
}
For examples using the dispatch interface, see dispatch_create(), message_attach(),
resmgr_attach(), and thread_pool_create().
Classification:
QNX Neutrino
Safety
Cancellation point
No
Interrupt handler
No
Signal handler
No
Thread
Yes
See also:
dispatch_block(), dispatch_context_free(), dispatch_create(),
dispatch_create_channel(), dispatch_handler(), dispatch_unblock()
“Layers in a resource manager” in the Bones of a Resource Manager chapter of
Writing a Resource Manager
June 19, 2012
QNX Neutrino Functions and Macros
321
dispatch_context_free()
© 2012, QNX Software Systems Limited
Free a dispatch context
Synopsis:
#include <sys/iofunc.h>
#include <sys/dispatch.h>
void dispatch_context_free(
dispatch_context_t * ctp );
Arguments:
ctp
A pointer to a dispatch_context_t structure that was allocated by
dispatch_context_alloc().
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
The dispatch_context_free() function frees the given dispatch context.
This function is part of the dispatch layer of a resource manager. For more
information, see “Layers in a resource manager” in the Bones of a Resource Manager
chapter of Writing a Resource Manager.
Examples:
#include <sys/dispatch.h>
#include <stdio.h>
#include <stdlib.h>
int main( int argc, char **argv ) {
dispatch_t
*dpp;
dispatch_context_t
*ctp;
if( ( dpp = dispatch_create() ) == NULL ) {
fprintf( stderr, "%s: Unable to allocate
dispatch handle.\n",argv[0] );
return EXIT_FAILURE;
}
.
.
.
ctp = dispatch_context_alloc( dpp );
.
.
.
dispatch_context_free ( ctp );
return EXIT_SUCCESS;
}
See dispatch_create(), message_attach(), resmgr_attach(), and thread_pool_create()
for examples using the dispatch interface.
322
QNX Neutrino Functions and Macros
June 19, 2012
dispatch_context_free()
© 2012, QNX Software Systems Limited
Classification:
QNX Neutrino
Safety
Cancellation point
No
Interrupt handler
No
Signal handler
No
Thread
Yes
See also:
dispatch_context_alloc()
“Layers in a resource manager” in the Bones of a Resource Manager chapter of
Writing a Resource Manager
June 19, 2012
QNX Neutrino Functions and Macros
323
dispatch_create()
© 2012, QNX Software Systems Limited
Allocate a dispatch handle
Synopsis:
#include <sys/iofunc.h>
#include <sys/dispatch.h>
dispatch_t *dispatch_create( void );
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
The dispatch_create() function allocates and initializes a dispatch handle. The attach
functions are:
• message_attach()
• pulse_attach()
• resmgr_attach()
• select_attach()
If you wish, you can do a resmgr_attach() with a NULL path. This has the effect of
initializing dispatch to receive messages and creates the channel among other things.
A channel is created only when you first attach something that requires a channel
(indicating you will block receiving messages).
If you want to create the channel yourself (e.g. in order to use name_attach()), call
dispatch_create_channel() instead of dispatch_create().
This function is part of the dispatch layer of a resource manager. For more
information, see “Layers in a resource manager” in the Bones of a Resource Manager
chapter of Writing a Resource Manager.
Returns:
A handle to a dispatch structure, or NULL if an error occurs.
The dispatch structure, dispatch_t, is an opaque data type; you can’t access its
contents directly.
324
QNX Neutrino Functions and Macros
June 19, 2012
dispatch_create()
© 2012, QNX Software Systems Limited
Errors:
ENOMEM
Insufficient memory to allocate context.
Examples:
#include
#include
#include
#include
#include
#include
<stdio.h>
<stdlib.h>
<stddef.h>
<fcntl.h>
<sys/iofunc.h>
<sys/dispatch.h>
int my_func( select_context_t *ctp, int fd,
unsigned flags, void *handle ) {
int
i, c;
/* Do some useful stuff with data */
i = read( fd, &c, 1 );
fprintf( stderr, "activity on fd %d: read char %c,
return code %d\n", fd, c, i );
}
int main( int argc, char **argv ) {
dispatch_t
*dpp;
dispatch_context_t
*ctp;
select_attr_t
attr;
int
fd, fd2;
if( ( dpp = dispatch_create() ) == NULL ) {
fprintf( stderr, "%s: Unable to allocate \
dispatch handle.\n",argv[0] );
return EXIT_FAILURE;
}
if( argc ≤ 2 || (fd = open( argv[1],
O_RDWR | O_NONBLOCK )) == -1 ) {
return EXIT_FAILURE;
}
if( argc ≤ 2 || (fd2 = open( argv[2],
O_RDWR | O_NONBLOCK )) == -1 ) {
return EXIT_FAILURE;
}
select_attach( dpp, &attr, fd,
SELECT_FLAG_READ | SELECT_FLAG_REARM, my_func, NULL );
select_attach( dpp, &attr, fd2,
SELECT_FLAG_READ | SELECT_FLAG_REARM, my_func, NULL );
ctp = dispatch_context_alloc( dpp );
for(;;) {
if( ctp = dispatch_block( ctp ) ) {
dispatch_handler( ctp );
}
}
return EXIT_SUCCESS;
}
For more examples using the dispatch interface, see message_attach(),
resmgr_attach(), and thread_pool_create().
June 19, 2012
QNX Neutrino Functions and Macros
325
dispatch_create()
© 2012, QNX Software Systems Limited
Classification:
QNX Neutrino
Safety
Cancellation point
No
Interrupt handler
No
Signal handler
No
Thread
Yes
See also:
dispatch_block(), dispatch_context_alloc(), dispatch_create_channel(),
dispatch_destroy(), dispatch_handler(), dispatch_timeout(), dispatch_unblock()
message_attach(), pulse_attach(), resmgr_attach(), select_attach()
“Layers in a resource manager” in the Bones of a Resource Manager chapter of
Writing a Resource Manager
Resource Managers chapter of Getting Started with QNX Neutrino
326
QNX Neutrino Functions and Macros
June 19, 2012
dispatch_create_channel()
© 2012, QNX Software Systems Limited
Allocate a dispatch handle, specifying a channel ID
Synopsis:
#include <sys/iofunc.h>
#include <sys/dispatch.h>
dispatch_t *dispatch_create_channel( int chid,
unsigned reserved );
Arguments:
chid
The ID of the channel to use for the dispatch layer.
reserved
Reserved; specify 0 for this argument.
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
The dispatch_create_channel() function allocates and initializes a dispatch handle.
The attach functions are:
• message_attach()
• pulse_attach()
• resmgr_attach()
• select_attach()
If you wish, you can do a resmgr_attach() with a NULL path. This has the effect of
initializing dispatch to receive messages, among other things.
This function is similar to dispatch_create(), but lets you specify a channel for the
dispatch to use. This lets you use name_attach() in a Photon application without
causing any problems with Photon itself. It also lets you specify channel flags for
name_attach().
This function is part of the dispatch layer of a resource manager. For more
information, see “Layers in a resource manager” in the Bones of a Resource Manager
chapter of Writing a Resource Manager.
Returns:
A handle to a dispatch structure, or NULL if an error occurs.
June 19, 2012
QNX Neutrino Functions and Macros
327
dispatch_create_channel()
© 2012, QNX Software Systems Limited
The dispatch structure, dispatch_t, is an opaque data type; you can’t access its
contents directly.
Errors:
ENOMEM
Insufficient memory to allocate context.
Classification:
QNX Neutrino
Safety
Cancellation point
No
Interrupt handler
No
Signal handler
No
Thread
Yes
See also:
ChannelCreate(), dispatch_block(), dispatch_context_alloc(), dispatch_create(),
dispatch_destroy(), dispatch_handler(), dispatch_timeout(), dispatch_unblock()
message_attach(), name_attach(), pulse_attach(), resmgr_attach(), select_attach()
“Layers in a resource manager” in the Bones of a Resource Manager chapter of
Writing a Resource Manager
Resource Managers chapter of Getting Started with QNX Neutrino
328
QNX Neutrino Functions and Macros
June 19, 2012
dispatch_destroy()
© 2012, QNX Software Systems Limited
Destroy a dispatch handle
Synopsis:
#include <sys/iofunc.h>
#include <sys/dispatch.h>
int dispatch_destroy( dispatch_t *dpp );
Arguments:
dpp
A dispatch handle created by dispatch_create().
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
The function dispatch_destroy() destroys the given dispatch handle.
This function is part of the dispatch layer of a resource manager. For more
information, see “Layers in a resource manager” in the Bones of a Resource Manager
chapter of Writing a Resource Manager.
Returns:
0
Success.
-1
An error occurred (errno is set).
Errors:
EINVAL
The dispatch handle, dpp, is invalid.
Examples:
#include <sys/dispatch.h>
#include <stdio.h>
#include <stdlib.h>
int main( int argc, char **argv ) {
dispatch_t
*dpp;
int
destroyed;
if( ( dpp = dispatch_create() ) == NULL ) {
fprintf( stderr, "%s: Unable to allocate \
dispatch handle.\n",argv[0] );
return EXIT_FAILURE;
}
.
.
.
if ( (destroyed = dispatch_destroy ( dpp )) == -1 ) {
June 19, 2012
QNX Neutrino Functions and Macros
329
dispatch_destroy()
© 2012, QNX Software Systems Limited
fprintf ( stderr, "Dispatch wasn’t destroyed, \
bad dispatch handle %d.\n", dpp);
return EXIT_FAILURE;
}
/* else dispatch was destroyed */
.
.
.
return EXIT_SUCCESS;
}
For examples using the dispatch interface, see dispatch_create(), message_attach(),
resmgr_attach(), and thread_pool_create().
Classification:
QNX Neutrino
Safety
Cancellation point
No
Interrupt handler
No
Signal handler
No
Thread
Yes
See also:
dispatch_create(), dispatch_create_channel(),
For more information, see “Layers in a resource manager” in the Bones of a Resource
Manager chapter of Writing a Resource Manager
330
QNX Neutrino Functions and Macros
June 19, 2012
dispatch_handler()
© 2012, QNX Software Systems Limited
Handle events received by dispatch_block()
Synopsis:
#include <sys/iofunc.h>
#include <sys/dispatch.h>
int dispatch_handler( dispatch_context_t * ctp );
Arguments:
ctp
A pointer to a dispatch_context_t structure that was allocated by
dispatch_context_alloc().
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
The dispatch_handler() function handles events received by dispatch_block(). This
function is part of the dispatch layer of a resource manager. For more information, see
“Layers in a resource manager” in the Bones of a Resource Manager chapter of
Writing a Resource Manager.
Depending on the blocking type, dispatch_handler() does one of the following:
• Calls the message_* subsystem. A search is made (based upon the message type or
pulse code) for a matching function (that was attached with message_attach() or
pulse_attach()). If a match is found, the attached function is called.
• If the message type is in the range handled by the resource manager (e.g. I/O
messages) and pathnames were attached using resmgr_attach(), then the resmgr_*
subsystem is called and handles the resource manager messages.
• If a pulse is received, it may be dispatched to the resmgr_* subsystem if it’s one of
the codes (unblock and disconnect pulses) handled by the resource manager. If a
select_attach() was done and the pulse matches the one used by select_attach(),
then the select_* subsystem is called and dispatches that event.
• If a message is received, and no matching handler is found for that message type,
MsgError() returns ENOSYS to the sender.
• If a SignalWaitinfo() blocking type is used, then a search is made based upon the
signal number for a matching function attached by the program (using the
sigwait_attach() function, not currently implemented). If a match is found, that
function is called.
June 19, 2012
QNX Neutrino Functions and Macros
331
dispatch_handler()
© 2012, QNX Software Systems Limited
Returns:
0
Success.
-1
One of the following occurred:
• The message was a _PULSE_CODE_THREADDEATH pulse message (see
ChannelCreate()) for which there’s no default handler function.
• The message length was less than 2 bytes. A 2-byte message type is
required at the beginning of the message so that a handler function can be
found or identified.
• The message wasn’t in native endian format and there were no handler
functions that specified MSG_FLAG_CROSS_ENDIAN on this range, even
though a handler was registered for it using message_attach(). The
MSG_FLAG_CROSS_ENDIAN flag wasn’t given to message_attach().
• A handler was found for the message, but the handler determined that there
was a problem.
In any case, if the message wasn’t a pulse, then the client will be replied to
with an appropriate errno.
Examples:
#include <stdlib.h>
#include <sys/dispatch.h>
int main( int argc, char **argv ) {
dispatch_context_t
*ctp;
.
.
.
for(;;) {
if( ctp = dispatch_block( ctp ) ) {
dispatch_handler( ctp );
}
}
return EXIT_SUCCESS;
}
For examples using the dispatch interface, see dispatch_create(), message_attach(),
resmgr_attach(), and thread_pool_create().
Classification:
QNX Neutrino
Safety
Cancellation point
Read the Caveats
Interrupt handler
No
continued. . .
332
QNX Neutrino Functions and Macros
June 19, 2012
dispatch_handler()
© 2012, QNX Software Systems Limited
Safety
Signal handler
No
Thread
Yes
Caveats:
This function might or might not be a cancellation point, depending on the
implementation of the handler.
See also:
dispatch_block(), dispatch_create(), dispatch_create_channel(), dispatch_timeout()
“Layers in a resource manager” in the Bones of a Resource Manager chapter of
Writing a Resource Manager
June 19, 2012
QNX Neutrino Functions and Macros
333
dispatch_timeout()
© 2012, QNX Software Systems Limited
Set a timeout
Synopsis:
#include <sys/iofunc.h>
#include <sys/dispatch.h>
int dispatch_timeout( dispatch_t *dpp,
struct timespec *reltime );
Arguments:
dpp
A dispatch handle created by dispatch_create().
reltime
A pointer to a timespec structure that specifies the relative time of the
timeout.
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
The function dispatch_timeout() sets a timeout that’s used when blocking with
dispatch_block().
This function is part of the dispatch layer of a resource manager. For more
information, see “Layers in a resource manager” in the Bones of a Resource Manager
chapter of Writing a Resource Manager.
Returns:
0
Success.
-1
An error occurred.
Examples:
#include
#include
#include
#include
<sys/dispatch.h>
<time.h>
<stdio.h>
<stdlib.h>
int main( int argc, char **argv ) {
dispatch_t
*dpp;
struct timespec
time_out;
int
timedout;
time_out.tv_sec = 1;
time_out.tv_nsec = 2;
if( ( dpp = dispatch_create() ) == NULL ) {
fprintf( stderr, "%s: Unable to allocate \
dispatch handle.\n",argv[0] );
return EXIT_FAILURE;
}
334
QNX Neutrino Functions and Macros
June 19, 2012
dispatch_timeout()
© 2012, QNX Software Systems Limited
.
.
.
if ( (timedout = dispatch_timeout ( dpp, &time_out ))
== -1 ) {
fprintf ( stderr, "Couldn’t set timeout );
return EXIT_FAILURE;
}
/* else successful timeout set */
.
.
.
return EXIT_SUCCESS;
}
For examples using the dispatch interface, see dispatch_create(), message_attach(),
resmgr_attach(), and thread_pool_create().
Classification:
QNX Neutrino
Safety
Cancellation point
No
Interrupt handler
No
Signal handler
No
Thread
Yes
See also:
dispatch_block(), dispatch_create(), dispatch_create_channel(), dispatch_handler(),
dispatch_unblock() timespec
“Layers in a resource manager” in the Bones of a Resource Manager chapter of
Writing a Resource Manager
June 19, 2012
QNX Neutrino Functions and Macros
335
dispatch_unblock()
© 2012, QNX Software Systems Limited
Unblock all of the threads that are blocked on a dispatch handle
Synopsis:
#include <sys/iofunc.h>
#include <sys/dispatch.h>
void dispatch_unblock( dispatch_context_t * ctp );
Arguments:
ctp
A pointer to a dispatch_context_t structure that defines the dispatch
context.
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
This routine tries to unblock all of the threads that are blocked on the given dispatch
handle. You should use this function in the thread pool structure as the unblock
function pointer so that thread_pool_control() will behave properly.
Currently, this function unblocks only channel resources.
This function is part of the dispatch layer of a resource manager. For more
information, see “Layers in a resource manager” in the Bones of a Resource Manager
chapter of Writing a Resource Manager.
Examples:
For examples using the dispatch interface, see dispatch_create(), message_attach(),
resmgr_attach(), and thread_pool_create().
Classification:
QNX Neutrino
Safety
336
Cancellation point
Yes
Interrupt handler
No
Signal handler
Yes
Thread
Yes
QNX Neutrino Functions and Macros
June 19, 2012
© 2012, QNX Software Systems Limited
dispatch_unblock()
See also:
dispatch_block(), dispatch_context_alloc(), dispatch_create(),
dispatch_create_channel(), dispatch_handler(), dispatch_timeout()
“Layers in a resource manager” in the Bones of a Resource Manager chapter of
Writing a Resource Manager
June 19, 2012
QNX Neutrino Functions and Macros
337
div()
© 2012, QNX Software Systems Limited
Calculate a quotient and remainder
Synopsis:
#include <stdlib.h>
div_t div( int numer,
int denom );
Arguments:
numer
The numerator in the division.
denom
The denominator.
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
The div() function calculates the quotient and remainder of the division of numer by
denom.
Returns:
A div_t structure containing the quotient and remainder:
typedef struct {
int quot;
int rem;
} div_t;
/* quotient */
/* remainder */
Examples:
#include <stdio.h>
#include <stdlib.h>
void print_time( int seconds )
{
div_t min_sec;
min_sec = div( seconds, 60 );
printf( "It took %d minutes and %d seconds\n",
min_sec.quot, min_sec.rem );
}
int main( void )
{
print_time( 130 );
return EXIT_SUCCESS;
}
produces the output:
It took 2 minutes and 10 seconds
338
QNX Neutrino Functions and Macros
June 19, 2012
div()
© 2012, QNX Software Systems Limited
Classification:
ANSI, POSIX 1003.1
Safety
Cancellation point
No
Interrupt handler
Yes
Signal handler
Yes
Thread
Yes
See also:
ldiv()
June 19, 2012
QNX Neutrino Functions and Macros
339
dladdr()
© 2012, QNX Software Systems Limited
Translate an address to symbolic information
Synopsis:
#include <dlfcn.h>
int dladdr( void *address,
Dl_info *dlip );
Arguments:
address
The address for which you want symbolic information.
dlip
A pointer to a Dl_info structure where the function can store the
symbolic information. Your application must allocate the space for this
structure; dladdr() fills in the members, based on the specified address.
The Dl_info structure includes the following members:
• const char * dli_fname — a pointer to the full path of the object
containing address.
• void *dli_fbase — the base address of the object containing address.
• const char *dli_sname — a pointer to the symbol name nearest the
specified address. This symbol is either at address, or is the nearest
symbol with a lower address.
• void *dli_saddr — the actual address of the dli_sname symbol.
If dladdr() can’t find a symbol that describes the specified address, the
function sets dli_sname and dli_saddr to NULL.
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
The dladdr() function determines whether the specified address is located within one
of the objects that make up the calling application’s address space.
The dladdr() function is available only to dynamically linked processes.
Returns:
0 if the specified address can’t be matched, or nonzero if it could be matched.
340
QNX Neutrino Functions and Macros
June 19, 2012
dladdr()
© 2012, QNX Software Systems Limited
Classification:
Unix
Safety
Cancellation point
No
Interrupt handler
No
Signal handler
No
Thread
Yes
Caveats:
The Dl_info pointers may become invalid if objects are removed via dlclose().
There’s no way to determine which symbol you’ll get if multiple symbols are mapped
to the same address.
See also:
dlclose(), dlerror(), dlopen(), dlsym()
June 19, 2012
QNX Neutrino Functions and Macros
341
dlclose()
© 2012, QNX Software Systems Limited
Close a shared object
Synopsis:
#include <dlfcn.h>
int dlclose( void *handle );
Arguments:
handle
A handle for a shared object, returned by dlopen().
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
The dlclose() function disassociates a shared object opened by dlopen() from the
calling process. An object’s symbols are no longer available after it’s been closed with
dlclose(). All objects loaded as a result of the closed objects dependencies are also
closed.
The handle argument is the value returned by a previous call to dlopen().
The dlclose() function is available only to dynamically linked processes.
Returns:
0 for success, or a nonzero value if an error occurs.
Errors:
If an error occurs, more detailed diagnostic information is available from dlerror().
Classification:
POSIX 1003.1 XSI
Safety
342
Cancellation point
Yes
Interrupt handler
No
Signal handler
No
Thread
Yes
QNX Neutrino Functions and Macros
June 19, 2012
dlclose()
© 2012, QNX Software Systems Limited
Caveats:
An object won’t be removed from the address space until all references to that object
(via dlopen() or dependencies from other objects) have been closed.
Referencing a symbol in a closed object can cause undefined behavior.
See also:
dladdr(), dlerror(), dlopen(), dlsym()
June 19, 2012
QNX Neutrino Functions and Macros
343
dlerror()
© 2012, QNX Software Systems Limited
Get dynamic loading diagnostic information
Synopsis:
#include <dlfcn.h>
char *dlerror( void );
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
The dlerror() function returns a NULL-terminated string (with no trailing newline)
describing the last error that occurred during a call to one of the dl*() functions. If no
errors have occurred, dlerror() returns NULL.
The dlopen() function is available only to dynamically linked processes.
Returns:
A pointer to an error description, or NULL.
Classification:
POSIX 1003.1 XSI
Safety
Cancellation point
No
Interrupt handler
No
Signal handler
No
Thread
Yes
See also:
dladdr(), dlclose(), dlopen(), dlsym()
344
QNX Neutrino Functions and Macros
June 19, 2012
dlopen()
© 2012, QNX Software Systems Limited
Gain access to an executable object file
Synopsis:
#include <dlfcn.h>
void * dlopen( const char * pathname,
int mode );
Arguments:
pathname
NULL, or the path to the executable object file that you want to access.
mode
Flags that control how dlopen() operates. POSIX defines these bits:
• RTLD_LAZY
• RTLD_NOW
• RTLD_GLOBAL
• RTLD_LOCAL
The following bits are Unix extensions:
• RTLD_NOLOAD
• RTLD_GROUP
• RTLD_WORLD
• RTLD_NODELETE
The following bits are QNX Neutrino extensions:
• RTLD_NOSHARE
• RTLD_LAZYLOAD
For more information, see “The mode,” below.
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
The dlopen() function gives you direct access to the dynamic linking facilities by
making the executable object file specified in pathname available to the calling
process. It returns a handle that you can use in subsequent calls to dlsym() and
dlclose().
June 19, 2012
QNX Neutrino Functions and Macros
345
dlopen()
© 2012, QNX Software Systems Limited
The dlopen() function is available only to a dynamically-linked process. A
statically-linked process (one where libc is linked statically) can’t call dlopen()
because a statically-linked executable:
• doesn’t export any of its symbols
• can’t export the required structure for libraries to link against
• can’t fill structures at startup needed to load subsequent shared objects
Any dependencies recorded within pathname are loaded as part of the dlopen() call.
These dependencies are searched in load-order to locate any additional dependencies.
This process continues until all of the dependencies for pathname have been satisfied.
This dependency tree is called a group.
If pathname is NULL, dlopen() provides a handle to the running process’s global
symbol object. This provides access to the symbols from the original program image
file, the dependencies it loaded at startup, plus any objects opened with dlopen() calls
using the RTLD_GLOBAL flag. This set of symbols can change dynamically if the
application subsequently calls dlopen() using RTLD_GLOBAL.
You can use dlopen() any number of times to open objects whose names resolve to the
same absolute or relative path name; the object is loaded into the process’s address
space only once.
In order to find the shared objects, dlopen() searches the following, in this order:
• the runtime library search path that was set using the -rpath option to ld (see the
Utilities Reference) when the binary was linked
• directories specified by the LD_LIBRARY_PATH environment variable
• directories specified by the _CS_LIBPATH configuration string
Note that LD_LIBRARY_PATH is ignored if the binary is setuid and the effective
user ID isn’t the same as the actual ID of the user running the binary. This is done for
security purposes.
346
QNX Neutrino Functions and Macros
June 19, 2012
dlopen()
© 2012, QNX Software Systems Limited
The above directories are set as follows:
• The LD_LIBRARY_PATH is generally set up by a startup script, either in the
boot image or by a secondary script. For example, on self-hosted Neutrino systems,
the ph script (which starts Photon) adds some libraries to this list. It isn’t part of
any default environment.
• _CS_LIBPATH is populated by the kernel, and the default value is based on the
LD_LIBRARY_PATH value of the procnto command line in the boot image.
Note that you can use getconf to inspect this value and setconf to set it. For
example:
setconf _CS_LIBPATH ’getconf _CS_LIBPATH’:/new/path
When loading shared objects, the application should open a specific version instead of
relying on the version pointed to by a symbolic link.
The mode
The mode argument indicates how dlopen() operates on pathname when handling
relocations, and controls the visibility of symbols found in pathname and its
dependencies.
The mode argument is a bitwise-OR of the constants described below. Note that the
relocation and visibility constants are mutually exclusive.
Relocation
When you load an object by calling dlopen(), the object may contain references to
symbols whose addresses aren’t known until the object has been loaded; these
references must be relocated before accessing the symbols. The mode controls when
relocations take place, and can be one of:
RTLD_LAZY
(QNX Neutrino 6.5.0 and later) References to data symbols are
relocated when the object is loaded. References to functions aren’t
relocated until that function is invoked. This improves performance
by preventing unnecessary relocations.
RTLD_NOW
All references are relocated when the object is loaded. This may
waste cycles if relocations are performed for functions that never
get called, but this behavior could be useful for applications that
need to know that all symbols referenced during execution are
available as soon as the object is loaded.
Visibility
The following mode bits determine the scope of visibility for symbols loaded with
dlopen():
June 19, 2012
QNX Neutrino Functions and Macros
347
dlopen()
© 2012, QNX Software Systems Limited
RTLD_GLOBAL
Make the object’s global symbols available to any other object
that’s opened later with RTLD_WORLD. Symbol lookup using
dlopen( 0, mode ) and an associated dlsym() are also able to
find the object’s symbols.
RTLD_LOCAL
Make the object’s global symbols available only to objects in the
same group.
RTLD_LAZYLOAD
Open the shared object and form its resolution scope by
appending its immediate dependencies. This is different from the
normal resolution scope, which is formed by appending the
whole dependency tree in breadth-first order. For more
information, see “Lazy loading” in the Compiling and
Debugging chapter of the QNX Neutrino Programmer’s Guide.
The program’s image and any objects loaded at program startup have a mode of
RTLD_GLOBAL; the default mode for objects acquired with dlopen() is
RTLD_LOCAL. A local object may be part of the dependencies for more than one
group; any object with a RTLD_LOCAL mode referenced as a dependency of an object
with a RTLD_GLOBAL mode is promoted to RTLD_GLOBAL.
Objects loaded with dlopen() that require relocations against global symbols can
reference the symbols in any RTLD_GLOBAL object.
Symbol scope
You can OR the mode with the following values to affect the symbol scope:
RTLD_GROUP
Only symbols from the associated group are available. All
dependencies between group members must be satisfied by the
objects in the group.
RTLD_WORLD
Only symbols from RTLD_GLOBAL objects are available.
If you don’t specify either of these values, dlopen() uses
RTLD_WORLD | RTLD_GROUP.
If you specify RTLD_WORLD without RTLD_GROUP, dlopen() doesn’t load any of the
DLL’s dependencies.
Other flags
The following flags provide additional capabilities:
RTLD_NODELETE
348
QNX Neutrino Functions and Macros
Don’t delete the specified object from the address space as part
of a call to dlclose().
June 19, 2012
dlopen()
© 2012, QNX Software Systems Limited
RTLD_NOLOAD
Don’t load the specified object, but return a valid handle if if the
object already exists as part of the process address space. You
can specify addition modes, which are ORed with the present
mode of the object and its dependencies. This flag gives you a
means of querying the presence or promoting the modes of an
existing dependency.
RTLD_NOSHARE
Don’t share the specified object. This flag forces the loading of
multiple instances of libraries.
Symbol resolution
When resolving the symbols in the shared object, the runtime linker searches for them
in the dynamic symbol table using the following order:
By default:
1
main executable
2
the shared object being loaded
3
objects specified by the LD_PRELOAD environment variable
4
all other loaded shared objects that were loaded with the
RTLD_GLOBAL flag
When -Bsymbolic is specified:
1
the shared object being loaded
2
main executable
3
objects specified by the LD_PRELOAD environment variable
4
all other loaded shared objects that were loaded with the
RTLD_GLOBAL flag
For executables, the dynamic symbol table typically contains only those symbols that
are known to be needed by any shared libraries. This is determined by the linker when
the executable is linked against a shared library.
Since you don’t link your executable against a shared object that you load with
dlopen(), the linker can’t determine which executable symbols need to be made
available to the shared object.
If your shared object needs to resolve symbols in the executable, then you may force
the linker to make all of the symbols in the executable available for dynamic linking
by specifying the -E linker option. For example:
qcc -Vgcc_ntox86 -Wl,-E -o main main.o
Shared objects always place all their symbols in dynamic symbol tables, so this option
isn’t needed when linking a shared object.
June 19, 2012
QNX Neutrino Functions and Macros
349
dlopen()
© 2012, QNX Software Systems Limited
Returns:
A handle to the object, or NULL if an error occurs.
Don’t interpret the value of this handle in any way. For example, if you open the same
object repeatedly, don’t assume that dlopen() returns the same handle.
Errors:
If an error occurs, more detailed diagnostic information is available from dlerror().
Environment variables:
DL_DEBUG
If this environment variable is set, the shared library loader
displays debugging information about the libraries as they’re
opened. The value can be a comma-separated list of the
following:
• all — display all debug messages.
• help — display a help message, and then exit.
• reloc — display relocation processing messages.
• libs — display information about shared objects being
opened.
• statistics — display runtime linker statistics.
• lazyload — print lazy-load debug messages.
• debug — print various runtime linker debug messages.
A value of 1 (one) is the same as all.
LD_BIND_NOW
Affects lazy-load dependencies due to full symbol resolution.
Typically, it forces the loading of all lazy-load dependencies
(until all symbols have been resolved).
LD_DEBUG
A synonym for DL_DEBUG. If you set both DL_DEBUG
and LD_DEBUG, then DL_DEBUG takes precedence.
LD_DEBUG_OUTPUT
The name of a file in which the dynamic linker writes its
output. By default, output is written to stderr.
For security reasons, the use of LD_DEBUG_OUTPUT with setuid binaries is
disabled.
LD_LIBRARY_PATH
A colon-separated list of directories to search for shared
libraries.
350
QNX Neutrino Functions and Macros
June 19, 2012
dlopen()
© 2012, QNX Software Systems Limited
LD_PRELOAD
A list of full paths to the shared libraries on an ELF system
that you want to load before loading other libraries. Use a
colon (:) to separate the libraries in this list. You can use this
environment variable to add or change functionality when you
run a program. For setuid or setgid ELF binaries, only
libraries in the standard search directories that are also setuid
will be loaded.
Classification:
POSIX 1003.1 XSI
Safety
Cancellation point
Yes
Interrupt handler
No
Signal handler
No
Thread
Yes
Caveats:
Some symbols defined in executables or shared objects might not be available to the
runtime linker. The symbol table created by ld for use by the runtime linker might
contain a subset of the symbols defined in the object.
See also:
dladdr(), dlclose(), dlerror(), dlsym()
ld, qcc in the Utilities Reference
“Lazy loading” in the Compiling and Debugging chapter of the QNX Neutrino
Programmer’s Guide
June 19, 2012
QNX Neutrino Functions and Macros
351
dlsym()
© 2012, QNX Software Systems Limited
Get the address of a symbol in a shared object
Synopsis:
#include <dlfcn.h>
void* dlsym( void* handle,
const char* name );
Arguments:
handle
Either a handle for a shared object, returned by dlopen(), or either of the
special flags, RTLD_NEXT or RTLD_DEFAULT.
name
The name of the symbol that you want to find in the shared object.
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
The dlsym() function lets a process obtain the address of the symbol specified by name
defined in a shared object.
The dlsym() function is available only to dynamically linked processes.
If handle is a handle returned by dlopen(), you must not have closed that shared object
by calling dlclose(). The dlsym() functions also searches for the named symbol in the
objects loaded as part of the dependencies for that object.
If handle is RTLD_NEXT, dlsym() searches the objects loaded after the object calling
dlsym().
If handle is RTLD_DEFAULT, dlsym() searches all objects in the current process, in
load-order.
In the case of both RTLD_NEXT and RTLD_DEFAULT, if the objects being searched
were loaded with dlopen(), dlsym() searches the object only if the caller is part of the
same dependency hierarchy, or if the object was loaded with global search access
(using the RTLD_GLOBAL mode).
Returns:
A pointer to the named symbol for success, or NULL if an error occurs.
352
QNX Neutrino Functions and Macros
June 19, 2012
dlsym()
© 2012, QNX Software Systems Limited
Errors:
Examples:
If an error occurs, more detailed diagnostic information is available from dlerror().
Use dlsym() to find a function pointer and a pointer to a global variable in a shared
library:
typedef int (*foofunc)( int );
void* handle;
int* some_global_int;
foofunc brain;
/* Open a shared library. */
handle = dlopen( "/usr/nto/x86/lib/libfoo.so.1", RTLD_NOW );
/* Find the address of a function and a global integer. */
brain = (foofunc)dlsym( handle, "takeover_world" );
some_global_int = (int* )dlsym( handle, "my_global_int" );
/* Invoke the function and print the int. */
x = (*brain)( 5 );
printf( "that global is %d\n", *some_global_int );
Check to see if a function is defined, and call it if it is:
typedef int (*funcptr)( void );
funcptr funk = NULL;
funk = (funcptr)dlsym( RTLD_DEFAULT, "get_funky" );
if( funk != NULL ) {
(*funk)();
}
Classification:
POSIX 1003.1 XSI
Safety
Cancellation point
No
Interrupt handler
No
Signal handler
No
Thread
Yes
Caveats:
Function pointers are a pain; use typedefs to help preserve your sanity.
June 19, 2012
QNX Neutrino Functions and Macros
353
dlsym()
© 2012, QNX Software Systems Limited
See also:
dladdr(), dlclose(), dlerror(), dlopen()
354
QNX Neutrino Functions and Macros
June 19, 2012
dn_comp()
© 2012, QNX Software Systems Limited
Compress an Internet domain name
Synopsis:
#include
#include
#include
#include
<sys/types.h>
<netinet/in.h>
<arpa/nameser.h>
<resolv.h>
int dn_comp( const char * exp_dn,
u_char * comp_dn,
int length,
u_char ** dnptrs,
u_char ** lastdnptr );
Arguments:
exp_dn
The Internet domain name you want to compress.
comp_dn
A buffer where the function can store the compressed name.
length
The size of the array that comp_dn points to.
dnptrs
NULL, or an array of pointers to previously compressed names in the
current message; see below.
lastdnptr
NULL, or the limit of the array specified by dnptrs.
Library:
libsocket
Use the -l socket option to qcc to link against this library.
Description:
The dn_comp() routine is a low-level routine used by res_query() to compress an
Internet domain name. This routine compresses the domain name exp_dn and stores it
in comp_dn.
The compression uses an array of pointers, dnptrs, to previously compressed names in
the current message. The first pointer points to the beginning of the message and the
list ends with NULL. The limit to the array is specified by lastdnptr. As a side effect,
dn_comp() updates the list of pointers for labels inserted into the message as the name
is compressed. If dnptrs is NULL, names aren’t compressed. If lastdnptr is NULL, the
list of labels isn’t updated.
Returns:
The size of the compressed domain name, in bytes, or -1 if an error occurs.
June 19, 2012
QNX Neutrino Functions and Macros
355
dn_comp()
© 2012, QNX Software Systems Limited
Classification:
Unix
Safety
Cancellation point
No
Interrupt handler
No
Signal handler
Yes
Thread
Yes
See also:
dn_expand(), gethostbyname(), res_init(), res_mkquery(), res_query(), res_search(),
res_send()
/etc/resolv.conf, hostname in the Utilities Reference
Based on RFC 974, RFC 1032, RFC 1033, RFC 1034, RFC 1035
356
QNX Neutrino Functions and Macros
June 19, 2012
dn_expand()
© 2012, QNX Software Systems Limited
Expand a compressed Internet domain name
Synopsis:
#include
#include
#include
#include
<sys/types.h>
<netinet/in.h>
<arpa/nameser.h>
<resolv.h>
int dn_expand( const u_char * msg,
const u_char * eomorig,
const u_char * comp_dn,
char * exp_dn,
int length );
Arguments:
msg
A pointer to the beginning of the message that contains the compressed
name.
eomorig
A pointer to the first location after the message.
comp_dn
The compressed name that you want to expand.
exp_dn
A buffer where the function can store the expanded name.
length
The length of the array specified by exp_dn.
Library:
libsocket
Use the -l socket option to qcc to link against this library.
Description:
The dn_expand() function is a low-level routine used by res_query() to expand the
compressed domain name, comp_dn, to a full domain name.
The compressed name is contained in a query or reply message.
Returns:
The size of the compressed domain name (not the expanded name), in bytes, or -1 if an
error occurs.
Classification:
Unix
Safety
Cancellation point
No
continued. . .
June 19, 2012
QNX Neutrino Functions and Macros
357
dn_expand()
© 2012, QNX Software Systems Limited
Safety
Interrupt handler
No
Signal handler
Yes
Thread
Yes
See also:
dn_comp(), gethostbyname(), res_init(), res_mkquery(), res_query(), res_search(),
res_send()
/etc/resolv.conf, hostname in the Utilities Reference
Based on RFC 974, RFC 1032, RFC 1033, RFC 1034, RFC 1035
358
QNX Neutrino Functions and Macros
June 19, 2012
drand48()
© 2012, QNX Software Systems Limited
Generate a pseudo-random double
Synopsis:
#include <stdlib.h>
double drand48( void );
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
The drand48() function uses a linear congruential algorithm and 48-bit integer
arithmetic to generate a nonnegative double uniformly distributed over the interval
[0.0, 1.0].
Call one of lcong48(), seed48(), or srand48() to initialize the random-number
generator before calling drand48(), lrand48(), or mrand48().
The erand48() function is a thread-safe version of drand48().
Returns:
A pseudo-random double.
Classification:
POSIX 1003.1 XSI
Safety
Cancellation point
No
Interrupt handler
No
Signal handler
No
Thread
No
See also:
erand48(), jrand48(), lcong48(), lrand48(), mrand48(), nrand48(), seed48(), srand48()
June 19, 2012
QNX Neutrino Functions and Macros
359
ds_clear()
© 2012, QNX Software Systems Limited
Delete a data server variable
Synopsis:
#include <ds.h>
int ds_clear( ds_t dsdes,
const char* variable_name );
Arguments:
dsdes
A data server descriptor returned by ds_register().
variable_name
The name of the variable that you want to delete.
Library:
libds
Use the -l ds option to qcc to link against this library.
Description:
The ds_clear() function deletes variable_name from the data server identified by
dsdes.
Returns:
0
Success.
-1
An error occurred (errno is set).
Errors:
EBADF
Invalid file descriptor dsdes.
ESRCH
The variable doesn’t exist in the data server.
Examples:
See slinger in the Utilities Reference.
Classification:
QNX Neutrino
Safety
360
Cancellation point
Yes
Interrupt handler
No
Signal handler
Yes
Thread
Yes
QNX Neutrino Functions and Macros
June 19, 2012
© 2012, QNX Software Systems Limited
ds_clear()
See also:
ds_deregister(), ds_flags()
June 19, 2012
QNX Neutrino Functions and Macros
361
ds_create()
© 2012, QNX Software Systems Limited
Create a data server variable
Synopsis:
#include <ds.h>
int ds_create( ds_t dsdes,
const char * variable_name,
char flags,
struct sigevent * sigevent );
Arguments:
dsdes
A data server descriptor returned by ds_register().
variable_name
The name of the variable that you want to create.
All variables are global, so only one instance of the variable can
exist in the data server process. The maximum length of a variable
name is 60 characters.
flags
Flags that specify the variable’s behavior:
• DS_PERM — don’t delete the variable when the application
that created it terminates. The variable is removed when the
data server process terminates, or if the flag is turned off after
the application that created the variable terminates.
If flags is 0, the variable is removed if you call ds_deregister(), or
the process terminates.
sigevent
A pointer to a sigevent structure that describes a proxy or signal
to be sent to the external application that created the variable if the
data referenced by the variable changes; see below.
Library:
libds
Use the -l ds option to qcc to link against this library.
Description:
The ds_create() function creates a variable, whose name is given by variable_name,
on the data server identified by dsdes.
If the data referenced by variable_name changes, a proxy or signal, described in the
sigevent structure, can be sent to the external application that created
variable_name (see ds_set()).
We recommend the following event types for use with this function:
• SIGEV_SIGNAL
• SIGEV_SIGNAL_CODE
362
QNX Neutrino Functions and Macros
June 19, 2012
ds_create()
© 2012, QNX Software Systems Limited
• SIGEV_SIGNAL_THREAD
• SIGEV_PULSE
• SIGEV_INTR
To display the current value of a variable on an HTML page, use the qnxvar token
with the read tag. See the description of slinger in the Utilities Reference.
Returns:
0
Success.
-1
An error occurred (errno is set).
Errors:
EBADF
Invalid file descriptor dsdes.
EEXIST
The variable name already exists in the data server.
ENOMEM
Not enough memory to create the variable or initialize the data.
Examples:
See slinger in the Utilities Reference.
Classification:
QNX Neutrino
Safety
Cancellation point
Yes
Interrupt handler
No
Signal handler
Yes
Thread
Yes
See also:
ds_flags(), ds_get(), ds_register(), ds_set(), sigevent
June 19, 2012
QNX Neutrino Functions and Macros
363
ds_deregister()
© 2012, QNX Software Systems Limited
Deregister an application with the data server
Synopsis:
#include <ds.h>
int ds_deregister( ds_t dsdes );
Arguments:
dsdes
A data server descriptor returned by ds_register().
Library:
libds
Use the -l ds option to qcc to link against this library.
Description:
The ds_deregister() function deregisters your application with the data server, dsdes,
and deletes any variables that the data server process created, except those with the
DS_PERM flag set (see ds_flags()).
Returns:
0
Success.
-1
An error occurred (errno is set).
Errors:
EBADF
Invalid file descriptor, dsdes.
Examples:
See slinger in the Utilities Reference.
Classification:
QNX Neutrino
Safety
364
Cancellation point
Yes
Interrupt handler
No
Signal handler
Yes
Thread
Yes
QNX Neutrino Functions and Macros
June 19, 2012
© 2012, QNX Software Systems Limited
ds_deregister()
See also:
ds_flags(), ds_register()
June 19, 2012
QNX Neutrino Functions and Macros
365
ds_flags()
© 2012, QNX Software Systems Limited
Set the flags for a data server variable
Synopsis:
#include <ds.h>
int ds_flags( ds_t dsdes,
const char* variable_name,
char flags );
Arguments:
dsdes
A data server descriptor returned by ds_register().
variable_name
The name of the data server variable.
flags
The new flags for the variable. The flags include:
• DS_PERM — don’t delete the variable when the application
that created it terminates. The variable is removed when the
data server process terminates, or if the flag is turned off after
the application that created the variable terminates.
Library:
libds
Use the -l ds option to qcc to link against this library.
Description:
The ds_flags() function changes the state of the flags belonging to the variable called
variable_name on the data server identified by dsdes.
Returns:
0 for success, or -1 if an error occurs (errno is set).
Errors:
EBADF
Invalid file descriptor dsdes.
ESRCH
The variable doesn’t exist in the data server.
Classification:
QNX Neutrino
Safety
Cancellation point
Yes
Interrupt handler
No
continued. . .
366
QNX Neutrino Functions and Macros
June 19, 2012
ds_flags()
© 2012, QNX Software Systems Limited
Safety
Signal handler
Yes
Thread
Yes
See also:
ds_clear(), ds_create(), ds_deregister(), ds_set()
June 19, 2012
QNX Neutrino Functions and Macros
367
ds_get()
© 2012, QNX Software Systems Limited
Retrieve a data server variable
Synopsis:
#include <ds.h>
int ds_get( ds_t dsdes,
const char* variable_name,
const char* variable_data,
size_t data_len );
Arguments:
dsdes
A data server descriptor returned by ds_register().
variable_name
The name of the data server variable that you want to get.
variable_data
A buffer where the function can store the data associated with the
variable.
data_len
The size of the buffer, in bytes.
Library:
libds
Use the -l ds option to qcc to link against this library.
Description:
The ds_get() function retrieves the data corresponding to variable_name from the data
server dsdes, and places it in the buffer pointed to by variable_data.
Returns:
The amount of data written to the buffer variable_data, or -1 if an error occurs (errno
is set).
Errors:
EBADF
Invalid file descriptor dsdes.
EMSGSIZE
The buffer isn’t big enough for the data.
ESRCH
The variable doesn’t exist in the data server.
Classification:
QNX Neutrino
368
QNX Neutrino Functions and Macros
June 19, 2012
ds_get()
© 2012, QNX Software Systems Limited
Safety
Cancellation point
Yes
Interrupt handler
No
Signal handler
Yes
Thread
Yes
See also:
ds_create(), ds_set()
June 19, 2012
QNX Neutrino Functions and Macros
369
ds_register()
© 2012, QNX Software Systems Limited
Register an application with the data server
Synopsis:
#include <ds.h>
ds_t ds_register( void );
Library:
libds
Use the -l ds option to qcc to link against this library.
Description:
The ds_register() function registers your application with the data server. The data
server must reside on the same node as your application.
Returns:
A data server descriptor, or -1 if an error occurs (errno is set).
Errors:
ENOENT
No such file or directory; the data server isn’t started.
ENOMEM
Insufficient memory is available to communicate with the data server.
Examples:
See slinger in the Utilities Reference.
Classification:
QNX Neutrino
Safety
Cancellation point
Yes
Interrupt handler
No
Signal handler
Yes
Thread
Yes
See also:
ds_deregister()
370
QNX Neutrino Functions and Macros
June 19, 2012
ds_set()
© 2012, QNX Software Systems Limited
Set a data server variable
Synopsis:
#include <ds.h>
int ds_set( ds_t dsdes,
const char* variable_name,
const char* variable_data,
size_t data_len );
Arguments:
dsdes
A data server descriptor returned by ds_register().
variable_name
The name of the data server variable that you want to set.
variable_data
A pointer to the data you want to associate with the variable.
data_len
The size of the data, in bytes.
Library:
libds
Use the -l ds option to qcc to link against this library.
Description:
The ds_set() function passes the data variable_data to the data server identified by
dsdes. The data server stores the data in the variable whose name is given by
variable_name, overwriting any existing value.
To display the modified data on an HTML page, use the qnxvar token with the read
tag. See the description of slinger in the Utilities Reference.
Returns:
0 for success, or -1 if an error occurs (errno is set).
Errors:
EBADF
Invalid file descriptor dsdes.
ENOMEM
Not enough memory to store the data.
ESRCH
The variable doesn’t exist in the data server.
Examples:
See slinger in the Utilities Reference.
June 19, 2012
QNX Neutrino Functions and Macros
371
ds_set()
© 2012, QNX Software Systems Limited
Classification:
QNX Neutrino
Safety
Cancellation point
Yes
Interrupt handler
No
Signal handler
Yes
Thread
Yes
See also:
ds_create(), ds_flags(), ds_get()
372
QNX Neutrino Functions and Macros
June 19, 2012
dup()
© 2012, QNX Software Systems Limited
Duplicate a file descriptor
Synopsis:
#include <unistd.h>
int dup( int filedes );
Arguments:
filedes
The file descriptor that you want to duplicate.
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
The dup() function duplicates the file descriptor specified by filedes. The new file
descriptor refers to the same open file descriptor as the original, and shares any locks.
The new file descriptor also:
• references the same file or device
• has the same open mode (read and/or write)
• has an identical file position to the original (changing the position with one
descriptor results in a changed position in the other).
Changing the file position with one descriptor results in a changed position for the
other.
Calling:
dup_filedes = dup( filedes );
is the same as:
dup_filedes = fcntl( filedes, F_DUPFD, 0 );
Returns:
The new file descriptor for success, or -1 if an error occurs (errno is set).
Errors:
June 19, 2012
EBADF
The file descriptor, filedes, isn’t a valid.
EMFILE
There are already OPEN_MAX file descriptors in use.
ENOSYS
The dup() function isn’t implemented for the filesystem specified by
filedes.
QNX Neutrino Functions and Macros
373
dup()
© 2012, QNX Software Systems Limited
Examples:
#include
#include
#include
#include
<fcntl.h>
<unistd.h>
<sys/stat.h>
<stdlib.h>
int main( void )
{
int filedes, dup_filedes;
filedes= open( "file",
O_WRONLY | O_CREAT | O_TRUNC,
S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP );
if( filedes != -1 ) {
dup_filedes = dup( filedes );
if( dup_filedes != -1 ) {
/* process file */
/* ... */
close( dup_filedes );
}
close( filedes );
return EXIT_SUCCESS;
}
return EXIT_FAILURE;
}
Classification:
POSIX 1003.1
Safety
Cancellation point
No
Interrupt handler
No
Signal handler
Yes
Thread
Yes
See also:
chsize(), close(), creat(), dup2(), eof(), errno, execl(), execle(), execlp(), execlpe(),
execv(), execve(), execvp(), execvpe(), fcntl(), fileno(), fstat(), isatty(), lseek(), open(),
read(), sopen(), stat(), tell(), umask(), write()
374
QNX Neutrino Functions and Macros
June 19, 2012
dup2()
© 2012, QNX Software Systems Limited
Duplicate a file descriptor, specifying the new descriptor
Synopsis:
#include <unistd.h>
int dup2( int filedes,
int filedes2 );
Arguments:
filedes
The file descriptor that you want to duplicate.
filedes2
The number that you want to use for the new file descriptor.
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
The dup2() function duplicates the file descriptor specified by filedes. The number of
the new file descriptor will be filedes2. If a file already is opened with this descriptor,
the file is closed before the duplication is attempted.
The new file descriptor:
• references the same file or device
• has the same open mode (read and/or write)
• has an identical file position to the original (changing the position with one
descriptor results in a changed position in the other).
Calling:
dup_filedes = dup2( filedes, filedes2 );
Is the same as:
close( filedes2 );
dup_filedes = fcntl( filedes , F_DUPFD, filedes2 );
Returns:
The value of filedes2 for success, or -1 if an error occurs (errno is set).
Errors:
June 19, 2012
EBADF
The file descriptor, filedes isn’t a valid open file descriptor, or filedes2 is
out of range.
EMFILE
There are already OPEN_MAX file descriptors in use.
ENOSYS
The dup2() function isn’t implemented for the filesystem specified by
filedes.
QNX Neutrino Functions and Macros
375
dup2()
© 2012, QNX Software Systems Limited
Examples:
#include
#include
#include
#include
<fcntl.h>
<unistd.h>
<sys/stat.h>
<stdlib.h>
int main( void )
{
int filedes , dup_filedes ;
filedes = open( "file",
O_WRONLY | O_CREAT | O_TRUNC,
S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP );
if( filedes != -1 ) {
dup_filedes = 4;
if( dup2( filedes, dup_filedes ) != -1 ) {
/* process file */
/* ... */
close( dup_filedes );
}
close( filedes );
return EXIT_SUCCESS;
}
return EXIT_FAILURE;
}
Classification:
POSIX 1003.1
Safety
Cancellation point
No
Interrupt handler
No
Signal handler
Yes
Thread
Yes
See also:
chsize(), close(), creat(), dup(), eof(), errno, execl(), execle(), execlp(), execlpe(),
execv(), execve(), execvp(), execvpe(), fcntl(), fileno(), fstat(), isatty(), lseek(), open(),
read(), sopen(), stat(), tell(), umask(), write()
376
QNX Neutrino Functions and Macros
June 19, 2012
eaccess()
© 2012, QNX Software Systems Limited
Check to see if a file or directory can be accessed (extended version)
Synopsis:
#include <libgen.h>
#include <unistd.h>
int eaccess( const char * path,
int amode );
Arguments:
path
The path to the file or directory that you want to access.
amode
The access mode you want to check. This must be either:
• F_OK — test for file existence.
or a bitwise ORing of the following access permissions to be checked, as
defined in the header <unistd.h>:
• R_OK — test for read permission.
• W_OK — test for write permission.
• X_OK — for a directory, test for search permission. Otherwise, test for
execute permission.
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
The eaccess() function is an extended version of access(). It checks if the file or
directory specified by path exists and if it can be accessed with the file access
permissions given by amode. However, unlike access(), it uses the effective user ID
and effective group ID.
Returns:
0
The file or directory exists and can be accessed with the specified mode.
-1
An error occurred (errno is set.)
Errors:
June 19, 2012
EACCES
The permissions specified by amode are denied, or search permission is
denied on a component of the path prefix.
EINVAL
An invalid value was specified for amode.
ELOOP
Too many levels of symbolic links or prefixes.
QNX Neutrino Functions and Macros
377
eaccess()
© 2012, QNX Software Systems Limited
ENAMETOOLONG
ENOENT
The length of the path string exceeds PATH_MAX, or a pathname
component is longer than NAME_MAX.
A component of the path isn’t valid.
ENOSYS
The eaccess() function isn’t implemented for the filesystem specified in
path.
ENOTDIR
A component of the path prefix isn’t a directory.
EROFS
Write access was requested for a file residing on a read-only file
system.
Classification:
Unix
Safety
Cancellation point
No
Interrupt handler
No
Signal handler
Yes
Thread
Yes
See also:
access(), chmod(), errno, fstat(), open(), stat()
378
QNX Neutrino Functions and Macros
June 19, 2012
© 2012, QNX Software Systems Limited
_edata
The end of the data segment, excluding BSS data
Synopsis:
N/A
Description:
This linker symbol defines the end of the data segment, excluding BSS data. This
variable isn’t defined in any header file.
Classification:
QNX Neutrino
See also:
brk(), _btext, _end, _etext, sbrk()
June 19, 2012
QNX Neutrino Functions and Macros
379
encrypt()
© 2012, QNX Software Systems Limited
Encrypt or decrypt a string
Synopsis:
#include <unistd.h>
void encrypt( char block[64],
int flag );
Arguments:
block
A 64-character array of binary values to encrypt. The function stores the
encrypted value in the same array.
flag
0 if you want to encrypt block, nonzero to decrypt it.
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
This function is in libc.a, but not in libc.so (in order to save space).
Description:
The encrypt() function uses the NBS Data Encryption Standard (DES) algorithm and
the key you specify by calling setkey() to encrypt (if flags is zero) or decrypt (if flags is
nonzero) the given block of data.
Classification:
POSIX 1003.1 XSI
Safety
Cancellation point
No
Interrupt handler
No
Signal handler
No
Thread
No
See also:
crypt(), setkey()
380
QNX Neutrino Functions and Macros
June 19, 2012
© 2012, QNX Software Systems Limited
_end
The end of the data segment, including BSS data
Synopsis:
N/A
Description:
This linker symbol defines the end of the data segment, including BSS data. This
variable isn’t defined in any header file.
Classification:
QNX Neutrino
See also:
brk(), _btext, _edata, _etext, sbrk()
June 19, 2012
QNX Neutrino Functions and Macros
381
endfsent()
© 2012, QNX Software Systems Limited
Close the filesystem table (/etc/fstab) file
Synopsis:
#include <fstab.h>
void endfsent( void );
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
This function is in libc.a, but not in libc.so (in order to save space).
Description:
The endfsent() routine closes the filesystem table file, /etc/fstab.
Classification:
NetBSD
Safety
Cancellation point
Yes
Interrupt handler
No
Signal handler
No
Thread
No
Caveats:
The functions that work with /etc/fstab use static data storage; if you need the data
for future use, copy it before any subsequent calls overwrite it.
See also:
getfsent(), getfsfile(), getfsspec(), setfsent()
/etc/fstab in the Utilities Reference
382
QNX Neutrino Functions and Macros
June 19, 2012
endgrent()
© 2012, QNX Software Systems Limited
Close the group database file
Synopsis:
#include <grp.h>
int endgrent( void );
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
The endgrent() routine closes the group name database file, so all group access
routines behave as if setgrent() had never been called.
Returns:
Zero.
Classification:
POSIX 1003.1 XSI
Safety
Cancellation point
Yes
Interrupt handler
No
Signal handler
No
Thread
No
See also:
getgrent(), setgrent()
June 19, 2012
QNX Neutrino Functions and Macros
383
endhostent()
© 2012, QNX Software Systems Limited
Close the TCP connection and the hosts file
Synopsis:
#include <netdb.h>
void endhostent( void );
Library:
libsocket
Use the -l socket option to qcc to link against this library.
Description:
The endhostent() routine closes the TCP connection and the hosts file.
Files:
/etc/hosts
Host database file.
Classification:
POSIX 1003.1
Safety
Cancellation point
Yes
Interrupt handler
No
Signal handler
No
Thread
No
See also:
gethostbyaddr(), gethostbyname(), gethostent(), hostent, sethostent()
/etc/hosts, /etc/resolv.conf in the Utilities Reference
384
QNX Neutrino Functions and Macros
June 19, 2012
ENDIAN_BE16()
© 2012, QNX Software Systems Limited
Return a big-endian 16-bit value in native format
Synopsis:
#include <gulliver.h>
uint16_t ENDIAN_BE16( uint16_t num );
Arguments:
num
The big-endian number you want to convert.
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
The ENDIAN_BE16() macro returns the native version of the big-endian value num.
Returns:
The native-endian value of num.
Examples:
Convert a big-endian value to native-endian:
#include
#include
#include
#include
<stdio.h>
<stdlib.h>
<gulliver.h>
<inttypes.h>
int main( void )
{
uint16_t val = 0x1234;
printf( "0x%04x = 0x%04x\n",
val, ENDIAN_BE16( val ) );
return EXIT_SUCCESS;
}
On a little-endian system, this prints:
0x1234 = 0x3412
Classification:
QNX Neutrino
June 19, 2012
QNX Neutrino Functions and Macros
385
ENDIAN_BE16()
© 2012, QNX Software Systems Limited
Safety
Cancellation point
No
Interrupt handler
Yes
Signal handler
Yes
Thread
Yes
Caveats:
ENDIAN_BE16() is implemented as a macro.
See also:
ENDIAN_BE32(), ENDIAN_BE64(), ENDIAN_LE16(), ENDIAN_LE32(),
ENDIAN_LE64(), ENDIAN_RET16(), ENDIAN_RET32(), ENDIAN_RET64(),
ENDIAN_SWAP16(), ENDIAN_SWAP32(), ENDIAN_SWAP64(), htonl(), htons(),
ntohl(), ntohs(), UNALIGNED_RET16(), UNALIGNED_RET32(),
UNALIGNED_RET64(), UNALIGNED_PUT16(), UNALIGNED_PUT32(),
UNALIGNED_PUT64()
386
QNX Neutrino Functions and Macros
June 19, 2012
ENDIAN_BE32()
© 2012, QNX Software Systems Limited
Return a big-endian 32-bit value in native format
Synopsis:
#include <gulliver.h>
uint32_t ENDIAN_BE32( uint32_t num );
Arguments:
num
The big-endian number you want to convert.
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
The ENDIAN_BE32() macro returns the native version of the big-endian value num.
Returns:
The native-endian value of num.
Examples:
Convert a big-endian value to native-endian:
#include
#include
#include
#include
<stdio.h>
<stdlib.h>
<gulliver.h>
<inttypes.h>
int main( void )
{
uint32_t val = 0xdeadbeef;
printf( "0x%08x = 0x%08x\n",
val, ENDIAN_BE32( val ) );
return EXIT_SUCCESS;
}
On a little-endian system, this prints:
0xdeadbeef = 0xefbeadde
Classification:
QNX Neutrino
June 19, 2012
QNX Neutrino Functions and Macros
387
ENDIAN_BE32()
© 2012, QNX Software Systems Limited
Safety
Cancellation point
No
Interrupt handler
Yes
Signal handler
Yes
Thread
Yes
Caveats:
ENDIAN_BE32() is implemented as a macro.
See also:
ENDIAN_BE16(), ENDIAN_BE64(), ENDIAN_LE16(), ENDIAN_LE32(),
ENDIAN_LE64(), ENDIAN_RET16(), ENDIAN_RET32(), ENDIAN_RET64(),
ENDIAN_SWAP16(), ENDIAN_SWAP32(), ENDIAN_SWAP64(), htonl(), htons(),
ntohl(), ntohs(), UNALIGNED_RET16(), UNALIGNED_RET32(),
UNALIGNED_RET64(), UNALIGNED_PUT16(), UNALIGNED_PUT32(),
UNALIGNED_PUT64()
388
QNX Neutrino Functions and Macros
June 19, 2012
ENDIAN_BE64()
© 2012, QNX Software Systems Limited
Return a big-endian 64-bit value in native format
Synopsis:
#include <gulliver.h>
uint64_t ENDIAN_BE64( uint64_t num );
Arguments:
num
The big-endian number you want to convert.
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
The ENDIAN_BE64() macro returns the native version of the big-endian value num.
Returns:
The native-endian value of num.
Examples:
Convert a big-endian value to native-endian:
#include
#include
#include
#include
<stdio.h>
<stdlib.h>
<gulliver.h>
<inttypes.h>
int main( void )
{
uint64_t val = 0x1234deadbeef5678;
printf( "0x%016llx = 0x%016llx\n",
val, ENDIAN_BE64( val ) );
return EXIT_SUCCESS;
}
On a little-endian system, this prints:
0x1234deadbeef5678 = 0x7856efbeadde3412
Classification:
QNX Neutrino
June 19, 2012
QNX Neutrino Functions and Macros
389
ENDIAN_BE64()
© 2012, QNX Software Systems Limited
Safety
Cancellation point
No
Interrupt handler
Yes
Signal handler
Yes
Thread
Yes
Caveats:
ENDIAN_BE64() is implemented as a macro.
See also:
ENDIAN_BE16(), ENDIAN_BE32(), ENDIAN_LE16(), ENDIAN_LE32(),
ENDIAN_LE64(), ENDIAN_RET16(), ENDIAN_RET32(), ENDIAN_RET64(),
ENDIAN_SWAP16(), ENDIAN_SWAP32(), ENDIAN_SWAP64(), htonl(), htons(),
ntohl(), ntohs(), UNALIGNED_RET16(), UNALIGNED_RET32(),
UNALIGNED_RET64(), UNALIGNED_PUT16(), UNALIGNED_PUT32(),
UNALIGNED_PUT64()
390
QNX Neutrino Functions and Macros
June 19, 2012
ENDIAN_LE16()
© 2012, QNX Software Systems Limited
Return a little-endian 16-bit value in native format
Synopsis:
#include <gulliver.h>
uint16_t ENDIAN_LE16( uint16_t num );
Arguments:
num
The little-endian number you want to convert.
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
The ENDIAN_LE16() macro returns the native version of the little-endian value num.
Returns:
The native-endian value of num.
Examples:
Convert a little-endian value to native-endian:
#include
#include
#include
#include
<stdio.h>
<stdlib.h>
<gulliver.h>
<inttypes.h>
int main( void )
{
uint16_t val = 0x1234;
printf( "0x%04x = 0x%04x\n",
val, ENDIAN_LE16( val ) );
return EXIT_SUCCESS;
}
On a big-endian system, this prints:
0x1234 = 0x3412
Classification:
QNX Neutrino
June 19, 2012
QNX Neutrino Functions and Macros
391
ENDIAN_LE16()
© 2012, QNX Software Systems Limited
Safety
Cancellation point
No
Interrupt handler
Yes
Signal handler
Yes
Thread
Yes
Caveats:
ENDIAN_LE16() is implemented as a macro.
See also:
ENDIAN_BE16(), ENDIAN_BE32(), ENDIAN_BE64(), ENDIAN_LE32(),
ENDIAN_LE64(), ENDIAN_RET16(), ENDIAN_RET32(), ENDIAN_RET64(),
ENDIAN_SWAP16(), ENDIAN_SWAP32(), ENDIAN_SWAP64(), htonl(), htons(),
ntohl(), ntohs(), UNALIGNED_RET16(), UNALIGNED_RET32(),
UNALIGNED_RET64(), UNALIGNED_PUT16(), UNALIGNED_PUT32(),
UNALIGNED_PUT64()
392
QNX Neutrino Functions and Macros
June 19, 2012
ENDIAN_LE32()
© 2012, QNX Software Systems Limited
Return a little-endian 32-bit value in native format
Synopsis:
#include <gulliver.h>
uint32_t ENDIAN_LE32( uint32_t num );
Arguments:
num
The little-endian number you want to convert.
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
The ENDIAN_LE32() macro returns the native version of the little-endian value num.
Returns:
The native-endian value of num.
Examples:
Convert a little-endian value to native-endian:
#include
#include
#include
#include
<stdio.h>
<stdlib.h>
<gulliver.h>
<inttypes.h>
int main( void )
{
uint32_t val = 0xdeadbeef;
printf( "0x%08x = 0x%08x\n",
val, ENDIAN_LE32( val ) );
return EXIT_SUCCESS;
}
On a big-endian system, this prints:
0xdeadbeef = 0xefbeadde
Classification:
QNX Neutrino
June 19, 2012
QNX Neutrino Functions and Macros
393
ENDIAN_LE32()
© 2012, QNX Software Systems Limited
Safety
Cancellation point
No
Interrupt handler
Yes
Signal handler
Yes
Thread
Yes
Caveats:
ENDIAN_LE32() is implemented as a macro.
See also:
ENDIAN_BE16(), ENDIAN_BE32(), ENDIAN_BE64(), ENDIAN_LE16(),
ENDIAN_LE64(), ENDIAN_RET16(), ENDIAN_RET32(), ENDIAN_RET64(),
ENDIAN_SWAP16(), ENDIAN_SWAP32(), ENDIAN_SWAP64(), htonl(), htons(),
ntohl(), ntohs(), UNALIGNED_RET16(), UNALIGNED_RET32(),
UNALIGNED_RET64(), UNALIGNED_PUT16(), UNALIGNED_PUT32(),
UNALIGNED_PUT64()
394
QNX Neutrino Functions and Macros
June 19, 2012
ENDIAN_LE64()
© 2012, QNX Software Systems Limited
Return a little-endian 64-bit value in native format
Synopsis:
#include <gulliver.h>
uint64_t ENDIAN_LE64( uint64_t num );
Arguments:
num
The little-endian number you want to convert.
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
The ENDIAN_LE64() macro returns the native version of the little-endian value num.
Returns:
The native-endian value of num.
Examples:
Convert a little-endian value to native-endian:
#include
#include
#include
#include
<stdio.h>
<stdlib.h>
<gulliver.h>
<inttypes.h>
int main( void )
{
uint64_t val = 0x1234deadbeef5678;
printf( "0x%016llx = 0x%016llx\n",
val, ENDIAN_LE64( val ) );
return EXIT_SUCCESS;
}
On a big-endian system, this prints:
0x1234deadbeef5678 = 0x7856efbeadde3412
Classification:
QNX Neutrino
June 19, 2012
QNX Neutrino Functions and Macros
395
ENDIAN_LE64()
© 2012, QNX Software Systems Limited
Safety
Cancellation point
No
Interrupt handler
Yes
Signal handler
Yes
Thread
Yes
Caveats:
ENDIAN_LE64() is implemented as a macro.
See also:
ENDIAN_BE16(), ENDIAN_BE32(), ENDIAN_BE64(), ENDIAN_LE16(),
ENDIAN_LE32(), ENDIAN_RET16(), ENDIAN_RET32(), ENDIAN_RET64(),
ENDIAN_SWAP16(), ENDIAN_SWAP32(), ENDIAN_SWAP64(), htonl(), htons(),
ntohl(), ntohs(), UNALIGNED_RET16(), UNALIGNED_RET32(),
UNALIGNED_RET64(), UNALIGNED_PUT16(), UNALIGNED_PUT32(),
UNALIGNED_PUT64()
396
QNX Neutrino Functions and Macros
June 19, 2012
ENDIAN_RET16()
© 2012, QNX Software Systems Limited
Return an endian-swapped 16-bit value
Synopsis:
#include <gulliver.h>
uint16_t ENDIAN_RET16( uint16_t num );
Arguments:
num
The number you want to convert.
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
The ENDIAN_RET16() macro returns the endian-swapped value of num.
Returns:
The endian-swapped value of num.
Examples:
Swap the endianness of a value:
#include
#include
#include
#include
<stdio.h>
<stdlib.h>
<gulliver.h>
<inttypes.h>
int main( void )
{
uint16_t val = 0x1234;
printf( "0x%04x = 0x%04x\n",
val, ENDIAN_RET16( val ) );
return EXIT_SUCCESS;
}
This prints:
0x1234 = 0x3412
Classification:
QNX Neutrino
June 19, 2012
QNX Neutrino Functions and Macros
397
ENDIAN_RET16()
© 2012, QNX Software Systems Limited
Safety
Cancellation point
No
Interrupt handler
Yes
Signal handler
Yes
Thread
Yes
Caveats:
ENDIAN_RET16() is implemented as a macro.
See also:
ENDIAN_BE16(), ENDIAN_BE32(), ENDIAN_BE64(), ENDIAN_LE16(),
ENDIAN_LE32(), ENDIAN_LE64(), ENDIAN_RET32(), ENDIAN_RET64(),
ENDIAN_SWAP16(), ENDIAN_SWAP32(), ENDIAN_SWAP64(), htonl(), htons(),
ntohl(), ntohs(), UNALIGNED_RET16(), UNALIGNED_RET32(),
UNALIGNED_RET64(), UNALIGNED_PUT16(), UNALIGNED_PUT32(),
UNALIGNED_PUT64()
398
QNX Neutrino Functions and Macros
June 19, 2012
ENDIAN_RET32()
© 2012, QNX Software Systems Limited
Return an endian-swapped 32-bit value
Synopsis:
#include <gulliver.h>
uint32_t ENDIAN_RET32( uint32_t num );
Arguments:
num
The number you want to convert.
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
The ENDIAN_RET32() macro returns the endian-swapped value of num.
Returns:
The endian-swapped value of num.
Examples:
Swap the endianness of a value:
#include
#include
#include
#include
<stdio.h>
<stdlib.h>
<gulliver.h>
<inttypes.h>
int main( void )
{
uint32_t val = 0xdeadbeef;
printf( "0x%08x = 0x%08x\n",
val, ENDIAN_RET32( val ) );
return EXIT_SUCCESS;
}
This prints:
0xdeadbeef = 0xefbeadde
Classification:
QNX Neutrino
June 19, 2012
QNX Neutrino Functions and Macros
399
ENDIAN_RET32()
© 2012, QNX Software Systems Limited
Safety
Cancellation point
No
Interrupt handler
Yes
Signal handler
Yes
Thread
Yes
Caveats:
ENDIAN_RET32() is implemented as a macro.
See also:
ENDIAN_BE16(), ENDIAN_BE32(), ENDIAN_BE64(), ENDIAN_LE16(),
ENDIAN_LE32(), ENDIAN_LE64(), ENDIAN_RET16(), ENDIAN_RET64(),
ENDIAN_SWAP16(), ENDIAN_SWAP32(), ENDIAN_SWAP64(), htonl(), htons(),
ntohl(), ntohs(), UNALIGNED_RET16(), UNALIGNED_RET32(),
UNALIGNED_RET64(), UNALIGNED_PUT16(), UNALIGNED_PUT32(),
UNALIGNED_PUT64()
400
QNX Neutrino Functions and Macros
June 19, 2012
ENDIAN_RET64()
© 2012, QNX Software Systems Limited
Return an endian-swapped 64-bit value
Synopsis:
#include <gulliver.h>
uint64_t ENDIAN_RET64( uint64_t num );
Arguments:
num
The number you want to convert.
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
The ENDIAN_RET64() macro returns the endian-swapped value of num.
Returns:
The endian-swapped value of num.
Examples:
Swap the endianness of a value:
#include
#include
#include
#include
<stdio.h>
<stdlib.h>
<gulliver.h>
<inttypes.h>
int main( void )
{
uint64_t val = 0x1234deadbeef5678;
printf( "0x%016llx = 0x%016llx\n",
val, ENDIAN_RET64( val ) );
return EXIT_SUCCESS;
}
This prints:
0x1234deadbeef5678 = 0x7856efbeadde3412
Classification:
QNX Neutrino
June 19, 2012
QNX Neutrino Functions and Macros
401
ENDIAN_RET64()
© 2012, QNX Software Systems Limited
Safety
Cancellation point
No
Interrupt handler
Yes
Signal handler
Yes
Thread
Yes
Caveats:
ENDIAN_RET64() is implemented as a macro.
See also:
ENDIAN_BE16(), ENDIAN_BE32(), ENDIAN_BE64(), ENDIAN_LE16(),
ENDIAN_LE32(), ENDIAN_LE64(), ENDIAN_RET16(), ENDIAN_RET32(),
ENDIAN_SWAP16(), ENDIAN_SWAP32(), ENDIAN_SWAP64(), htonl(), htons(),
ntohl(), ntohs(), UNALIGNED_RET16(), UNALIGNED_RET32(),
UNALIGNED_RET64(), UNALIGNED_PUT16(), UNALIGNED_PUT32(),
UNALIGNED_PUT64()
402
QNX Neutrino Functions and Macros
June 19, 2012
ENDIAN_SWAP16()
© 2012, QNX Software Systems Limited
Endian-swap a 16-bit value in place
Synopsis:
#include <gulliver.h>
void ENDIAN_SWAP16( uint16_t * num );
Arguments:
num
A pointer to the number you want to convert.
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
The ENDIAN_SWAP16() macro endian-swaps the value pointed to by num in place.
Examples:
Swap the endianness of a value:
#include
#include
#include
#include
<stdio.h>
<stdlib.h>
<gulliver.h>
<inttypes.h>
int main( void )
{
uint16_t val = 0x1234;
ENDIAN_SWAP16( &val );
printf( "val = 0x%04x\n", val );
return EXIT_SUCCESS;
}
This prints:
val = 0x3412
Classification:
QNX Neutrino
Safety
Cancellation point
No
Interrupt handler
Yes
continued. . .
June 19, 2012
QNX Neutrino Functions and Macros
403
ENDIAN_SWAP16()
© 2012, QNX Software Systems Limited
Safety
Signal handler
Yes
Thread
Yes
Caveats:
ENDIAN_SWAP16() is implemented as a macro.
See also:
ENDIAN_BE16(), ENDIAN_BE32(), ENDIAN_BE64(), ENDIAN_LE16(),
ENDIAN_LE32(), ENDIAN_LE64(), ENDIAN_RET16(), ENDIAN_RET32(),
ENDIAN_RET64(), ENDIAN_SWAP32(), ENDIAN_SWAP64(), htonl(), htons(),
ntohl(), ntohs(), UNALIGNED_RET16(), UNALIGNED_RET32(),
UNALIGNED_RET64(), UNALIGNED_PUT16(), UNALIGNED_PUT32(),
UNALIGNED_PUT64()
404
QNX Neutrino Functions and Macros
June 19, 2012
ENDIAN_SWAP32()
© 2012, QNX Software Systems Limited
Endian-swap a 32-bit value in place
Synopsis:
#include <gulliver.h>
void ENDIAN_SWAP32( uint32_t * num );
Arguments:
num
A pointer to the number you want to convert.
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
The ENDIAN_SWAP32() macro endian-swaps the value pointed to by num in place.
Examples:
Swap the endianness of a value:
#include
#include
#include
#include
<stdio.h>
<stdlib.h>
<gulliver.h>
<inttypes.h>
int main( void )
{
uint32_t val = 0xdeadbeef;
ENDIAN_SWAP32( &val );
printf( "val = 0x%08x\n", val );
return EXIT_SUCCESS;
}
This prints:
val = 0xefbeadde
Classification:
QNX Neutrino
Safety
Cancellation point
No
Interrupt handler
Yes
continued. . .
June 19, 2012
QNX Neutrino Functions and Macros
405
ENDIAN_SWAP32()
© 2012, QNX Software Systems Limited
Safety
Signal handler
Yes
Thread
Yes
Caveats:
ENDIAN_SWAP32() is implemented as a macro.
See also:
ENDIAN_BE16(), ENDIAN_BE32(), ENDIAN_BE64(), ENDIAN_LE16(),
ENDIAN_LE32(), ENDIAN_LE64(), ENDIAN_RET16(), ENDIAN_RET32(),
ENDIAN_RET64(), ENDIAN_SWAP16(), ENDIAN_SWAP64(), htonl(), htons(),
ntohl(), ntohs(), UNALIGNED_RET16(), UNALIGNED_RET32(),
UNALIGNED_RET64(), UNALIGNED_PUT16(), UNALIGNED_PUT32(),
UNALIGNED_PUT64()
406
QNX Neutrino Functions and Macros
June 19, 2012
ENDIAN_SWAP64()
© 2012, QNX Software Systems Limited
Endian-swap a 64-bit value in place
Synopsis:
#include <gulliver.h>
void ENDIAN_SWAP64( uint64_t * num );
Arguments:
num
A pointer to the number you want to convert.
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
The ENDIAN_SWAP64() macro endian-swaps the value pointed to by num in place.
Examples:
Swap the endianness of a value:
#include
#include
#include
#include
<stdio.h>
<stdlib.h>
<gulliver.h>
<inttypes.h>
int main( void )
{
uint64_t val = 0x1234deadbeef5678LL;
ENDIAN_SWAP16( &val );
printf( "val = 0x%016x\n", val );
return EXIT_SUCCESS;
}
This prints:
val = 0x7856efbeadde3412
Classification:
QNX Neutrino
Safety
Cancellation point
No
Interrupt handler
Yes
continued. . .
June 19, 2012
QNX Neutrino Functions and Macros
407
ENDIAN_SWAP64()
© 2012, QNX Software Systems Limited
Safety
Signal handler
Yes
Thread
Yes
Caveats:
ENDIAN_SWAP64() is implemented as a macro.
See also:
ENDIAN_BE16(), ENDIAN_BE32(), ENDIAN_BE64(), ENDIAN_LE16(),
ENDIAN_LE32(), ENDIAN_LE64(), ENDIAN_RET16(), ENDIAN_RET32(),
ENDIAN_RET64(), ENDIAN_SWAP16(), ENDIAN_SWAP32(), htonl(), htons(),
ntohl(), ntohs(), UNALIGNED_PUT16(), UNALIGNED_PUT32(),
UNALIGNED_PUT64() UNALIGNED_RET16(), UNALIGNED_RET32(),
UNALIGNED_RET64(),
408
QNX Neutrino Functions and Macros
June 19, 2012
endnetent()
© 2012, QNX Software Systems Limited
Close the network name database file
Synopsis:
#include <netdb.h>
void endnetent( void );
Library:
libsocket
Use the -l socket option to qcc to link against this library.
Description:
The endnetent() routine closes the network name database file.
Files:
/etc/networks
Network name database file.
Classification:
POSIX 1003.1
Safety
Cancellation point
Yes
Interrupt handler
No
Signal handler
No
Thread
No
See also:
getnetbyaddr(), getnetbyname(), getnetent(), netent, setnetent()
/etc/networks in the Utilities Reference
June 19, 2012
QNX Neutrino Functions and Macros
409
endprotoent()
© 2012, QNX Software Systems Limited
Close the protocol name database file
Synopsis:
#include <netdb.h>
void endprotoent( void );
Library:
libsocket
Use the -l socket option to qcc to link against this library.
Description:
The endprotoent() routine closes the protocol name database file.
Files:
/etc/protocols
Protocol name database file.
Classification:
POSIX 1003.1
Safety
Cancellation point
Yes
Interrupt handler
No
Signal handler
No
Thread
No
See also:
getprotobyname() getprotobynumber(), getprotoent(), protoent, setprotoent()
/etc/protocols in the Utilities Reference
410
QNX Neutrino Functions and Macros
June 19, 2012
endpwent()
© 2012, QNX Software Systems Limited
Close the password database file
Synopsis:
#include <sys/types.h>
#include <pwd.h>
int endpwent( void );
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
The endpwent() function closes the password name database file, so all password
access routines behave as if setpwent() had never been called.
Returns:
Zero.
Classification:
POSIX 1003.1 XSI
Safety
Cancellation point
Yes
Interrupt handler
No
Signal handler
No
Thread
No
See also:
getpwent(), getpwent_r(), setpwent()
June 19, 2012
QNX Neutrino Functions and Macros
411
endservent()
© 2012, QNX Software Systems Limited
Close the network services database file
Synopsis:
#include <netdb.h>
void endservent( void );
Library:
libsocket
Use the -l socket option to qcc to link against this library.
Description:
The endservent() routine closes the network services database file.
Files:
/etc/services
Network services database file.
Classification:
POSIX 1003.1
Safety
Cancellation point
Yes
Interrupt handler
No
Signal handler
No
Thread
No
See also:
getservbyname(), getservbyport(), getservent(), servent, setservent()
/etc/services in the Utilities Reference
412
QNX Neutrino Functions and Macros
June 19, 2012
endspent()
© 2012, QNX Software Systems Limited
Close the shadow password database file
Synopsis:
#include <sys/types.h>
#include <shadow.h>
void endspent( void );
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
The endspent() function closes the shadow password database file, so all password
access routines behave as if setspent() had never been called.
Returns:
Zero.
Classification:
Unix
Safety
Cancellation point
Yes
Interrupt handler
No
Signal handler
No
Thread
No
See also:
getspent(), setspent()
June 19, 2012
QNX Neutrino Functions and Macros
413
endutent()
© 2012, QNX Software Systems Limited
Close the current user-information file
Synopsis:
#include <utmp.h>
void endutent( void );
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
This function is in libc.a, but not in libc.so (in order to save space).
Description:
The endutent() function closes the currently open file specified in _PATH_UTMP.
Files:
_PATH_UTMP
The name of the user information file.
Classification:
Unix
Safety
Cancellation point
Yes
Interrupt handler
No
Signal handler
No
Thread
No
See also:
getutent(), getutid(), getutline(), pututline(), setutent(), utmp, utmpname()
login in the Utilities Reference
414
QNX Neutrino Functions and Macros
June 19, 2012
environ
© 2012, QNX Software Systems Limited
Pointer to the process’s environment variables
Synopsis:
#include <unistd.h>
extern char ** environ;
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
When a process begins, an array of strings called the environment is made available.
This array is pointed to by the external variable environ. The strings in the array have
the form:
variable=value
and are terminated by a NULL pointer.
Classification:
POSIX 1003.1
Caveats:
Don’t modify environ directly; use clearenv(), getenv(), putenv(), searchenv(), setenv(),
and unsetenv().
Changes to the environment affect all threads in a multithreaded process.
See also:
clearenv(), getenv(), putenv(), searchenv(), setenv(), unsetenv()
June 19, 2012
QNX Neutrino Functions and Macros
415
eof()
© 2012, QNX Software Systems Limited
Test if the end-of-file has been reached
Synopsis:
#include <unistd.h>
int eof( int filedes );
Arguments:
filedes
A file descriptor for the file that you want to check.
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
The eof() function is a low-level function that determines if the end of the file specified
by filedes has been reached.
Input operations set the current file position; you can call the eof() function to detect
the end of the file before more input operations to prevent attempts at reading beyond
the end of the file.
Returns:
1
The end-of-file has been reached.
0
The end-of-file hasn’t been reached.
-1
An error occurred (errno is set).
Errors:
EBADF
The file descriptor, filedes, isn’t valid.
Examples:
#include
#include
#include
#include
<stdio.h>
<fcntl.h>
<unistd.h>
<stdlib.h>
int main( void )
{
int filedes , len;
char buffer[100];
filedes = open( "file", O_RDONLY );
if( filedes != -1 ) {
while( ! eof( filedes ) ) {
len = read( filedes , buffer, sizeof(buffer) - 1 );
buffer[ len ] = ’\0’;
416
QNX Neutrino Functions and Macros
June 19, 2012
eof()
© 2012, QNX Software Systems Limited
printf( "%s", buffer );
}
close( filedes );
return EXIT_SUCCESS;
}
return EXIT_FAILURE;
}
Classification:
QNX 4
Safety
Cancellation point
Yes
Interrupt handler
No
Signal handler
Yes
Thread
Yes
See also:
errno, feof(), open(), read()
June 19, 2012
QNX Neutrino Functions and Macros
417
erand48()
© 2012, QNX Software Systems Limited
Generate a pseudo-random double in a thread-safe manner
Synopsis:
#include <stdlib.h>
double erand48( unsigned short int xsubi[3] );
Arguments:
xsubi
An array that comprises the 48 bits of the initial value that you want to use.
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
The erand48() function uses a linear congruential algorithm and 48-bit integer
arithmetic to generate a nonnegative double uniformly distributed over the interval
[0.0, 1.0]. It’s a thread-safe version of drand48().
The xsubi array should contain the desired initial value; this makes erand48()
thread-safe, and lets you start a sequence of random numbers at any known value.
Returns:
A pseudo-random double.
Classification:
POSIX 1003.1 XSI
Safety
Cancellation point
No
Interrupt handler
No
Signal handler
No
Thread
Yes
See also:
drand48(), jrand48(), lcong48(), lrand48(), mrand48(), nrand48(), seed48(), srand48()
418
QNX Neutrino Functions and Macros
June 19, 2012
erf(), erff()
© 2012, QNX Software Systems Limited
Compute the error function of a number
Synopsis:
#include <math.h>
double erf ( double x );
float erff ( float x );
Arguments:
x
The number for which you want to compute the error function.
Library:
libm
Use the -l m option to qcc to link against this library.
Description:
The erf() and erff() functions compute the following:
x
2
π
2
e-t dt
0
If x is large and the result of erf() is subtracted from 1.0, the results aren’t very
accurate; use erfc() instead.
This equality is true: erf (-x) = -erf (x)
Returns:
The value of the error function, or NAN if x is NAN.
If an error occurs, these functions return 0, but this is also a valid mathematical result.
If you want to check for errors, set errno to 0, call the function, and then check errno
again. These functions don’t change errno if no errors occurred.
Classification:
ANSI, POSIX 1003.1
Safety
Cancellation point
No
Interrupt handler
No
Signal handler
No
continued. . .
June 19, 2012
QNX Neutrino Functions and Macros
419
erf(), erff()
© 2012, QNX Software Systems Limited
Safety
Thread
Yes
See also:
erfc()
420
QNX Neutrino Functions and Macros
June 19, 2012
erfc(), erfcf(), erfcl()
© 2012, QNX Software Systems Limited
Complementary error function
Synopsis:
#include <math.h>
double erfc ( double x );
float erfcf ( float x );
long double erfcl( long double x );
Arguments:
x
The number for which you want to compute the complementary error function.
Library:
libm
Use the -l m option to qcc to link against this library.
Description:
The erfc(), erfcf(), and erfcl() functions calculate the complementary error function of
x (i.e. the result of the error function, erf(), subtracted from 1.0). This is useful
because the error function isn’t very accurate when x is large.
The erf() function computes:
x
2
π
2
e-t dt
0
This equality is true: erfc(-x) = 2 - erfc(x)
Returns:
The value of the error function, or NAN if x is NAN. For a correct value that would
cause an underflow, these functions return 0.0.
If an error occurs, these functions return 0, but this is also a valid mathematical result.
If you want to check for errors, set errno to 0, call the function, and then check errno
again. These functions don’t change errno if no errors occurred.
Classification:
ANSI, POSIX 1003.1
June 19, 2012
QNX Neutrino Functions and Macros
421
erfc(), erfcf(), erfcl()
© 2012, QNX Software Systems Limited
Safety
Cancellation point
No
Interrupt handler
No
Signal handler
No
Thread
Yes
See also:
erf()
422
QNX Neutrino Functions and Macros
June 19, 2012
err(), errx()
© 2012, QNX Software Systems Limited
Display a formatted error message, and then exit
Synopsis:
#include <err.h>
void err( int eval,
const char *fmt, ...);
void errx( int eval,
const char *fmt, ...);
Arguments:
eval
The value to use as the exit code of the process.
fmt
NULL, or a printf()-style string used to format the message.
Additional arguments
As required by the format string.
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
The err() and warn() family of functions display a formatted error message on stderr:
• The functions without an x in their names display the string associated with the
current value of errno.
• Those with a v are “varargs” functions.
• Those with err exit instead of returning.
Function
errno string?
Varargs?
Exits?
err()
Yes
No
Yes
errx()
No
No
Yes
verr()
Yes
Yes
Yes
verrx()
No
Yes
Yes
vwarn()
Yes
Yes
No
vwarnx()
No
Yes
No
continued. . .
June 19, 2012
QNX Neutrino Functions and Macros
423
err(), errx()
© 2012, QNX Software Systems Limited
Function
errno string?
Varargs?
Exits?
warn()
Yes
No
No
warnx()
No
No
No
The err() function produces a message that consists of:
• the last component of the program name, followed by a colon and a space
• the formatted message, followed by a colon and a space, if the fmt argument isn’t
NULL
• the string associated with the current value of errno
• a newline character.
The errx() function produces a similar message, except that it doesn’t include the
string associated with errno. The message consists of:
• the last component of the program name, followed by a colon and a space
• the formatted message, if the fmt argument isn’t NULL
• a newline character.
The err() and errx() functions don’t return, but exit with the value of the argument
eval.
Examples:
Display the current errno information string and exit:
if ((p = malloc(size)) == NULL)
err(1, NULL);
if ((fd = open(file_name, O_RDONLY, 0)) == -1)
err(1, "%s", file_name);
Display an error message and exit:
if (tm.tm_hour < START_TIME)
errx(1, "too early, wait until %s", start_time_string);
Classification:
Unix
Safety
Cancellation point
Yes
Interrupt handler
No
continued. . .
424
QNX Neutrino Functions and Macros
June 19, 2012
err(), errx()
© 2012, QNX Software Systems Limited
Safety
Signal handler
Yes
Thread
Yes
See also:
printf(), stderr, strerror(), verr(), verrx(), vwarn(), vwarnx(), warn(), warnx()
June 19, 2012
QNX Neutrino Functions and Macros
425
errno
© 2012, QNX Software Systems Limited
Global error variable
Synopsis:
#include <errno.h>
extern int errno;
char * const sys_errlist[];
int sys_nerr;
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
The errno variable is set to certain error values by many functions whenever an error
has occurred.
You can’t assume that the value of errno is valid unless the function that you’ve called
indicates that an error has occurred. The runtime library never resets errno to 0.
The documentation for a function might list special meanings for certain values of
errno, but this doesn’t mean that these are the only values that the function might set.
The errno variable may be implemented as a macro, but you can always examine or
set it as if it were a simple integer variable.
Each thread in a multi-threaded program has its own error value in its thread local
storage. No matter which thread you’re in, you can simply refer to errno — it’s defined
in such a way that it refers to the correct variable for the thread. For more information,
see “Local storage for private data” in the documentation for ThreadCreate().
The following variables are also defined in <errno.h>:
sys_errlist
An array of error messages corresponding to errno.
sys_nerr
The number of entries in the sys_errlist array.
The values for errno include at least the following values:
426
QNX Neutrino Functions and Macros
June 19, 2012
errno
© 2012, QNX Software Systems Limited
Value
Meaning
E2BIG
Argument list is too long
EACCES
Permission denied
EADDRINUSE
Address is already in use
EADDRNOTAVAIL
Can’t assign requested address
EADV
Advertise error
EAFNOSUPPORT
Address family isn’t supported by protocol family
EAGAIN
Resource is temporarily unavailable; try again
EALREADY
Operation is already in progress (see “Changes to
EALREADY,” below)
EBADE
Invalid exchange
EBADF
Bad file descriptor
EBADFD
FD is invalid for this operation
EBADFSYS
Corrupted filesystem detected
EBADMSG
Bad message (1003.1b-1993)
EBADR
Invalid request descriptor
EBADRPC
RPC struct is bad
EBADRQC
Invalid request code
EBADSLT
Invalid slot
EBFONT
Bad font-file format
EBUSY
Device or resource is busy
ECANCELED
Operation canceled (1003.1b-1993)
ECHILD
No child processes
ECHRNG
Channel number is out of range
ECOMM
Communication error occurred on send
ECONNABORTED
Software caused connection to abort
ECONNREFUSED
Connection refused
ECONNRESET
Connection reset by peer
ECTRLTERM
Remap to the controlling terminal
EDEADLK
Resource deadlock avoided
continued. . .
June 19, 2012
QNX Neutrino Functions and Macros
427
errno
© 2012, QNX Software Systems Limited
Value
Meaning
EDEADLOCK
File locking deadlock
EDESTADDRREQ
Destination address is required
EDOM
Math argument is out of domain for the function
EDQUOT
Disk quota exceeded
EENDIAN
Endian not supported
EEXIST
File exists
EFAULT
Bad address
EFPOS
File positioning error
EFBIG
File is too large
EHOSTDOWN
Host is down
EHOSTUNREACH
Unable to communicate with remote node
EIDRM
Identifier removed
EILSEQ
Illegal byte sequence
EINPROGRESS
Operation now in progress
EINTR
Interrupted function call
EINVAL
Invalid argument
EIO
I/O error
EISCONN
Socket is already connected
EISDIR
Is a directory
EL2HLT
Level 2 halted
EL2NSYNC
Level 2 not synchronized
EL3HLT
Level 3 halted
EL3RST
Level 3 reset
ELIBACC
Can’t access shared library
ELIBBAD
Accessing a corrupted shared library
ELIBEXEC
Attempting to exec a shared library
ELIBMAX
Attempting to link in too many libraries
ELIBSCN
The .lib section in a.out is corrupted
ELNRNG
Link number is out of range
continued. . .
428
QNX Neutrino Functions and Macros
June 19, 2012
errno
© 2012, QNX Software Systems Limited
Value
Meaning
ELOOP
Too many levels of symbolic links or prefixes
EMFILE
Too many open files
EMLINK
Too many links
EMORE
More to do, send message again
EMSGSIZE
Inappropriate message buffer length
EMULTIHOP
Multihop attempted
ENAMETOOLONG
Filename is too long
ENETDOWN
Network is down
ENETRESET
Network dropped connection on reset
ENETUNREACH
Network is unreachable
ENFILE
Too many open files in the system
ENOANO
No anode
ENOBUFS
No buffer space available
ENOCSI
No CSI structure available
ENODATA
No data (for no-delay I/O)
ENODEV
No such device
ENOENT
No such file or directory
ENOEXEC
Exec format error
ENOLCK
No locks available
ENOLIC
No license available
ENOLINK
The link has been severed
ENOMEM
Not enough memory
ENOMSG
No message of desired type
ENONDP
Need an NDP (8087...) to run
ENONET
Machine isn’t on the network
ENOPKG
Package isn’t installed
ENOPROTOOPT
Protocol isn’t available
ENOREMOTE
Must be done on local machine
ENOSPC
No space left on device
continued. . .
June 19, 2012
QNX Neutrino Functions and Macros
429
errno
© 2012, QNX Software Systems Limited
Value
Meaning
ENOSR
Out of streams resources
ENOSTR
Device isn’t a stream
ENOSYS
Function isn’t implemented
ENOTBLK
Block device is required
ENOTCONN
Socket isn’t connected
ENOTDIR
Not a directory
ENOTEMPTY
Directory isn’t empty
ENOTSOCK
Socket operation on nonsocket
ENOTSUP
Not supported (1003.1b-1993)
ENOTTY
Inappropriate I/O control operation
ENOTUNIQ
Given name isn’t unique
ENXIO
No such device or address
EOK
No error
EOPNOTSUPP
Operation isn’t supported
EOVERFLOW
Value too large to be stored in data type
EOWNERDEAD
The owner of a lock died while holding it
EPERM
Operation isn’t permitted
EPFNOSUPPORT
Protocol family isn’t supported
EPIPE
Broken pipe
EPROCUNAVAIL
Bad procedure for program
EPROGMISMATCH
Program version wrong
EPROGUNAVAIL
RPC program isn’t available
EPROTO
Protocol error
EPROTONOSUPPORT
Protocol isn’t supported
EPROTOTYPE
Protocol is wrong type for socket
ERANGE
Result is too large
EREMCHG
Remote address changed
EREMOTE
The object is remote
ERESTART
Restartable system call
continued. . .
430
QNX Neutrino Functions and Macros
June 19, 2012
errno
© 2012, QNX Software Systems Limited
Value
Meaning
EROFS
Read-only filesystem
ERPCMISMATCH
RPC version is wrong
ESHUTDOWN
Can’t send after socket shutdown
ESOCKTNOSUPPORT
Socket type isn’t supported
ESPIPE
Illegal seek
ESRCH
No such process
ESRMNT
Server mount error
ESRVRFAULT
The receive side of a message transfer encountered a
memory fault accessing the receive/reply buffer.
ESTALE
Potentially recoverable I/O error
ESTRPIPE
If pipe/FIFO, don’t sleep in stream head
ETIME
Timer expired
ETIMEDOUT
Connection timed out
ETOOMANYREFS
Too many references: can’t splice
ETXTBSY
Text file is busy
EUNATCH
Protocol driver isn’t attached
EUSERS
Too many users (for UFS)
EWOULDBLOCK
Operation would block
EXDEV
Cross-device link
EXFULL
Exchange full
Changes to EALREADY
POSIX requires that the error numbers in <errno.h> have unique values. In order to
satisfy this requirement, we’re changing EALREADY so that it no longer has the same
value as EBUSY.
This change could cause incompatibility problems because code that currently uses
EALREADY has been compiled to use the old value. In order to allow applications to
safely make the transition to the new value, we’ve modified <errno.h> to define a
number of new symbolic values:
June 19, 2012
EALREADY_OLD
The old value (16).
EALREADY_NEW
The new value (237).
QNX Neutrino Functions and Macros
431
errno
© 2012, QNX Software Systems Limited
EALREADY_DYNAMIC
A value that you can configure at runtime. This is a variable in
libc that’s set to either the old or new value, based on a
system-wide configuration parameter.
In QNX Neutrino 6.4.0, EALREADY is defined as EALREADY_OLD, so that programs
by default are compatible with existing binaries. EALREADY will be changed in a
future release to EALREADY_NEW. In order to support a safe transition to the new
value, you should modify your code as follows:
• If your code checks for EALREADY return codes, recode it to be like this:
#if defined(EALREADY_NEW) && defined(EALREADY_OLD)
if (error == EALREADY_NEW || error == EALREADY_OLD) {
// deal with EALREADY error cases
}
#else
if (error == EALREADY) {
// deal with EALREADY error cases
}
#endif
This will ensure that the code handles EALREADY error cases from any API that
returns either the old or new value.
• If your code returns an EALREADY error, modify it to return
EALREADY_DYNAMIC instead. In many cases, you can do this by adding
-DEALREADY=EALREADY_DYNAMIC to the compiler flags.
You can use the -e option to procnto to specify the value of EALREADY_DYNAMIC:
-eo
Use the old value, which is the same as that of EBUSY.
-en
Use the POSIX-compliant value.
Examples:
/*
* The following program makes an illegal call
* to the write() function, then prints the
* value held in errno.
*/
#include <stdio.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
int main( void )
{
int errvalue;
errno = EOK;
write( -1, "hello, world\n",
strlen( "hello, world\n" ) );
errvalue = errno;
printf( "The error generated was %d\n", errvalue );
printf( "That means: %s\n", strerror( errvalue ) );
}
432
QNX Neutrino Functions and Macros
June 19, 2012
errno
© 2012, QNX Software Systems Limited
Classification:
ANSI, POSIX 1003.1
See also:
h_errno, perror(), stderr, strerror(), strerror_r()
June 19, 2012
QNX Neutrino Functions and Macros
433
_etext
© 2012, QNX Software Systems Limited
The end of the text segment
Synopsis:
N/A
Description:
This linker symbol defines the end of the text segment. This variable isn’t defined in
any header file.
Classification:
QNX Neutrino
See also:
brk(), _btext, _edata, _end, sbrk()
434
QNX Neutrino Functions and Macros
June 19, 2012
execl()
© 2012, QNX Software Systems Limited
Execute a file
Synopsis:
#include <process.h>
int execl( const char * path,
const char * arg0,
const char * arg1,
.
.
.
const char * argn,
NULL );
Arguments:
path
The path of the file to execute.
arg0, . . . , argn
Pointers to NULL-terminated character strings. These strings
constitute the argument list available to the new process image.
You must terminate the list with a NULL pointer. The arg0
argument must point to a filename that’s associated with the
process being started.
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
The execl() function replaces the current process image with a new process image
specified by path. The new image is constructed from a regular, executable file called
the new process image file. No return is made because the calling process image is
replaced by the new process image.
When a C-language program is executed as a result of this call, it’s entered as a
C-language function call as follows:
int main (int argc, char *argv[]);
where argc is the argument count and argv is an array of character pointers to the
arguments themselves. In addition, the following variable:
extern char **environ;
is initialized as a pointer to an array of character pointers to the environment strings.
The argv and environ arrays are each terminated by a null pointer. The null pointer
terminating the argv array isn’t counted in argc.
Multithreaded applications shouldn’t use the environ variable to access or modify any
environment variable while any other thread is concurrently modifying any
environment variable. A call to any function dependent on any environment variable is
considered a use of the environ variable to access that environment variable.
June 19, 2012
QNX Neutrino Functions and Macros
435
execl()
© 2012, QNX Software Systems Limited
The arguments specified by a program with one of the exec* functions are passed on to
the new process image in the corresponding main() arguments.
The number of bytes available for the new process’s combined argument and
environment lists is ARG_MAX.
File descriptors open in the calling process image remain open in the new process
image, except for when fcntl()’s FD_CLOEXEC flag is set. For those file descriptors
that remain open, all attributes of the open file description, including file locks remain
unchanged. If a file descriptor is closed for this reason, file locks are removed as
described by close() while locks not affected by close() aren’t changed.
Directory streams open in the calling process image are closed in the new process
image.
Signals set to SIG_DFL in the calling process are set to the default action in the new
process image. Signals set to SIG_IGN by the calling process images are ignored by
the new process image. Signals set to be caught by the calling process image are set to
the default action in the new process image. After a successful call, alternate signal
stacks aren’t preserved and the SA_ONSTACK flag is cleared for all signals.
After a successful call, any functions previously registered by atexit() are no longer
registered.
If the path is on a filesystem mounted with the ST_NOSUID flag set, the effective user
ID, effective group ID, saved set-user ID and saved set-group ID are unchanged for the
new process. Otherwise, if the set-user ID mode bit is set, the effective user ID of the
new process image is set to the user ID of path. Similarly, if the set-group ID mode bit
is set, the effective group ID of the new process is set to the group ID of path. The real
user ID, real group ID, and supplementary group IDs of the new process remain the
same as those of the calling process. The effective user ID and effective group ID of
the new process image are saved (as the saved set-user ID and the saved set-group ID
used by setuid()).
Any shared memory segments attached to the calling process image aren’t attached to
the new process image. If the calling process had locked any memory, the locks are
released.
The new process also inherits at least the following attributes from the calling process
image:
• process ID
• parent process ID
• process group ID
• session membership
• real user ID
• real group ID
• supplementary group IDs
436
QNX Neutrino Functions and Macros
June 19, 2012
execl()
© 2012, QNX Software Systems Limited
• time left until an alarm clock signal (see alarm())
• current working directory
• root directory
• file mode creation mask (see umask())
• process signal mask (see sigprocmask())
• pending signal (see sigpending())
• tms_utime, tms_stime, tms_cutime, and tms_cstime (see times())
• resource limits
• controlling terminal
• interval timers.
If you call this function from a process with more than one thread, all of the threads
are terminated and the new executable image is loaded and executed. No destructor
functions are called.
Upon successful completion, the st_atime field of the file is marked for update. If the
exec* function failed but was able to locate the process image file, whether the
st_atime field is marked for update is unspecified. On success, the process image file
is considered to be opened with open(). The corresponding close() is considered to
occur at a time after this open, but before process termination or successful completion
of a subsequent call to one of the exec* functions.
exec*() summary
Function
Description
POSIX?
execl()
NULL-terminated argument list
Yes
execle()
NULL-terminated argument list, specify the new process
environment
Yes
execlp()
NULL-terminated argument list, search for the new
process in PATH
Yes
execlpe()
NULL-terminated argument list, search for the new
process in PATH, specify the new process environment
No
execv()
NULL-terminated array of arguments
Yes
execve()
NULL-terminated array of arguments, specify the new
process environment
Yes
execvp()
NULL-terminated array of arguments, search for the new
process in PATH
Yes
continued. . .
June 19, 2012
QNX Neutrino Functions and Macros
437
execl()
© 2012, QNX Software Systems Limited
Function
Description
POSIX?
execvpe()
NULL-terminated array of arguments, search for the new
process in PATH, specify the new process environment
No
Returns:
When execl() is successful, it doesn’t return; otherwise, it returns -1 (errno is set).
Errors:
E2BIG
The argument list and the environment is larger than the system limit
of ARG_MAX bytes.
EACCES
The calling process doesn’t have permission to search a directory
listed in path, or it doesn’t have permission to execute path, or path’s
filesystem was mounted with the ST_NOEXEC flag.
ELOOP
Too many levels of symbolic links or prefixes.
ENAMETOOLONG
The length of path or an element of the PATH environment variable
exceeds PATH_MAX.
ENOENT
One or more components of the pathname don’t exist, or the path
argument points to an empty string.
ENOEXEC
The new process image file has the correct access permissions, but
isn’t in the proper format.
ENOMEM
There’s insufficient memory available to create the new process.
ENOTDIR
A component of path isn’t a directory.
ETXTBSY
The text file that you’re trying to execute is busy (e.g. it might be open
for writing).
Examples:
Replace the current process with myprog as if a user had typed:
myprog ARG1 ARG2
at the shell:
#include <stddef.h>
#include <process.h>
execl( "myprog", "myprog", "ARG1", "ARG2", NULL );
In this example, myprog will be found if it exists in the current working directory.
438
QNX Neutrino Functions and Macros
June 19, 2012
execl()
© 2012, QNX Software Systems Limited
Classification:
POSIX 1003.1
Safety
Cancellation point
No
Interrupt handler
No
Signal handler
No
Thread
Yes
See also:
abort(), atexit(), errno, execle(), execlp(), execlpe(), execv(), execve(), execvp(),
execvpe(), _exit(), exit(), getenv(), main(), putenv(), spawn(), spawnl(), spawnle(),
spawnlp(), spawnlpe(), spawnp(), spawnv(), spawnve(), spawnvp(), spawnvpe(),
system()
Processes and Threads chapter of Getting Started with QNX Neutrino
June 19, 2012
QNX Neutrino Functions and Macros
439
execle()
© 2012, QNX Software Systems Limited
Execute a file
Synopsis:
#include <process.h>
int execle( const char * path,
const char * arg0,
const char * arg1,
.
.
.
const char * argn,
NULL,
const char * envp[] );
Arguments:
path
The path of the file to execute.
arg0, . . . , argn
Pointers to NULL-terminated character strings. These strings
constitute the argument list available to the new process image.
You must terminate the list with a NULL pointer. The arg0
argument must point to a filename that’s associated with the
process being started.
envp
An array of character pointers to NULL-terminated strings. These
strings constitute the environment for the new process image.
Terminate the envp array with a NULL pointer.
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
The execle() function replaces the current process image with a new process image
specified by path. The new image is constructed from a regular, executable file called
the new process image file. No return is made because the calling process image is
replaced by the new process image.
When a C-language program is executed as a result of this call, it’s entered as a
C-language function call as follows:
int main (int argc, char *argv[]);
where argc is the argument count and argv is an array of character pointers to the
arguments themselves. In addition, the following variable:
extern char **environ;
is initialized as a pointer to an array of character pointers to the environment strings.
The argv and environ arrays are each terminated by a null pointer. The null pointer
terminating the argv array isn’t counted in argc.
440
QNX Neutrino Functions and Macros
June 19, 2012
© 2012, QNX Software Systems Limited
execle()
Multithreaded applications shouldn’t use the environ variable to access or modify any
environment variable while any other thread is concurrently modifying any
environment variable. A call to any function dependent on any environment variable is
considered a use of the environ variable to access that environment variable.
The arguments specified by a program with one of the exec functions are passed on to
the new process image in the corresponding main() arguments.
The number of bytes available for the new process’s combined argument and
environment lists is ARG_MAX.
File descriptors open in the calling process image remain open in the new process
image, except for when fcntl()’s FD_CLOEXEC flag is set. For those file descriptors
that remain open, all attributes of the open file description, including file locks remain
unchanged. If a file descriptor is closed for this reason, file locks are removed as
described by close() while locks not affected by close() aren’t changed.
Directory streams open in the calling process image are closed in the new process
image.
Signals set to SIG_DFL in the calling process are set to the default action in the new
process image. Signals set to SIG_IGN by the calling process images are ignored by
the new process image. Signals set to be caught by the calling process image are set to
the default action in the new process image. After a successful call, alternate signal
stacks aren’t preserved and the SA_ONSTACK flag is cleared for all signals.
After a successful call, any functions previously registered by atexit() are no longer
registered.
If the path is on a filesystem mounted with the ST_NOSUID flag set, the effective user
ID, effective group ID, saved set-user ID and saved set-group ID are unchanged for the
new process. Otherwise, if the set-user ID mode bit is set, the effective user ID of the
new process image is set to the user ID of path. Similarly, if the set-group ID mode bit
is set, the effective group ID of the new process is set to the group ID of path. The real
user ID, real group ID, and supplementary group IDs of the new process remain the
same as those of the calling process. The effective user ID and effective group ID of
the new process image are saved (as the saved set-user ID and the saved set-group ID
used by setuid()).
Any shared memory segments attached to the calling process image aren’t attached to
the new process image. If the calling process had locked any memory, the locks are
released.
The new process also inherits at least the following attributes from the calling process
image:
• process ID
• parent process ID
• process group ID
• session membership
June 19, 2012
QNX Neutrino Functions and Macros
441
execle()
© 2012, QNX Software Systems Limited
• real user ID
• real group ID
• supplementary group IDs
• time left until an alarm clock signal (see alarm())
• current working directory
• root directory
• file mode creation mask (see umask())
• process signal mask (see sigprocmask())
• pending signal (see sigpending())
• tms_utime, tms_stime, tms_cutime, and tms_cstime (see times())
• resource limits
• controlling terminal
• interval timers.
A call to this function from a process with more than one thread results in all threads
being terminated and the new executable image being loaded and executed. No
destructor functions are called.
Upon successful completion, the st_atime field of the file is marked for update. If the
exec* function failed but was able to locate the process image file, whether the
st_atime field is marked for update is unspecified. On success, the process image file
is considered to be opened with open(). The corresponding close() is considered to
occur at a time after this open, but before process termination or successful completion
of a subsequent call to one of the exec* functions.
exec*() summary
Function
Description
POSIX?
execl()
NULL-terminated argument list
Yes
execle()
NULL-terminated argument list, specify the new process’s
environment
Yes
execlp()
NULL-terminated argument list, search for the new
process in PATH
Yes
execlpe()
NULL-terminated argument list, search for the new
process in PATH, specify the new process’s environment
No
execv()
NULL-terminated array of arguments
Yes
continued. . .
442
QNX Neutrino Functions and Macros
June 19, 2012
execle()
© 2012, QNX Software Systems Limited
Function
Description
POSIX?
execve()
NULL-terminated array of arguments, specify the new
process’s environment
Yes
execvp()
NULL-terminated array of arguments, search for the new
process in PATH
Yes
execvpe()
NULL-terminated array of arguments, search for the new
process in PATH, specify the new process’s environment
No
Returns:
When execle() is successful, it doesn’t return; otherwise, it returns -1 and sets errno.
Errors:
E2BIG
The argument list and the environment is larger than the system limit
of ARG_MAX bytes.
EACCES
The calling process doesn’t have permission to search a directory
listed in path, or it doesn’t have permission to execute path, or path’s
filesystem was mounted with the ST_NOEXEC flag.
ELOOP
Too many levels of symbolic links or prefixes.
ENAMETOOLONG
The length of path or an element of the PATH environment variable
exceeds PATH_MAX.
ENOENT
One or more components of the pathname don’t exist, or the path
argument points to an empty string.
ENOEXEC
The new process’s image file has the correct access permissions, but
isn’t in the proper format.
ENOMEM
There’s insufficient memory available to create the new process.
ENOTDIR
A component of path isn’t a directory.
ETXTBSY
The text file that you’re trying to execute is busy (e.g. it might be open
for writing).
Examples:
Replace the current process with myprog as if a user had typed:
myprog ARG1 ARG2
at the shell:
June 19, 2012
QNX Neutrino Functions and Macros
443
execle()
© 2012, QNX Software Systems Limited
#include <stddef.h>
#include <process.h>
char* env_list[] = { "SOURCE=MYDATA",
"TARGET=OUTPUT",
"lines=65",
NULL
};
execle( "myprog",
"myprog", "ARG1", "ARG2", NULL,
env_list );
In this example, myprog will be found if it exists in the current working directory. The
environment for the invoked program consists of the three environment variables
SOURCE, TARGET and lines.
Classification:
POSIX 1003.1
Safety
Cancellation point
No
Interrupt handler
No
Signal handler
Yes
Thread
Yes
See also:
abort(), atexit(), errno, execl(), execlp(), execlpe(), execv(), execve(), execvp(),
execvpe(), _exit(), exit(), getenv(), main(), putenv(), spawn(), spawnl(), spawnle(),
spawnlp(), spawnlpe(), spawnp(), spawnv(), spawnve(), spawnvp(), spawnvpe(),
system()
Processes and Threads chapter of Getting Started with QNX Neutrino
444
QNX Neutrino Functions and Macros
June 19, 2012
execlp()
© 2012, QNX Software Systems Limited
Execute a file
Synopsis:
#include <process.h>
int execlp( const char * file,
const char * arg0,
const char * arg1,
.
.
.
const char * argn,
NULL );
Arguments:
file
Used to construct a pathname that identifies the new process image
file. If the file argument contains a slash character, the file
argument is used as the pathname for the file. Otherwise, the path
prefix for this file is obtained by a search of the directories passed
as the environment variable PATH.
arg0, . . . , argn
Pointers to NULL-terminated character strings. These strings
constitute the argument list available to the new process image.
Terminate the list terminated with a NULL pointer. The arg0
argument must point to a filename that’s associated with the
process.
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
The execlp() function replaces the current process image with a new process image
specified by file. The new image is constructed from a regular, executable file called
the new process image file. No return is made because the calling process image is
replaced by the new process image.
When a C-language program is executed as a result of this call, it’s entered as a
C-language function call as follows:
int main (int argc, char *argv[]);
where argc is the argument count and argv is an array of character pointers to the
arguments themselves. In addition, the following variable:
extern char **environ;
is initialized as a pointer to an array of character pointers to the environment strings.
The argv and environ arrays are each terminated by a null pointer. The null pointer
terminating the argv array isn’t counted in argc.
June 19, 2012
QNX Neutrino Functions and Macros
445
execlp()
© 2012, QNX Software Systems Limited
Multithreaded applications shouldn’t use the environ variable to access or modify any
environment variable while any other thread is concurrently modifying any
environment variable. A call to any function dependent on any environment variable is
considered a use of the environ variable to access that environment variable.
The arguments specified by a program with one of the exec functions are passed on to
the new process image in the corresponding main() arguments.
If the process image file isn’t a valid executable object, the contents of the file are
passed as standard input to a command interpreter conforming to the system()
function. In this case, the command interpreter becomes the new process image.
The number of bytes available for the new process’s combined argument and
environment lists is ARG_MAX.
File descriptors open in the calling process image remain open in the new process
image, except for when fcntl()’s FD_CLOEXEC flag is set. For those file descriptors
that remain open, all attributes of the open file description, including file locks remain
unchanged. If a file descriptor is closed for this reason, file locks are removed as
described by close() while locks not affected by close() aren’t changed.
Directory streams open in the calling process image are closed in the new process
image.
Signals set to SIG_DFL in the calling process are set to the default action in the new
process image. Signals set to SIG_IGN by the calling process images are ignored by
the new process image. Signals set to be caught by the calling process image are set to
the default action in the new process image. After a successful call, alternate signal
stacks aren’t preserved and the SA_ONSTACK flag is cleared for all signals.
After a successful call, any functions previously registered by atexit() are no longer
registered.
If the file is on a filesystem mounted with the ST_NOSUID flag set, the effective user
ID, effective group ID, saved set-user ID and saved set-group ID are unchanged for the
new process. Otherwise, if the set-user ID mode bit is set, the effective user ID of the
new process image is set to the user ID of file. Similarly, if the set-group ID mode bit
is set, the effective group ID of the new process is set to the group ID of file. The real
user ID, real group ID, and supplementary group IDs of the new process remain the
same as those of the calling process. The effective user ID and effective group ID of
the new process image are saved (as the saved set-user ID and the saved set-group ID
used by setuid()).
Any shared memory segments attached to the calling process image aren’t attached to
the new process image. If the calling process had locked any memory, the locks are
released.
The new process also inherits at least the following attributes from the calling process
image:
• process ID
• parent process ID
446
QNX Neutrino Functions and Macros
June 19, 2012
execlp()
© 2012, QNX Software Systems Limited
• process group ID
• session membership
• real user ID
• real group ID
• supplementary group IDs
• time left until an alarm clock signal (see alarm())
• current working directory
• root directory
• file mode creation mask (see umask())
• process signal mask (see sigprocmask())
• pending signal (see sigpending())
• tms_utime, tms_stime, tms_cutime, and tms_cstime (see times())
• resource limits
• controlling terminal
• interval timers.
A call to this function from a process with more than one thread results in all threads
being terminated and the new executable image being loaded and executed. No
destructor functions are called.
Upon successful completion, the st_atime field of the file is marked for update. If the
exec* failed but was able to locate the process image file, whether the st_atime field is
marked for update is unspecified. On success, the process image file is considered to
be opened with open(). The corresponding close() is considered to occur at a time
after this open, but before process termination or successful completion of a
subsequent call to one of the exec* functions.
exec*() summary
Function
Description
POSIX?
execl()
NULL-terminated argument list
Yes
execle()
NULL-terminated argument list, specify the new process’s
environment
Yes
execlp()
NULL-terminated argument list, search for the new
process in PATH
Yes
continued. . .
June 19, 2012
QNX Neutrino Functions and Macros
447
execlp()
© 2012, QNX Software Systems Limited
Function
Description
POSIX?
execlpe()
NULL-terminated argument list, search for the new
process in PATH, specify the new process’s environment
No
execv()
NULL-terminated array of arguments
Yes
execve()
NULL-terminated array of arguments, specify the new
process’s environment
Yes
execvp()
NULL-terminated array of arguments, search for the new
process in PATH
Yes
execvpe()
NULL-terminated array of arguments, search for the new
process in PATH, specify the new process’s environment
No
Returns:
When execlp() is successful, it doesn’t return; otherwise, it returns -1 and sets errno.
Errors:
E2BIG
The argument list and the environment is larger than the system limit
of ARG_MAX bytes.
EACCES
The calling process doesn’t have permission to search a directory listed
in file, or it doesn’t have permission to execute file, or file’s filesystem
was mounted with the ST_NOEXEC flag.
ELOOP
Too many levels of symbolic links or prefixes.
ENAMETOOLONG
The length of file or an element of the PATH environment variable
exceeds PATH_MAX.
ENOENT
One or more components of the pathname don’t exist, or the file
argument points to an empty string.
ENOMEM
There’s insufficient memory available to create the new process.
ENOTDIR
A component of file isn’t a directory.
ETXTBSY
The text file that you’re trying to execute is busy (e.g. it might be open
for writing).
Classification:
POSIX 1003.1
448
QNX Neutrino Functions and Macros
June 19, 2012
execlp()
© 2012, QNX Software Systems Limited
Safety
Cancellation point
No
Interrupt handler
No
Signal handler
No
Thread
Yes
See also:
abort(), atexit(), errno, execl(), execle(), execlpe(), execv(), execve(), execvp(),
execvpe() _exit(), exit(), getenv(), main(), putenv(), spawn(), spawnl(), spawnle(),
spawnlp(), spawnlpe(), spawnp(), spawnv(), spawnve(), spawnvp(), spawnvpe(),
system()
Processes and Threads chapter of Getting Started with QNX Neutrino
June 19, 2012
QNX Neutrino Functions and Macros
449
execlpe()
© 2012, QNX Software Systems Limited
Execute a file
Synopsis:
#include <process.h>
int execlpe( const char * file,
const char * arg0,
const char * arg1,
.
.
.
const char * argn,
NULL,
const char * envp[] );
Arguments:
file
Used to construct a pathname that identifies the new process image
file. If the file argument contains a slash character, the file argument is
used as the pathname for the file. Otherwise, the path prefix for this
file is obtained by a search of the directories passed as the
environment variable PATH.
arg0. . . argn
Pointers to NULL-terminated character strings. These strings
constitute the argument list available to the new process image.
Terminate the list terminated with a NULL pointer. The arg0
argument must point to a filename that’s associated with the process.
envp
An array of character pointers to NULL-terminated strings. These
strings constitute the environment for the new process image.
Terminate the envp array with a NULL pointer.
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
See execl() for further information on the exec*() family of functions.
The execlpe() function replaces the current process image with a new process image
specified by file. The new image is constructed from a regular, executable file called
the new process image file. No return is made because the calling process image is
replaced by the new process image.
450
QNX Neutrino Functions and Macros
June 19, 2012
execlpe()
© 2012, QNX Software Systems Limited
If the new child process is a shell script, the first line must start with #!, followed by
the path of the program to run to interpret the script, optionally followed by one
argument. The script must also be marked as executable. For more information, see
“The first line” in the Writing Shell Scripts chapter of the Neutrino User’s Guide.
The execlpe() function uses the paths listed in the PATH environment variable to
locate the program to be loaded, provided that the following conditions are met:
• The argument file identifies the name of program to be loaded.
• If no path character (/) is included in the name, an attempt is made to load the
program from one of the paths in the PATH environment variable.
• If PATH isn’t defined, the current working directory is used.
• If a path character (/) is included in the name, the program is loaded from the path
specified in file.
The process is started with the arguments specified in the NULL-terminated arguments
arg1. . . argn. arg0 should point to a filename associated with the program being
loaded. Only arg0 is required, arg1. . . argn are optional.
The new process’s environment is specified in envp, a NULL-terminated array of
NULL-terminated strings. envp cannot be NULL, but envp[0] can be a NULL pointer if
no environment strings are passed.
Each pointer in envp points to a string in the form:
variable=value
that is used to define an environment variable.
The environment is the collection of environment variables whose values have been
defined with the export shell command, the env utility, or by the successful
execution of the putenv() or setenv() functions.
A program may read these values with the getenv() function.
An error is detected when the program cannot be found.
If the file is on a filesystem mounted with the ST_NOSUID flag set, the effective user
ID, effective group ID, saved set-user ID and saved set-group ID are unchanged for the
new process. Otherwise, if the set-user ID mode bit is set, the effective user ID of the
new process is set to the owner ID of file. Similarly, if the set-group ID mode bit is set,
the effective group ID of the new process is set to the group ID of file. The real user
ID, real group ID and supplementary group IDs of the new process remain the same as
those of the calling process. The effective user ID and effective group ID of the new
process are saved as the saved set-user ID and the saved set-group ID used by setuid().
If the calling process had locked any memory, the locks are released.
June 19, 2012
QNX Neutrino Functions and Macros
451
execlpe()
© 2012, QNX Software Systems Limited
exec*() summary
Function
Description
POSIX?
execl()
NULL-terminated argument list
Yes
execle()
NULL-terminated argument list, specify the new process’s
Yes
environment
execlp()
NULL-terminated argument list, search for the new
process in PATH
Yes
execlpe()
NULL-terminated argument list, search for the new
process in PATH, specify the new process’s environment
No
execv()
NULL-terminated array of arguments
Yes
execve()
NULL-terminated array of arguments, specify the new
Yes
process’s environment
execvp()
NULL-terminated array of arguments, search for the new
Yes
process in PATH
execvpe()
NULL-terminated array of arguments, search for the new
process in PATH, specify the new process’s environment
No
Returns:
When execlpe() is successful, it doesn’t return; otherwise, it returns -1 and sets errno.
Errors:
E2BIG
The argument list and the environment is larger than the system limit
of ARG_MAX bytes.
EACCES
The calling process doesn’t have permission to search a directory listed
in file, or it doesn’t have permission to execute file, or file’s filesystem
was mounted with the ST_NOEXEC flag.
ELOOP
Too many levels of symbolic links or prefixes.
ENAMETOOLONG
The length of file or an element of the PATH environment variable
exceeds PATH_MAX.
452
ENOENT
One or more components of the pathname don’t exist, or the file
argument points to an empty string.
ENOMEM
There’s insufficient memory available to create the new process.
ENOTDIR
A component of file isn’t a directory.
ETXTBSY
The text file that you’re trying to execute is busy (e.g. it might be open
for writing).
QNX Neutrino Functions and Macros
June 19, 2012
execlpe()
© 2012, QNX Software Systems Limited
Classification:
QNX 4
Safety
Cancellation point
No
Interrupt handler
No
Signal handler
No
Thread
Yes
See also:
abort(), atexit(), errno, execl(), execle(), execlp(), execv(), execve(), execvp(),
execvpe(), _exit(), exit(), getenv(), main(), putenv(), spawn(), spawnl(), spawnle(),
spawnlp(), spawnlpe(), spawnp(), spawnv(), spawnve(), spawnvp(), spawnvpe(),
system()
Processes and Threads chapter of Getting Started with QNX Neutrino
June 19, 2012
QNX Neutrino Functions and Macros
453
execv()
© 2012, QNX Software Systems Limited
Execute a file
Synopsis:
#include <process.h>
int execv( const char * path,
char * const argv[] );
Arguments:
path
A path name that identifies the new process image file.
argv
An array of character pointers to NULL-terminated strings. Your application
must ensure that the last member of this array is a NULL pointer. These
strings constitute the argument list available to the new process image. The
value in argv[0] must point to a filename that’s associated with the process
being started.
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
The execv() function replaces the current process image with a new process image
specified by path. The new image is constructed from a regular, executable file called
the new process image file. No return is made because the calling process image is
replaced by the new process image.
When a C-language program is executed as a result of this call, it’s entered as a
C-language function call as follows:
int main (int argc, char *argv[]);
where argc is the argument count and argv is an array of character pointers to the
arguments themselves. In addition, the following variable:
extern char **environ;
is initialized as a pointer to an array of character pointers to the environment strings.
The argv and environ arrays are each terminated by a null pointer. The null pointer
terminating the argv array isn’t counted in argc.
Multithreaded applications shouldn’t use the environ variable to access or modify any
environment variable while any other thread is concurrently modifying any
environment variable. A call to any function dependent on any environment variable is
considered a use of the environ variable to access that environment variable.
The arguments specified by a program with one of the exec functions are passed on to
the new process image in the corresponding main() arguments.
454
QNX Neutrino Functions and Macros
June 19, 2012
© 2012, QNX Software Systems Limited
execv()
The environment for the new process image is taken from the external variable environ
in the calling process.
The number of bytes available for the new process’s combined argument and
environment lists is ARG_MAX.
File descriptors open in the calling process image remain open in the new process
image, except for when fcntl()’s FD_CLOEXEC flag is set. For those file descriptors
that remain open, all attributes of the open file description, including file locks remain
unchanged. If a file descriptor is closed for this reason, file locks are removed as
described by close() while locks not affected by close() aren’t changed.
Directory streams open in the calling process image are closed in the new process
image.
Signals set to SIG_DFL in the calling process are set to the default action in the new
process image. Signals set to SIG_IGN by the calling process images are ignored by
the new process image. Signals set to be caught by the calling process image are set to
the default action in the new process image. After a successful call, alternate signal
stacks aren’t preserved and the SA_ONSTACK flag is cleared for all signals.
After a successful call, any functions previously registered by atexit() are no longer
registered.
If the path is on a filesystem mounted with the ST_NOSUID flag set, the effective user
ID, effective group ID, saved set-user ID and saved set-group ID are unchanged for the
new process. Otherwise, if the set-user ID mode bit is set, the effective user ID of the
new process image is set to the user ID of path. Similarly, if the set-group ID mode bit
is set, the effective group ID of the new process is set to the group ID of path. The real
user ID, real group ID, and supplementary group IDs of the new process remain the
same as those of the calling process. The effective user ID and effective group ID of
the new process image are saved (as the saved set-user ID and the saved set-group ID
used by setuid()).
Any shared memory segments attached to the calling process image aren’t attached to
the new process image. If the calling process had locked any memory, the locks are
released.
The new process also inherits at least the following attributes from the calling process
image:
• process ID
• parent process ID
• process group ID
• session membership
• real user ID
• real group ID
• supplementary group IDs
June 19, 2012
QNX Neutrino Functions and Macros
455
execv()
© 2012, QNX Software Systems Limited
• time left until an alarm clock signal (see alarm())
• current working directory
• root directory
• file mode creation mask (see umask())
• process signal mask (see sigprocmask())
• pending signal (see sigpending())
• tms_utime, tms_stime, tms_cutime, and tms_cstime (see times())
• resource limits
• controlling terminal
• interval timers.
A call to this function from a process with more than one thread results in all threads
being terminated and the new executable image being loaded and executed. No
destructor functions are called.
Upon successful completion, the st_atime field of the file is marked for update. If the
exec* failed but was able to locate the process image file, whether the st_atime field is
marked for update is unspecified. On success, the process image file is considered to
be opened with open(). The corresponding close() is considered to occur at a time
after this open, but before process termination or successful completion of a
subsequent call to one of the exec* functions.
exec*() summary
Function
Description
POSIX?
execl()
NULL-terminated argument list
Yes
execle()
NULL-terminated argument list, specify the new process’s
environment
Yes
execlp()
NULL-terminated argument list, search for the new
process in PATH
Yes
execlpe()
NULL-terminated argument list, search for the new
process in PATH, specify the new process’s environment
No
execv()
NULL-terminated array of arguments
Yes
execve()
NULL-terminated array of arguments, specify the new
process’s environment
Yes
execvp()
NULL-terminated array of arguments, search for the new
process in PATH
Yes
continued. . .
456
QNX Neutrino Functions and Macros
June 19, 2012
execv()
© 2012, QNX Software Systems Limited
Function
Description
POSIX?
execvpe()
NULL-terminated array of arguments, search for the new
process in PATH, specify the new process’s environment
No
Returns:
When execv() is successful, it doesn’t return; otherwise, it returns -1 and sets errno.
Errors:
E2BIG
The argument list and the environment is larger than the system limit
of ARG_MAX bytes.
EACCES
The calling process doesn’t have permission to search a directory
listed in path, or it doesn’t have permission to execute path, or path’s
filesystem was mounted with the ST_NOEXEC flag.
ELOOP
Too many levels of symbolic links or prefixes.
ENAMETOOLONG
The length of path or an element of the PATH environment variable
exceeds PATH_MAX.
ENOENT
One or more components of the pathname don’t exist, or the path
argument points to an empty string.
ENOEXEC
The new process’s image file has the correct access permissions, but
isn’t in the proper format.
ENOMEM
There’s insufficient memory available to create the new process.
ENOTDIR
A component of path isn’t a directory.
ETXTBSY
The text file that you’re trying to execute is busy (e.g. it might be open
for writing).
Examples:
#include <stddef.h>
#include <process.h>
char* arg_list[] = { "myprog", "ARG1", "ARG2", NULL };
execv( "myprog", arg_list );
The preceding invokes myprog as if the user entered:
myprog ARG1 ARG2
as a command at the shell. The program will be found if myprog exists in the current
working directory.
June 19, 2012
QNX Neutrino Functions and Macros
457
execv()
© 2012, QNX Software Systems Limited
Classification:
POSIX 1003.1
Safety
Cancellation point
No
Interrupt handler
No
Signal handler
No
Thread
Yes
See also:
abort(), atexit(), errno, execl(), execle(), execlp(), execlpe(), execve(), execvp(),
execvpe(), _exit(), exit(), getenv(), main(), putenv(), spawn(), spawnl(), spawnle(),
spawnlp(), spawnlpe(), spawnp(), spawnv(), spawnve(), spawnvp(), spawnvpe(),
system()
Processes and Threads chapter of Getting Started with QNX Neutrino
458
QNX Neutrino Functions and Macros
June 19, 2012
execve()
© 2012, QNX Software Systems Limited
Execute a file
Synopsis:
#include <process.h>
int execve( const char * path,
char * const argv[],
char * const envp[] );
Arguments:
path
A path name that identifies the new process image file.
argv
An array of character pointers to NULL-terminated strings. Your application
must ensure that the last member of this array is a NULL pointer. These
strings constitute the argument list available to the new process image. The
value in argv[0] must point to a filename that’s associated with the process
being started.
envp
An array of character pointers to NULL-terminated strings. These strings
constitute the environment for the new process image. Terminate the envp
array with a NULL pointer.
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
The execve() function replaces the current process image with a new process image
specified by path. The new image is constructed from a regular, executable file called
the new process image file. No return is made because the calling process image is
replaced by the new process image.
When a C-language program is executed as a result of this call, it’s entered as a
C-language function call as follows:
int main (int argc, char *argv[]);
where argc is the argument count and argv is an array of character pointers to the
arguments themselves. In addition, the following variable:
extern char **environ;
is initialized as a pointer to an array of character pointers to the environment strings.
The argv and environ arrays are each terminated by a null pointer. The null pointer
terminating the argv array isn’t counted in argc.
Multithreaded applications shouldn’t use the environ variable to access or modify any
environment variable while any other thread is concurrently modifying any
June 19, 2012
QNX Neutrino Functions and Macros
459
execve()
© 2012, QNX Software Systems Limited
environment variable. A call to any function dependent on any environment variable is
considered a use of the environ variable to access that environment variable.
The arguments specified by a program with one of the exec functions are passed on to
the new process image in the corresponding main() arguments.
The number of bytes available for the new process’s combined argument and
environment lists is ARG_MAX.
File descriptors open in the calling process image remain open in the new process
image, except for when fcntl()’s FD_CLOEXEC flag is set. For those file descriptors
that remain open, all attributes of the open file description, including file locks remain
unchanged. If a file descriptor is closed for this reason, file locks are removed as
described by close() while locks not affected by close() aren’t changed.
Directory streams open in the calling process image are closed in the new process
image.
Signals set to SIG_DFL in the calling process are set to the default action in the new
process image. Signals set to SIG_IGN by the calling process images are ignored by
the new process image. Signals set to be caught by the calling process image are set to
the default action in the new process image. After a successful call, alternate signal
stacks aren’t preserved and the SA_ONSTACK flag is cleared for all signals.
After a successful call, any functions previously registered by atexit() are no longer
registered.
If the path is on a filesystem mounted with the ST_NOSUID flag set, the effective user
ID, effective group ID, saved set-user ID and saved set-group ID are unchanged for the
new process. Otherwise, if the set-user ID mode bit is set, the effective user ID of the
new process image is set to the user ID of path. Similarly, if the set-group ID mode bit
is set, the effective group ID of the new process is set to the group ID of path. The real
user ID, real group ID, and supplementary group IDs of the new process remain the
same as those of the calling process. The effective user ID and effective group ID of
the new process image are saved (as the saved set-user ID and the saved set-group ID
used by setuid()).
Any shared memory segments attached to the calling process image aren’t attached to
the new process image. If the calling process had locked any memory, the locks are
released.
The new process also inherits at least the following attributes from the calling process
image:
• process ID
• parent process ID
• process group ID
• session membership
• real user ID
460
QNX Neutrino Functions and Macros
June 19, 2012
execve()
© 2012, QNX Software Systems Limited
• real group ID
• supplementary group IDs
• time left until an alarm clock signal (see alarm())
• current working directory
• root directory
• file mode creation mask (see umask())
• process signal mask (see sigprocmask())
• pending signal (see sigpending())
• tms_utime, tms_stime, tms_cutime, and tms_cstime (see times())
• resource limits
• controlling terminal
• interval timers.
A call to this function from a process with more than one thread results in all threads
being terminated and the new executable image being loaded and executed. No
destructor functions are called.
Upon successful completion, the st_atime field of the file is marked for update. If the
exec* failed but was able to locate the process image file, whether the st_atime field is
marked for update is unspecified. On success, the process image file is considered to
be opened with open(). The corresponding close() is considered to occur at a time
after this open, but before process termination or successful completion of a
subsequent call to one of the exec* functions.
exec*() summary
Function
Description
POSIX?
execl()
NULL-terminated argument list
Yes
execle()
NULL-terminated argument list, specify the new process’s
environment
Yes
execlp()
NULL-terminated argument list, search for the new
process in PATH
Yes
execlpe()
NULL-terminated argument list, search for the new
process in PATH, specify the new process’s environment
No
execv()
NULL-terminated array of arguments
Yes
continued. . .
June 19, 2012
QNX Neutrino Functions and Macros
461
execve()
© 2012, QNX Software Systems Limited
Function
Description
POSIX?
execve()
NULL-terminated array of arguments, specify the new
process’s environment
Yes
execvp()
NULL-terminated array of arguments, search for the new
process in PATH
Yes
execvpe()
NULL-terminated array of arguments, search for the new
process in PATH, specify the new process’s environment
No
Returns:
When execve() is successful, it doesn’t return; otherwise, it returns -1 and sets errno.
Errors:
E2BIG
The argument list and the environment is larger than the system limit
of ARG_MAX bytes.
EACCES
The calling process doesn’t have permission to search a directory
listed in path, or it doesn’t have permission to execute path, or path’s
filesystem was mounted with the ST_NOEXEC flag.
ELOOP
Too many levels of symbolic links or prefixes.
ENAMETOOLONG
The length of path or an element of the PATH environment variable
exceeds PATH_MAX.
ENOENT
One or more components of the pathname don’t exist, or the path
argument points to an empty string.
ENOEXEC
The new process’s image file has the correct access permissions, but
isn’t in the proper format.
ENOMEM
There’s insufficient memory available to create the new process.
ENOTDIR
A component of path isn’t a directory.
ETXTBSY
The text file that you’re trying to execute is busy (e.g. it might be open
for writing).
Classification:
POSIX 1003.1
462
QNX Neutrino Functions and Macros
June 19, 2012
execve()
© 2012, QNX Software Systems Limited
Safety
Cancellation point
No
Interrupt handler
No
Signal handler
Yes
Thread
Yes
See also:
abort(), atexit(), errno, execl(), execle(), execlp(), execlpe(), execv(), execvp(),
execvpe(), _exit(), exit(), getenv(), main(), putenv(), spawn(), spawnl(), spawnle(),
spawnlp(), spawnlpe(), spawnp(), spawnv(), spawnve(), spawnvp(), spawnvpe(),
system()
Processes and Threads chapter of Getting Started with QNX Neutrino
June 19, 2012
QNX Neutrino Functions and Macros
463
execvp()
© 2012, QNX Software Systems Limited
Execute a file
Synopsis:
#include <process.h>
int execvp( const char * file,
char * const argv[] );
Arguments:
file
Used to construct a pathname that identifies the new process image file. If the
file argument contains a slash character, the file argument is used as the
pathname for the file. Otherwise, the path prefix for this file is obtained by a
search of the directories passed as the environment variable PATH.
argv
An array of character pointers to NULL-terminated strings. Your application
must ensure that the last member of this array is a NULL pointer. These
strings constitute the argument list available to the new process image. The
value in argv[0] must point to a filename that’s associated with the process
being started.
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
The execvp() function replaces the current process image with a new process image
specified by file. The new image is constructed from a regular, executable file called
the new process image file. No return is made because the calling process image is
replaced by the new process image.
When a C-language program is executed as a result of this call, it’s entered as a
C-language function call as follows:
int main (int argc, char *argv[]);
where argc is the argument count and argv is an array of character pointers to the
arguments themselves. In addition, the following variable:
extern char **environ;
is initialized as a pointer to an array of character pointers to the environment strings.
The argv and environ arrays are each terminated by a null pointer. The null pointer
terminating the argv array isn’t counted in argc.
Multithreaded applications shouldn’t use the environ variable to access or modify any
environment variable while any other thread is concurrently modifying any
environment variable. A call to any function dependent on any environment variable is
considered a use of the environ variable to access that environment variable.
464
QNX Neutrino Functions and Macros
June 19, 2012
© 2012, QNX Software Systems Limited
execvp()
The arguments specified by a program with one of the exec functions are passed on to
the new process image in the corresponding main() arguments.
If the process image file isn’t a valid executable object, the contents of the file are
passed as standard input to a command interpreter conforming to the system()
function. In this case, the command interpreter becomes the new process image.
The environment for the new process image is taken from the external variable environ
in the calling process.
The number of bytes available for the new process’s combined argument and
environment lists is ARG_MAX.
File descriptors open in the calling process image remain open in the new process
image, except for when fcntl()’s FD_CLOEXEC flag is set. For those file descriptors
that remain open, all attributes of the open file description, including file locks remain
unchanged. If a file descriptor is closed for this reason, file locks are removed as
described by close() while locks not affected by close() aren’t changed.
Directory streams open in the calling process image are closed in the new process
image.
Signals set to SIG_DFL in the calling process are set to the default action in the new
process image. Signals set to SIG_IGN by the calling process images are ignored by
the new process image. Signals set to be caught by the calling process image are set to
the default action in the new process image. After a successful call, alternate signal
stacks aren’t preserved and the SA_ONSTACK flag is cleared for all signals.
After a successful call, any functions previously registered by atexit() are no longer
registered.
If the file is on a filesystem mounted with the ST_NOSUID flag set, the effective user
ID, effective group ID, saved set-user ID and saved set-group ID are unchanged for the
new process. Otherwise, if the set-user ID mode bit is set, the effective user ID of the
new process image is set to the user ID of file. Similarly, if the set-group ID mode bit
is set, the effective group ID of the new process is set to the group ID of file. The real
user ID, real group ID, and supplementary group IDs of the new process remain the
same as those of the calling process. The effective user ID and effective group ID of
the new process image are saved (as the saved set-user ID and the saved set-group ID
used by setuid()).
Any shared memory segments attached to the calling process image aren’t attached to
the new process image. If the calling process had locked any memory, the locks are
released.
The new process also inherits at least the following attributes from the calling process
image:
• process ID
• parent process ID
• process group ID
June 19, 2012
QNX Neutrino Functions and Macros
465
execvp()
© 2012, QNX Software Systems Limited
• session membership
• real user ID
• real group ID
• supplementary group IDs
• time left until an alarm clock signal (see alarm())
• current working directory
• root directory
• file mode creation mask (see umask())
• process signal mask (see sigprocmask())
• pending signal (see sigpending())
• tms_utime, tms_stime, tms_cutime, and tms_cstime (see times())
• resource limits
• controlling terminal
• interval timers.
A call to this function from a process with more than one thread results in all threads
being terminated and the new executable image being loaded and executed. No
destructor functions are called.
Upon successful completion, the st_atime field of the file is marked for update. If the
exec function failed but was able to locate the process image file, whether the st_atime
field is marked for update is unspecified. On success, the process image file is
considered to be opened with open(). The corresponding close() is considered to occur
at a time after this open, but before process termination or successful completion of a
subsequent call to one of the exec* functions.
exec*() summary
Function
Description
POSIX?
execl()
NULL-terminated argument list
Yes
execle()
NULL-terminated argument list, specify the new process’s
environment
Yes
execlp()
NULL-terminated argument list, search for the new
process in PATH
Yes
execlpe()
NULL-terminated argument list, search for the new
process in PATH, specify the new process’s environment
No
continued. . .
466
QNX Neutrino Functions and Macros
June 19, 2012
execvp()
© 2012, QNX Software Systems Limited
Function
Description
POSIX?
execv()
NULL-terminated array of arguments
Yes
execve()
NULL-terminated array of arguments, specify the new
process’s environment
Yes
execvp()
NULL-terminated array of arguments, search for the new
process in PATH
Yes
execvpe()
NULL-terminated array of arguments, search for the new
process in PATH, specify the new process’s environment
No
Returns:
When execvp() is successful, it doesn’t return; otherwise, it returns -1 and sets errno.
Errors:
E2BIG
The argument list and the environment is larger than the system limit
of ARG_MAX bytes.
EACCES
The calling process doesn’t have permission to search a directory listed
in file, or it doesn’t have permission to execute file, or file’s filesystem
was mounted with the ST_NOEXEC flag.
ELOOP
Too many levels of symbolic links or prefixes.
ENAMETOOLONG
The length of file or an element of the PATH environment variable
exceeds PATH_MAX.
ENOENT
One or more components of the pathname don’t exist, or the file
argument points to an empty string.
ENOMEM
There’s insufficient memory available to create the new process.
ENOTDIR
A component of file isn’t a directory.
ETXTBSY
The text file that you’re trying to execute is busy (e.g. it might be open
for writing).
Classification:
POSIX 1003.1
Safety
Cancellation point
No
continued. . .
June 19, 2012
QNX Neutrino Functions and Macros
467
execvp()
© 2012, QNX Software Systems Limited
Safety
Interrupt handler
No
Signal handler
No
Thread
Yes
See also:
abort(), atexit(), errno, execl(), execle(), execlp(), execlpe(), execv(), execve(),
execvpe(), _exit(), exit(), getenv(), main(), putenv(), spawn(), spawnl(), spawnle(),
spawnlp(), spawnlpe(), spawnp(), spawnv(), spawnve(), spawnvp(), spawnvpe(),
system()
Processes and Threads chapter of Getting Started with QNX Neutrino
468
QNX Neutrino Functions and Macros
June 19, 2012
execvpe()
© 2012, QNX Software Systems Limited
Execute a file
Synopsis:
#include <process.h>
int execvpe( const char * file,
char * const argv[],
char * const envp[] );
Arguments:
file
Used to construct a pathname that identifies the new process image file. If the
file argument contains a slash character, the file argument is used as the
pathname for the file. Otherwise, the path prefix for this file is obtained by a
search of the directories passed as the environment variable PATH.
argv
An array of character pointers to NULL-terminated strings. Your application
must ensure that the last member of this array is a NULL pointer. These
strings constitute the argument list available to the new process image. The
value in argv[0] must point to a filename that’s associated with the process
being started.
envp
An array of character pointers to NULL-terminated strings. These strings
constitute the environment for the new process image. Terminate the envp
array with a NULL pointer.
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
See execl() for further information on the exec*() family of functions.
The execvpe() function replaces the current process image with a new process image
specified by file. The new image is constructed from a regular, executable file called
the new process image file. No return is made because the calling process image is
replaced by the new process image.
If the new child process is a shell script, the first line must start with #!, followed by
the path of the program to run to interpret the script, optionally followed by one
argument. The script must also be marked as executable. For more information, see
“The first line” in the Writing Shell Scripts chapter of the Neutrino User’s Guide.
The execvpe() function uses the paths listed in the PATH environment variable to
locate the program to be loaded, provided that the following conditions are met:
• The file argument identifies the name of program to be loaded.
June 19, 2012
QNX Neutrino Functions and Macros
469
execvpe()
© 2012, QNX Software Systems Limited
• If no path character (/) is included in the name, an attempt is made to load the
program from one of the paths in the PATH environment variable.
• If PATH isn’t defined, the current working directory is used.
• If a path character (/) is included in the name, the program is loaded from the path
specified in file.
The process is started with the argument specified in argv, a NULL-terminated array of
NULL-terminated strings. The argv[0] entry should point to a filename associated with
the program being loaded. The argv argument can’t be NULL but argv[0] can be NULL
if no arguments are required.
The new process’s environment is specified in envp, a NULL-terminated array of
NULL-terminated strings. envp cannot be NULL, but envp[0] can be a NULL pointer if
no environment strings are passed.
Each pointer in envp points to a string in the form:
variable=value
that is used to define an environment variable.
The environment is the collection of environment variables whose values have been
defined with the export shell command, the env utility, or by the successful
execution of the putenv() or setenv() functions.
A program may read these values with the getenv() function.
An error is detected when the program cannot be found.
If the file is on a filesystem mounted with the ST_NOSUID flag set, the effective user
ID, effective group ID, saved set-user ID and saved set-group ID are unchanged for the
new process. Otherwise, if the set-user ID mode bit is set, the effective user ID of the
new process is set to the owner ID of file. Similarly, if the set-group ID mode bit is set,
the effective group ID of the new process is set to the group ID of file. The real user
ID, real group ID and supplementary group IDs of the new process remain the same as
those of the calling process. The effective user ID and effective group ID of the new
process are saved as the saved set-user ID and the saved set-group ID used by setuid().
If the calling process had locked any memory, the locks are released.
exec*() summary
Function
Description
POSIX?
execl()
NULL-terminated argument list
Yes
execle()
NULL-terminated argument list, specify the new process’s
environment
Yes
execlp()
NULL-terminated argument list, search for the new
process in PATH
Yes
continued. . .
470
QNX Neutrino Functions and Macros
June 19, 2012
execvpe()
© 2012, QNX Software Systems Limited
Function
Description
POSIX?
execlpe()
NULL-terminated argument list, search for the new
process in PATH, specify the new process’s environment
No
execv()
NULL-terminated array of arguments
Yes
execve()
NULL-terminated array of arguments, specify the new
process’s environment
Yes
execvp()
NULL-terminated array of arguments, search for the new
process in PATH
Yes
execvpe()
NULL-terminated array of arguments, search for the new
process in PATH, specify the new process’s environment
No
Returns:
When execvpe() is successful, it doesn’t return; otherwise, it returns -1 and sets errno.
Errors:
E2BIG
The argument list and the environment is larger than the system limit
of ARG_MAX bytes.
EACCES
The calling process doesn’t have permission to search a directory listed
in file, or it doesn’t have permission to execute file, or file’s filesystem
was mounted with the ST_NOEXEC flag.
ELOOP
Too many levels of symbolic links or prefixes.
ENAMETOOLONG
The length of file or an element of the PATH environment variable
exceeds PATH_MAX.
ENOENT
One or more components of the pathname don’t exist, or the file
argument points to an empty string.
ENOMEM
There’s insufficient memory available to create the new process.
ENOTDIR
A component of file isn’t a directory.
ETXTBSY
The text file that you’re trying to execute is busy (e.g. it might be open
for writing).
Classification:
QNX 4
June 19, 2012
QNX Neutrino Functions and Macros
471
execvpe()
© 2012, QNX Software Systems Limited
Safety
Cancellation point
No
Interrupt handler
No
Signal handler
Yes
Thread
Yes
See also:
abort(), atexit(), errno, execl(), execle(), execlp(), execlpe(), execv(), execve(),
execvp(), _exit(), exit(), getenv(), main(), putenv(), spawn(), spawnl(), spawnle(),
spawnlp(), spawnlpe(), spawnp(), spawnv(), spawnve(), spawnvp(), spawnvpe(),
system()
Processes and Threads chapter of Getting Started with QNX Neutrino
472
QNX Neutrino Functions and Macros
June 19, 2012
_exit()
© 2012, QNX Software Systems Limited
Terminate the program
Synopsis:
#include <stdlib.h>
void _exit( int status );
Arguments:
status
The exit status to use for the program. The value may be zero,
EXIT_STATUS, EXIT_FAILURE or any other value. Note that only the least
significant bits (i.e. status and 0377) may be available to a waiting parent
process.
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
The _exit() function causes normal program termination to occur.
The functions registered with atexit() aren’t called when you use _exit() to terminate a
program. If you want those functions to be called, use exit() instead.
The _exit() function does the following when a process terminates for any reason:
June 19, 2012
1
Closes all open file descriptors and directory streams in the calling process.
2
Notifies the parent process of the calling process if the parent called wait() or
waitpid(). The low-order 8 bits of status are made available to the parent via
wait() or waitpid().
3
Saves the exit status if the parent process of the calling process isn’t executing a
wait() or waitpid() function. If the parent calls wait() or waitpid() later, this
status is returned immediately.
4
Sends a SIGHUP signal to the calling process’s children; this can indirectly
cause the children to exit if they don’t handle SIGHUP. Children of a terminated
process are assigned a new parent process.
5
Sends a SIGCHLD signal to the parent process.
6
Sends a SIGHUP signal to each process in the foreground process group if the
calling process is the controlling process for the controlling terminal of that
process group.
7
Disassociates the controlling terminal from the calling process’s session if the
process is a controlling process, allowing it to be acquired by a new controlling
process.
QNX Neutrino Functions and Macros
473
_exit()
© 2012, QNX Software Systems Limited
8
If the process exiting causes a process group to become orphaned, and if any
member of the newly-orphaned process group is stopped, then a SIGHUP signal
followed by a SIGCONT signal is sent to each process in the newly-orphaned
process group.
Returns:
The _exit() function doesn’t return.
Examples:
#include <stdio.h>
#include <stdlib.h>
int main( int argc, char *argv[] )
{
FILE *fp;
if( argc <= 1 ) {
fprintf( stderr, "Missing argument\n" );
exit( EXIT_FAILURE );
}
fp = fopen( argv[1], "r" );
if( fp == NULL ) {
fprintf( stderr, "Unable to open ’%s’\n", argv[1] );
_exit( EXIT_FAILURE );
}
fclose( fp );
/*
At this point, calling _exit() is the same as calling
return EXIT_SUCCESS;...
*/
_exit( EXIT_SUCCESS );
}
Classification:
POSIX 1003.1
Safety
474
Cancellation point
No
Interrupt handler
No
Signal handler
Yes
Thread
Yes
QNX Neutrino Functions and Macros
June 19, 2012
© 2012, QNX Software Systems Limited
_exit()
See also:
abort(), atexit(), close(), execl(), execle(), execlp(), execlpe(), execv(), execve(),
execvp(), execvpe(), exit(), getenv(), main(), putenv(), sigaction(), signal(), spawn(),
spawnl(), spawnle(), spawnlp(), spawnlpe(), spawnp(), spawnv(), spawnve(),
spawnvp(), spawnvpe(), system(), wait(), waitpid()
June 19, 2012
QNX Neutrino Functions and Macros
475
exit()
© 2012, QNX Software Systems Limited
Exit the calling program
Synopsis:
#include <stdlib.h>
void exit( int status );
Arguments:
status
The exit status to use for the program. The value may be zero,
EXIT_STATUS, EXIT_FAILURE or any other value. Note that only the least
significant bits (i.e. status and 0377) may be available to a waiting parent
process.
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
The exit() function causes the calling program to exit normally. When a program exits
normally:
1
All functions registered with the atexit() function are called.
2
All open file streams (those opened by fopen(), fdopen(), freopen(), or popen())
are flushed and closed.
3
All temporary files created by the tmpfile() function are removed.
4
The return status is made available to the parent process; status is typically set
to EXIT_SUCCESS to indicate successful termination and set to EXIT_FAILURE
or some other value to indicate an error.
Returns:
The exit() function doesn’t return.
Examples:
#include <stdio.h>
#include <stdlib.h>
int main( int argc, char *argv[] )
{
FILE *fp;
if( argc <= 1 ) {
fprintf( stderr, "Missing argument\n" );
exit( EXIT_FAILURE );
}
fp = fopen( argv[1], "r" );
476
QNX Neutrino Functions and Macros
June 19, 2012
exit()
© 2012, QNX Software Systems Limited
if( fp == NULL ) {
fprintf( stderr, "Unable to open ’%s’\n", argv[1] );
exit( EXIT_FAILURE );
}
fclose( fp );
exit( EXIT_SUCCESS );
/*
You’ll never get here; this prevents compiler
warnings about "function has no return value".
*/
return EXIT_SUCCESS;
}
Classification:
ANSI, POSIX 1003.1
Safety
Cancellation point
No
Interrupt handler
No
Signal handler
No
Thread
Yes
See also:
abort(), atexit(), _exit(), main()
June 19, 2012
QNX Neutrino Functions and Macros
477
exp(), expf(), expl()
© 2012, QNX Software Systems Limited
Compute the exponential function of a number
Synopsis:
#include <math.h>
double exp( double x );
float expf( float x );
long double expl( long double x );
Arguments:
x
The number for which you want to calculate the exponential.
Library:
libm
Use the -l m option to qcc to link against this library.
Description:
These functions compute the exponential function of x (ex ).
A range error occurs if the magnitude of x is too large.
Returns:
The exponential value of x. For a correct value that would cause an underflow, these
functions return 0.0.
If an error occurs, these functions return 0, but this is also a valid mathematical result.
If you want to check for errors, set errno to 0, call the function, and then check errno
again. These functions don’t change errno if no errors occurred.
Examples:
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
int main( void )
{
printf( "%f\n", exp(.5) );
return EXIT_SUCCESS;
}
produces the output:
1.648721
478
QNX Neutrino Functions and Macros
June 19, 2012
exp(), expf(), expl()
© 2012, QNX Software Systems Limited
Classification:
ANSI, POSIX 1003.1
Safety
Cancellation point
No
Interrupt handler
No
Signal handler
No
Thread
Yes
Caveats:
The value of expm1(x) may be more accurate than exp(x) - 1.0 for small values of x.
See also:
errno, expm1, log()
June 19, 2012
QNX Neutrino Functions and Macros
479
expm1(), expm1f()
© 2012, QNX Software Systems Limited
Compute the exponential of a number, then subtract 1
Synopsis:
#include <math.h>
double expm1 ( double x );
float expm1f ( float x );
Arguments:
x
The number for which you want to calculate the exponential minus one.
Library:
libm
Use the -l m option to qcc to link against this library.
Description:
The expm1() and expm1f() functions compute the exponential of x, minus 1 (ex - 1).
A range error occurs if the magnitude of x is too large.
The value of expm1( x ) may be more accurate than exp( x ) - 1.0 for small values of x.
The expm1() and log1p() functions are useful for financial calculations of
(((1+x)**n)-1)/x, namely:
expm1(n * log1p(x))/x
when x is very small (for example, when performing calculations with a small daily
interest rate). These functions also simplify writing accurate inverse hyperbolic
functions.
Returns:
The exponential value of x, minus 1.
If an error occurs, these functions return 0, but this is also a valid mathematical result.
If you want to check for errors, set errno to 0, call the function, and then check errno
again. These functions don’t change errno if no errors occurred.
Examples:
#include
#include
#include
#include
#include
<stdio.h>
<errno.h>
<inttypes.h>
<math.h>
<fpstatus.h>
int main(int argc, char** argv)
{
double a, b;
480
QNX Neutrino Functions and Macros
June 19, 2012
expm1(), expm1f()
© 2012, QNX Software Systems Limited
a = 2;
b = expm1(a);
printf("(e ˆ %f) -1
is %f \n", a, b);
return(0);
}
produces the output:
(e ˆ 2.000000) -1
is 6.389056
Classification:
ANSI, POSIX 1003.1
Safety
Cancellation point
No
Interrupt handler
No
Signal handler
No
Thread
Yes
See also:
exp(), log1p()
June 19, 2012
QNX Neutrino Functions and Macros
481
fabs(), fabsf()
© 2012, QNX Software Systems Limited
Compute the absolute value of a double number
Synopsis:
#include <math.h>
double fabs( double x );
float fabsf( float x );
Arguments:
x
The number you want the absolute value of.
Library:
libm
Use the -l m option to qcc to link against this library.
Description:
These functions compute the absolute value of x.
Returns:
The absolute value of x.
If an error occurs, these functions return 0, but this is also a valid mathematical result.
If you want to check for errors, set errno to 0, call the function, and then check errno
again. These functions don’t change errno if no errors occurred.
Examples:
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
int main( void )
{
printf( "%f %f\n", fabs(.5), fabs(-.5) );
return EXIT_SUCCESS;
}
produces the output:
0.500000 0.500000
Classification:
ANSI, POSIX 1003.1
482
QNX Neutrino Functions and Macros
June 19, 2012
fabs(), fabsf()
© 2012, QNX Software Systems Limited
Safety
Cancellation point
No
Interrupt handler
No
Signal handler
No
Thread
Yes
See also:
abs(), cabs(), labs(), llabs()
June 19, 2012
QNX Neutrino Functions and Macros
483
fcfgopen()
© 2012, QNX Software Systems Limited
Open a configuration file
Synopsis:
#include <cfgopen.h>
FILE * fcfgopen( const char * path,
const char * mode,
int location,
const char * historical,
char * namebuf ,
int nblen );
Arguments:
path
The name of the configuration file that you want to open.
mode
A string that describes the mode to open in; see fopen().
location
Flags that describe how the path is constructed. See “Search condition
flags” in the documentation for cfgopen().
historical
A optional file to open as a last resort if none of the criteria for finding
the path is met. This string works like a path search order, and lets you
search more than one location. You can also specify %H to substitute the
hostname value into the string. Specify NULL to ignore this option.
namebuf
A buffer to save the pathname in. Specify NULL to ignore this option.
nblen
The length of the buffer pointed to by namebuf . Specify 0 to ignore this
option.
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
This function is in libc.a, but not in libc.so (in order to save space).
Description:
The fcfgopen() function is similar to cfgopen() with these exceptions:
• The CFGFILE_NOFD flag isn’t valid.
• The values for flags described in open() aren’t valid.
484
QNX Neutrino Functions and Macros
June 19, 2012
fcfgopen()
© 2012, QNX Software Systems Limited
Returns:
A valid fd if CFGFILE_NOFD isn’t specified, a nonnegative value if CFGFILE_NOFD
is specified, or -1 if an error occurs.
Classification:
QNX Neutrino
Safety
Cancellation point
Yes
Interrupt handler
No
Signal handler
Yes
Thread
Yes
See also:
cfgopen(), confstr()
mib.txt, snmpd.conf in the Utilities Reference
June 19, 2012
QNX Neutrino Functions and Macros
485
fchdir()
© 2012, QNX Software Systems Limited
Change the working directory
Synopsis:
#include <unistd.h>
int fchdir(int fd);
Arguments:
var
A file descriptor for the directory that you want to become the current working
directory.
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
The fchdir() function is similar to chdir(), except that you use a file descriptor to
specify the directory that you want to become the new current working directory. You
can obtain a file descriptor for a directory by calling open(), provided that the file
status flags and access modes don’t contain O_WRONLY or O_RDWR.
Returns:
0, or -1 if an error occurred (errno is set). If the function fails, the current working
directory isn’t changed.
Errors:
EACCES
Search permission is denied for the directory referenced by fd.
EBADF
The fd argument isn’t an open file descriptor.
ENOTDIR
The open file descriptor fd doesn’t refer to a directory.
EINTR
A signal was caught during the execution of fchdir().
EIO
An I/O error occurred while reading from or writing to the filesystem.
Classification:
POSIX 1003.1 XSI
486
QNX Neutrino Functions and Macros
June 19, 2012
fchdir()
© 2012, QNX Software Systems Limited
Safety
Cancellation point
No
Interrupt handler
No
Signal handler
Yes
Thread
Yes
See also:
chdir(), errno, getcwd(), mkdir(), rmdir()
June 19, 2012
QNX Neutrino Functions and Macros
487
fchmod()
© 2012, QNX Software Systems Limited
Change the permissions for a file
Synopsis:
#include <sys/types.h>
#include <sys/stat.h>
int fchmod( int fd,
mode_t mode );
Arguments:
fd
A file descriptor for the file whose permissions you want to change.
mode
The new permissions for the file. For more information, see “Access
permissions” in the documentation for stat().
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
The fchmod() function changes the permissions for a file referred to by fd to be the
settings in the mode given by mode.
If the effective user ID of the calling process is equal to the file owner, or the calling
process has appropriate privileges (for example, the superuser), fchmod() sets the
S_ISUID, S_ISGID and the file permission bits, defined in the <sys/stat.h> header
file, from the corresponding bits in the mode argument. These bits define access
permissions for the user associated with the file, the group associated with the file, and
all others.
For a regular file, if the calling process doesn’t have appropriate privileges, and if the
group ID of the file doesn’t match the effective group ID, the S_ISGID (set-group-ID
on execution) bit in the file’s mode is cleared upon successful return from fchmod().
Changing the permissions has no any effect on any file descriptors for files that are
already open.
If fchmod() succeeds, the st_ctime field of the file is marked for update.
Returns:
488
0
Success.
-1
An error occurred (errno is set).
QNX Neutrino Functions and Macros
June 19, 2012
fchmod()
© 2012, QNX Software Systems Limited
Errors:
EBADF
ENOSYS
Invalid file descriptor.
The fchmod() function isn’t implemented for the filesystem specified by
fd.
EPERM
The effective user ID doesn’t match the owner of the file, and the calling
process doesn’t have appropriate privileges.
EROFS
The referenced file resides on a read-only filesystem.
Examples:
/*
* Change the permissions of a list of files
* to be read/write by the owner only
*/
#include <stdio.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
int main( int argc, char **argv )
{
int i;
int ecode = 0;
int fd;
for( i = 1; i < argc; i++ ) {
if( ( fd = open( argv[i], O_RDONLY ) ) == -1 ) {
perror( argv[i] );
ecode++;
}
else if( fchmod( fd, S_IRUSR | S_IWUSR ) == -1 ) {
perror( argv[i] );
ecode++;
}
close( fd );
}
return ecode;
}
Classification:
POSIX 1003.1
Safety
June 19, 2012
Cancellation point
No
Interrupt handler
No
Signal handler
Yes
Thread
Yes
QNX Neutrino Functions and Macros
489
fchmod()
© 2012, QNX Software Systems Limited
See also:
chmod(), chown(), errno, fchown(), fstat(), open(), stat()
490
QNX Neutrino Functions and Macros
June 19, 2012
fchown()
© 2012, QNX Software Systems Limited
Change the user ID and group ID of a file
Synopsis:
#include <sys/types.h>
#include <unistd.h>
int fchown( int fd,
uid_t owner,
gid_t group );
Arguments:
fd
A file descriptor for the file whose ownership you want to change.
owner
The user ID of the new owner.
group
The group ID of the new owner.
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
The fchown() function changes the user ID and group ID of the file referenced by fd to
be the numeric values contained in owner and group, respectively.
Only processes with an effective user ID equal to the user ID of the file, or with
appropriate privileges (for example, the superuser) may change the ownership of a file.
The _POSIX_CHOWN_RESTRICTED flag is enforced. This means that only the
superuser may change the ownership of a file. The group of a file may be changed by
the superuser, or also by a process with the effective user ID equal to the user ID of the
file, if (and only if) owner is equal to the user ID of the file and group is equal to the
effective group ID of the calling process.
If the fd argument refers to a regular file, the set-user-ID (S_ISUID) and set-group-ID
(S_ISGID) bits of the file mode are cleared if the function is successful.
If fchown() succeeds, the st_ctime field of the file is marked for update.
Returns:
June 19, 2012
0
Success.
-1
An error occurred (errno is set).
QNX Neutrino Functions and Macros
491
fchown()
© 2012, QNX Software Systems Limited
Errors:
EBADF
EPERM
Invalid file descriptor.
The effective user ID doesn’t match the owner of the file, or the calling
process doesn’t have appropriate privileges.
EROFS
The named file resides on a read-only filesystem.
Examples:
/*
* Change the ownership of a list of files
* to the current user/group
*/
#include <stdio.h>
#include <fcntl.h>
#include <sys/types.h>
#include <unistd.h>
int main( int argc, char **argv )
{
int i;
int ecode = 0;
int fd;
for( i = 1; i < argc; i++ ) {
if( ( fd = open( argv[i], O_RDONLY ) ) == -1 ) {
perror( argv[i] );
ecode++;
}
else if( fchown( fd, getuid(), getgid() ) == -1 ) {
perror( argv[i] );
ecode++;
}
close( fd );
}
return ecode;
}
Classification:
POSIX 1003.1
Safety
492
Cancellation point
Yes
Interrupt handler
No
Signal handler
Yes
Thread
Yes
QNX Neutrino Functions and Macros
June 19, 2012
fchown()
© 2012, QNX Software Systems Limited
See also:
chmod(), chown(), errno, fchmod(), fstat(), lchown(), open(), stat()
June 19, 2012
QNX Neutrino Functions and Macros
493
fclose()
© 2012, QNX Software Systems Limited
Close a stream
Synopsis:
#include <stdio.h>
int fclose( FILE* fp );
Arguments:
fp
The stream you want to close.
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
The fclose() function closes the stream specified by fp. Any unwritten, buffered data is
flushed before the file is closed. Any unread, buffered data is discarded.
If the associated buffer was automatically allocated, it’s deallocated.
Returns:
0 for success, or EOF if an error occurred (errno is set).
Errors:
EAGAIN
The O_NONBLOCK flag is set for the file descriptor underlying fp, and
the process would be delayed in the write operation.
EBADF
The file descriptor underlying fp isn’t valid.
EFBIG
One of the following:
• An attempt was made to write a file that exceeds the maximum file
size.
• An attempt was made to write a file that exceeds the process’s file size
limit.
• The file is a regular file, and an attempt was made to write at or
beyond the offset maximum associated with the corresponding stream.
EINTR
The fclose() function was interrupted by a signal.
EIO
One of the following:
• The process is a member of a background process group attempting to
write to its controlling terminal, TOSTOP is set, the process is neither
ignoring nor blocking SIGTTOU, and the process group of the process
is orphaned.
494
QNX Neutrino Functions and Macros
June 19, 2012
fclose()
© 2012, QNX Software Systems Limited
• (QNX Neutrino extension) An I/O error occurred when writing
cached data to the underlying media.
• (QNX Neutrino extension) An I/O error occurred when updating
metadata on the underlying media.
• (QNX Neutrino extension) The filesystem resides on a removable
media device, and the media has been forcibly removed.
ENOSPC
There was no free space remaining on the device containing the file.
ENXIO
A request was made of a nonexistent device, or the request was outside
the capabilities of the device.
EPIPE
An attempt was made to write to a pipe or FIFO that wasn’t open for
reading by any process. A SIGPIPE signal is also sent to the thread.
Examples:
#include <stdio.h>
#include <stdlib.h>
int main( void )
{
FILE *fp;
fp = fopen( "stdio.h", "r" );
if( fp != NULL ) {
fclose( fp );
return EXIT_SUCCESS;
}
return EXIT_FAILURE;
}
Classification:
ANSI, POSIX 1003.1
Safety
Cancellation point
Yes
Interrupt handler
No
Signal handler
No
Thread
Yes
See also:
errno, fcloseall(), fdopen(), fopen(), freopen()
June 19, 2012
QNX Neutrino Functions and Macros
495
fcloseall()
© 2012, QNX Software Systems Limited
Close all open stream files
Synopsis:
#include <stdio.h>
int fcloseall( void );
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
The fcloseall() function closes all open streams, except stdin, stdout and stderr. This
includes streams created (and not yet closed) by fdopen(), fopen() and freopen().
Returns:
0
Errors:
If an error occurs, errno is set.
Examples:
#include <stdio.h>
#include <stdlib.h>
int main( void )
{
printf( "The number of files closed is %d\n", fcloseall() );
return EXIT_SUCCESS;
}
Classification:
QNX 4
Safety
496
Cancellation point
Yes
Interrupt handler
No
Signal handler
No
Thread
Yes
QNX Neutrino Functions and Macros
June 19, 2012
© 2012, QNX Software Systems Limited
fcloseall()
See also:
fclose(), fdopen(), fopen(), freopen()
June 19, 2012
QNX Neutrino Functions and Macros
497
fcntl()
© 2012, QNX Software Systems Limited
Provide control over an open file
Synopsis:
#include <sys/types.h>
#include <unistd.h>
#include <fcntl.h>
int fcntl( int fildes,
int cmd,
... );
Arguments:
fildes
The descriptor for the file you want to control.
cmd
The command to execute; see below.
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
The fcntl() function provides control over the open file referenced by file descriptor
fildes. To establish a lock with this function, open with write-only permission
(O_WRONLY) or with read/write permission (O_RDWR).
The type of control is specified by the cmd argument, which may require a third data
argument (arg). The cmd argument is defined in <fcntl.h>, and includes at least the
following values:
F_ALLOCSP
Allocate storage space for the section of the file specified by the
l_start, l_len, and l_whence fields of a struct flock structure
pointed to by the additional argument to fcntl()
F_ALLOCSP64
Same as F_ALLOCSP, except that the argument is a pointer to a
struct flock64 structure, where the l_start and l_len fields are
64-bit values.
498
F_DUPFD
Allocate and return a new file descriptor that’s the lowest
numbered available (i.e. not already open) file descriptor greater
than or equal to the third argument, arg, taken as an int. The new
file descriptor refers to the same file as fildes, and shares any locks.
F_FREESP
Free storage space for the section of the file specified by the
l_start, l_len, and l_whence fields of the struct flock
structure pointed to by the additional argument to fcntl().
QNX Neutrino Functions and Macros
June 19, 2012
fcntl()
© 2012, QNX Software Systems Limited
F_FREESP64
Same as F_FREESP, except that the argument is a pointer to a
struct flock64 structure, where the l_start and l_len fields are
64-bit values.
F_GETFD
Get the file descriptor flags associated with the file descriptor
fildes. File descriptor flags are associated with a single file
descriptor, and don’t affect other file descriptors referring to the
same file.
F_GETFL
Get the file status flags and the file access modes associated with
fildes. The flags and modes are defined in <fcntl.h>.
The file status flags (see open() for more detailed information) are:
• O_APPEND — Set append mode.
• O_NONBLOCK — No delay.
The file access modes are:
• O_RDONLY — Open for reading only.
• O_RDWR — Open for reading and writing.
• O_WRONLY — Open for writing only.
F_GETLK
Get the first lock that blocks the lock description pointed to by the
third argument, arg, taken as a pointer to type struct flock
(defined in <fcntl.h>). For more information, see the flock
structure section below. The information returned overwrites the
information passed to fcntl() in the structure pointed to by arg.
If no lock is found that prevents this lock from being created, the
structure is left unchanged, except for the lock type, which is set to
F_UNLCK. If a lock is found, the l_pid member of the structure
pointed to by arg is set to the process ID of the process holding the
blocking lock and l_whence is set to SEEK_SET.
F_GETLK64
Same as F_GETLK, except that the argument is a pointer to a
struct flock64 structure, where the l_start and l_len fields are
64-bit values.
F_SETFD
Set the file descriptor flags associated with fildes to the third
argument, arg, taken as type int. See the above discussion for
more details.
The only defined file descriptor flag is:
FD_CLOEXEC
F_SETFL
June 19, 2012
When this flag is clear, the file remains open
across spawn*() or exec*() calls; else the file is
closed.
Set the file status flags, as shown above, for the open file
description associated with fildes from the corresponding bits in
QNX Neutrino Functions and Macros
499
fcntl()
© 2012, QNX Software Systems Limited
the third argument, arg, taken as type int. You can’t use this
function to change the file access mode. All bits set in arg, other
than the file status bits, are ignored.
F_SETLK
Set or clear a file segment lock, according to the lock description
pointed to by the third argument, arg, taken as a pointer to type
struct flock, as defined in the header file <fcntl.h>, and
documented below. This command is used to create the following
locks (defined in <fcntl.h>):
F_RDLCK
Shared or read locks.
F_UNLCK
Remove either type of lock.
F_WRLCK
Exclusive or write locks.
If a lock can’t be set, fcntl() returns immediately.
F_SETLK64
Same as F_SETLK, except that the argument is a pointer to a
struct flock64 structure, where the l_start and l_len fields are
64-bit values.
F_SETLKW
This command is the same as F_SETLK, except that when a lock is
blocked by other locks, the process waits until the request can be
satisfied. If a signal that’s to be caught is received while fcntl() is
waiting for a region, the call is interrupted without performing the
lock operation, and fcntl() returns -1 with errno set to EINTR.
F_SETLKW64
Same as F_GETLKW, except that the argument is a pointer to a
struct flock64 structure, where the l_start and l_len fields are
64-bit values.
flock structure
The flock structure contains at least the following members:
500
short l_type
One of F_RDLCK, F_WRLCK or F_UNLCK.
short l_whence
One of the following flags that specify where the relative offset,
l_start, is measured from:
SEEK_CUR
Current seek position.
SEEK_END
End of file.
SEEK_SET
Start of file.
off_t l_start
Relative offset in bytes.
off_t l_len
Consecutive bytes to lock; if 0, then until EOF; if negative, the
preceding bytes up to, but not including, the start byte.
QNX Neutrino Functions and Macros
June 19, 2012
© 2012, QNX Software Systems Limited
pid_t l_pid
fcntl()
Process ID of the process holding the lock, returned when cmd
is F_GETLK.
When a shared lock is set on a segment of a file, other processes can set shared locks
on the same segment, or a portion of it. A shared lock prevents other processes from
setting exclusive locks on any portion of the protected area. A request for a shared
lock fails if the file was opened write-only.
An exclusive lock prevents any other process from setting a shared or an exclusive
lock on a portion of the protected area. A request for an exclusive lock fails if the file
was opened read-only.
Locks may start and extend beyond the current end of file, but may not start or extend
before the beginning of the file; to attempt to do so is an error. A lock extends to
“infinity” (the largest possible value for the file offset) if l_len is set to zero. If
l_whence and l_start point to the beginning of the file, and l_len is zero, the entire file
is locked.
The calling process may have only one type of lock set for each byte of a file. Before
successfully returning from an F_SETLK or F_SETLKW request, the previous lock
type (if any) for each byte in the specified lock region is replaced by the new lock
type. All locks associated with a file for a given process are removed when a file
descriptor for that file is closed by the process, or the process holding the file
descriptor terminates. Locks aren’t inherited by a child process using the fork()
function. However, locks are inherited across exec*() or spawn*() calls.
A potential for deadlock occurs if a process controlling a locked region is put to sleep
by attempting to lock another process’s locked region. If the system detects that
sleeping until a locked region is unlocked would cause a deadlock, fcntl() fails with
EDEADLK. However, the system can’t always detect deadlocks in the network case,
and care should be exercised in the design of your application for this possibility.
June 19, 2012
QNX Neutrino Functions and Macros
501
fcntl()
© 2012, QNX Software Systems Limited
Locking is a protocol designed for updating a file shared among concurrently running
applications. Locks are only advisory, that is, they don’t prevent an errant or
poorly-designed application from overwriting a locked region of a shared file. An
application should use locks to indicate regions of a file that are to be updated by the
application, and it should respect the locks of other applications.
The following functions ignore locks:
• chsize()
• ltrunc()
• open()
• read()
• sopen()
• write()
Returns:
-1 if an error occurred (errno is set). The successful return value(s) depend on the
request type specified by arg, as shown in the following table:
F_DUPFD
A new file descriptor.
F_GETFD
Value of the file descriptor flags (never a negative value).
F_GETFL
Value of the file status flags and access modes as shown above (never
a negative value).
F_GETLK
Value other than -1.
F_SETFD
Value other than -1.
F_SETFL
Value other than -1.
F_SETLK
Value other than -1.
F_SETLKW
Value other than -1.
Errors:
EAGAIN
502
QNX Neutrino Functions and Macros
The cmd argument is F_SETLK, the type of lock (l_type) is a shared
lock (F_RDLCK), and the segment of a file to be locked is already
exclusive-locked by another process, or the type is an exclusive
lock and some portion of the segment of a file to be locked is
already shared-locked or exclusive-locked by another process.
June 19, 2012
fcntl()
© 2012, QNX Software Systems Limited
EBADF
One of the following occurred:
• The fildes argument isn’t a valid file descriptor.
• The cmd argument is F_SETLK or F_SETLKW, the type of lock
(l_type) is a shared lock (F_RDLCK), and fildes isn’t a valid file
descriptor open for reading.
• The cmd argument is F_SETLK or F_SETLKW, the type of lock
(l_type) is an exclusive lock (F_WRLCK), and fildes isn’t a valid
file descriptor open for writing.
EDEADLK
The cmd argument is F_SETLKW, and a deadlock condition was
detected.
EINTR
The cmd argument is F_SETLKW, and the function was interrupted
by a signal.
EINVAL
One of the following occurred:
• The cmd argument is invalid.
• The cmd argument is F_DUPFD, and the third argument is
negative, or greater than the configured number of maximum
open file descriptors per process.
• The cmd argument is F_GETLK, F_SETLK or F_SETLKW, and
the data arg isn’t valid, or fildes refers to a file that doesn’t
support locking.
EMFILE
The cmd argument is F_DUPFD, and the process has no unused file
descriptors, or no file descriptors greater than or equal to arg are
available.
ENOLCK
The cmd argument is F_SETLK or F_SETLKW, and satisfying the
lock or unlock request causes the number of lock regions in the
system to exceed the system-imposed limit.
ENOSYS
The filesystem doesn’t support the operation.
EOVERFLOW
One of the values to be returned can’t be represented correctly.
Examples:
/*
* This program makes "stdout" synchronous
* to guarantee the data is recoverable
* (if it’s redirected to a file).
*/
#include <unistd.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
int main( void )
{
int flags, retval;
June 19, 2012
QNX Neutrino Functions and Macros
503
fcntl()
© 2012, QNX Software Systems Limited
flags = fcntl( STDOUT_FILENO, F_GETFL );
flags |= O_DSYNC;
retval = fcntl( STDOUT_FILENO, F_SETFL, flags );
if( retval == -1 ) {
printf( "error setting stdout flags\n" );
return EXIT_FAILURE;
}
printf( "hello QNX world\n" );
return EXIT_SUCCESS;
}
Classification:
POSIX 1003.1
Safety
Cancellation point
Read the Caveats
Interrupt handler
No
Signal handler
Yes
Thread
Yes
Caveats:
The fcntl() function may be a cancellation point in the case of F_DUPFD (when
dupping across the network), F_GETFD, and F_SETFD.
See also:
close(), dup(), dup2(), execl(), execle(), execlp(), execlpe(), execv(), execve(), execvp(),
execvpe(), ioctl(), open()
504
QNX Neutrino Functions and Macros
June 19, 2012
fdatasync()
© 2012, QNX Software Systems Limited
Synchronize file data
Synopsis:
#include <unistd.h>
int fdatasync( int filedes );
Arguments:
filedes
The descriptor of the file that you want to synchronize.
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
The fdatasync() function forces all queued I/O operations for the file specified by the
filedes file descriptor to finish, synchronizing the file’s data. The function blocks until
this is finished. For more information about synchronizing, see “Filesystems and block
I/O (devb-*) drivers” in the Fine-Tuning Your System chapter of the QNX Neutrino
User’s Guide.
This function is similar to fsync(), except that fsync() also guarantees the integrity of
file information, such as access and modification times.
Returns:
0
Success.
-1
An error occurred (errno is set).
Errors:
EBADF
The specified filedes isn’t a valid file descriptor open for writing.
EINVAL
The implementation doesn’t support synchronized I/O for the given file.
ENOSYS
The fdatasync() function isn’t supported for the filesystem specified by
filedes.
Classification:
POSIX 1003.1 SIO
June 19, 2012
QNX Neutrino Functions and Macros
505
fdatasync()
© 2012, QNX Software Systems Limited
Safety
Cancellation point
No
Interrupt handler
No
Signal handler
Yes
Thread
Yes
See also:
aio_fsync(), close(), fcntl(), fsync(), open(), read(), sync(), write()
“Filesystems and block I/O (devb-*) drivers” in the Fine-Tuning Your System
chapter of the QNX Neutrino User’s Guide
506
QNX Neutrino Functions and Macros
June 19, 2012
fdopen()
© 2012, QNX Software Systems Limited
Associate a stream with a file descriptor
Synopsis:
#include <stdio.h>
FILE* fdopen( int filedes,
const char* mode );
Arguments:
filedes
The file descriptor that you want to associate with a stream.
mode
The mode specified when filedes was originally opened. For information,
see fopen(), except modes begining with w don’t cause truncation of the file.
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
The fdopen() function associates a stream with the file descriptor filedes, which
represents an opened file or device.
The filedes argument is a file descriptor that was returned by one of accept(), creat(),
dup(), dup2(), fcntl(), open(), pipe(), or sopen().
The fdopen() function preserves the offset maximum previously set for the open file
description corresponding to filedes.
Returns:
A file stream for success, or NULL if an error occurs (errno is set).
Errors:
EBADF
The filedes argument isn’t a valid file descriptor.
EINVAL
The mode argument isn’t a valid mode.
EMFILE
Too many file descriptors are currently in use by this process.
ENOMEM
There isn’t enough memory for the FILE structure.
Examples:
#include
#include
#include
#include
<stdio.h>
<fcntl.h>
<unistd.h>
<stdlib.h>
int main( void )
{
June 19, 2012
QNX Neutrino Functions and Macros
507
fdopen()
© 2012, QNX Software Systems Limited
int filedes ;
FILE *fp;
filedes = open( "file", O_RDONLY );
if( filedes != -1 ) {
fp = fdopen( filedes , "r" );
if( fp != NULL ) {
/* Also closes the underlying FD, filedes. */
fclose( fp );
}
}
return EXIT_SUCCESS;
}
Classification:
POSIX 1003.1
Safety
Cancellation point
Yes
Interrupt handler
No
Signal handler
No
Thread
Yes
See also:
creat(), dup(), dup2(), errno, fcntl(), fopen(), freopen(), open(), pipe(), sopen()
508
QNX Neutrino Functions and Macros
June 19, 2012
feof()
© 2012, QNX Software Systems Limited
Test a stream’s end-of-file flag
Synopsis:
#include <stdio.h>
int feof( FILE* fp );
Arguments:
fp
The stream you want to test.
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
The feof() function tests the end-of-file flag for the stream specified by fp.
Because the end-of-file flag is set when an input operation attempts to read past the
end-of-file, the feof() function detects the end-of-file only after an attempt is made to
read beyond the end-of-file. Thus, if a file contains 10 lines, the feof() won’t detect the
end-of-file after the tenth line is read; it will detect the end-of-file on the next read
operation.
Returns:
0 if the end-of-file flag isn’t set, or nonzero if the end-of-file flag is set.
Examples:
#include <stdio.h>
#include <stdlib.h>
void process_record( char *buf )
{
printf( "%s\n", buf );
}
int main( void )
{
FILE *fp;
char buffer[100];
fp = fopen( "file", "r" );
fgets( buffer, sizeof( buffer ), fp );
while( ! feof( fp ) ) {
process_record( buffer );
fgets( buffer, sizeof( buffer ), fp );
}
fclose( fp );
return EXIT_SUCCESS;
}
June 19, 2012
QNX Neutrino Functions and Macros
509
feof()
© 2012, QNX Software Systems Limited
Classification:
ANSI, POSIX 1003.1
Safety
Cancellation point
No
Interrupt handler
No
Signal handler
No
Thread
Yes
See also:
clearerr(), ferror(), fgetc(), fgetchar(), fgets(), fgetwc(), fgetws(), fopen(), freopen(),
getc(), getc_unlocked(), getchar(), getchar_unlocked(), gets(), getw(), getwc(),
getwchar(), perror(), read()
510
QNX Neutrino Functions and Macros
June 19, 2012
ferror()
© 2012, QNX Software Systems Limited
Test a stream’s error flag
Synopsis:
#include <stdio.h>
int ferror( FILE* fp );
Arguments:
fp
The stream whose error flag you want to test.
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
The ferror() function tests the error flag for the stream specified by fp.
Returns:
0 if the error flag isn’t set, or nonzero if the error flag is set.
Examples:
#include <stdio.h>
#include <stdlib.h>
int main( void )
{
FILE *fp;
int c;
fp = fopen( "file", "r" );
if( fp != NULL ) {
c = fgetc( fp );
if( ferror( fp ) ) {
printf( "Error reading file\n" );
}
}
fclose( fp );
return EXIT_SUCCESS;
}
Classification:
ANSI, POSIX 1003.1
June 19, 2012
QNX Neutrino Functions and Macros
511
ferror()
© 2012, QNX Software Systems Limited
Safety
Cancellation point
No
Interrupt handler
No
Signal handler
No
Thread
Yes
See also:
clearerr(), feof(), fgetc(), fgetchar(), fgets(), fgetwc(), fgetws(), getc(), getc_unlocked(),
getchar(), getchar_unlocked(), gets(), getw(), getwc(), getwchar(), perror(), strerror()
512
QNX Neutrino Functions and Macros
June 19, 2012
fflush()
© 2012, QNX Software Systems Limited
Flush the buffers for a stream
Synopsis:
#include <stdio.h>
int fflush( FILE* fp );
Arguments:
fp
NULL, or the stream whose buffers you want to flush.
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
If the stream specified by fp is open for output or update, the fflush() function causes
any buffered (see setvbuf()) but unwritten data to be written to the file descriptor
associated with the stream (see fileno()).
If the file specified by fp is open for input or update, the fflush() function undoes the
effect of any preceding ungetc operation on the stream.
If fp is NULL, all open streams are flushed.
Returns:
0 for success, or EOF if an error occurs (errno is set).
Errors:
EAGAIN
The O_NONBLOCK flag is set for the file descriptor underlying fp, and
the process would be delayed in the write operation.
EBADF
The file descriptor underlying fp isn’t valid.
EFBIG
One of the following:
• An attempt was made to write a file that exceeds the maximum file
size.
• An attempt was made to write a file that exceeds the process’s file size
limit.
• The file is a regular file, and an attempt was made to write at or
beyond the offset maximum associated with the corresponding stream.
June 19, 2012
EINTR
The fflush() function was interrupted by a signal.
EIO
One of the following:
QNX Neutrino Functions and Macros
513
fflush()
© 2012, QNX Software Systems Limited
• The process is a member of a background process group attempting to
write to its controlling terminal, TOSTOP is set, the process is neither
ignoring nor blocking SIGTTOU, and the process group of the process
is orphaned.
• (QNX Neutrino extension) An I/O error occurred when writing
cached data to the underlying media.
• (QNX Neutrino extension) An I/O error occurred when updating
metadata on the underlying media.
• (QNX Neutrino extension) The filesystem resides on a removable
media device, and the media has been forcibly removed.
ENOSPC
There was no free space remaining on the device containing the file.
ENXIO
A request was made of a nonexistent device, or the request was outside
the capabilities of the device.
EPIPE
An attempt was made to write to a pipe or FIFO that wasn’t open for
reading by any process. A SIGPIPE signal is also sent to the thread.
Examples:
#include <stdio.h>
#include <stdlib.h>
int main( void )
{
printf( "Press Enter to continue..." );
fflush( stdout );
getchar();
return EXIT_SUCCESS;
}
Classification:
ANSI, POSIX 1003.1
Safety
514
Cancellation point
Yes
Interrupt handler
No
Signal handler
No
Thread
Yes
QNX Neutrino Functions and Macros
June 19, 2012
© 2012, QNX Software Systems Limited
fflush()
See also:
errno, fgetc(), fgets(), fileno(), flushall(), fopen(), getc(), gets(), setbuf(), setvbuf(),
ungetc()
June 19, 2012
QNX Neutrino Functions and Macros
515
ffs()
© 2012, QNX Software Systems Limited
Find the first bit set in a bit string
Synopsis:
#include <strings.h>
int ffs( int value );
Arguments:
value
The bit string.
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
The ffs() function finds the first bit set in value and returns the index of that bit. Bits
are numbered starting from 1, starting at the rightmost bit.
Returns:
The index of the first bit set, or 0 if value is zero.
Classification:
POSIX 1003.1 XSI
Safety
516
Cancellation point
No
Interrupt handler
No
Signal handler
Yes
Thread
Yes
QNX Neutrino Functions and Macros
June 19, 2012
fgetc()
© 2012, QNX Software Systems Limited
Read a character from a stream
Synopsis:
#include <stdio.h>
int fgetc( FILE* fp );
Arguments:
fp
The stream from which you want to read a character.
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
The fgetc() function reads the next character from the stream specified by fp.
Returns:
The next character from fp, cast as (int)(unsigned char), or EOF if end-of-file
has been reached or if an error occurs (errno is set).
Use feof() or ferror() to distinguish an end-of-file condition from an error.
Errors:
EAGAIN
The O_NONBLOCK flag is set for the file descriptor underlying fp,
and the process would be delayed in the write operation.
EBADF
The file descriptor underlying fp isn’t a valid file descriptor that’s
open for reading.
EINTR
The read operation was terminated due to the receipt of a signal,
and no data was transferred.
EIO
One of the following:
• A physical I/O error occurred.
• The process is in a background process group attempting to read
from its controlling terminal, and either the process is ignoring
or blocking the SIGTTIN signal or the process group is orphaned.
• (QNX Neutrino extension) The filesystem resides on a
removable media device, and the media has been forcibly
removed.
ENOMEM
June 19, 2012
Insufficient space is available.
QNX Neutrino Functions and Macros
517
fgetc()
© 2012, QNX Software Systems Limited
ENXIO
EOVERFLOW
A request was made of a nonexistent device, or the request was
outside the capabilities of the device.
The file is a regular file, and an attempt was made to read at or
beyond the offset maximum associated with the corresponding
stream.
Examples:
#include <stdio.h>
#include <stdlib.h>
int main( void )
{
FILE *fp;
int c;
fp = fopen( "file", "r" );
if( fp != NULL ) {
while( (c = fgetc( fp )) != EOF ) {
fputc( c, stdout );
}
fclose( fp );
return EXIT_SUCCESS;
}
return EXIT_FAILURE;
}
Classification:
ANSI, POSIX 1003.1
Safety
Cancellation point
Yes
Interrupt handler
No
Signal handler
No
Thread
Yes
See also:
errno, feof(), ferror(), fgetchar(), fgets(), fopen(), fputc(), getc(), gets(), ungetc()
518
QNX Neutrino Functions and Macros
June 19, 2012
fgetchar()
© 2012, QNX Software Systems Limited
Read a character from stdin
Synopsis:
#include <stdio.h>
int fgetchar( void );
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
The fgetchar() function is the same as fgetc() with an argument of stdin.
Returns:
The next character from stdin, cast as (int)(unsigned char), EOF if end-of-file
has been reached on stdin or if an error occurs (errno is set).
Use feof() or ferror() to distinguish an end-of-file condition from an error.
Examples:
#include <stdio.h>
#include <stdlib.h>
int main( void )
{
FILE *fp;
int c;
fp = freopen( "file", "r", stdin );
if( fp != NULL ) {
while( (c = fgetchar()) != EOF ) {
fputchar(c);
}
fclose( fp );
return EXIT_SUCCESS;
}
return EXIT_FAILURE;
}
Classification:
QNX 4
June 19, 2012
QNX Neutrino Functions and Macros
519
fgetchar()
© 2012, QNX Software Systems Limited
Safety
Cancellation point
Yes
Interrupt handler
No
Signal handler
No
Thread
Yes
See also:
errno, feof(), ferror(), fgetc(), fputchar(), getc(), getchar()
520
QNX Neutrino Functions and Macros
June 19, 2012
fgetpos()
© 2012, QNX Software Systems Limited
Get the current position of a stream
Synopsis:
#include <stdio.h>
int fgetpos( FILE* fp,
fpos_t* pos );
Arguments:
fp
The stream whose position you want to determine.
pos
A pointer to a fpos_t object where the function can store the position.
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
The fgetpos() function stores the current position of the stream fp in the fpos_t object
specified by pos.
You can use the value stored in pos in a call to fsetpos() if you want to reposition the
file to the position at the time of the fgetpos() call.
Returns:
0 for success, or nonzero if an error occurs (errno is set).
Examples:
#include <stdio.h>
#include <stdlib.h>
int main( void )
{
FILE *fp;
fpos_t position;
char buffer[80];
fp = fopen( "file", "r" );
if( fp != NULL ) {
fgetpos( fp, &position ); /* get position
*/
fgets( buffer, 80, fp );
/* read record
*/
fsetpos( fp, &position ); /* set position
*/
fgets( buffer, 80, fp );
/* read same record */
fclose( fp );
return EXIT_SUCCESS;
}
return EXIT_FAILURE;
}
June 19, 2012
QNX Neutrino Functions and Macros
521
fgetpos()
© 2012, QNX Software Systems Limited
Classification:
ANSI, POSIX 1003.1
Safety
Cancellation point
No
Interrupt handler
No
Signal handler
No
Thread
Yes
See also:
errno, fopen(), fseek(), fsetpos(), ftell()
522
QNX Neutrino Functions and Macros
June 19, 2012
fgets()
© 2012, QNX Software Systems Limited
Read a string of characters from a stream
Synopsis:
#include <stdio.h>
char* fgets( char* buf ,
size_t n,
FILE* fp );
Arguments:
buf
A pointer to a buffer in which fgets() can store the characters that it reads.
n
The maximum number of characters to read.
fp
The stream from which to read the characters.
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
The fgets() function reads a string of characters from the stream specified by fp, and
stores them in the array specified by buf .
It stops reading characters when:
• the end-of-file is reached
Or:
• a newline (’\n’) character is read
Or:
• n-1 characters have been read.
The newline character isn’t discarded. A null character is placed immediately after the
last character read into the array.
Don’t assume that there’s a newline character in every string that you read with fgets().
A newline character isn’t present if there are more than n-1 characters before the
newline.
Also, a newline character might not appear as the last character in a file when the
end-of-file is reached.
June 19, 2012
QNX Neutrino Functions and Macros
523
fgets()
© 2012, QNX Software Systems Limited
Returns:
The same pointer as buf , or NULL if the stream is at the end-of-file or an error occurs
(errno is set).
Use feof() or ferror() to distinguish an end-of-file condition from an error.
Examples:
#include <stdio.h>
#include <stdlib.h>
int main( void )
{
FILE *fp;
char buffer[80];
fp = fopen( "file", "r" );
if( fp != NULL ) {
while( fgets( buffer, 80, fp ) != NULL ) {
fputs( buffer, stdout );
}
fclose( fp );
return EXIT_SUCCESS;
}
return EXIT_FAILURE;
}
Classification:
ANSI, POSIX 1003.1
Safety
Cancellation point
Yes
Interrupt handler
No
Signal handler
No
Thread
Yes
See also:
errno, feof(), ferror(), fopen(), fputs(), getc(), gets(), fgetc()
524
QNX Neutrino Functions and Macros
June 19, 2012
fgetspent()
© 2012, QNX Software Systems Limited
Get an entry from the shadow password database
Synopsis:
#include <sys/types.h>
#include <shadow.h>
struct spwd* fgetspent( FILE* f );
Arguments:
f
The stream from which to read the shadow password database.
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
The fgetspent() works like the getspent() function but it assumes that it’s reading from
a file formatted like a shadow password database file. This function uses a static buffer
that’s overwritten by each call.
The fgetspent(), getspent(), and getspnam() functions share the same static buffer.
Returns:
A pointer to an object of type struct spwd containing the next entry from the
password database. For more information about this structure, see putspent().
Errors:
The fgetspent() function uses the following functions, and as a result errno can be set
to an error for any of these calls:
• fclose()
• fgets()
• fopen()
• fseek()
• rewind()
Examples:
#include
#include
#include
#include
June 19, 2012
<stdio.h>
<stdlib.h>
<pwd.h>
<shadow.h>
QNX Neutrino Functions and Macros
525
fgetspent()
© 2012, QNX Software Systems Limited
/*
* This program loops, reading a entries from a file
* (which is formatted in the shadow password way)
* reading the next shadow password entry.
* For example this_file /etc/shadow
*/
int main( int argc, char** argv )
{
FILE*
fp;
struct spwd* sp;
if (argc < 2) {
printf("%s filename \n", argv[0]);
return(EXIT_FAILURE);
}
if (!(fp = fopen(argv[1], "r"))) {
fprintf(stderr, "Can’t open file %s \n", argv[1]);
return(EXIT_FAILURE);
}
while( (sp = fgetspent(fp)) != (struct spwd *) 0 ) {
printf( "Username: %s\n", sp->sp_namp );
printf( "Password: %s\n", sp->sp_pwdp );
}
fclose(fp);
return( EXIT_SUCCESS );
}
Classification:
Unix
Safety
Cancellation point
Yes
Interrupt handler
No
Signal handler
No
Thread
No
See also:
errno, getgrent(), getlogin(), getpwnam(), getpwuid(), getspent(), getspnam(),
putspent()
526
QNX Neutrino Functions and Macros
June 19, 2012
fgetwc()
© 2012, QNX Software Systems Limited
Read a wide character from a stream
Synopsis:
#include <wchar.h>
wint_t fgetwc( FILE * fp );
Arguments:
fp
The stream from which you want to read a character.
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
The fgetwc() function reads the next wide character from the stream specified by fp.
Returns:
The next character from fp, cast as (wint_t)(wchar_t), or WEOF if end-of-file has
been reached or if an error occurs (errno is set).
Use feof() or ferror() to distinguish an end-of-file condition from an error.
Errors:
EAGAIN
The O_NONBLOCK flag is set for fp and would have been blocked
by this operation.
EBADF
The file descriptor for fp isn’t valid for reading.
EINTR
A signal terminated the read operation; no data was transferred.
EIO
Either a physical I/O error has occurred, or the process is in the
background and is being ignored or blocked.
EOVERFLOW
Cannot read at or beyond the offset maximum for this stream.
Classification:
ANSI, POSIX 1003.1
Safety
Cancellation point
Yes
continued. . .
June 19, 2012
QNX Neutrino Functions and Macros
527
fgetwc()
© 2012, QNX Software Systems Limited
Safety
Interrupt handler
No
Signal handler
No
Thread
Yes
See also:
errno, feof(), ferror(), fgetc(), fgetws(), fputwc(), fputws(), getwc(), getwchar()
528
QNX Neutrino Functions and Macros
June 19, 2012
fgetws()
© 2012, QNX Software Systems Limited
Read a string of wide characters from a stream
Synopsis:
#include <wchar.h>
wchar_t * fgetws( wchar_t * buf ,
int n,
FILE * fp );
Arguments:
buf
A pointer to a buffer in which fgetws() can store the wide characters that it
reads.
n
The maximum number of characters to read.
fp
The stream from which to read the characters.
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
The fgetws() function reads a string of wide characters from the stream specified by fp,
and stores them in the array specified by buf .
It stops reading wide characters when one of the following occurs:
• The end-of-file is reached.
• A newline (’\n’) character is read.
• n-1 characters have been read.
The fgetws() function places a NUL at the end of the string.
Don’t assume all strings have newline characters. A newline character isn’t present
when more than n-1 characters occur before the newline.
Also, a newline character might not appear as the last character in a file when the
end-of-file is reached.
Returns:
June 19, 2012
NULL
Failure; the stream is at the end-of-file or an error occurred (errno is set).
buf
Success.
QNX Neutrino Functions and Macros
529
fgetws()
© 2012, QNX Software Systems Limited
Use feof() or ferror() to distinguish an end-of-file condition from an error.
Errors:
EAGAIN
The O_NONBLOCK flag is set for fp and would have been blocked
by this operation.
EBADF
The file descriptor for fp isn’t valid for reading.
EINTR
A signal terminated the read operation; no data was transferred.
EIO
Either a physical I/O error has occurred, or the process is in the
background and is being ignored or blocked.
EOVERFLOW
Cannot read at or beyond the offset maximum for this stream.
Classification:
ANSI, POSIX 1003.1
Safety
Cancellation point
Yes
Interrupt handler
No
Signal handler
No
Thread
Yes
See also:
errno, feof(), ferror(), fgets(), fputwc(), fputws(), fwide(), gets()
530
QNX Neutrino Functions and Macros
June 19, 2012
fileno()
© 2012, QNX Software Systems Limited
Return the file descriptor for a stream
Synopsis:
#include <stdio.h>
int fileno( FILE * stream );
Arguments:
stream
The stream whose file descriptor you want to find.
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
The fileno() function returns the file descriptor for the specified file stream. This file
descriptor can be used in POSIX input/output calls anywhere the value returned by
open() can be used.
To associate a stream with a file descriptor, call fdopen().
In QNX Neutrino, the file descriptor is also the connection ID (coid) used by various
Neutrino-specific functions.
The following symbolic values in <unistd.h> define the file descriptors associated
with the C language stdin, stdout, and stderr streams:
STDIN_FILENO
Standard input file number, stdin (0)
STDOUT_FILENO
Standard output file number, stdout (1)
STDERR_FILENO
Standard error file number, stderr (2)
Returns:
A file descriptor, or -1 if an error occurs (errno is set).
Examples:
#include <stdlib.h>
#include <stdio.h>
int main( void )
{
FILE *stream;
stream = fopen( "file", "r" );
if( stream != NULL ) {
printf( "File number is %d.\n", fileno( stream ) );
June 19, 2012
QNX Neutrino Functions and Macros
531
fileno()
© 2012, QNX Software Systems Limited
fclose( stream );
return EXIT_SUCCESS;
}
return EXIT_FAILURE;
}
Produces output similar to:
File number is 7.
Classification:
POSIX 1003.1
Safety
Cancellation point
No
Interrupt handler
No
Signal handler
Yes
Thread
Yes
See also:
errno, fdopen(), fopen(), open()
532
QNX Neutrino Functions and Macros
June 19, 2012
flink()
© 2012, QNX Software Systems Limited
Assign a pathname to a file descriptor
Synopsis:
#include <unistd.h>
int flink( int fd,
const char *path );
Arguments:
fd
The file descriptor.
path
The path you want to associate with the file descriptor.
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
The flink() function assigns the pathname, path, to the file associated with the file
descriptor, fd.
Returns:
0
Success.
-1
An error occurred; errno is set.
Errors:
EACCES
A component of either path prefix denies search permission, or the link
named by path is in a directory with a mode that denies write
permission.
EBADF
The file descriptor fd is invalid.
EEXIST
The link named by path already exists.
ELOOP
Too many levels of symbolic links or prefixes.
EMLINK
The number of links to the file would exceed LINK_MAX.
ENAMETOOLONG
The length of the path string exceeds PATH_MAX, or a pathname
component is longer than NAME_MAX.
ENOENT
This error code can mean the following:
• A component of either path prefix doesn’t exist.
June 19, 2012
QNX Neutrino Functions and Macros
533
flink()
© 2012, QNX Software Systems Limited
ENOSPC
• The path points to an empty string.
The directory that would contain the link can’t be extended.
ENOSYS
The flink() function isn’t implemented for the filesystem specified in
path.
ENOTDIR
A component of either path prefix isn’t a directory.
EROFS
The requested link requires writing in a directory on a read-only file
system.
EXDEV
The link named by path is on a different logical disk.
Classification:
Unix
Safety
Cancellation point
No
Interrupt handler
No
Signal handler
Yes
Thread
Yes
See also:
link()
534
QNX Neutrino Functions and Macros
June 19, 2012
flock()
© 2012, QNX Software Systems Limited
Apply or remove an advisory lock on an open file
Synopsis:
#include <fcntl.h>
int flock( int filedes,
int operation );
Arguments:
filedes
The file descriptor of an open file.
operation
What you want to do to the file; see below.
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
The flock() function applies or removes an advisory lock on the file associated with the
open file descriptor filedes. To establish a lock with this function, open with write-only
permission (O_WRONLY) or with read/write permission (O_RDWR).
A lock is applied by specifying one of the following values for operation:
LOCK_EX
Exclusive lock.
LOCK_NB
Don’t block when locking. This may be ORed with LOCK_EX or
LOCK_SH to give nonblocking behavior.
LOCK_SH
Shared lock.
LOCK_UN
Unlock an existing lock operation.
Advisory locks allow cooperating processes to perform consistent operations on files,
but they don’t guarantee consistency.
The locking mechanism allows two types of locks: shared and exclusive. At any time,
multiple shared locks may be applied to a file, but at no time are multiple exclusive, or
both shared and exclusive, locks allowed simultaneously on a file.
A shared lock may be upgraded to an exclusive lock, and vice versa, by specifying the
appropriate lock type. The previous lock is released and a new lock is applied
(possibly after other processes have gained and released the lock).
Requesting a lock on an object that’s already locked causes the caller to be blocked
until the lock may be acquired. If you don’t want the caller to be blocked, you can
specify LOCK_NB in the operation to fail the call (errno is set to EWOULDBLOCK).
June 19, 2012
QNX Neutrino Functions and Macros
535
flock()
© 2012, QNX Software Systems Limited
Locks are applied to files, not file descriptors. That is, file descriptors duplicated
through dup() or fork() don’t result in multiple instances of a lock, but rather multiple
references to a single lock. If a process holding a lock on a file forks and the child
explicitly unlocks the file, the parent loses its lock.
Processes blocked awaiting a lock may be awakened by signals.
Returns:
0
The operation was successful.
-1
An error occurred (errno is set).
Errors:
EBADF
Invalid descriptor, filedes.
EINVAL
The argument operation doesn’t include one of LOCK_EX,
LOCK_SH, or LOCK_UN.
ENOMEM
The system can’t allocate sufficient memory to store lock
resources.
ENOSYS
The filesystem doesn’t support the operation.
EOPNOTSUPP
The filedes argument refers to an object other than a file.
EWOULDBLOCK
The file is locked and LOCK_NB was specified.
Classification:
Unix
Safety
536
Cancellation point
No
Interrupt handler
No
Signal handler
Yes
Thread
Yes
QNX Neutrino Functions and Macros
June 19, 2012
© 2012, QNX Software Systems Limited
flock()
See also:
fcntl(), lockf(), open()
June 19, 2012
QNX Neutrino Functions and Macros
537
flockfile()
© 2012, QNX Software Systems Limited
Acquire ownership of a file
Synopsis:
#include <stdio.h>
void flockfile( FILE* file );
Arguments:
file
A pointer to the FILE object for the file you want to lock.
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
The flockfile() function provides for explicit application-level locking of stdio (FILE)
objects. This function can be used by a thread to delineate a sequence of I/O
statements that are to be executed as a unit.
The flockfile() function is used by a thread to acquire ownership of a FILE. The
ftrylockfile() function is a nonblocking version of flockfile(). To unlock the file, call
funlockfile().
The implementation acts as if there is a lock count associated with each FILE. This
count is implicitly initialized to zero when the FILE is created. The FILE object is
unlocked when the count is zero. When the count is positive, a single thread owns the
FILE. When the flockfile() function is called, if the count is zero or if the count is
positive and the caller owns the FILE, the count is incremented. Otherwise, the calling
thread is suspended, waiting for the count to return to zero.
Classification:
POSIX 1003.1 TSF
Safety
538
Cancellation point
No
Interrupt handler
No
Signal handler
No
Thread
Yes
QNX Neutrino Functions and Macros
June 19, 2012
© 2012, QNX Software Systems Limited
flockfile()
See also:
ftrylockfile(), funlockfile(), getc_unlocked(), getchar_unlocked(), putc_unlocked(),
putchar_unlocked()
June 19, 2012
QNX Neutrino Functions and Macros
539
floor(), floorf()
© 2012, QNX Software Systems Limited
Round down a value to the next integer
Synopsis:
#include <math.h>
double floor( double x );
float floorf( float x );
Arguments:
x
The value you want to round.
Library:
libm
Use the -l m option to qcc to link against this library.
Description:
These functions compute the largest integer ≤ x (rounding towards the “floor”).
Returns:
The largest integer ≤ x.
If an error occurs, these functions return 0, but this is also a valid mathematical result.
If you want to check for errors, set errno to 0, call the function, and then check errno
again. These functions don’t change errno if no errors occurred.
Examples:
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
int main( void )
{
printf( "%f\n",
printf( "%f\n",
printf( "%f\n",
printf( "%f\n",
printf( "%f\n",
floor(
floor(
floor(
floor(
floor(
-3.14 ) );
-3. ) );
0. ) );
3.14 ) );
3. ) );
return EXIT_SUCCESS;
}
produces the output:
-4.000000
-3.000000
0.000000
3.000000
3.000000
540
QNX Neutrino Functions and Macros
June 19, 2012
floor(), floorf()
© 2012, QNX Software Systems Limited
Classification:
ANSI, POSIX 1003.1
Safety
Cancellation point
No
Interrupt handler
No
Signal handler
No
Thread
Yes
See also:
ceil(), fmod(), round()
June 19, 2012
QNX Neutrino Functions and Macros
541
flushall()
© 2012, QNX Software Systems Limited
Flush all input/output buffers
Synopsis:
#include <stdio.h>
int flushall( void );
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
The flushall() function flushes all buffers associated with open input/output streams. A
subsequent read operation on an input stream reads new data from the associated
stream.
Calling the flushall() function is equivalent to calling fflush() for all open streams.
Returns:
0
Success.
-1
An error occurred (errno is set).
Classification:
QNX 4
Safety
Cancellation point
Yes
Interrupt handler
No
Signal handler
No
Thread
Yes
Caveats:
The QNX 4 version of this function returns the number of streams flushed.
See also:
errno, fopen(), fflush()
542
QNX Neutrino Functions and Macros
June 19, 2012
fmod(), fmodf(), fmodl()
© 2012, QNX Software Systems Limited
Compute a residue, using floating-point modular arithmetic
Synopsis:
#include <math.h>
double fmod( double x,
double y );
float fmodf( float x,
float y );
long double fmodl( long double x,
long double y );
Arguments:
x
An arbitrary number.
y
The modulus.
Library:
libm
Use the -l m option to qcc to link against this library.
Description:
The fmod() and fmodf() functions compute the floating-point residue of x (mod y),
which is the remainder of x ÷ y, even if the quotient x ÷ y isn’t representable.
Returns:
The residue, x - (i × y), for some integer i such that, if y is nonzero, the result has the
same sign as x and a magnitude less than the magnitude of y.
For a correct value that would cause an underflow, these functions return 0.0. The
return value when y is zero is NaN. The return value when x is infinite is NaN.
If an error occurs, these functions return 0, but this is also a valid mathematical result.
If you want to check for errors, set errno to 0, call the function, and then check errno
again. These functions don’t change errno if no errors occurred.
Examples:
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
int main( void )
{
June 19, 2012
QNX Neutrino Functions and Macros
543
fmod(), fmodf(), fmodl()
printf(
printf(
printf(
printf(
"%f\n",
"%f\n",
"%f\n",
"%f\n",
© 2012, QNX Software Systems Limited
fmod( 4.5, 2.0 )
fmod( -4.5, 2.0 )
fmod( 4.5, -2.0 )
fmod( -4.5, -2.0 )
);
);
);
);
return EXIT_SUCCESS;
}
produces the output:
0.500000
-0.500000
0.500000
-0.500000
Classification:
ANSI, POSIX 1003.1
Safety
Cancellation point
No
Interrupt handler
No
Signal handler
No
Thread
Yes
See also:
ceil(), div(), fabs(), floor(), round()
544
QNX Neutrino Functions and Macros
June 19, 2012
fnmatch()
© 2012, QNX Software Systems Limited
Check to see if a file or path name matches a pattern
Synopsis:
#include <fnmatch.h>
int fnmatch( const char* pat,
const char* str,
int flags );
Arguments:
pat
The pattern to match; see “Pattern Matching Special Characters,” below.
str
The string to match against the pattern.
flags
Flags that modify interpretation of pat and str; a bitwise inclusive OR of
these bits:
FNM_PATHNAME
If this is set, a slash character in str is explicitly
matched by a slash in pat; it isn’t matched by either the
asterisk or question mark special characters, or by a
bracket expression.
FNM_PERIOD
If this is set, a leading period in str matches a period in
pat, where the definition of “leading” depends on
FNM_PATHNAME:
• If FNM_PATHNAME is set, a period is leading if it’s
the first character in str, or if it immediately follows
a slash.
• If FNM_PATHNAME isn’t set, a period is leading
only if it’s the first character in str.
FNM_QUOTE
If this isn’t set, a backslash (\) in pat followed by
another character matches that second character. If
FNM_QUOTE is set, a backslash is treated as an
ordinary character.
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
The fnmatch() function checks the file or path name specified by the str argument to
see if it matches the pattern specified by the pat argument.
June 19, 2012
QNX Neutrino Functions and Macros
545
fnmatch()
© 2012, QNX Software Systems Limited
Pattern Matching Special Characters
A pattern-matching special character that is quoted is a pattern that matches the
special character itself. When not quoted, such special characters have special
meaning in the specification of patterns. The pattern-matching special characters and
the contexts in which they have their special meaning are as follows:
?
Matches any printable or nonprintable collating element except
<newline>.
*
Matches any string, including the null string.
[bracket_expr]
Matches a single collating element as per Regular Expression
Bracket Expressions (1003.2 2.9.1.2) except that:
• The exclamation point character (!) replaces the circumflex
character (ˆ) in its role as a nonmatching list in the regular
expression notation.
• The backslash is used as an escape character within bracket
expressions.
The ?, * and [ characters aren’t special when used inside a
bracket expression.
The concatenation of patterns matching a single character is a valid pattern that
matches the concatenation of the single characters or collating elements matched by
each of the concatenated patterns. For example, the pattern a[bc] matches the strings
ab and ac.
The concatenation of one or more patterns matching a single character with one or
more asterisks (*) is a valid pattern. In such patterns, each asterisk matches a string of
zero or more characters, up to the first character that matches the character following
the asterisk in the pattern. For example, the pattern a*d matches the strings ad, abd,
and abcd, but not the string abc.
When an asterisk is the first or last character in a pattern, it matches zero or more
characters that precede or follow the characters matched by the remainder of the
pattern. For example, the pattern a*d* matches the strings ad, abcd, abcdef, aaaad
and adddd; the pattern *a*d matches the strings ad, abcd, efabcd, aaaad and
adddd.
Returns:
546
0
The str argument matches the pattern specified by pat.
Nonzero
The str argument doesn’t match the pattern specified by pat.
QNX Neutrino Functions and Macros
June 19, 2012
fnmatch()
© 2012, QNX Software Systems Limited
Examples:
/*
* The following example accepts a set of patterns
* for filenames as argv[1..argc]. It reads lines
* from standard input, and outputs the lines that
* match any of the patterns.
*/
#include <stdio.h>
#include <fnmatch.h>
#include <stdlib.h>
#include <limits.h>
int main( int argc, char **argv )
{
int i;
char buffer[PATH_MAX+1];
while( gets( buffer ) ) {
for( i = 0; i < argc; i++ ) {
if( fnmatch( argv[i], buffer, 0 ) == 0 ) {
puts( buffer );
break;
}
}
}
exit( EXIT_SUCCESS );
}
Classification:
POSIX 1003.1
Safety
Cancellation point
No
Interrupt handler
No
Signal handler
Yes
Thread
Yes
See also:
regcomp()
June 19, 2012
QNX Neutrino Functions and Macros
547
fopen(), fopen64()
© 2012, QNX Software Systems Limited
Open a file stream
Synopsis:
#include <stdio.h>
FILE * fopen( const char * filename,
const char * mode );
FILE * fopen64( const char * filename,
const char * mode );
Arguments:
filename
The name of the file that you want to open.
mode
The access mode; see below.
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
The fopen() and fopen64() functions open a file stream for the file specified by
filename. The mode string begins with one of the following sequences:
a
Append: create a new file or open the file for writing at its end.
a+
Append: open the file or create it for update, writing at end-of-file; use the
default file translation.
r
Open the file for reading.
r+
Open the file for update (reading and/or writing); use the default file
translation.
w
Create the file for writing, or truncate it to zero length.
w+
Create the file for update, or truncate it to zero length; use the default file
translation.
You can add the letter b to the end of any of the above sequences to indicate that the
file is (or must be) a binary file (this is an ANSI requirement for portability to systems
that make a distinction between text and binary files, such as DOS). Under QNX
Neutrino, there’s no difference between text files and binary files.
• Opening a file in read mode (r in the mode) fails if the file doesn’t exist or can’t be
read.
548
QNX Neutrino Functions and Macros
June 19, 2012
© 2012, QNX Software Systems Limited
fopen(), fopen64()
• Opening a file in append mode (a in the mode) causes all subsequent writes to the
file to be forced to the current end-of-file, regardless of previous calls to the fseek()
function.
• When a file is opened with update mode (+ in the mode), both input and output may
be performed on the associated stream.
When using a stream in update mode, writing can’t be followed by reading without an
intervening call to fflush(), or to a file-positioning function (fseek(), fsetpos() or
rewind()). Similarly, reading can’t be followed by writing without an intervening call
to a file-positioning function, unless the read resulted in end-of-file.
The largest value that can be represented correctly in an object of type off_t shall be
established as the offset maximum in the open file description.
Returns:
A pointer to a file stream for success, or NULL if an error occurs (errno is set).
Errors:
EACCES
Search permission is denied on a component of the filename prefix,
or the file exists and the permissions specified by mode are denied,
or the file doesn’t exist and write permission is denied for the
parent directory of the file to be created.
EBADFSYS
While attempting to open the named file, either the file itself or a
component of the filename prefix was found to be corrupted. A
system failure — from which no automatic recovery is possible —
occurred while the file was being written to, or while the directory
was being updated. You’ll need to invoke appropriate
systems-administration procedures to correct this situation before
proceeding.
EBUSY
File access was denied due to a conflicting open (see sopen()).
EINTR
The fopen() operation was interrupted by a signal.
EINVAL
The value of the mode argument is not valid.
EISDIR
The named file is a directory, and the mode argument specifies
write-only or read/write access.
ELOOP
Too many levels of symbolic links or prefixes.
EMFILE
Too many file descriptors are currently in use by this process.
ENAMETOOLONG
The length of the filename string exceeds PATH_MAX, or a
pathname component is longer than NAME_MAX.
June 19, 2012
QNX Neutrino Functions and Macros
549
fopen(), fopen64()
© 2012, QNX Software Systems Limited
ENFILE
ENOENT
Too many files are currently open in the system.
Either the named file or the filename prefix doesn’t exist, or the
filename argument points to an empty string.
ENOMEM
There isn’t enough memory for the FILE structure.
ENOSPC
The directory or filesystem that would contain the new file can’t be
extended.
ENOSYS
The fopen() function isn’t implemented for the filesystem specified
in filename.
ENOTDIR
A component of the filename prefix isn’t a directory.
ENXIO
The media associated with the file has been removed (e.g. CD,
floppy).
EOVERFLOW
The named file is a regular file and the size of the file can’t be
represented correctly in an object of type off_t.
EROFS
The named file resides on a read-only filesystem.
Examples:
#include <stdio.h>
#include <stdlib.h>
int main( void )
{
FILE *fp;
fp = fopen( "report.dat", "r" );
if( fp != NULL ) {
/* rest of code goes here */
fclose( fp );
return EXIT_SUCCESS;
}
return EXIT_FAILURE;
}
Classification:
fopen() is ANSI, POSIX 1003.1; fopen64() is Large-file support
Safety
550
Cancellation point
Yes
Interrupt handler
No
Signal handler
No
Thread
Yes
QNX Neutrino Functions and Macros
June 19, 2012
© 2012, QNX Software Systems Limited
fopen(), fopen64()
See also:
errno, fclose(), fcloseall(), fdopen(), freopen(), freopen64()
June 19, 2012
QNX Neutrino Functions and Macros
551
fork()
© 2012, QNX Software Systems Limited
Create a new process
Synopsis:
#include <sys/types.h>
#include <process.h>
pid_t fork( void );
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
The fork() function creates a new process. The new process (child process) is an exact
copy of the calling process (parent process), except for the following:
• The child process has a unique process ID.
• The child process has a different parent process ID (which is the process ID of the
calling process).
• The child process has its own copy of the parent’s file descriptors. Each of the
child’s file descriptors refers to the same open file description with the
corresponding file descriptor of the parent.
• The child process has its own copy of the parent’s open directory streams.
• The child process’s values of tms_utime, tms_stime, tms_cutime, and tms_cstime
are set to zero.
• File locks previously set by the parent aren’t inherited by the child.
• Pending alarms are cleared for the child process.
• The set of signals pending for the child process is initialized to the empty set.
• The child process doesn’t inherit any memory locks that the parent set. For more
information, see “Locking memory” in the Process Manager chapter of the System
Architecture guide.
Returns:
A value of zero to the child process; and the process ID of the child process to the
parent process. Both processes continue to execute from the fork() function. If an error
occurs, fork() returns -1 to the parent and sets errno.
552
QNX Neutrino Functions and Macros
June 19, 2012
fork()
© 2012, QNX Software Systems Limited
Errors:
EAGAIN
Insufficient resources are available to create the child process. For
example, you might have exceeded the maximum number of processes
permitted; see the RLIMIT_NPROC resource for getrlimit().
ENOMEM
The process requires more memory than the system is able to supply.
ENOSYS
The fork() function isn’t implemented for this memory protection
model. See also “Caveats,” below.
Examples:
/*
* This program executes the program and arguments
* specified by argv[1..argc]. The standard input
* of the executed program is converted to upper
* case.
*/
#include
#include
#include
#include
#include
#include
int main(
{
pid_t
pid_t
int
char
int
int
<stdio.h>
<stdlib.h>
<unistd.h>
<ctype.h>
<process.h>
<sys/wait.h>
int argc, char **argv )
pid;
wpid;
fd[2];
buffer[80];
i, len;
status;
if( pipe( fd ) == -1 ) {
perror( "pipe" );
return EXIT_FAILURE;
}
if( ( pid = fork() ) == -1 ) {
perror( "fork" );
return EXIT_FAILURE;
}
if( pid == 0 ) {
/* This is the child process.
* Move read end of the pipe to stdin ( 0 ),
* close any extraneous file descriptors,
* then use exec to ’become’ the command.
*/
dup2( fd[0], 0 );
close( fd[1] );
execvp( argv[1], argv+1 );
/* This can only happen if exec fails; print message
* and exit.
*/
perror( argv[1] );
return EXIT_FAILURE;
June 19, 2012
QNX Neutrino Functions and Macros
553
fork()
© 2012, QNX Software Systems Limited
} else {
/* This is the parent process.
* Remove extraneous file descriptors,
* read descriptor 0, write into pipe,
* close pipe, and wait for child to die.
*/
close( fd[0] );
while( ( len = read( 0, buffer, sizeof( buffer ) )
) > 0 ) {
for( i = 0; i < len; i++ ) {
if( isupper( buffer[i] ) )
buffer[i] = tolower( buffer[i] );
}
write( fd[1], buffer, len );
}
close( fd[1] );
do {
wpid = waitpid( pid, &status, 0 );
} while( WIFEXITED( status ) == 0 );
return WEXITSTATUS( status );
}
}
Classification:
POSIX 1003.1
Safety
Cancellation point
No
Interrupt handler
No
Signal handler
Yes
Thread
Yes
Caveats:
Currently, fork() is supported only in single-threaded applications. If you create a
thread and then call fork(), the function returns -1 and sets errno to ENOSYS.
See also:
errno, execl(), execle(), execlp(), execlpe(), execv(), execve(), execvp(), execvpe(),
spawn(), spawnl(), spawnle(), spawnlp(), spawnlpe(), spawnp(), spawnv(), spawnve(),
spawnvp(), spawnvpe(), wait()
Processes and Threads chapter of Getting Started with QNX Neutrino
554
QNX Neutrino Functions and Macros
June 19, 2012
forkpty()
© 2012, QNX Software Systems Limited
Create a new process operating in a pseudo-tty
Synopsis:
#include <unix.h>
pid_t forkpty( int *amaster,
char *name,
struct termios *termp,
struct winsize *winp );
Arguments:
amaster
A pointer to a location where forkpty() can store the file descriptor of the
master side of the pseudo-tty.
name
NULL, or a pointer to a buffer where forkpty() can store the filename of
the slave side of the pseudo-tty.
termp
NULL, or a pointer to a termios structure that describes the terminal’s
control attributes to apply to the slave side of the pseudo-tty.
winp
A pointer to a winsize structure that defines the window size to use for
the slave side of the pseudo-tty.
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
This function is in libc.a, but not in libc.so (in order to save space).
Description:
The forkpty() function combines openpty(), fork(), and login_tty() to create a new
process operating in a pseudo-tty.
This function fails if either openpty() or fork() fails.
Returns:
0 to the child process, the child’s process ID to the parent, or -1 if an error occurred.
Classification:
Unix
June 19, 2012
QNX Neutrino Functions and Macros
555
forkpty()
© 2012, QNX Software Systems Limited
Safety
Cancellation point
Yes
Interrupt handler
No
Signal handler
Yes
Thread
Yes
See also:
fork(), login_tty(), openpty(), termios
556
QNX Neutrino Functions and Macros
June 19, 2012
fp_exception_mask()
© 2012, QNX Software Systems Limited
Get or set the current exception mask
Synopsis:
#include <fpstatus.h>
int fp_exception_mask ( int new_mask,
int set );
Arguments:
new_mask
The new mask to apply. The bits include:
• _FP_EXC_INVALID
• _FP_EXC_DIVZERO
• _FP_EXC_OVERFLOW
• _FP_EXC_UNDERFLOW
• _FP_EXC_INEXACT
• _FP_EXC_DENORMAL
set
A value that indicates what you want the function to do:
• If set < 0, return the current mask. The new_mask argument is
ignored.
• If set = 0, disable the bits in the exception mask that correspond to
the bits set in new_mask.
• If set > 0, enable the bits in the exception mask that correspond to
the bits set in new_mask.
Library:
libm
Use the -l m option to qcc to link against this library.
Description:
The fp_exception_mask() function gets or sets the current exception mask, depending
on the value of the set argument.
Returns:
June 19, 2012
If set < 0
The current exception mask.
If set ≥ 0
The previous mask.
QNX Neutrino Functions and Macros
557
fp_exception_mask()
© 2012, QNX Software Systems Limited
This function doesn’t return a special value to indicate that an error occurred. If you
want to check for errors, set errno to 0, call the function, and then check errno again.
Examples:
#include <fpstatus.h>
int main(int argc, char** argv)
{
int ret;
if ((ret = fp_exception_mask(0, -1)) < 0)
printf("*** Problem retrieving exceptions \n");
printf("Exceptions Enabled: \n\t");
if (ret & _FP_EXC_INEXACT)
printf("Inexact ");
if (ret & _FP_EXC_DIVZERO)
printf("DivZero ");
if (ret & _FP_EXC_UNDERFLOW)
printf("Underflow ");
if (ret & _FP_EXC_OVERFLOW)
printf("Overflow ");
if (ret & _FP_EXC_INVALID)
printf("Invalid ");
printf("\n");
/* Set the exception mask to enable division by zero errors */
if ((ret = fp_exception_mask(_FP_EXC_DIVZERO, 1)) < 0)
printf("*** Problem setting exceptions \n");
if ((ret = fp_exception_mask(0, -1)) < 0)
printf("*** Problem retrieving exceptions \n");
printf("Exceptions Enabled: \n\t");
if (ret & _FP_EXC_INEXACT)
printf("Inexact ");
if (ret & _FP_EXC_DIVZERO)
printf("DivZero ");
if (ret & _FP_EXC_UNDERFLOW)
printf("Underflow ");
if (ret & _FP_EXC_OVERFLOW)
printf("Overflow ");
if (ret & _FP_EXC_INVALID)
printf("Invalid ");
printf("\n");
return(0);
}
Classification:
QNX Neutrino
Safety
Cancellation point
No
continued. . .
558
QNX Neutrino Functions and Macros
June 19, 2012
fp_exception_mask()
© 2012, QNX Software Systems Limited
Safety
Interrupt handler
No
Signal handler
No
Thread
Yes
See also:
fp_exception_value(), fp_precision(), fp_rounding(), fp_setenv()
June 19, 2012
QNX Neutrino Functions and Macros
559
fp_exception_value()
© 2012, QNX Software Systems Limited
Get the value of the current exception registers
Synopsis:
#include <fpstatus.h>
int fp_exception_value( int mask );
Arguments:
mask
A mask whose bits indicate which registers you want the value of. The bits
include:
• _FP_EXC_INVALID
• _FP_EXC_DIVZERO
• _FP_EXC_OVERFLOW
• _FP_EXC_UNDERFLOW
• _FP_EXC_INEXACT
• _FP_EXC_DENORMAL
Library:
libm
Use the -l m option to qcc to link against this library.
Description:
The fp_exception_value() function gets the value of the current exception registers.
Set bits indicate that the exception has signaled, unset bits indicate that the exception
hasn’t signaled.
Returns:
The value of the current exception registers based on the values from <fpstatus.h>.
This function doesn’t return a special value to indicate that an error occurred. If you
want to check for errors, set errno to 0, call the function, and then check errno again.
Examples:
#include <fpstatus.h>
int main(int argc, char** argv)
{
int ret;
/* Test to see if an operation has set (but not necessarily
* signaled depending on the exception mask) the
* division by zero bit:
*/
if (fp_exception_value(_FP_EXC_DIVZERO) & _FP_EXC_DIVZERO)
printf("Division by zero has occurred \n");
560
QNX Neutrino Functions and Macros
June 19, 2012
fp_exception_value()
© 2012, QNX Software Systems Limited
else
printf("Division by zero has not occurred \n");
return(0);
}
Classification:
QNX Neutrino
Safety
Cancellation point
No
Interrupt handler
No
Signal handler
No
Thread
Yes
See also:
fp_precision(), fp_rounding(), fp_exception_mask(), fp_setenv()
June 19, 2012
QNX Neutrino Functions and Macros
561
fp_precision()
© 2012, QNX Software Systems Limited
Set or get the current precision
Synopsis:
#include <fpstatus.h>
int fp_precision( int newprecision );
Arguments:
newprecision
The new precision; one of:
• < 0 — return the current setting.
• _FP_PREC_FLOAT
• _FP_PREC_DOUBLE
• _FP_PREC_EXTENDED
• _FP_PREC_DOUBLE_EXTENDED
Library:
libm
Use the -l m option to qcc to link against this library.
Description:
The fp_precision() function sets or gets the current floating-point precision, depending
on the value of newprecision.
Returns:
If newprecision is less than 0, the current precision; otherwise, the previous precision.
This function doesn’t return a special value to indicate that an error occurred. If you
want to check for errors, set errno to 0, call the function, and then check errno again.
Examples:
#include <fpstatus.h>
int main(int argc, char** argv)
{
int ret;
ret = fp_precision(-1);
printf("Precision: ");
if (ret == _FP_PREC_FLOAT)
printf("Float \n");
else if (ret == _FP_PREC_DOUBLE)
printf("Double \n");
else if (ret == _FP_PREC_EXTENDED)
printf("Extended \n");
else if (ret == _FP_PREC_DOUBLE_EXTENDED)
printf("128 Bit \n");
else if (ret == _FP_PREC_EXTENDED)
562
QNX Neutrino Functions and Macros
June 19, 2012
fp_precision()
© 2012, QNX Software Systems Limited
printf("Extended \n");
else if (ret == _FP_PREC_DOUBLE_EXTENDED)
printf("128 Bit \n");
else
printf("Error \n");
return(0);
}
Classification:
QNX Neutrino
Safety
Cancellation point
No
Interrupt handler
No
Signal handler
No
Thread
Yes
See also:
fp_exception_mask(), fp_exception_value(), fp_rounding(), fp_setenv()
June 19, 2012
QNX Neutrino Functions and Macros
563
fp_rounding()
© 2012, QNX Software Systems Limited
Set or get the current rounding
Synopsis:
#include <fpstatus.h>
int fp_rounding( int newrounding );
Arguments:
newrounding
The new rounding; one of:
• < 0 — return the current setting.
• _FP_ROUND_NEAREST
• _FP_ROUND_ZERO
• _FP_ROUND_POSITIVE
• _FP_ROUND_NEGATIVE
Library:
libm
Use the -l m option to qcc to link against this library.
Description:
The fp_rounding() function sets or gets the current rounding mode, depending on the
value of newrounding.
Returns:
If newrounding is less than 0, the current rounding mode; otherwise, the previous
mode.
This function doesn’t return a special value to indicate that an error occurred. If you
want to check for errors, set errno to 0, call the function, and then check errno again.
Examples:
#include <fpstatus.h>
#include <stdlib.h>
#include <stdio.h>
int main(int argc, char** argv)
{
int ret;
ret = fp_rounding(-1);
printf("Rounding mode: ");
if (ret == _FP_ROUND_NEAREST)
printf("Nearest \n");
else if (ret == _FP_ROUND_POSITIVE)
printf("Positive \n");
else if (ret == _FP_ROUND_NEGATIVE)
printf("Negative \n");
564
QNX Neutrino Functions and Macros
June 19, 2012
fp_rounding()
© 2012, QNX Software Systems Limited
else if (ret == _FP_ROUND_ZERO)
printf("To Zero \n");
else
printf("Error \n");
return EXIT_SUCCESS;
}
Classification:
QNX Neutrino
Safety
Cancellation point
No
Interrupt handler
No
Signal handler
No
Thread
Yes
See also:
fp_exception_mask(), fp_exception_value(), fp_precision(), fp_setenv()
June 19, 2012
QNX Neutrino Functions and Macros
565
fp_setenv()
© 2012, QNX Software Systems Limited
Set the floating point environment
Synopsis:
#include <fpstatus.h>
void fp_setenv( int rounding
int flags
int fmask
int exc
int emask);
Arguments:
exc
Modify the thread’s exception mask. This parameter is analogous with
flags.
emask
Modify the thread’s exception mask. This parameter is analogous with
fmask. This is the same mask that’s manipulated by the
fp_exception_mask() function.
flags
Describe the sticky exception flags that are set or cleared. For each flag
that’s set in fmask, the corresponding sticky exception flag of the thread
is set if that flag is also set in flags; otherwise, it’s cleared. Sticky
exception flags for which the corresponding flag isn’t set in fmask are
unchanged.
fmask
Describes the sticky exception flags that are set or cleared. For each flag
that’s set in fmask, the corresponding sticky exception flag of the thread
is set if that flag is also set in flags; otherwise, it’s cleared. Sticky
exception flags for which the corresponding flag isn’t set in fmask are
unchanged.
rounding
The rounding mode. You can use -1 for unchanged. The rounding
parameter is treated exactly as for the fp_rounding() function.
Library:
libm
Use the -l m option to qcc to link against this library.
Description:
Currently the fp_setenv() function is defined only for PPC (both SPE and non-SPE); it
isn’t defined for other architectures.
The fp_setenv() function is basically a combination of the functions fp_rounding() and
fp_exception_mask() along with additional functionality. The fp_setenv() function
permits:
• the calling thread to set its floating point rounding mode
• a change its set of currently set sticky exception flags
566
QNX Neutrino Functions and Macros
June 19, 2012
fp_setenv()
© 2012, QNX Software Systems Limited
• a change its set of enabled exceptions.
For all of the above situations, only the calling thread is affected.
The parameters flags, fmask, exc, and emaskall represent sets of flags. The flags are
exactly the same as those described for the new_mask parameter of
fp_exception_mask():
• _FP_EXC_INVALID
• _FP_EXC_DIVZERO
• _FP_EXC_OVERFLOW
• _FP_EXC_UNDERFLOW
• _FP_EXC_INEXACT
• _FP_EXC_DENORMAL
After fp_setenv() is called (directly or indirectly), exceptions that aren’t masked will
result in SIGFPE being delivered to the thread whenever the corresponding exception
occurs. Regardless of whether an exception was masked, the corresponding sticky
exception flag is set whenever the associated exception occurs. Once raised, sticky
exception flags remain raised until they’re cleared by the application thread.
Returns:
This function doesn’t return any value. There is no error indication.
Examples:
Clear all sticky flags and allow SIGFPE for divide-by-zero (only); the rounding mode
remains unchanged:
fp_setenv(-1, 0, _FP_EXC_ALL, _FP_EXC_DIVZERO, _FP_EXC_DIVZERO);
Classification:
QNX Neutrino
Safety
June 19, 2012
Cancellation point
No
Interrupt handler
No
Signal handler
No
Thread
Yes
QNX Neutrino Functions and Macros
567
fp_setenv()
© 2012, QNX Software Systems Limited
See also:
fp_exception_mask(), fp_exception_value(), fp_precision() fp_rounding()
568
QNX Neutrino Functions and Macros
June 19, 2012
fpathconf()
© 2012, QNX Software Systems Limited
Return the value of a configurable limit associated with a file
Synopsis:
#include <unistd.h>
long fpathconf( int filedes,
int name );
Arguments:
filedes
A file descriptor for the file whose limit you want to check.
name
The name of the configurable limit; see below.
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
The fpathconf() function returns a value of a configurable limit indicated by name
that’s associated with the file indicated by filedes.
Configurable limits are defined in <confname.h>, and include at least the following
values:
_PC_ASYNC_IO
Defined (not -1) if asynchronous I/O is supported for the file.
_PC_CHOWN_RESTRICTED
If defined (not -1), indicates that the use of the chown()
function is restricted to a process with appropriate privileges,
and to changing the group ID of a file to the effective group ID
of the process or to one of its supplementary group IDs.
June 19, 2012
_PC_LINK_DIR
Defined (not -1) if the filesystem permits the unlinking of a
directory.
_PC_LINK_MAX
Maximum value of a file’s link count.
_PC_MAX_CANON
Maximum number of bytes in a terminal’s canonical input
buffer (edit buffer).
_PC_MAX_INPUT
Maximum number of bytes in a terminal’s raw input buffer.
_PC_NAME_MAX
Maximum number of bytes in a file name (not including the
terminating null).
_PC_NO_TRUNC
If defined (not -1), indicates that the use of pathname
components longer than the value given by _PC_NAME_MAX
generates an error.
QNX Neutrino Functions and Macros
569
fpathconf()
© 2012, QNX Software Systems Limited
_PC_PATH_MAX
_PC_PIPE_BUF
Maximum number of bytes in a pathname (not including the
terminating null).
Maximum number of bytes that can be written atomically when
writing to a pipe.
_PC_PRIO_IO
Defined (not -1) if prioritized I/O is supported for the file.
_PC_SYNC_IO
Defined (not -1) if synchronous I/O is supported for the file.
_PC_VDISABLE
If defined (not -1), this is the character value that can be used to
individually disable special control characters in the termios
control structure.
Returns:
The requested configurable limit, or -1 if an error occurred (errno is set).
Errors:
EINVAL
The name argument is invalid, or the indicated limit isn’t supported for
this filedes.
EBADF
The argument filedes is invalid.
Examples:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main()
{
long value;
value = fpathconf( 0, _PC_MAX_INPUT );
printf( "Input buffer size is %ld bytes\n",
value );
return EXIT_SUCCESS;
}
Classification:
POSIX 1003.1
Safety
570
Cancellation point
No
Interrupt handler
No
Signal handler
Yes
Thread
Yes
QNX Neutrino Functions and Macros
June 19, 2012
© 2012, QNX Software Systems Limited
fpathconf()
See also:
confstr(), pathconf(), sysconf(), termios
June 19, 2012
QNX Neutrino Functions and Macros
571
fprintf()
© 2012, QNX Software Systems Limited
Write output to a stream
Synopsis:
#include <stdio.h>
int fprintf( FILE* fp,
const char* format,
... );
Arguments:
fp
The stream to which you want to send the output.
format
A string that specifies the format of the output. The formatting string
determines what additional arguments you need to provide. For more
information, see printf().
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
The fprintf() function writes output to the stream specified by fp, under control of the
format specifier.
Returns:
The number of characters written, or a negative value if an output error occurred
(errno is set).
Examples:
#include <stdio.h>
#include <stdlib.h>
char *weekday = { "Saturday" };
char *month = { "April" };
int main( void )
{
fprintf( stdout, "%s, %s %d, %d\n",
weekday, month, 10, 1999 );
return EXIT_SUCCESS;
}
Produces:
Saturday, April 10, 1999
572
QNX Neutrino Functions and Macros
June 19, 2012
fprintf()
© 2012, QNX Software Systems Limited
Classification:
ANSI, POSIX 1003.1
Safety
Cancellation point
Yes
Interrupt handler
No
Signal handler
No
Thread
Yes
See also:
errno, fwprintf(), printf(), snprintf(), sprintf(), swprintf(), vfprintf(), vfwprintf(),
vprintf(), vsnprintf(), vsprintf(), vswprintf(), vwprintf(), wprintf()
June 19, 2012
QNX Neutrino Functions and Macros
573
fputc()
© 2012, QNX Software Systems Limited
Write a character to a stream
Synopsis:
#include <stdio.h>
int fputc( int c,
FILE* fp );
Arguments:
c
The character you want to write.
fp
The stream you want to write the character to.
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
The fputc() function writes the character specified by c, cast as (int)(unsigned
char), to the stream specified by fp.
Returns:
The character written, cast as (int)(unsigned char), or EOF if an error occurred
(errno is set).
Errors:
EAGAIN
The O_NONBLOCK flag is set for the file descriptor underlying fp, and
the process would be delayed in the write operation.
EBADF
The file descriptor underlying fp isn’t a valid file descriptor that’s open
for writing.
EFBIG
One of the following:
• An attempt was made to write a file that exceeds the maximum file
size.
• An attempt was made to write a file that exceeds the process’s file
size limit.
• The file is a regular file, and an attempt was made to write at or
beyond the offset maximum associated with the corresponding
stream.
574
EINTR
The write operation was terminated due to the receipt of a signal, and
no data was transferred.
EIO
One of the following:
QNX Neutrino Functions and Macros
June 19, 2012
fputc()
© 2012, QNX Software Systems Limited
• A physical I/O error occurred.
• The process is in a background process group attempting to write to
its controlling terminal, and either the process is ignoring or
blocking the SIGTTIN signal or the process group is orphaned.
• (QNX Neutrino extension) The filesystem resides on a removable
media device, and the media has been forcibly removed.
ENOMEM
Insufficient space is available.
ENXIO
A request was made of a nonexistent device, or the request was outside
the capabilities of the device.
ENOSPC
There was no free space remaining on the device containing the file.
EPIPE
An attempt was made to write to a pipe or FIFO that wasn’t open for
reading by any process. A SIGPIPE signal is also sent to the thread.
Examples:
#include <stdio.h>
#include <stdlib.h>
int main( void )
{
FILE *fp;
int c;
fp = fopen( "file", "r" );
if( fp != NULL ) {
while( (c = fgetc( fp )) != EOF ) {
fputc( c, stdout );
}
fclose( fp );
return EXIT_SUCCESS;
}
return EXIT_FAILURE;
}
Classification:
ANSI, POSIX 1003.1
Safety
June 19, 2012
Cancellation point
Yes
Interrupt handler
No
Signal handler
No
Thread
Yes
QNX Neutrino Functions and Macros
575
fputc()
© 2012, QNX Software Systems Limited
Caveats:
If c is negative, the value returned by this function isn’t equal to c — unless c is -1 and
an error occurred :-)
See also:
errno, fgetc(), fopen(), fprintf(), fputchar(), fputs(), putc(), putchar(), puts()
576
QNX Neutrino Functions and Macros
June 19, 2012
fputchar()
© 2012, QNX Software Systems Limited
Write a character to stdout
Synopsis:
#include <stdio.h>
int fputchar( int c );
Arguments:
c
The character you want to write.
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
The fputchar() function writes the character specified by c, cast as (int)(unsigned
char), to stdout. It’s equivalent to putchar() and to:
fputc( c, stdout );
Returns:
The character written, cast as (int)(unsigned char), or EOF if an error occurred
(errno is set).
Examples:
#include <stdio.h>
#include <stdlib.h>
int main( void )
{
FILE *fp;
int c;
fp = fopen( "file", "r" );
if( fp != NULL ) {
c = fgetc( fp );
while( c != EOF ) {
fputchar( c );
c = fgetc( fp );
}
fclose( fp );
return EXIT_SUCCESS;
}
return EXIT_FAILURE;
}
June 19, 2012
QNX Neutrino Functions and Macros
577
fputchar()
© 2012, QNX Software Systems Limited
Classification:
QNX 4
Safety
Cancellation point
Yes
Interrupt handler
No
Signal handler
No
Thread
Yes
Caveats:
If c is negative, the value returned by this function isn’t equal to c — unless c is -1 and
an error occurred :-)
See also:
errno, fgetc(), fgetchar(), fprintf(), fputc(), fputs(), putc(), putchar()
578
QNX Neutrino Functions and Macros
June 19, 2012
fputs()
© 2012, QNX Software Systems Limited
Write a string to an output stream
Synopsis:
#include <stdio.h>
int fputs( const char* buf ,
FILE* fp );
Arguments:
buf
The string you want to write.
fp
The stream you want to write the string to.
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
The fputs() function writes the character string specified by buf to the output stream
specified by fp.
The terminating NUL character isn’t written.
Returns:
A nonnegative value for success, or EOF if an error occurs (errno is set).
Examples:
#include <stdio.h>
#include <stdlib.h>
int main( void )
{
FILE *fp_in, *fp_out;
char buffer[80];
fp_in = fopen( "file", "r" );
fp_out = fopen( "outfile", "w" );
if( fp_in != NULL && fp_out != NULL) {
while( fgets( buffer, 80, fp_in ) != NULL ) {
fputs( buffer, fp_out );
}
fclose( fp_in );
fclose( fp_out );
return EXIT_SUCCESS;
}
return EXIT_FAILURE;
}
June 19, 2012
QNX Neutrino Functions and Macros
579
fputs()
© 2012, QNX Software Systems Limited
Classification:
ANSI, POSIX 1003.1
Safety
Cancellation point
Yes
Interrupt handler
No
Signal handler
No
Thread
Yes
See also:
errno, fgets(), fopen(), fprintf(), fputc(), putc(), puts()
580
QNX Neutrino Functions and Macros
June 19, 2012
fputwc()
© 2012, QNX Software Systems Limited
Write a wide character to a stream
Synopsis:
#include <wchar.h>
wint_t fputwc( wchar_t wc,
FILE * fp );
Arguments:
wc
The wide character you want to write.
fp
The stream you want to write the character to.
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
The fputwc() function writes the wide character specified by wc, cast as
(wint_t)(wchar_t), to the stream specified by fp.
Returns:
The wide character written, cast as (wint_t)(wchar_t), or WEOF if an error
occurred (errno is set).
If wc exceeds the valid wide-character range, the value returned is the wide character
written, not wc.
Errors:
EAGAIN
The O_NONBLOCK flag is set for fp and would have been blocked by
this operation.
EBADF
The stream specified by fp isn’t valid for writing.
EFBIG
The file exceeds the maximum file size, the process’s file size limit, or
the function can’t write at or beyond the offset maximum.
EINTR
A signal terminated the write operation; no data was transferred.
EIO
A physical I/O error has occurred or all of the following conditions were
met:
• The process is in the background.
• TOSTOP is set.
• The process is blocking/ignoring SIGTTOU.
June 19, 2012
QNX Neutrino Functions and Macros
581
fputwc()
© 2012, QNX Software Systems Limited
EPIPE
• The process group is orphaned.
Can’t write to pipe or FIFO because it’s closed; a SIGPIPE signal is also
sent to the thread.
Classification:
ANSI, POSIX 1003.1
Safety
Cancellation point
Yes
Interrupt handler
No
Signal handler
No
Thread
Yes
See also:
errno, fgetwc(), fgetws(), fputc(), fputws()
582
QNX Neutrino Functions and Macros
June 19, 2012
fputws()
© 2012, QNX Software Systems Limited
Write a wide-character string to an output stream
Synopsis:
#include <wchar.h>
int fputws( const wchar_t * ws,
FILE * fp );
Arguments:
buf
The wide-character string you want to write.
fp
The stream you want to write the string to.
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
The fputws() function writes the wide-character string specified by ws to the output
stream specified by fp.
The terminating NUL wide character isn’t written.
Returns:
A nonnegative value for success, or WEOF if an error occurs (errno is set).
Errors:
EAGAIN
The O_NONBLOCK flag is set for fp and would have been blocked by
this operation.
EBADF
The stream specified by fp isn’t valid for writing.
EFBIG
The file exceeds the maximum file size, the process’s file size limit, or
the function can’t write at or beyond the offset maximum.
EINTR
A signal terminated the write operation; no data was transferred.
EIO
A physical I/O error has occurred or all of the following conditions were
met:
•
•
•
•
EPIPE
June 19, 2012
The process is in the background.
TOSTOP is set.
The process is blocking/ignoring SIGTTOU.
The process group is orphaned.
Can’t write to pipe or FIFO because it’s closed; a SIGPIPE signal is also
sent to the thread.
QNX Neutrino Functions and Macros
583
fputws()
© 2012, QNX Software Systems Limited
Classification:
ANSI, POSIX 1003.1
Safety
Cancellation point
Yes
Interrupt handler
No
Signal handler
No
Thread
Yes
See also:
errno, fgetwc(), fgetws(), fputs(), fputwc() fwide()
584
QNX Neutrino Functions and Macros
June 19, 2012
fread()
© 2012, QNX Software Systems Limited
Read elements of a given size from a stream
Synopsis:
#include <stdio.h>
size_t fread( void* buf ,
size_t size,
size_t num,
FILE* fp );
Arguments:
buf
A pointer to a buffer where the function can store the elements that it reads.
size
The size of each element to read.
num
The number of elements to read.
fp
The stream from which to read the elements.
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
The fread() function reads num elements of size bytes each from the stream specified
by fp into the buffer specified by buf .
Returns:
The number of complete elements successfully read; this value may be less than the
requested number of elements.
Use the feof() and ferror() functions to determine whether the end of the file was
encountered or if an input/output error has occurred.
Errors:
If an error occurs, errno is set to indicate the type of error.
Examples:
The following example reads a simple student record containing binary data. The
student record is described by the struct student_data declaration.
#include <stdio.h>
#include <stdlib.h>
struct student_data {
int student_id;
unsigned char marks[10];
June 19, 2012
QNX Neutrino Functions and Macros
585
fread()
© 2012, QNX Software Systems Limited
};
size_t read_data( FILE *fp, struct student_data *p )
{
return( fread( p, sizeof( struct student_data ), 1, fp ) );
}
int main( void )
{
FILE *fp;
struct student_data std;
int i;
fp = fopen( "file", "r" );
if( fp != NULL ) {
while( read_data( fp, &std ) != 0 ) {
printf( "id=%d ", std.student_id );
for( i = 0; i < 10; i++ ) {
printf( "%3d ", std.marks[ i ] );
}
printf( "\n" );
}
fclose( fp );
return EXIT_SUCCESS;
}
return EXIT_FAILURE;
}
Classification:
ANSI, POSIX 1003.1
Safety
Cancellation point
Yes
Interrupt handler
No
Signal handler
No
Thread
Yes
See also:
errno, fopen(), feof(), ferror()
586
QNX Neutrino Functions and Macros
June 19, 2012
free()
© 2012, QNX Software Systems Limited
Deallocate a block of memory
Synopsis:
#include <stdlib.h>
void free( void* ptr );
Arguments:
ptr
A pointer to the block of memory that you want to free. It’s safe to call free()
with a NULL pointer.
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
The free() function deallocates the memory block specified by ptr, which was
previously returned by a call to calloc(), malloc() or realloc().
Examples:
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
int main( void )
{
char *buffer;
buffer = (char *)malloc( 80 );
if( buffer == NULL ) {
printf( "Unable to allocate memory\n" );
return EXIT_FAILURE;
} else {
/* rest of code goes here */
free( buffer );
/* deallocate buffer */
}
return EXIT_SUCCESS;
}
Classification:
ANSI, POSIX 1003.1
Safety
Cancellation point
No
continued. . .
June 19, 2012
QNX Neutrino Functions and Macros
587
free()
© 2012, QNX Software Systems Limited
Safety
Interrupt handler
No
Signal handler
No
Thread
Yes
Caveats:
Calling free() on a pointer already deallocated by a call to free() or realloc() could
corrupt the memory allocator’s data structures.
See also:
alloca(), calloc(), malloc(), realloc(), sbrk()
588
QNX Neutrino Functions and Macros
June 19, 2012
freeaddrinfo()
© 2012, QNX Software Systems Limited
Free a list of address information structures
Synopsis:
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
void freeaddrinfo( struct addrinfo * ai );
Arguments:
ai
A pointer to the addrinfo structure that’s at the beginning of the list to be
freed.
Library:
libsocket
Use the -l socket option to qcc to link against this library.
Description:
The freeaddrinfo() function frees the given list of addrinfo structures and the
dynamic storage associated with each item in the list.
Classification:
POSIX 1003.1
Safety
Cancellation point
No
Interrupt handler
No
Signal handler
No
Thread
Yes
See also:
addrinfo, gai_strerror(), getaddrinfo()
June 19, 2012
QNX Neutrino Functions and Macros
589
freeifaddrs()
© 2012, QNX Software Systems Limited
Free a network interface address
Synopsis:
#include <sys/types.h>
#include <sys/socket.h>
#include <ifaddrs.h>
void freeifaddrs( struct ifaddrs * ifap );
Arguments:
ifap
A pointer to the linked list of ifaddrs structures to be freed.
Library:
libsocket
Use the -l socket option to qcc to link against this library.
Description:
The freeifaddrs() function frees the dynamically allocated data returned by
getifaddrs().
Classification:
Unix
Safety
Cancellation point
No
Interrupt handler
No
Signal handler
No
Thread
Yes
See also:
getifaddrs(), ifaddrs, ioctl(), malloc(), socket(), sysctl()
590
QNX Neutrino Functions and Macros
June 19, 2012
freopen(), freopen64()
© 2012, QNX Software Systems Limited
Reopen a stream
Synopsis:
#include <stdio.h>
FILE* freopen( const char* filename,
const char* mode,
FILE* fp );
FILE* freopen64( const char* filename,
const char* mode,
FILE* fp );
Arguments:
filename
The name of the file to open.
mode
The mode to use when opening the file. For more information, see
fopen().
fp
The stream to associate with the file.
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
The freopen() and freopen64() functions close the open stream fp, open the file
specified by filename, and associate its stream with fp.
The largest value that can be represented correctly in an object of type off_t is the
offset maximum in the open file description.
(QNX Neutrino extension) The following mode changes are permitted:
• w to a
• a to w
• r+ to r
• r+ to w
• r+ to a
• r+ to w+
• r+ to a+
• w+ to r
June 19, 2012
QNX Neutrino Functions and Macros
591
freopen(), freopen64()
© 2012, QNX Software Systems Limited
• w+ to w
• w+ to a
• w+ to r+
• w+ to w+
• w+ to a+
• a+ to r
• a+ to w
• a+ to a
• a+ to r+
• a+ to w+
Returns:
A pointer to the newly opened stream, or NULL if an error occurs (errno is set).
Errors:
592
EACCES
Search permission is denied on a component of the filename prefix,
or the file exists and the permissions specified by mode are denied,
or the file doesn’t exist and write permission is denied for the
parent directory of the file to be created.
EBADF
The underlying file descriptor is invalid or doesn’t support the
requested mode change.
EBADFSYS
While attempting to open the named file, either the file itself or a
component of the filename prefix was found to be corrupted. A
system failure — from which no automatic recovery is possible —
occurred while the file was being written to, or while the directory
was being updated. You’ll need to invoke appropriate
systems-administration procedures to correct this situation before
proceeding.
EBUSY
File access was denied due to a conflicting open (see sopen()).
EINTR
The freopen() operation was interrupted by a signal.
EINVAL
The value of the mode argument is not valid.
EISDIR
The named file is a directory, and the mode argument specifies
write-only or read/write access.
ELOOP
Too many levels of symbolic links or prefixes.
EMFILE
Too many file descriptors are currently in use by this process.
QNX Neutrino Functions and Macros
June 19, 2012
freopen(), freopen64()
© 2012, QNX Software Systems Limited
ENAMETOOLONG
The length of the filename string exceeds PATH_MAX, or a
pathname component is longer than NAME_MAX.
ENFILE
Too many files are currently open in the system.
ENOENT
Either the named file or the filename prefix doesn’t exist, or the
filename argument points to an empty string.
ENOMEM
There is no memory for FILE structure.
ENOSPC
The directory or filesystem that would contain the new file can’t be
extended.
ENOSYS
The freopen() function isn’t implemented for the filesystem
specified in filename.
ENOTDIR
A component of the filename prefix isn’t a directory.
ENXIO
The media associated with the file has been removed (e.g. CD,
floppy).
EOVERFLOW
The named file is a regular file and the size of the file can’t be
represented correctly in an object of type off_t.
EROFS
The named file resides on a read-only filesystem.
Examples:
#include <stdio.h>
#include <stdlib.h>
int main( void )
{
FILE* fp;
int c;
/* Reopen the stdin stream so it’s reading
* from "file" instead of standard input.
*/
fp = freopen( "file", "r", stdin );
if( fp != NULL ) {
/* Now we can read from "file" using the
* stdin functions like fgetchar()...
*/
while( ( c = fgetchar() ) != EOF ) {
fputchar( c );
}
fclose( fp );
return EXIT_SUCCESS;
}
return EXIT_FAILURE;
}
June 19, 2012
QNX Neutrino Functions and Macros
593
freopen(), freopen64()
© 2012, QNX Software Systems Limited
Classification:
freopen() is ANSI, POSIX 1003.1; freopen64() is Large-file support
Safety
Cancellation point
Yes
Interrupt handler
No
Signal handler
No
Thread
Yes
See also:
errno, fclose(), fcloseall(), fdopen(), fopen(), fopen64()
594
QNX Neutrino Functions and Macros
June 19, 2012
frexp(), frexpf()
© 2012, QNX Software Systems Limited
Break a floating-point number into a normalized fraction and an integral power of 2
Synopsis:
#include <math.h>
double frexp( double value,
int* exp );
float frexpf( float value,
int* exp );
Arguments:
value
The value you want to break into a normalized fraction.
exp
A pointer to a location where the function can store the integral power of 2.
Library:
libm
Use the -l m option to qcc to link against this library.
Description:
These functions break a floating-point number into a normalized fraction and an
integral power of 2. It stores the integral power of 2 in the int pointed to by exp.
Returns:
x, such that x is a double with magnitude in the interval [0.5, 1] or 0, and value equals
x times 2 raised to the power exp. If value is 0, then both parts of the result are 0.
Examples:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main( void )
{
int expon;
double value;
value =
printf(
value =
printf(
frexp( 4.25, &expon );
"%f %d\n", value, expon );
frexp( -4.25, &expon );
"%f %d\n", value, expon );
return EXIT_SUCCESS;
}
produces the output:
0.531250 3
-0.531250 3
June 19, 2012
QNX Neutrino Functions and Macros
595
frexp(), frexpf()
© 2012, QNX Software Systems Limited
Classification:
ANSI, POSIX 1003.1
Safety
Cancellation point
No
Interrupt handler
No
Signal handler
No
Thread
Yes
See also:
ldexp(), modf()
596
QNX Neutrino Functions and Macros
June 19, 2012
fscanf()
© 2012, QNX Software Systems Limited
Scan input from a stream
Synopsis:
#include <stdio.h>
int fscanf( FILE* fp,
const char* format,
... );
Arguments:
fp
The stream that you want to read from.
format
A string that specifies the format of the input. For more information, see
scanf(). The formatting string determines what additional arguments you
need to provide.
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
The fscanf() function scans input from the stream specified by fp, under control of the
argument format.
Returns:
The number of input arguments for which values were successfully scanned and
stored, or EOF if the scanning reached the end of the input stream before storing any
values (errno is set).
Examples:
Scan a date in the form “Friday March 26 1999”:
#include <stdio.h>
#include <stdlib.h>
int main( void )
{
int day;
int year;
char weekday[10];
char month[10];
FILE *in_data;
in_data = fopen( "file", "r" );
if( in_data != NULL ) {
fscanf( in_data, "%s %s %d %d",
weekday, month, &day, &year );
printf( "Weekday=%s Month=%s Day=%d Year=%d\n",
June 19, 2012
QNX Neutrino Functions and Macros
597
fscanf()
© 2012, QNX Software Systems Limited
weekday, month, day, year );
fclose( in_data );
return EXIT_SUCCESS;
}
return EXIT_FAILURE;
}
Classification:
ANSI, POSIX 1003.1
Safety
Cancellation point
Yes
Interrupt handler
No
Signal handler
No
Thread
Yes
See also:
errno, fwscanf(), scanf(), sscanf(), swscanf(), vfscanf(), vfwscanf(), vscanf(), vsscanf(),
vswscanf(), vwscanf(), wscanf()
598
QNX Neutrino Functions and Macros
June 19, 2012
fseek(), fseeko(), fseeko64()
© 2012, QNX Software Systems Limited
Change the current position of a stream
Synopsis:
#include <stdio.h>
int fseek( FILE *fp,
long offset,
int whence );
int fseeko( FILE *fp,
off_t offset,
int whence );
int fseeko64( FILE *fp,
off64_t offset,
int whence );
Arguments:
fp
A FILE pointer returned by fopen() or freopen().
offset
The position to seek to, relative to one of the positions specified by
whence.
whence
The position from which to apply the offset; one of:
SEEK_SET
Compute the new file position relative to the start of the file.
The value of offset must not be negative.
SEEK_CUR
Compute the new file position relative to the current file
position. The value of offset may be positive, negative or
zero. A SEEK_CUR with a 0 offset is necessary when you
want to switch from reading to writing on a stream opened
for updates.
SEEK_END
Compute the new file position relative to the end of the file.
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
The fseek(), fseeko(), and fseeko64() functions change the current position of the
stream specified by fp. This position defines the character that will be read or written
by the next I/O operation on the file. The difference between these functions is the
data type of the offset argument.
These functions clear the end-of-file indicator, and undo any effects of the ungetc()
function on the stream.
June 19, 2012
QNX Neutrino Functions and Macros
599
fseek(), fseeko(), fseeko64()
© 2012, QNX Software Systems Limited
You can use ftell(), ftello(), or ftello64() to get the current position of the stream before
changing it. You can restore the position by using the value returned by one of the
ftell() functions in a subsequent call to the corresponding fseek() function with the
whence parameter set to SEEK_SET.
Returns:
0
Success
-1
An error occurred; errno is set.
Errors:
These functions fail if, either the stream is unbuffered or the stream’s buffer needed to
be flushed, and the call to fseek(), fseeko(), or fseeko64() causes an underlying lseek()
or write() to be invoked, and:
EAGAIN
The O_NONBLOCK flag is set for the file descriptor, and the
process would be delayed in the write operation.
EBADF
The file descriptor underlying the stream file isn’t open for writing,
or the stream’s buffer needed to be flushed and the file isn’t open.
EFBIG
One of the following:
• An attempt was made to write a file that exceeds the maximum
file size.
• An attempt was made to write a file that exceeds the process’s
file size limit.
• The file is a regular file, and an attempt was made to write at or
beyond the offset maximum associated with the corresponding
stream.
EINTR
The write operation was terminated due to the receipt of a signal; no
data was transferred.
EINVAL
The whence argument is invalid. The resulting file-position
indicator would be set to a negative value.
EIO
One of the following:
• A physical I/O error has occurred.
• The process is a member of a background process group
attempting to perform a write() to its controlling terminal,
TOSTOP is set, the process is neither ignoring nor blocking
SIGTTOU, and the process group of the process is orphaned.
• (QNX Neutrino extension) The filesystem resides on a
removable media device, and the media has been forcibly
removed.
600
QNX Neutrino Functions and Macros
June 19, 2012
fseek(), fseeko(), fseeko64()
© 2012, QNX Software Systems Limited
ENOSPC
There was no free space remaining on the device containing the file.
ENXIO
A request was made of a nonexistent device, or the request was
outside the capabilities of the device.
EOVERFLOW
• For fseek(), the resulting file offset would be a value that can’t be
represented correctly in an object of type long.
• For fseeko(), the resulting file offset would be a value that can’t
be represented correctly in an object of type off_t.
EPIPE
An attempt was made to write to a pipe or FIFO that isn’t open for
reading by any process; a SIGPIPE signal is also sent to the thread.
ESPIPE
The file descriptor underlying stream is associated with a pipe or
FIFO.
ENOSYS
The underlying device is incapable of seeking.
Examples:
Determine the size of a file, by saving and restoring the current position of the file:
#include <stdio.h>
#include <stdlib.h>
long filesize( FILE *fp )
{
long int save_pos;
long size_of_file;
/* Save the current position. */
save_pos = ftell( fp );
/* Jump to the end of the file. */
fseek( fp, 0L, SEEK_END );
/* Get the end position. */
size_of_file = ftell( fp );
/* Jump back to the original position. */
fseek( fp, save_pos, SEEK_SET );
return( size_of_file );
}
int main( void )
{
FILE *fp;
fp = fopen( "file", "r" );
if( fp != NULL ) {
printf( "File size=%ld\n", filesize( fp ) );
fclose( fp );
return EXIT_SUCCESS;
}
June 19, 2012
QNX Neutrino Functions and Macros
601
fseek(), fseeko(), fseeko64()
© 2012, QNX Software Systems Limited
return EXIT_FAILURE;
}
Classification:
fseek() is ANSI, POSIX 1003.1; fseeko() is POSIX 1003.1; fseeko64() is Large-file
support
Safety
Cancellation point
No
Interrupt handler
No
Signal handler
Yes
Thread
Yes
See also:
errno, fgetpos(), fopen(), fsetpos(), ftell(), ftello(), ftello64()
602
QNX Neutrino Functions and Macros
June 19, 2012
fsetpos()
© 2012, QNX Software Systems Limited
Set the current position of a file
Synopsis:
#include <stdio.h>
int fsetpos( FILE* fp,
const fpos_t* pos );
Arguments:
fp
The stream whose position you want to set.
pos
A pointer to a fpos_t object that specifies the new position for the stream.
You must have initialized the value pointed to by pos by calling fgetpos() on
the same file.
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
The fsetpos() function sets the current position of the stream specified by fp according
to the value of the fpos_t object pointed to by pos.
Returns:
0 for success, or nonzero if an error occurs (errno is set).
Errors:
EAGAIN
The O_NONBLOCK flag is set for the file descriptor, and the process
would be delayed in the write operation.
EBADF
The file descriptor underlying the stream file isn’t open for writing, or
the stream’s buffer needed to be flushed and the file isn’t open.
EFBIG
One of the following:
• An attempt was made to write a file that exceeds the maximum file
size.
• An attempt was made to write a file that exceeds the process’s file size
limit.
• The file is a regular file, and an attempt was made to write at or
beyond the offset maximum associated with the corresponding
stream.
EINTR
June 19, 2012
The write operation was terminated due to the receipt of a signal; no data
was transferred.
QNX Neutrino Functions and Macros
603
fsetpos()
© 2012, QNX Software Systems Limited
EINVAL
EIO
The whence argument is invalid. The resulting file-position indicator
would be set to a negative value.
One of the following:
• A physical I/O error has occurred.
• The process is a member of a background process group attempting to
perform a write() to its controlling terminal, TOSTOP is set, the
process is neither ignoring nor blocking SIGTTOU, and the process
group of the process is orphaned.
• (QNX Neutrino extension) The filesystem resides on a removable
media device, and the media has been forcibly removed.
ENOSPC
There was no free space remaining on the device containing the file.
ENXIO
A request was made of a nonexistent device, or the request was outside
the capabilities of the device.
ESPIPE
The file descriptor underlying stream is associated with a pipe or FIFO.
ENOSYS
The underlying device is incapable of seeking.
Examples:
See fgetpos().
Classification:
ANSI, POSIX 1003.1
Safety
Cancellation point
No
Interrupt handler
No
Signal handler
Yes
Thread
Yes
See also:
errno, fgetpos(), fopen(), fseek(), ftell()
604
QNX Neutrino Functions and Macros
June 19, 2012
fstat(), fstat64()
© 2012, QNX Software Systems Limited
Get file information, given a file description
Synopsis:
#include <sys/types.h>
#include <sys/stat.h>
int fstat( int filedes,
struct stat* buf );
int fstat64( int filedes,
struct stat64* buf );
Arguments:
filedes
The descriptor of the file that you want to get information about.
buf
A pointer to a buffer where the function can store the information about the
file.
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
The fstat() and fstat64() functions get information from the file specified by filedes and
stores it in the structure pointed to by buf .
The file <sys/stat.h> contains definitions for struct stat, as well as following
macros:
S_ISBLK(m)
Test for block special file.
S_ISCHR(m)
Test for character special file.
S_ISDIR(m)
Test for directory.
S_ISFIFO(m)
Test for FIFO.
S_ISLNK(m)
Test for symbolic link.
S_ISREG(m)
Test for regular file.
S_TYPEISMQ(buf )
Test for message queue.
S_TYPEISSEM(buf )
Test for semaphore.
S_TYPEISSHM(buf )
Test for shared memory object.
June 19, 2012
QNX Neutrino Functions and Macros
605
fstat(), fstat64()
© 2012, QNX Software Systems Limited
The arguments to the macros are:
m
The value of st_mode in a stat structure.
buf
A pointer to a stat structure.
The macros evaluate to nonzero if the test is true, and zero if the test is false.
Access permissions are specified as a combination of bits in the st_mode field of the
stat structure. These bits are defined in <sys/stat.h>. For more information, see
“Access permissions” in the documentation for stat().
The st_mode field also encodes the following bits:
S_ISUID
Set user ID on execution. The process’s effective user ID (EUID) is set
to that of the owner of the file when the file is run as a program. On a
regular file, this bit may be cleared for security reasons on any write.
S_ISGID
Set group ID on execution. Set effective group ID (EGID) on the
process to the file’s group when the file is run as a program. On a regular
file, this bit bit may be cleared for security reasons on any write.
Returns:
0
Success.
-1
An error occurred (errno is set).
Errors:
EBADF
The filedes argument isn’t a valid file descriptor.
ENOSYS
The fstat() function isn’t implemented for the filesystem specified
by filedes.
EOVERFLOW
The file size in bytes or the number of blocks allocated to the file or
the file serial number can’t be represented correctly in the structure
pointed to by buf .
Examples:
#include
#include
#include
#include
#include
#include
<stdio.h>
<sys/types.h>
<sys/stat.h>
<fcntl.h>
<unistd.h>
<stdlib.h>
int main( void )
{
int filedes;
int rc;
606
QNX Neutrino Functions and Macros
June 19, 2012
fstat(), fstat64()
© 2012, QNX Software Systems Limited
struct stat buf;
filedes = open( "file", O_RDONLY );
if( filedes != -1 ) {
rc = fstat( filedes , &buf );
if( rc != -1 ) {
printf( "File size = %d\n", buf.st_size );
}
close( filedes );
return EXIT_SUCCESS;
}
return EXIT_FAILURE;
}
Classification:
fstat() is POSIX 1003.1; fstat64() is Large-file support
Safety
Cancellation point
No
Interrupt handler
No
Signal handler
Yes
Thread
Yes
See also:
creat(), dup(), dup2(), errno, fcntl(), lstat(), open(), pipe(), sopen(), stat()
June 19, 2012
QNX Neutrino Functions and Macros
607
fstatvfs(), fstatvfs64()
© 2012, QNX Software Systems Limited
Get filesystem information, given a file descriptor
Synopsis:
#include <sys/statvfs.h>
int fstatvfs( int fildes,
struct statvfs *buf );
int fstatvfs64( int fildes,
struct statvfs64 *buf );
Arguments:
fildes
The descriptor for a file that resides on the filesystem that you want to get
information about.
buf
A pointer to a buffer where the function can store information about the
filesystem; see below.
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
The fstatvfs() function returns a “generic superblock” describing a filesystem; you can
use it to get information about mounted filesystems. The fstatvfs64() function is a
64-bit version of fstatvfs(). The statvfs() and statvfs64() functions are similar, but they
take a path name instead of a file descriptor.
The fildes argument is an open file descriptor, obtained from a successful call to
open(), creat(), dup(), fcntl(), or pipe(), for a file that resides on that filesystem. The
filesystem type is known to the operating system. Read, write, or execute permission
for the named file isn’t required.
The buf argument is a pointer to a statvfs or statvfs64 structure that’s filled by
the function. It contains at least:
unsigned long f_bsize
The preferred filesystem blocksize.
unsigned long f_frsize
The fundamental filesystem blocksize (if supported)
fsblkcnt_t f_blocks
The total number of blocks on the filesystem, in units of f_frsize.
fsblkcnt_t f_bfree
The total number of free blocks.
608
QNX Neutrino Functions and Macros
June 19, 2012
fstatvfs(), fstatvfs64()
© 2012, QNX Software Systems Limited
fsblkcnt_t f_bavail
The number of free blocks available to a nonsuperuser.
fsfilcnt_t f_files
The total number of file nodes (inodes).
fsfilcnt_t f_ffree
The total number of free file nodes.
fsfilcnt_t f_favail
The number of inodes available to a nonsuperuser.
unsigned long f_fsid
The filesystem ID (currently the device ID).
char f_basetype[16]
The type of the target filesystem, as a null-terminated string.
unsigned long f_flag
A bitmask of flags; the function can set these flags (the _MOUNT_* and ST_*
bits are equivalent):
_MOUNT_*
ST_*
_MOUNT_READONLY ST_RDONLY
Meaning
The filesystem is read-only.
_MOUNT_NOEXEC
ST_NOEXEC
The filesystem doesn’t permit the
loading of executables.
_MOUNT_NOSUID
ST_NOSUID
The filesystem doesn’t support setuid()
and setgid() semantics.
_MOUNT_NOCREAT
ST_NOCREAT You can’t create files on the filesystem.
_MOUNT_OFF32
ST_OFF32
_MOUNT_NOATIME
ST_NOATIME The filesystem doesn’t support the
The off_t type is limited to 32 bits.
logging of file access times.
unsigned long f_namemax
The maximum filename length.
The values returned for f_files, f_ffree, and f_favail depend on the filesystem:
fs-dos.so, fs-qnx4.so
These filesystems embed inodes in directories, so the number of files is
limited by the amount of disk space, so basically there’s no limit. They
don’t count the number of files created either, so they set all these fields
to 0.
June 19, 2012
QNX Neutrino Functions and Macros
609
fstatvfs(), fstatvfs64()
© 2012, QNX Software Systems Limited
fs-qnx6.so, fs-etfs-ram, fs-ext2.so
These filesystems have a fixed inodes table, so they fill in these fields.
fs-cd.so, fs-mac.so, fs-nt.so, fs-udf.so
Read-only fsystems always set f_ffree and f_favail to 0. Where possible
or known, they try to set f_files:
• fs-mac.so knows exactly
• fs-nt.so provides an upper bound based on the current size of the
Master File Table (MFT)
• fs-udf.so knows when it’s a UDF that’s mounted; ISO formats
don’t indicate that information, so f_files is set to 0
• fs-cd.so sets it to 0
fs-cifs
The CIFS filesystem sets these fields to 0.
devf-*
Flash filesystem drivers estimate the values of these fields, based on the
amount of free space.
Returns:
0
Success.
-1
An error occurred (errno is set).
Errors:
EBADF
The fildes argument isn’t an open file descriptor.
EFAULT
The buf argument points to an illegal address.
EINTR
A signal was caught during execution.
EIO
An I/O error occurred while reading the filesystem.
EOVERFLOW
One of the values to be returned can’t be represented correctly in
the structure pointed to by buf .
Classification:
fstatvfs() is POSIX 1003.1 XSI; fstatvfs64() is Large-file support
Safety
610
Cancellation point
No
Interrupt handler
No
Signal handler
Yes
Thread
Yes
QNX Neutrino Functions and Macros
June 19, 2012
© 2012, QNX Software Systems Limited
fstatvfs(), fstatvfs64()
See also:
chmod(), chown(), creat(), dup(), fcntl(), link(), mknod(), open(), pipe(), read(),
statvfs(), statvfs64(), time(), unlink(), utime(), write()
June 19, 2012
QNX Neutrino Functions and Macros
611
fsync()
© 2012, QNX Software Systems Limited
Synchronize the file state
Synopsis:
#include <unistd.h>
int fsync( int filedes );
Arguments:
filedes
The descriptor for the file that you want to synchronize.
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
The fsync() function forces all queued I/O operations for the file specified by the
filedes file descriptor to finish, synchronizing the file’s state. The function blocks until
this is finished. For more information about synchronizing, see “Filesystems and block
I/O (devb-*) drivers” in the Fine-Tuning Your System chapter of the QNX Neutrino
User’s Guide.
Although similar to fdatasync(), fsync() also guarantees the integrity of file
information such as access and modification times.
Returns:
0 for success, or -1 if an error occurs (errno is set).
Errors:
EBADF
The filedes argument isn’t a valid file descriptor open for writing.
EINVAL
The implementation doesn’t support synchronized I/O for the given file.
ENOSYS
The fsync() function isn’t supported for the filesystem specified by
filedes.
Classification:
POSIX 1003.1 FSC
Safety
Cancellation point
Yes
Interrupt handler
No
continued. . .
612
QNX Neutrino Functions and Macros
June 19, 2012
fsync()
© 2012, QNX Software Systems Limited
Safety
Signal handler
Yes
Thread
Yes
See also:
aio_fsync(), close(), fcntl(), fdatasync(), open(), read(), sync(), write()
“Filesystems and block I/O (devb-*) drivers” in the Fine-Tuning Your System
chapter of the QNX Neutrino User’s Guide
June 19, 2012
QNX Neutrino Functions and Macros
613
ftell(), ftello(), ftello64()
© 2012, QNX Software Systems Limited
Return the current position of a stream
Synopsis:
#include <stdio.h>
long int ftell( FILE* fp );
off_t ftello( FILE* fp );
off64_t ftello64( FILE* fp );
Arguments:
fp
The stream that you want to get the current position of.
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
The ftell(), ftello(), and ftello64() functions return the current position of the stream
specified by fp. This position defines the character that will be read or written by the
next I/O operation on the file. The difference between these functions is the data type
of the returned position.
You can use the value returned by an ftell() function in a subsequent call to fseek(),
fseeko(), or fseeko64() to restore the file position to a previous value.
Returns:
The current position of the file or -1L if an error occurred (errno is set).
Examples:
#include <stdio.h>
#include <stdlib.h>
long filesize( FILE *fp )
{
long int save_pos;
long size_of_file;
/* Save the current position. */
save_pos = ftell( fp );
/* Jump to the end of the file. */
fseek( fp, 0L, SEEK_END );
/* Get the end position. */
size_of_file = ftell( fp );
614
QNX Neutrino Functions and Macros
June 19, 2012
ftell(), ftello(), ftello64()
© 2012, QNX Software Systems Limited
/* Jump back to the original position. */
fseek( fp, save_pos, SEEK_SET );
return( size_of_file );
}
int main( void )
{
FILE *fp;
fp = fopen( "file", "r" );
if( fp != NULL ) {
printf( "File size=%ld\n", filesize( fp ) );
fclose( fp );
return EXIT_SUCCESS;
}
return EXIT_FAILURE;
}
Classification:
ftell() is ANSI, POSIX 1003.1; ftello() is POSIX 1003.1; ftello64() is Large-file
support
Safety
Cancellation point
Yes
Interrupt handler
No
Signal handler
No
Thread
Yes
See also:
errno, fgetpos(), fopen(), fsetpos(), fseek(), fseeko(), fseeko64()
June 19, 2012
QNX Neutrino Functions and Macros
615
ftime()
© 2012, QNX Software Systems Limited
Get the current time
Synopsis:
#include <sys/timeb.h>
int ftime( struct timeb * timeptr );
Arguments:
timeptr
A pointer to a timeb structure where the function can store the current
time; see below.
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
The ftime() function stores the current time in the timeptr structure. The timeb
structure contains the following fields:
time_t time
Time, in seconds, since the Unix Epoch, 00:00:00 January 1,
1970 Coordinated Universal Time (UTC).
unsigned short millitm
Milliseconds.
short timezone
Difference in minutes of the timezone from UTC.
short dstflag
Nonzero if in daylight savings time.
Returns:
0
Success.
-1
An error occurred (errno is set).
Examples:
#include
#include
#include
#include
<stdio.h>
<time.h>
<sys/timeb.h>
<stdlib.h>
int main( void )
{
struct timeb timebuf;
char *now;
ftime( &timebuf );
now = ctime( &timebuf.time );
616
QNX Neutrino Functions and Macros
June 19, 2012
ftime()
© 2012, QNX Software Systems Limited
/* Note that we’re cutting "now" off
* after 19 characters to avoid the
* \n that ctime() appends to the
* formatted time string.
*/
printf( "The time is %.19s.%hu\n",
now, timebuf.millitm );
return EXIT_SUCCESS;
}
Produces output similar to the following:
The time is Mon Jul 05 15:58:42.870
Classification:
POSIX 1003.1 XSI
Safety
Cancellation point
No
Interrupt handler
No
Signal handler
Yes
Thread
Yes
See also:
asctime(), clock(), ctime(), difftime(), gmtime(), localtime(), mktime(), strftime(),
time(), tzset()
June 19, 2012
QNX Neutrino Functions and Macros
617
ftruncate(), ftruncate64()
© 2012, QNX Software Systems Limited
Truncate a file
Synopsis:
#include <unistd.h>
int ftruncate( int fildes,
off_t length );
int ftruncate64( int fildes,
off64_t length );
Arguments:
fildes
The descriptor for the file that you want to truncate.
length
The length that you want the file to be, in bytes.
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
These functions cause the file referenced by fildes to have a size of length bytes. If the
size of the file previously exceeded length, the extra data is discarded (this is similar to
using the F_FREESP option with fcntl()). If the size of the file was previously shorter
than length, the file size is extended with NUL characters (similar to the F_ALLOCSP
option to fcntl()).
The value of the seek pointer isn’t modified by a call to ftruncate().
Upon successful completion, the ftruncate() function marks the st_ctime and st_mtime
fields of the file for update. If the ftruncate() function is unsuccessful, the file is
unaffected.
Returns:
Zero for success, or -1 if an error occurred (errno is set).
Errors:
618
EBADF
The fildes argument isn’t a valid file descriptor.
EFBIG
The file is a regular file and length is greater than the offset maximum
associated with the file.
EINTR
A signal was caught during the call to ftruncate().
EINVAL
The fildes argument doesn’t refer to a file on which this operation is
possible, the filedes argument isn’t open for writing or the length
argument is less than the minimum file size for the specified filesystem.
QNX Neutrino Functions and Macros
June 19, 2012
ftruncate(), ftruncate64()
© 2012, QNX Software Systems Limited
EIO
ENOMEM
An I/O error occurred while reading from or writing to the filesystem.
There wasn’t enough memory to change the size of a shared memory
object.
ENOSYS
The ftruncate() function isn’t implemented for the filesystem specified
by filedes.
ENOTSUP
The ftruncate() function is implemented for the specified filesystem,
but the specific operation (F_ALLOCSP or F_FREESP; see fcntl()) isn’t
supported.
EROFS
The file resides on a read-only filesystem.
Classification:
ftruncate() is POSIX 1003.1; ftruncate64() is Large-file support
Safety
Cancellation point
No
Interrupt handler
No
Signal handler
Yes
Thread
Yes
See also:
mmap(), open(), shm_open(), truncate()
June 19, 2012
QNX Neutrino Functions and Macros
619
ftrylockfile()
© 2012, QNX Software Systems Limited
Acquire ownership of a file, without blocking
Synopsis:
#include <stdio.h>
int ftrylockfile( FILE* file );
Arguments:
file
A pointer to the FILE object for the file you want to lock.
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
The ftrylockfile() function is used by a thread to acquire ownership of a FILE if the
object is available; ftrylockfile() is a nonblocking version of flockfile(). To unlock the
file, call funlockfile().
Returns:
0
Success.
Nonzero
The lock can’t be acquired.
Classification:
POSIX 1003.1 TSF
Safety
Cancellation point
No
Interrupt handler
No
Signal handler
Yes
Thread
Yes
See also:
flockfile(), funlockfile(), getc_unlocked(), getchar_unlocked(), putc_unlocked(),
putchar_unlocked()
620
QNX Neutrino Functions and Macros
June 19, 2012
ftw(), ftw64()
© 2012, QNX Software Systems Limited
Walk a file tree
Synopsis:
#include <ftw.h>
int ftw( const char *path,
int (*fn)( const char *fname,
const struct stat *sbuf ,
int flags),
int depth );
Arguments:
path
The path of the directory whose file tree you want to walk.
fn
A pointer to a function that you want to call for each file; see below.
depth
The maximum number of file descriptors that ftw() can use. The ftw()
function uses one file descriptor for each level in the tree.
If depth is zero or negative, the effect is the same as if it were 1. The depth
must not be greater than the number of file descriptors currently available
for use. The ftw() function is faster if depth is at least as large as the number
of levels in the tree.
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
These functions are in libc.a, but not in libc.so (in order to save space).
Description:
The ftw() function recursively descends the directory hierarchy identified by path. For
each object in the hierarchy, ftw() calls the user-defined function fn(), passing to it:
• a pointer to a NULL-terminated character string containing the name of the object
• a pointer to a stat structure (see stat()) containing information about the object
• an integer. Possible values of the integer, defined in the <ftw.h> header, are:
June 19, 2012
FTW_F
The object is a file.
FTW_D
The object is a directory.
FTW_DNR
The object is a directory that can’t be read. Descendants of the
directory aren’t processed.
FTW_NS
The stat() failed on the object because the permissions weren’t
appropriate, or the object is a symbolic link that points to a
nonexistent file. The stat buffer passed to fn() is undefined.
QNX Neutrino Functions and Macros
621
ftw(), ftw64()
© 2012, QNX Software Systems Limited
The ftw() function visits a directory before visiting any of its descendants.
The tree traversal continues until the tree is exhausted, an invocation of fn() returns a
nonzero value, or some error is detected within ftw() (such as an I/O error). If the tree
is exhausted, ftw() returns zero. If fn() returns a nonzero value, ftw() stops its tree
traversal and returns whatever value was returned by fn().
When ftw() returns, it closes any file descriptors it opened; it doesn’t close any file
descriptors that may have been opened by fn().
Returns:
0
Success.
-1
An error (other than EACCES) occurred (errno is set).
Classification:
ftw() is POSIX 1003.1 XSI; ftw64() is Large-file support
Safety
Cancellation point
Yes
Interrupt handler
No
Signal handler
Yes
Thread
Yes
Caveats:
Because ftw() is recursive, it might terminate with a memory fault when applied to
very deep file structures.
This function uses malloc() to allocate dynamic storage during its operation. If ftw() is
forcibly terminated, for example if longjmp() is executed by fn() or an interrupt
routine, ftw() doesn’t have a chance to free that storage, so it remains permanently
allocated. A safe way to handle interrupts is to store the fact that an interrupt has
occurred, and arrange to have fn() return a nonzero value at its next invocation.
See also:
longjmp(), malloc(), nftw(), readdir(), stat()
622
QNX Neutrino Functions and Macros
June 19, 2012
funlockfile()
© 2012, QNX Software Systems Limited
Release ownership of a file
Synopsis:
#include <stdio.h>
void funlockfile( FILE* file );
Arguments:
file
A pointer to the FILE object for the file you want to unlock.
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
The funlockfile() function is used to release ownership of file granted to the thread by a
call to flockfile() or ftrylockfile(). The behavior is undefined if a thread other than the
current owner calls the funlockfile() function.
For more information, see flockfile().
Classification:
POSIX 1003.1 TSF
Safety
Cancellation point
No
Interrupt handler
No
Signal handler
No
Thread
Yes
See also:
flockfile(), ftrylockfile(), getc_unlocked(), getchar_unlocked(), putc_unlocked(),
putchar_unlocked()
June 19, 2012
QNX Neutrino Functions and Macros
623
futime()
© 2012, QNX Software Systems Limited
Record the modification time for a file
Synopsis:
#include <utime.h>
int futime( int fildes,
const struct utimbuf *times );
struct utimbuf {
time_t
actime;
time_t
modtime;
};
/* access time */
/* modification time */
Arguments:
fildes
The descriptor for the file whose modification time you want to get or set.
times
NULL, or a pointer to a utimbuf structure where the function can store the
modification time.
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
The futime() function records the modification time for the file or directory with the
descriptor, fildes.
If the times argument is NULL, the access and modification times of the file or
directory are set to the current time. The effective user ID of the process must match
the owner of the file or directory, or the process must have write permission to the file
or directory, or appropriate privileges in order to use the futime() function in this way.
If the times argument isn’t NULL, it’s interpreted as a pointer to a utimbuf structure,
and the access and modification times of the file or directory are set to the values
contained in the actime and modtime fields in this structure. Only the owner of the file
or directory, and processes with appropriate privileges are permitted to use the futime()
function in this way.
Returns:
624
0
Success.
-1
An error occurred (errno) is set.
QNX Neutrino Functions and Macros
June 19, 2012
futime()
© 2012, QNX Software Systems Limited
Errors:
EACCES
Search permission is denied for a component of path, or the times
argument is NULL, and the effective user ID of the process doesn’t
match the owner of the file, and write access is denied.
ENAMETOOLONG
The argument path exceeds PATH_MAX in length, or a pathname
component is longer than NAME_MAX.
ENOENT
The specified path doesn’t exist, or path is an empty string.
ENOTDIR
A component of path isn’t a directory.
EPERM
The times argument isn’t NULL, and the calling process’s effective user
ID has write access to the file but doesn’t match the owner of the file,
and the calling process doesn’t have the appropriate privileges.
EROFS
The named file resides on a read-only filesystem.
Classification:
Unix
Safety
Cancellation point
No
Interrupt handler
No
Signal handler
Yes
Thread
Yes
See also:
errno, utime()
June 19, 2012
QNX Neutrino Functions and Macros
625
fwide()
© 2012, QNX Software Systems Limited
Set or get the stream orientation
Synopsis:
#include <wchar.h>
int fwide( FILE * fp,
int mode );
Arguments:
fp
The stream whose orientation you want to set.
mode
The orientation mode:
• If mode is greater than zero and the stream orientation hasn’t been set,
fwide() flags the stream as wide-oriented.
• If mode is less than zero, fwide() behaves similarly, but flags the stream
as byte-oriented.
• If mode is zero, fwide() returns the stream type without altering the
stream.
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
The fwide() function sets or determines the orientation of the stream fp.
Returns:
>0
The stream is (now) wide-oriented.
0
The stream is unbound.
<0
The stream is (now) byte-oriented.
Errors:
EBADF
The fp argument isn’t valid.
Classification:
ANSI, POSIX 1003.1
626
QNX Neutrino Functions and Macros
June 19, 2012
fwide()
© 2012, QNX Software Systems Limited
Safety
Cancellation point
Yes
Interrupt handler
No
Signal handler
Yes
Thread
Yes
See also:
fgets(), fgetws(), fputs(), fputwc()
June 19, 2012
QNX Neutrino Functions and Macros
627
fwprintf()
© 2012, QNX Software Systems Limited
Write wide-character output to a stream
Synopsis:
#include <wchar.h>
int fwprintf( FILE * fp,
const wchar_t * format,
... );
Arguments:
fp
The stream to which you want to send the output.
format
A wide-character string that specifies the format of the output. The
formatting string determines what additional arguments you need to
provide. For more information, see printf().
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
The fwprintf() function writes output to the stream specified by fp, under control of the
format specifier.
The fwprintf() function is the wide-character version of fprintf().
Returns:
The number of wide characters written, excluding the terminating NUL, or a negative
number if an error occurred (errno is set).
Classification:
ANSI, POSIX 1003.1
Safety
628
Cancellation point
Yes
Interrupt handler
No
Signal handler
No
Thread
Yes
QNX Neutrino Functions and Macros
June 19, 2012
© 2012, QNX Software Systems Limited
fwprintf()
See also:
errno, fprintf(), printf(), snprintf(), sprintf(), swprintf(), vfprintf(), vfwprintf(),
vprintf(), vsnprintf(), vsprintf(), vswprintf(), vwprintf(), wprintf()
June 19, 2012
QNX Neutrino Functions and Macros
629
fwrite()
© 2012, QNX Software Systems Limited
Write elements to a file
Synopsis:
#include <stdio.h>
size_t fwrite( const void* buf ,
size_t size,
size_t num,
FILE* fp );
Arguments:
buf
A pointer to a buffer that contains the elements that you want to write.
size
The size of each element to write.
num
The number of elements to write.
fp
The stream to which to write the elements.
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
The fwrite() function writes num elements of size bytes each to the stream specified by
fp.
Returns:
The number of complete elements successfully written; if an error occurs, this is less
than num.
Errors:
If an error occurs, errno is set to indicate the type of error.
Examples:
#include <stdio.h>
#include <stdlib.h>
struct student_data {
int student_id;
unsigned char marks[10];
};
int main( void )
{
FILE *fp;
struct student_data std;
int i;
630
QNX Neutrino Functions and Macros
June 19, 2012
fwrite()
© 2012, QNX Software Systems Limited
fp = fopen( "file", "w" );
if( fp != NULL ) {
std.student_id = 1001;
for( i = 0; i < 10; i++ ) {
std.marks[i] = (unsigned char)(85 + i);
}
/* write student record with marks */
i = fwrite( &std, sizeof( struct student_data ), 1, fp );
printf( "Successfully wrote %d records\n", i );
fclose( fp );
if( i == 1 ) {
return EXIT_SUCCESS;
}
}
return EXIT_FAILURE;
}
Classification:
ANSI, POSIX 1003.1
Safety
Cancellation point
Yes
Interrupt handler
No
Signal handler
No
Thread
Yes
See also:
errno, ferror(), fopen()
June 19, 2012
QNX Neutrino Functions and Macros
631
fwscanf()
© 2012, QNX Software Systems Limited
Scan wide-character input from a stream
Synopsis:
#include <wchar.h>
int fwscanf( FILE * fp,
const wchar_t * format,
... );
Arguments:
fp
The stream that you want to read from.
format
A wide-character string that specifies the format of the input. For more
information, see scanf(). The formatting string determines what additional
arguments you need to provide.
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
The fwscanf() function scans input from the stream specified by fp, under control of the
argument format. Following the format string is a list of addresses to receive values.
The fwscanf() function is the wide-character version of fscanf().
Returns:
The number of input arguments for which values were successfully scanned and
stored, or EOF if the scanning reached the end of the input stream before storing any
values.
Classification:
ANSI, POSIX 1003.1
Safety
632
Cancellation point
Yes
Interrupt handler
No
Signal handler
No
Thread
Yes
QNX Neutrino Functions and Macros
June 19, 2012
© 2012, QNX Software Systems Limited
fwscanf()
See also:
errno, fscanf(), scanf(), sscanf(), swscanf(), vfscanf(), vfwscanf(), vscanf(), vsscanf(),
vswscanf(), vwscanf(), wscanf()
June 19, 2012
QNX Neutrino Functions and Macros
633
gai_strerror()
© 2012, QNX Software Systems Limited
Return the string associated with a getaddrinfo() error code
Synopsis:
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
const char * gai_strerror( int ecode );
Arguments:
ecode
The error code number from the getaddrinfo() function.
Library:
libsocket
Use the -l socket option to qcc to link against this library.
Description:
The gai_strerror() function returns a string describing the error code from the
getaddrinfo() function. Nonzero error codes are defined in <netdb.h> as follows:
EAI_ADDRFAMILY
The address family for nodename isn’t supported.
634
EAI_AGAIN
There was a temporary failure in name resolution.
EAI_BADFLAGS
Invalid value for ai_flags.
EAI_FAIL
Nonrecoverable failure in name resolution.
EAI_FAMILY
The ai_family isn’t supported.
EAI_MEMORY
Memory allocation failure.
EAI_NODATA
No address associated with the nodename.
EAI_NONAME
Either the nodename or the servname argument wasn’t provided
or isn’t known.
EAI_SERVICE
The servname argument isn’t supported for ai_socktype.
EAI_SOCKTYPE
The ai_socktype isn’t supported.
EAI_SYSTEM
System error returned in errno.
QNX Neutrino Functions and Macros
June 19, 2012
gai_strerror()
© 2012, QNX Software Systems Limited
Returns:
If called with a proper ecode argument, a pointer to a string describing the given error
code. If the argument isn’t one of the EAI_* values, a pointer to a string whose
contents indicate an unknown error.
Don’t modify the strings that this function returns.
Classification:
POSIX 1003.1
Safety
Cancellation point
No
Interrupt handler
Yes
Signal handler
Yes
Thread
Yes
See also:
addrinfo, freeaddrinfo(), getaddrinfo()
June 19, 2012
QNX Neutrino Functions and Macros
635
gamma(), gamma_r(), gammaf(), gammaf_r()
© 2012, QNX Software Systems Limited
Log gamma function
Synopsis:
#include <math.h>
double gamma( double x );
double gamma_r( double x,
int* signgam);
float gammaf( float x );
float gammaf_r( float x,
int* signgam);
Arguments:
x
An arbitrary number.
signgam
(gamma_r(), gammaf_r() only) A pointer to a location where the
function can store the sign of Γ(x).
Library:
libm
Use the -l m option to qcc to link against this library.
Description:
The gamma() and gamma_r() functions return the natural log (ln) of the gamma()
function and are equivalent to lgamma(). These functions return ln|Γ(x)|, where
Γ(x) is defined as follows:
8
e-t t x-1dt
For x > 0:
For x < 1:
0
n / (Γ( 1-x ) * sin( nx ))
The results converge when x is between 0 and 1. The Γ function has the property:
Γ(N) = Γ(N-1)×N
The gamma* functions compute the log because the Γ function grows very quickly.
The gamma() and gammaf() functions use the external integer signgam to return the
sign of Γ(x), while gamma_r() and gammaf_r() use the user-allocated space addressed
by signgamp.
636
QNX Neutrino Functions and Macros
June 19, 2012
© 2012, QNX Software Systems Limited
gamma(), gamma_r(), gammaf(), gammaf_r()
The signgam variable isn’t set until gamma() or gammaf() returns. For example, don’t
use the expression:
g = signgam * exp( gamma( x ));
to compute g = Γ(x)’. Instead, compute gamma() first:
lg = gamma(x);
g = signgam * exp( lg );
Note that Γ(x) must overflow when x is large enough, underflow when -x is large
enough, and generate a division by 0 exception at the singularities x a nonpositive
integer.
Returns:
ln|Γ(x)|
If an error occurs, these functions return 0, but this is also a valid mathematical result.
If you want to check for errors, set errno to 0, call the function, and then check errno
again. These functions don’t change errno if no errors occurred.
Classification:
Legacy Unix
Safety
Cancellation point
No
Interrupt handler
No
Signal handler
No
Thread
Yes
See also:
lgamma()
June 19, 2012
QNX Neutrino Functions and Macros
637
getaddrinfo()
© 2012, QNX Software Systems Limited
Get socket address information
Synopsis:
#include <sys/socket.h>
#include <netdb.h>
int getaddrinfo( const char * nodename,
const char * servname,
const struct addrinfo * hints,
struct addrinfo ** res );
Arguments:
nodename
The node name. A non-NULL nodename may be either a node name or
a numeric host address string (i.e. a dotted-decimal IPv4 address or an
IPv6 hex address.)
servname
The server name. A non-NULL servname may be either a server name
or a decimal port number.
hints
A pointer to an addrinfo structure that provides hints about the type
of socket you’re supporting. See “Using the hints argument” for more
information.
res
The address of a location where the function can store a pointer to a
linked list of one or more addrinfo structures.
Library:
libsocket
Use the -l socket option to qcc to link against this library.
Description:
The getaddrinfo() function performs the functionality of gethostbyname() and
getservbyname() but in a more sophisticated manner.
The nodename and servname arguments are either pointers to null-terminated strings
or NULL. One or both of these two arguments must be a non-NULL pointer. Normally,
a client scenario specifies both nodename and servname.
On success, the getaddrinfo() function stores, in the location pointed to by res, a
pointer to a linked list of one or more addrinfo structures. You can process each
addrinfo structure in this list by following the ai_next pointer until reaching a NULL
pointer. Each addrinfo structure contains the corresponding ai_family, ai_socktype,
and ai_protocol arguments for a call to the socket() function. The ai_addr argument
of the addrinfo structure points to a filled-in socket address structure with a length
specified by the ai_addrlen argument.
638
QNX Neutrino Functions and Macros
June 19, 2012
getaddrinfo()
© 2012, QNX Software Systems Limited
If the name server isn’t responding, there’s a timeout of 1.5 minutes per name server.
Using the hints argument
You can optionally pass an addrinfo structure, pointed to by the hints argument, that
provides hints concerning the type of socket that your application supports.
In this structure, all members — except ai_flags, ai_family, ai_socktype, and
ai_protocol — must be zero or a NULL pointer. The addrinfo structure of the hints
argument can accept various types of sockets:
To accept:
Set:
To:
Any protocol family
ai_family
PF_UNSPEC
Any socket type
ai_socktype
0
Any protocol
ai_protocol
0
All of the above (as well as setting ai_flags to 0)
hints
NULL
The hints argument defaults to all possibilities, but you can also use it to limit choices:
• If the application handles only TCP but not UDP, you could set the ai_socktype
member of the hints structure to SOCK_STREAM.
• If the application handles only IPv4 but not IPv6, you could set the ai_family
member of the hints structure to PF_INET.
Using the ai_flags argument in the hints structure
You can set the ai_flags argument to further configure the hints structure. Settings for
ai_flags include:
AI_PASSIVE
Set this bit if you plan to use the returned addrinfo structure in a
call to bind(). In this call, if the nodename argument is a NULL
pointer, then the IP address portion of the socket address structure
ai_addr is set to INADDR_ANY for an IPv4 address or
IN6ADDR_ANY_INIT for an IPv6 address.
If you don’t set the AI_PASSIVE flag, you can use the returned
addrinfo structure in a call to:
• connect() — connectionless or connection-oriented protocol
• sendto() — connectionless protocol
• sendmsg() — connectionless protocol
June 19, 2012
QNX Neutrino Functions and Macros
639
getaddrinfo()
© 2012, QNX Software Systems Limited
In this case, if the nodename argument is a NULL pointer, then the
IP address portion of the socket address structure ai_addr is set to
the loopback address.
AI_CANONNAME
Set this bit if you want the ai_canonname argument of the first
addrinfo structure to point to a null-terminated string containing
the canonical name of the specified nodename.
AI_NUMERICHOST
Set this bit if you want to prevent any type of name resolution
service (such as DNS) from being used. A non-NULL nodename
string must be a numeric host address string; otherwise,
getaddrinfo() returns EAI_NONAME.
Pitfalls
The arguments to getaddrinfo() must be sufficiently consistent and unambiguous or
this function will return an error. Here are some problems you may encounter:
• Inconsistent hints — for Internet address families, specifying SOCK_STREAM for
ai_socktype while specifying IPPROTO_UDP for ai_protocol.
• Inconsistent servname — specifying a servname that’s defined only for certain
ai_socktype values, such as the TFTP service (a datagram service SOCK_DGRAM)
on SOCK_STREAM.
• Undefined service names — specifying a servname while specifying SOCK_RAW
for ai_socktype. (Service names aren’t defined for the internet SOCK_RAW space.)
• Incomplete specifications — specifying a numeric servname while leaving
ai_socktype and ai_protocol unspecified. The getaddrinfo() function isn’t allowed
to glob() the argument when a numeric servname doesn’t have a specified socket
type.
The getaddrinfo() function dynamically allocates space for the following:
• addrinfo structures
• socket address structures
• canonical node name strings pointed to by the addrinfo structures.
Use freeaddrinfo() to free the addrinfo structures, and gai_strerror() to decipher error
codes.
640
QNX Neutrino Functions and Macros
June 19, 2012
getaddrinfo()
© 2012, QNX Software Systems Limited
Returns:
Zero for success, or nonzero if an error occurs.
Errors:
To get an explanation of any error code, use gai_strerror().
Examples:
The following code tries to connect to www.kame.net service HTTP using a stream
socket. It loops through all the addresses available, regardless of the address family. If
the destination resolves to an IPv4 address, it uses a AF_INET socket. Similarly, it uses
an AF_INET6 socket if it resolves to IPv6. Note that there aren’t any hardcoded
references to any particular address family; the code works even if getaddrinfo()
returns addresses that aren’t IPv4/v6.
struct addrinfo hints, *res, *res0;
int error;
int s;
const char *cause = NULL;
memset(&hints, 0, sizeof(hints));
hints.ai_family = PF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
error = getaddrinfo("www.kame.net", "http", &hints, &res0);
if (error) {
err1(1, "%s", gai_strerror(error));
/*NOTREACHED*/
}
s = -1;
for (res = res0; res; res = res->ai_next) {
s = socket(res->ai_family, res->ai_socktype,
res->ai_protocol);
if (s < 0) {
cause = "socket";
continue;
}
if (connect(s, res->ai_addr, res->ai_addrlen) < 0) {
cause = "connect";
close(s);
s = -1;
continue;
}
break; /* okay we got one */
}
if (s < 0) {
err(1, cause);
/*NOTREACHED*/
}
freeaddrinfo(res0);
The following example tries to open a wildcard-listening socket onto the HTTP
service for all of the available address families:
struct addrinfo hints, *res, *res0;
int error;
June 19, 2012
QNX Neutrino Functions and Macros
641
getaddrinfo()
© 2012, QNX Software Systems Limited
int s[MAXSOCK];
int nsock;
const char *cause = NULL;
memset(&hints, 0, sizeof(hints));
hints.ai_family = PF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
hints.ai_flags = AI_PASSIVE;
error = getaddrinfo(NULL, "http", &hints, &res0);
if (error) {
err1(1, "%s", gai_strerror(error));
/*NOTREACHED*/
}
nsock = 0;
for (res = res0; res && nsock < MAXSOCK; res = res->ai_next) {
s[nsock] = socket(res->ai_family, res->ai_socktype,
res->ai_protocol);
if (s[nsock] < 0) {
cause = "socket";
continue;
}
if (connect(s[nsock], res->ai_addr, res->ai_addrlen) < 0) {
cause = "connect";
close(s[nsock]);
continue;
}
nsock++;
}
if (nsock == 0) {
err(1, cause);
/*NOTREACHED*/
}
freeaddrinfo(res0);
Files:
/etc/nsswitch.conf
Name-service switch configuration file.
Classification:
POSIX 1003.1
Safety
642
Cancellation point
Yes
Interrupt handler
No
Signal handler
No
Thread
No
QNX Neutrino Functions and Macros
June 19, 2012
getaddrinfo()
© 2012, QNX Software Systems Limited
See also:
addrinfo, freeaddrinfo(), gai_strerror()
/etc/nsswitch.conf in the Utilities Reference
June 19, 2012
QNX Neutrino Functions and Macros
643
getc()
© 2012, QNX Software Systems Limited
Get the next character from a file
Synopsis:
#include <stdio.h>
int getc( FILE* fp );
Arguments:
fp
The stream you want to get the character from.
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
The getc() macro gets the next character from the stream designated by fp. The
character is returned as an int value.
Returns:
The next character from the stream fp, cast as (int)(unsigned char), or EOF if an
end-of-file or error condition occurs (errno is set).
Use feof() or ferror() to distinguish an end-of-file condition from an error.
Examples:
#include <stdio.h>
#include <stdlib.h>
int main( void )
{
FILE* fp;
int c;
fp = fopen( "file", "r" );
if( fp != NULL ) {
while( (c = getc( fp )) != EOF ) {
putchar(c);
}
fclose( fp );
return EXIT_SUCCESS;
}
return EXIT_FAILURE;
}
644
QNX Neutrino Functions and Macros
June 19, 2012
getc()
© 2012, QNX Software Systems Limited
Classification:
ANSI, POSIX 1003.1
Safety
Cancellation point
Yes
Interrupt handler
No
Signal handler
No
Thread
Yes
Caveats:
getc() is a macro.
See also:
errno, feof(), ferror(), fgetc(), fgetchar(), fgets(), fopen(), getchar(), gets(), putc(),
putc_unlocked(), putchar(), putchar_unlocked(), ungetc()
June 19, 2012
QNX Neutrino Functions and Macros
645
getc_unlocked()
© 2012, QNX Software Systems Limited
Get the next character from a file
Synopsis:
#include <stdio.h>
int getc_unlocked( FILE *fp );
Arguments:
fp
The stream you want to get the character from.
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
The getc_unlocked() function is a thread-unsafe version of getc(). You can use it
safely only when the invoking thread has locked fp using flockfile() (or ftrylockfile())
and funlockfile().
Returns:
The next character from the input stream pointed to by fp, or EOF if an end-of-file or
error condition occurs (errno is set).
Use feof() or ferror() to distinguish an end-of-file condition from an error.
Classification:
POSIX 1003.1 TSF
Safety
Cancellation point
Yes
Interrupt handler
No
Signal handler
No
Thread
No
See also:
feof(), ferror(), flockfile(), getc(), getchar(), getchar_unlocked(), putc(),
putc_unlocked(), putchar(), putchar_unlocked()
646
QNX Neutrino Functions and Macros
June 19, 2012
getchar()
© 2012, QNX Software Systems Limited
Get a character from stdin
Synopsis:
#include <stdio.h>
int getchar( void );
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
The getchar() function is equivalent to getc() on the stdin stream.
Returns:
The next character from the input stream pointed to by stdin, cast as
(int)(unsigned char), or EOF if an end-of-file or error condition occurs (errno is
set).
Use feof() or ferror() to distinguish an end-of-file condition from an error.
Examples:
#include <stdio.h>
#include <stdlib.h>
int main( void )
{
FILE *fp;
int c;
/* Get characters from "file" instead of
* stdin.
*/
fp = freopen( "file", "r", stdin );
while( ( c = getchar() ) != EOF ) {
putchar(c);
}
fclose( fp );
return EXIT_SUCCESS;
}
Classification:
ANSI, POSIX 1003.1
June 19, 2012
QNX Neutrino Functions and Macros
647
getchar()
© 2012, QNX Software Systems Limited
Safety
Cancellation point
Yes
Interrupt handler
No
Signal handler
No
Thread
Yes
See also:
errno, feof(), ferror(), fgetc(), fgetchar(), getc(), putc(), putc_unlocked(), putchar(),
putchar_unlocked()
648
QNX Neutrino Functions and Macros
June 19, 2012
getchar_unlocked()
© 2012, QNX Software Systems Limited
Get a character from stdin
Synopsis:
#include <stdio.h>
int getchar_unlocked( void );
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
The getchar_unlocked() function is a thread-unsafe version of getchar(). You can use
it safely only when the invoking thread has locked stdin using flockfile() (or
ftrylockfile()) and funlockfile().
Returns:
The next character from the input stream pointed to by stdin, cast as
(int)(unsigned char), or EOF if an end-of-file or error condition occurs (errno is
set).
Use feof() or ferror() to distinguish an end-of-file condition from an error.
Classification:
POSIX 1003.1 TSF
Safety
Cancellation point
Yes
Interrupt handler
No
Signal handler
No
Thread
No
See also:
feof(), ferror(), getc(), getc_unlocked(), getchar(), putc(), putc_unlocked(), putchar(),
putchar_unlocked()
June 19, 2012
QNX Neutrino Functions and Macros
649
getcwd()
© 2012, QNX Software Systems Limited
Get the name of the current working directory
Synopsis:
#include <unistd.h>
char* getcwd( char* buffer,
size_t size );
Arguments:
buffer
NULL, or a pointer to a buffer where the function can store the directory
name.
size
The size of the buffer, in bytes.
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
The getcwd() function returns the name of the current working directory. buffer is a
pointer to a buffer of at least size bytes where the NUL-terminated name of the current
working directory will be placed.
The maximum size that might be required for buffer is PATH_MAX + 1 bytes. See
<limits.h>.
POSIX doesn’t specify what should happen if you call getcwd( NULL, 0). The
Neutrino version (like many others) allocates a buffer for the name of the directory;
it’s up to your application to free the buffer when you no longer need it.
Returns:
The address of the string containing the name of the current working directory, or
NULL if an error occurred (errno is set).
Errors:
650
EINVAL
The argument size is negative or 0.
ELOOP
Too many levels of symbolic links.
ENOSYS
The getcwd() function isn’t implemented for the filesystem specified in
the current working directory.
ERANGE
The buffer is too small (as specified by size) to contain the name of the
current working directory.
QNX Neutrino Functions and Macros
June 19, 2012
getcwd()
© 2012, QNX Software Systems Limited
Examples:
#include
#include
#include
#include
<stdio.h>
<stdlib.h>
<unistd.h>
<limits.h>
int main( void )
{
char* cwd;
char buff[PATH_MAX + 1];
cwd = getcwd( buff, PATH_MAX + 1 );
if( cwd != NULL ) {
printf( "My working directory is %s.\n", cwd );
}
return EXIT_SUCCESS;
}
produces the output:
My working directory is /home/bill.
Classification:
POSIX 1003.1
Safety
Cancellation point
Yes
Interrupt handler
No
Signal handler
No
Thread
Yes
Caveats:
There is only one current working directory per process. In a multithreaded
application, any thread calling chdir() will change the current working directory for all
threads in that process.
See also:
chdir(), errno, fchdir(), mkdir(), rmdir()
June 19, 2012
QNX Neutrino Functions and Macros
651
getdomainname()
© 2012, QNX Software Systems Limited
Get the domain name of the current host
Synopsis:
#include <unistd.h>
int getdomainname( char * name,
size_t namelen );
Arguments:
name
A buffer where the function can store the domain name.
namelen
The size of the name array.
Library:
libsocket
Use the -l socket option to qcc to link against this library.
Description:
The getdomainname() function gets the standard domain name for the current
processor and stores it in the buffer that name points to. The name is null-terminated.
If the buffer is too small, the name is truncated.
Returns:
0
Success.
-1
An error occurred (errno is set).
Errors:
EFAULT
The name or namelen parameters gave an invalid address.
Classification:
Unix
Safety
652
Cancellation point
No
Interrupt handler
No
Signal handler
Yes
Thread
Yes
QNX Neutrino Functions and Macros
June 19, 2012
© 2012, QNX Software Systems Limited
getdomainname()
See also:
setdomainname()
June 19, 2012
QNX Neutrino Functions and Macros
653
getdtablesize()
© 2012, QNX Software Systems Limited
Get the size of the file descriptor table
Synopsis:
#include <unistd.h>
int
getdtablesize( void );
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
Each process has a fixed size descriptor table, which is guaranteed to have at least 20
slots. The entries in the descriptor table are numbered with small integers starting at 0.
The getdtablesize() returns the size of this table.
This function is equivalent to getrlimit() with the RLIMIT_NOFILE option.
Returns:
The size of the file descriptor table.
Classification:
Legacy Unix
Safety
Cancellation point
No
Interrupt handler
No
Signal handler
Yes
Thread
Yes
See also:
close(), dup(), getrlimit(), open(), select(), sysconf()
654
QNX Neutrino Functions and Macros
June 19, 2012
getegid()
© 2012, QNX Software Systems Limited
Get the effective group ID
Synopsis:
#include <sys/types.h>
#include <unistd.h>
gid_t getegid( void );
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
The getegid() function gets the effective group ID for the calling process.
Returns:
The calling process’s effective group ID. This function can’t fail.
Examples:
/*
* Print
*/
#include
#include
#include
#include
the effective group ID of a process
<stdio.h>
<stdlib.h>
<sys/types.h>
<unistd.h>
int main( void )
{
printf( "My effective group ID is %d\n", getegid() );
return EXIT_SUCCESS;
}
Classification:
POSIX 1003.1
Safety
June 19, 2012
Cancellation point
No
Interrupt handler
No
Signal handler
Yes
Thread
Yes
QNX Neutrino Functions and Macros
655
getegid()
© 2012, QNX Software Systems Limited
See also:
geteuid(), getgid(), getuid(), setegid()
656
QNX Neutrino Functions and Macros
June 19, 2012
getenv()
© 2012, QNX Software Systems Limited
Get the value of an environment variable
Synopsis:
#include <stdlib.h>
char* getenv( const char* name );
Arguments:
name
The name of the environment variable whose value you want to get.
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
The getenv() function searches the environment list for a string in the form
name=value and returns a pointer to a string containing the value for the specified
name. The matching is case-sensitive.
Returns:
A pointer to the value assigned to name, or NULL if name wasn’t found in the
environment.
Don’t modify the returned string.
Examples:
#include <stdio.h>
#include <stdlib.h>
int main( void )
{
char* path;
path = getenv( "INCLUDE" );
if( path != NULL ) {
printf( "INCLUDE=%s\n", path );
return EXIT_SUCCESS;
}
return EXIT_FAILURE;
}
Classification:
ANSI, POSIX 1003.1
June 19, 2012
QNX Neutrino Functions and Macros
657
getenv()
© 2012, QNX Software Systems Limited
Safety
Cancellation point
No
Interrupt handler
No
Signal handler
No
Thread
No
Caveats:
The getenv() function manipulates the environment pointed to by the global environ
variable.
See also:
clearenv(), environ, execl(), execle(), execlp(), execlpe(), execv(), execve(), execvp(),
execvpe(), putenv(), searchenv(), setenv(), spawn*() functions, system()
658
QNX Neutrino Functions and Macros
June 19, 2012
geteuid()
© 2012, QNX Software Systems Limited
Get the effective user ID
Synopsis:
#include <sys/types.h>
#include <unistd.h>
uid_t geteuid( void );
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
The geteuid() function gets the effective user ID for the calling process.
Returns:
The calling process’s effective user ID.
Examples:
/*
* Print
*/
#include
#include
#include
#include
the effective user ID of a process.
<stdio.h>
<stdlib.h>
<sys/types.h>
<unistd.h>
int main( void )
{
printf( "My effective user ID is %d\n", geteuid() );
return EXIT_SUCCESS;
}
Classification:
POSIX 1003.1
Safety
June 19, 2012
Cancellation point
No
Interrupt handler
No
Signal handler
Yes
Thread
Yes
QNX Neutrino Functions and Macros
659
geteuid()
© 2012, QNX Software Systems Limited
See also:
getegid(), getgid(), getuid(), seteuid()
660
QNX Neutrino Functions and Macros
June 19, 2012
getfsfile()
© 2012, QNX Software Systems Limited
Search for a filesystem name in the filesystem table (/etc/fstab) file
Synopsis:
#include <fstab.h>
struct fstab * getfsfile(const char *file);
Arguments:
file
The prefix of the filesystem that you want to search for.
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
This function is in libc.a, but not in libc.so (in order to save space).
Description:
The getfsfile() function searches the filesystem table (/etc/fstab) for an entry for
the specified filesystem prefix.
Returns:
A pointer to the fstab structure for the filesystem (see the entry for getfsent()), or
NULL if the entry couldn’t be found.
Classification:
NetBSD
Safety
Cancellation point
No
Interrupt handler
No
Signal handler
Yes
Thread
Yes
Caveats:
The functions that work with /etc/fstab use static data storage; if you need the data
for future use, copy it before any subsequent calls overwrite it.
June 19, 2012
QNX Neutrino Functions and Macros
661
getfsfile()
© 2012, QNX Software Systems Limited
See also:
endfsent(), getfsent(), getfsspec(), mount(), setfsent()
/etc/fstab in the Utilities Reference
662
QNX Neutrino Functions and Macros
June 19, 2012
getfsent()
© 2012, QNX Software Systems Limited
Get the next entry from the filesystem table (/etc/fstab) file
Synopsis:
#include <fstab.h>
struct fstab * getfsent(void);
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
This function is in libc.a, but not in libc.so (in order to save space).
Description:
The getfsent() function gets the next entry from the filesystem table file, /etc/fstab.
The fstab structure
The getfsent(), getfsfile(), and getfsspec() functions return pointers to a fstab
structure, which is defined as follows:
struct fstab {
char
char
char
char
char
int
int
};
*fs_spec;
*fs_file;
*fs_vfstype;
*fs_mntops;
*fs_type;
init_flags;
init_mask;
The members include:
June 19, 2012
fs_spec
The block special device name (e.g. /dev/hd0t177).
fs_file
The filesystem path prefix.
fs_vfstype
The type of filesystem; for a list of types, see the entry for mount in the
Utilities Reference.
fs_mntops
A comma-separated list of mount options, which can include:
QNX Neutrino Functions and Macros
663
getfsent()
© 2012, QNX Software Systems Limited
String
Constant
Meaning
implied
FSTAB_IMPLIED The root entry was implied, not
specified.
allservers FSTAB_OCB
fs_type
ro
FSTAB_RO
Read-only device.
rw
FSTAB_RW
Read-write device.
xx
FSTAB_XX
Completely ignore the entry.
The type of filesystem; one of the following:
String Constant
init_flags
Send the mount request to all servers.
Meaning
ro
FSTAB_RO Read-only device.
rw
FSTAB_RW Read-write device.
xx
FSTAB_XX Completely ignore the entry.
Flags to OR in:
• _MFLAG_OCB — ignore the special device string, and contact all
servers.
• _MOUNT_IMPLIED — the mountpoint is unspecified by the client.
init_mask
Flags to AND out.
Returns:
A pointer to the fstab structure for the next entry in the file, or NULL if the function
reached the end of the file.
Classification:
NetBSD
Safety
664
Cancellation point
No
Interrupt handler
No
Signal handler
Yes
Thread
Yes
QNX Neutrino Functions and Macros
June 19, 2012
getfsent()
© 2012, QNX Software Systems Limited
Caveats:
The functions that work with /etc/fstab use static data storage; if you need the data
for future use, copy it before any subsequent calls overwrite it.
See also:
endfsent(), getfsfile(), getfsspec(), mount(), setfsent()
/etc/fstab, mount in the Utilities Reference
June 19, 2012
QNX Neutrino Functions and Macros
665
getfsspec()
© 2012, QNX Software Systems Limited
Search for a block special device in the filesystem table (/etc/fstab) file
Synopsis:
#include <fstab.h>
struct fstab * getfsspec(const char *spec);
Arguments:
spec
The name of the block special device that you want to search for.
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
This function is in libc.a, but not in libc.so (in order to save space).
Description:
The getfsfile() function searches the filesystem table (/etc/fstab) for an entry for
the specified block special device.
Returns:
A pointer to the fstab structure for the block special device (see the entry for
getfsent()), or NULL if the entry couldn’t be found.
Classification:
NetBSD
Safety
Cancellation point
No
Interrupt handler
No
Signal handler
Yes
Thread
Yes
Caveats:
The functions that work with /etc/fstab use static data storage; if you need the data
for future use, copy it before any subsequent calls overwrite it.
666
QNX Neutrino Functions and Macros
June 19, 2012
getfsspec()
© 2012, QNX Software Systems Limited
See also:
endfsent(), getfsent(), getfsfile(), mount(), setfsent()
/etc/fstab in the Utilities Reference
June 19, 2012
QNX Neutrino Functions and Macros
667
getgid()
© 2012, QNX Software Systems Limited
Get the group ID
Synopsis:
#include <sys/types.h>
#include <unistd.h>
gid_t getgid( void );
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
The getgid() function gets the group ID for the calling process.
Returns:
The calling process’s group ID. This function can’t fail.
Examples:
/*
* Print the group id of a process.
*/
#include
#include
#include
#include
<stdlib.h>
<stdio.h>
<sys/types.h>
<unistd.h>
int main( void )
{
printf( "I belong to group ID %d\n", getgid() );
return EXIT_SUCCESS;
}
Classification:
POSIX 1003.1
Safety
668
Cancellation point
No
Interrupt handler
No
Signal handler
Yes
Thread
Yes
QNX Neutrino Functions and Macros
June 19, 2012
© 2012, QNX Software Systems Limited
getgid()
See also:
getegid(), geteuid(), getuid()
June 19, 2012
QNX Neutrino Functions and Macros
669
getgrent()
© 2012, QNX Software Systems Limited
Return an entry from the group database
Synopsis:
#include <grp.h>
struct group* getgrent( void );
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
The getgrent() function returns the next entry from the group database, although no
particular order is guaranteed. This function uses a static buffer that’s overwritten by
each call.
The getgrent(), getgrgid(), and getgrnam() function share the same static buffer.
Returns:
The next entry from the group database. When you first call getgrent(), the group
database is opened. It remains open until either getgrent() returns NULL to signify
end-of-file, or you call endgrent().
Errors:
The getgrent() function uses the following functions, and as a result, errno can be set
to an error for any of these calls:
• fclose()
• fgets()
• fopen()
• fseek()
• rewind()
Examples:
/*
* This program loops, reading a group name from
* standard input and checking to see if it is a valid
* group. If it isn’t valid, the entire contents of the
* group database are printed.
*/
#include <stdio.h>
#include <stdlib.h>
#include <grp.h>
#include <limits.h>
670
QNX Neutrino Functions and Macros
June 19, 2012
getgrent()
© 2012, QNX Software Systems Limited
int main( void )
{
struct group* gr;
char
buf[80];
setgrent();
while( gets(buf) != NULL) {
if( (gr=getgrnam(buf)) != (struct group *)0) {
printf("Valid group is: %s\n",gr->gr_name);
} else {
setgrent();
while( (gr=getgrent()) != (struct group *)0 )
printf("%s\n",gr->gr_name);
}
}
endgrent();
return( EXIT_SUCCESS );
}
Classification:
POSIX 1003.1 XSI
Safety
Cancellation point
Yes
Interrupt handler
No
Signal handler
No
Thread
No
See also:
endgrent(), errno, getgrgid(), getgrnam(), getpwent(), getpwent_r(), setgrent()
June 19, 2012
QNX Neutrino Functions and Macros
671
getgrgid()
© 2012, QNX Software Systems Limited
Get information about the group with a given ID
Synopsis:
#include <sys/types.h>
#include <grp.h>
struct group* getgrgid( gid_t gid );
Arguments:
gid
The ID of the group you want to get information about.
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
The getgrgid() function lets a process gain more knowledge about group gid. This
function uses a static buffer that’s overwritten by each call.
The getgrent(), getgrgid(), and getgrnam() functions share the same static buffer.
Returns:
A pointer to an object of type struct group containing an entry from the group
database with a matching gid. On error or failure to find an entry with a matching gid,
a NULL pointer is returned.
Examples:
/*
* Print
*/
#include
#include
#include
#include
#include
a list of all users in your group
<stdio.h>
<stdlib.h>
<unistd.h>
<sys/types.h>
<grp.h>
int main( void )
{
struct group* g;
char** p;
if( ( g = getgrgid( getgid() ) ) == NULL ) {
fprintf( stderr, "getgrgid: NULL pointer\n" );
return( EXIT_FAILURE );
}
printf( "group name:%s\n", g->gr_name );
for( p = g->gr_mem; *p != NULL; p++ ) {
printf( "\t%s\n", *p );
}
672
QNX Neutrino Functions and Macros
June 19, 2012
getgrgid()
© 2012, QNX Software Systems Limited
return( EXIT_SUCCESS );
}
Classification:
POSIX 1003.1
Safety
Cancellation point
Yes
Interrupt handler
No
Signal handler
No
Thread
No
See also:
getgrent(), getgrgid_r(), getgrnam()
June 19, 2012
QNX Neutrino Functions and Macros
673
getgrgid_r()
© 2012, QNX Software Systems Limited
Get information about the group with a given ID
Synopsis:
#include <sys/types.h>
#include <grp.h>
int getgrgid_r ( gid_t gid,
struct group* grp,
char* buffer,
size_t bufsize,
struct group** result );
Arguments:
gid
The ID of the group you want to get information about.
grp
A pointer to a group structure where the function can store information
about the group.
buffer
A buffer from which to allocate any memory required.
bufsize
The size of the buffer.
result
The address of a pointer that getgrgid_r() sets to the same pointer as grp
on success, or to NULL if the function can’t find the group.
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
If _POSIX_THREAD_SAFE_FUNCTIONS is defined, getgrgid_r() updates the group
structure pointed by grp and stores a pointer to that structure at the location pointed by
result. The structure contains an entry from the group database with a matching gid.
This function allocates storage referenced by the group structure from the memory
provided with the buffer parameter, which is bufsize characters in size. You can
determine the maximum size needed for this buffer by calling sysconf() with an
argument of _SC_GETGR_R_SIZE_MAX.
The getgrgid_r() stores a NULL pointer at the location pointed by result on error or if
the requested entry isn’t found.
Returns:
Zero for success, or an error number if an error occurred.
674
QNX Neutrino Functions and Macros
June 19, 2012
getgrgid_r()
© 2012, QNX Software Systems Limited
Errors:
Insufficient storage was supplied via buffer and bufsize to contain the
resulting group structure.
The getgrgid_r() function uses the following functions, and as a result, errno can be
set to an error for any of these calls:
ERANGE
• fclose()
• fgets()
• fopen()
• fseek()
• rewind()
Classification:
POSIX 1003.1 TSF
Safety
Cancellation point
Yes
Interrupt handler
No
Signal handler
No
Thread
Yes
See also:
getgrgid(), getgrnam(), getgrnam_r(), getlogin(), sysconf()
June 19, 2012
QNX Neutrino Functions and Macros
675
getgrnam()
© 2012, QNX Software Systems Limited
Get information about the group with a given name
Synopsis:
#include <sys/types.h>
#include <grp.h>
struct group* getgrnam( const char* name );
Arguments:
name
The name of the group you want to get information about.
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
The getgrnam() function lets a process gain more knowledge about the group named
name. This function uses a static buffer that’s overwritten by each call.
The getgrent(), getgrgid(), and getgrnam() functions share the same static buffer.
Returns:
A pointer to an object of type struct group containing an entry from the group
database with a matching name, or NULL on error or failure to find an entry with a
matching name.
Examples:
/*
* Print the name of all users in the group given in
* argv[1]
*/
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <grp.h>
int main( int argc, char** argv )
{
struct group* g;
char** p;
if( ( g = getgrnam( argv[1] ) ) == NULL ) {
fprintf( stderr, "getgrnam: %s failed\n",
argv[1] );
return( EXIT_FAILURE );
}
printf( "group name:%s\n", g->gr_name );
for( p = g->gr_mem; *p != NULL; p++ ) {
676
QNX Neutrino Functions and Macros
June 19, 2012
getgrnam()
© 2012, QNX Software Systems Limited
printf( "\t%s\n", *p );
}
return( EXIT_SUCCESS );
}
Classification:
POSIX 1003.1
Safety
Cancellation point
Yes
Interrupt handler
No
Signal handler
No
Thread
No
See also:
getgrent(), getgrgid(), getgrnam_r()
June 19, 2012
QNX Neutrino Functions and Macros
677
getgrnam_r()
© 2012, QNX Software Systems Limited
Get information about the group with a given name
Synopsis:
#include <sys/types.h>
#include <grp.h>
int getgrnam_r( const char* name,
struct group* grp,
char* buffer,
size_t bufsize,
struct group** result );
Arguments:
name
The name of the group you want to get information about.
grp
A pointer to a group structure where the function can store information
about the group.
buffer
A buffer from which to allocate any memory required.
bufsize
The size of the buffer.
result
The address of a pointer that getgrgid_r() sets to the same pointer as grp
on success, or to NULL if the function can’t find the group.
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
If _POSIX_THREAD_SAFE_FUNCTIONS is defined, the getgrnam_r() function
updates the group structure pointed by grp and stores a pointer to that structure at the
location pointed by result. The structure contains an entry from the group database
with a matching name.
This function allocates storage referenced by the group structure from the memory
provided with the buffer parameter, which is bufsize characters in size. You can
determine the maximum size needed for this buffer by calling sysconf() with an
argument of _SC_GETGR_R_SIZE_MAX.
The getgrnam_r() stores a NULL pointer at the location pointed by result on error or if
the requested entry isn’t found.
Returns:
Zero for success, or an error number if an error occurred.
678
QNX Neutrino Functions and Macros
June 19, 2012
getgrnam_r()
© 2012, QNX Software Systems Limited
Errors:
Insufficient storage was supplied via buffer and bufsize to contain the
group structure.
The getgrnam_r() function uses the following functions, and as a result, errno can be
set to an error for any of these calls:
ERANGE
• fclose()
• fgets()
• fopen()
• fseek()
• rewind()
Classification:
POSIX 1003.1 TSF
Safety
Cancellation point
Yes
Interrupt handler
No
Signal handler
No
Thread
Yes
See also:
getgrgid(), getgrgid_r(), getgrnam(), getlogin(), sysconf()
June 19, 2012
QNX Neutrino Functions and Macros
679
getgrouplist()
© 2012, QNX Software Systems Limited
Determine the group access list for a user
Synopsis:
#include <unistd.h>
int getgrouplist( const char *name,
gid_t basegid,
gid_t *groups,
int *ngroups );
Arguments:
name
The name of the user.
basegid
The basegid is automatically included in the list of groups. Typically this
value is given as the group number from the password file.
The Neutrino implementation of getgrouplist() ignores the basegid argument; see the
“Caveats,” below.
groups
A pointer to an array where the function can store the group IDs.
ngroups
A pointer to the size of the groups array. The function sets the value
pointed to by ngroups to be the actual number of groups found.
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
This function is in libc.a, but not in libc.so (in order to save space).
Description:
The getgrouplist() function reads the group file and determines the group access list
for the user specified in name.
Returns:
680
0
Success; the function fills in the group array and sets *ngroups to the number of
groups found.
-1
The groups array is too small to hold all the user’s groups. The function fills the
group array with as many groups as fit.
QNX Neutrino Functions and Macros
June 19, 2012
getgrouplist()
© 2012, QNX Software Systems Limited
Examples:
#include
#include
#include
#include
#include
<stdio.h>
<stdlib.h>
<sys/types.h>
<unistd.h>
<limits.h>
int main()
{
int ngroups, i;
gid_t groups[NGROUPS_MAX];
ngroups = NGROUPS_MAX;
if ( getgrouplist( getlogin(), getegid(), groups, &ngroups) == -1) {
printf ("Groups array is too small: %d\n", ngroups);
}
printf ("%s belongs to these groups: %d", getlogin(), getegid());
for (i=0; i < ngroups; i++) {
printf (", %d", groups[i]);
}
printf ("\n");
return EXIT_SUCCESS;
}
Files:
/etc/group
Group membership list.
Classification:
Unix
Safety
Cancellation point
Yes
Interrupt handler
No
Signal handler
Yes
Thread
Yes
Caveats:
• The getgrouplist() function uses the routines based on getgrent(). If the invoking
program uses any of these routines, the group structure will be overwritten in the
call to getgrouplist().
• This routine is BSD, and was designed for a system in which the effective group ID
is placed in the supplementary group list. Neutrino doesn’t do this, so it ignores the
basegid argument.
June 19, 2012
QNX Neutrino Functions and Macros
681
getgrouplist()
© 2012, QNX Software Systems Limited
See also:
initgroups(), setgroups()
682
QNX Neutrino Functions and Macros
June 19, 2012
getgroups()
© 2012, QNX Software Systems Limited
Get the supplementary group IDs of the calling process
Synopsis:
#include <sys/types.h>
#include <unistd.h>
int getgroups( int gidsetsize,
gid_t grouplist[] );
Arguments:
gidsetsize
The size of the grouplist array.
grouplist
An array that the function can fill in with the process’s supplementary
group IDs.
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
The getgroups() function fills the array grouplist with the supplementary group IDs of
the calling process. The values of array entries with indices greater than or equal to the
returned value are undefined.
Returns:
The number of supplementary groups IDs; this value is zero if NGROUPS_MAX is
zero. A value of -1 indicates an error (errno is set).
Errors:
EINVAL
The gidsetsize argument isn’t equal to zero, and is less than the number
of supplementary group IDs.
Examples:
/*
* Print the supplementary group IDs of
* the calling process.
*/
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
int main( void )
{
int
gidsize;
gid_t
*grouplist;
int
i;
June 19, 2012
QNX Neutrino Functions and Macros
683
getgroups()
© 2012, QNX Software Systems Limited
gidsize = getgroups( 0, NULL );
grouplist = malloc( gidsize * sizeof( gid_t ) );
getgroups( gidsize, grouplist );
for( i = 0; i < gidsize; i++ )
printf( "%d\n", ( int ) grouplist[i] );
return EXIT_SUCCESS;
}
Classification:
POSIX 1003.1
Safety
Cancellation point
No
Interrupt handler
No
Signal handler
Yes
Thread
Yes
See also:
errno, getegid(), geteuid(), getgid(), getuid(), setgroups()
684
QNX Neutrino Functions and Macros
June 19, 2012
gethostbyaddr()
© 2012, QNX Software Systems Limited
Get a network host entry, given an Internet address
Synopsis:
#include <netdb.h>
struct hostent * gethostbyaddr( const void * addr,
socklen_t len,
int type );
Arguments:
addr
A pointer to the binary-format (i.e. not NULL-terminated) address in
network byte order.
len
The length, in bytes, of addr.
type
The type of address. Currently, this must be AF_INET.
Library:
libsocket
Use the -l socket option to qcc to link against this library.
Description:
The gethostbyaddr() function searches for information associated with a host, which
has the address pointed to by addr within the address family specified by type,
opening a connection to the database if necessary.
Both gethostbyaddr() and gethostbyname() are marked as obsolete in POSIX 1003.1.
You should use getaddrinfo() or getnameinfo() instead.
This function returns a pointer to a structure of type hostent that describes an
Internet host. This structure contains either the information obtained from a name
server, or broken-out fields from a line in /etc/hosts.
You can use sethostent() to request the use of a connected TCP socket for queries. If
the stayopen flag is nonzero, all queries to the name server will use TCP and the
connection will be retained after each call to gethostbyaddr() or gethostbyname(). If
the stayopen flag is zero, queries use UDP datagrams.
Returns:
A pointer to a valid hostent structure, or NULL if an error occurs (h_errno is set).
Errors:
See herror().
June 19, 2012
QNX Neutrino Functions and Macros
685
gethostbyaddr()
© 2012, QNX Software Systems Limited
Examples:
Use the gethostbyaddr() function to find a host:
struct sockaddr_in client;
struct hostent* host;
int sock, fd, len;
.
.
.
len = sizeof( client );
fd
= accept( sock, (struct sockaddr*)&client, &len );
if( fd == -1 ) {
perror( "accept" );
exit( 1 );
}
host = gethostbyaddr( (const void*)&client.sin_addr,
sizeof(struct in_addr),
AF_INET );
printf( "Connection from %s: (%s)\n",
host ? host->h_name : "<unknown>",
inet_ntoa( client.sin_addr ) );
.
.
.
Files:
/etc/hosts
Host database file.
/etc/nsswitch.conf
Name-service switch configuration file.
Classification:
POSIX 1003.1 OBS
Safety
686
Cancellation point
Yes
Interrupt handler
No
Signal handler
No
Thread
No
QNX Neutrino Functions and Macros
June 19, 2012
© 2012, QNX Software Systems Limited
gethostbyaddr()
Caveats:
This function uses static data storage; if you need the data for future use, copy it
before any subsequent calls overwrite it. Currently, only the Internet address format is
understood.
See also:
endhostent(), gethostbyname(), gethostbyaddr_r(), gethostent(), herror(), hostent,
sethostent()
/etc/hosts, /etc/nsswitch.conf in the Utilities Reference
June 19, 2012
QNX Neutrino Functions and Macros
687
gethostbyaddr_r()
© 2012, QNX Software Systems Limited
Get a network host entry, in a thread-safe manner
Synopsis:
#include
#include
#include
#include
#include
<sys/types.h>
<sys/socket.h>
<netinet/in.h>
<arpa/inet.h>
<netdb.h>
struct hostent * gethostbyaddr_r(
const void * addr,
socklen_t length,
int type,
struct hostent * result,
char * buffer,
int buflen,
int * h_errnop );
Arguments:
addr
A pointer to the binary-format (i.e. not NULL-terminated) address in
network byte order.
length
The length, in bytes, of addr.
type
The type of address. Currently, this must be AF_INET.
result
A pointer to a struct hostent where the function can store the host
entry.
buffer
A pointer to a buffer that the function can use during the operation to
store host database entries; buffer should be large enough to hold all of
the data associated with the host entry. A 2K buffer is usually more than
enough; a 256-byte buffer is safe in most cases.
buflen
The length of the area pointed to by buffer.
h_errnop
A pointer to a location where the function can store an herrno value if
an error occurs.
Library:
libsocket
Use the -l socket option to qcc to link against this library.
Description:
The gethostbyaddr_r() function is a thread-safe version of gethostbyaddr(). This
function gets the network host entry for the host specified by addr. The addr argument
is the network address of the specified network family, type. The buffer for addr is at
least length bytes.
If you need to convert a text-based address into the format necessary for use as
gethostbyaddr_r()’s addr, see inet_pton().
688
QNX Neutrino Functions and Macros
June 19, 2012
gethostbyaddr_r()
© 2012, QNX Software Systems Limited
Returns:
Errors:
A pointer to result, or NULL if an error occurs.
If an error occurs, the int pointed to by h_errnop is set to:
The supplied buffer isn’t large enough to store the result.
ERANGE
HOST_NOT_FOUND
Authoritative answer: Unknown host.
NO_ADDRESS
No address associated with name; look for an MX record.
NO_DATA
Valid name, but no data record of the requested type. The name
is known to the name server, but has no IP address associated
with it—this isn’t a temporary error. Another type of request to
the name server using this domain name will result in an answer
(e.g. a mail-forwarder may be registered for this domain).
NO_RECOVERY
Unknown server error. An unexpected server failure was
encountered. This is a nonrecoverable network error.
TRY_AGAIN
Nonauthoritative answer: Host name lookup failure. This is
usually a temporary error and means that the local server didn’t
receive a response from an authoritative server. A retry at some
later time may succeed.
Files:
/etc/hosts
Local host database file.
/etc/nsswitch.conf
Name-service switch configuration file.
Classification:
Unix
Safety
June 19, 2012
Cancellation point
Yes
Interrupt handler
No
Signal handler
No
Thread
Yes
QNX Neutrino Functions and Macros
689
gethostbyaddr_r()
© 2012, QNX Software Systems Limited
See also:
gethostbyaddr(), gethostbyname(), gethostbyname_r(), inet_ntop(), inet_pton()
/etc/hosts, /etc/nsswitch.conf in the Utilities Reference
690
QNX Neutrino Functions and Macros
June 19, 2012
gethostbyname(), gethostbyname2()
© 2012, QNX Software Systems Limited
Get a network host entry, given a name
Synopsis:
#include <netdb.h>
struct hostent * gethostbyname( const char * name );
struct hostent * gethostbyname2( const char * name,
int af );
Arguments:
name
The name of the Internet host whose entry you want to find.
af
(gethostbyname2() only) The address family; one of:
• AF_INET
• AF_INET6
Library:
libsocket
Use the -l socket option to qcc to link against this library.
Description:
The gethostbyname() routine gets the network host entry for a given name. It returns a
pointer to a structure of type hostent that describes an Internet host. This structure
contains either the information obtained from a name server, or broken-out fields from
a line in /etc/hosts.
Both gethostbyaddr() and gethostbyname() are marked as obsolete in POSIX 1003.1.
You should use getaddrinfo() or getnameinfo() instead.
When using the name server, gethostbyname() searches for the named host in the
current domain and in the domain’s parents, unless the name ends in a dot.
• If the name server isn’t responding, there’s a timeout of 1.5 minutes per name
server.
• If the name doesn’t contain a dot, and the environment variable HOSTALIASES
contains the name of an alias file, the alias file is first searched for an alias
matching the input name. This file has the same form as /etc/hosts.
You can use sethostent() to request the use of a connected TCP socket for queries. If
the stayopen flag is nonzero, all queries to the name server use TCP and the
connection is retained after each call to gethostbyname() or gethostbyaddr(). If the
stayopen flag is zero, queries use UDP datagrams.
June 19, 2012
QNX Neutrino Functions and Macros
691
gethostbyname(), gethostbyname2()
© 2012, QNX Software Systems Limited
The gethostbyname2() function is an evolution of the gethostbyname() function that
lets you look up host names in address families other than AF_INET. If you specify an
invalid address family, the function returns NULL and sets h_errno to
NETDB_INTERNAL.
Returns:
A pointer to a valid hostent structure, or NULL if an error occurs (h_errno is set).
Errors:
See herror().
Files:
/etc/hosts
Host database file.
/etc/nsswitch.conf
Name-service switch configuration file.
For information about these files, see the Utilities Reference.
Environment variables:
HOSTALIASES
Name of the alias file that gethostbyname() is to search first
when the hostname doesn’t contain a dot.
Classification:
gethostbyname() is POSIX 1003.1 OBS; gethostbyname2() is QNX Neutrino
Safety
Cancellation point
Yes
Interrupt handler
No
Signal handler
No
Thread
No
Caveats:
This function uses static data storage; if you need the data for future use, copy it
before any subsequent calls overwrite it.
692
QNX Neutrino Functions and Macros
June 19, 2012
© 2012, QNX Software Systems Limited
gethostbyname(), gethostbyname2()
See also:
endhostent(), getaddrinfo(), gethostbyaddr(), gethostbyname_r(), gethostent(),
getnameinfo(), herror(), hostent, sethostent()
/etc/hosts, /etc/nsswitch.conf in the Utilities Reference
June 19, 2012
QNX Neutrino Functions and Macros
693
gethostbyname_r()
© 2012, QNX Software Systems Limited
Get a network host entry by name
Synopsis:
#include
#include
#include
#include
#include
<sys/types.h>
<sys/socket.h>
<netinet/in.h>
<arpa/inet.h>
<netdb.h>
struct hostent *gethostbyname_r(
const char * name,
struct hostent * result,
char * buffer,
int bufflen,
int * h_errnop );
Arguments:
name
The name of the Internet host whose entry you want to find.
result
A pointer to a struct hostent where the function can store the host
entry.
buffer
A pointer to a buffer that the function can use during the operation to
store host database entries; buffer should be large enough to hold all of
the data associated with the host entry. A 2K buffer is usually more than
enough; a 256-byte buffer is safe in most cases.
buflen
The length of the area pointed to by buffer.
h_errnop
A pointer to a location where the function can store an herrno value if
an error occurs.
Library:
libsocket
Use the -l socket option to qcc to link against this library.
Description:
The gethostbyname_r() function is a thread-safe version of gethostbyname(). This
function gets the network host entry for the host specified by name, and stores the
entry in the struct hostent pointed to by result.
Returns:
A pointer to result, or NULL if an error occurs.
694
QNX Neutrino Functions and Macros
June 19, 2012
gethostbyname_r()
© 2012, QNX Software Systems Limited
Errors:
If an error occurs, the int pointed to by h_errnop is set to:
ERANGE
The supplied buffer isn’t large enough to store the result.
HOST_NOT_FOUND
Authoritative answer: Unknown host.
NO_ADDRESS
No address associated with name; look for an MX record.
NO_DATA
Valid name, but no data record of the requested type. The name
is known to the name server, but has no IP address associated
with it—this isn’t a temporary error. Another type of request to
the name server using this domain name will result in an answer
(e.g. a mail-forwarder may be registered for this domain).
NO_RECOVERY
Unknown server error. An unexpected server failure was
encountered. This is a nonrecoverable network error.
TRY_AGAIN
Nonauthoritative answer: Host name lookup failure. This is
usually a temporary error and means that the local server didn’t
receive a response from an authoritative server. A retry at some
later time may succeed.
Files:
/etc/hosts
Local host database file.
/etc/nsswitch.conf
Name-service switch configuration file.
For information about these files, see the Utilities Reference.
Classification:
Unix
Safety
June 19, 2012
Cancellation point
Yes
Interrupt handler
No
Signal handler
No
Thread
Yes
QNX Neutrino Functions and Macros
695
gethostbyname_r()
© 2012, QNX Software Systems Limited
See also:
gethostbyaddr(), gethostbyaddr_r(), gethostbyname()
/etc/hosts, /etc/nsswitch.conf in the Utilities Reference
696
QNX Neutrino Functions and Macros
June 19, 2012
gethostent()
© 2012, QNX Software Systems Limited
Read the next line of the host database file
Synopsis:
#include <netdb.h>
struct hostent * gethostent( void );
Library:
libsocket
Use the -l socket option to qcc to link against this library.
Description:
The gethostent() routine reads the next line in the host database file.
Returns:
A pointer to a valid hostent structure, or NULL if an error occurs.
Files:
/etc/hosts
Host database file.
/etc/resolv.conf
Resolver configuration file.
Classification:
POSIX 1003.1
Safety
Cancellation point
Yes
Interrupt handler
No
Signal handler
No
Thread
No
Caveats:
This function uses static data storage; if you need the data for future use, copy it
before any subsequent calls overwrite it.
Currently, this function understands only the Internet address format.
June 19, 2012
QNX Neutrino Functions and Macros
697
gethostent()
© 2012, QNX Software Systems Limited
See also:
endhostent(), gethostbyaddr(), gethostbyname(), gethostent_r(), hostent,
sethostent()
/etc/hosts, /etc/resolv.conf in the Utilities Reference
698
QNX Neutrino Functions and Macros
June 19, 2012
gethostent_r()
© 2012, QNX Software Systems Limited
Read the next line of the host database file
Synopsis:
#include
#include
#include
#include
#include
<sys/types.h>
<sys/socket.h>
<netinet/in.h>
<arpa/inet.h>
<netdb.h>
struct hostent * gethostent_r( FILE ** hostf ,
struct hostent * result,
char * buffer,
int buflen,
int * h_errnop );
Arguments:
hostf
NULL, or the address of the FILE * pointer associated with the host
database file.
result
A pointer to a struct hostent where the function can store the host
entry.
buffer
A pointer to a buffer that the function can use during the operation to
store host database entries; buffer should be large enough to hold all of
the data associated with the host entry. A 2K buffer is usually more than
enough; a 256-byte buffer is safe in most cases.
buflen
The length of the area pointed to by buffer.
h_errnop
A pointer to a location where the function can store an herrno value if
an error occurs.
Library:
libsocket
Use the -l socket option to qcc to link against this library.
Description:
The gethostent_r() function is a thread-safe version of the gethostent() function. This
function gets the local host’s entry. If the pointer pointed to by hostf is NULL,
gethostent_r() opens /etc/hosts and returns its file pointer in hostf for later use.
It’s the calling process’s responsibility to close the host file with fclose().
The first time that you call gethostent_r(), pass NULL in the pointer pointed to by
hostf .
June 19, 2012
QNX Neutrino Functions and Macros
699
gethostent_r()
© 2012, QNX Software Systems Limited
Returns:
Errors:
A pointer to result, or NULL if an error occurs.
If an error occurs, the int pointed to by h_errnop is set to:
The supplied buffer isn’t large enough to store the result.
ERANGE
HOST_NOT_FOUND
Authoritative answer: Unknown host.
NO_ADDRESS
No address associated with name, look for an MX record.
NO_DATA
Valid name, no data record of the requested type. The name is
known to the name server, but has no IP address associated with
it—this isn’t a temporary error. Another type of request to the
name server using this domain name will result in an answer
(e.g. a mail-forwarder may be registered for this domain).
NO_RECOVERY
Unknown server error. An unexpected server failure was
encountered. This is a nonrecoverable network error.
TRY_AGAIN
Nonauthoritative answer: Host name lookup failure. This is
usually a temporary error and means that the local server didn’t
receive a response from an authoritative server. A retry at some
later time may succeed.
Files:
/etc/hosts
Local host database file.
Classification:
Unix
Safety
700
Cancellation point
Yes
Interrupt handler
No
Signal handler
No
Thread
Yes
QNX Neutrino Functions and Macros
June 19, 2012
© 2012, QNX Software Systems Limited
gethostent_r()
See also:
endhostent(), gethostent(), sethostent()
/etc/hosts in the Utilities Reference
June 19, 2012
QNX Neutrino Functions and Macros
701
gethostname()
© 2012, QNX Software Systems Limited
Get the name of the current host
Synopsis:
#include <unistd.h>
int gethostname( char * name,
size_t namelen );
Arguments:
name
A buffer where the function can store the host name.
namelen
The size of the buffer.
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
The gethostname() function stores in name the standard hostname for the current
processor, as previously set by sethostname(). The parameter namelen specifies the
size of the name array. The returned name is NULL-terminated unless insufficient
space is provided.
This function gets the value of the _CS_HOSTNAME configuration string, not that of the
HOSTNAME environment variable.
Returns:
0
Success.
-1
An error occurred (errno isn’t set).
Classification:
POSIX 1003.1
Safety
702
Cancellation point
Yes
Interrupt handler
No
Signal handler
Yes
Thread
Yes
QNX Neutrino Functions and Macros
June 19, 2012
© 2012, QNX Software Systems Limited
gethostname()
Caveats:
Hostnames are limited to MAXHOSTNAMELEN characters (defined in
<sys/param.h>).
See also:
sethostname()
June 19, 2012
QNX Neutrino Functions and Macros
703
getifaddrs()
© 2012, QNX Software Systems Limited
Get a network interface address
Synopsis:
#include <sys/types.h>
#include <sys/socket.h>
#include <ifaddrs.h>
int getifaddrs( struct ifaddrs ** ifap );
Arguments:
ifap
The address of a location where the function can store a pointer to a linked list
of ifaddrs structures that contain the data related to the network interfaces
on the local machine.
Library:
libsocket
Use the -l socket option to qcc to link against this library.
Description:
The getifaddrs() function stores a reference to a linked list of the network interfaces on
the local machine in the memory referenced by ifap.
The data returned by getifaddrs() is dynamically allocated; you should free it by
calling freeifaddrs() when you no longer need it.
Returns:
0
Success.
-1
An error occurred (errno is set).
Errors:
The getifaddrs() function may fail and set errno for any of the errors specified by
ioctl(), malloc(), socket(), and sysctl().
Classification:
Unix
Safety
704
Cancellation point
Yes
Interrupt handler
No
Signal handler
No
Thread
Yes
QNX Neutrino Functions and Macros
June 19, 2012
getifaddrs()
© 2012, QNX Software Systems Limited
See also:
errno, freeifaddrs(), ifaddrs, ioctl(), malloc(), socket(), sysctl()
June 19, 2012
QNX Neutrino Functions and Macros
705
GETIOVBASE()
© 2012, QNX Software Systems Limited
Get the base member of an iov_t structure
Synopsis:
#include <sys/types.h>
#include <unistd.h>
#define GETIOVBASE( _iov ) ...
Arguments:
_iov
A pointer to the iov_t structure you want to get the base member from.
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
This macro evaluates to the iov_base member of the given iov_t structure.
Returns:
The iov_base member of the iov_t structure, which is of type void *.
Classification:
QNX Neutrino
Safety
Cancellation point
No
Interrupt handler
Yes
Signal handler
Yes
Thread
Yes
See also:
GETIOVLEN(), SETIOV()
706
QNX Neutrino Functions and Macros
June 19, 2012
GETIOVLEN()
© 2012, QNX Software Systems Limited
Get the length member of an iov_t structure
Synopsis:
#include <sys/types.h>
#include <unistd.h>
#define GETIOVLEN( _iov ) ...
Arguments:
_iov
A pointer to the iov_t structure you want to get the length member from.
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
This macro evaluates to the iov_len member of the given iov_t structure.
Returns:
The iov_len member of the iov_t structure, which is of type size_t.
Classification:
QNX Neutrino
Safety
Cancellation point
No
Interrupt handler
Yes
Signal handler
Yes
Thread
Yes
See also:
GETIOVBASE(), SETIOV()
June 19, 2012
QNX Neutrino Functions and Macros
707
getitimer()
© 2012, QNX Software Systems Limited
Get the value of an interval timer
Synopsis:
#include <sys/time.h>
int getitimer ( int which,
struct itimerval *value );
Arguments:
which
The interval time whose value you want to get. Currently, this must be
ITIMER_REAL.
value
A pointer to a itimerval structure where the function can store the value
of the interval timer.
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
The system provides each process with several interval timers, defined in
<sys/time.h>. The getitimer() function stores the current value of the timer
specified by which into the structure pointed to by value.
A timer value is defined by the itimerval structure (see gettimeofday() for the
definition of timeval), which includes the following members:
struct timeval
struct timeval
it_interval;
it_value;
/* timer interval */
/* current value */
The it_value member indicates the time to the next timer expiration. The it_interval
member specifies a value to be used in reloading it_value when the timer expires.
Setting it_value to 0 disables a timer, regardless of the value of it_interval. Setting
it_interval to 0 disables a timer after its next expiration (assuming it_value is
nonzero).
Time values smaller than the resolution of the system clock are rounded up to the
resolution of the system clock.
The interval timers include:
ITIMER_REAL
708
QNX Neutrino Functions and Macros
Decrements in real time. A SIGALRM signal is delivered when this
timer expires.
June 19, 2012
getitimer()
© 2012, QNX Software Systems Limited
Returns:
0
-1
Success.
An error occurred (errno is set).
Errors:
EINVAL
The specified number of seconds is greater than 100,000,000, the number
of microseconds is greater than or equal to 1,000,000, or the which
argument is unrecognized.
Classification:
POSIX 1003.1 XSI
Safety
Cancellation point
No
Interrupt handler
No
Signal handler
Yes
Thread
Yes
See also:
alarm(), gettimeofday(), pthread_attr_setscope(), pthread_sigmask(), setitimer(),
sigprocmask(), sleep(), sysconf()
Tick, Tock: Understanding the Neutrino Microkernel’s Concept of Time chapter of the
QNX Neutrino Programmer’s Guide
June 19, 2012
QNX Neutrino Functions and Macros
709
getlogin()
© 2012, QNX Software Systems Limited
Get the user name associated with the calling process
Synopsis:
#include <unistd.h>
char* getlogin( void ) ;
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
This function is in libc.a, but not in libc.so (in order to save space).
Description:
The getlogin() function returns a pointer to a string containing the login name of the
user associated with the calling process.
Returns:
A pointer to a string containing the user’s login name, or NULL if the user’s login
name can’t be found.
The return value from getlogin() may point to static data and, therefore, may be
overwritten by each call.
Classification:
POSIX 1003.1
Safety
Cancellation point
Yes
Interrupt handler
No
Signal handler
No
Thread
No
See also:
getlogin_r(), getpwent(), getpwent_r(), getpwnam(), getpwuid()
710
QNX Neutrino Functions and Macros
June 19, 2012
getlogin_r()
© 2012, QNX Software Systems Limited
Get the user name associated with the calling process
Synopsis:
#include <unistd.h>
int getlogin_r( char* name,
size_t namesize );
Arguments:
name
A buffer where the function can store the user name.
namesize
The size of the buffer.
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
This function is in libc.a, but not in libc.so (in order to save space).
Description:
If _POSIX_THREAD_SAFE_FUNCTIONS is defined, the getlogin_r() function puts the
login name of the user associated with the calling process in the character array
pointed to by name. The array is namesize characters long and should have space for
the name and the terminating NULL character. The maximum size of the login name is
_POSIX_LOGIN_NAME_MAX.
If getlogin_r() is successful, name points to the name the user used at login, even if
there are several login names with the same user ID.
Returns:
EOK
Success.
ERANGE
Insufficient storage was supplied via the name and namesize arguments
to contain the user’s name.
Classification:
POSIX 1003.1 TSF
Safety
Cancellation point
Yes
Interrupt handler
No
continued. . .
June 19, 2012
QNX Neutrino Functions and Macros
711
getlogin_r()
© 2012, QNX Software Systems Limited
Safety
Signal handler
No
Thread
Yes
See also:
getlogin(), getpwnam(), getpwnam_r(), getpwuid(), getpwuid_r()
712
QNX Neutrino Functions and Macros
June 19, 2012
getnameinfo()
© 2012, QNX Software Systems Limited
Perform address-to-nodename translation in a protocol-independent manner
Synopsis:
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
int getnameinfo(const struct sockaddr *sa,
socklen_t salen,
char *host, size_t hostlen,
char *serv, size_t servlen,
int flags);
Arguments:
sa
Points to either a sockaddr_in structure (for IPv4) or a sockaddr_in6
structure (for IPv6) that holds the IP address and port number.
salen
Length of the sockaddr_in or sockaddr_in6 structure.
host
Buffer pointer for the host.
hostlen
Size of the host buffer.
serv
Buffer pointer for the server.
servlen
Length of the server buffer.
flags
Change the default action of getnameinfo(). By default, the fully qualified
domain name (FQDN) for the host is looked up in the DNS and returned.
These flags are defined in <netdb.h>:
Only the nodename portion of the FQDN is
returned for local hosts.
NI_NUMERICHOST If set, or if the host’s name can’t be located in the
DNS, the numeric form of the host’s address is
returned instead of its name (e.g. by calling
inet_ntop() instead of getnodebyaddr()).
NI_NAMEREQD
If set, an error is returned when the host’s name
can’t be located in the DNS.
NI_NUMERICSERV If set, the numeric form of the service address
(instead of its name) is returned e.g. its port
number. You may require two NI_NUMERICxxx
flags to support the -n flag that many commands
provide.
NI_DGRAM
Specify that the service is a datagram service. Call
getservbyport() with a second argument of udp
instead of its default of tcp. This is required for the
few ports (512-514) that have different services for
UDP and TCP.
NI_NOFQDN
June 19, 2012
QNX Neutrino Functions and Macros
713
getnameinfo()
© 2012, QNX Software Systems Limited
Library:
libsocket
Use the -l socket option to qcc to link against this library.
Description:
The getnameinfo() function defines and performs protocol-independent
address-to-nodename translation. You can think of it as implementing the
reverse-functionality of getaddrinfo() or similar functionality of gethostbyaddr() or
getservbypor().
This function looks up an IP address and port number provided by the caller in the
DNS and system-specific database. For both IP address and port number, the
getnameinfo() function returns text strings in respective buffers provided by the caller.
The function indicates successful completion by a zero return value; a non-zero return
value indicates failure.
The getnameinfo() function returns the nodename associated with the IP address in the
buffer pointed to by the host argument. The hostlen argument gives the length of this
buffer.
The getnameinfo() function returns the service name associated with the port number
in the buffer pointed to by the serv argument. The servlen argument gives the length of
this buffer.
Specify zero for hostlen or servlen when the caller chooses not to return either string.
Otherwise, the caller must provide buffers large enough to hold the nodename and the
service name, including the terminating null characters.
Most systems don’t provide constants that specify the maximum size of either a
FQDN or a service name. In order to aid your application in allocating buffers, the
following constants are defined in <netdb.h>:
#define NI_MAXHOST
#define NI_MAXSERV
1025
32
You may find the first value as the constant MAXDNAME in recent versions of BIND’s
<arpa/nameser.h>; older versions of BIND define this constant to be 256. The
second value is a guess based on the services listed in the current Assigned Numbers
RFC. BIND (Berkeley Internet Name Domain) is a suite of functionalities that
implements Domain Name System (DNS) protocols.
Extension
The implementation allows experimental numeric IPv6 address notation with scope
identifier. An IPv6 link-local address appears as string like fe80::1%ne0, when the
NI_WITHSCOPEID bit is enabled in the flags argument. See getaddrinfo() for the
notation.
714
QNX Neutrino Functions and Macros
June 19, 2012
getnameinfo()
© 2012, QNX Software Systems Limited
Returns:
0
Success.
Non-zero value
An error occurred (see below).
Errors:
EAI_AGAIN
The name couldn’t be resolved at this time. Future attempts may
succeed.
EAI_BADFLAGS
The flags had invalid values.
EAI_FAIL
A nonrecoverable error occurred.
EAI_FAMILY
The address family wasn’t recognized or the address length was
invalid for the specified family.
EAI_MEMORY
There was a memory allocation failure.
EAI_NONAME
The name doesn’t resolve for the supplied parameters.
NI_NAMEREQD is set and the host’s name can’t be located, or
both node name and serv name were null.
EAI_SYSTEM
A system error occurred. The error code can be found in errno.
Examples:
The following code gets the numeric hostname and the service name for a given socket
address. There is no hardcoded reference to a particular address family.
struct sockaddr *sa;
/* input */
char hbuf[NI_MAXHOST], sbuf[NI_MAXSERV];
if (getnameinfo(sa, sa->sa_len, hbuf, sizeof(hbuf), sbuf,
sizeof(sbuf), NI_NUMERICHOST | NI_NUMERICSERV)) {
errx(1, "could not get numeric hostname");
/*NOTREACHED*/
}
printf("host=%s, serv=%s\n", hbuf, sbuf);
The following version checks if the socket address has reverse address mapping.
struct sockaddr *sa;
char hbuf[NI_MAXHOST];
/* input */
if (getnameinfo(sa, sa->sa_len, hbuf, sizeof(hbuf), NULL, 0,
NI_NAMEREQD)) {
errx(1, "could not resolve hostname"); /*NOTREACHED*/
}
printf("host=%s\n", hbuf);
June 19, 2012
QNX Neutrino Functions and Macros
715
getnameinfo()
© 2012, QNX Software Systems Limited
Classification:
POSIX 1003.1
Safety
Cancellation point
Yes
Interrupt handler
No
Signal handler
No
Thread
No
See also:
getaddrinfo(), gethostbyaddr(), getservbyport(), /etc/hosts,
/etc/nsswitch.conf, /etc/services, named
716
QNX Neutrino Functions and Macros
June 19, 2012
getnetbyaddr()
© 2012, QNX Software Systems Limited
Get a network entry, given an address (Unix)
Synopsis:
#include <netdb.h>
struct netent * getnetbyaddr( uint32_t net,
int type );
Arguments:
net
The net address whose network entry you want to find.
type
The address type. This must currently be AF_INET.
Library:
libsocket
Use the -l socket option to qcc to link against this library.
Description:
The getnetbyaddr() function gets an entry for the given address, net, from the network
database, /etc/networks.
This function returns a pointer to a structure of type netent, which contains the
broken-out fields of a line in the network database.
The setnetent() function opens and rewinds the file. If you pass a nonzero stayopen
argument to setnetent(), the network database isn’t closed after each call to
getnetbyname(), or getnetbyaddr().
The getnetbyname() and getnetbyaddr() functions sequentially search from the
beginning of the file until a matching net name or net address and type is found, or
until EOF is encountered. Network numbers are supplied in host order.
Returns:
A pointer to a valid netent structure, or NULL if an error occurs.
Files:
/etc/networks
Network name database file.
/etc/nsswitch.conf
Name-service switch configuration file.
Classification:
POSIX 1003.1
June 19, 2012
QNX Neutrino Functions and Macros
717
getnetbyaddr()
© 2012, QNX Software Systems Limited
Safety
Cancellation point
Yes
Interrupt handler
No
Signal handler
No
Thread
No
Caveats:
This function uses static data; if you need the data for future use, copy it before any
subsequent calls overwrite it.
Only Internet network numbers are currently understood.
See also:
endnetent(), getnetbyname(), getnetent(), netent, setnetent()
/etc/networks, /etc/nsswitch.conf in the Utilities Reference
718
QNX Neutrino Functions and Macros
June 19, 2012
getnetbyname()
© 2012, QNX Software Systems Limited
Get a network entry, given a name
Synopsis:
#include <netdb.h>
struct netent * getnetbyname( const char * name );
Arguments:
name
The name of the network whose entry you want to find.
Library:
libsocket
Use the -l socket option to qcc to link against this library.
Description:
The getnetbyname() function gets the network entry for the given name. This function
returns a pointer to a structure of type netent, which contains the broken-out fields of
a line in the network database, /etc/networks.
The setnetent() function opens and rewinds the file. If you pass a nonzero stayopen
argument to setnetent(), the network database isn’t closed after each call to
getnetbyname() or getnetbyaddr().
The getnetbyaddr() and getnetbyname() functions sequentially search from the
beginning of the file until a matching net name or net address and type is found, or
until EOF is encountered. Network numbers are supplied in host order.
Returns:
A pointer to a valid netent structure, or NULL if an error occurs.
Files:
/etc/networks
Network name database file.
/etc/nsswitch.conf
Name-service switch configuration file.
Classification:
POSIX 1003.1
Safety
Cancellation point
Yes
Interrupt handler
No
continued. . .
June 19, 2012
QNX Neutrino Functions and Macros
719
getnetbyname()
© 2012, QNX Software Systems Limited
Safety
Signal handler
No
Thread
No
See also:
endnetent(), getnetbyaddr(), getnetent(), netent, setnetent()
/etc/networks, /etc/nsswitch.conf in the Utilities Reference
720
QNX Neutrino Functions and Macros
June 19, 2012
getnetent()
© 2012, QNX Software Systems Limited
Read the next line of the network name database file
Synopsis:
#include <netdb.h>
struct netent * getnetent( void );
Library:
libsocket
Use the -l socket option to qcc to link against this library.
Description:
The getnetent() function reads the next line of the network name database file, opening
the file if necessary. It returns a pointer to a structure of type netent, which contains
the broken-out fields of a line in the network database, /etc/networks.
Returns:
A pointer to a valid netent structure, or NULL if an error occurs.
Files:
/etc/networks
Network name database file.
Classification:
POSIX 1003.1
Safety
Cancellation point
Yes
Interrupt handler
No
Signal handler
No
Thread
No
See also:
endnetent(), getnetbyaddr(), getnetbyname(), netent, setnetent()
/etc/networks in the Utilities Reference
June 19, 2012
QNX Neutrino Functions and Macros
721
getopt()
© 2012, QNX Software Systems Limited
Parse options from a command line
Synopsis:
#include <unistd.h>
int getopt( int argc,
char * const argv[],
const char * optstring );
extern char * optarg;
extern int optind, opterr, optopt;
Arguments:
argc
The argument count that was passed to main().
argv
The argument array that was passed to main().
optstring
A string of recognized option letters; if a letter is followed by a colon,
the option takes an argument. Valid option characters for optstring
consist of a single alphanumeric character (i.e. a letter or digit).
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
The getopt() function is a command-line parser that can be used by applications that
follow the Utility Syntax Guidelines described below.
The optind global variable is the index of the next element of the argv[] vector to be
processed. The system initializes optind to 1 when the program is loaded, and getopt()
updates it when it finishes with each element of argv[]. Reset optind to 1 if you want
to use getopt() to process additional argument sets.
The getopt() function returns the next option character from argv that matches a letter
in optstring, if there’s one that matches. If the option takes an argument, getopt() sets
the global variable optarg to point to the option argument as follows:
1
If the option is the last letter in the string pointed to by an element of argv, then
optarg contains the next element of argv, and optind is incremented by 2.
2
Otherwise, optarg points to the string following the option letter in that element
of argv, and optind is incremented by 1.
The getopt() function returns -1 is returned and doesn’t change optind if:
• argv[optind] is NULL
• *argv[optind] isn’t the character ’-’
722
QNX Neutrino Functions and Macros
June 19, 2012
getopt()
© 2012, QNX Software Systems Limited
• argv[optind] points to the string "-".
This function returns -1 after incrementing optind, if:
• argv[optind] points to the string "--".
If getopt() encounters an option character that isn’t contained in optstring, it returns
the ? character. If it detects a missing option argument, getopt() returns:
• a colon (:) if the first character of optstring is a colon
or:
• a question mark (?) otherwise
and sets optopt to the option character that caused the error.
The getopt() always prints a diagnostic message to stderr unless opterr is set to 0, or
the first character of optstring is a : character.
Utility Syntax Guidelines
The getopt() function may be used by applications that follow these guidelines:
• When describing the syntax of a utility, the options are listed in alphabetical order.
There’s no implied relationship between the options based upon the order in which
they appear, unless otherwise stated in the Options section, or:
- the options are documented as mutually-exclusive and such an option is
documented to override any incompatible options preceding it
- when an option has option arguments repeated, the option and option argument
combinations are interpreted in the order specified on the command line.
If an option that doesn’t have option arguments is repeated, the results depend on
the application.
• Names of parameters that require substitution by actual values may be shown with
embedded underscores or as <parameter name>. Angle brackets are used for the
symbolic grouping of a phrase representing a single parameter and portable
applications shouldn’t include them in data submitted to the utility.
• Options may be documented individually, or grouped (if they don’t take option
arguments):
utility_name [-a] [-b] [-c option_argument]
[-d|-e] [-foption_argument] [operand...]
Or:
utility_name [-ab] [-c option_argument]
[-d|-e] [-foption_argument] [operand...]
Utilities with very complex arguments may be shown as:
utility_name [options] [operand]
June 19, 2012
QNX Neutrino Functions and Macros
723
getopt()
© 2012, QNX Software Systems Limited
• Unless specified, whenever an operand or option argument is, or contains, a
numeric value:
- the number is interpreted as a decimal integer
- numerals in the range 0 to 2,147,483,647 are syntactically recognized as
numeric values
- when the utility description states that it accepts negative numbers as operands
or option arguments, numerals in the range -2,147,483,647 to 2,147,483,647 are
syntactically recognized as numeric values
- ranges greater than those listed here are allowed.
All numbers within the allowable range aren’t necessarily semantically correct. A
standard utility that accepts an option argument or operand that’s to be interpreted
as a number, and for which a range of values smaller than that shown above is
permitted, describes that smaller range along with the description of the option
argument or operand. If an error is generated, the utility’s diagnostic message
indicates that the value is out of the supported range, not that it’s syntactically
incorrect.
• Arguments or option arguments enclosed in the “[” and “]” notation are optional
and can be omitted. Portable applications shouldn’t include the “[” and “]” symbols
in data submitted to the utility.
• Ellipses (. . . ) are used to denote that one or more occurrences of an option or
operand are allowed. When an option or an operand followed by ellipses is
enclosed in brackets, zero or more options or operands may be specified. The
forms:
utility_name -f option_argument...[operand...]
utility_name [-g option_argument]...[operand...]
indicate that multiple occurrences of the option and its option argument preceding
the ellipses are valid, with semantics as indicated in the Options section of the
utility. In the first example, each option argument requires a preceding -f and at
least one -foption_argument must be given.
• When the synopsis is too long to be printed on a single line in the documentation,
the indented lines following the initial line are continuation lines. An actual use of
the command appears on a single logical line.
Returns:
One of the following:
• the next option character specified on the command line
• a colon if a missing argument is detected and the first character of optstring is a
colon
724
QNX Neutrino Functions and Macros
June 19, 2012
getopt()
© 2012, QNX Software Systems Limited
• a question mark if a missing argument is detected and the first character of
optstring isn’t a colon
• a question mark if an option character is encountered that’s not in optstring
• -1 when all command-line options have been parsed
Examples:
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
int main( int argc, char* argv[] )
{
int c, errflag = 0;
while( ( c = getopt( argc, argv, "abt:" ) )
!= -1 ) {
switch( c ) {
case ’a’: printf( "apples\n" );
break;
case ’b’: printf( "bananas\n" );
break;
case ’t’: printf( "tree = %s\n", optarg );
break;
case ’?’: ++errflag;
break;
}
}
return EXIT_SUCCESS;
}
Classification:
POSIX 1003.1
Safety
Cancellation point
Yes
Interrupt handler
No
Signal handler
No
Thread
No
See also:
getsubopt(), stderr
Guidelines 3,4,5,6,7,9 and 10 in the Base Definitions volume of the IEEE
Std.1003.1-2001, Section 12.2, Utility Syntax Guidelines.
June 19, 2012
QNX Neutrino Functions and Macros
725
getpagesize()
© 2012, QNX Software Systems Limited
Get the current page size (Legacy Unix)
Synopsis:
#include <unistd.h>
int getpagesize(void);
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
The getpagesize() function gets the current page size. It’s equivalent to:
sysconf(_SC_PAGESIZE)
The value that getpagesize() returns might not be the minimum value that malloc() can
allocate, and you shouldn’t assume you can actually allocate an object of this size.
Because getpagesize() returns an int, it might not represent large values correctly.
You should use sysconf() instead.
Returns:
The current page size.
Classification:
Legacy Unix
Safety
Cancellation point
No
Interrupt handler
No
Signal handler
Yes
Thread
Yes
See also:
getpagesizes() getrlimit(), malloc(), mmap(), mprotect(), munmap(), sysconf()
726
QNX Neutrino Functions and Macros
June 19, 2012
getpagesizes(), getpagesizes64()
© 2012, QNX Software Systems Limited
Get the available page sizes
Synopsis:
#include <sys/mman.h>
int getpagesizes( size_t pagesize[],
int nelem );
int getpagesizes64( uint64_t pagesize[],
int nelem );
Arguments:
pagesize
NULL, or an array where the function can store the available page sizes.
nelem
The number of elements in the array.
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
The getpagesizes() and getpagesizes64() functions get the available page sizes and
store up to nelem of them in the pagesize array. Software that wants to optimize its
usage of large pages can use these functions to determine what sizes are available.
If you use getpagesizes64(), some page sizes will have the
_SYS_GETPAGESIZES_HIGHUSAGE bit (defined in <sys/sysmsg.h>) set to
indicate that they’re available only when mapping objects marked with the
SHMCTL_HIGHUSAGE flag. These page sizes aren’t included in the list provided by
getpagesizes().
If you pass NULL for pagesize and 0 for nelem, the functions return the number of
available page sizes.
Returns:
The number of entries filled in the array, or -1 if an error occurred (errno is set).
Errors:
EINVAL
June 19, 2012
The value of the nelem argument is negative, or it’s positive, but pagesize
is NULL.
QNX Neutrino Functions and Macros
727
getpagesizes(), getpagesizes64()
© 2012, QNX Software Systems Limited
Examples:
#include <stdio.h>
#include <stdlib.h>
#include <sys/mman.h>
int main ( void )
{
size_t *pagesizes;
int i, num_found;
num_found = getpagesizes( NULL, 0 );
if (num_found <= 0)
{
printf ("num_found is %d\n", num_found);
return EXIT_FAILURE;
}
pagesizes = (size_t *) malloc ( num_found * sizeof (size_t));
if (pagesizes == NULL)
{
perror ("malloc()");
return EXIT_FAILURE;
}
num_found = getpagesizes( pagesizes, NUM_SIZES );
printf ("Found %d sizes:\n", num_found);
for (i=0; i < num_found; i++)
{
printf ("
%d\n", pagesizes[i]);
}
return EXIT_SUCCESS;
}
Classification:
getpagesizes() is Unix; getpagesizes64() is QNX Neutrino
Safety
Cancellation point
No
Interrupt handler
No
Signal handler
Yes
Thread
Yes
See also:
getpagesize()
728
QNX Neutrino Functions and Macros
June 19, 2012
getpass()
© 2012, QNX Software Systems Limited
Prompt for and read a password
Synopsis:
#include <unistd.h>
char *getpass( const char *prompt );
Arguments:
prompt
The string you want to display to prompt for the password.
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
This function is in libc.a, but not in libc.so (in order to save space).
Description:
The getpass() function can be used to get a password. It opens the current terminal,
displays the given prompt, suppresses echoing, reads up to 32 characters into a static
buffer, and restores echoing. This function adds a null character to the end of the
string, but ignores additional characters and the newline character.
Returns:
A pointer to the static buffer.
Classification:
Legacy Unix
Safety
Cancellation point
Yes
Interrupt handler
No
Signal handler
No
Thread
No
Caveats:
This function leaves its result in an internal static buffer and returns a pointer to it.
Subsequent calls to getpass() modify the same buffer. The calling process should zero
June 19, 2012
QNX Neutrino Functions and Macros
729
getpass()
© 2012, QNX Software Systems Limited
the password as soon as possible to avoid leaving the clear-text password visible in the
process’s address space.
See also:
crypt()
730
QNX Neutrino Functions and Macros
June 19, 2012
getpeereid()
© 2012, QNX Software Systems Limited
Get the effective credentials of a UNIX-domain peer
Synopsis:
#include <sys/types.h>
#include <unistd.h>
int getpeereid( int s,
uid_t *euid,
gid_t *egid );
Arguments:
s
A UNIX-domain socket (see the UNIX protocol) of type SOCK_STREAM on
which either you’ve called connect(), or one returned from accept() after
you’ve called bind() and listen().
euid
NULL, or a pointer to a location where the function can store the effective
user ID.
egid
NULL, or a pointer to a location where the function can store the effective
group ID.
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
The getpeereid() function gets the effective user and group IDs of the peer connected
to a UNIX-domain socket. If euid and egid are non-NULL, the function stores the IDs
in the locations they point to.
If you got the socket by calling connect(), the credentials are those of your peer when
you called bind(). If the socket was one returned from accept(), the credentials are
those of your peer when you called connect(). This mechanism is reliable; there is no
way for either side to influence the credentials returned to its peer except by calling the
appropriate system call (i.e., either connect() or bind()) under different effective
credentials.
UNIX-domain servers and clients commonly use this function to verify each other’s
credentials.
Returns:
June 19, 2012
0
Success.
-1
An error occurred; errno is set.
QNX Neutrino Functions and Macros
731
getpeereid()
© 2012, QNX Software Systems Limited
Errors:
EBADF
ENOTSOCK
The argument s isn’t a valid descriptor.
The argument s is a file, not a socket.
ENOTCONN
The argument s doesn’t refer to a socket on which you’ve called
connect(), or isn’t one returned by listen().
EINVAL
The argument s doesn’t refer to a socket of type SOCK_STREAM, or
the system returned invalid data.
Classification:
NetBSD
Safety
Cancellation point
No
Interrupt handler
No
Signal handler
Yes
Thread
Yes
See also:
accept(), bind(), connect(), listen(), UNIX protocol
732
QNX Neutrino Functions and Macros
June 19, 2012
getpeername()
© 2012, QNX Software Systems Limited
Get the name of the peer connected to a socket
Synopsis:
#include <sys/socket.h>
int getpeername( int s,
struct sockaddr * name,
socklen_t * namelen );
Arguments:
s
The socket whose connected peer you want to get.
name
A buffer where the function can store the name of the peer.
namelen
A pointer to a socklen_t object that initially specifies the size of the
buffer. This function stores the actual size of the name, in bytes, in this
object.
Library:
libsocket
Use the -l socket option to qcc to link against this library.
Description:
The getpeername() function returns the name of the peer connected to socket s. The
name is truncated if the buffer provided is too small.
Returns:
0
Success.
-1
An error occurred (errno is set).
Errors:
June 19, 2012
EBADF
Invalid descriptor s.
EFAULT
The name parameter points to memory not in a valid part of the
process address space.
ENOBUFS
Insufficient resources were available in the system to perform the
operation.
ENOTCONN
The socket isn’t connected.
QNX Neutrino Functions and Macros
733
getpeername()
© 2012, QNX Software Systems Limited
Classification:
POSIX 1003.1
Safety
Cancellation point
Yes
Interrupt handler
No
Signal handler
No
Thread
Yes
See also:
accept(), bind(), getsockname(), socket()
734
QNX Neutrino Functions and Macros
June 19, 2012
getpgid()
© 2012, QNX Software Systems Limited
Get a process group ID
Synopsis:
#include <unistd.h>
pid_t getpgid( pid_t pid );
Arguments:
pid
The ID of the process whose process group ID you want to get.
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
The getpgid() returns the group ID for the process specified by pid. If pid is 0,
getpgid() returns the calling process’s group ID.
The following definitions are worth mentioning:
Process
An executing instance of a program, identified by a nonnegative
integer called a process ID.
Process group
A collection of one or more processes, with a unique process group
ID. A process group ID is a positive integer.
Returns:
A process group ID for success, or (pid_t)-1 if an error occurs.
Errors:
If an error occurs, errno is set to:
ESRCH
The process specified by pid doesn’t exist.
Classification:
POSIX 1003.1 XSI
Safety
Cancellation point
No
Interrupt handler
No
continued. . .
June 19, 2012
QNX Neutrino Functions and Macros
735
getpgid()
© 2012, QNX Software Systems Limited
Safety
Signal handler
Yes
Thread
Yes
See also:
getsid(), setpgid(), setsid()
736
QNX Neutrino Functions and Macros
June 19, 2012
getpgrp()
© 2012, QNX Software Systems Limited
Get the process group
Synopsis:
#include <sys/types.h>
#include <process.h>
pid_t getpgrp( void );
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
The getpgrp() function gets the ID of the process group to which the calling process
belongs.
Returns:
The calling process’s process group ID.
Examples:
#include
#include
#include
#include
<stdio.h>
<stdlib.h>
<process.h>
<sys/types.h>
int main( void )
{
printf( "I am in process group %d\n", (int) getpgrp() );
return EXIT_SUCCESS;
}
Classification:
POSIX 1003.1
Safety
June 19, 2012
Cancellation point
No
Interrupt handler
No
Signal handler
Yes
Thread
Yes
QNX Neutrino Functions and Macros
737
getpgrp()
© 2012, QNX Software Systems Limited
See also:
setpgrp(), setsid()
738
QNX Neutrino Functions and Macros
June 19, 2012
getpid()
© 2012, QNX Software Systems Limited
Get the process ID
Synopsis:
#include <process.h>
pid_t getpid( void );
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
The getpid() function gets the process ID for the calling process.
Returns:
The process ID of the calling process.
Examples:
#include <stdio.h>
#include <stdlib.h>
#include <process.h>
int main ( void )
{
printf( "I’m process %d\n", getpid() );
return EXIT_SUCCESS;
}
Classification:
POSIX 1003.1
Safety
Cancellation point
No
Interrupt handler
No
Signal handler
Yes
Thread
Yes
See also:
getppid()
June 19, 2012
QNX Neutrino Functions and Macros
739
getppid()
© 2012, QNX Software Systems Limited
Get the parent process ID
Synopsis:
#include <sys/types.h>
#include <process.h>
pid_t getppid( void );
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
The getppid() function gets the process ID of the parent of the calling process.
Returns:
The calling process’s parent’s process ID.
Examples:
#include
#include
#include
#include
<stdio.h>
<stdlib.h>
<sys/types.h>
<process.h>
int main( void )
{
printf( "My parent is %d\n", getppid() );
return EXIT_SUCCESS;
}
Classification:
POSIX 1003.1
Safety
Cancellation point
No
Interrupt handler
No
Signal handler
Yes
Thread
Yes
See also:
getpid()
740
QNX Neutrino Functions and Macros
June 19, 2012
getprio()
© 2012, QNX Software Systems Limited
Get the priority of a given process
Synopsis:
#include <sched.h>
int getprio( pid_t pid );
Arguments:
pid
The process ID of the process whose priority you want to get.
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
The getprio() function returns the current priority of thread 1 in process pid. If pid is
zero, the priority of the calling thread is returned.
Returns:
The priority, or -1 if an error occurred (errno is set).
Errors:
ESRCH
The process pid doesn’t exist.
Classification:
QNX 4
Safety
Cancellation point
No
Interrupt handler
No
Signal handler
Yes
Thread
Yes
Caveats:
The getprio() and setprio() functions are included in the QNX Neutrino libraries for
porting QNX 4 applications. For new programs, use pthread_getschedparam().
June 19, 2012
QNX Neutrino Functions and Macros
741
getprio()
© 2012, QNX Software Systems Limited
See also:
errno, pthread_getschedparam(), pthread_setschedparam(), pthread_setschedprio(),
sched_get_priority_max(), sched_get_priority_min(), sched_getparam(),
sched_getscheduler(), sched_setscheduler(), sched_yield(), setprio()
“Thread scheduling” in the QNX Neutrino Microkernel chapter of the System
Architecture guide
“Scheduling policies” in the Programming Overview chapter of the QNX Neutrino
Programmer’s Guide
742
QNX Neutrino Functions and Macros
June 19, 2012
getprotobyname()
© 2012, QNX Software Systems Limited
Get a protocol entry, given a name
Synopsis:
#include <netdb.h>
struct protoent * getprotobyname( const char * name );
Arguments:
name
The name of the protocol whose entry you want to get.
Library:
libsocket
Use the -l socket option to qcc to link against this library.
Description:
The getprotobyname() function gets the entry for the given name from the protocol
database, /etc/protocols. This function returns a pointer to a structure of type
protoent, which contains the broken-out fields of a line in the network protocol
database.
The setprotoent() function opens and rewinds the file. If you pass a nonzero stayopen
argument to setprotoent(), the protocol database isn’t closed after each call to
getprotobyname() or getprotobynumber().
The getprotobyname() and getprotobynumber() functions sequentially search from the
beginning of the file until a matching protocol name or protocol number is found, or
until EOF is encountered.
Returns:
A pointer to a valid protoent structure, or NULL if an error occurs.
Files:
/etc/protocols
Protocol name database file.
Classification:
POSIX 1003.1
Safety
Cancellation point
Yes
Interrupt handler
No
Signal handler
No
continued. . .
June 19, 2012
QNX Neutrino Functions and Macros
743
getprotobyname()
© 2012, QNX Software Systems Limited
Safety
Thread
No
Caveats:
This function uses static data; if you need the data for future use, copy it before any
subsequent calls overwrite it.
Currently, only the Internet protocols are understood.
See also:
endprotoent(), getprotobynumber(), getprotoent(), protoent, setprotoent()
/etc/protocols in the Utilities Reference
744
QNX Neutrino Functions and Macros
June 19, 2012
getprotobynumber()
© 2012, QNX Software Systems Limited
Get a protocol entry, given a number
Synopsis:
#include <netdb.h>
struct protoent * getprotobynumber( int proto );
Arguments:
proto
The protocol number whose entry you want to get.
Library:
libsocket
Use the -l socket option to qcc to link against this library.
Description:
The getprotobynumber() function gets the protocol entry for the given number. It
returns a pointer to structure of type protoent, which contains the broken-out fields
of a line in the network protocol database, /etc/protocols.
The setprotoent() function opens and rewinds the file. If you pass a nonzero stayopen
argument to setprotoent(), the protocol database isn’t closed after each call to
getprotobyname() or getprotobynumber().
The getprotobyname() and getprotobynumber() functions sequentially search from the
beginning of the file until a matching protocol name or protocol number is found, or
until EOF is encountered.
Returns:
A pointer to a valid protoent structure, or NULL if an error occurs.
Files:
/etc/protocols
Protocol name database file.
Classification:
POSIX 1003.1
Safety
June 19, 2012
Cancellation point
Yes
Interrupt handler
No
Signal handler
No
Thread
No
QNX Neutrino Functions and Macros
745
getprotobynumber()
© 2012, QNX Software Systems Limited
Caveats:
This function uses static data; if you need the data for future use, copy it before any
subsequent calls overwrite it.
Currently, only the Internet protocols are understood.
See also:
endprotoent(), getprotobyname(), getprotoent(), protoent, setprotoent()
/etc/protocols in the Utilities Reference
746
QNX Neutrino Functions and Macros
June 19, 2012
getprotoent()
© 2012, QNX Software Systems Limited
Read the next line of the protocol name database file
Synopsis:
#include <netdb.h>
struct protoent * getprotoent( void );
Library:
libsocket
Use the -l socket option to qcc to link against this library.
Description:
The getprotoent() function reads the next line of the protocol name database file,
opening the file if necessary. It returns a pointer to a structure of type protoent,
which contains the broken-out fields of a line in the network protocol database,
/etc/protocols.
Returns:
A pointer to a valid protoent structure, or NULL if an error occurs.
Files:
/etc/protocols
Protocol name database file.
Classification:
POSIX 1003.1
Safety
Cancellation point
Yes
Interrupt handler
No
Signal handler
No
Thread
No
Caveats:
This function uses static data; if you need the data for future use, copy it before any
subsequent calls overwrite it.
Currently, only the Internet protocols are understood.
June 19, 2012
QNX Neutrino Functions and Macros
747
getprotoent()
© 2012, QNX Software Systems Limited
See also:
endprotoent(), getprotobyname(), getprotobynumber(), protoent, setprotoent()
/etc/protocols in the Utilities Reference
748
QNX Neutrino Functions and Macros
June 19, 2012
getpwent()
© 2012, QNX Software Systems Limited
Get the next entry from the password database
Synopsis:
#include <sys/types.h>
#include <pwd.h>
struct passwd* getpwent( void );
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
The getpwent() function returns the next entry from the password database. This
function uses a static buffer that’s overwritten by each call.
The getpwent(), getpwnam(), and getpwuid(), functions share the same static buffer.
For a reentrant version of this function, see getpwent_r().
Returns:
A pointer to an object of type struct passwd containing the next entry from the
password database. When getpwent() is first called, the password database is opened,
and remains open until either a NULL is returned to signify end-of-file, or endpwent()
is called.
Errors:
The getpwent() function uses the following functions, and as a result, errno can be set
to an error for any of these calls:
• fclose()
• fgets()
• fopen()
• fseek()
• rewind()
Examples:
/*
* This program loops, reading a login name from standard
* input and checking to see if it is a valid name. If it
* is not valid, the entire contents of the name in the
* password database are printed.
*/
#include <stdio.h>
#include <stdlib.h>
June 19, 2012
QNX Neutrino Functions and Macros
749
getpwent()
© 2012, QNX Software Systems Limited
#include <sys/types.h>
#include <pwd.h>
int main( void )
{
struct passwd* pw;
char
buf[80];
setpwent( );
while( gets( buf ) != NULL ) {
if( ( pw = getpwnam( buf ) ) != ( struct passwd * )0 ) {
printf( "Valid login name is: %s\n", pw->pw_name );
} else {
setpwent( );
while( ( pw=getpwent( ) ) != ( struct passwd * )0 )
printf( "%s\n", pw->pw_name );
}
}
endpwent();
return( EXIT_SUCCESS );
}
Classification:
POSIX 1003.1 XSI
Safety
Cancellation point
Yes
Interrupt handler
No
Signal handler
No
Thread
No
See also:
endpwent(), errno, getgrent(), getlogin(), getpwent_r(), getpwnam(), getpwuid(),
setpwent()
750
QNX Neutrino Functions and Macros
June 19, 2012
getpwent_r()
© 2012, QNX Software Systems Limited
Get the next entry from the password database
Synopsis:
#include <sys/types.h>
#include <pwd.h>
int getpwent_r( struct passwd *pwd,
char *buffer,
size_t bufsize,
struct passwd **result);
Arguments:
pwd
A pointer to a passwd structure where the function can store the entry.
buffer
A block of memory that the function can use to allocate storage referenced
by the passwd structure. You can determine the maximum size needed for
this buffer by calling sysconf() with an argument of
_SC_GETPW_R_SIZE_MAX.
bufsize
The size of the block that buffer points to, in characters.
result
The address of a pointer to a passwd structure. If getpwent_r() finds the
next entry, it stores a pointer to pwd in the location indicated by result;
otherwise the function stores a NULL pointer there.
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
The getpwent_r() function returns the next entry from the password database. It’s
similar to getpwent(), but getpwent_r() is reentrant.
Returns:
0 on success or if the entry couldn’t be found, or nonzero if an error occurred (errno is
set).
Errors:
The getpwent_r() function uses the following functions, and as a result, errno can be
set to an error for any of these calls:
• fclose()
• fgets()
• fopen()
June 19, 2012
QNX Neutrino Functions and Macros
751
getpwent_r()
© 2012, QNX Software Systems Limited
• fseek()
• rewind()
Classification:
POSIX 1003.1 TSF
Safety
Cancellation point
Yes
Interrupt handler
No
Signal handler
No
Thread
Yes
See also:
endpwent(), errno, getgrent(), getlogin(), getpwnam(), getpwuid(), setpwent()
752
QNX Neutrino Functions and Macros
June 19, 2012
getpwnam()
© 2012, QNX Software Systems Limited
Get information about the user with a given name
Synopsis:
#include <sys/types.h>
#include <pwd.h>
struct passwd* getpwnam( const char* name );
Arguments:
name
The name of the user whose entry you want to find.
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
The getpwnam() function gets information about the user with the given name. It uses
a static buffer that’s overwritten by each call.
The getpwent(), getpwnam(), and getpwuid() functions share the same static buffer.
The getpwnam_r() function is a reentrant version of getpwnam().
Returns:
A pointer to an object of type struct passwd containing an entry from the group
database with a matching name. A NULL pointer is returned on error or failure to find
a entry with a matching name.
Examples:
/*
* Print
* about
*/
#include
#include
#include
#include
#include
information from the password entry
the user name given as argv[1].
<stdio.h>
<unistd.h>
<stdlib.h>
<sys/types.h>
<pwd.h>
int main( int argc, char* *argv )
{
struct passwd* pw;
if( ( pw = getpwnam( argv[1] ) ) == NULL ) {
fprintf( stderr, "getpwnam: unknown %s\n",
argv[1] );
return( EXIT_FAILURE );
}
printf( "login name %s\n", pw->pw_name );
June 19, 2012
QNX Neutrino Functions and Macros
753
getpwnam()
© 2012, QNX Software Systems Limited
printf(
printf(
printf(
printf(
return(
"user id
"group id
"home dir
"login shell
EXIT_SUCCESS
%d\n",
%d\n",
%s\n",
%s\n",
);
pw->pw_uid );
pw->pw_gid );
pw->pw_dir );
pw->pw_shell );
}
Classification:
POSIX 1003.1
Safety
Cancellation point
Yes
Interrupt handler
No
Signal handler
No
Thread
No
See also:
getlogin(), getpwent(), getpwent_r(), getpwnam_r() getpwuid()
754
QNX Neutrino Functions and Macros
June 19, 2012
getpwnam_r()
© 2012, QNX Software Systems Limited
Get information about the user with a given name
Synopsis:
#include <sys/types.h>
#include <pwd.h>
int getpwnam_r( const char* name,
struct passwd* pwd,
char* buffer,
size_t bufsize,
struct passwd* result );
Arguments:
name
The name of the user whose entry you want to find.
pwd
A pointer to a passwd structure where the function can store the entry.
buffer
A block of memory that the function can use to allocate storage referenced
by the passwd structure. You can determine the maximum size needed for
this buffer by calling sysconf() with an argument of
_SC_GETPW_R_SIZE_MAX.
bufsize
The size of the block that buffer points to, in characters.
result
The address of a pointer to a passwd structure. If getpwnam_r() finds the
entry, it stores a pointer to pwd in the location indicated by result;
otherwise the function stores a NULL pointer there.
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
The getpwnam_r() function is a reentrant version of getpwnam(). It gets information
about the user with the given name.
If _POSIX_THREAD_SAFE_FUNCTIONS is defined, the getpwnam_r() function
updates the passwd structure pointed to by pwd and stores a pointer to that structure
at the location pointed by result. The structure contains an entry from the user
database with the given name.
The function stores a NULL pointer at the location pointed by result on error or if it
can’t find the requested entry.
June 19, 2012
QNX Neutrino Functions and Macros
755
getpwnam_r()
© 2012, QNX Software Systems Limited
Returns:
Errors:
Zero for success, or an error number.
ERANGE
Insufficient storage was supplied via buffer and bufsize to contain the
resulting passwd structure.
The getpwnam_r() function uses the following functions, and as a result, errno can be
set to an error for any of these calls:
• fclose()
• fgets()
• fopen()
• fseek()
• rewind()
Classification:
POSIX 1003.1 TSF
Safety
Cancellation point
Yes
Interrupt handler
No
Signal handler
No
Thread
Yes
See also:
getlogin(), getpwent(), getpwent_r(), getpwnam(), getpwuid(), getpwuid_r()
756
QNX Neutrino Functions and Macros
June 19, 2012
getpwuid()
© 2012, QNX Software Systems Limited
Get information about the user with a given ID
Synopsis:
#include <sys/types.h>
#include <pwd.h>
struct passwd* getpwuid( uid_t uid );
Arguments:
uid
The userid whose entry you want to find.
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
The getpwuid() function gets information about user uid. This function uses a static
buffer that’s overwritten by each call.
The getpwent(), getpwnam(), and getpwuid() functions share the same static buffer.
Returns:
A pointer to an object of type struct passwd containing an entry from the group
database with a matching uid, or NULL if an error occurred or the function couldn’t
find a matching entry.
Examples:
/*
* Print
*/
#include
#include
#include
#include
#include
password info on the current user.
<stdio.h>
<unistd.h>
<stdlib.h>
<sys/types.h>
<pwd.h>
int main( void )
{
struct passwd* pw;
if( ( pw = getpwuid( getuid() ) ) == NULL ) {
fprintf( stderr,
"getpwuid: no password entry\n" );
return( EXIT_FAILURE );
}
printf( "login name %s\n", pw->pw_name );
printf( "user id
%d\n", pw->pw_uid );
printf( "group id
%d\n", pw->pw_gid );
printf( "home dir
%s\n", pw->pw_dir );
June 19, 2012
QNX Neutrino Functions and Macros
757
getpwuid()
© 2012, QNX Software Systems Limited
printf( "login shell %s\n", pw->pw_shell );
return( EXIT_SUCCESS );
}
Classification:
POSIX 1003.1
Safety
Cancellation point
Yes
Interrupt handler
No
Signal handler
No
Thread
No
See also:
getlogin(), getpwent(), getpwent_r(), getpwnam()
758
QNX Neutrino Functions and Macros
June 19, 2012
getpwuid_r()
© 2012, QNX Software Systems Limited
Get information about the user with a given ID
Synopsis:
#include <sys/types.h>
#include <pwd.h>
int getpwuid_r( uid_t uid,
struct passwd* pwd,
char* buffer,
size_t bufsize,
struct passwd** result );
Arguments:
uid
The userid whose entry you want to find.
pwd
A pointer to a passwd structure where the function can store the entry.
buffer
A block of memory that the function can use to allocate storage referenced
by the passwd structure. You can determine the maximum size needed for
this buffer by calling sysconf() with an argument of
_SC_GETPW_R_SIZE_MAX.
bufsize
The size of the block that buffer points to, in characters.
result
The address of a pointer to a passwd structure. If getpwnam_r() finds the
entry, it stores a pointer to pwd in the location indicated by result;
otherwise the function stores a NULL pointer there.
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
The getpwuid_r() function is a reentrant version of getpwuid(). It lets a process gain
more knowledge about user with the given uid.
If _POSIX_THREAD_SAFE_FUNCTIONS is defined, the getpwuid_r() function
updates the passwd structure pointed to by pwd and stores a pointer to that structure
at the location pointed by result. The structure contains an entry from the user
database with a matching uid.
The function stores a NULL pointer at the location pointed by result on error or if it
can’t find the requested entry.
June 19, 2012
QNX Neutrino Functions and Macros
759
getpwuid_r()
© 2012, QNX Software Systems Limited
Returns:
Errors:
Zero for success, or an error number.
ERANGE
Insufficient storage was supplied via buffer and bufsize to contain the
resulting passwd structure.
The getpwuid_r() function uses the following functions, and as a result, errno can be
set to an error for any of these calls:
• fclose()
• fgets()
• fopen()
• fseek()
• rewind()
Classification:
POSIX 1003.1 TSF
Safety
Cancellation point
Yes
Interrupt handler
No
Signal handler
No
Thread
Yes
See also:
getlogin(), getpwent(), getpwent_r(), getpwnam(), getpwnam_r(), getpwuid()
760
QNX Neutrino Functions and Macros
June 19, 2012
getrlimit(), getrlimit64()
© 2012, QNX Software Systems Limited
Get the limit on a system resource
Synopsis:
#include <sys/resource.h>
int getrlimit( int resource,
struct rlimit * rlp );
int getrlimit64( int resource,
struct rlimit64 * rlp );
Arguments:
resource
The resource whose limit you want to get; one of the following:
• RLIMIT_AS
• RLIMIT_CORE
• RLIMIT_CPU
• RLIMIT_DATA
• RLIMIT_NOFILE
• RLIMIT_NPROC
• RLIMIT_NTHR
• RLIMIT_OFILE
• RLIMIT_RSS
• RLIMIT_STACK
• RLIMIT_VMEM
For descriptions and the actions taken when the current limit is exceeded,
see setrlimit().
rlp
A pointer to a rlimit or rlimit64 structure where the function can
store the limit on the resource. The rlimit and rlimit64 structures
include at least the following members:
rlim_t rlim_cur; /* current (soft) limit */
rlim_t rlim_max; /* hard limit */
The rlim_t type is an arithmetic data type to which you can cast objects
of type int, size_t, and off_t without loss of information.
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
June 19, 2012
QNX Neutrino Functions and Macros
761
getrlimit(), getrlimit64()
© 2012, QNX Software Systems Limited
Description:
The getrlimit() function gets the limits on the consumption of a variety of system
resources by a process and each process it creates. The getrlimit64() function is a
64-bit version of getrlimit().
Each call to getrlimit() identifies a specific resource to be operated upon as well as a
resource limit. A resource limit is a pair of values:
• the current (soft) limit
• a maximum (hard) limit.
A process can change soft limits to any value that’s less than or equal to the hard limit.
A process may (irreversibly) lower its hard limit to any value that’s greater than or
equal to the soft limit. Only a process with an effective user ID of root can raise a
hard limit. Both hard and soft limits can be changed in a single call to setrlimit()
subject to the constraints described above. Limits may have an “infinite” value of
RLIM_INFINITY.
Because limit information is stored in the per-process information, the shell builtin
ulimit command (see the entry for ksh in the Utilities Reference) must directly
execute this system call if it’s to affect all future processes created by the shell.
The values of the current limit of the following resources affect these parameters:
Resource
Parameter
RLIMIT_NOFILE
OPEN_MAX
When using getrlimit(), if a resource limit can be represented correctly in an object of
type rlim_t, then its representation is returned; otherwise, if the value of the resource
limit is equal to that of the corresponding saved hard limit, the value returned is
RLIM_SAVED_MAX; otherwise, the value returned is RLIM_SAVED_CUR.
A limit whose value is greater than RLIM_INFINITY is permitted.
The exec* family of functions also causes resource limits to be saved.
Returns:
0
Success.
-1
An error occurred (errno is set).
Errors:
762
EFAULT
The rlp argument points to an illegal address.
EINVAL
An invalid resource was specified.
EPERM
The limit specified to setrlimit() would have raised the maximum limit
value, and the effective user of the calling process isn’t the superuser.
QNX Neutrino Functions and Macros
June 19, 2012
getrlimit(), getrlimit64()
© 2012, QNX Software Systems Limited
Examples:
#include <stdio.h>
#include <stdlib.h>
#include <sys/resource.h>
int main( void )
{
struct rlimit curr_limits;
if (getrlimit (RLIMIT_NPROC, &curr_limits) == -1) {
perror ("The call to getrlimit() failed.");
return EXIT_FAILURE;
} else {
printf ("The current maximum number of processes is %d.\n",
(int) curr_limits.rlim_cur);
printf ("The hard limit on the number of processes is %d.\n",
(int) curr_limits.rlim_max);
}
return EXIT_SUCCESS;
}
Classification:
getrlimit() is POSIX 1003.1 XSI; getrlimit64() is Large-file support
Safety
Cancellation point
No
Interrupt handler
No
Signal handler
Yes
Thread
Yes
See also:
brk(), execl(), execle(), execlp(), execlpe(), execv(), execve(), execvp(), execvpe(),
fork(), getdtablesize(), malloc(), open(), setrlimit(), setrlimit64(), signal(), sysconf()
ulimit builtin command (see the entry for ksh in the Utilities Reference)
June 19, 2012
QNX Neutrino Functions and Macros
763
getrusage()
© 2012, QNX Software Systems Limited
Get information about resource utilization
Synopsis:
#include <sys/resource.h>
int getrusage( int who,
struct rusage * r_usage );
Arguments:
who
Which process to get the usage for:
• RUSAGE_CHILDREN — get information about resources used by the
terminated and waited-for children of the current process. If the child
is never waited for (e.g., if the parent has SA_NOCLDWAIT set, or sets
SIGCHLD to SIG_IGN), the resource information for the child process
is discarded and isn’t included.
• RUSAGE_SELF — get information about resources used by the current
process.
r_usage
A pointer to an object of type struct rusage in which the function can
store the resource information; see below.
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
The getrusage() function provides measures of the resources used by the current
process or its terminated and waited-for child processes, depending on the value of the
who argument.
The rusage structure is defined as:
struct timeval
struct timeval
long
long
long
long
long
long
long
long
long
long
long
long
long
long
ru_utime;
ru_stime;
ru_maxrss;
ru_ixrss;
ru_idrss;
ru_isrss;
ru_minflt;
ru_majflt;
ru_nswap;
ru_inblock;
ru_oublock;
ru_msgsnd;
ru_msgrcv;
ru_nsignals;
ru_nvcsw;
ru_nivcsw;
/*
/*
/*
/*
/*
/*
/*
/*
/*
/*
/*
/*
/*
/*
/*
/*
user time used */
system time used */
max resident set size */
integral shared memory size */
integral unshared data " */
integral unshared stack " */
page reclaims */
page faults */
swaps */
block input operations */
block output operations */
messages sent */
messages received */
signals received */
voluntary context switches */
involuntary " */
The members include:
764
QNX Neutrino Functions and Macros
June 19, 2012
getrusage()
© 2012, QNX Software Systems Limited
June 19, 2012
ru_utime
The total amount of time, in seconds and microseconds, spent
executing in user mode.
ru_stime
The total amount of time, in seconds and microseconds, spent
executing in system mode.
ru_maxrss
The maximum resident set size, given in pages. See the Caveats
section, below.
ru_ixrss
Not currently supported.
ru_idrss
An “integral” value indicating the amount of memory in use by a
process while the process is running. This value is the sum of the
resident set sizes of the process running when a clock tick occurs.
The value is given in pages times clock ticks. It doesn’t take sharing
into account. See the Caveats section, below.
ru_isrss
Not currently supported.
ru_minflt
The number of page faults serviced that didn’t require any physical
I/O activity. See the Caveats section, below.
ru_majflt
The number of page faults serviced that required physical I/O
activity. This could include page ahead operations by the kernel. See
the Caveats section, below
ru_nswap
The number of times a process was swapped out of main memory.
ru_inblock
The number of times the file system had to perform input in servicing
a read() request.
ru_oublock
The number of times the filesystem had to perform output in
servicing a write() request.
ru_msgsnd
The number of messages sent over sockets.
ru_msgrcv
The number of messages received from sockets.
ru_nsignals
The number of signals delivered.
ru_nvcsw
The number of times a context switch resulted due to a process’s
voluntarily giving up the processor before its timeslice was
completed (usually to await availability of a resource).
ru_nivcsw
The number of times a context switch resulted due to a higher
priority process’s becoming runnable or because the current process
exceeded its time slice.
QNX Neutrino Functions and Macros
765
getrusage()
© 2012, QNX Software Systems Limited
Returns:
0
-1
Success.
An error occurred (errno is set).
Errors:
EFAULT
The address specified by the r_usage argument isn’t in a valid portion of
the process’s address space.
EINVAL
Invalid who parameter.
Classification:
POSIX 1003.1 XSI
Safety
Cancellation point
No
Interrupt handler
No
Signal handler
Yes
Thread
Yes
Caveats:
Only the timeval fields of struct rusage are supported.
The numbers ru_inblock and ru_oublock account only for real I/O, and are
approximate measures at best. Data supplied by the cache mechanism is charged only
to the first process to read and the last process to write the data.
The way resident set size is calculated is an approximation, and could misrepresent the
true resident set size.
Page faults can be generated from a variety of sources and for a variety of reasons.
The customary cause for a page fault is a direct reference by the program to a page
that isn’t in memory. Now, however, the kernel can generate page faults on behalf of
the user, for example, servicing read() and write() functions. Also, a page fault can be
caused by an absent hardware translation to a page, even though the page is in physical
memory.
In addition to hardware-detected page faults, the kernel may cause pseudo page faults
in order to perform some housekeeping. For example, the kernel may generate page
faults, even if the pages exist in physical memory, in order to lock down pages
involved in a raw I/O request.
By definition, major page faults require physical I/O, while minor page faults don’t.
For example, reclaiming the page from the free list would avoid I/O and generate a
766
QNX Neutrino Functions and Macros
June 19, 2012
© 2012, QNX Software Systems Limited
getrusage()
minor page fault. More commonly, minor page faults occur during process startup as
references to pages which are already in memory. For example, if an address space
faults on some “hot” executable or shared library, a minor page fault results for the
address space. Also, anyone doing a read() or write() to something that’s in the page
cache gets a minor page fault(s) as well.
There’s no way to obtain information about a child process that hasn’t yet terminated.
See also:
gettimeofday(), read(), times(), wait(), write()
June 19, 2012
QNX Neutrino Functions and Macros
767
gets()
© 2012, QNX Software Systems Limited
Get a string of characters from standard input
Synopsis:
#include <stdio.h>
char *gets( char *buf );
Arguments:
buf
A buffer where the function can store the string.
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
The gets() function gets a string of characters from the stdin stream, and stores them in
the array pointed to by buf until end-of-file is encountered or a newline character is
read. Any newline character is discarded, and the string is NUL-terminated.
You should use fgets() instead of gets(); gets() happily overflows the buf array if a
newline character isn’t read from stdin before the end of the array is reached.
The gets() function is similar to fgets(), except that gets() operates with stdin, has no
size argument, and replaces a newline character with the NUL character.
Returns:
A pointer to buf , or NULL when end-of-file is encountered before reading any
characters or a read error occurred (errno is set).
Use feof() or ferror() to distinguish an end-of-file condition from an error.
Examples:
#include <stdio.h>
#include <stdlib.h>
int main( void )
{
char buffer[80];
while( gets( buffer ) != NULL ) {
puts( buffer );
}
return EXIT_SUCCESS;
}
768
QNX Neutrino Functions and Macros
June 19, 2012
gets()
© 2012, QNX Software Systems Limited
Classification:
ANSI, POSIX 1003.1
Safety
Cancellation point
Yes
Interrupt handler
No
Signal handler
No
Thread
Yes
See also:
errno, feof(), ferror(), fopen(), getc(), fgetc(), fgets(), puts(), ungetc()
June 19, 2012
QNX Neutrino Functions and Macros
769
getservbyname()
© 2012, QNX Software Systems Limited
Get a service entry, given a name
Synopsis:
#include <netdb.h>
struct servent * getservbyname( const char * name,
const char * proto );
Arguments:
name
The name of the service whose entry you want to find.
proto
NULL, or the protocol for the service.
Library:
libsocket
Use the -l socket option to qcc to link against this library.
Description:
The getservbyname() function gets the entry for the given name and protocol from the
network services database, /etc/services. This function returns a pointer of type
servent, which contains the broken-out fields of a line in the network services
database.
The setservent() function opens and rewinds the file. If you pass a nonzero stayopen
argument to setservent(), the services database isn’t closed after each call to
getservbyname() or getservbyport().
The getservbyname() and getservbyport() functions sequentially search from the
beginning of the file until a matching protocol name or port number is found, or until
EOF is encountered. If a protocol name is also supplied (non-NULL), searches must
also match the protocol.
Returns:
A valid pointer to a servent structure, or NULL if an error occurs.
Files:
/etc/services
Network services database file.
Classification:
POSIX 1003.1
Safety
Cancellation point
Yes
continued. . .
770
QNX Neutrino Functions and Macros
June 19, 2012
getservbyname()
© 2012, QNX Software Systems Limited
Safety
Interrupt handler
No
Signal handler
No
Thread
No
Caveats:
This function uses static data; if you need the data for future use, copy it before any
subsequent calls overwrite it.
See also:
endservent(), getprotoent(), getservbyport(), getservent(), servent, setservent()
/etc/services in the Utilities Reference
June 19, 2012
QNX Neutrino Functions and Macros
771
getservbyport()
© 2012, QNX Software Systems Limited
Get a service entry, given a port
Synopsis:
#include <netdb.h>
struct servent * getservbyport( int port,
const char * proto );
Arguments:
port
The port number for the service.
proto
NULL, or the protocol for the service.
Library:
libsocket
Use the -l socket option to qcc to link against this library.
Description:
The getservbyport() function gets the entry for the given port from the services
database, /etc/services. This function returns a pointer to a structure of type
servent, which contains the broken-out fields of a line in the network services
database.
The setservent() function opens and rewinds the file. If you pass a nonzero stayopen
argument to setservent(), the services database isn’t closed after each call to
getservbyname() or getservbyport().
The getservbyport() function sequentially searches from the beginning of the file until
a matching protocol name or port number is found, or until EOF is encountered. If a
protocol name is also supplied (non-NULL), searches must also match the protocol.
Returns:
A valid pointer to a servent structure, or NULL if an error occurs.
Files:
/etc/services
Network services database file.
Classification:
POSIX 1003.1
Safety
Cancellation point
Yes
Interrupt handler
No
continued. . .
772
QNX Neutrino Functions and Macros
June 19, 2012
getservbyport()
© 2012, QNX Software Systems Limited
Safety
Signal handler
No
Thread
No
Caveats:
This function uses static data; if you need the data for future use, copy it before any
subsequent calls overwrite it.
See also:
endservent(), getservbyname(), getservent(), servent, setservent()
/etc/services in the Utilities Reference
June 19, 2012
QNX Neutrino Functions and Macros
773
getservent()
© 2012, QNX Software Systems Limited
Read the next line of network services database file
Synopsis:
#include <netdb.h>
struct servent * getservent( void );
Library:
libsocket
Use the -l socket option to qcc to link against this library.
Description:
The getservent() function reads the next line of network services database file, opening
the file if necessary. It returns a pointer to a structure of type servent, which contains
the broken-out fields of a line in the network services database, /etc/services.
Returns:
A valid pointer to a servent structure, or NULL if an error occurs.
Files:
/etc/services
Network services database file.
Classification:
POSIX 1003.1
Safety
Cancellation point
Yes
Interrupt handler
No
Signal handler
No
Thread
No
Caveats:
This function uses static data; if you need the data for future use, copy it before any
subsequent calls overwrite it.
See also:
endservent(), getservbyname(), getservbyport(), servent, setservent()
/etc/services in the Utilities Reference
774
QNX Neutrino Functions and Macros
June 19, 2012
getsid()
© 2012, QNX Software Systems Limited
Get the session ID of a process
Synopsis:
#include <unistd.h>
pid_t getsid( pid_t pid );
Arguments:
pid
The process ID for the process whose session ID you want to get.
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
The getsid() function determines the session ID for the given process ID, pid.
Returns:
The session ID, or -1 if an error occurs (errno is set).
Errors:
EPERM
The process specified by pid is not in the same session as the calling
process. The implementation doesn’t allow access to the process group
ID of the session leader from the calling process.
EINVAL
There isn’t a process with the given ID.
Classification:
POSIX 1003.1 XSI
Safety
June 19, 2012
Cancellation point
No
Interrupt handler
No
Signal handler
No
Thread
Yes
QNX Neutrino Functions and Macros
775
getsid()
© 2012, QNX Software Systems Limited
See also:
errno, setsid()
776
QNX Neutrino Functions and Macros
June 19, 2012
getsockname()
© 2012, QNX Software Systems Limited
Get the name of a socket
Synopsis:
#include <sys/socket.h>
int getsockname( int s,
struct sockaddr * name,
socklen_t * namelen );
Arguments:
s
The file descriptor of the socket whose name you want to get.
name
A pointer to a sockaddr object where the function can store the socket’s
name.
namelen
A pointer to a socklen_t object that initially indicates the amount of
space pointed to by name. The function updates namelen to contain the
actual size of the name (in bytes).
Library:
libsocket
Use the -l socket option to qcc to link against this library.
Description:
The getsockname() function returns the current name for the specified socket.
Returns:
0
Success.
-1
An error occurred (errno is set).
Errors:
EBADF
Invalid descriptor s.
EFAULT
The name parameter points to memory that isn’t in a valid part of the
process address space.
ENOBUFS
Insufficient resources were available in the system to perform the
operation.
Classification:
POSIX 1003.1
June 19, 2012
QNX Neutrino Functions and Macros
777
getsockname()
© 2012, QNX Software Systems Limited
Safety
Cancellation point
Yes
Interrupt handler
No
Signal handler
No
Thread
Yes
See also:
getpeername()
778
QNX Neutrino Functions and Macros
June 19, 2012
getsockopt()
© 2012, QNX Software Systems Limited
Get options associated with a socket
Synopsis:
#include <sys/types.h>
#include <sys/socket.h>
int getsockopt( int s,
int level,
int optname,
void * optval,
socklen_t * optlen );
Arguments:
s
The file descriptor of the socket that the option is to be applied to, as
returned by socket().
level
The protocol layer that the option is to be applied to. In most cases, it’s a
socket-level option and is indicated by SOL_SOCKET.
optname
The option for the socket file descriptor. For a list of options, see
“Options,” below.
optval
A pointer to the value of the option (in most cases, whether the option is
to be turned on or off). If no option value is to be returned, optval may
be NULL.
Most socket-level options use an int parameter for optval. Others, such
as the SO_LINGER, SO_SNDTIMEO, and SO_RCVTIMEO options, use
structures that also let you get data associated with the option.
optlen
A pointer to the length of the value of the option. This argument is a
value-result parameter; initialize it to indicate the size of the buffer
pointed to by optval.
Library:
libsocket
Use the -l socket option to qcc to link against this library.
Description:
The getsockopt() function gets options associated with a socket.
Manipulating socket options
When manipulating a socket option, you must specify the option’s name (optname)
and the level (level) at which the option resides.
To manipulate options at the socket-level, specify level as SOL_SOCKET. When
manipulating options any other level, the value that you specify for level is represented
by the protocol number of the appropriate protocol controlling the option. You can
obtain the value in a variety of ways:
June 19, 2012
QNX Neutrino Functions and Macros
779
getsockopt()
© 2012, QNX Software Systems Limited
• from the “Options” section below, use the symbolic constant (e.g. IPPROTO_IP,
IPPROTO_TCP) that corresponds to the option
• from /etc/protocols, specify the protocol number for the appropriate protocol
• call getprotobyname() and pass the appropriate protocol (e.g. getprotobyname(
tcp );) to retrieve the number of the protocol level.
The latter two ways might not work if you have customized /etc/protocols.
The optname parameter and any specified options are passed uninterpreted to the
appropriate protocol module for interpretation. The <sys/socket.h> header file
contains definitions for the socket-level options. Options at other protocol levels vary
in format and name.
Since levels (e.g. SOL_SOCKET, IPPROTO_IP and IPPROTO_TCP) and the options
within the levels can vary, you need to ensure the proper headers are included for both.
For example, when setting TCP_NODELAY:
int on = 1;
setsockopt(s, IPPROTO_TCP, TCP_NODELAY, &on, sizeof(on));
the level IPPROTO_TCP is defined in <netinet/in.h>, whereas the TCP_NODELAY
option is defined in <netinet/tcp.h>.
Options
This section describes some of the more common options and their corresponding
level.
Except where noted, you can examine the state of the option by calling getsockopt(),
and set the state by calling setsockopt().
IP_HDRINCL
level: IPPROTO_IP
Get or set the custom IP header that’s included with your data. You can use it only for
raw sockets. For example:
(socket(AF_INET, SOCK_RAW, ...)
IP_TOS
level: IPPROTO_IP
Get or set the type-of-service field in the IP header for SOCK_STREAM and
SOCK_DGRAM sockets.
780
QNX Neutrino Functions and Macros
June 19, 2012
© 2012, QNX Software Systems Limited
getsockopt()
SO_BINDTODEVICE
level: SOL_SOCKET
Applies to setsockopt() only.
Allow packets to be sent or received on this specified interface only. If the interface
specified conflicts with the parameters of bind(), or with the routing table, an error or
undesired behavior may occur.
This option accepts the ifreq structure with the ifr_name member set to the interface
name (e.g. en0). Currently, you can use this option only for UDP sockets.
SO_BROADCAST
level: SOL_SOCKET
Enable or disable the permission to transmit broadcast messages. You can use this
option only for UDP sockets. For example:
(socket(AF_INET, SOCK_DGRAM, ...))
“Broadcast” was a privileged operation in earlier versions of the system.
SO_DEBUG
level: SOL_SOCKET
Enable or disable the recording of debug information in the underlying protocol
modules.
SO_DONTROUTE
level: SOL_SOCKET
Enable or disable the bypassing of routing tables for outgoing messages. Indicates that
outgoing messages should bypass the standard routing facilities. The messages are
directed to the appropriate network interface according to the network portion of the
destination address.
SO_ERROR
level: SOL_SOCKET
Applies to getsockopt() only.
Get any pending error on the socket and clears the error status. You can use it to check
for asynchronous errors on connected datagram sockets or for other asynchronous
errors.
SO_KEEPALIVE
level: SOL_SOCKET
Enable or disable the periodic (at least every 2 hours) transmission of messages on a
connected socket. Should the connected party fail to respond to these messages, the
June 19, 2012
QNX Neutrino Functions and Macros
781
getsockopt()
© 2012, QNX Software Systems Limited
connection is considered broken, and processes that are using the socket are notified
via a SIGPIPE signal when they attempt to send data. See “Keepalive timing,” below.
SO_LINGER
level: SOL_SOCKET
Controls the action that’s taken when unsent messages are queued on socket when a
close() is performed.
If it’s enabled and the socket promises reliable delivery of data, the system blocks the
process on the close() attempt until it’s able to transmit the data or until it decides it
can’t deliver the information (a timeout period, termed the linger interval, is specified
in the setsockopt() call when SO_LINGER is requested).
If it’s disabled, the system processes the close() in a way that lets the process continue
as quickly as possible.
The struct linger parameter (defined in <sys/socket.h>) specifies the desired
state of the option in the l_onoff field and the linger interval in the l_linger field,
in seconds. A value of 0 causes a reset on the socket when the application closes the
socket.
SO_OOBINLINE
level: SOL_SOCKET
For protocols that support out-of-band data, allows or disallows out-of-band data to be
placed in the normal data input queue as received. The data is accessible using the
recv() or read() calls without the MSG_OOB flag. Some protocols always behave as if
this option is set.
SO_RCVBUF and SO_SNDBUF
level: SOL_SOCKET
Gets or sets the normal buffer sizes allocated for output (SO_SNDBUF) and input
(SO_RCVBUF) buffers. You can increase the buffer size for high-volume connections,
or decrease it to limit the possible backlog of incoming data. The system places an
absolute limit on these values and defaults them to at least 16K for TCP sockets.
SO_RCVLOWAT
level: SOL_SOCKET
Gets or sets the minimum count for input operations (default is 1). In general, receive
calls block until any (nonzero) amount of data is received, and then return with the
amount available or the amount requested, whichever is smaller.
If you set the value to be larger than the default, blocking receive calls will wait until
they’ve received the low-water mark value or the requested amount, whichever is
smaller. Receive calls may still return less than the low-water mark if: an error occurs,
782
QNX Neutrino Functions and Macros
June 19, 2012
© 2012, QNX Software Systems Limited
getsockopt()
a signal is caught, or if the type of data next in the receive queue differs from that
returned.
SO_RCVTIMEO
level: SOL_SOCKET
Gets or sets a timeout value for input operations. It accepts a struct timeval
parameter (defined in <sys/time.h>) with the number of seconds and microseconds
used to limit waits for input operations to complete.
In the current implementation, this timer is restarted each time additional data is
received by the protocol, so the limit is in effect an inactivity timer. If a receive
operation has been blocked for this much time without receiving additional data, it
returns with a short count or, if no data was received, with the error EWOULDBLOCK.
SO_REUSEADDR
level: SOL_SOCKET
Enables or disables the reuse of duplicate addresses and port bindings. Indicates that
the rules used in validating addresses supplied in a bind() call allows/disallows local
addresses to be reused.
SO_REUSEPORT
level: SOL_SOCKET
Enables or disables duplicate address and port bindings. Complete duplicate bindings
by multiple processes are allowed when they all set SO_REUSEPORT before binding
the port. This option permits multiple instances of a program to each receive UDP/IP
multicast or broadcast datagrams destined for the bound port. See the
reuseport_unicast option of io-pkt to see how unicast packets are also received
on all sockets bound to the same port.
SO_SNDLOWAT
level: SOL_SOCKET
Gets or sets the minimum count for output operations. In BSD, this count is typically
2048, but it is a calculated value in Neutrino. If you require a specific
SO_SNDLOWAT, you must specify the count. Most output operations process all of the
data supplied by the call, delivering data to the protocol for transmission and blocking
as necessary for flow control. Nonblocking output operations will process as much
data as permitted (subject to flow control without blocking), but will process no data if
flow control doesn’t allow the smaller of the low-water mark value or the entire
request to be processed.
A select() operation that tests the ability to write to a socket returns true only if the
low-water mark amount could be processed.
June 19, 2012
QNX Neutrino Functions and Macros
783
getsockopt()
© 2012, QNX Software Systems Limited
SO_SNDTIMEO
level: SOL_SOCKET
Gets or sets a timeout value for output operations. It accepts a struct timeval
parameter (defined in <sys/time.h>) that includes the number of seconds and
microseconds that are used to limit waits for output operations to complete. If a send
operation has blocked for this much time, it returns with a partial count or with the
error EWOULDBLOCK if data weren’t sent.
This timer is restarted each time additional data is delivered to the protocol, implying
that the limit applies to output portions ranging in size from the low-water mark to the
high-water mark for output. Timeouts are restricted to 32 seconds or under.
SO_TIMESTAMP
level: SOL_SOCKET
Enables or disables the reception of a timestamp with datagrams. If enabled on a
SOCK_DGRAM socket, the recvmsg() call returns a timestamp corresponding to when
the datagram was received. The msg_control field in the msghdr structure points to a
buffer that contains a cmsghdr structure followed by a struct timeval. The
cmsghdr fields have the following values:
cmsg_len = sizeof(struct cmsghdr) + sizeof(struct timeval)
cmsg_level = SOL_SOCKET
cmsg_type = SCM_TIMESTAMP
SO_TYPE
level: SOL_SOCKET
Applies to getsockopt() only.
Gets the type of the socket (e.g. SOCK_STREAM). This information is useful for
servers that inherit sockets on startup.
SO_USELOOPBACK
level: SOL_SOCKET
Enables or disables the sending process to receive its own routing messages.
TCP_KEEPALIVE
level: IPPROTO_TCP
Gets or sets the amount of time in seconds between keepalive probes (the default value
is 2 hours). It accepts a struct timeval parameter with the number of seconds to
wait between the keepalive probes. See “Keepalive timing,” below.
784
QNX Neutrino Functions and Macros
June 19, 2012
getsockopt()
© 2012, QNX Software Systems Limited
TCP_NODELAY
level: IPPROTO_TCP
Don’t delay sending in order to coalesce packets. Under most circumstances, TCP
sends data when it’s presented. When outstanding data hasn’t yet been acknowledged,
TCP gathers small amounts of output to be sent in a single packet once an
acknowledgment is received.
For a few clients (such as windowing systems that send a stream of mouse events that
receive no replies), this packetization may cause significant delays. Therefore, TCP
provides a boolean option, TCP_NODELAY, to defeat this algorithm.
Keepalive timing
Use the SO_KEEPALIVE option to turn on keepalive probes, and the TCP_KEEPALIVE
option to set the amount of idle time before a probe is sent out (the default is 7200
seconds, or two hours).
You can set the number of probes to send out and the interval between probes by using
the sysctl() function, which modifies or queries the state of the socket manager. The
documentation for the sysctl utility includes information on identifiers related to
keepcnt and keepintvl. The default number of unsuccessful probes before the
socket is considered broken is 8, and the interval between probes defaults to 75
seconds.
Here’s an example of turning on a socket keepalive with a 20-second idle time, then up
to 3 probes, 5 seconds apart:
int mib[4];
int on=1, ival;
struct timeval tval;
mib[0]
mib[1]
mib[2]
mib[3]
ival =
= CTL_NET;
= AF_INET;
= IPPROTO_TCP;
= TCPCTL_KEEPCNT;
3; /* Number of keepalive probe attempts
(default is 8) */
sysctl(mib, 4, NULL, NULL, &ival, sizeof(ival));
mib[0]
mib[1]
mib[2]
mib[3]
ival =
= CTL_NET;
= AF_INET;
= IPPROTO_TCP;
= TCPCTL_KEEPINTVL;
10; /* Half seconds between probe attempts;
default is 150 (75 sec) */
sysctl(mib, 4, NULL, NULL, &ival, sizeof(ival));
memset(&tval, 0, sizeof(tval));
tval.tv_sec = 20; /* Seconds of idle time before probing
starts (default is 7200) */
setsockopt(fdi, SOL_SOCKET, SO_KEEPALIVE, (void *) &on,
sizeof(on));
setsockopt(fdi, IPPROTO_TCP, TCP_KEEPALIVE, (void *) &tval,
sizeof(tval);
June 19, 2012
QNX Neutrino Functions and Macros
785
getsockopt()
© 2012, QNX Software Systems Limited
Beware that the sysctl() calls above make system-wide changes that persist after the
process finishes executing.
Returns:
0
Success.
-1
An error occurred (errno is set).
Errors:
EBADF
Invalid file descriptor s.
EDOM
Value was set out of range.
EFAULT
The address pointed to by optval isn’t in a valid part of the
process address space. For getsockopt(), this error may also be
returned if optlen isn’t in a valid part of the process address
space.
EINVAL
The optval argument can’t be NULL; optlen can’t be 0.
ENOPROTOOPT
The option is unknown at the level indicated.
Classification:
POSIX 1003.1
Safety
Cancellation point
Yes
Interrupt handler
No
Signal handler
No
Thread
Yes
See also:
ICMP, IP, TCP, and UDP protocols
close(), getprotobyname(), ioctl(), read(), select(), setsockopt(), socket(), sysctl()
/etc/protocols, sysctl in the Utilities Reference
786
QNX Neutrino Functions and Macros
June 19, 2012
getspent(), getspent_r()
© 2012, QNX Software Systems Limited
Get an entry from the shadow password database
Synopsis:
#include <sys/types.h>
#include <shadow.h>
struct spwd* getspent( void );
struct spwd* getspent_r( struct spwd* result,
char* buffer,
int buflen );
Arguments:
These arguments apply only to getspent_r():
result
A pointer to a spwd structure where the function can store the entry. For
more information about this structure, see putspent().
buffer
A block of memory that the function can use to allocate storage referenced
by the spwd structure. You can determine the maximum size needed for
this buffer by calling sysconf() with an argument of
_SC_GETPW_R_SIZE_MAX.
bufsize
The size of the block that buffer points to, in characters.
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
The getspent() and getspent_r() functions return the next entry from the shadow
password database. The getspent() function uses a static buffer that’s overwritten by
each call.
The fgetspent(), getspent(), getspnam(), and functions share the same static buffer.
Returns:
The getspent() function returns a pointer to an object of type struct spwd
containing the next entry from the shadow password database. When getspent() is first
called, the database is opened, and remains open until either a NULL is returned to
signify end-of-file, or endspent() is called.
June 19, 2012
QNX Neutrino Functions and Macros
787
getspent(), getspent_r()
© 2012, QNX Software Systems Limited
Errors:
The getspent() function uses the following functions, and as a result, errno can be set
to an error for any of these calls:
• fclose()
• fgets()
• fopen()
• fseek()
• rewind()
Examples:
#include
#include
#include
#include
<stdio.h>
<stdlib.h>
<pwd.h>
<shadow.h>
/*
* This program loops, reading a login name from standard
* input and checking to see if it is a valid name. If it
* is not valid, the entire contents of the name in the
* password database are printed.
*/
int main(int argc, char** argv)
{
struct spwd* sp;
char buf[80];
setpwent( );
while( gets( buf ) != NULL ) {
if( ( sp = getspnam( buf ) ) != ( struct spwd * )0 ) {
printf( "Valid login name is: %s\n", sp->sp_namp );
} else {
setspent( );
while( ( sp=getspent( ) ) != ( struct spwd * )0 )
printf( "%s\n", sp->sp_namp );
}
}
endspent();
return( EXIT_SUCCESS );
}
Classification:
Unix
getspent()
Safety
Cancellation point
Yes
continued. . .
788
QNX Neutrino Functions and Macros
June 19, 2012
getspent(), getspent_r()
© 2012, QNX Software Systems Limited
Safety
Interrupt handler
No
Signal handler
No
Thread
No
getspent_r()
Safety
Cancellation point
Yes
Interrupt handler
No
Signal handler
No
Thread
Yes
See also:
errno, fgetspent(), getgrent(), getlogin(), getspnam(), getpwuid(), putspent(), setspent()
June 19, 2012
QNX Neutrino Functions and Macros
789
getspnam(), getspnam_r()
© 2012, QNX Software Systems Limited
Get information about a user with a given name
Synopsis:
#include <sys/types.h>
#include <shadow.h>
struct spwd* getspnam( char* name );
struct spwd* getspnam_r( const char* name,
struct spwd* result,
char* buffer,
size_t bufsize );
Arguments:
name
The name of the user.
result
(getspnam_r() only) A pointer to a spwd structure where the function can
store the entry. For more information about this structure, see putspent().
buffer
(getspnam_r() only) A block of memory that the function can use to
allocate storage referenced by the spwd structure. You can determine the
maximum size needed for this buffer by calling sysconf() with an argument
of _SC_GETPW_R_SIZE_MAX.
bufsize
(getspnam_r() only) The size of the block that buffer points to, in
characters.
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
The getspnam() and getspnam_r() functions allow a process to gain more knowledge
about a user name. The getspnam() function uses a static buffer that’s overwritten by
each call.
The fgetspent(), getspent(), and getspnam() functions share the same static buffer.
Returns:
A pointer to an object of type struct spwd containing an entry from the group
database with a matching name, or NULL if an error occurred or the function couldn’t
find a matching entry.
790
QNX Neutrino Functions and Macros
June 19, 2012
getspnam(), getspnam_r()
© 2012, QNX Software Systems Limited
Examples:
#include
#include
#include
#include
<stdio.h>
<stdlib.h>
<pwd.h>
<shadow.h>
/*
* Print information from the password entry
* about the user name given as argv[1].
*/
int main( int argc, char** argv )
{
struct spwd* sp;
if (argc < 2) {
printf("%s username \n", argv[0]);
return(EXIT_FAILURE);
}
if( ( sp = getspnam( argv[1] ) ) == (struct spwd*)0) {
fprintf( stderr, "getspnam: unknown %s\n",
argv[1] );
return( EXIT_FAILURE );
}
printf( "login name %s\n", sp->sp_namp );
printf( "password
%s\n", sp->sp_pwdp );
return( EXIT_SUCCESS );
}
Classification:
Unix
getspnam()
Safety
Cancellation point
Yes
Interrupt handler
No
Signal handler
No
Thread
No
getspnam_r()
Safety
June 19, 2012
Cancellation point
Yes
Interrupt handler
No
Signal handler
No
Thread
Yes
QNX Neutrino Functions and Macros
791
getspnam(), getspnam_r()
© 2012, QNX Software Systems Limited
See also:
fgetspent(), getlogin(), getspent(), getpwuid(), putspent()
792
QNX Neutrino Functions and Macros
June 19, 2012
getsubopt()
© 2012, QNX Software Systems Limited
Parse suboptions from a string
Synopsis:
#include <stdlib.h>
int getsubopt( char** optionp,
char* const* tokens,
char** valuep );
Arguments:
optionp
The address of a pointer to the string of options that you want to parse.
The function updates this pointer as it parses the options; see below.
tokens
A vector of possible tokens.
valuep
The address of a pointer that the function updates to point to the first
character of a value that’s associated with an option; see below.
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
The getsubopt() functions parses suboptions in a flag argument that was initially
parsed by getopt(). These suboptions are separated by commas and may consist of
either a single token or a token-value pair separated by an equal sign. Since commas
delimit suboptions in the option string, they aren’t allowed to be part of the suboption
or the value of a suboption. A command that uses this syntax is mount, which allows
the user to specify mount parameters with the -o option as follows:
mount -o rw,hard,bg,wsize=1024 speed:/usr /usr
In this example there are four suboptions: rw, hard, bg, and wsize, the last of which
has an associated value of 1024.
The getsubopt() function takes the address of a pointer to the option string, a vector of
possible tokens, and the address of a value string pointer. It returns the index of the
token that matched the suboption in the input string, or -1 if there was no match. If the
option string at optionp contains only one suboption, getsubopt() updates optionp to
point to the null character at the end of the string; otherwise, it isolates the suboption
by replacing the comma separator with a null character, and updates optionp to point
to the start of the next suboption. If the suboption has an associated value, getsubopt()
updates valuep to point to the value’s first character. Otherwise, it sets valuep to NULL.
The token vector is organized as a series of pointers to null strings. The end of the
token vector is identified by a NULL pointer.
June 19, 2012
QNX Neutrino Functions and Macros
793
getsubopt()
© 2012, QNX Software Systems Limited
When getsubopt() returns, if valuep isn’t NULL, the suboption processed included a
value. The calling program may use this information to determine if the presence or
lack of a value for this suboption is an error.
Additionally, when getsubopt() fails to match the suboption with the tokens in the
tokens array, the calling program should decide if this is an error, or if the
unrecognized option should be passed to another program.
Returns:
The getsubopt() function returns -1 when the token it’s scanning isn’t in the tokens
vector. The variable addressed by valuep contains a pointer to the first character of the
token that wasn’t recognized rather than a pointer to a value for that token.
The variable addressed by optionp points to the next option to be parsed, or a null
character if there are no more options.
Examples:
The following code fragment shows how to process options to the mount(1M)
command using getsubopt():
#include <stdlib.h>
char *myopts[] = {
#define READONLY
0
"ro",
#define READWRITE
1
"rw",
#define WRITESIZE
2
"wsize",
#define READSIZE
3
"rsize",
NULL};
main(argc, argv)
int argc;
char **argv;
{
int sc, c, errflag;
char *options, *value;
extern char *optarg;
extern int optind;
.
.
.
while((c = getopt(argc, argv, "abf:o:")) != -1) {
switch (c) {
case ’a’: /* process a option */
break;
case ’b’: /* process b option */
break;
case ’f’:
ofile = optarg;
break;
case ’?’:
errflag++;
break;
794
QNX Neutrino Functions and Macros
June 19, 2012
getsubopt()
© 2012, QNX Software Systems Limited
case ’o’:
options = optarg;
while (*options != ’\0’) {
switch(getsubopt(&options,myopts,&value)) {
case READONLY : /* process ro option */
break;
case READWRITE : /* process rw option */
break;
case WRITESIZE : /* process wsize option */
if (value == NULL) {
error_no_arg();
errflag++;
} else
write_size = atoi(value);
break;
case READSIZE : /* process rsize option */
if (value == NULL) {
error_no_arg();
errflag++;
} else
read_size = atoi(value);
break;
default :
/* process unknown token */
error_bad_token(value);
errflag++;
break;
}
}
break;
}
}
if (errflag) {
/* print usage instructions etc. */
}
for (; optind < argc; optind++) {
/* process remaining arguments */
}
.
.
.
}
Classification:
POSIX 1003.1 XSI
Safety
June 19, 2012
Cancellation point
No
Interrupt handler
No
Signal handler
Yes
Thread
Yes
QNX Neutrino Functions and Macros
795
getsubopt()
© 2012, QNX Software Systems Limited
Caveats:
During parsing, commas in the option input string are changed to null characters.
White space in tokens or token-value pairs must be protected from the shell by quotes.
See also:
getopt()
796
QNX Neutrino Functions and Macros
June 19, 2012
gettimeofday()
© 2012, QNX Software Systems Limited
Get the current time
Synopsis:
#include <sys/time.h>
int gettimeofday( struct timeval * when,
void * not_used );
Arguments:
when
A pointer to a timeval structure where the function can store the time.
The struct timeval contains the following members:
• time_t tv_sec — the number of seconds since the start of the Unix
Epoch.
• suseconds_t tv_usec — the number of microseconds.
not_used
This pointer must be NULL or the behavior of gettimeofday() is
unspecified. This argument is provided only for backwards
compatibility.
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
The gettimeofday() function returns the current time in when in seconds and
microseconds, since the Unix Epoch, 00:00:00 January 1, 1970 Coordinated Universal
Time (UTC) (formerly known as Greenwich Mean Time (GMT)).
Returns:
0 for success, or -1 if an error occurs (errno is set).
Errors:
EFAULT
An error occurred while accessing the when buffer.
Classification:
POSIX 1003.1 XSI
Safety
Cancellation point
No
Interrupt handler
No
continued. . .
June 19, 2012
QNX Neutrino Functions and Macros
797
gettimeofday()
© 2012, QNX Software Systems Limited
Safety
Signal handler
Yes
Thread
Yes
Caveats:
The gettimeofday() function is provided for porting existing code. You shouldn’t use it
in new code; use clock_gettime() instead.
See also:
asctime(), asctime_r(), clock_gettime(), clock_settime(), ctime(), ctime_r(), difftime(),
gmtime(), gmtime_r(), localtime(), localtime_r(), settimeofday(), time()
798
QNX Neutrino Functions and Macros
June 19, 2012
getuid()
© 2012, QNX Software Systems Limited
Get the user ID
Synopsis:
#include <sys/types.h>
#include <unistd.h>
uid_t getuid( void );
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
The getuid() function gets the user ID for the calling process.
Returns:
The user ID for the calling process.
Examples:
#include
#include
#include
#include
<stdio.h>
<stdlib.h>
<sys/types.h>
<unistd.h>
int main( void )
{
printf( "My userid is %d\n", getuid() );
return EXIT_SUCCESS;
}
Classification:
POSIX 1003.1
Safety
Cancellation point
No
Interrupt handler
No
Signal handler
Yes
Thread
Yes
See also:
getegid(), geteuid(), getgid(), setuid()
June 19, 2012
QNX Neutrino Functions and Macros
799
getutent()
© 2012, QNX Software Systems Limited
Read the next entry from the user-information file
Synopsis:
#include <utmp.h>
struct utmp * getutent( void );
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
This function is in libc.a, but not in libc.so (in order to save space).
Description:
The getutent() function reads in the next entry from a user-information file. If the file
isn’t already open, getutent() opens it. If the function reaches the end of the file, it fails.
Returns:
A pointer to a utmp structure for the next entry, or NULL if the file couldn’t be read or
reached the end of file.
Files:
_PATH_UTMP
Specifies the user information file.
Classification:
Unix
Safety
Cancellation point
Yes
Interrupt handler
No
Signal handler
No
Thread
Yes
Caveats:
The most current entry is saved in a static structure. Copy it before making further
accesses.
On each call to either getutid() or getutline(), the routine examines the static structure
before performing more I/O. If the contents of the static structure match what it’s
800
QNX Neutrino Functions and Macros
June 19, 2012
© 2012, QNX Software Systems Limited
getutent()
searching for, the function looks no further. For this reason, to use getutline() to search
for multiple occurrences, zero out the static area after each success, or getutline() will
return the same structure over and over again.
There’s one exception to the rule about emptying the structure before further reads are
done: the implicit read done by pututline() (if it finds that it isn’t already at the correct
place in the file) doesn’t hurt the contents of the static structure returned by the
getutent(), getutid() or getutline() routines, if you just modified those contents and
passed the pointer back to pututline().
These routines use buffered standard I/O for input, but pututline() uses an unbuffered
nonstandard write to avoid race conditions between processes trying to modify the
utmp and wtmp files.
See also:
endutent(), getutid(), getutline(), pututline(), setutent(), utmp, utmpname()
login in the Utilities Reference
June 19, 2012
QNX Neutrino Functions and Macros
801
getutid()
© 2012, QNX Software Systems Limited
Search for an entry in the user-information file
Synopsis:
#include <utmp.h>
struct utmp * getutid( struct utmp * id );
Arguments:
id
A pointer to a utmp structure that you want to find in the user-information file.
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
This function is in libc.a, but not in libc.so (in order to save space).
Description:
The getutid() function searches forward from the current point in the utmp file until it
finds a matching entry:
• If id->ut_type is one of RUN_LVL, BOOT_TIME, OLD_TIME, or NEW_TIME, the
function looks for an entry with the same ut_type.
• If id->ut_type is INIT_PROCESS, LOGIN_PROCESS, USER_PROCESS, or
DEAD_PROCESS, getutid() looks for the first entry entry with the same ut_type and
a ut_id field that matches id->ut_id.
If getutid() reaches the end of the file without finding a match, the search fails.
Returns:
A pointer to the utmp structure for the matching entry, or NULL if it couldn’t be found.
Files:
_PATH_UTMP
Specifies the user information file.
Classification:
Unix
Safety
Cancellation point
Yes
continued. . .
802
QNX Neutrino Functions and Macros
June 19, 2012
getutid()
© 2012, QNX Software Systems Limited
Safety
Interrupt handler
No
Signal handler
No
Thread
Yes
Caveats:
The most current entry is saved in a static structure. Copy it before making further
accesses.
On each call to either getutid() or getutline(), the routine examines the static structure
before performing more I/O. If the contents of the static structure match what it’s
searching for, the function looks no further. For this reason, to use getutline() to search
for multiple occurrences, zero out the static area after each success, or getutline() will
return the same structure over and over again.
There’s one exception to the rule about emptying the structure before further reads are
done: the implicit read done by pututline() (if it finds that it isn’t already at the correct
place in the file) doesn’t hurt the contents of the static structure returned by the
getutent(), getutid() or getutline() routines, if the user has just modified those contents
and passed the pointer back to pututline().
These routines use buffered standard I/O for input, but pututline() uses an unbuffered
nonstandard write to avoid race conditions between processes trying to modify the
utmp and wtmp files.
See also:
endutent(), getutent(), getutline(), pututline(), setutent(), utmp, utmpname()
login in the Utilities Reference
June 19, 2012
QNX Neutrino Functions and Macros
803
getutline()
© 2012, QNX Software Systems Limited
Get an entry from the user-information file
Synopsis:
#include <utmp.h>
struct utmp * getutline( struct utmp * line );
Arguments:
line
A pointer to a utmp structure that you want to find in the user-information file.
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
This function is in libc.a, but not in libc.so (in order to save space).
Description:
The getutline() function searches forward from the current point in the utmp file until
it finds an entry of the type LOGIN_PROCESS or a ut_line string that matches
line->ut_line. If the function reaches the end of the file is reached without finding a
match, the function fails.
Returns:
A pointer to the utmp structure for the entry found, or NULL if the search failed.
Files:
_PATH_UTMP
Specifies the user information file.
Classification:
Unix
Safety
804
Cancellation point
Yes
Interrupt handler
No
Signal handler
No
Thread
Yes
QNX Neutrino Functions and Macros
June 19, 2012
© 2012, QNX Software Systems Limited
getutline()
Caveats:
The most current entry is saved in a static structure. Copy it before making further
accesses.
On each call to either getutid() or getutline(), the routine examines the static structure
before performing more I/O. If the contents of the static structure match what it’s
searching for, the function looks no further. For this reason, to use getutline() to search
for multiple occurrences, zero out the static area after each success, or getutline() will
return the same structure over and over again.
There’s one exception to the rule about emptying the structure before further reads are
done: the implicit read done by pututline() (if it finds that it isn’t already at the correct
place in the file) doesn’t hurt the contents of the static structure returned by the
getutent(), getutid() or getutline() routines, if the user has just modified those contents
and passed the pointer back to pututline().
These routines use buffered standard I/O for input, but pututline() uses an unbuffered
nonstandard write to avoid race conditions between processes trying to modify the
utmp and wtmp files.
See also:
endutent(), getutent(), getutid(), pututline(), setutent(), utmp, utmpname()
login in the Utilities Reference
June 19, 2012
QNX Neutrino Functions and Macros
805
getw()
© 2012, QNX Software Systems Limited
Get a word from a stream
Synopsis:
#include <stdio.h>
int getw( FILE* stream );
Arguments:
stream
The stream that you want to read a word from.
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
This function is in libc.a, but not in libc.so (in order to save space).
Description:
The getw() function returns the next word (i.e. integer) from the named input stream.
This function increments the associated file pointer, if defined, to point to the next
word. The size of a word is the size of an integer, and varies from machine to machine.
The getw() function assumes no special alignment in the file.
Returns:
The next word, or the constant EOF at the end-of-file or on an error; it sets the EOF or
error indicator of the stream.
Use feof() or ferror() to distinguish an end-of-file condition from an error.
Errors:
EOVERFLOW
The file is a regular file, and an attempt was made to read at or
beyond the offset maximum associated with the corresponding
stream.
Classification:
Legacy Unix
Safety
Cancellation point
Yes
continued. . .
806
QNX Neutrino Functions and Macros
June 19, 2012
getw()
© 2012, QNX Software Systems Limited
Safety
Interrupt handler
No
Signal handler
Yes
Thread
Yes
Caveats:
Because of possible differences in word length and byte ordering, files written using
putw() are implementation-dependent, and might not be read correctly using getw() on
a different processor.
See also:
fclose(), feof(), ferror(), fgetc(), flockfile(), fopen(), fread(), getc(), getc_unlocked(),
getchar(), getchar_unlocked(), gets(), putc(), putw(), scanf(), ungetc(),
June 19, 2012
QNX Neutrino Functions and Macros
807
getwc()
© 2012, QNX Software Systems Limited
Read a wide character from a stream
Synopsis:
#include <wchar.h>
wint_t getwc( FILE * fp );
Arguments:
fp
The stream from which you want to read a wide character.
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
The getwc() function reads the next wide character from the specified stream.
Returns:
The next character from the stream, cast as (wint_t)(wchar_t), or WEOF if
end-of-file has been reached or if an error occurs (errno is set).
Use feof() or ferror() to distinguish an end-of-file condition from an error.
Errors:
EAGAIN
The O_NONBLOCK flag is set for fp and would have been blocked
by this operation.
EBADF
The fp stream isn’t valid for reading.
EINTR
A signal terminated the read operation; no data was transferred.
EIO
Either a physical I/O error has occurred, or the process is in the
background and is being ignored or blocked.
EOVERFLOW
Cannot read at or beyond the offset maximum for this stream.
Classification:
ANSI, POSIX 1003.1
Safety
Cancellation point
Yes
continued. . .
808
QNX Neutrino Functions and Macros
June 19, 2012
getwc()
© 2012, QNX Software Systems Limited
Safety
Interrupt handler
No
Signal handler
No
Thread
Yes
See also:
errno, feof(), ferror(), fgetwc(), fgetws(), getc(), getwchar(), putwc(), putwchar()
June 19, 2012
QNX Neutrino Functions and Macros
809
getwchar()
© 2012, QNX Software Systems Limited
Read a character from a stream
Synopsis:
#include <wchar.h>
wint_t getwchar( void );
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
The getwchar() function reads the next wide character from stdin.
Returns:
The next character from stdin, cast as (wint_t)(wchar_t), or WEOF if the
end-of-file has been reached or if an error occurs (errno is set).
Use feof() or ferror() to distinguish an end-of-file condition from an error.
Errors:
EAGAIN
The O_NONBLOCK flag is set for stdin and would have been
blocked by this operation.
EINTR
A signal terminated the read operation; no data was transferred.
EIO
Either a physical I/O error has occurred, or the process is in the
background and is being ignored or blocked.
EOVERFLOW
Cannot read at or beyond the offset maximum for this stream.
Classification:
ANSI, POSIX 1003.1
Safety
810
Cancellation point
Yes
Interrupt handler
No
Signal handler
No
Thread
Yes
QNX Neutrino Functions and Macros
June 19, 2012
© 2012, QNX Software Systems Limited
getwchar()
See also:
errno, feof(), ferror(), fgetwc(), fgetws(), getc(), getwc(), putwc(), putwchar()
June 19, 2012
QNX Neutrino Functions and Macros
811
getwd()
© 2012, QNX Software Systems Limited
Get current working directory pathname
Synopsis:
#include <unistd.h>
char* getwd( char *path_name );
Arguments:
path_name
A buffer where the function can store the current working directory.
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
This function is in libc.a, but not in libc.so (in order to save space).
Description:
The getwd() function determines the absolute pathname of the current working
directory of the calling process, and copies that pathname into the array pointed to by
the path_name argument.
If the length of the pathname of the current working directory is greater than
({PATH_MAX} + 1) including the null byte, getwd() fails and returns a null pointer.
For portability, use getcwd() instead of getwd().
Returns:
A pointer to the string containing the absolute pathname of the current working
directory. On error, getwd() returns a null pointer and the contents of the array pointed
to by path_name are undefined.
Classification:
POSIX 1003.1 XSI
Safety
812
Cancellation point
Yes
Interrupt handler
No
Signal handler
Yes
Thread
Yes
QNX Neutrino Functions and Macros
June 19, 2012
© 2012, QNX Software Systems Limited
getwd()
See also:
getcwd()
June 19, 2012
QNX Neutrino Functions and Macros
813
glob()
© 2012, QNX Software Systems Limited
Find paths matching a pattern
Synopsis:
#include <glob.h>
int glob( const char* pattern,
int flags,
int (*errfunc)( const char* epath,
int error ),
glob_t* pglob );
Arguments:
pattern
The pattern you want to match. This can include these wildcard characters:
• * matches any string, of any length
• ? matches any single character
• [chars] matches any of the characters found in the string chars.
flags
Flags that affect the search; see below.
errfunc
A pointer to a function that glob() calls when it encounters a directory that
it can’t open or read. For more information, see below.
pglob
A pointer to a glob_t structure where glob() can store the paths found.
This structure contains at least the following members:
• size_t gl_pathc — the number of pathnames matched by pattern.
• char** gl_pathv — a NULL-terminated array of pointers to the
pathnames matched by pattern.
• size_t gl_offs — the number of pointers to reserve at the beginning
of gl_pathv.
You must create the glob_t structure before calling glob(). The glob()
function allocates storage as needed for the gl_pathv array. Use globfree()
to free this space.
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
This function is in libc.a, but not in libc.so (in order to save space).
814
QNX Neutrino Functions and Macros
June 19, 2012
glob()
© 2012, QNX Software Systems Limited
Description:
The glob() function finds pathnames matching the given pattern.
In order to have access to a pathname, glob() must have search permission on every
component of the path except the last, and read permission on each directory of every
filename component of pattern that contains any of the special characters (*, ?, [ and
]).
The errfunc argument is a pointer to an error-handler function with this prototype:
int errfunc( const char* epath, int error );
The errfunc function is called when glob() encounters a directory that it can’t open or
read. The arguments are:
epath
A pointer to the path that failed.
error
The value of errno from the failure. The error argument can be set to any of
the values returned by opendir(), readdir(), or stat().
The errfunc function should return 0 if glob() should continue, or a nonzero value if
glob() should stop searching.
You can set errfunc to NULL to ignore these types of errors.
The flags argument can be set to any combination of the following bits:
June 19, 2012
GLOB_APPEND
Append found pathnames to the ones from a previous call from
glob().
GLOB_DOOFFS
Use the value in pglob->gl_offs to specify how many NULL
pointers to add at the beginning of pglob->pathv. After the call
to glob(), pglob->pathv will contain pglob->gl_offs NULL
pointers, followed by pglob->gl_pathc pathnames, followed by
a NULL pointer. This can be useful if you’re building a
command to be applied to the matched files.
GLOB_ERR
Cause glob() to return when it encounters a directory that it
can’t open or read. Otherwise, glob() will continue to find
matches.
GLOB_MARK
Append a slash to each matching pathname that’s a directory.
GLOB_NOCHECK
If pattern doesn’t match any path names, return only the
contents of pattern.
GLOB_NOESCAPE
Disable backslash escapes in pattern.
GLOB_NOSORT
Don’t sort the returned pathnames; their order will be
unspecified. The default is to sort the pathnames.
QNX Neutrino Functions and Macros
815
glob()
© 2012, QNX Software Systems Limited
The following flags are BSD extensions:
GLOB_PERIOD
Allow metacharacters to match leading periods.
GLOB_MAGCHAR
Pattern had globbing characters.
GLOB_ALTDIRFUNC
Use alternately specified directory functions.
GLOB_BRACE
Expand braces the way that the C shell does.
GLOB_NOMAGIC
Similar to GLOB_NOCHECK without magic characters (csh).
GLOB_TILDE
Expand tilde names from the passwd file.
GLOB_NO_DOTDIRS
Make . and .. vanish from wildcards.
GLOB_LIMIT
Limit memory used by matches to ARG_MAX.
Returns:
Zero for success, or an error value.
Errors:
GLOB_ABEND
The scan was stopped because GLOB_ERR was set, or the
errfunc function returned nonzero.
GLOB_NOMATCH
The value of pattern doesn’t match any existing pathname, and
GLOB_NOCHECK wasn’t set in flags.
GLOB_NOSPACE
Unable to allocate memory to store the matched paths.
Examples:
This simple example attempts to find all of the .c files in the current directory and
print them in the order the filesystem found them.
#include <unistd.h>
#include <stdio.h>
#include <glob.h>
int main( void )
{
glob_t paths;
int retval;
paths.gl_pathc = 0;
paths.gl_pathv = NULL;
paths.gl_offs = 0;
retval = glob( "*.c", GLOB_NOCHECK | GLOB_NOSORT,
816
QNX Neutrino Functions and Macros
June 19, 2012
glob()
© 2012, QNX Software Systems Limited
NULL, &paths );
if( retval == 0 ) {
int idx;
for( idx = 0; idx < paths.gl_pathc; idx++ ) {
printf( "[%d]: %s\n", idx,
paths.gl_pathv[idx] );
}
globfree( &paths );
} else {
puts( "glob() failed" );
}
return 0;
}
Classification:
POSIX 1003.1
Safety
Cancellation point
Yes
Interrupt handler
No
Signal handler
Yes
Thread
Yes
Caveats:
Don’t change the values in pglob between calling glob() and globfree().
See also:
globfree(), wordexp(), wordfree()
June 19, 2012
QNX Neutrino Functions and Macros
817
globfree()
© 2012, QNX Software Systems Limited
Free storage allocated by a call to glob()
Synopsis:
#include <glob.h>
void globfree( glob_t* pglob );
Arguments:
pglob
A pointer to a glob_t structure that you passed to glob().
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
This function is in libc.a, but not in libc.so (in order to save space).
Description:
The globfree() function frees the storage allocated by a call to glob().
Classification:
POSIX 1003.1
Safety
Cancellation point
No
Interrupt handler
No
Signal handler
Yes
Thread
Yes
Caveats:
Don’t change the values in pglob between calling glob() and globfree().
See also:
glob(), wordexp(), wordfree()
818
QNX Neutrino Functions and Macros
June 19, 2012
gmtime()
© 2012, QNX Software Systems Limited
Convert calendar time to a broken-down time
Synopsis:
#include <time.h>
struct tm* gmtime( const time_t* timer );
Arguments:
timer
A pointer to a time_t structure that contains the time that you want to
convert.
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
The gmtime() function converts the calendar time pointed to by timer into a
broken-down time, expressed as Coordinated Universal Time (UTC) (formerly known
as Greenwich Mean Time or GMT).
The gmtime() function places the converted time in a static structure that’s reused each
time you call gmtime() or localtime(). Calling asctime() or ctime() could also change
the data in this static buffer.
In a multithreaded application, use gmtime_r().
You typically use the date command to set the computer’s internal clock using
Coordinated Universal Time (UTC). Use the TZ environment variable or
_CS_TIMEZONE configuration string to establish the local time zone. For more
information, see “Setting the time zone” in the Configuring Your Environment chapter
of the Neutrino User’s Guide.
Returns:
A pointer to the static tm structure that contains the broken-down time.
Classification:
ANSI, POSIX 1003.1
Safety
Cancellation point
No
Interrupt handler
No
continued. . .
June 19, 2012
QNX Neutrino Functions and Macros
819
gmtime()
© 2012, QNX Software Systems Limited
Safety
Signal handler
No
Thread
No
See also:
asctime(), asctime_r(), clock(), ctime(), difftime(), gmtime_r(), localtime(),
localtime_r(), mktime(), strftime(), time(), tm, tzset()
“Setting the time zone” in the Configuring Your Environment chapter of the Neutrino
User’s Guide
820
QNX Neutrino Functions and Macros
June 19, 2012
gmtime_r()
© 2012, QNX Software Systems Limited
Convert calendar time to a broken-down time
Synopsis:
#include <time.h>
struct tm* gmtime_r( const time_t* timer,
struct tm* result );
Arguments:
timer
A pointer to a time_t structure that contains the time that you want to
convert.
result
A pointer to a tm structure where the function can store the broken-down
time.
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
The gmtime_r() function converts the calendar time pointed to by timer into a
broken-down time, expressed as Coordinated Universal Time (UTC) (formerly known
as Greenwich Mean Time or GMT) and stores it in the tm structure pointed to by
result.
You typically use the date command to set the computer’s internal clock using
Coordinated Universal Time (UTC). Use the TZ environment variable or
_CS_TIMEZONE configuration string to establish the local time zone. For more
information, see “Setting the time zone” in the Configuring Your Environment chapter
of the Neutrino User’s Guide.
Returns:
A pointer to the tm structure containing the broken-down time.
Classification:
POSIX 1003.1 TSF
Safety
June 19, 2012
Cancellation point
No
Interrupt handler
No
Signal handler
Yes
Thread
Yes
QNX Neutrino Functions and Macros
821
gmtime_r()
© 2012, QNX Software Systems Limited
See also:
asctime(), asctime_r(), clock(), ctime(), difftime(), localtime(), localtime_r(),
mktime(), strftime(), time(), tm, tzset()
“Setting the time zone” in the Configuring Your Environment chapter of the Neutrino
User’s Guide
822
QNX Neutrino Functions and Macros
June 19, 2012
h_errno
© 2012, QNX Software Systems Limited
Host error variable
Synopsis:
#include <netdb.h>
extern int h_errno;
Library:
libsocket
Use the -l socket option to qcc to link against this library.
Description:
The h_errno variable can be set by any one of the following functions:
• gethostbyaddr()
• gethostbyaddr_r()
• gethostbyname()
• gethostbyname2()
• gethostbyname_r()
• res_query()
• res_search()
It can be set to any one of the following:
HOST_NOT_FOUND
Authoritative answer: Unknown host.
NETDB_INTERNAL
You specified an invalid address family when calling
gethostbyname2().
June 19, 2012
NO_DATA
Valid name, no data record of the requested type. The name is
known to the name server, but has no IP address associated with
it—this isn’t a temporary error. Another type of request to the
name server using this domain name will result in an answer
(e.g. a mail-forwarder may be registered for this domain).
NO_RECOVERY
Unknown server error. An unexpected server failure was
encountered. This is a nonrecoverable network error.
TRY_AGAIN
Nonauthoritative answer: Host name lookup failure. This is
usually a temporary error and means that the local server didn’t
receive a response from an authoritative server. A retry at some
later time may succeed.
QNX Neutrino Functions and Macros
823
h_errno
© 2012, QNX Software Systems Limited
Classification:
POSIX 1003.1 OBS
Caveats:
Unlike errno, h_errno isn’t thread-safe.
See also:
errno, gethostbyaddr(), gethostbyaddr_r(), gethostbyname(), gethostbyname2(),
gethostbyname_r(), res_query(), res_search()
824
QNX Neutrino Functions and Macros
June 19, 2012
hcreate()
© 2012, QNX Software Systems Limited
Create a hash search table
Synopsis:
#include <search.h>
int hcreate( size_t nel );
Arguments:
nel
An estimate of the maximum number of entries that the table will contain. The
algorithm might adjust this number upward in order to obtain certain
mathematically favorable circumstances.
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
The hcreate() function allocates space for the hash search table. You must call this
function before using hsearch().
The hsearch() and hcreate() functions use malloc() to allocate space.
Only one hash search table may be active at any given time. You can destroy the table
by calling hdestroy().
Returns:
0 if there isn’t enough space available to allocate the table.
Examples:
See hsearch().
Classification:
POSIX 1003.1 XSI
Safety
June 19, 2012
Cancellation point
No
Interrupt handler
No
Signal handler
No
Thread
Yes
QNX Neutrino Functions and Macros
825
hcreate()
© 2012, QNX Software Systems Limited
See also:
bsearch(), hdestroy(), hsearch(), malloc()
The Art of Computer Programming, Volume 3, Sorting and Searching by Donald E.
Knuth, published by Addison-Wesley Publishing Company, 1973.
826
QNX Neutrino Functions and Macros
June 19, 2012
hdestroy()
© 2012, QNX Software Systems Limited
Destroy the hash search table
Synopsis:
#include <search.h>
void hdestroy( void );
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
The hdestroy() function destroys the hash search table that was created by hcreate()
and used by hsearch(). Only one hash search table may be active at any given time.
Examples:
See hsearch().
Classification:
POSIX 1003.1 XSI
Safety
Cancellation point
No
Interrupt handler
No
Signal handler
No
Thread
Yes
See also:
hcreate(), hsearch()
June 19, 2012
QNX Neutrino Functions and Macros
827
herror()
© 2012, QNX Software Systems Limited
Print the message associated with the value of h_errno to standard error
Synopsis:
#include <netdb.h>
void herror( const char* prefix );
Arguments:
prefix
NULL, or a string that you want to print before the error message.
Library:
libsocket
Use the -l socket option to qcc to link against this library.
Description:
The herror() function prints the message corresponding to the error number contained
in h_errno to stderr. The following functions can set h_errno:
• gethostbyaddr()
• gethostbyaddr_r()
• gethostbyname()
• gethostbyname2()
• gethostbyname_r()
• res_query()
• res_search()
If the prefix string is non-NULL, it’s printed, followed by a colon and a space. The
error message is printed with a trailing newline. One of the following messages could
be printed:
HOST_NOT_FOUND
Authoritative answer: Unknown host.
NETDB_INTERNAL
You specified an invalid address family when calling
gethostbyname2().
NO_DATA
828
QNX Neutrino Functions and Macros
Valid name, no data record of the requested type. The name is
known to the name server, but has no IP address associated with
it—this isn’t a temporary error. Another type of request to the
name server using this domain name will result in an answer
(e.g. a mail-forwarder may be registered for this domain).
June 19, 2012
herror()
© 2012, QNX Software Systems Limited
NO_RECOVERY
TRY_AGAIN
Unknown server error. An unexpected server failure was
encountered. This is a nonrecoverable network error.
Nonauthoritative answer: Host name lookup failure. This is
usually a temporary error and means that the local server didn’t
receive a response from an authoritative server. A retry at some
later time may succeed.
Classification:
Unix
Safety
Cancellation point
Yes
Interrupt handler
No
Signal handler
No
Thread
No
See also:
gethostbyaddr(), gethostbyaddr_r(), gethostbyname(), gethostbyname_r(), h_errno,
res_query(), res_search(), stderr
June 19, 2012
QNX Neutrino Functions and Macros
829
hostent
© 2012, QNX Software Systems Limited
Structure that describes an Internet host
Synopsis:
#include <netdb.h>
struct hostent {
char * h_name;
char ** h_aliases;
int
h_addrtype;
int
h_length;
char ** h_addr_list;
};
#define h_addr
h_addr_list[0]
Description:
This structure describes an Internet host. It contains either the information obtained
from a name server, or broken-out fields from a line in /etc/hosts.
The members of this structure are:
h_name
The official name of the host.
h_aliases
A zero-terminated array of alternate names for the host.
h_addrtype
The type of address being returned; currently always AF_INET.
h_length
The length of the address, in bytes.
h_addr_list
A zero-terminated array of network addresses for the host. Host
addresses are returned in network byte order.
A #define statement is used to define the following:
h_addr
The first address in h_addr_list. This is for backward compatibility.
Classification:
POSIX 1003.1
See also:
endhostent(), gethostbyaddr(), gethostbyname(), gethostent(), sethostent()
/etc/hosts, /etc/resolv.conf in the Utilities Reference
830
QNX Neutrino Functions and Macros
June 19, 2012
hsearch()
© 2012, QNX Software Systems Limited
Search the hash search table
Synopsis:
#include <search.h>
ENTRY* hsearch ( ENTRY item,
ACTION action );
Arguments:
item
A structure of type ENTRY, defined in <search.h>, that contains:
• char *key — a pointer to the comparison key.
• void *data — a pointer to any other data to be associated with the key.
action
A member of an enumeration type ACTION, also defined in <search.h>,
indicating what to do with the entry if it isn’t in the table:
• ENTER — insert the entry in the table at the appropriate point. If the
item is a duplicate of an existing item, the new item isn’t added, and
hsearch() returns a pointer to the existing one.
• FIND — don’t add the entry. If the item can’t be found, hsearch()
returns NULL.
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
The hsearch() function is a hash-table search routine generalized from Knuth (6.4)
Algorithm D. Before using this function, you must call hcreate() to create the hash
table.
The hsearch() function returns a pointer into a hash table indicating the location at
which an entry can be found. This function uses strcmp() as the comparison function.
The hsearch() and hcreate() functions use malloc() to allocate space.
Only one hash search table may be active at any given time. You can destroy the table
by calling hdestroy().
Returns:
A pointer to the item found, or NULL if either the action is FIND and the item wasn’t
found, or the action is ENTER and the table is full.
June 19, 2012
QNX Neutrino Functions and Macros
831
hsearch()
© 2012, QNX Software Systems Limited
Examples:
The following example reads in strings followed by two numbers and stores them in a
hash table, discarding duplicates. It then reads in strings, finds the matching entry in
the hash table and prints it.
#include <stdio.h>
#include <search.h>
#include <string.h>
#include <stdlib.h>
struct info {
/* this is the info stored in table */
int age, room;
/* other than the key */
};
#define NUM_EMPL
5000 /* # of elements in search table */
main( )
{
/* space to store strings */
char string_space[NUM_EMPL*20];
/* space to store employee info */
struct info info_space[NUM_EMPL];
/* next avail space in string_space */
char *str_ptr = string_space;
/* next avail space in info_space */
struct info *info_ptr = info_space;
ENTRY item, *found_item;
/* name to look for in table */
char name_to_find[30];
int i = 0;
/* create table */
(void) hcreate(NUM_EMPL);
while (scanf("%s%d%d", str_ptr, &info_ptr->age,
&info_ptr->room) != EOF && i++ < NUM_EMPL) {
/* put info in structure, and structure in item */
item.key = str_ptr;
item.data = (void *)info_ptr;
str_ptr += strlen(str_ptr) + 1;
info_ptr++;
/* put item into table */
(void) hsearch(item, ENTER);
}
/* access table */
item.key = name_to_find;
while (scanf("%s", item.key) != EOF) {
if ((found_item = hsearch(item, FIND)) != NULL) {
/* if item is in the table */
(void)printf("found %s, age = %d, room = %d\n",
found_item->key,
((struct info *)found_item->data)->age,
((struct info *)found_item->data)->room);
} else {
(void)printf("no such employee %s\n",
name_to_find);
}
}
hdestroy();
return 0;
}
832
QNX Neutrino Functions and Macros
June 19, 2012
hsearch()
© 2012, QNX Software Systems Limited
Classification:
POSIX 1003.1 XSI
Safety
Cancellation point
No
Interrupt handler
No
Signal handler
Yes
Thread
Yes
See also:
bsearch(), hcreate(), hdestroy(), malloc(), strcmp()
The Art of Computer Programming, Volume 3, Sorting and Searching by Donald E.
Knuth, published by Addison-Wesley Publishing Company, 1973.
June 19, 2012
QNX Neutrino Functions and Macros
833
hstrerror()
© 2012, QNX Software Systems Limited
Get an error message string associated with the error return status
Synopsis:
#include <netdb.h>
const char* hstrerror( int err );
Arguments:
err
The error code that you want to get the message for. For more information, see
h_errno.
Library:
libsocket
Use the -l socket option to qcc to link against this library.
Description:
The hstrerror() function gets an error message string associated with the error return
status from network host-related functions.
Network host-related functions such as the following can return the error status:
• gethostbyaddr(), gethostbyaddr_r()
• gethostbyname(), gethostbyname_r()
• res_query()
• res_search()
You can check the external integer h_errno to see whether this is a temporary failure
or an invalid or unknown host.
Returns:
A pointer to the message string affiliated with an error number.
Don’t modify the message string.
Classification:
Unix
Safety
Cancellation point
No
Interrupt handler
No
continued. . .
834
QNX Neutrino Functions and Macros
June 19, 2012
hstrerror()
© 2012, QNX Software Systems Limited
Safety
Signal handler
Yes
Thread
Yes
See also:
h_errno, herror
June 19, 2012
QNX Neutrino Functions and Macros
835
htonl()
© 2012, QNX Software Systems Limited
Convert a 32-bit value from host-byte order to network-byte order
Synopsis:
#include <arpa/inet.h>
uint32_t htonl( uint32_t hostlong );
Arguments:
hostlong
The value that you want to convert.
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
The htonl() function converts a 32-bit value from host-byte order to network-byte
order.
You typically use this routine in conjunction with the internet addresses and ports that
gethostbyname() and getservent() return.
Returns:
The value in network-byte order.
Classification:
POSIX 1003.1
Safety
Cancellation point
No
Interrupt handler
Yes
Signal handler
Yes
Thread
Yes
See also:
gethostbyname(), getservent(), htons(), ntohl(), ntohs()
836
QNX Neutrino Functions and Macros
June 19, 2012
htons()
© 2012, QNX Software Systems Limited
Convert a 16-bit value from host-byte order to network-byte order
Synopsis:
#include <arpa/inet.h>
uint16_t htons( uint16_t hostshort );
Arguments:
hostshort
The value that you want to convert.
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
The htons() function converts a 16-bit value from host-byte order to network-byte
order.
You typically use this routine in conjunction with the internet addresses and ports that
gethostbyname() and getservent() return.
Returns:
The value in network-byte order.
Classification:
POSIX 1003.1
Safety
Cancellation point
No
Interrupt handler
Yes
Signal handler
Yes
Thread
Yes
See also:
gethostbyname(), getservent(), htonl(), ntohl(), ntohs()
June 19, 2012
QNX Neutrino Functions and Macros
837
hwi_find_item()
© 2012, QNX Software Systems Limited
Find an item in the hwinfo structure
Synopsis:
#include <hw/sysinfo.h>
unsigned hwi_find_item( unsigned start,
... );
Arguments:
start
Where to start the search for the given item.
For the initial call, set this argument to HWI_NULL_OFF. If the item found
isn’t the one that you want, pass the return value from the first call to
hwi_find_item() as the start parameter of the next call. This makes the
search pick up where it left off. You can repeat this process as many times
as required (the return value from the second call going into the start
parameter of the third, etc).
char *
A sequence of names for identifying the item being searched.
Terminate the sequence with a NULL pointer. The last string before the
NULL is the bottom-level item name that you’re looking for, the string in
front of that is the name of the item that owns the bottom-level item, etc.
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
This function is in libc.a, but not in libc.so (in order to save space).
Description:
The hwi_find_item() function finds an item in the hwinfo structure of the system page.
Returns:
The offset of the item requested, or HWI_NULL_OFF if the item wasn’t found.
Examples:
Find the first occurrence of an item called “foobar”:
item_off = hwi_find_item(HWI_NULL_OFF, "foobar", NULL);
Find the first occurrence of an item called “foobar” that’s owned by “sam”:
item_off = hwi_find_item(HWI_NULL_OFF, "sam", "foobar", NULL);
838
QNX Neutrino Functions and Macros
June 19, 2012
hwi_find_item()
© 2012, QNX Software Systems Limited
Classification:
QNX Neutrino
Safety
Cancellation point
No
Interrupt handler
Yes
Signal handler
Yes
Thread
Yes
See also:
hwi_find_tag(), hwi_off2tag(), hwi_tag2off()
“Structure of the system page” in the Customizing Image Startup Programs chapter of
Building Embedded Systems
June 19, 2012
QNX Neutrino Functions and Macros
839
hwi_find_tag()
© 2012, QNX Software Systems Limited
Find a tag in the hwinfo structure
Synopsis:
#include <hw/sysinfo.h>
unsigned hwi_find_tag( unsigned start,
int curr_item,
const char * tagname );
Arguments:
start
Where to start to search for the given item.
For the initial call, set this argument to HWI_NULL_OFF. If the item
found isn’t the one that you want, pass the return value from the first
call to hwi_find_tag() as the start parameter of the next call. This
makes the search pick up where it left off. You can repeat this process
as many times as required (the return value from the second call going
into the start parameter of the third, etc).
curr_item
If this argument is nonzero, the search stops at the end of the current
item (i.e. the one that start points to). If curr_item is zero, the search
continues until the end of the section.
tagname
The name of tag to search for.
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
This function is in libc.a, but not in libc.so (in order to save space).
Description:
The hwi_find_tag() function finds the tag named tagname.
Returns:
The offset of the tag, or HWI_NULL_OFF if the tag wasn’t found.
Classification:
QNX Neutrino
Safety
Cancellation point
No
continued. . .
840
QNX Neutrino Functions and Macros
June 19, 2012
hwi_find_tag()
© 2012, QNX Software Systems Limited
Safety
Interrupt handler
Yes
Signal handler
Yes
Thread
Yes
See also:
hwi_find_item(), hwi_off2tag(), hwi_tag2off()
“Structure of the system page” in the Customizing Image Startup Programs chapter of
Building Embedded Systems
June 19, 2012
QNX Neutrino Functions and Macros
841
hwi_off2tag()
© 2012, QNX Software Systems Limited
Return a pointer to the start of a tag in the hwinfo area of the system page
Synopsis:
#include <hw/sysinfo.h>
void * hwi_off2tag( unsigned offsect );
Arguments:
offsect
The offset, in bytes from the start of the hwinfo section, of a tag.
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
This function is in libc.a, but not in libc.so (in order to save space).
Description:
The hwi_off2tag() function returns a pointer to the start of the tag, given an offset.
Returns:
A pointer to the start of the tag.
Classification:
QNX Neutrino
Safety
Cancellation point
No
Interrupt handler
Yes
Signal handler
Yes
Thread
Yes
See also:
hwi_find_item(), hwi_find_tag(), hwi_tag2off()
“Structure of the system page” in the Customizing Image Startup Programs chapter of
Building Embedded Systems
842
QNX Neutrino Functions and Macros
June 19, 2012
hwi_tag2off()
© 2012, QNX Software Systems Limited
Return the offset from the start of the hwinfo area of the system page
Synopsis:
#include <hw/sysinfo.h>
unsigned hwi_tag2off( void *tag );
Arguments:
tag
A pointer to a tag in the hwinfo area of the system page.
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
This function is in libc.a, but not in libc.so (in order to save space).
Description:
Given a pointer to the start of a tag, the hwi_tag2off() function returns the offset, in
bytes, from the beginning of the start of the hwinfo section.
Returns:
The offset of the tag, in bytes.
Classification:
QNX Neutrino
Safety
Cancellation point
No
Interrupt handler
Yes
Signal handler
Yes
Thread
Yes
See also:
hwi_find_item(), hwi_find_tag(), hwi_off2tag()
“Structure of the system page” in the Customizing Image Startup Programs chapter of
Building Embedded Systems
June 19, 2012
QNX Neutrino Functions and Macros
843
hypot(), hypotf()
© 2012, QNX Software Systems Limited
Calculate the length of the hypotenuse for a right-angled triangle
Synopsis:
#include <math.h>
double hypot( double x,
double y );
float hypotf( float x,
float y );
Arguments:
x, y
The lengths of the sides that are adjacent to the right angle.
Library:
libm
Use the -l m option to qcc to link against this library.
Description:
These functions compute the length of the hypotenuse for a right triangle whose sides
are x and y adjacent to the right angle. The calculation is equivalent to:
length = sqrt( x*x + y*y );
Returns:
The length of the hypotenuse.
If an error occurs, these functions return 0, but this is also a valid mathematical result.
If you want to check for errors, set errno to 0, call the function, and then check errno
again. These functions don’t change errno if no errors occurred.
Examples:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main( void )
{
printf( "%f\n", hypot( 3.0, 4.0 ) );
return EXIT_SUCCESS;
}
produces the output:
5.000000
844
QNX Neutrino Functions and Macros
June 19, 2012
hypot(), hypotf()
© 2012, QNX Software Systems Limited
Classification:
ANSI, POSIX 1003.1
Safety
Cancellation point
No
Interrupt handler
No
Signal handler
No
Thread
Yes
See also:
sqrt
June 19, 2012
QNX Neutrino Functions and Macros
845
ICMP
© 2012, QNX Software Systems Limited
Internet Control Message Protocol
Synopsis:
#include <sys/socket.h>
#include <netinet/in.h>
int socket( AF_INET,
SOCK_RAW,
proto );
Description:
ICMP is the error- and control-message protocol used by IP and the Internet protocol
family. The protocol may be accessed through a “raw socket” for network monitoring
and diagnostic functions.
To get the proto parameter to socket() that’s used to create an ICMP socket, call
getprotobyname(). You normally use ICMP sockets, which are connectionless, with
sendto() and recvfrom(), although you can also use connect() to fix the destination for
future packets (in which case you can use the read() or recv(), and write() or send()
system calls).
Outgoing packets automatically have an IP header prepended to them that’s based on
the destination address. Incoming packets are received with the IP header and IP
options intact.
Returns:
A descriptor referencing the socket, or -1 if an error occurs (errno is set).
Errors:
EADDRNOTAVAIL
Tried to create a socket with a network address for which no network
interface exists.
EISCONN
Tried to establish a connection on a socket that already has one, or
tried to send a datagram with the destination address specified but
the socket is already connected.
ENOBUFS
The system ran out of memory for an internal data structure.
ENOTCONN
Tried to send a datagram, but no destination address was specified,
and the socket hasn’t been connected.
See also:
ICMP6, IP protocols
connect(), getprotobyname(), read(), recv(), recvfrom(), send(), sendto(), socket(),
write()
Based on RFC 792
846
QNX Neutrino Functions and Macros
June 19, 2012
ICMP6
© 2012, QNX Software Systems Limited
Internet Control Message Protocol for IP6
Synopsis:
#include <sys/socket.h>
#include <netinet/in.h>
#include <netinet/icmp6.h>
int socket( AF_INET6,
SOCK_RAW,
proto);
Description:
ICMP6 is the error and control message protocol that IP6 and the Internet Protocol
family use. It may be accessed through a “raw socket” for network monitoring and
diagnostic functions. Use the getprotobyname() function to obtain the proto parameter
to the socket() function, or simply pass IPPROTO_ICMPV6.
ICMPv6 sockets are connectionless, and are normally used with the sendto() and
recvfrom() functions. You may also use the connect() function to fix the destination for
future packets (in which case, you may also use the read() or recv() functions and the
write() or send() system calls).
Outgoing packets automatically have an IP6 header prepended to them (based on the
destination address). The ICMP6 pseudo header checksum field (icmp6_cksum, found
in the icmp6_hdr structure in <netinet/icmp6.h>) is filled automatically by the
socket manager. Incoming packets are received without the IP6 header or extension
headers.
This behavior is opposite from both IPv4 raw sockets and ICMPv4 sockets.
ICMP6 type/code filter
Each ICMP6 raw socket has an associated filter whose data type is defined as struct
icmp6_filter. This structure, along with the macros and constants defined below
are defined in the <netinet/icmp6.h> header.
You can get and set the current filter by calling getsockopt() and setsockopt() with a
level of IPPROTO_ICMPV6 and an option name of ICMP6_FILTER.
The following macros operate on an icmp6_filter structure. If the first argument is
an integer, it represents an ICMP6 message type, with a value between 0 and 255. The
pointer arguments are pointers to the filters that are either set or examined, depending
on the macro:
ICMP6_FILTER_SETPASSALL( struct icmp6_filter* )
Pass all ICMPv6 messages to the application.
ICMP6_FILTER_SETBLOCKALL( struct icmp6_filter* )
Block all ICMPv6 messages from the application.
June 19, 2012
QNX Neutrino Functions and Macros
847
ICMP6
© 2012, QNX Software Systems Limited
ICMP6_FILTER_SETPASS( int, struct icmp6_filter* )
Pass messages of a certain ICMPv6 type to the application.
ICMP6_FILTER_SETBLOCK ( int, struct icmp6_filter* )
Block messages of a certain ICMPv6 type from the application.
ICMP6_FILTER_WILLPASS( int, const struct icmp6_filter* )
Return true or false, depending on whether or not the specified message type is
passed to the application.
ICMP6_FILTER_WILLBLOCK ( int, const struct icmp6_filter* )
Return true or false, depending on whether or not the specified message type is
blocked from the application.
When you create an ICMP6 raw socket, it passes all ICMPv6 message types to the
application by default.
For more information, see RFC 2292.
See also:
INET6, IP6 protocols
connect(), getprotobyname(), getsockopt(), read(), recv(), recvfrom(), send(), sendto(),
setsockopt(), socket(), write()
Based on RFC 2292
848
QNX Neutrino Functions and Macros
June 19, 2012
if_freenameindex()
© 2012, QNX Software Systems Limited
Free dynamic memory allocated by if_nameindex()
Synopsis:
#include <net/if.h>
void if_freenameindex( struct if_nameindex * ptr );
Arguments:
ptr
A pointer to the if_nameindex structure to be freed.
Library:
libsocket
Use the -l socket option to qcc to link against this library.
Description:
The if_freenameindex() function frees the dynamic memory that you allocated by
calling if_nameindex().
Classification:
POSIX 1003.1
Safety
Cancellation point
No
Interrupt handler
No
Signal handler
No
Thread
Yes
See also:
getifaddrs(), if_indextoname(), if_nameindex(), if_nametoindex()
June 19, 2012
QNX Neutrino Functions and Macros
849
if_indextoname()
© 2012, QNX Software Systems Limited
Map an interface index to its name
Synopsis:
#include <net/if.h>
char * if_indextoname( unsigned int ifindex,
char * ifname );
Arguments:
ifindex
The interface index.
ifname
A pointer to a buffer in which if_indextoname() copies the interface name.
The buffer must be a minimum of IFNAMSIZ bytes long.
Library:
libsocket
Use the -l socket option to qcc to link against this library.
Description:
The if_indextoname() function maps the interface index specified by ifindex to its
corresponding name. The name is copied into the buffer pointed to by ifname.
Returns:
A pointer to the name, or NULL if There isn’t an interface corresponding to the
specified index.
Classification:
POSIX 1003.1
Safety
Cancellation point
Yes
Interrupt handler
No
Signal handler
No
Thread
Yes
See also:
getifaddrs(), if_freenameindex(), if_nameindex(), if_nametoindex()
850
QNX Neutrino Functions and Macros
June 19, 2012
if_nameindex()
© 2012, QNX Software Systems Limited
Return a list of interfaces
Synopsis:
#include <net/if.h>
struct if_nameindex * if_nameindex( void );
Library:
libsocket
Use the -l socket option to qcc to link against this library.
Description:
The if_nameindex() function returns an array of if_nameindex structures, with one
structure per interface, as defined in the include file <net/if.h>. The
if_nameindex structure contains at least the following members:
unsigned int if_index
The index of the interface (1, 2, . . . ).
char *if_name
A null-terminated name (e.g. le0).
The end of the array of structures is indicated by an entry with an if_index of 0 and an
if_name of NULL.
Returns:
A valid array of if_nameindex structures, or NULL if and error occurred while using
getifaddrs() to retrieve the list, or there wasn’t enough memory available.
Classification:
POSIX 1003.1
Safety
Cancellation point
Yes
Interrupt handler
No
Signal handler
No
Thread
Yes
See also:
getifaddrs(), if_freenameindex(), if_indextoname(), if_nametoindex()
June 19, 2012
QNX Neutrino Functions and Macros
851
if_nametoindex()
© 2012, QNX Software Systems Limited
Map an interface name to its index
Synopsis:
#include <net/if.h>
unsigned int if_nametoindex( const char * ifname );
Arguments:
ifname
The interface name that you want to map.
Library:
libsocket
Use the -l socket option to qcc to link against this library.
Description:
The if_nametoindex() function maps the interface name specified by ifname to its
corresponding index.
Returns:
The index number of the interface, or 0 if the specified interface couldn’t be found or
an error occurred while using getifaddrs() to retrieve the list of interfaces.
Classification:
POSIX 1003.1
Safety
Cancellation point
Yes
Interrupt handler
No
Signal handler
No
Thread
Yes
See also:
getifaddrs(), if_freenameindex(), if_indextoname(), if_nameindex()
852
QNX Neutrino Functions and Macros
June 19, 2012
ifaddrs
© 2012, QNX Software Systems Limited
Structure that describes an Internet host
Synopsis:
#include <ifaddrs.h>
struct ifaddrs {
struct ifaddrs *
char *
u_int
struct sockaddr *
struct sockaddr *
struct sockaddr *
void *
};
ifa_next;
ifa_name;
ifa_flags;
ifa_addr;
ifa_netmask;
ifa_dstaddr;
ifa_data;
Description:
The ifaddrs structure contains the following entries:
ifa_next
A pointer to the next structure in the list. This field is NULL in the
last structure in the list.
ifa_name
The interface name.
ifa_flags
The interface flags, as set by the ifconfig utility.
ifa_addr
Either the address of the interface or the link-level address of the
interface, if one exists; otherwise it’s NULL. See the sa_family
member of the sockaddr structure pointed to by ifa_addr to
determine the format of the address.
ifa_netmask
The netmask associated with ifa_addr, if one is set; otherwise it’s
NULL.
ifa_dstaddr
The destination address on a P2P interface, if one exists; otherwise
it’s NULL. If the interface isn’t a P2P interface, ifa_dstaddr contains
the broadcast address associated with ifa_addr, if one exists;
otherwise it’s NULL (see <ifaddr.h>).
ifa_data
Currently, this is set to NULL.
Classification:
Unix
See also:
freeifaddrs(), getifaddrs()
June 19, 2012
QNX Neutrino Functions and Macros
853
ilogb(), ilogbf()
© 2012, QNX Software Systems Limited
Compute the integral part of a logarithm
Synopsis:
#include <math.h>
int ilogb ( double x );
int ilogbf (float x );
Arguments:
x
The number you want to compute the integral part of the logarithm.
Library:
libm
Use the -l m option to qcc to link against this library.
Description:
The ilogb() and ilogbf() functions compute the integral part of:
logr |x|
as a signed integral value, for nonzero finite x, where r is the radix of the machine’s
floating point arithmetic.
Returns:
The exponent part of x, in integer format:
If x is:
ilogb() returns:
0
-INT_MAX
NAN
INT_MAX
Negative infinity
INT_MAX
Positive infinity
INT_MAX
If an error occurs, these functions return 0, but this is also a valid mathematical result.
If you want to check for errors, set errno to 0, call the function, and then check errno
again. These functions don’t change errno if no errors occurred.
Examples:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main( void )
{
854
QNX Neutrino Functions and Macros
June 19, 2012
ilogb(), ilogbf()
© 2012, QNX Software Systems Limited
printf( "%f\n", ilogb(.5) );
return EXIT_SUCCESS;
}
Classification:
ANSI, POSIX 1003.1
Safety
Cancellation point
No
Interrupt handler
No
Signal handler
No
Thread
Yes
See also:
log(), logb(), log10(), log1p()
June 19, 2012
QNX Neutrino Functions and Macros
855
in8()
© 2012, QNX Software Systems Limited
Read an 8-bit value from a port
Synopsis:
#include <hw/inout.h>
uint8_t in8( uintptr_t port );
Arguments:
port
The port you want to read the value from.
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
The in8() function reads an 8-bit value from the specified port.
Returns:
An 8-bit value.
Classification:
QNX Neutrino
Safety
Cancellation point
No
Interrupt handler
Yes
Signal handler
Yes
Thread
Yes
Caveats:
The calling thread must have I/O privileges; see ThreadCtl()’s _NTO_TCTL_IO
command for details.
The calling process must also use mmap_device_io() to access the device’s I/O
registers.
See also:
in8s(), in16(), in16s(), in32(), in32s(), mmap_device_io(), out8(), out8s(), out16(),
out16s(), out32(), out32s()
856
QNX Neutrino Functions and Macros
June 19, 2012
in8s()
© 2012, QNX Software Systems Limited
Read 8-bit values from a port
Synopsis:
#include <hw/inout.h>
void * in8s( void * buff ,
unsigned len,
uintptr_t port );
Arguments:
buff
A pointer to a buffer where the function can store the values read.
len
The number of values that you want to read.
port
The port you want to read the values from.
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
The in8s() function reads len 8-bit values from the specified port and stores them in
the buffer pointed to by buff .
Returns:
A pointer to the end of the read data.
Classification:
QNX Neutrino
Safety
Cancellation point
No
Interrupt handler
Yes
Signal handler
Yes
Thread
Yes
Caveats:
The calling thread must have I/O privileges; see ThreadCtl()’s _NTO_TCTL_IO
command for details.
June 19, 2012
QNX Neutrino Functions and Macros
857
in8s()
© 2012, QNX Software Systems Limited
The calling process must also use mmap_device_io() to access the device’s I/O
registers.
See also:
in8(), in16(), in16s(), in32(), in32s(), mmap_device_io(), out8(), out8s(), out16(),
out16s(), out32(), out32s()
858
QNX Neutrino Functions and Macros
June 19, 2012
in16(), inbe16(), inle16()
© 2012, QNX Software Systems Limited
Read a 16-bit value from a port
Synopsis:
#include <hw/inout.h>
uint16_t in16( uintptr_t port );
#define inbe16 ( port ) ...
#define inle16 ( port ) ...
Arguments:
port
The port you want to read the value from.
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
The in16() function reads a 16-bit value from the specified port in native-endian
format (there’s no conversion required).
The inbe16() and inle16() macros read a 16-bit value that’s in big-endian or
little-endian format, respectively, from the specified port, and returns the value as
native-endian.
!
CAUTION: The inbe16() and inle16() macros access the specified port more than
once if endian conversion is necessary. This could be a problem on some hardware.
Returns:
A 16-bit value in native-endian.
Classification:
QNX Neutrino
Safety
June 19, 2012
Cancellation point
No
Interrupt handler
Yes
Signal handler
Yes
Thread
Yes
QNX Neutrino Functions and Macros
859
in16(), inbe16(), inle16()
© 2012, QNX Software Systems Limited
Caveats:
The calling thread must have I/O privileges; see ThreadCtl()’s _NTO_TCTL_IO
command for details.
The calling process must also use mmap_device_io() to access the device’s I/O
registers.
Both inbe16() and inle16() are implemented as macros.
See also:
in8(), in8s(), in16s(), in32(), in32s(), mmap_device_io(), out8(), out8s(), out16(),
out16s(), out32(), out32s()
860
QNX Neutrino Functions and Macros
June 19, 2012
in16s()
© 2012, QNX Software Systems Limited
Read 16-bit values from a port
Synopsis:
#include <hw/inout.h>
void * in16s( void * buff ,
unsigned len,
uintptr_t port );
Arguments:
buff
A pointer to a buffer where the function can store the values read.
len
The number of values that you want to read.
port
The port you want to read the values from.
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
The in16s() function reads len 16-bit values from the specified port and stores them in
the buffer pointed to by buff .
Returns:
A pointer to the end of the read data.
Classification:
QNX Neutrino
Safety
Cancellation point
No
Interrupt handler
Yes
Signal handler
Yes
Thread
Yes
Caveats:
The calling thread must have I/O privileges; see ThreadCtl()’s _NTO_TCTL_IO
command for details.
June 19, 2012
QNX Neutrino Functions and Macros
861
in16s()
© 2012, QNX Software Systems Limited
The calling process must also use mmap_device_io() to access the device’s I/O
registers.
See also:
in8(), in8s(), in16(), in32(), in32s(), mmap_device_io(), out8(), out8s(), out16(),
out16s(), out32(), out32s()
862
QNX Neutrino Functions and Macros
June 19, 2012
in32(), inbe32(), inle32()
© 2012, QNX Software Systems Limited
Read a 32-bit value from a port
Synopsis:
#include <hw/inout.h>
uint32_t in32( uintptr_t port );
#define inbe32 ( port ) ...
#define inle32 ( port ) ...
Arguments:
port
The port you want to read the value from.
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
The in32() function reads a 32-bit value from the specified port.
The inbe32() and inle32() macros read a 32-bit value that’s in big-endian or
little-endian format, respectively, from the specified port, and returns the value as
native-endian.
!
CAUTION: The inbe32() and inle32() macros access the specified port more than
once if endian conversion is necessary. This could be a problem on some hardware.
Returns:
A 32-bit value in native-endian.
Classification:
QNX Neutrino
Safety
June 19, 2012
Cancellation point
No
Interrupt handler
Yes
Signal handler
Yes
Thread
Yes
QNX Neutrino Functions and Macros
863
in32(), inbe32(), inle32()
© 2012, QNX Software Systems Limited
Caveats:
The calling thread must have I/O privileges; see ThreadCtl()’s _NTO_TCTL_IO
command for details.
The calling process must also use mmap_device_io() to access the device’s I/O
registers.
Both inbe32() and inle32() are implemented as macros.
See also:
in8(), in8s(), in16(), in16s(), in32s(), mmap_device_io(), out8(), out8s(), out16(),
out16s(), out32(), out32s()
864
QNX Neutrino Functions and Macros
June 19, 2012
in32s()
© 2012, QNX Software Systems Limited
Read 32-bit values from a port
Synopsis:
#include <hw/inout.h>
void * in32s( void * buff ,
unsigned len,
uintptr_t port );
Arguments:
buff
A pointer to a buffer where the function can store the values read.
len
The number of values that you want to read.
port
The port you want to read the values from.
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
The in32s() function reads len 32-bit values from the specified port and stores them in
the buffer pointed to by buff .
Returns:
A pointer to the end of the read data.
Classification:
QNX Neutrino
Safety
Cancellation point
No
Interrupt handler
Yes
Signal handler
Yes
Thread
Yes
Caveats:
The calling thread must have I/O privileges; see ThreadCtl()’s _NTO_TCTL_IO
command for details.
June 19, 2012
QNX Neutrino Functions and Macros
865
in32s()
© 2012, QNX Software Systems Limited
The calling process must also use mmap_device_io() to access the device’s I/O
registers.
See also:
in8(), in8s(), in16(), in16s(), in32(), mmap_device_io(), out8(), out8s(), out16(),
out16s(), out32(), out32s()
866
QNX Neutrino Functions and Macros
June 19, 2012
index()
© 2012, QNX Software Systems Limited
Find a character in a string
Synopsis:
#include <strings.h>
char* index( const char* s,
int c );
Arguments:
s
The string you want to search. This string must end with a null (\0) character.
The null character is considered to be part of the string.
c
The character you’re looking for.
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
The index() function returns a pointer to the first occurrence of the character c in the
string s.
Returns:
A pointer to the character, or NULL if the character doesn’t occur in the string.
Classification:
POSIX 1003.1 XSI
Safety
Cancellation point
No
Interrupt handler
No
Signal handler
Yes
Thread
Yes
See also:
rindex(), strchr(), strrchr()
June 19, 2012
QNX Neutrino Functions and Macros
867
inet_addr()
© 2012, QNX Software Systems Limited
Convert a string into a numeric Internet address
Synopsis:
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
in_addr_t inet_addr( const char * cp );
Arguments:
cp
A pointer to a string that represents an Internet address.
Library:
libsocket
Use the -l socket option to qcc to link against this library.
Description:
The inet_addr() routine converts a string representing an IPv4 Internet address (for
example, “127.0.0.1”) into a numeric Internet address. To convert a hostname such
as ftp.qnx.com, call gethostbyname().
All Internet addresses are returned in network byte order (bytes are ordered from left
to right). All network numbers and local address parts are returned as machine-format
integer values. For more information on Internet addresses, see inet_net_ntop().
Returns:
An Internet address, or INADDR_NONE if an error occurs.
Classification:
POSIX 1003.1
Safety
Cancellation point
No
Interrupt handler
No
Signal handler
Yes
Thread
Yes
Caveats:
Although the value INADDR_NONE (0xFFFFFFFF) is a valid broadcast address,
inet_addr() always indicates failure when returning that value. The inet_aton()
function doesn’t share this problem.
868
QNX Neutrino Functions and Macros
June 19, 2012
© 2012, QNX Software Systems Limited
inet_addr()
See also:
inet_aton(), inet_network()
June 19, 2012
QNX Neutrino Functions and Macros
869
inet_aton()
© 2012, QNX Software Systems Limited
Convert a string into an Internet address stored in a structure
Synopsis:
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
int inet_aton( const char * cp,
struct in_addr * addr );
Arguments:
cp
A pointer to the character string.
addr
A pointer to a in_addr structure where the function can store the converted
address.
Library:
libsocket
Use the -l socket option to qcc to link against this library.
Description:
The inet_aton() routine interprets the specified character string as an IPv4 Internet
address, placing the address into the structure provided.
All Internet addresses are returned in network byte order (bytes are ordered from left
to right). All network numbers and local address parts are returned as machine-format
integer values.
For more information on Internet addresses, see inet_net_ntop().
Returns:
1
Success; the string was successfully interpreted.
0
Failure; the string is invalid.
Classification:
Unix
Safety
870
Cancellation point
No
Interrupt handler
No
Signal handler
Yes
Thread
Yes
QNX Neutrino Functions and Macros
June 19, 2012
inet_aton()
© 2012, QNX Software Systems Limited
See also:
gethostbyname(), getnetent() inet_addr(), inet_lnaof(), inet_makeaddr(), inet_netof(),
inet_network(), inet_ntoa()
/etc/hosts, /etc/networks in the Utilities Reference
June 19, 2012
QNX Neutrino Functions and Macros
871
inet_lnaof()
© 2012, QNX Software Systems Limited
Extract the local network address from an Internet address
Synopsis:
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
unsigned long inet_lnaof( struct in_addr in );
Arguments:
in
An Internet address.
Library:
libsocket
Use the -l socket option to qcc to link against this library.
Description:
The inet_lnaof() routine returns the local network address for an IPv4 Internet
address.
All Internet addresses are returned in network byte order (bytes are ordered from left
to right). All network numbers and local address parts are returned as machine-format
integer values. For more information on Internet addresses, see inet_net_ntop().
Returns:
A local network address.
Classification:
QNX Neutrino
Safety
Cancellation point
No
Interrupt handler
No
Signal handler
Yes
Thread
Yes
See also:
inet_aton(), inet_netof()
872
QNX Neutrino Functions and Macros
June 19, 2012
inet_makeaddr()
© 2012, QNX Software Systems Limited
Convert a network number and a local network address into an Internet address
Synopsis:
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
struct in_addr inet_makeaddr( unsigned long net,
unsigned long lna );
Arguments:
net
An Internet network number.
lna
The local network address.
Library:
libsocket
Use the -l socket option to qcc to link against this library.
Description:
The inet_makeaddr() routine takes an Internet network number and a local network
address and constructs an IPv4 Internet address.
All Internet addresses are returned in network byte order (bytes are ordered from left
to right). All network numbers and local address parts are returned as machine-format
integer values. For more information on Internet addresses, see inet_net_ntop().
Returns:
An Internet address.
Classification:
QNX Neutrino
Safety
June 19, 2012
Cancellation point
No
Interrupt handler
No
Signal handler
Yes
Thread
Yes
QNX Neutrino Functions and Macros
873
inet_makeaddr()
© 2012, QNX Software Systems Limited
See also:
inet_aton()
874
QNX Neutrino Functions and Macros
June 19, 2012
inet_net_ntop()
© 2012, QNX Software Systems Limited
Convert an Internet network number to CIDR format
Synopsis:
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
char * inet_net_ntop( int af ,
const void * src,
int bits,
char * dst,
size_t size );
Arguments:
af
The address family. Currently, only AF_INET is supported.
src
A pointer to the Internet network number that you want to convert. The
format of the address is interpreted according to af .
bits
The number of bits that specify the network number (src).
dst
a pointer to the buffer where the function can store the converted address.
size
The size of the buffer that dst points to, in bytes.
Library:
libsocket
Use the -l socket option to qcc to link against this library.
Description:
The inet_net_ntop() function converts an Internet network number from network
format (usually a struct in_addr or some other binary form, in network byte
order) to CIDR (Classless Internet Domain Routing) presentation format that’s
suitable for external display purposes.
With CIDR, a single IP address can be used to designate many unique IP addresses. A
CIDR IP address looks like a normal IP address, except that it ends with a slash (/)
followed by a number, called the IP prefix. For example:
172.200.0.0/16
The IP prefix specifies how many addresses are covered by the CIDR address, with
lower numbers covering more addresses.
Network Numbers (IPv4 Internet addresses)
You can specify Internet addresses in the “dotted quad” notation, or Internet network
numbers, using one of the following forms:
June 19, 2012
QNX Neutrino Functions and Macros
875
inet_net_ntop()
© 2012, QNX Software Systems Limited
a.b.c.d/bits or a.b.c.d
When you specify a four-part address, each part is interpreted as a byte of
data and is assigned, from left to right, to the four bytes of an Internet
network number (or Internet address). When an Internet network number is
viewed as a 32-bit integer quantity on a system that uses little-endian byte
order (i.e. right to left), such as the Intel 486 and Pentium processors, the
bytes referred to above appear as “d.c.b.a”.
a.b.c
When you specify a three-part address, the last part is interpreted as a 16-bit
quantity and is placed in the rightmost two bytes of the Internet network
number (or network address). This makes the three-part address format
convenient for specifying Class B network addresses as net.net.host.
a.b
When you specify a two-part address, the last part is interpreted as a 24-bit
quantity and is placed in the rightmost three bytes of the Internet network
number (or network address). This makes the two-part number format
convenient for specifying Class A network numbers as net.host.
a
When you specify a one-part address, the value is stored directly in the
Internet network number (network address) without any byte rearrangement.
All numbers supplied as “parts” in a dot notation may be decimal, octal, or
hexadecimal, as specified in the C language. That is, a number is interpreted as
decimal unless it has a leading 0 (octal), or a leading 0x or 0X (hex).
Returns:
A pointer to the destination string (dst), or NULL if a system error occurs (errno is set).
Errors:
ENOENT
Invalid argument af .
Classification:
QNX Neutrino
Safety
876
Cancellation point
No
Interrupt handler
No
Signal handler
No
Thread
Yes
QNX Neutrino Functions and Macros
June 19, 2012
© 2012, QNX Software Systems Limited
inet_net_ntop()
See also:
inet_aton(), inet_net_ntop()
June 19, 2012
QNX Neutrino Functions and Macros
877
inet_netof()
© 2012, QNX Software Systems Limited
Extract the network number from an Internet address
Synopsis:
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
unsigned long inet_netof( struct in_addr in );
Arguments:
in
An Internet address.
Library:
libsocket
Use the -l socket option to qcc to link against this library.
Description:
The inet_netof() routine returns the network number of the specified IPv4 Internet
address.
All Internet addresses are returned in network order (bytes are ordered from left to
right). All network numbers and local address parts are returned as machine-format
integer values. For more information on Internet addresses, see inet_net_ntop().
Returns:
An Internet network number.
Classification:
QNX Neutrino
Safety
Cancellation point
No
Interrupt handler
No
Signal handler
Yes
Thread
Yes
See also:
inet_aton(), inet_lnaof()
878
QNX Neutrino Functions and Macros
June 19, 2012
inet_net_pton()
© 2012, QNX Software Systems Limited
Convert an Internet network number from CIDR format to network format
Synopsis:
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
int inet_net_pton( int af ,
const char * src,
void * dst,
size_t size );
Arguments:
af
The address family. Currently, only AF_INET is supported.
src
A pointer to the presentation-format (CIDR) address. The format of the
address is interpreted according to af .
dst
A pointer to the buffer where the function can store the converted address.
size
The size of the buffer pointed to by dst, in bytes.
Library:
libsocket
Use the -l socket option to qcc to link against this library.
Description:
The inet_net_pton() function converts an Internet network number from presentation
format — a printable form as held in a character string, such as, Internet standard dot
notation, or Classless Internet Domain Routing (CIDR) — to network format (usually
a struct in_addr or some other internal binary representation, in network byte order).
For more information on Internet addresses, see inet_net_ntop().
Returns:
The number of bits that specify the network number (computed based on the class, or
specified with /CIDR), or -1 if an error occurred (errno is set).
Errors:
ENOENT
Invalid argument af .
Classification:
QNX Neutrino
June 19, 2012
QNX Neutrino Functions and Macros
879
inet_net_pton()
© 2012, QNX Software Systems Limited
Safety
Cancellation point
No
Interrupt handler
No
Signal handler
No
Thread
Yes
See also:
inet_aton(), inet_net_ntop()
880
QNX Neutrino Functions and Macros
June 19, 2012
inet_network()
© 2012, QNX Software Systems Limited
Convert a string into an Internet network number
Synopsis:
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
unsigned long inet_network( const char * cp );
Arguments:
cp
A pointer to a string representing an Internet address.
Library:
libsocket
Use the -l socket option to qcc to link against this library.
Description:
The inet_network() routine converts a string representing an IPv4 Internet address (for
example, “127.0.0.1”) into a numeric Internet network number.
All Internet addresses are returned in network order (bytes are ordered from left to
right). All network numbers and local address parts are returned as machine-format
integer values. For more information on Internet addresses, see inet_net_ntop().
Returns:
An Internet network number, or INADDR_NONE if an error occurs.
Classification:
QNX Neutrino
Safety
Cancellation point
No
Interrupt handler
No
Signal handler
Yes
Thread
Yes
See also:
inet_addr(), inet_aton()
June 19, 2012
QNX Neutrino Functions and Macros
881
inet_ntoa()
© 2012, QNX Software Systems Limited
Convert an Internet address into a string
Synopsis:
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
char * inet_ntoa( struct in_addr in );
Arguments:
in
The Internet address that you want to convert.
Library:
libsocket
Use the -l socket option to qcc to link against this library.
Description:
The inet_ntoa() routine converts an IPv4 Internet address into an ASCII string
representing the address in dot notation (for example, “127.0.0.1”).
For more information on Internet addresses, see inet_net_ntop().
Returns:
A string representing an Internet address.
Classification:
POSIX 1003.1
Safety
Cancellation point
No
Interrupt handler
No
Signal handler
No
Thread
No
Caveats:
The string returned by this function is stored in a static buffer that’s reused for every
call to inet_ntoa(). For a thread-safe version, see inet_ntoa_r().
882
QNX Neutrino Functions and Macros
June 19, 2012
© 2012, QNX Software Systems Limited
inet_ntoa()
See also:
inet_aton(), inet_ntoa_r()
June 19, 2012
QNX Neutrino Functions and Macros
883
inet_ntoa_r()
© 2012, QNX Software Systems Limited
Convert an Internet address into a string
Synopsis:
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
char * inet_ntoa_r( struct in_addr in,
char * buffer,
int bufflen );
Arguments:
in
The Internet address that you want to convert.
buffer
A buffer where the function can store the result.
bufflen
The size of the buffer, in bytes.
Library:
libsocket
Use the -l socket option to qcc to link against this library.
Description:
The inet_ntoa_r() function is a thread-safe version of inet_ntoa(). It converts an IPv4
Internet address into a string (for example, “127.0.0.1"”). For more information on
this routine, see inet_aton().
Returns:
A string representing an Internet address, or NULL if an error occurs (errno is set).
Errors:
ERANGE
The supplied buffer isn’t large enough to store the result.
Classification:
Unix
Safety
884
Cancellation point
No
Interrupt handler
No
Signal handler
No
Thread
Yes
QNX Neutrino Functions and Macros
June 19, 2012
© 2012, QNX Software Systems Limited
inet_ntoa_r()
See also:
inet_aton(), inet_ntoa()
June 19, 2012
QNX Neutrino Functions and Macros
885
inet_ntop()
© 2012, QNX Software Systems Limited
Convert a numeric network address to a string
Synopsis:
#include <sys/socket.h>
#include <arpa/inet.h>
const char * inet_ntop( int af ,
const void * src,
char * dst,
socklen_t size );
Arguments:
af
The src address’s network family; one of:
AF_INET
IPv4 addresses
AF_INET6
IPv6 addresses
src
The numeric network address that you want to convert to a string.
dst
The text string that represents the translated network address. You can use the
following constants to allocate buffers of the correct size (they’re defined in
<netinet/in.h>):
• INET_ADDRSTRLEN — storage for an IPv4 address
• INET6_ADDRSTRLEN — storage for an IPv6 address
size
The size of the buffer pointed to by dst.
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
The inet_ntop() function converts a numeric network address pointed to by src into a
text string in the buffer pointed to by dst.
Returns:
A pointer to the buffer containing the text version of the address, or NULL if an error
occurs (errno is set).
Errors:
886
EAFNOSUPPORT
The value of the af argument isn’t a supported network family.
ENOSPC
The dst buffer isn’t large enough (according to size) to store the
translated address.
QNX Neutrino Functions and Macros
June 19, 2012
inet_ntop()
© 2012, QNX Software Systems Limited
Examples:
#include
#include
#include
#include
#include
<stdio.h>
<stdlib.h>
<sys/socket.h>
<arpa/inet.h>
<errno.h>
#define INADDR "10.1.0.29"
#define IN6ADDR "DEAD:BEEF:7654:3210:FEDC:3210:7654:BA98"
int
main()
{
struct in_addr inaddr;
struct in6_addr in6addr;
char buf[INET_ADDRSTRLEN], buf6[INET6_ADDRSTRLEN];
int rval;
if ( (rval = inet_pton(AF_INET, INADDR, &inaddr)) == 0) {
printf("Invalid address: %s\n", INADDR);
exit(EXIT_FAILURE);
} else if (rval == -1) {
perror("inet_pton");
exit(EXIT_FAILURE);
}
if (inet_ntop(AF_INET, &inaddr, buf, sizeof(buf)) != NULL)
printf("inet addr: %s\n", buf);
else {
perror("inet_ntop");
exit(EXIT_FAILURE);
}
if ( (rval = inet_pton(AF_INET6, IN6ADDR, &in6addr)) == 0) {
printf("Invalid address: %s\n", IN6ADDR);
exit(EXIT_FAILURE);
} else if (rval == -1) {
perror("inet_pton");
exit(EXIT_FAILURE);
}
if (inet_ntop(AF_INET6, &in6addr, buf6, sizeof(buf6)) != NULL)
printf("inet6 addr: %s\n", buf6);
else {
perror("inet_ntop");
exit(EXIT_FAILURE);
}
return(EXIT_SUCCESS);
}
Classification:
POSIX 1003.1
Safety
Cancellation point
No
continued. . .
June 19, 2012
QNX Neutrino Functions and Macros
887
inet_ntop()
© 2012, QNX Software Systems Limited
Safety
Interrupt handler
No
Signal handler
Yes
Thread
Yes
See also:
inet_pton()
888
QNX Neutrino Functions and Macros
June 19, 2012
inet_pton()
© 2012, QNX Software Systems Limited
Convert a text host address to a numeric address
Synopsis:
#include <sys/socket.h>
#include <arpa/inet.h>
int inet_pton( int af ,
const char * src,
void * dst );
Arguments:
af
The src address’s network family; one of:
AF_INET
IPv4 addresses
AF_INET6
IPv6 addresses
src
A pointer to the text host address that you want to convert. The format of the
address is interpreted according to af
dst
A pointer to a buffer where the function can store the converted address.
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
The inet_pton() function converts the standard text representation of the numeric
network address (src) into its numeric network byte-order binary form (dst).
The converted address is stored in network byte order in dst. The buffer pointed to by
dst must be large enough to hold the numeric address:
Family
Numeric address size
AF_INET
4 bytes
AF_INET6
16 bytes
AF_INET addresses
IPv4 addresses must be specified in the standard dotted-decimal form:
ddd.ddd.ddd.ddd
where ddd is a one- to three-digit decimal number between 0 and 255.
June 19, 2012
QNX Neutrino Functions and Macros
889
inet_pton()
© 2012, QNX Software Systems Limited
Many existing implementations of inet_addr() and inet_aton() accept nonstandard
input: octal numbers, hexadecimal numbers, and fewer than four numbers. The
inet_pton() function doesn’t accept these formats.
AF_INET6 addresses
IPv6 addresses must be specified in one of the following standard formats:
• The preferred form is:
x:x:x:x:x:x:x:x
where x is a hexadecimal value for one of the eight 16-bit pieces of the address. For
example:
DEAD:BEEF:7654:3210:FEDC:3210:7654:BA98
417A:200C:800:8:0:0:0:1080
• A :: can be used once per address to represent multiple groups of 16 zero-bits. For
example, the following addresses:
1080:0:0:0:8:800:200C:417A
FF01:0:0:0:0:0:0:43
0:0:0:0:0:0:0:1
0:0:0:0:0:0:0:0
can be represented as:
1080::8:800:200C:417A
FF01::43
::1
::
• A convenient format when dealing with mixed IPv4 and IPv6 environments is:
x:x:x:x:x:x:d.d.d.d
where x is a hexadecimal value for one of the six high-order 16-bit pieces of the
address and d is a decimal value for one of the four low-order 8-bit pieces of the
address (standard AF_INET representation). For example:
0:0:0:0:0:0:13.1.68.3
0:0:0:0:0:FFFF:129.144.52.38
Or, in their compressed forms:
::13.1.68.3
::FFFF:129.144.52.38
Returns:
890
1
Success.
0
The input isn’t a valid address.
-1
An error occurred (errno is set).
QNX Neutrino Functions and Macros
June 19, 2012
inet_pton()
© 2012, QNX Software Systems Limited
Errors:
EAFNOSUPPORT
The af argument isn’t one of the supported networking families.
Examples:
#include
#include
#include
#include
#include
<stdio.h>
<stdlib.h>
<sys/socket.h>
<arpa/inet.h>
<errno.h>
#define INADDR "10.1.0.29"
#define IN6ADDR "DEAD:BEEF:7654:3210:FEDC:3210:7654:BA98"
int
main()
{
struct in_addr inaddr;
struct in6_addr in6addr;
char buf[INET_ADDRSTRLEN], buf6[INET6_ADDRSTRLEN];
int rval;
if ( (rval = inet_pton(AF_INET, INADDR, &inaddr)) == 0) {
printf("Invalid address: %s\n", INADDR);
exit(EXIT_FAILURE);
} else if (rval == -1) {
perror("inet_pton");
exit(EXIT_FAILURE);
}
if (inet_ntop(AF_INET, &inaddr, buf, sizeof(buf)) != NULL)
printf("inet addr: %s\n", buf);
else {
perror("inet_ntop");
exit(EXIT_FAILURE);
}
if ( (rval = inet_pton(AF_INET6, IN6ADDR, &in6addr)) == 0) {
printf("Invalid address: %s\n", IN6ADDR);
exit(EXIT_FAILURE);
} else if (rval == -1) {
perror("inet_pton");
exit(EXIT_FAILURE);
}
if (inet_ntop(AF_INET6, &in6addr, buf6, sizeof(buf6)) != NULL)
printf("inet6 addr: %s\n", buf6);
else {
perror("inet_ntop");
exit(EXIT_FAILURE);
}
return(EXIT_SUCCESS);
}
June 19, 2012
QNX Neutrino Functions and Macros
891
inet_pton()
© 2012, QNX Software Systems Limited
Classification:
POSIX 1003.1
Safety
Cancellation point
No
Interrupt handler
No
Signal handler
Yes
Thread
Yes
See also:
inet_ntop()
Based on RFC 2373
892
QNX Neutrino Functions and Macros
June 19, 2012
INET6
© 2012, QNX Software Systems Limited
Internet protocol version 6 family
Synopsis:
#include <netinet/in.h>
struct sockaddr_in6 {
uint8_t sin6_len;
sa_family_t sin6_family;
in_port_t sin6_port;
uint32_t sin6_flowinfo;
struct in6_addr sin6_addr;
uint32_t sin6_scope_id;
};
Description:
Protocols
The INET6 family consists of the:
• IPv6 network protocol
• Internet Control Message Protocol version 6 (ICMP)
• Transmission Control Protocol (TCP)
• User Datagram Protocol (UDP).
TCP supports the SOCK_STREAM abstraction, while UDP supports the
SOCK_DGRAM abstraction. Note that TCP and UDP are common to INET and
INET6. A raw interface to IPv6 is available by creating an Internet SOCK_RAW
socket. The ICMPv6 message protocol may be accessed from a raw socket.
The INET6 protocol family is an updated version of the INET family. While INET
implements Internet Protocol version 4, INET6 implements Internet Protocol version
6.
Addressing
IPv6 addresses are 16-byte quantities, stored in network standard (big-endian) byte
order. The header file <netinet/in.h> defines this address as a discriminated union.
Sockets bound to the INET6 family use the structure shown above.
You can create sockets with the local address :: (which is equal to IPv6 address
0:0:0:0:0:0:0:0) to cause “wildcard” matching on incoming messages. You can
specify the address in a call to connect() or sendto() as :: to mean the local host. You
can get the :: value by setting the sin6_addr field to 0, or by using the address
contained in the in6addr_any global variable, which is declared in
<netinet6/in6.h>.
The IPv6 specification defines scoped addresses, such as link-local or site-local
addresses. A scoped address is ambiguous to the kernel if it’s specified without a
scope identifier. To manipulate scoped addresses properly in your application, use the
advanced API defined in RFC 2292. A compact description on the advanced API is
June 19, 2012
QNX Neutrino Functions and Macros
893
INET6
© 2012, QNX Software Systems Limited
available in IP6. If you specify scoped addresses without an explicit scope, the socket
manager may return an error.
Scoped addresses are currently experimental, from both a specification and an
implementation point of view.
The KAME implementation supports extended numeric IPv6 address notation for
link-local addresses. For example, you can use fe80::1%de0 to specify “fe80::1
on the de0 interface.” The getaddrinfo() and getnameinfo() functions support this
notation. Some utilities, such as telnet and ftp, can use the notation. With special
programs like ping6, you can disambiguate scoped addresses by specifying the
outgoing interface with extra command-line options.
The socket manager handles scoped addresses in a special manner. In the socket
manager’s routing tables or interface structures, a scoped address’s interface index is
embedded in the address. Therefore, the address contained in some of the socket
manager structures isn’t the same as on the wire. The embedded index becomes
visible when using the PF_ROUTE socket or the sysctl() function. You shouldn’t use
the embedded form.
Interaction between IPv4/v6 sockets
The behavior of the AF_INET6 TCP/UDP socket is documented in the RFC 2553
specification, which states:
• A specific bind on an AF_INET6 socket (bind() with an address specified) should
accept IPv6 traffic to that address only.
• If you perform a wildcard bind on an AF_INET6 socket (bind() to the IPv6 address
::), and there isn’t a wildcard-bound AF_INET socket on that TCP/UDP port,
then the IPv6 traffic as well as the IPv4 traffic should be routed to that AF_INET6
socket. IPv4 traffic should be seen by the application as if it came from an IPv6
address such as ::ffff:10.1.1.1. This is called an IPv4 mapped address.
• If there are both wildcard-bound AF_INET sockets and wildcard-bound
AF_INET6 sockets on one TCP/UDP port, they should operate independently:
IPv4 traffic should be routed to the AF_INET socket, and IPv6 should be routed to
the AF_INET6 socket.
However, the RFC 2553 specification doesn’t define the constraint between the
binding order, nor how the IPv4 TCP/UDP port numbers and the IPv6 TCP/UDP port
numbers relate each other (whether they must be integrated or separated). The
behavior is very different from implementation to implementation. It is unwise to rely
too much on the behavior of the AF_INET6 wildcard-bound socket. Instead, connect
to two sockets, one for AF_INET and another for AF_INET6, when you want to
accept both IPv4 and IPv6 traffic.
894
QNX Neutrino Functions and Macros
June 19, 2012
INET6
© 2012, QNX Software Systems Limited
!
CAUTION: Use caution when handling connections from IPv4 mapped addresses
with AF_INET6 sockets—if the target node routes IPv4 traffic to AF_INET6 sockets,
malicious parties can bypass security.
Because of the security hole, by default, NetBSD doesn’t route IPv4 traffic to
AF_INET6 sockets. If you want to accept both IPv4 and IPv6 traffic, use two sockets.
IPv4 traffic may be routed with multiple per-socket/per-node configurations, but, it
isn’t recommended. See IP6 for details.
The IPv6 support is subject to change as the Internet protocols develop. Don’t depend
on details of the current implementation, but rather the services exported. Try to
implement version-independent code as much as possible, because you’ll need to
support both INET and INET6.
See also:
ICMP, ICMP6, IP6, IP, TCP, UDP protocols
bind(), connect(), getaddrinfo(), ioctl(), sendto(), socket(), sysctl()
ftp, ping6, telnet in the Utilities Reference
Based on RFC 2553, RFC 2292
June 19, 2012
QNX Neutrino Functions and Macros
895
inet6_option_alloc()
© 2012, QNX Software Systems Limited
Append IPv6 hop-by-hop or destination options into ancillary data object
Synopsis:
#include <netinet/in.h>
u_int8_t * inet6_option_alloc(struct cmsghdr *cmsg,
int datalen,
int multx,
int plusy);
Arguments:
cmsg
A pointer to the cmsghdr structure that must have been initialized by
inet6_option_init().
datalen
The length of the option, in bytes. This value is required as an argument to
allow the function to determine if padding should be appended at the end
of the option, argument since the option data length must already be stored
by the caller (the inet6_option_append() function doesn’t need a data
length).
multx
The value x in the alignment term xn + y. It must have a value of 1, 2, 4,
or 8.
plusy
Value y in the alignment term xn + y. It must have a value between 0 and
7, inclusive.
Library:
libsocket
Use the -l socket option to qcc to link against this library.
Description:
This inet6_option_alloc() function appends a hop-by-hop option or a destination
option into an ancillary data object that has been initialized by inet6_option_init().
The difference between this function and inet6_option_append() is that the latter
copies the contents of the previously built option into the ancillary data object. This
function returns a pointer to the space in the data object where the option’s
type-length-value or TLV must then be built by the caller.
Returns:
A pointer to the 8-bit option type field that starts the option, or NULL if an error has
occurred.
896
QNX Neutrino Functions and Macros
June 19, 2012
inet6_option_alloc()
© 2012, QNX Software Systems Limited
Classification:
RFC 2292
Safety
Cancellation point
No
Interrupt handler
No
Signal handler
Yes
Thread
Yes
See also:
inet6_option_append(), inet6_option_find(), inet6_option_init(),
inet6_option_next(), inet6_option_space()
Based on:
• W. Stevens and M. Thomas, Advanced Sockets API for IPv6, RFC 2292, February
1998. Contains examples.
• S. Deering and R. Hinden, Internet Protocol, Version 6 (IPv6) Specification, RFC
2460, December 1998.
June 19, 2012
QNX Neutrino Functions and Macros
897
inet6_option_append()
© 2012, QNX Software Systems Limited
Append an IPv6 hop-by-hop or destination option to an ancillary data object
Synopsis:
#include <netinet/in.h>
int inet6_option_append(struct cmsghdr *cmsg,
const u_int8_t *typep,
int multx,
int plusy);
Arguments:
cmsg
A pointer to the cmsghdr structure that must have been initialized by
inet6_option_init().
typep
A pointer to the 8-bit option type. It’s assumed that this field is immediately
followed by the 8-bit option data length field, which is then followed by the
option data. You must initialize these three fields (the type-length-value, or
TLV) before calling this function.
The option type must have a value from 2 to 255, inclusive. (0 and 1 are
reserved for the Pad1 and PadN options, respectively.)
The option data length must be between 0 and 255, inclusive, and is the
length of the option data that follows.
multx
The value x in the alignment term xn + y. It must have a value of 1, 2, 4, or
8.
plusy
The value y in the alignment term xn + y. It must have a value between 0
and 7, inclusive.
Library:
libsocket
Use the -l socket option to qcc to link against this library.
Description:
This inet6_option_append() function appends a hop-by-hop option or a destination
option to an ancillary data object that has been initialized by inet6_option_init().
Returns:
898
0
Success.
-1
An error has occurred.
QNX Neutrino Functions and Macros
June 19, 2012
inet6_option_append()
© 2012, QNX Software Systems Limited
Classification:
RFC 2292
Safety
Cancellation point
No
Interrupt handler
No
Signal handler
Yes
Thread
Yes
See also:
inet6_option_alloc(), inet6_option_find(), inet6_option_init(), inet6_option_next(),
inet6_option_space()
W. Stevens and M. Thomas, Advanced Sockets API for IPv6, RFC 2292, February
1998. Contains examples.
S. Deering and R. Hinden, Internet Protocol, Version 6 (IPv6) Specification, RFC
2460, December 1998.
June 19, 2012
QNX Neutrino Functions and Macros
899
inet6_option_find()
© 2012, QNX Software Systems Limited
Search for IPv6 hop-by-hop and destination options
Synopsis:
#include <netinet/in.h>
int inet6_option_find(const struct cmsghdr *cmsg,
u_int8_t **tptrp,
int type);
Arguments:
cmsg
A pointer to the cmsghdr structure that must have been initialized by
inet6_option_init().
type
The type of option to search for. Either IPV6_HOPOPTS or IPV6_DSTOPTS.
This type is stored in the cmsg_type member of the cmsghdr structure
pointed to by *cmsgp.
tptrp
A pointer to a pointer to an 8-bit byte.
Library:
libsocket
Use the -l socket option to qcc to link against this library.
Description:
This inet6_option_find() function is similar to inet6_option_next(). It however, lets
the caller specify the option type to be searched for, instead of always returning the
next option in the ancillary data object. The cmsg is a pointer to the cmsghdr
structure of which cmsg_level equals IPPROTO_IPV6 and cmsg_type equals either
IPV6_HOPOPTS or IPV6_DSTOPTS.
The tptrp is a pointer to a pointer to an 8-bit byte that the function uses to remember
its place in the ancillary data object each time the function is called.
The first time you call this function for a given ancillary data object, you must set
*tptrp must be set to NULL. This function starts searching for an option of the
specified type beginning after the value of *tptrp pointer.
Returns:
0 with *tptrp pointing to the 8-bit option
The option was found.
-1 with *tptrp pointing to NULL
The option wasn’t found.
-1 with *tptrp pointing to non-NULL
An error has occurred.
900
QNX Neutrino Functions and Macros
June 19, 2012
inet6_option_find()
© 2012, QNX Software Systems Limited
Classification:
RFC 2292
Safety
Cancellation point
No
Interrupt handler
No
Signal handler
Yes
Thread
Yes
See also:
inet6_option_alloc(), inet6_option_append(), inet6_option_init(),
inet6_option_next(), inet6_option_space()
Based on:
• W. Stevens and M. Thomas, Advanced Sockets API for IPv6, RFC 2292, February
1998. Contains examples.
• S. Deering and R. Hinden, Internet Protocol, Version 6 (IPv6) Specification, RFC
2460, December 1998.
June 19, 2012
QNX Neutrino Functions and Macros
901
inet6_option_init()
© 2012, QNX Software Systems Limited
Initialize an ancillary data object that contains IPv6 hop-by-hop and destination options
Synopsis:
#include <netinet/in.h>
int inet6_option_init(void *bp,
struct cmsghdr **cmsgp,
int type);
Arguments:
bp
A pointer to previously allocated space that contains the ancillary data
object. It must be large enough to contain all the individual options to be
added by later calls to inet6_option_append() and inet6_option_alloc().
cmsgp
A pointer to a cmsghdr structure. The *cmsgp variable is initialized by
this function to point to the cmsghdr structure that this function constructs
in the buffer pointed to by bp.
type
The type of option which must be either IPV6_HOPOPTS or
IPV6_DSTOPTS. This type is stored in the cmsg_type member of the
cmsghdr structure pointed to by *cmsgp.
Library:
libsocket
Use the -l socket option to qcc to link against this library.
Description:
Call inet6_option_init() function once per ancillary data object that contains either
hop-by-hop or destination options.
Returns:
0
Success.
-1
An error has occurred.
Classification:
RFC 2292
Safety
Cancellation point
No
Interrupt handler
No
continued. . .
902
QNX Neutrino Functions and Macros
June 19, 2012
inet6_option_init()
© 2012, QNX Software Systems Limited
Safety
Signal handler
Yes
Thread
Yes
See also:
inet6_option_alloc(), inet6_option_append(), inet6_option_find(),
inet6_option_next(), inet6_option_space()
Based on:
• W. Stevens and M. Thomas, Advanced Sockets API for IPv6, RFC 2292, February
1998. Contains examples.
• S. Deering and R. Hinden, Internet Protocol, Version 6 (IPv6) Specification, RFC
2460, December 1998.
June 19, 2012
QNX Neutrino Functions and Macros
903
inet6_option_next()
© 2012, QNX Software Systems Limited
Find the next IPv6 hop-by-hop or destination option
Synopsis:
#include <netinet/in.h>
int inet6_option_next(const struct cmsghdr *cmsg,
u_int8_t **tptrp);
Arguments:
cmsg
A pointer to the cmsghdr structure that must have been initialized by
inet6_option_init().
tptrp
A pointer to a pointer to an 8-bit byte.
Library:
libsocket
Use the -l socket option to qcc to link against this library.
Description:
This inet6_option_next() function finds the next hop-by-hop option or destination
option in an ancillary data object. If another option remains to be processed, the return
value of the function is 0 and *tptrp points to the 8-bit option type field the option data.
The cmsg variable is a pointer to cmsghdr structure for which cmsg_level equals
IPPROTO_IPV6 and cmsg_type equals either IPV6_HOPOPTS or IPV6_DSTOPTS.
The tptrp is a pointer to a pointer to an 8-bit byte and *tptrp is used by the function to
remember its place in the ancillary data object each time the function is called. The
first time you call this function for a given ancillary data object, you must set *tptrp to
NULL.
Each time this function returns success, *tptrp points to the 8-bit option type field for
the next option to be processed.
Returns:
0
The option is located and the *tptrp points to the 8-bit option type field.
-1 with *tptrp pointing to NULL
No more options to process.
-1 with *tptrp pointing to non-NULL
An error has occurred.
904
QNX Neutrino Functions and Macros
June 19, 2012
inet6_option_next()
© 2012, QNX Software Systems Limited
Classification:
RFC 2292
Safety
Cancellation point
No
Interrupt handler
No
Signal handler
Yes
Thread
Yes
See also:
inet6_option_alloc(), inet6_option_append(), inet6_option_find(),
inet6_option_init(), inet6_option_space()
Based on:
• W. Stevens and M. Thomas, Advanced Sockets API for IPv6, RFC 2292, February
1998. Contains examples.
• S. Deering and R. Hinden, Internet Protocol, Version 6 (IPv6) Specification, RFC
2460, December 1998.
June 19, 2012
QNX Neutrino Functions and Macros
905
inet6_option_space()
© 2012, QNX Software Systems Limited
Determine how much space an IPv6 hop-by-hop or destination option requires
Synopsis:
#include <netinet/in.h>
int inet6_option_space(int nbytes);
Arguments:
nbytes
The size of the structure that defines the option. It includes any padding
bytes at the beginning (the value y in the alignment term xn + y, the type
byte), the length byte, and the option data.
Library:
libsocket
Use the -l socket option to qcc to link against this library.
Description:
This inet6_option_space() function returns the number of bytes required to hold an
option when it’s stored as ancillary data, including the cmsghdr structure at the
beginning, and any padding at the end (to make its size a multiple of 8 bytes).
When multiple options are stored in a single ancillary data object, this function
overestimates the amount of space required by the size of N-1 cmsghdr structures,
where N is the number of options to be stored in the object. This is of little
consequence, since it’s assumed that most hop-by-hop option and destination option
headers carry only one option (see Appendix B of RFC 2460).
Classification:
RFC 2292
Safety
906
Cancellation point
No
Interrupt handler
No
Signal handler
Yes
Thread
Yes
QNX Neutrino Functions and Macros
June 19, 2012
© 2012, QNX Software Systems Limited
inet6_option_space()
See also:
inet6_option_alloc(), inet6_option_append() inet6_option_find(),
inet6_option_init(), inet6_option_next()
Based on:
• W. Stevens and M. Thomas, Advanced Sockets API for IPv6, RFC 2292, February
1998. Contains examples.
• S. Deering and R. Hinden, Internet Protocol, Version 6 (IPv6) Specification, RFC
2460, December 1998.
June 19, 2012
QNX Neutrino Functions and Macros
907
inet6_rthdr_add()
© 2012, QNX Software Systems Limited
Add an address to an IPv6 routing header
Synopsis:
#include <netinet/in.h>
int inet6_rthdr_add(struct cmsghdr *cmsg,
const struct in6_addr *addr,
unsigned int flags);
Arguments:
addr
A pointer to the IPv6 address structure to add to the routing header.
flags
Routing header flags. For an IPv6 Type 0 routing header, it’s either
IPV6_RTHDR_LOOSE or IPV6_RTHDR_STRICT.
cmsg
A pointer to Ancillary data containing the routing header.
Library:
libsocket
Use the -l socket option to qcc to link against this library.
Description:
This function adds the address pointed to by addr to the end of the Routing header
being constructed and sets the type of this hop to the value of flags.
If successful, the cmsg_len member of the cmsghdr structure is updated to account
for the new address in the routing header.
Returns:
0
Success.
-1
An error has occurred.
Classification:
RFC 2292
Safety
908
Cancellation point
No
Interrupt handler
No
Signal handler
Yes
Thread
Yes
QNX Neutrino Functions and Macros
June 19, 2012
© 2012, QNX Software Systems Limited
inet6_rthdr_add()
See also:
inet6_rthdr_getaddr(), inet6_rthdr_getflags(), inet6_rthdr_init(),
inet6_rthdr_lasthop(), inet6_rthdr_reverse(), inet6_rthdr_segments(),
inet6_rthdr_space()
Based on:
• W. Stevens and M. Thomas, Advanced Sockets API for IPv6, RFC 2292, February
1998. Contains good examples.
• S. Deering and R. Hinden, Internet Protocol, Version 6 (IPv6) Specification, RFC
2460, December 1998.
June 19, 2012
QNX Neutrino Functions and Macros
909
inet6_rthdr_getaddr()
© 2012, QNX Software Systems Limited
Get a pointer to an IPv6 address in the routing header
Synopsis:
#include <netinet/in.h>
struct in6_addr * inet6_rthdr_getaddr(
struct cmsghdr *cmsg,
int index);
Arguments:
cmsg
A pointer to the Ancillary data containing the routing header.
index
A value between 0 and the number returned by inet6_rthdr_segments().
Library:
libsocket
Use the -l socket option to qcc to link against this library.
Description:
This function returns a pointer to the IPv6 address specified by index in the routing
header described by cmsg. The index must have a value between 1 and the number
returned by inet6_rthdr_segments(). You should first call inet6_rthdr_segments() to
obtain the number of segments in the Routing header.
Returns:
A pointer to the IPv6 address, or NULL if an error occured.
Classification:
RFC 2292
Safety
Cancellation point
No
Interrupt handler
No
Signal handler
Yes
Thread
Yes
See also:
inet6_rthdr_add(), inet6_rthdr_getflags(), inet6_rthdr_init(), inet6_rthdr_lasthop(),
inet6_rthdr_reverse(), inet6_rthdr_segments(), inet6_rthdr_space()
910
QNX Neutrino Functions and Macros
June 19, 2012
© 2012, QNX Software Systems Limited
inet6_rthdr_getaddr()
W. Stevens and M. Thomas, Advanced Sockets API for IPv6, RFC 2292, February
1998. Contains good examples.
S. Deering and R. Hinden, Internet Protocol, Version 6 (IPv6) Specification, RFC
2460, December 1998.
June 19, 2012
QNX Neutrino Functions and Macros
911
inet6_rthdr_getflags()
© 2012, QNX Software Systems Limited
Get the flags for a segment in an IPv6 routing header
Synopsis:
#include <netinet/in.h>
int inet6_rthdr_getflags(const struct cmsghdr *cmsg,
int index);
Arguments:
cmsg
A pointer to the Ancillary data containing the routing header.
index
A value between 0 and the number returned by inet6_rthdr_segments().
Library:
libsocket
Use the -l socket option to qcc to link against this library.
Description:
This function returns the flags for the segment specified by index in the routing header
described by cmsg. The index must have a value between 0 and the number returned
by inet6_rthdr_segments().
Addresses are indexed starting at 1, and flags starting at 0. They’re consistent with the
terminology and figures in RFC2460.
Returns:
• IPV6_RTHDR_LOOSE or IPV6_RTHDR_STRICT for an IPv6 Type 0 routing header
• -1 on error.
Classification:
RFC 2292
Safety
912
Cancellation point
No
Interrupt handler
No
Signal handler
Yes
Thread
Yes
QNX Neutrino Functions and Macros
June 19, 2012
© 2012, QNX Software Systems Limited
inet6_rthdr_getflags()
See also:
inet6_rthdr_add(), inet6_rthdr_getaddr(), inet6_rthdr_init(), inet6_rthdr_lasthop(),
inet6_rthdr_reverse(), inet6_rthdr_segments(), inet6_rthdr_space()
Based on:
• W. Stevens and M. Thomas, Advanced Sockets API for IPv6, RFC 2292, February
1998. Contains good examples.
• S. Deering and R. Hinden, Internet Protocol, Version 6 (IPv6) Specification, RFC
2460, December 1998.
June 19, 2012
QNX Neutrino Functions and Macros
913
inet6_rthdr_init()
© 2012, QNX Software Systems Limited
Initialize an IPv6 routing header
Synopsis:
#include <netinet/in.h>
struct cmsghdr * inet6_rthdr_init(void *bp,
int type);
Arguments:
bp
A pointer to the buffer where the function can build a cmsghdr structure
followed by a Routing header of the specified type.
type
The type of IPv6 Routing header (e.g. Type 0 as defined in
<netinet/in.h>).
Library:
libsocket
Use the -l socket option to qcc to link against this library.
Description:
This function initializes the buffer pointed to by bp to contain a cmsghdr structure
followed by a Routing header of the specified type. The cmsg_len member of the
cmsghdr structure is initialized to the size of the structure plus the amount of space
required by the Routing header.
The cmsg_level and cmsg_type members are also initialized as required.
You must allocate the buffer before calling this function. To determine the size of the
buffer, call inet6_rthdr_space().
Returns:
A pointer to the cmsghdr structure, which you’ll pass to other functions (and used as
the first argument to list functions) or NULL if an error occured.
Classification:
RFC 2292
Safety
Cancellation point
No
Interrupt handler
No
Signal handler
Yes
continued. . .
914
QNX Neutrino Functions and Macros
June 19, 2012
inet6_rthdr_init()
© 2012, QNX Software Systems Limited
Safety
Thread
Yes
See also:
inet6_rthdr_add(), inet6_rthdr_getaddr(), inet6_rthdr_getflags(),
inet6_rthdr_lasthop(), inet6_rthdr_reverse(), inet6_rthdr_segments(),
inet6_rthdr_space()
Based on:
• W. Stevens and M. Thomas, Advanced Sockets API for IPv6, RFC 2292, February
1998. Contains good examples.
• S. Deering and R. Hinden, Internet Protocol, Version 6 (IPv6) Specification, RFC
2460, December 1998.
June 19, 2012
QNX Neutrino Functions and Macros
915
inet6_rthdr_lasthop()
© 2012, QNX Software Systems Limited
Specify the Strict/Loose flag for the final hop of an IPv6 routing header
Synopsis:
#include <netinet/in.h>
int inet6_rthdr_lasthop(struct cmsghdr *cmsg,
unsigned int flags);
Arguments:
cmsg
Ancillary data containing routing header.
flags
Routing header flags. It’s either IPV6_RTHDR_LOOSE or
IPV6_RTHDR_STRICT for an IPv6 Type 0 routing header.
Library:
libsocket
Use the -l socket option to qcc to link against this library.
Description:
This function specifies the Strict/Loose flag for the final hop of a Routing header.
A routing header specifying N intermediate nodes requires N+1 Strict/Loose flags.
This requires N calls to inet6_rthdr_add() followed by one call to
inet6_rthdr_lasthop().
Returns:
0
Success.
-1
An error has occurred.
Classification:
RFC 2292
Safety
916
Cancellation point
No
Interrupt handler
No
Signal handler
Yes
Thread
Yes
QNX Neutrino Functions and Macros
June 19, 2012
© 2012, QNX Software Systems Limited
inet6_rthdr_lasthop()
See also:
inet6_rthdr_add(), inet6_rthdr_getaddr(), inet6_rthdr_getflags(), inet6_rthdr_init(),
inet6_rthdr_reverse(), inet6_rthdr_segments(), inet6_rthdr_space()
Based on:
• W. Stevens and M. Thomas, Advanced Sockets API for IPv6, RFC 2292, February
1998. Contains good examples.
• S. Deering and R. Hinden, Internet Protocol, Version 6 (IPv6) Specification, RFC
2460, December 1998.
June 19, 2012
QNX Neutrino Functions and Macros
917
inet6_rthdr_reverse()
© 2012, QNX Software Systems Limited
Reverse the list of addresses in an IPv6 router header
Synopsis:
#include <netinet/in.h>
int inet6_rthdr_reverse(const struct cmsghdr *in,
struct cmsghdr *out);
Arguments:
in
Ancillary data containing Routing header.
out
Ancillary data containing Routing header.
Library:
libsocket
Use the -l socket option to qcc to link against this library.
Description:
The inet6_rthdr_reverse() has not been implemented yet.
This function takes a routing header that has been received as ancillary data (pointed
to by the first argument, in) and writes a new routing header. The routing header sends
datagrams along the reverse of that route. Both arguments are allowed to point to the
same buffer (that is, the reversal can occur in place).
Returns:
0
Success.
-1
An error has occurred.
Classification:
RFC 2292
Safety
918
Cancellation point
No
Interrupt handler
No
Signal handler
Yes
Thread
Yes
QNX Neutrino Functions and Macros
June 19, 2012
© 2012, QNX Software Systems Limited
inet6_rthdr_reverse()
See also:
inet6_rthdr_add(), inet6_rthdr_getaddr(), inet6_rthdr_getflags(), inet6_rthdr_init(),
inet6_rthdr_lasthop(), inet6_rthdr_segments(), inet6_rthdr_space()
Based on:
• W. Stevens and M. Thomas, Advanced Sockets API for IPv6, RFC 2292, February
1998. Contains good examples.
• S. Deering and R. Hinden, Internet Protocol, Version 6 (IPv6) Specification, RFC
2460, December 1998.
June 19, 2012
QNX Neutrino Functions and Macros
919
inet6_rthdr_segments()
© 2012, QNX Software Systems Limited
Count the segments in an IPv6 routing header
Synopsis:
#include <netinet/in.h>
int inet6_rthdr_segments(const struct cmsghdr *cmsg);
Arguments:
cmsg
A pointer to Ancillary data containing a routing header.
Library:
libsocket
Use the -l socket option to qcc to link against this library.
Description:
inet6_rthdr_segments()
This function returns the number of segments (addresses) contained in the Routing
header described by cmsg.
Returns:
1 to 23
Success.
-1
An error has occurred.
Classification:
RFC 2292
Safety
Cancellation point
No
Interrupt handler
No
Signal handler
Yes
Thread
Yes
See also:
inet6_rthdr_add(), inet6_rthdr_getaddr(), inet6_rthdr_getflags(), inet6_rthdr_init(),
inet6_rthdr_lasthop(), inet6_rthdr_reverse(), inet6_rthdr_space()
920
QNX Neutrino Functions and Macros
June 19, 2012
© 2012, QNX Software Systems Limited
inet6_rthdr_segments()
Based on:
• W. Stevens and M. Thomas, Advanced Sockets API for IPv6, RFC 2292, February
1998. Contains good examples.
• S. Deering and R. Hinden, Internet Protocol, Version 6 (IPv6) Specification, RFC
2460, December 1998.
June 19, 2012
QNX Neutrino Functions and Macros
921
inet6_rthdr_space()
© 2012, QNX Software Systems Limited
Determine the space required by an IPv6 routing header
Synopsis:
#include <netinet/in.h>
size_t inet6_rthdr_space(int type,
int segments);
Arguments:
type
The type of IPv6 Routing header (e.g. Type 0 as defined in
<netinet/in.h>).
segments
The number of segments (addresses) in the Routing header.
Library:
libsocket
Use the -l socket option to qcc to link against this library.
Description:
This function returns the number of bytes required to hold a Routing header of the
specified type containing a specified number of segments (addresses). For an IPv6
Type 0 Routing header, the number of segments must be between 1 and 23, inclusive.
The return value includes the size of the cmsghdr structure that precedes the Routing
header, and any required padding.
This function returns the size but doesn’t allocate the space required for the ancillary
data. This allows an application to allocate a larger buffer, if other ancillary data
objects are desired. All the ancillary data objects must be specified to sendmsg() as a
single msg_control buffer in the msghdr structure msg_control member.
Returns:
0, for either of the two situations: the type of the routing header isn’t supported by this
implementation or the number of segments is invalid for this type of routing header.
Classification:
RFC 2292
Safety
Cancellation point
No
Interrupt handler
No
continued. . .
922
QNX Neutrino Functions and Macros
June 19, 2012
inet6_rthdr_space()
© 2012, QNX Software Systems Limited
Safety
Signal handler
Yes
Thread
Yes
See also:
inet6_rthdr_add() inet6_rthdr_getaddr(), inet6_rthdr_getflags(), inet6_rthdr_init(),
inet6_rthdr_lasthop(), inet6_rthdr_reverse(), inet6_rthdr_segments(),
inet6_rthdr_space()
Based on:
• W. Stevens and M. Thomas, Advanced Sockets API for IPv6, RFC 2292, February
1998. Contains good examples.
• S. Deering and R. Hinden, Internet Protocol, Version 6 (IPv6) Specification, RFC
2460, December 1998.
June 19, 2012
QNX Neutrino Functions and Macros
923
initgroups()
© 2012, QNX Software Systems Limited
Initialize the supplementary group access list
Synopsis:
#include <grp.h>
#include <sys/types.h>
int initgroups( const char * name,
gid_t basegid );
Arguments:
name
The name of the user whose group membership you want to use as the
supplementary group access list.
basegid
A group ID that you want to include in the group access list.
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
The initgroups() function reads the group membership for the user specified by name
from the group database, and then initializes the supplementary group access list of the
calling process (see getgrnam() and getgroups()).
If the number of groups in the supplementary access list exceeds NGROUPS_MAX, the
extra groups are ignored.
Returns:
0
Success.
-1
An error occurred (errno is set).
Errors:
EPERM
The caller isn’t root.
Files:
/etc/group
The group database.
Classification:
Unix
924
QNX Neutrino Functions and Macros
June 19, 2012
initgroups()
© 2012, QNX Software Systems Limited
Safety
Cancellation point
No
Interrupt handler
No
Signal handler
No
Thread
No
Caveats:
If initgroups() fails, it doesn’t change the supplementary group access list.
The getgrouplist() function called by initgroups() is based on getgrent(). If the calling
process uses getgrent(), the in-memory group structure is overwritten in the call to
initgroups().
See also:
getgroups(), getgrnam()
June 19, 2012
QNX Neutrino Functions and Macros
925
initstate()
© 2012, QNX Software Systems Limited
Initialize a pseudo-random number generator
Synopsis:
#include <stdlib.h>
char* initstate( unsigned int seed,
char* state,
size_t size );
Arguments:
seed
A starting point for the random-number sequence. This lets you restart the
sequence at the same point.
state
The state array that you want to initialize.
size
The size, in bytes, of the state array; see below.
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
This function is in libc.a, but not in libc.so (in order to save space).
Description:
The initstate() initializes the given state array for future use when generating
pseudo-random numbers.
This function uses the size argument to determine what type of random-number
generator to use; the larger the state array, the more random the numbers. Values for
the amount of state information are 8, 32, 64, 128, and 256 bytes. Other values greater
than 8 bytes are rounded down to the nearest one of these values. For values smaller
than 8, random() uses a simple linear congruential random number generator.
Use this function in conjunction with the following:
random()
Generate a pseudo-random number using a default state.
setstate()
Specify the state of the pseudo-random number generator.
srandom()
Set the seed used by the pseudo-random number generator.
If you haven’t called initstate(), random() behaves as though you had called initstate()
with a seed of 1 and a size of 128.
After initialization, you can restart a state array at a different point in one of these
ways:
926
QNX Neutrino Functions and Macros
June 19, 2012
initstate()
© 2012, QNX Software Systems Limited
• Call initstate() with the desired seed, state array, and size of the array.
• Call setstate() with the desired state, then call srandom() with the desired seed. The
advantage of using both of these functions is that the size of the state array doesn’t
have to be saved once it’s initialized.
Returns:
A pointer to the previous state array, or NULL if an error occurred.
Examples:
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
static char state1[32];
int main() {
initstate( time(NULL), state1, sizeof(state1));
setstate(state1);
printf("%d0\n", random());
return EXIT_SUCCESS;
}
Classification:
POSIX 1003.1 XSI
Safety
Cancellation point
Yes
Interrupt handler
No
Signal handler
No
Thread
No
See also:
drand48(), rand(), random(), setstate(), srand(), srandom()
June 19, 2012
QNX Neutrino Functions and Macros
927
input_line()
© 2012, QNX Software Systems Limited
Get a string of characters from a file
Synopsis:
#include <stdio.h>
char* input_line( FILE* fp,
char* buf ,
int bufsize );
extern int _input_line_max;
Arguments:
fp
The file that you want to read from.
buf
A pointer to a buffer where the function can store the string that it reads.
bufsize
The size of the buffer, in bytes.
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
This function is in libc.a, but not in libc.so (in order to save space).
Description:
The input_line() function gets a string of characters from the file designated by fp and
stores them in the array pointed to by buf . The input_line() function stops reading
characters when:
• end-of-file is reached
• a newline character is read
• bufsize - 1 characters have been read.
In addition, the input_line() function buffers the last _input_line_max lines internally.
The _input_line_max variable is defined in <stdio.h>. You can set it before calling
input_line() for the first time; its default value is 20. While the line is being read, the
KEY_UP and KEY_DOWN keys can be used to move to the previous and next line
respectively in a circular buffer of previously read lines. The newline character (\n) is
replaced with the null character on input.
Returns:
A pointer to the input line. On end-of-file or on encountering an error reading from fp,
NULL is returned and errno is set.
928
QNX Neutrino Functions and Macros
June 19, 2012
input_line()
© 2012, QNX Software Systems Limited
Examples:
#include <stdlib.h>
#include <stdio.h>
#define SIZ 256
int _input_line_max;
int main( void )
{
FILE
*fp;
char
*p,
buf[SIZ];
fp = stdin;
_input_line_max = 25;
/* Or any stream */
/* set before 1st call */
while( ( p = input_line( fp, buf, SIZ ) ) != NULL ) {
printf( "%s\n", buf );
fflush( stdout );
}
return EXIT_SUCCESS;
}
Classification:
QNX 4
Safety
June 19, 2012
Cancellation point
Yes
Interrupt handler
No
Signal handler
No
Thread
No
QNX Neutrino Functions and Macros
929
insque()
© 2012, QNX Software Systems Limited
Insert an element into a doubly linked queue
Synopsis:
#include <search.h>
void insque( void *elem,
void *pred);
Arguments:
elem
A pointer to the element you want to insert.
pred
A pointer to the previous element in the list, or NULL if you want to initialize
the head of the list.
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
This function is in libc.a, but not in libc.so (in order to save space).
Description:
The insque() function inserts the element pointed to by elem into a doubly linked
queue immediately after the element pointed to by pred. The queue can be either
circular or linear.
The first two members of the elements must be pointers to the same type of structure;
the names of the members don’t matter. The first member of the structure is a forward
pointer to the next element in the queue, and the second is a backward pointer to the
previous element. The application can define any additional members in the structure.
If the queue is linear, the queue is terminated with NULL pointers.
If the queue is to be used as a linear list, invoking insque( &element, NULL),
where element is the initial element of the queue, initializes the forward and backward
pointers of the element to NULL.
If you intend to use the queue as a circular list, initialize the forward pointer and the
backward pointer of the initial element of the queue to the element’s own address.
You can use remque() to remove elements from the queue.
Classification:
POSIX 1003.1 XSI
930
QNX Neutrino Functions and Macros
June 19, 2012
insque()
© 2012, QNX Software Systems Limited
Safety
Cancellation point
No
Interrupt handler
Yes
Signal handler
Yes
Thread
Yes
See also:
remque()
June 19, 2012
QNX Neutrino Functions and Macros
931
InterruptAttach(), InterruptAttach_r()
© 2012, QNX Software Systems Limited
Attach an interrupt handler to an interrupt source
Synopsis:
#include <sys/neutrino.h>
int InterruptAttach( int intr,
const struct sigevent * (* handler)(void *, int),
const void * area,
int size,
unsigned flags );
int InterruptAttach_r( int intr,
const struct sigevent * (* handler)(void *, int),
const void * area,
int size,
unsigned flags );
Arguments:
intr
The interrupt that you want to attach a handler to; see “Interrupt vector
numbers,” below.
handler
A pointer to the handler function; see “Interrupt handler function,” below.
area
A pointer to a communications area in your process, or NULL if you don’t
want a communications area.
size
The size of the communications area; this should be 0 if area is NULL.
InterruptAttach() currently ignores this argument.
flags
Flags that specify how you want to attach the interrupt handler. For more
information, see “Flags,” below.
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
The InterruptAttach() and InterruptAttach_r() kernel calls attach the interrupt function
handler to the hardware interrupt specified by intr. They automatically enable (i.e.,
unmask) the interrupt level.
These functions are identical except in the way they indicate errors. See the Returns
section for details.
Before calling either of these functions, the thread must request I/O privileges by
calling:
ThreadCtl( _NTO_TCTL_IO, 0 );
If the thread doesn’t do this, the attachment fails with an error code of EPERM.
On a multicore system, the interrupt handler runs on the CPU that takes the interrupt.
932
QNX Neutrino Functions and Macros
June 19, 2012
InterruptAttach(), InterruptAttach_r()
© 2012, QNX Software Systems Limited
Interrupt vector numbers
The interrupt values for intr are logical interrupt vector numbers grouped into related
“interrupt classes” that generally correspond to a particular interrupt line on the CPU.
The following interrupt classes are present on all QNX Neutrino systems:
_NTO_INTR_CLASS_EXTERNAL
Normal external interrupts (such as the ones generated by the INTR pin on x86
CPUs).
_NTO_INTR_CLASS_SYNTHETIC
Synthetic, kernel-generated interrupts.
_NTO_INTR_SPARE is usually the only _NTO_INTR_CLASS_SYNTHETIC interrupt
you’ll use; _NTO_INTR_SPARE is guaranteed not to match any valid logical interrupt
vector number.
There can be additional interrupt classes defined for specific CPUs or embedded
systems. For the interrupt assignments for specific boards, see the sample build files in
${QNX_TARGET}/${PROCESSOR}/boot/build.
Interrupts and startup code
The mapping of logical interrupt vector numbers is completely dependent on the
implementer of the startup code.
Device drivers must:
• Let the user specify an interrupt number on the command line; don’t use a
hard-coded value. Eventually, the configuration manager will provide interrupt
numbers for the device drivers.
• Store interrupt numbers in an unsigned int variable; don’t assume an interrupt
number fits into a byte.
Typical x86 Interrupt vector numbers
The following list contains typical interrupt assignments for the 16 hardware interrupts
on an x86-based PC using startup-bios:
Interrupt intr
Description
0
A clock that runs at the resolution set by ClockPeriod()
1
Keyboard
2
Slave 8259 — you can’t attach to this interrupt.
3
Com2
continued. . .
June 19, 2012
QNX Neutrino Functions and Macros
933
InterruptAttach(), InterruptAttach_r()
Interrupt intr
Description
4
Com1
5
Net card / sound card / other
6
Floppy
7
Parallel printer / sound card / other
© 2012, QNX Software Systems Limited
8
9
Remapped interrupt 2
10
11
12
13
Co-processor
14
Primary disk controller
15
Secondary disk controller
The interrupt assignments are different for other boards.
Interrupt handler function
The function to call is specified by the handler argument. This function runs in the
environment of your process, and the area and size arguments define a
communications area in your process. This typically is a structure containing buffers
and information needed by the handler and the process when it runs.
The area argument can be NULL to indicate no communications area. If area is NULL,
size should be 0.
The handler function’s prototype is:
const struct sigevent* handler( void* area, int id );
Where area is a pointer to the area specified by the call to InterruptAttach(), and id is
the ID returned by InterruptAttach().
Follow the following guidelines when writing your handler:
• A temporary interrupt stack of limited depth is provided at interrupt time, so avoid
placing large arrays or structures on the stack frame of the handler. It’s safe to
assume that about 200 bytes of stack are available.
• The interrupt handler runs asynchronously with the threads in the process. Any
variables modified by the handler should be declared with the volatile keyword
934
QNX Neutrino Functions and Macros
June 19, 2012
© 2012, QNX Software Systems Limited
InterruptAttach(), InterruptAttach_r()
and modified with interrupts disabled or using the atomic*() functions in any thread
and ISR.
• The interrupt handler should be kept as short as possible. If a significant amount of
work needs to be done, the handler should deliver an event to awaken a thread to do
the work.
• The handler can’t call library routines that contain kernel calls except for
InterruptDisable(), InterruptEnable(), InterruptLock(), InterruptMask(),
InterruptUnlock(), and InterruptUnmask().
The handler can call TraceEvent(), but not all of its commands are valid.
• It isn’t safe to use floating-point operations in Interrupt Service Routines.
The return value of the handler function should be NULL or a pointer to a valid
sigevent structure that the kernel delivers. These events are defined in <signal.h>.
Consider the following when choosing the event type:
• Message-driven processes that block in a receive loop using MsgReceivev() should
consider using SIGEV_PULSE to trigger a pulse.
• Threads that block at a particular point in their code and don’t go back to a
common receive point should consider using SIGEV_INTR as the event notification
type and InterruptWait() as the blocking call.
The thread that calls InterruptWait() must be the one that called InterruptAttach().
• Using SIGEV_SIGNAL, SIGEV_SIGNAL_CODE, SIGEV_SIGNAL_THREAD, or
SIGEV_THREAD is discouraged. It’s less efficient than the other mechanisms for
interrupt event delivery.
Flags
The flags argument is a bitwise OR of the following values, or 0:
June 19, 2012
Flag
Description
_NTO_INTR_FLAGS_END
Put the new handler at the end of the list of
existing handlers (for shared interrupts) instead
of the start.
_NTO_INTR_FLAGS_PROCESS
Associate the handler with the process instead
of the attaching thread.
_NTO_INTR_FLAGS_TRK_MSK
Track calls to InterruptMask() and
InterruptUnmask() to make detaching the
interrupt handler safer.
QNX Neutrino Functions and Macros
935
InterruptAttach(), InterruptAttach_r()
© 2012, QNX Software Systems Limited
_NTO_INTR_FLAGS_END
The interrupt structure allows hardware interrupts to be shared. For example, if two
processes take over the same physical interrupt, both handlers are invoked
consecutively. When a handler attaches, it’s placed in front of any existing handlers
for that interrupt and is called first. You can change this behavior by setting the
_NTO_INTR_FLAGS_END flag in the flags argument. This adds the handler at the end
of any existing handlers. Although the Neutrino microkernel allows full interrupt
sharing, your hardware might not. For example, the ISA bus doesn’t allow interrupt
sharing, while the PCI bus does.
Processor interrupts are enabled during the execution of the handler. Don’t attempt to
talk to the interrupt controller chip. The operating system issues the end-of-interrupt
command to the chip after processing all handlers at a given level.
The first process to attach to an interrupt unmasks the interrupt. When the last process
detaches from an interrupt, the system masks it.
If the thread that attached the interrupt handler terminates without detaching the
handler, the kernel does it automatically.
_NTO_INTR_FLAGS_PROCESS
Adding _NTO_INTR_FLAGS_PROCESS to flags associates the interrupt handler with
the process instead of the attaching thread. The interrupt handler is removed when the
process exits, instead of when the attaching thread exits.
_NTO_INTR_FLAGS_TRK_MSK
The _NTO_INTR_FLAGS_TRK_MSK flag and the id argument to InterruptMask() and
InterruptUnmask() let the kernel track the number of times a particular interrupt
handler or event has been masked. Then, when an application detaches from the
interrupt, the kernel can perform the proper number of unmasks to ensure that the
interrupt functions normally. This is important for shared interrupt levels.
You should always set _NTO_INTR_FLAGS_TRK_MSK.
Blocking states
This call doesn’t block.
Returns:
The only difference between these functions is the way they indicate errors:
936
InterruptAttach()
An interrupt function ID. If an error occurs, -1 is returned and
errno is set.
InterruptAttach_r()
An interrupt function ID. This function does NOT set errno. If
an error occurs, the negative of a value from the Errors section
is returned.
QNX Neutrino Functions and Macros
June 19, 2012
InterruptAttach(), InterruptAttach_r()
© 2012, QNX Software Systems Limited
Errors:
Use the function ID with the InterruptDetach() function to detach this interrupt
handler.
EAGAIN
All kernel interrupt entries are in use.
EFAULT
A fault occurred when the kernel tried to access the buffers provided.
EINVAL
The value of intr isn’t a valid interrupt number.
EPERM
The process doesn’t have I/O privileges.
Classification:
QNX Neutrino
Safety
Cancellation point
No
Interrupt handler
No
Signal handler
Yes
Thread
Yes
Caveats:
If you’re writing a resource manager and using the resmgr_*() functions with multiple
threads, a thread that attaches to an interrupt must use _NTO_INTR_FLAGS_PROCESS
in the flags argument when calling InterruptAttach().
If your interrupt handler isn’t SMP-safe, you must lock it to one processor using:
ThreadCtl( _NTO_TCTL_RUNMASK, ... );
See also:
atomic_add(), atomic_clr(), atomic_set(), atomic_sub(), atomic_toggle(),
InterruptAttachEvent(), InterruptDetach(), InterruptDisable(), InterruptEnable(),
InterruptLock(), InterruptMask(), InterruptUnlock(), InterruptUnmask(),
InterruptWait(), mlock(), sigevent, ThreadCtl(), TraceEvent()
Writing an Interrupt Handler chapter of the Neutrino Programmer’s Guide
Interrupts chapter of Getting Started with QNX Neutrino
June 19, 2012
QNX Neutrino Functions and Macros
937
InterruptAttachEvent(), InterruptAttachEvent_r()
© 2012, QNX Software Systems
Limited
Attach an event to an interrupt source
Synopsis:
#include <sys/neutrino.h>
int InterruptAttachEvent(
int intr,
const struct sigevent* event,
unsigned flags );
int InterruptAttachEvent_r(
int intr,
const struct sigevent* event,
unsigned flags );
Arguments:
intr
The interrupt vector number that you want to attach an event to; for more
information, see “Interrupt vector numbers” in the documentation for
InterruptAttach().
event
A pointer to the sigevent structure that you want to be delivered when this
interrupt occurs.
flags
Flags that specify how you want to attach the interrupt handler. For more
information, see “Flags,” below.
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
The InterruptAttachEvent() and InterruptAttachEvent_r() kernel calls attach the given
event to the hardware interrupt specified by intr. They automatically enable (i.e.,
unmask) the interrupt level.
The InterruptAttachEvent() and InterruptAttachEvent_r() functions are identical
except in the way they indicate errors. See the Returns section for details.
Before calling either of these functions, the thread must request I/O privileges by
calling:
ThreadCtl( _NTO_TCTL_IO, 0 );
If the thread doesn’t do this, it might SIGSEGV when it calls InterruptAttachEvent() or
InterruptAttachEvent_r().
To prevent infinite interrupt recursion, the kernel automatically does an
InterruptMask() for intr when delivering the event. After the interrupt-handling thread
has dealt with the event, it must call InterruptUnmask() to reenable the interrupt.
Consider the following when choosing an event type:
938
QNX Neutrino Functions and Macros
June 19, 2012
© 2012, QNX Software Systems Limited
InterruptAttachEvent(),
InterruptAttachEvent_r()
• Message-driven processes that block in a receive loop using MsgReceivev() should
consider using SIGEV_PULSE to trigger a channel.
• Threads that block at a particular point in their code and don’t go back to a
common receive point, should consider using SIGEV_INTR as the event notification
type and InterruptWait() as the blocking call.
The thread that calls InterruptWait() must be the one that called
InterruptAttachEvent().
• Using SIGEV_SIGNAL, SIGEV_SIGNAL_CODE, or SIGEV_SIGNAL_THREAD is
discouraged. It is less efficient than the other mechanisms for interrupt event
delivery.
On a multicore system, the thread that receives the event set up by
InterruptAttachEvent() runs on any CPU, limited only by the scheduler and the
runmask.
Flags
The flags argument is a bitwise OR of the following values, or 0:
Flag
Description
_NTO_INTR_FLAGS_END
Put the new event at the end of the list of
existing events instead of the start.
_NTO_INTR_FLAGS_PROCESS
Associate the event with the process instead of
the attaching thread.
_NTO_INTR_FLAGS_TRK_MSK
Track calls to InterruptMask() and
InterruptUnmask() to make detaching the
interrupt handler safer.
_NTO_INTR_FLAGS_END
The interrupt structure allows hardware interrupts to be shared. For example if two
processes call InterruptAttachEvent() for the same physical interrupt, both events are
sent consecutively. When an event attaches, it’s placed in front of any existing events
for that interrupt and is delivered first. You can change this behavior by setting the
_NTO_INTR_FLAGS_END flag in the flags argument. This adds the event at the end of
any existing events.
_NTO_INTR_FLAGS_PROCESS
Adding _NTO_INTR_FLAGS_PROCESS to flags associates the interrupt event with the
process instead of the attaching thread. The interrupt event is removed when the
process exits, instead of when the attaching thread exits.
June 19, 2012
QNX Neutrino Functions and Macros
939
InterruptAttachEvent(), InterruptAttachEvent_r()
© 2012, QNX Software Systems
Limited
The kernel automatically attempts to set the _NTO_INTR_FLAGS_PROCESS flag if the
event is directed at the process in general (for SIGEV_SIGNAL,
SIGEV_SIGNAL_CODE, and SIGEV_PULSE events).
_NTO_INTR_FLAGS_TRK_MSK
The _NTO_INTR_FLAGS_TRK_MSK flag and the id argument to InterruptMask() and
InterruptUnmask() let the kernel track the number of times a particular interrupt
handler or event has been masked. Then, when an application detaches from the
interrupt, the kernel can perform the proper number of unmasks to ensure that the
interrupt functions normally. This is important for shared interrupt levels.
You should always set _NTO_INTR_FLAGS_TRK_MSK.
Advantages & disadvantages
InterruptAttachEvent() has several advantages over InterruptAttach():
• Less work is done at interrupt time (you avoid the context switch necessary to map
in an interrupt handler).
• Interrupt handling code runs at the thread’s priority, which lets you specify the
priority of the interrupt handling.
• You can use process-level debugging on your interrupt handler code.
• It isn’t safe to use floating-point operations in Interrupt Service Routines.
There are also some disadvantages:
• There might be a delay before the interrupt handling code runs (until the thread is
scheduled to run).
• For multiple devices sharing an event, the amount of time spent with the interrupt
masked increases.
You can freely mix calls to InterruptAttach() and InterruptAttachEvent() for a
particular interrupt.
Blocking states
This call doesn’t block.
Returns:
The only difference between these functions is the way they indicate errors:
InterruptAttachEvent()
An interrupt function ID. If an error occurs, -1 is returned and errno is set.
940
QNX Neutrino Functions and Macros
June 19, 2012
InterruptAttachEvent(),
InterruptAttachEvent_r()
© 2012, QNX Software Systems Limited
InterruptAttachEvent_r()
An interrupt function ID. This function does NOT set errno. If an error occurs,
the negative of a value from the Errors section is returned.
Use the ID with InterruptDetach() to detach this interrupt event.
Errors:
EAGAIN
All kernel interrupt entries are in use.
EFAULT
A fault occurred when the kernel tried to access the buffers provided.
EINVAL
The value of intr isn’t a valid interrupt number.
EPERM
The process doesn’t have I/O privileges.
Classification:
QNX Neutrino
Safety
Cancellation point
No
Interrupt handler
No
Signal handler
Yes
Thread
Yes
See also:
InterruptAttach(), InterruptDetach(), InterruptLock(), InterruptMask(),
InterruptUnlock(), InterruptUnmask(), InterruptWait(), sigevent
Writing an Interrupt Handler chapter of the Neutrino Programmer’s Guide
Interrupts chapter of Getting Started with QNX Neutrino
June 19, 2012
QNX Neutrino Functions and Macros
941
InterruptDetach(), InterruptDetach_r()
© 2012, QNX Software Systems Limited
Detach an interrupt handler by ID
Synopsis:
#include <sys/neutrino.h>
int InterruptDetach( int id );
int InterruptDetach_r( int id );
Arguments:
id
The value returned by InterruptAttach() InterruptAttachEvent(), or
InterruptHookIdle().
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
These kernel calls detach the interrupt handler specified by the id argument. If, after
detaching, no thread is attached to the interrupt, then the interrupt is masked off. The
thread that detaches the interrupt handler must be in the same process as the thread
that attached it.
The InterruptDetach() and InterruptDetach_r() functions are identical except in the
way they indicate errors. See the Returns section for details.
Before calling either of these functions, the thread must request I/O privileges by
calling:
ThreadCtl( _NTO_TCTL_IO, 0 );
If the thread doesn’t do this, it might SIGSEGV when it calls InterruptDetach() or
InterruptDetach_r().
Blocking states
These calls don’t block.
Returns:
The only difference between these functions is the way they indicate errors:
InterruptDetach()
If an error occurs, -1 is returned and errno is set. Any other
value returned indicates success.
InterruptDetach_r() EOK is returned on success. This function does NOT set errno.
If an error occurs, any value in the Errors section may be
returned.
942
QNX Neutrino Functions and Macros
June 19, 2012
InterruptDetach(), InterruptDetach_r()
© 2012, QNX Software Systems Limited
Errors:
EINVAL
EPERM
The value of id doesn’t exist for this process.
The process doesn’t have superuser privileges, or isn’t the process that
attached the interrupt identified by id.
Classification:
QNX Neutrino
Safety
Cancellation point
No
Interrupt handler
No
Signal handler
Yes
Thread
Yes
See also:
InterruptAttach(), InterruptAttachEvent(), InterruptHookIdle(), InterruptUnlock()
Writing an Interrupt Handler chapter of the Neutrino Programmer’s Guide
Interrupts chapter of Getting Started with QNX Neutrino
June 19, 2012
QNX Neutrino Functions and Macros
943
InterruptDisable()
© 2012, QNX Software Systems Limited
Disable hardware interrupts
Synopsis:
#include <sys/neutrino.h>
void InterruptDisable( void );
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
The InterruptDisable() function disables all hardware interrupts. You can call it from a
thread or from an interrupt handler. Before calling this function, the thread must
request I/O privileges by calling:
ThreadCtl( _NTO_TCTL_IO, 0 );
Any kernel call results in the re-enabling of interrupts, and many library routines are
built on kernel calls. Masked interrupts are not affected.
If the thread doesn’t do this, it might SIGSEGV when it calls InterruptDisable().
Reenable the interrupts by calling InterruptEnable().
!
CAUTION: Since this function disables all hardware interrupts, take care to reenable
them as quickly as possible. Failure to do so may result in increased interrupt latency
and nonrealtime performance.
Use InterruptDisable() instead of an inline cli to ensure hardware portability with
non-x86 CPUs.
Use InterruptLock() and InterruptUnlock() instead of InterruptDisable() and
InterruptEnable(). The InterruptLock() and InterruptUnlock() functions perform the
intended function on SMP hardware, and allow your interrupt thread to run on any
processor in the system.
Classification:
QNX Neutrino
Safety
Cancellation point
No
continued. . .
944
QNX Neutrino Functions and Macros
June 19, 2012
InterruptDisable()
© 2012, QNX Software Systems Limited
Safety
Interrupt handler
Yes
Signal handler
Yes
Thread
Yes
See also:
InterruptEnable(), InterruptLock(), InterruptMask(), InterruptStatus(),
InterruptUnlock(), InterruptUnmask(), ThreadCtl()
Writing an Interrupt Handler chapter of the Neutrino Programmer’s Guide
Interrupts chapter of Getting Started with QNX Neutrino
June 19, 2012
QNX Neutrino Functions and Macros
945
InterruptEnable()
© 2012, QNX Software Systems Limited
Enable hardware interrupts
Synopsis:
#include <sys/neutrino.h>
void InterruptEnable( void );
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
The InterruptEnable() function enables all hardware interrupts. You can call it from a
thread or from an interrupt handler. Before calling this function, the thread must
request I/O privileges by calling:
ThreadCtl( _NTO_TCTL_IO, 0 );
If the thread doesn’t do this, it might SIGSEGV when it calls InterruptEnable().
You should call this function as quickly as possible after calling InterruptDisable().
Use InterruptLock() and InterruptUnlock() instead of InterruptDisable() and
InterruptEnable(). The InterruptLock() and InterruptUnlock() functions perform the
intended function on SMP hardware, and allow your interrupt thread to run on any
processor in the system.
Classification:
QNX Neutrino
Safety
Cancellation point
No
Interrupt handler
Yes
Signal handler
Yes
Thread
Yes
See also:
InterruptDisable(), InterruptLock(), InterruptMask(), InterruptStatus(),
InterruptUnlock(), InterruptUnmask(), ThreadCtl()
Writing an Interrupt Handler chapter of the Neutrino Programmer’s Guide
Interrupts chapter of Getting Started with QNX Neutrino
946
QNX Neutrino Functions and Macros
June 19, 2012
InterruptHookIdle()
© 2012, QNX Software Systems Limited
Attach an “idle” interrupt handler
Synopsis:
#include <sys/neutrino.h>
int InterruptHookIdle(
void (*handler)(uint64_t *, struct qtime_entry *),
unsigned flags );
Arguments:
handler
A pointer to the handler function; see below.
flags
Flags that specify how you want to attach the interrupt handler. For more
information, see “Flags,” below.
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
The InterruptHookIdle() kernel call attaches the specified interrupt handler to the
“idle” interrupt, which is called when the system is idle. This is typically used to
implement power management features.
The arguments to the handler functions are:
uint64_t*
A pointer to the time, in nanoseconds, when the next timer will
expire.
struct qtime_entry *
A pointer to the section of the system page with the time
information, including the current time of day.
The simplest idle handler consists of a halt instruction.
Flags
The flags argument is a bitwise OR of the following values, or 0:
June 19, 2012
QNX Neutrino Functions and Macros
947
InterruptHookIdle()
© 2012, QNX Software Systems Limited
Flag
Description
_NTO_INTR_FLAGS_END
Put the new handler at the end of the list of
existing handlers (for shared interrupts) instead
of the start.
_NTO_INTR_FLAGS_PROCESS
Associate the handler with the process instead
of the attaching thread.
_NTO_INTR_FLAGS_TRK_MSK
Track calls to InterruptMask() and
InterruptUnmask() to make detaching the
interrupt handler safer.
_NTO_INTR_FLAGS_END
The interrupt structure allows hardware interrupts to be shared. For example, if two
processes take over the same physical interrupt, both handlers are invoked
consecutively. When a handler attaches, it’s placed in front of any existing handlers
for that interrupt and is called first. You can change this behavior by setting the
_NTO_INTR_FLAGS_END flag in the flags argument. This adds the handler at the end
of any existing handlers.
Processor interrupts are enabled during the execution of the handler. Don’t attempt to
talk to the interrupt controller chip. The end of interrupt command is issued to the chip
by the operating system after processing all handlers at a given level.
The first process to attach to an interrupt unmasks the interrupt. When the last process
detaches from an interrupt, the system masks it.
If the thread that attached the interrupt handler terminates without detaching the
handler, the kernel does it automatically.
_NTO_INTR_FLAGS_PROCESS
Adding _NTO_INTR_FLAGS_PROCESS to flags associates the interrupt handler with
the process instead of the attaching thread. The interrupt handler is removed when the
process exits, instead of when the attaching thread exits.
_NTO_INTR_FLAGS_TRK_MSK
The _NTO_INTR_FLAGS_TRK_MSK flag and the id argument to InterruptMask() and
InterruptUnmask() let the kernel track the number of times a particular interrupt
handler or event has been masked. Then, when an application detaches from the
interrupt, the kernel can perform the proper number of unmasks to ensure that the
interrupt functions normally. This is important for shared interrupt values.
Blocking states
This call doesn’t block.
948
QNX Neutrino Functions and Macros
June 19, 2012
InterruptHookIdle()
© 2012, QNX Software Systems Limited
Returns:
An interrupt function ID, or -1 if an error occurs (errno is set).
Use the returned value with the InterruptDetach() function to detach this interrupt
handler.
Errors:
EAGAIN
All kernel interrupt entries are in use.
EPERM
The process doesn’t have superuser capabilities.
Classification:
QNX Neutrino
Safety
Cancellation point
No
Interrupt handler
No
Signal handler
Yes
Thread
Yes
See also:
InterruptAttach(), InterruptAttachEvent(), InterruptDetach(), InterruptHookTrace()
Writing an Interrupt Handler chapter of the Neutrino Programmer’s Guide
June 19, 2012
QNX Neutrino Functions and Macros
949
InterruptHookTrace()
© 2012, QNX Software Systems Limited
Attach the pseudo interrupt handler that the instrumented module uses
Synopsis:
#include <sys/neutrino.h>
int InterruptHookTrace(
const struct sigevent * (* handler)(int),
unsigned flags );
Arguments:
handler
A pointer to the handler function.
flags
Flags that specify how you want to attach the interrupt handler; 0, or the
following bit:
• _NTO_INTR_FLAGS_END — put the new handler at the end of the list
of existing handlers (for shared interrupts) instead of the start. For
more information, see below.
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
The InterruptHookTrace() kernel call attaches the pseudo interrupt handler handle that
the instrumented module uses.
This function requires the instrumented kernel. For more information, see the System
Analysis Toolkit (SAT) User’s Guide.
Before calling this function, the thread must request I/O privileges by calling:
ThreadCtl( _NTO_TCTL_IO, 0 );
The handler argument specifies the pseudo interrupt handler that receives trace events
from the kernel. The integer that’s passed to the handler is a combination of the buffer
index and the sequence number; to extract each part, pass the integer to the
_TRACE_GET_BUFFNUM() and _TRACE_GET_BUFFSEQ() macros defined in
<sys/trace.h>.
_NTO_INTR_FLAGS_END
The interrupt structure allows trace interrupts to be shared. For example, if two
processes take over the same trace interrupt, both handlers are invoked consecutively.
When a handler attaches, it’s placed in front of any existing handlers for that interrupt
and is called first. This behavior can be changed by setting the
950
QNX Neutrino Functions and Macros
June 19, 2012
InterruptHookTrace()
© 2012, QNX Software Systems Limited
_NTO_INTR_FLAGS_END flag in the flags argument. This adds the handler at the end
of any existing handlers.
Blocking states
This call doesn’t block.
Returns:
An interrupt function ID, or -1 if an error occurs (errno is set).
Errors:
EAGAIN
All kernel interrupt entries are in use.
EFAULT
A fault occurred when the kernel tried to access the buffers provided.
EPERM
The process doesn’t have superuser capabilities.
ENOTSUP
The kernel isn’t instrumented.
Classification:
QNX Neutrino
Safety
Cancellation point
No
Interrupt handler
No
Signal handler
Yes
Thread
Yes
See also:
InterruptAttach(), TraceEvent()
Writing an Interrupt Handler chapter of the Neutrino Programmer’s Guide
System Analysis Toolkit (SAT) User’s Guide
June 19, 2012
QNX Neutrino Functions and Macros
951
InterruptLock()
© 2012, QNX Software Systems Limited
Guard a critical section in an interrupt handler
Synopsis:
#include <sys/neutrino.h>
void InterruptLock( intrspin_t* spinlock );
Arguments:
spinlock
The spinlock (a variable shared between the interrupt handler and a
thread) to use.
If spinlock isn’t a static variable, you must initialize it by calling:
memset( spinlock, 0, sizeof( *spinlock ) );
before using it with InterruptLock().
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included
automatically.
Description:
The InterruptLock() function guards a critical section by locking the specified
spinlock. You can call this function from a thread or from an interrupt handler. Before
calling this function, the thread must request I/O privileges by calling:
ThreadCtl( _NTO_TCTL_IO, 0 );
If the thread doesn’t do this, it might SIGSEGV when it calls InterruptLock().
This function tries to acquire the spinlock (a variable shared between the interrupt
handler and a thread) while interrupts are disabled. The code spins in a tight loop until
the lock is acquired. It