Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking...

1020
Systems/C C Library Version 2.25 Copyright c 2020, Dignus, LLC

Transcript of Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking...

Page 1: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

Systems/C C LibraryVersion 2.25

Copyright c© 2020, Dignus, LLC

Page 2: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant
Page 3: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

Systems/C C LibraryVersion 2.25

i

Page 4: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

Copyright c© 2018 Dignus LLC, 8378 Six Forks Road Suite 203, Raleigh NC, 27615.World rights reserved. No part of this publication may be stored in a retrievalsystem, transmitted, or reproduced in any way, including but not limited to pho-tocopy, photograph, magnetic or other record, without the prior agreement andwritten permission of the publisher.

This product includes software developed by the University of California, Berkeleyand its contributors.

Copyright (c) 1990, 1993The Regents of the University of California. All rights reserved.

IBM, S/390, zSeries, zArchitecure, z/OS, z/VM, z/VSE, OS/390, MVS, VM, CMS,HLASM, and High Level Assembler are registered trademarks of International Busi-ness Machines Corporation.

UNIX is a registered trademark in the United States and/or other countries licensedexclusively through X/Open Company Limited.

Microsoft, Windows, Windows NT, Windows XP are trademarks of Microsoft Cor-poration in the United States and other countries.

Dignus, Systems/C, Systems/C++ and Systems/ASM are registered trademarks ofDignus, LLC.

ii

Page 5: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

Contents

How to use this book 1

Using the Systems/C C library 3Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3

A note on re-entrant (RENT) programs . . . . . . . . . . . . . . . . 3Using PLINK . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4Linking under the OpenEdition shell . . . . . . . . . . . . . . . . . . 5Other useful utilities . . . . . . . . . . . . . . . . . . . . . . . . . . . 6Linking programs on OS/390 and z/OS . . . . . . . . . . . . . . . . 7Executing programs . . . . . . . . . . . . . . . . . . . . . . . . . . . 8

Systems/C C Library Features 11Special “built-in” implementations for common C library functions. . 11

Using the Systems/C Direct-CALL interface . . . . . . . . . . . . . . . . . 12

Systems/C z/Architecture Library 21z/Architecture library features . . . . . . . . . . . . . . . . . . . . . 21z/Architecture data and code locations . . . . . . . . . . . . . . . . . 21Determining addressing mode . . . . . . . . . . . . . . . . . . . . . . 22Linking with the Systems/C z/Architecture Library . . . . . . . . . 22z/Architecture and OpenEdition services . . . . . . . . . . . . . . . . 23Direct-CALL extensions . . . . . . . . . . . . . . . . . . . . . . . . . 23Mixing z/Architecture and non-z/Architecture functions . . . . . . . 23

Programming for TSO and BATCH 25Running programs under TSO . . . . . . . . . . . . . . . . . . . . . . . . 25argv processing under TSO . . . . . . . . . . . . . . . . . . . . . . . . . . 26Running programs under BATCH JCL . . . . . . . . . . . . . . . . . . . . 26argv processing under BATCH . . . . . . . . . . . . . . . . . . . . . . . . 26

Programming for OpenEdition 29Linking programs under the OpenEdition Shell . . . . . . . . . . . . . . . 29Copying programs from a PDS to the OpenEdition Shell . . . . . . . . . . 30Running programs under the OpenEdition Shell . . . . . . . . . . . . . . 30

Systems/C C Library iii

Page 6: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

Programming for CMS 31Linking programs for CMS . . . . . . . . . . . . . . . . . . . . . . . . . . 31

Using PLINK to create CMS programs . . . . . . . . . . . . . . . . . 31Using LKED to link CMS programs . . . . . . . . . . . . . . . . . . 33Executing programs on CMS . . . . . . . . . . . . . . . . . . . . . . 34

Programming for MVS 3.8 35Linking programs for MVS 3.8 . . . . . . . . . . . . . . . . . . . . . . . . 35

Using PLINK to create MVS 3.8 programs . . . . . . . . . . . . . . . 36MVS 3.8 runtime restrictions . . . . . . . . . . . . . . . . . . . . . . . . . 37

Controlling the runtime environment 39Runtime Options specified in the program arguments . . . . . . . . . . . . 39

Runtime Options in TSO and Batch . . . . . . . . . . . . . . . . . . 39Runtime Options in OpenEdition . . . . . . . . . . . . . . . . . . . . 40Disabling/Enabling runtime options in TSO and Batch . . . . . . . . 40

stdin, stdout and stderr . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41Changing standard filenames at execution time . . . . . . . . . . . . 41Changing standard filenames and attributes at compile time . . . . . 41

Choosing the TCP/IP interface . . . . . . . . . . . . . . . . . . . . . . . . 42Changing argv delimiters for BATCH and TSO . . . . . . . . . . . . . . . 43Disabling runtime options for BATCH and TSO . . . . . . . . . . . . . . 43Controlling stack space allocation . . . . . . . . . . . . . . . . . . . . . . . 44Specifying the runtime storage SUBPOOL . . . . . . . . . . . . . . . . . . 45Specifying the runtime KEY . . . . . . . . . . . . . . . . . . . . . . . . . . 45Controlling access to Unix System Services . . . . . . . . . . . . . . . . . 45Signal Handling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46

Considerations for SIGABND processing . . . . . . . . . . . . . . . . . 46OpenEdition . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47

Linking under OpenEdition . . . . . . . . . . . . . . . . . . . . . . . 47Running under OpenEdition . . . . . . . . . . . . . . . . . . . . . . . 48

Data locations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48Stand alone function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49

Compiler invoked routines . . . . . . . . . . . . . . . . . . . . . . . . 50Initializing re-entrant data . . . . . . . . . . . . . . . . . . . . . . . . 50

User ABEND codes issued by the runtime 53

Systems/C C Library functions 55System Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 56

ACCESS(2) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 57CHDIR(2) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59CHMOD(2) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 61CHOWN(2) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 64CHROOT(2) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 66CLOCK GETTIME(2) . . . . . . . . . . . . . . . . . . . . . . . . . . 68

iv

Page 7: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

CLOSE(2) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 70DCALL ENV(2) . . . . . . . . . . . . . . . . . . . . . . . . . . . . 72

DDNFIND(2) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73DYNALL(2) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75

DUP(2) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 83EXECVE(2) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 85EXIT(2) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 89

FCNTL(2) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 91FLDATA(2) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 93FORK(2) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 97FSYNC(2) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 99

GET CPUID(2) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 101GETITIMER(2) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 102GETDTABLESIZE(2) . . . . . . . . . . . . . . . . . . . . . . . . . . 105GETGID(2) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 106GETGROUPS(2) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 107GETLOGIN(2) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 108GETPID(2) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 109GETPGRP(2) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 110GETPRIORITY(2) . . . . . . . . . . . . . . . . . . . . . . . . . . . . 112GETPRV(2) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 114GETRUSAGE(2) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 115GETSID(2) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 117GETTIMEOFDAY(2) . . . . . . . . . . . . . . . . . . . . . . . . . . 118GETUID(2) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 120GRANTPT(2) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 121

ISPOSIXON(2) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 122JOBNAME(2) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 123

KILL(2) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 124LINK(2) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 126LSEEK(2) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 128MKDIR(2) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 130MKFIFO(2) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 132MKNOD(2) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 134MMAP(2) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 136MPROTECT(2) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 139MSYNC(2) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 141MSGCTL(2) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 143MSGGET(2) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 146MSGRCV(2) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 148MSGSND(2) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 150MUNMAP(2) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 152NANOSLEEP(2) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 153OPEN(2) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 155OSDDINFO(2) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 164

v

Page 8: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

PASSWD(2) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 166PATHCONF(2) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 168PIPE(2) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 170

PROCNAME(2) . . . . . . . . . . . . . . . . . . . . . . . . . . . . 172QUERYDUB(2) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 173

READ(2) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 174READLINK(2) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 176RENAME(2) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 177RMDIR(2) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 180SCHED YIELD(2) . . . . . . . . . . . . . . . . . . . . . . . . . . . . 182SEMCTL(2) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 183SEMGET(2) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 186SEMOP(2) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 188SETGROUPS(2) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 191SETMODE(2) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 192

SETPGID(2) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 193SETREGID(2) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 195SETREUID(2) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 197SETSID(2) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 198SETUID(2) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 200SHMAT(2) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 202SHMCTL(2) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 204SHMGET(2) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 206SIGACTION(2) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 208SIGPENDING(2) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 215SIGPROCMASK(2) . . . . . . . . . . . . . . . . . . . . . . . . . . . 216SIGSUSPEND(2) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 218SIGWAIT(2) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 219STAT(2) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 221

STEPNAME(2) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 225SYMLINK(2) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 226

SVC99(2) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 228SYNC(2) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 235TRUNCATE(2) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 236UMASK(2) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 238UNLINK(2) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 239UNLOCKPT(2) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 241

USERID(2) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 242UTIMES(2) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 243VFORK(2) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 245WAIT(2) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 247WRITE(2) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 250

TCP/IP related functions . . . . . . . . . . . . . . . . . . . . . . . . . . . 253ACCEPT(2) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 254BIND(2) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 256

vi

Page 9: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

CONNECT(2) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 258GETCLIENTID(2) . . . . . . . . . . . . . . . . . . . . . . . . . . . . 260GETHOSTID(2) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 261GETHOSTNAME(2) . . . . . . . . . . . . . . . . . . . . . . . . . . . 263GETPEERNAME(2) . . . . . . . . . . . . . . . . . . . . . . . . . . . 264GETSOCKNAME(2) . . . . . . . . . . . . . . . . . . . . . . . . . . . 265GETSOCKOPT(2) . . . . . . . . . . . . . . . . . . . . . . . . . . . . 267GIVESOCKET(2) . . . . . . . . . . . . . . . . . . . . . . . . . . . . 271IOCTL(2) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 274LISTEN(2) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 277POLL(2) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 278RECV(2) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 281SELECT(2) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 285SELECTEX(2) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 288SEND(2) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 289

SETSOCKPARM(2) . . . . . . . . . . . . . . . . . . . . . . . . . . 292SOCKET(2) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 294SHUTDOWN(2) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 297TAKESOCKET(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . 299

Gen Library . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 301ATOE(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 302TO XX(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 304

ALARM(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 307ASSERT(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 308BITSTRING(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 309CLOCK(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 312CTERMID(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 313DIRECTORY(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 315DLOPEN(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 317ERR(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 320EXEC(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 323FMTCHECK(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 326FMTMSG(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 328FNMATCH(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 331FTOK(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 333GETCWD(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 334GETCONTEXT(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . 336GETGRENT(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 338GETPROGNAME(3) . . . . . . . . . . . . . . . . . . . . . . . . . . 340GETPWENT(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 341GLOB(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 343HCREATE(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 348ISATTY(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 352LSEARCH(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 353MAKECONTEXT(3) . . . . . . . . . . . . . . . . . . . . . . . . . . 354

vii

Page 10: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

NICE(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 356POPEN(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 357POSIX SPAWN(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . 359POSIX SPAWNATTR GETFLAGS(3) . . . . . . . . . . . . . . . . . 364POSIX SPAWNATTR GETPGROUP(3) . . . . . . . . . . . . . . . 366POSIX SPAWNATTR GETSIGDEFAULT(3) . . . . . . . . . . . . . 368POSIX SPAWNATTR INIT(3) . . . . . . . . . . . . . . . . . . . . . 371POSIX SPAWN FILE ACTIONS ADDOPEN(3) . . . . . . . . . . . 373POSIX SPAWN FILE ACTIONS INIT(3) . . . . . . . . . . . . . . . 376PSELECT(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 378PSIGNAL(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 380PTSNAME(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 381PAUSE(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 383QUEUE(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 384RAISE(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 400SEM DESTROY(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . 401SEM GETVALUE(3) . . . . . . . . . . . . . . . . . . . . . . . . . . 402SEM INIT(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 404SEM OPEN(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 406SEM POST(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 409SEM WAIT(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 412SIGNAL(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 414SIGSETOPS(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 418SETJMP(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 420SLEEP(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 422SYSCONF(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 423TCGETPGRP(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 425TCSENDBREAK(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . 426TCSETATTR(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 428TCSETPGRP(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 432THRD CREATE(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . 434TIME(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 439TIMES(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 440TIMEZONE(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 442TPUT(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 443TRACEBACK(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 444TSEARCH(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 446TTYNAME(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 448UCONTEXT(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 449UNAME(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 450USLEEP(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 451UTIME(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 452WORDEXP(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 453WTO(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 456

Locale Library . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 457

viii

Page 11: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

BTOWC(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 458CTYPE(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 459ISALNUM(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 461ISALPHA(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 462ISASCII(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 463ISBLANK(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 464ISCNTRL(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 465ISDIGIT(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 466ISGRAPH(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 467ISLOWER(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 468ISPRINT(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 469ISPUNCT(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 470ISSPACE(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 471ISUPPER(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 472ISWALNUM(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 473ISXDIGIT(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 476MBLEN(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 477MBRLEN(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 479MBRTOWC(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 481MBSINIT(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 483MBSRTOWCS(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 484MULTIBYTE(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 486RUNE(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 488SETLOCALE(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 491TOASCII(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 495TOLOWER(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 496TOUPPER(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 497TOWLOWER(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 498TOWUPPER(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 499WCSTOL(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 500WCTRANS(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 502WCTYPE(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 504WCWIDTH(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 506

Math library . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 507MATH(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 508

FP CAST(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 515ISBFP(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 516

ACOS(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 518ACOSH(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 519SCALBN(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 520ASIN(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 521ASINH(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 522ATAN(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 523ATAN2(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 524ATANH(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 526

ix

Page 12: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

CEIL(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 527COPYSIGN(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 528COS(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 529COSH(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 530ERF(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 531EXP(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 533FABS(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 536FDIM(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 537FEENABLEEXCEPT(3) . . . . . . . . . . . . . . . . . . . . . . . . 538FLOOR(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 540FMA(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 541FMAX(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 543FMOD(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 545FPCLASSIFY(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 546FREXP(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 548HYPOT(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 549ILOGB(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 550ISGREATER(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 552LDEXP(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 554LGAMMA(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 555LOG(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 557LRINT(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 559LROUND(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 561MODF(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 563NAN(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 564NEXTAFTER(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 566REMAINDER(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 567RINT(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 569ROUND(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 571SIGNBIT(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 572SIN(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 573SINH(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 574SQRT(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 575TAN(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 577TANH(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 578TRUNC(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 579

Standard I/O Library . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 580STDIO(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 581FCLOSE(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 586FERROR(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 587FFLUSH(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 589FGETLN(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 591FGETWLN(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 593GETLINE(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 595FGETS(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 597

x

Page 13: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

FGETWS(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 599FOPEN(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 601FPUTS(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 604FPUTWS(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 606FREAD(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 607FSEEK(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 610FUNOPEN(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 613FWIDE(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 615GETC(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 616GETWC(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 618MKTEMP(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 620PRINTF(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 623PUTC(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 629PUTWC(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 631REMOVE(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 632SCANF(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 633SETBUF(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 637TMPFILE(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 639UNGETC(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 642UNGETWC(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 643WPRINTF(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 644WSCANF(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 650

The Standard Library . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 655FREE24(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 656FREE31(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 657MALLOC24(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 658MALLOC31(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 659

ABORT(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 660ABS(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 661ARC4RANDOM(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . 662ATEXIT(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 664ATOF(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 665ATOI(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 666ATOL(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 667BSEARCH(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 669CALLOC(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 670DIV(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 671ENVIRON(7) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 672EXIT(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 673FREE(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 674GETENV(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 675GETOPT(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 677GETSUBOPT(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 680IMAXABS(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 682IMAXDIV(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 683

xi

Page 14: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

LABS(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 684LDIV(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 685LLABS(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 686LLDIV(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 687MALLOC(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 688MEMORY(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 689QSORT(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 691RADIXSORT(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 694RAND(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 696RANDOM(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 697REALLOC(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 699REALPATH(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 700STRTOD(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 701STRTOL(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 703STRTOUL(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 705SYSCONF(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 707SYSTEM(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 709

Standard Time library . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 710CTIME(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 711STRFTIME(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 715STRPTIME(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 718TIME2POSIX(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 719TZSET(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 721TZFILE(5) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 724

String Library . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 726BCMP(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 727BCOPY(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 728BSTRING(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 729BZERO(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 731FFS(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 732INDEX(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 733MEMCCPY(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 734MEMCHR(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 735MEMCMP(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 736MEMCPY(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 737MEMMEM(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 738MEMMOVE(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 739MEMSET(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 740RINDEX(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 741STRCASECMP(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . 742STRCAT(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 743STRCHR(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 744STRCMP(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 745STRCOLL(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 746STRCPY(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 747

xii

Page 15: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

STRCSPN(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 749STRDUP(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 750STRERROR(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 751STRING(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 753STRLCPY(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 756STRLEN(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 759STRPBRK(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 760STRRCHR(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 761STRSEP(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 762STRSPN(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 763STRSTR(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 764STRTOK(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 766STRXFRM(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 768SWAB(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 769WCSWIDTH(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 770WMEMCHR(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 771

Regular Expression Library . . . . . . . . . . . . . . . . . . . . . . . . . . 773REGEX(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 774RE FORMAT(7) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 781

Net Library . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 785ADDR2ASCII(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 786BYTEORDER(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 789ETHERS(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 790GAI STRERROR(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . 793GETADDRINFO(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . 795GETHOSTBYNAME(3) . . . . . . . . . . . . . . . . . . . . . . . . . 801

NSSWITCH LINE(3) . . . . . . . . . . . . . . . . . . . . . . . . . 805GETIPNODEBYNAME(3) . . . . . . . . . . . . . . . . . . . . . . . 807GETNAMEINFO(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . 811GETNETENT(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 815GETPROTOENT(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . 817GETSERVENT(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . 819INET(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 821NS(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 824RESOLVER(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 826

Thread Library . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 829PTHREAD(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 830PTHREAD ATFORK(3) . . . . . . . . . . . . . . . . . . . . . . . . 842PTHREAD ATTR(3) . . . . . . . . . . . . . . . . . . . . . . . . . . 844PTHREAD BARRIER(3) . . . . . . . . . . . . . . . . . . . . . . . . 849PTHREAD BARRIERATTR(3) . . . . . . . . . . . . . . . . . . . . 851PTHREAD CANCEL(3) . . . . . . . . . . . . . . . . . . . . . . . . . 853PTHREAD CLEANUP POP(3) . . . . . . . . . . . . . . . . . . . . 855PTHREAD CLEANUP PUSH(3) . . . . . . . . . . . . . . . . . . . . 856PTHREAD CONDATTR(3) . . . . . . . . . . . . . . . . . . . . . . 857

xiii

Page 16: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

PTHREAD COND BROADCAST(3) . . . . . . . . . . . . . . . . . 860PTHREAD COND DESTROY(3) . . . . . . . . . . . . . . . . . . . 861PTHREAD COND INIT(3) . . . . . . . . . . . . . . . . . . . . . . . 862PTHREAD COND SIGNAL(3) . . . . . . . . . . . . . . . . . . . . . 864PTHREAD COND TIMEDWAIT(3) . . . . . . . . . . . . . . . . . . 865PTHREAD COND WAIT(3) . . . . . . . . . . . . . . . . . . . . . . 867PTHREAD CREATE(3) . . . . . . . . . . . . . . . . . . . . . . . . . 868PTHREAD DETACH(3) . . . . . . . . . . . . . . . . . . . . . . . . 870PTHREAD EQUAL(3) . . . . . . . . . . . . . . . . . . . . . . . . . 872PTHREAD EXIT(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . 873PTHREAD GETSPECIFIC(3) . . . . . . . . . . . . . . . . . . . . . 875PTHREAD JOIN(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . 877PTHREAD KEY CREATE(3) . . . . . . . . . . . . . . . . . . . . . 879PTHREAD KEY DELETE(3) . . . . . . . . . . . . . . . . . . . . . 881PTHREAD KILL(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . 883PTHREAD MUTEXATTR(3) . . . . . . . . . . . . . . . . . . . . . 884PTHREAD MUTEX DESTROY(3) . . . . . . . . . . . . . . . . . . 887PTHREAD MUTEX INIT(3) . . . . . . . . . . . . . . . . . . . . . . 888PTHREAD MUTEX LOCK(3) . . . . . . . . . . . . . . . . . . . . . 890PTHREAD MUTEX TRYLOCK(3) . . . . . . . . . . . . . . . . . . 891PTHREAD MUTEX UNLOCK(3) . . . . . . . . . . . . . . . . . . . 892PTHREAD ONCE(3) . . . . . . . . . . . . . . . . . . . . . . . . . . 893PTHREAD RWLOCKATTR DESTROY(3) . . . . . . . . . . . . . . 895PTHREAD RWLOCKATTR GETPSHARED(3) . . . . . . . . . . . 896PTHREAD RWLOCKATTR SETPSHARED(3) . . . . . . . . . . . 899PTHREAD RWLOCK DESTROY(3) . . . . . . . . . . . . . . . . . 901PTHREAD RWLOCK INIT(3) . . . . . . . . . . . . . . . . . . . . . 903PTHREAD RWLOCK RDLOCK(3) . . . . . . . . . . . . . . . . . . 905PTHREAD RWLOCK UNLOCK(3) . . . . . . . . . . . . . . . . . . 907PTHREAD RWLOCK WRLOCK(3) . . . . . . . . . . . . . . . . . . 908PTHREAD SELF(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . 910PTHREAD SET LIMIT NP(3) . . . . . . . . . . . . . . . . . . . . . 911PTHREAD SIGMASK(3) . . . . . . . . . . . . . . . . . . . . . . . . 914PTHREAD SPIN INIT(3) . . . . . . . . . . . . . . . . . . . . . . . . 916PTHREAD SPIN LOCK(3) . . . . . . . . . . . . . . . . . . . . . . . 918PTHREAD TESTCANCEL(3) . . . . . . . . . . . . . . . . . . . . . 920PTHREAD YIELD(3) . . . . . . . . . . . . . . . . . . . . . . . . . . 923THRD CREATE(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . 924

CEEPIPI interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 929CEEPIPI(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 930

CEEPIPI init main(3) . . . . . . . . . . . . . . . . . . . . . . . . . 936CEEPIPI init main dp(3) . . . . . . . . . . . . . . . . . . . . . . . 937CEEPIPI init sub(3) . . . . . . . . . . . . . . . . . . . . . . . . . . 938CEEPIPI init sub dp(3) . . . . . . . . . . . . . . . . . . . . . . . . 939CEEPIPI call main(3) . . . . . . . . . . . . . . . . . . . . . . . . . 940

xiv

Page 17: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

CEEPIPI call sub(3) . . . . . . . . . . . . . . . . . . . . . . . . . . 942CEEPIPI call sub addr(3) . . . . . . . . . . . . . . . . . . . . . . . 944CEEPIPI end seq(3) . . . . . . . . . . . . . . . . . . . . . . . . . . 946CEEPIPI start seq(3) . . . . . . . . . . . . . . . . . . . . . . . . . 947CEEPIPI term(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . 948CEEPIPI add entry(3) . . . . . . . . . . . . . . . . . . . . . . . . . 949CEEPIPI delete entry(3) . . . . . . . . . . . . . . . . . . . . . . . . 951CEEPIPI identify entry(3) . . . . . . . . . . . . . . . . . . . . . . . 952CEEPIPI identify environment(3) . . . . . . . . . . . . . . . . . . . 953CEEPIPI identify attributes(3) . . . . . . . . . . . . . . . . . . . . 955CEEPIPI set user word(3) . . . . . . . . . . . . . . . . . . . . . . . 956CEEPIPI get user word(3) . . . . . . . . . . . . . . . . . . . . . . . 957CEEPIPI alloc CEEPIT(3) . . . . . . . . . . . . . . . . . . . . . . 958

Keyed Access (VSAM) I/O . . . . . . . . . . . . . . . . . . . . . . . . . . 960VSAMIO(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 961KCLOSE(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 967KDATA(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 968KDELETE(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 970KERRINFO(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 972KGETPOS(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 973KINSERT(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 975KOPEN(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 977KREAD(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 980KREPLACE(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 982KRETRV(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 983KSEARCH(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 985KSEEK(2) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 987KSETPOS(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 989KWRITE(3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 991

ASCII/EBCDIC Translation Table 993

SIGABND example to catch ABEND 978 (out-of-stack) 995

DCALL example 999

xv

Page 18: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

xvi

Page 19: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

How to use this book

This book describes the Systems/C C run-time library.

The Systems/C run-time library provides functions that implement most of theANSI-C standard library on OS/390 and z/OS. Using the Systems/C library, youcan build stand-alone programs that run on OS/390 and z/OS.

For information on the Systems/C C compiler, refer to the Systems/C C Compilermanual.

Systems/C also includes several utility programs used to manage the process ofbuilding OS/390 and z/OS programs. For more information regarding these utilities,see the Systems/C Utilities manual.

For further information, contact Dignus, LLC at (919) 676-0847, or visithttp://www.dignus.com.

Systems/C C Library 1

Page 20: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

2 Systems/C C Library

Page 21: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

Using the Systems/C C library

This section describes how to link with the Systems/C C library and how to executethe resulting programs.

Linking with the Systems/C C run-time library onOS/390 and z/OS

Once the compiler generated assembly source has been assembled, the disparateobjects can be linked into an executable load module. If the Systems/ASM assem-bler was used to cross-assemble the assembly source, the object decks should betransferred to OS/390 via FTP or some other binary-mode transfer mechanism.

Systems/C contains two versions of the Systems/C library - the RENT versionfor generating re-entrant programs and the non-rent version for generating non-re-entrant programs.

If the source were compiled with the –frent option, the RENT library should be em-ployed to produce a re-entrant load module. This will require using the Systems/Cpre-linker PLINK during the link step.

If no source was compiled with the –frent option, then the non-rent library shouldbe used. In that case, it is not necessary to use the Systems/C pre-linker, PLINK.

A note on re-entrant (RENT) programs

Re-entrant (RENT) programs are programs which can safely be linked with theRENT option applied to the IBM LINKER, and can be placed in the OS/390 LIN-KLST, etc... They are, generally speaking, programs which do not modify theirown loaded sections, but instead allocate memory to contain program variables atprogram start-up.

When a C source file is compiled with the –frent option, the compiler will place allof the extern and static variables in the pseudo-register vector, the PRV. Thesevariables are referred to by Q-CON references in the generated assembly source.

Systems/C C Library 3

Page 22: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

The IBM linker gathers all of the Q-CON references together allocating an entry foreach in the PRV.

The Systems/C library, at start-up, allocates the appropriate space for the PRV,and retains a pointer to the PRV at a known location.

At run-time, a reference to a variable in the PRV uses the PRV pointer and thevalue the linker has substituted for the Q-CON, adding them together to produce therun-time offset for the variable.

An issue arises because of variable initialization allowed by the ANSI C standard.For example, the address of a variable in the PRV isn’t known until run-time, whenthe PRV is allocated, but is a valid file-scoped initialization value.

Because of this, the Systems/C compiler, DCC produces run-time initializationscripts which the Systems/C library processes at program start up, after the PRVhas been allocated. It is the job of the Systems/C pre-linker, PLINK, to locate thestart of these scripts in each object and gather them together. PLINK then placesa list of these at the end of the resulting object, in a known section. The run-timelibrary walks the list, interpreting the scripts it finds.

Thus, RENT programs must be processed with the Systems/C pre-linker, PLINK,to ensure proper run-time initialization of variables located in the PRV.

Using PLINK

PLINK gathers the input objects together, performing AUTOCALL resolutionwhere appropriate, producing a single file which can then be processed by the IBMBINDER or older IEWL linker.

As PLINK gathers objects, it examines the defined symbols, looking for a Sys-tems/C initialization script section and other object file processing that may needto be performed.

The output of PLINK is then processed by the IBM BINDER to produce theexecutable load module.

For detailed information on PLINK, see the PLINK section in the Systems/CUtilities manual.

On cross-hosted platforms (Windows and UNIX), PLINK is typically executedwith the object files listed on the command line; and a –S option or library namesto locate any required library objects.

For example, on a Windows platform the command:

plink "-SC:\sysc\lib\objs_rent\&M" prog.obj

4 Systems/C C Library

Page 23: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

will read the initial input file, prog.obj and examine the C:\sysc\lib\objs rentdirectory for any AUTOCALL references. Because no -o option was specified, theresulting object file is writting to the file p.out.

This command, on UNIX platforms:

plink t1.obj t2.obj libone.a -L../mylibs -ltwo

will read the two primary input objects t1.obj and t2.obj. It will try and resolvereferences from the DAR archive libone.a and then the second DAR archive../mylibs/libtwo.a

On OS/390 or z/OS, PLINK operates similar to the IBM pre-linker. The result-ing gathered object is written to the file //DDN:SYSMOD unless otherwise specified.PLINK has a default library template of -S//DDN:SYSLIB(%M) which causes it tolook in the SYSLIB PDS for autocall references. Other input objects, -S librarytemplates or DAR archives may be added in the PARMS option on the PLINKstep. PLINK reads the file //DDN:SYSIN as the initial input file. Typically, thisfile contains INCLUDE cards to include the primary objects for the program. Otherprimary input files may be included in the PARMS for PLINK. For example, thefollowing JCL reads the object INDD(PROG) and uses DIGNUS.LIBCR.OBJ as theautocall library:

//PLINK EXEC PGM=PLINK//STDERR DD SYSOUT=A//STDOUT DD SYSOUT=A//SYSLIB DD DSN=DIGNUS.LIBCR.OBJ,DISP=SHR//INDD DD DSN=mypds,DISP=SHR//SYSIN DD *INCLUDE INDD(PROG)//SYSMOD DD DSN=myoutput.obj,DISP=NEW

Note that the STDERR and STDOUT DDs were specified for PLINK’s message output.Also, the ARLIBRARY control card could have been used to add additional DARarchive files for resolving external references.

For more detailed information regarding PLINK and the other Systems/C utilities,see the Systems/C Utilities manual.

Linking under the OpenEdition shell

Systems/C programs can be linked under the OpenEdition shell; to create loadmodules that reside in the Hierarchical File System (HFS).

Systems/C C Library 5

Page 24: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

To create an HFS load-module, the output from PLINK can be linked using theOpenEdition cc command. The -e // option should be added the cc command toindicate that the entry-point is not the default Language Environment entry pointexpected by cc. The Systems/C runtime library will specify its own entry-point.

For example, to pre-link and link the object myfunc.o and produce the HFS load-module myprog under the OpenEdition shell (assuming /usr/local/dignus is theinstallation location), simply run PLINK:

plink -omyprog.o myfunc.o "-S/usr/local/dignus/objs_rent/&m"

then use the OpenEdition cc command:

cc -e // -omyprog myprog.o

to produce the myprog load-module. myprog can then be invoked as any otherOpenEdition program.

Other useful utilities

Systems/C provides other useful utilities. More details and examples of their usecan be found in the Systems/C Utilities manual.

DAR — the Systems/C Archive utility

The Systems/C archive utility, DAR, creates and maintains groups of files combinedinto an archive. Once an archive has been created, new files can be added andexisting files can be extracted, deleted or replaced. Files gathered together withDAR can be used to resolve AUTOCALLed references from PLINK.

DRANLIB — the Systems/C Archive index utility

DRANLIB is used to index a Systems/C archive to allow for AUTOCALL refer-ences to longer names, or to names which are not dependent on the archive membername. DRANLIB will create a SYMDEF member in the Systems/C archive whichPLINK will consult when looking for symbolic resolutions.

GOFF2XSD — Convert GOFF format objects to XSD format

GOFF2XSD is used to convert GOFF format objects to XSD format. Typically,GOFF format objects are created by the IBM HLASM assembler when the XOBJECToption is enabled. The PLINK linker can read GOFF format natively. This utilityis no longer required for using PLINK and is provided only for back-level support.

6 Systems/C C Library

Page 25: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

DCCPC — the Systems/C CICS Command Processor

DCCPC is used to convert EXEC CICS commands in C source into plain C code forcompilation. It is especially useful in cross environments where IBM’s translatorscannot be used.

D2S — the Systems/C DSECT to struct conversion tool

D2S extracts assembly DSECTs from assembler-generated ADATA information andgenerates C-style struct definitions. This is intended to allow C code to workseamlessly with data structures from your assembly code.

Linking programs on OS/390 and z/OS

Before execution, programs must be prepared, optionally using the Systems/C pre-linker, PLINK, and then linked using either PLINK or the IBM LINKER orBINDER.

Systems/C provides two versions of the Systems/C C library, one for RENT pro-grams and one for non-RENT programs. If you are using the Systems/C library,it is important to link with the appropriate version. If any source programs refer-ence variables found in the Systems/C library (e.g. errno) and that program wascompiled with the –frent option, then the re-entrant version of the Systems/C li-brary should be used. Using the incorrect version of the library will cause strangerun-time errors. The installation instructions for your particular host platform willdetail where to find the correct Systems/C library. Normally the Systems/C libraryis specified as the last library to use for AUTOCALL resolution in the PLINKstep. Furthermore, PLINK must be used for re-entrant programs that use the Sys-tems/C library or to take advantage of DAR archive libraries for external referenceresolution.

In the following example JCL, there are three objects to link together to form theresulting executable, MAIN, SUB1, and SUB2, representing a main module and twosupporting sub-modules. These are found in the PDS MY.PDS.OBJ. The resultingexecutable is written to MY.PDS.LOAD(MPROG).

//LINK JOB//PLINK EXEC PGM=PLINK,REGION=2048K//STEPLIB DD DSN=DIGNUS.LOAD,DISP=SHR//STDOUT DD SYSOUT=*//STDERR DD SYSOUT=*//SYSLIB DD DSN=DIGNUS.LIBCR.OBJ,DISP=SHR//SYSMOD DD DSN=&&PLKDD,UNIT=VIO,DISP=(NEW,PASS),// SPACE=(32000,(30,30)),

Systems/C C Library 7

Page 26: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

// DCB=(RECFM=FB,LRECL=80,BLKSIZE=3200)//INDD DD DSN=MYPDS.OBJ,DISP=SHR//SYSIN DD *INCLUDE INDD(MAIN)INCLUDE INDD(SUB1)INCLUDE INDD(SUB2)

//STDIN DD *//LINK EXEC PGM=IEWL,REGION=2M,PARM=(’LIST’,// ’MAP,XREF,LET’,// ’ALIASES=NO,UPCASE=NO,MSGLEVEL=4,EDIT=YES’)//SYSPRINT DD SYSOUT=*//SYSUT1 DD UNIT=SYSDA,SPACE=(CYL,(1,1))//SYSUT2 DD UNIT=SYSDA,SPACE=(CYL,(1,1))

First, the Systems/C pre-linker, PLINK is invoked, specifying the inclusion of thethree object modules and the Systems/C C reentrant library. This step could havebeen performed on a cross-platform host, running PLINK there. Then the IBMBINDER is invoked for final linking and generation of the resulting load module.

Executing programs

Once a program has been successfully linked, it is a typical OS/390 or zOS loadmodule and may be executed via JCL, TSO CALL command or, via the OpenEditionexec() linkage.

By default, the Systems/C library contains no modules that are loaded during pro-gram execution, meaning it is “all-resident.” As such, there are no run-time libraryconcerns, and no particular modules which must be present in a STEPLIB concaten-dation.

For traditional (non-POSIX) programs, the Systems/C C library’s default behavioris to open file descriptors descriptors #0, #1 and #2 using the names //DDN:STDIN,//DDN:STDOUT and //DDN:STDERR. Thus, the DD-names STDIN, STDOUT and STDERRmust be properly allocated. The open(2) description contains more informationregarding file descriptors and file I/O.

For standard Systems/C library uses, where the Direct-CALL feature is not em-ployed, arguments specified in the TSO CALL command, or via the PARM optionof JCL are processed and presented to the program in the argv[] array passed tothe main() function. The Systems/C library uses a comma (,) as the argumentdelimiter, similar to other option processes used in TSO and batch environments.

For example, if the resulting program was named “PROG” in the MY.PROGS PDS, thefollowing JCL would execute the program, passing the argument strings “arg1”,“arg2”, and “arg3” in the argv[] array.

8 Systems/C C Library

Page 27: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

...//PROG EXEC PGM=PROG,PARM="arg1,arg2,arg3"//STEPLIB DD DSN=MY.PROGS,DISP=SHR//STDOUT DD SYSOUT=*//STDERR DD SYSOUT=*

Note the definition of the STDOUT and STDERR DD statements to provide the neces-sary output path for the Systems/C library.

For programs invoked via the exec() service (POSIX programs), the first 3 filedescriptors are inherited from the parent process. Also, the arguments are processedby the Unix Systems Services environment and are presented to the program in thetypical UNIX style.

Systems/C C Library 9

Page 28: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

10 Systems/C C Library

Page 29: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

Systems/C C Library Features

The Systems/C C Library contains several features to aid in the development ofOS/390 and z/OS programs.

This include Systems/C C compiler support for in-line expansion of certain com-monly used C functions, support for using Systems/C programs in almost any run-time environment, and enhanced support for z/Architecture 64-bit programs.

Special “built-in” implementations for common C library functions.

The Systems/C compiler, DCC, provides built-in implementations for some of themore common C library functions. Built-in functions are used when the Systems/CC library header file <string.h> system header file is included. The followingfunctions have built-in implementations:

memcpy()memset()memcmp()memchr()strcpy()strlen()strcmp()strcat()strchr()strncat()strncmp()strncpy()strrchr()

#include <string.h> to take advantage of the built-in versions of these functions.

Systems/C C Library 11

Page 30: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

Using the Systems/C Direct-CALL interface

The Systems/C C library is implemented using the Systems/C entry and exit macroswhich assume a Systems/C environment is extent at run time.

The Systems/C environment includes items such as the local stack frame used forautomatic variables in your C code, the Systems/C run-time heap, I/O data blocks,etc...

Thus, in order to call a Systems/C function which uses the Systems/C entry andexit linkage macros, this environment must be established and accessible.

For typical Systems/C programs, where the initial function is a C main() function;the Systems/C library handles creation of this environment.

However, there are circumstances where there is no Systems/C main() function.For example, calling Systems/C routines from COBOL or directly from assemblersource in a system exit.

For this situation, Systems/C provides the Direct-CALL (DCALL) interface, wherea Systems/C function can be directly called from any environment. This interfacecan be employed to either automatically create and destroy a Systems/C environ-ment, or to create and re-use, then destroy a Systems/C environment.

Automatic Creation/Destruction of the Systems/C environment

To use the Direct-CALL to automatically create an destroy a Systems/C environ-ment, particular Systems/C functions are indicated as being “directly called”. Thesefunctions establish a Systems/c environment, so that normal System/C library func-tions can be employed until the “directly called” function has ended. At the endof execution of the “directly called” function, the System/C library environment isdestroyed and all resources are returned to the operating system.

To indicate that a particular function is to be “directly called”, the DCALL=YESkeyword is added to the functions prologue macro with a #pragma prolkey controlstatement:

#pragma prolkey(funcname,"DCALL=YES")

where funcname is the name of the “directly called” function. This causes theprologue generated for the named function to establish the System/C environment,and destroy it on return from the function.

For more information regarding #pragma prolkey, see the Systems/C C Compilermanual.

12 Systems/C C Library

Page 31: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

For example, if MYFUNC was to be “directly called” from assembler language;and MYFUNC would further use the Systems/C library you might have in yourassembler source:

L 2,=F’1’ST 2,PARMSL 2,=F’2’ST 2,PARMS+4LA 1,PARMSL 15,=V(MYFUNC)BALR 14,15 Call ’MYFUNC’

* The return value from MYFUNC is in R15....

PARMS DS 2F

which invokes MYFUNC with a standard parameter list, passing the values #1 and#2.

For the C definition of MYFUNC:

#pragma prolkey(MYFUNC,"DCALL=YES")

intMYFUNC(int one, int two){

printf("In MYFUNC - arg #1 is %d\n", one);printf(" arg #2 is %d\n", two);

...return (0); /* return 0 to the caller */

}

In this example, when MYFUNC is invoked, a Systems/C environment will becreated, and MYFUNC can then invoke Systems/C library functions (e.g. printf()above.)

On return from MYFUNC - the Systems/C environment will be destroyed and anyresources will be returned to the operating system. The return value from MYFUNCwill be in R15 as it is declared to be a function returning an int.

Notice also that two parameters were passed to MYFUNC in this example. TheSystems/C linkage follows standard linkage conventions, so Systems/C “direct call”functions interoperate well with most environments. When invoking “direct call”Systems/C functions from some high-level languages, such as PL/I and COBOL,be sure to declare any parameters as pointers to their data types, as these otherlanguages pass parameters by-reference, instead of the C by-value approach.

Systems/C C Library 13

Page 32: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

Creating, re-using and destroying a Systems/C environment

The Direct-CALL interface can also be used to create a Systems/C environmentwhich is not destroyed. The created environment may be used multiple times until itis explicitly destroyed. This can save run-time cost, as the creation of a Systems/Cenvironment involves some overhead. Reusing a previously created environmentavoids the creation problem for functions called many times.

Creating a Systems/C environment

To create a Systems/C environment, the DCALL prologue key is altered to indicatethat the environment should be created when the named function is invoked, butnot destroyed when the function returns. To indicate this, use

DCALL=ALLOCATE

on the prologue key statement. On return from the C function, an environmentpointer is returned in general register one (R1). This value should be saved, andmay be re-used on subsequent Systems/C function calls to re-use the created envi-ronment. Note that the creation function can call other Systems/C functions, alterglobal data in the environment, etc... providing for a nice location to accomplishany particular initialization that may be needed.

For example:

#pragma prolkey(create,"DCALL=ALLOCATE")voidcreate(){

/* This function is called to create a *//* Systems/C environment. */

/* On return, the created environment address *//* is returned in R1. */

}

Another approach to saving the environment pointer for R1 is to use thedcall env() function. dcall env() returns the same environment pointer that

will be returned in the R1 register.

Thus, dcall env() can be used to save the environment pointer in a parameterpassed to the

DCALL=ALLOCATE

14 Systems/C C Library

Page 33: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

function. For example:

#include <machine/dcall.h>

voidcreate(void **env_ptr){

/* Set the *env_ptr value to the created environment *//* pointer*/

*env_ptr = __dcall_env();}

Using this approach, the environment pointer can be saved in a parameter whichcan then later be passed to other functions which need it.

Reusing a created environment

To reuse a previously created Systems/C environment, a different DCALL prologuekey is provided, indicating that an environment should not be established, but canbe found in the supplied location. To indicate this use:

DCALL=SUPPLIED

on the prologue key statement. When this is specified, the Systems/C librarywill use the environment address specified in register zero (R0). Before invok-ing the function, load register 0 with the address previously returned in R1 bya DCALL=ALLOCATE function call.

For example:

#pragma prolkey(func1,"DCALL=SUPPLIED")func1(){

/* calls to func1() assume a Systems/C *//* environment is passed in R0 */printf("in func1\n");

}

#pragma prolkey(func2,"DCALL=SUPPLIED")func2(){

/* calls to func2() assume a Systems/C *//* environment is passed in R0 */printf("in func2\n");

}

Systems/C C Library 15

Page 34: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

A DCALL=SUPPLIED function cannot invoke another DCALL=SUPPLIED function usingthe same environment address. That is, while the environment is being used bya DCALL=SUPPLIED function, a separately invoked DCALL=SUPPLIED function willrestart the stack point and corrupt the program. If two DCALL=SUPPLIED interfacesare provided, and need to share function code, then a 3rd non-DCALL function isthe best approach.

The Systems/C library also provides for an exit to locate the desired environmentwhen a function is called, the FINDENV=exitname option for DCALL function.FINDENV specifies an entry point which will be invoked for DCALL=SUPPLIEDfunction calls. When FINDENV is present, the Systems/C library will invoke theexit before any other processing. The exit should return with a

L R15,=V(CRT9A)BR 15

having located the Systems/C environment and placing that address into register 0(R0.)

The FINDENV exit must preserve register nine through thirteen (R9-R13) and doesnot have an available save area.

For example,

#pragma prolkey(func3,"DCALL=SUPPLIED,FINDENV=FINDME")

When func3() is invoked, the exit FINDME will be driven to load the Systems/Cenvironment pointer into R0.

One example of using the FINDENV option is to pass the environment pointer inthe parameter block. For example, if the SUPPLIED function was:

#progma prolkey (SUPPEX, "DCALL=SUPPLIED,FINDENV=@@FNDENV")SUPPEX(void **env_ptr, int *parm1){/* env_ptr is used by the @@FNDENV assembler piece *//* to set R0 to the environment pointer. */

}

then the @@FNDENV assembly function might be:

@@FNDENV CSECT@@FNDENV AMODE ANY@@FNDENV RMODE ANY

16 Systems/C C Library

Page 35: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

USING @@FNDENV,15L 2,0(0,1)L 0,0(0,2) Get environment ptr into R0L 15,=V(@CRT9A)BR 15LTORGEND

Note that if the name specified in FINDENV is an external label, not present in thecurrent compilation, then it should be made visible to the assembler via an EXTRNstatement. For example:

__asm { EXTRN FARAWAY }#pragma prolkey(func4,"DCALL=SUPPLIED,FINDENV=FARAWAY")

The DCCPRLG macro will reference the FINDENV specified label via an address-constant (A-CON), and the label needs to be appropriately defined for proper ref-erence. Note that the EXTRN statement should only appear once in the generatedassembly. Multiple EXTRN statements for the same label are flagged as errors by theassembler.

Reusing an existing PRV

For a DCALL=ALLOCATE function, it is possible to indicate that the previouslyestablished PRV should be employed instead of re-allocating the PRV and perform-ing global initialization functions.

Normally, when a DCALL=ALLOCATE environment is invoked, the routine willacquire space for the PRV and run global initialization functions (including globalconstructor functions.)

However, there are instances where a new stack frame is required, but no PRVshould be allocated. For example; to implement multi-threading via the ATTACHmacro.

In this case, the PRV=0 option on the DCALL=ALLOCATE can be used.

When DCALL=ALLOCATE,PRV=0 is specified, the Dignus runtime will createa new stack frame environment for the allocated environment but will not createor initialize a new PRV and will not invoke global constructor functions. Instead,the PRV is taken from the value found in register zero (R0) at the start of theDCALL=ALLOCATE function.

The Dignus library function getprv(2) can be used to retrieve the current PRVvalue before invoking a DCALL=ALLOCATE,PRV=0 function.

Systems/C C Library 17

Page 36: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

Differences from main()

The Systems/C Direct-CALL environment start up does not provide all the samefunction that a normal main() start up provides.

There is no argument processing in the Direct-CALL environment, theDCALL=ALLOCATE function is simply invoked directly and processes parameters asany other C function.

Furthermore, the Direct-CALL start up does not initialize the TZ environment vari-able. The TZ environment variable is used by the localtime() function to determinethe current timezone and is initialized when a normal main() function is invoked.However, this initialization is operating-system specific and is avoided in the Direct-CALL start up.

To havelocaltime() present a locale time zone, the TZ environment variable shouldbe set appropriately. See the tzset(3) description for more information on the formatof the TZ environment variable.

Destroying the Systems/C environment

After the Systems/C environment is no longer needed, it should be destroyed toreturn resources to the operating system. To destroy an environment, use theDCALL=DESTROY prologue key. The address of the environment to destroyshould be placed in register 0 (R0.) To indicate this use:

DCALL=DESTROY

on a prologue key pragma. The specified function will be invoked with the givenenvironment, and may invoke any other Systems/C functions. On return from thatfunction, the environment will be destroyed, returning resources to the operatingsystem. After calling the function, the environment address is no longer valid.

For example:

#pragma prolkey(destroy,"DCALL=DESTROY")destroy(){

/* perform any clean-up that needs to happen *//* On return from this function, the *//* Systems/C environment specified in R0 *//* will be destroyed. */

}

18 Systems/C C Library

Page 37: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

Note that the Pseudo-Register-Vector (PRV) is created when aDCALL=ALLOCATE function is invoked, and is used when any SUP-PLIED or DESTROY functions are subsequently invoked. Thus, allDCALL=ALLOCATE/SUPPLIED/DESTROYed functions that use the sameglobal variables must be in the same load module, so they will have the same PRV.That is, environments created with DCALL=ALLOCATE cannot be passed tofunctions linked in different load modules, unless remote function pointers areemployed to switch PRVs.

Saving environment memory by avoiding I/O

By default, when a Systems/C environment is created, with either DCALL=YESor DCALL=ALLOCATE, the Systems/C library initializes the I/O functions so fileI/O can occur. This initialization consumes some overhead in both run-time andmemory. If the Systems/C functions do not make use of any of the Systems/C I/Ofacilities, this can be avoided by adding

NOSTDIO=1

to the DCALL statements in the prologue keys for the library creation. WhenNOSTDIO=1 is specified, the Systems/C library will not initialize its I/O functions.Any calls to I/O functions in that environment will ABEND, so care must be takento ensure none exist.

For example:

#pragma prolkey(noio,"DCALL=YES,NOSTDIO=1")noio(){

/* This function, or any function it calls, *//* does no I/O */

}

Systems/C C Library 19

Page 38: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

20 Systems/C C Library

Page 39: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

Systems/C z/ArchitectureLibrary

Systems/C supports programs for the z/Architecture system, providing the completeSystems/C library to the z/Architecture environment.

This includes full support for 64-bit addresses, bringing the power of the Systems/Clibrary to this environment.

The Systems/c z/Architecture library uses the LP64 programming model, long andpointer data types are 64-bits wide.

z/Architecture library features

The Systems/C library contains extentions to the memory management facil-ities helpful in a 64-bit programming environment, malloc31(), free31(),malloc24(), free24(). These allow for the management of allocated space

that is guaranteed to be 31-bit or 24-bit addressable as appropriate.

z/Architecture programs can use the Systems/C and Systems/C++ ptr31 pointerqualifier to define and use 31-bit addresses in z/Architecture mode. For more infor-mation regarding the ptr31 qualifier, see the Systems/C C Compiler manual.

The Systems/C z/Architecture library provides full support for all of the functionsin the 31-bit library, including TCP/IP, memory allocation, and file I/O. For manyapplications, simply recompiling and relinking with the z/Architecture library willenable programs on the new z/Architecture hardware.

The Systems/C z/Architecture library has no restrictions on program data, all datacan reside above the 2-gigabyte “bar”.

z/Architecture data and code locations

The Systems/C z/Architecture library allows loading of data above the 2-gigabyte“bar”. There are no restrictions in the Systems/C z/Architecture library for data to

Systems/C C Library 21

Page 40: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

reside anywhere in particular. The default location for the runtime heap, stack andre-entrant data in the z/Architecture library is above the 2-gigabyte “bar”, freeingup lower instructions for.

Currently, the z/OS program loader will not load instruction code above the 2-gigabyte “bar”, thus the Systems/C library assumes that program code is locatedwithin the first 2-gigabytes of the address space.

Determining addressing mode

The z/Architecture library has no restrictions on the addressing mode. It willoperate correctly if the AMODE is 64, 31 or 24.

At program start-up, the z/Architecture library determines the proper addressingmode based on flags present in the definition of the main() function. If main() wascompiled with the –mlp64 option, and the –famode option was not used to specifyotherwise, the z/Architecture library will switch to AMODE=64 before beginning theprogram.

If the –famode option was used to indicate an AMODE other than 64, thez/Architecture library will not change the AMODE to 64.

The Systems/C C Compiler manual has more information on the –mlp64 and–famode options.

Linking with the Systems/C z/Architecture Library

To produce z/Architecture programs, the program must be linked with thez/Architecture libraries. The procedure is only slightly different that linking withthe non-z/Architecture library.

Systems/C provides a reentrant and non-reentrant z/Architecture libraries. Oncross-platform hosts, these objects are in the objs rent z and objs norent z di-rectories. On OS/390 and z/OS, these are in the LIBCRZ and LIBCNZ PDSes. Touse the Systems/C z/Architecture library, simply specify these directories/PDSs inplace of the non-zArchitecture versions.

For example, JCL to execute the PLINK pre-linker with the Systems/Cz/Architecture reentrant library would be similar to the following:

...//PLINK EXEC PGM=PLINK//STDERR DD SYSOUT=A//STDOUT DD SYSOUT=A//SYSLIB DD DSN=DIGNUS.LIBCRZ.OBJ,DISP=SHR

22 Systems/C C Library

Page 41: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

//INDD DD DSN=mypds,DISP=SHR//SYSIN DD *INCLUDE INDD(PROG)//SYSMOD DD DSN=myoutput.obj,DISP=NEW

The same command on a UNIX or Windows platform might be:

plink -omyoutput.obj prog.obj "-SC:\sysc\objs_rent_z\&M"

assuming Systems/C was installed in the C:\sysc directory.

z/Architecture and OpenEdition services

All of the OpenEdition (POSIX) functions available to 31-bit programs operate withthe z/Architecture library. The Systems/C library uses the 64-bit z/OS interfacesfor this, and thus all pointers will be 64-bits in size.

The 64-bit z/OS interfaces were only made available after z/OS 1.5, and thus thez/Architecture library requires z/OS 1.5 or later for OpenEdition services.

Direct-CALL extensions

Systems/C Direct-CALL programs linked with the z/Architecture library can beinvoked from a 64-bit or 31-bit execution environment. The Direct-CALL librarywill automatically switch to AMODE 64 when a z/Architecture DCALL entry pointis invoked.

Note that the environment pointer returned in register R0 with a DCALL=CREATEinvocation is allocated in the AMODE of the calling function. Thus, for 31-bit programsinvoking z/Architecture DCALL=SUPPLIED entry points, even if the entry pointer isrunning with AMODE=64, the environment pointer will be a 31-bit address. Forz/Architecture programs running with AMODE=64, the environment pointer for aDCALL=SUPPLIED invocation is be a complete 64-bit value.

Mixing z/Architecture and non-z/Architecture functions

With Systems/C, each load module is either linked with the z/Architecture versionsof the Systems/C library, or non-z/Architecture versions. This allows for a completelibrary in both environments without issues in clashing names or varying pointersizes, or other considerations.

However, programs linked with the z/Architecture library may invoke DCALL pro-grams created with the non-z/Architecture library, and vice-versa. The Systems/C

Systems/C C Library 23

Page 42: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

DCALL environment initialization will automatically switch AMODEs as appropriate,allowing for a seamless transition between the AMODE=64 and AMODE=24/AMODE=31environments.

Also, Systems/C and Systems/C++ provide extensions which allow the programmerto declare explicit 64 and 31-bit pointers which facilitates the transition betweenthe two environments. See the Systems/C Compiler manual and Systems/C++Compiler manual for more information.

24 Systems/C C Library

Page 43: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

Programming for TSO andBATCH

Systems/C programs can be executed from either TSO or BATCH (JCL) environ-ments.

Running programs under TSO

Systems/C programs started via a TSO address space are typically invoked via theCALL command.

For example:

READYcall ’my.progs(prog)’ ’my parms’

would invoke the program prog in the my.progs PDS, passing the single parm string“my parms”.

The double-quote character can be used to group together characters including acomma. Within a double-quoted string, the back-slash character can be used torepresent the double quote. For example, to produce the argv[] strings "my,parm"and "parm2", the parm string would be ’"my,parm",parm2’.

Note that TSO, by default, will upper-case parameter strings. If lower-case lettersare needed in the parm string, be careful to add the ASIS option on the CALLcommand.

If a Systems/C program is in a PDS that is in the JOBLIB or STEPLIB concatenta-tions, it can be executed just as any other system program, without directly usingCALL.

Systems/C C Library 25

Page 44: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

argv processing under TSO

When a program is executed via the TSO CALL interface, the argument string isparsed looking for commas (,). Each comma separates the argument value.

Unlike UNIX (USS) systems, the parm string is not parsed for spaces, or quotes. Itis simply broken at each instance of a comma.

An alternate character for argument delimiters can be specified by defining the charargvc variable. If that is defined, the runtime uses the specified character as the

delimiter. If the character specified is a space, the runtime will skip multiple spaces.

Thus, the parm string ’my,parms’ would produce two values passed in the argvarray on the invocation of main(). The first would be the string "my", the secondis the string "parms".

Similarly, the parm string ’my space,parms’ would produce two argv elements,"my space" and "parms", because spaces are not a parameter delimiter.

Running programs under BATCH JCL

Systems/C programs can be executed under normal JCL via the typical EXEC JCLstatement.

For example, if the PDS MY.PDS contained a Systems/C program named MYPROGthen the JCL statement:

//RUN EXEC PGM=MY.PDS(MYPROG),PARM=’parm string’

would execute MYPROG passing the parameter string ’parm string’.

argv processing under BATCH

Similar to argument processing under TSO, the Systems/C runtime looks for com-mas to separate arguments. Unlike UNIX or POSIX systems, BATCH mainframeprograms typically use commas as a parameter delimiter. To better integrate intoexisting environments, Systems/C adopts the same approach.

Each comma in the incoming PARM value is taken as a separator to separate theresulting argv values passed to the main() function.

However, just as under TSO, the char argvc variable can indicate a differentcharacter to use as the argument separator. If char argvc is set to a space, theruntime environment will skip adjacent spaces, considering them as one.

26 Systems/C C Library

Page 45: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

Thus, the PARM value ’my,parms’ would produce two values passed in the argvarray on the invocation of main(). The first would be the string "my", the secondis the string "parms".

Similarly, the PARM string ’my space,parms’ would produce two argv elements,"my space" and "parms", because spaces are not a parameter delimiter.

If needed, the double-quote character can be used to group together characters,including a comma. Within a double-quoted string, the back-slash character canbe used to represent the double quote. For example, to produce the argv[] strings"my,parm" and "parm2", the PARM string would be ’"my,parm",parm2’.

Systems/C C Library 27

Page 46: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

28 Systems/C C Library

Page 47: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

Programming for OpenEdition

The Systems/C library supports programs executed under OpenEdition MVS (UnixSystems Servies - USS). Programs can be executed under the USS shell, or takeadvantage of the facilities provided by OpenEdition services, including the variousPOSIX functions and Hierarchical File System (HFS.)

Note that all of the POSIX functions also operate in 64-bit mode.

As noted in the individual function descriptions, many of the POSIX functions areonly supported for HFS files. A POSIX file funtion applied to a non-POSIX file willfail with an appropriate error code.

If Unix System Services are unavailable, the functions will fail with error returncodes when possible.

More recent versions of OpenEdition require re-entrant programs; thus the compileroption –frent must be specified when compiling, and the objects should be linkedwith the re-entrant Systems/C library.

Linking programs under the OpenEdition Shell

Systems/C programs can be linked under the OpenEdition shell; to create loadmodules that reside in the Hierarchical File System (HFS).

To create an HFS load-module, the output from PLINK can be linked using theOpenEdition cc command. The -e // option should be added the cc command toindicate that the entry-point is not the default Language Environment entry pointexpected by cc. The Systems/C runtime library will specify its own entry-point.

For example, to pre-link and link the object myfunc.o and produce the HFS load-module myprog under the OpenEdition shell (assuming /usr/local/dignus is theinstallation location), simply run PLINK:

plink -omyprog.o myfunc.o "-S/usr/local/dignus/objs_rent/&m"

then use the OpenEdition cc command:

Systems/C C Library 29

Page 48: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

cc -e // -omyprog myprog.o

to produce the myprog load-module. myprog can then be invoked as any otherOpenEdition program.

Copying programs from a PDS to the OpenEdition Shell

To copy a program from a PDS or PDSE to the HFS file system, the program mustbe re-linked into the HFS. Unfortunately, the IBM linker will not determine theproper entry-point in this case, and so the Systems/C entry point must be specifiedon the cc command.

To re-link a program from a PDS or PDSE into the HFS, the Systems/C entry-point@crt0 (lower-case) must be specified in the cc command.

For example, if the PDS MYNAME.T.LOAD contained the Systems/C program namedMYPROG, it could be copied into the HFS executabled named myprog with the com-mand:

cc -e @crt0 -omyprog "//’MYNAME.T.LOAD(TEST)’"

Running programs under the OpenEdition Shell

Programs running under the OpenEdition shell are started via the BPX1EXC execservice. Systems/C programs residing in the HFS can simply be run as any otherOpenEdition program.

More recent versions of OpenEdition require re-entrant programs; thus the compileroption –frent must be specified when compiling, and the objects should be linkedwith the re-entrant Systems/C library.

The Systems/C runtime recognizes when the program is started via the exec service,and processes the incoming argument and environment parameters appropriately.The arguments will be presented to the program in the argv array; and the envi-ronment variables will be available via the standard getenv() functions.

Furthermore, when started via exec, the first three file descriptors will be inheritedfrom the invoking process. The Systems/C I/O functions will make these directlyavailable to the program as file descriptors #0, #1 and #2, which are then alsoassociated with FILE * variables stdin, stdout and stderr. Also in this case, thedefault filename style will be set to “//HFS:” so that file names will, by default,refer to files within the Hierarchical File System.

30 Systems/C C Library

Page 49: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

Programming for CMS

The Systems/C library supports a limited CMS environment, taking advantage ofthe OSRUN facility on CMS. The library does not support TCP/IP, or the SFS, butis a basic port of the existing I/O and memory management library used on z/OS.

Linking programs for CMS

To produce an object deck that is eventually linked on CMS, the CMS runtimeobjects must be present on the PLINK command line before the normal objectlibrary specification. This will insert the CMS runtime ahead of the normal runtime.These are the cmsutil, @@iocms, @@ddndec, @@tyqsac and @@ddncms object decksfound in the objs rent and objs norent directories on cross-platform hosts, or theLIBCR and LIBCN PDSs on z/OS.

The Systems/C runtime also makes reference to the DMSSTKR symbol when linking,thus during the PLINK step the –allow ref=DMSSTKR option should be used toaccount for this unresolved reference in the PLINK step.

Once the PLINK step is performed, the resulting object deck can be copied toCMS, and placed in an FB 80 file with the .TEXT file mode.

The CMS linker, LKED can then be used to create a member of a LOADLIB that canbe executed with OSRUN.

Note that Systems/C programs for CMS are currently limited to RMODE=24 execu-tion, because of restrictions in the OS/390 emulation routines.

Using PLINK to create CMS programs

PLINK performs several important tasks for CMS programs.

The CMS linkage editor (LKED) is limited to only 4096 bytes for PRV (PsuedoRegister Vector) processing. PLINK addresses this issue by performing all PRVprocessing, so that the object deck presented to LKED has no PRV references.

Systems/C C Library 31

Page 50: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

LKED also does not handle XSD or GOFF style input. PLINK when the –(px) optionwill properly adjust the resulting object deck to only be ESD-style, shortening longnames and converting the input object decks appropriately.

To create programs for CMS, the CMS runtime support must be specified beforethe normal z/OS runtime libraries.

For example, on a Windows platform, if the typical PLINK command for pre-linking looked like (where the Systems/C installation was in the C:\sysc directory):

plink -px -omy_prog.obj t1.obj t2.obj "-SC:\sysc\objs_rent\&M"

then to link for execution on CMS, we need to insert the CMS runtime objects andspecify the DMSSTKR is allowed to be an unresolved reference:

plink -px -omy_prog.obj t1.obj t2.obj-allow_ref=DMSSTKRC:\sysc\objs_rent\cmsutilC:\sysc\objs_rent\@@iocmsC:\sysc\objs_rent\@@ddndecC:\sysc\objs_rent\@@tyqsacC:\sysc\objs_rent\@@ddnms

"-SC:\sysc\objs_rent\&M"

(note that if the command line becomes too long for Windows, the –@ option canbe used to place command line options in a file. See the PLINK section of theSystems/C Utilities manual for more information.)

To implement the same task when running PLINK on OS/390 or z/OS, simplyadjust the SYSIN stream to specify the CMS runtime object decks.

If the typical PLINK step in the JCL looked like:

...//PLINK EXEC PGM=PLINK,PARM=’-px’//STDERR DD SYSOUT=A//STDOUT DD SYSOUT=A//SYSLIB DD DSN=DIGNUS.LIBCR.OBJ,DISP=SHR//INDD DD DSN=mypds,DISP=SHR//SYSIN DD *INCLUDE INDD(PROG)//SYSMOD DD DSN=myoutput.obj,DISP=NEW

then, to pre-link this program for CMS, adjust the PARM value to include the -allow ref=DMSSTKR and specify the CMS objects in the SYSIN stream, as in:

32 Systems/C C Library

Page 51: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

...//PLINK EXEC PGM=PLINK,PARM=’-px,allow_ref=DMSSTKR’//STDERR DD SYSOUT=A//STDOUT DD SYSOUT=A//SYSLIB DD DSN=DIGNUS.LIBCR.OBJ,DISP=SHR//INDD DD DSN=mypds,DISP=SHR//SYSIN DD *INCLUDE INDD(PROG)INCLUDE SYSLIB(CMSUTIL)INCLUDE SYSLIB(@@IOCMS)INCLUDE SYSLIB(@@DDNDEC)INCLUDE SYSLIB(@@TYQSAC)INCLUDE SYSLIB(@@DDNCMS)//SYSMOD DD DSN=myoutput.obj,DISP=NEW

(note that the –px option was also specified in the PARM string when executingPLINK.)

Using LKED to link CMS programs

After the PLINK step has been executed the resulting object deck should be copiedto CMS and placed into an FB 80 dataset with the TEXT file mode. This can beaccomplished using FTP or any other binary transfer.

Once the PLINK output has been placed on CMS, the LKED command will link itand produce a LOADLIB member which can be executed with OSRUN.

The VMLIB TXTLIB must be GLOBAL’d to resolve references that the Systems/C run-time requires. Also, this library should be specified as the SYSLIB so LKED canresolve those references.

The PLINK generated object deck should be specified as the SYSLIN input to LKED.

Because of limitations in the OSRUN environment, Systems/C programs must belinked with RMODE=24 specified.

For example, if the result of PLINK was placed on the A disk with the file namePROG TEXT A, and the resulting program should reside in the MYLOAD LOADLIB Aload library, these commands would execute LKED to accomplish the linking:

FILEDEF SYSLMOD DISK MYLOAD LOADLIB A (RECFM UGLOBAL TXTLIB VMLIBFILEDEF SYSLIB DISK VMLIB TXTLIB S (PERMFILEDEF SYSLIN DISK PROG TEXT ALKED PROG (RMODE 24 AMODE 31FILEDEF SYSLMOD CLEAR

Systems/C C Library 33

Page 52: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

FILEDEF SYSLIB CLEARFILEDEF SYSLIN CLEAR

Note the RMODE 24 was specified on the LKED command.

Consult the IBM VM/CMS documentation for further information about these com-mands.

Executing programs on CMS

To execute Systems/C programs on CMS, the OSRUN command is used. AppropriateFILEDEFs should be specified as the program may require. Each DD the programopens should be FILEDEF’d so that the open() may succeed.

The PARM option of the OSRUN command specifies any parameters passed to theprogram.

For example, if we intend to execute the program PROG with the parameters,“any,parms”, from the MYLOAD LOADLIB A library, and the program read from theSTDIN DD and wrote to the STDOUT and STDERR DDs, these commands would beemployed:

GLOBAL LOADLIB MYLOADFILEDEF STDIN TERMINALFILEDEF STDOUT TERMINAL (LRECL 133 BLKSIZE 133FILEDEF STDERR TERMINAL (LRECL 133 BLKSIZE 133OSRUN PROG PARM=’any,parms’

Note that the LRECL and BLKSIZE values must be specified on the FILEDEF for CMSfiles. For TERMINAL type files, the LRECL and BLKSIZE should be the same to avoidany block level buffering.

Systems/C programs are limited to the environment supported by OSRUN.

34 Systems/C C Library

Page 53: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

Programming for MVS 3.8

The Systems/C library supports programs for the MVS 3.8 operating system. Gen-erally, the full support of the Systems/C library is available, with the restrictionsinherent in the MVS 3.8 environment.

Linking programs for MVS 3.8

Systems/C supports executing C programs on MVS 3.8 by inserting MVS 3.8 specificobjects in the link step before the normal library objects. These objects replace thenormal library objects, providing MVS 3.8 low-level operating system support. Themodules can be found in the MVS38 objs rent and MVS38 objs norent directorieson cross-platform hosts, or as PDS members in the LIBCR38 and LIBCN38 PDSlibraries on OS/390 and z/OS hosts.

To create MVS 3.8 executables, simple place these directories (or PDSs) in thePLINK search order ahead of the normal library.

Also, for support of long names in external identifiers, the Systems/C library isdelivered in extended object (XSD) form. The MVS 3.8 linker does not support thisform of object deck. Thus, the Systems/C pre-linker, PLINK, must be used andthe –px option of PLINK must be enabled to process these objects and produce anobject deck that is suitable for linking with the MVS 3.8 linker.

If IBM’s HLASM assembler is used to produce the objects, and the XOBJECT param-eter to HLASM is enabled, HLASM will produce object files in the GOFF objectfile format. PLINK can directly process these input files and produce objects thatcan be handled by the MVS 3.8 linker. PLINK, with the –px option, will properlyconvert these files into objects suitable for the MVS 3.8 linker. With this approach,HLASM-produced objects with support for long identifier names can be used tocreate MVS 3.8 programs. For more detailed information about PLINK see theSystems/C Utilities manual.

Systems/C C Library 35

Page 54: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

Using PLINK to create MVS 3.8 programs

As mentioned above, PLINK must be used to pre-link the input objects and placethem in a format suitable for use on MVS 3.8. PLINK’s primary function in thisregard is to convert any long names and or XSD cards in the generated objects toshort names and produce an object file that the MVS 3.8 linker will process. Thus,the –px option should be used on the PLINK command, which instructs PLINKto perform this processing.

Furthermore, for re-entrant programs, PLINK will process all PRV-related opera-tions, processing PR and XD symbols internally. The MVS 3.8 linker cannot handlePRV vectors larger than 4K bytes. The PLINK –prem option, which supports thisfunction, is enabled by default, and should not be disabled when creating MVS 3.8executables.

PLINK is also used to ensure the MVS 3.8 objects are used instead of the normallibrary objects. On cross-platform systems, simply specify the MVS 3.8 objectdirectories ahead of the normal object directoris on the PLINK command line. OnOS/390 or z/OS, specify the MVS 3.8 library PDS ahead, in a concatenation withthe normal library PDS.

On OS/390 or z/OS to link with the MVS 3.8 re-entrant libraries, add theLIBCR38 PDS to the SYSLIB concatenation, otherwise use the LIBCN38 PDS.On cross-platform hosts, to link with the re-entrant MVS 3.8 library, add theMVS38 objs rent directory to the search list, ahead of the normal library speci-fication. To link with the non-re-entrant MVS 3.8, on cross-platform hosts, add theMVS38 objs norent directory.

For example, on a Windows platform, if the typical PLINK command for pre-linking looked like (where the Systems/C installation was in the C:\sysc directory):

plink -omy_prog.obj t1.obj t2.obj "-SC:\sysc\objs_rent\&M"

then to link for execution on MVS 3.8, insert another search template which specifiesthe MVS 3.8 directory, as in:

plink -omy_prog.obj t1.obj t2.obj "-SC:\sysc\MVS38_objs_rent\&M""-SC:\sysc\objs_rent\&M"

(note that if the command line becomes too long for Windows, the –@ option canbe used to place command line options in a file. See the PLINK section of theSystems/C Utilities manual for more information.)

To implement the same task when running PLINK on OS/390 or z/OS, simplyadjust the SYSLIB DD statement to provide the proper concatenation.

If the typical PLINK step in the JCL looked like:

36 Systems/C C Library

Page 55: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

...//PLINK EXEC PGM=PLINK,PARM=’-px’//STDERR DD SYSOUT=A//STDOUT DD SYSOUT=A//SYSLIB DD DSN=DIGNUS.LIBCR.OBJ,DISP=SHR//INDD DD DSN=mypds,DISP=SHR//SYSIN DD *INCLUDE INDD(PROG)//SYSMOD DD DSN=myoutput.obj,DISP=NEW

then, to pre-link this program for MVS 3.8, adjust the SYSLIB DD statement to addthe MVS 3.8 PDS, as in:

...//PLINK EXEC PGM=PLINK,PARM=’-px’//STDERR DD SYSOUT=A//STDOUT DD SYSOUT=A//SYSLIB DD DSN=DIGNUS.LIBCR38.OBJ,DISP=SHR// DD DSN=DIGNUS.LIBCR.OBJ,DISP=SHR//INDD DD DSN=mypds,DISP=SHR//SYSIN DD *INCLUDE INDD(PROG)//SYSMOD DD DSN=myoutput.obj,DISP=NEW

(note that the –px option was specified in the PARM string when executing PLINK.)

MVS 3.8 runtime restrictions

In general, beyond the environmental constraints of an MVS 3.8 system, there areno issues with Systems/C programs. Except for the following noted differences, theentire Systems/C run-time library and all of the Systems/C programming featuresoperate as they would on a more recent operating system.

MVS 3.8 only supports 24-bit addresses, thus Systems/C programs are limited byMVS 3.8’s memory size restrictions.

Dynamic allocation of files via the O CREAT flag on open(2) calls is not supported.

MVS 3.8 does not provide TCP/IP, thus the TCP/IP related functions in the Sys-tems/C library will not operate.

MVS 3.8 does not provide the BPX family of services, thus POSIX functions are notavailable and will fail with an error return code.

Systems/C C Library 37

Page 56: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

MVS 3.8 programs can be executed on OS/390 or z/OS. If the program objectsare re-linked on OS/390 or z/OS, the AMODE=24 and RMODE=24 options should bespecified on the IBM link step, or to the PLINK command if PLINK is creatinga TSO TRANSMIT module. The MVS 3.8 low-level operating system interfacesprovided in the MVS 3.8 objects will not operate correctly on OS/390 or z/OS ifthe program is not linked AMODE=24 and RMODE=24.

38 Systems/C C Library

Page 57: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

Controlling the runtimeenvironment

Runtime Options specified in the program arguments

Runtime options can be specified in the program arguments in a BATCH or TSOprogram, or in the DIG RUNOPTS environment variable in a program running underOpenEdition.

Runtime options are not examined in DCALL environments.

By default, runtime options are disabled in the BATCH and TSO environments, toenable them set the global int runopt variable to 1.

The following runtime options are supported:

ENVAR(name=val) specifies that the environment variable name should be set to thevalue val in the start-up runtime environment.

TRAP(trap-setting) Specifies that a runtime ESTAE should be established for thereceipt of signals generated by hardware interrupts. trap-setting iseither ON or OFF.

Unrecognized options are silently ignored.

Runtime Options in TSO and Batch

In the TSO and BATCH environment, the incoming argument string is examined.All text up to the first backslash () is examined to look for runtime options. The actual program arguments followthis first backslash. If no backslash is present at all, then the entire string is takento be the program arguments. Note that the backslash character can be changedvia the declaration of the global variable rochar, as in:

Systems/C C Library 39

Page 58: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

char __rochar = ’/’; /* set / as the runtime options delimiter */

Previous versions of the Dignus Systems/C runtime use the slash (’/’) character asthe delimiter; but Dignus Systems/C programs use the slash in file names whichfrequently appear as command line arguments (i.e. //DSN:MY.FILE.NAME). Becauseof this the default runtime options delimiter character was changed to backslash.

Furthermore, to avoid other potential issues with older programs, runtime optionsprocessing is off by default in the TSO and BATCH environments. If your programwants to take advantage of runtime options processing in the TSO or BATCH en-vironments, it needs to be specifically enabled by declaring the runopt integer asin:

int __runopt = 1;

Runtime Options in OpenEdition

When running in the OpenEdition environment, the Systems/C library looks forruntime options in the environment variable ” DIG RUNOPTS”. Any runtime optionsare specified there. The incoming argument list is not examined in this environment.

Disabling/Enabling runtime options in TSO and Batch

If you define an integer named runopt at global scope, and give it the value 0;then runtime options processing is disabled, and the entire parameter string will beused.

This is the default behavior.

That is:

int __runopt = 0;

will defeat runtime options processing in TSO and Batch.

To enable runtime options processing in TSO and Batch, set the value of runoptto 1 as in:

int __runopt = 1;

40 Systems/C C Library

Page 59: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

By default, the backslash () character is used to delimit the end of the runtime options and the start of theargument string. You can change this default character by declaring the charactervariable rochar at file scope and initializing it with the character to use. Forexample:

char __rochar = ’|’; /* use | to mark end of runtime options */

stdin, stdout and stderr

According to the C standard definition, three standard streams are initilized andopened when program begins execution, stdin for input, and stdout and stderrfor output.

In Systems/C, streams are implemented in terms of lower-level file descriptors, stdinis associated with file descriptor #0, stdout is associated with file descriptor #1and stderr is associated with file descriptor #2.

Initially, the Systems/C library opens these file descriptors with the names"//DDN:STDIN", "//DDN:STDOUT" and "//DDN:STDERR". "//DDN:STDOUT" and"//DDN:STDERR" are opened with an LRECL=133 and BLKSIZE=1330 by default.

Changing standard filenames at execution time

The standard approach of using the freopen(3) function to reassociate the standardfile streams operates as expected with the Systems/C runtime.

For example, to close and re-open the stdin stream to the SYSIN DD, a programcan simply:

if(!(freopen("//DDN:SYSIN", "r", stdin)) {perror("couldn’t re-open stdin");

}

See the freopen(3) function description for more information.

Changing standard filenames and attributes at compile time

A program can specify alternate strings to change the names the library uses toopen the first three file descriptors.

To change the name, initialize a char * variable with the replacement file name tobe used, as described in the following table:

Systems/C C Library 41

Page 60: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

stdin char * fd0nm = "name";stdout char * fd1nm = "name";stderr char * fd2nm = "name";

When fd0nm, fd1nm, or fd2nm is defined, the library uses the name definedthere as the initial name for file descriptors #0, #1 and #2 respectively.

For example, the following declaration causes the library to associate the SYSIN DDwith file descriptor #0, making it the stdin stream at program start-up:

char *__fd0nm = "//DDN:SYSIN";

To change the default attribute used to open a file, specify an attribute string in thefd0atr, fd1atr or fd2atr global variables. The string specified will be passed

as the attribute parameter to the open(2) invocation at library start-up.

For example, the following declaration will cause the stdout stream, file descriptor#1, to be opened as an FB80 file with a blocksize of 800:

char *__fd1atr = "recfm=fb,lrecl=80,blksize=800";

See the open(2) function description for more information about file attributestrings.

Note that these names are only used when a program is not executed via the BPXexecve interface. If a program is executed from the USS shell, or via the BPXCALLinterface in batch mode, the first 3 file descriptors are inherited from the environmentand the Systems/C library does not invoke open(2) to provide them.

Choosing the TCP/IP interface

By default, the Systems/C runtime library uses the BPX socket interface for imple-mentation of the various TCP/IP-related functions.

Older versions used the EZASMI interface.

You can choose to use the EZASMI interface by defining the bpxso integer variableat a global scope and initializing it with the value 0, as in:

int __bpxso = 0;

Note that if you use the EZASMI interface, socket file descriptors will not be inheritedacross a fork() function call and the file descriptor will be close()’d in the child.

42 Systems/C C Library

Page 61: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

Changing argv delimiters for BATCH and TSO

By default, when a Systems/C program is executed under BATCH or TSO, thedelimiter that separates arguments is the comma, which is typical of these programs.

However, it can be changed to any character by defining the char argvc variablein a program.

When argvc is defined, the runtime library uses the character value specified thereas the argument delimiter.

Furthermore, if argvc is defined as a single space, the runtime will consider adja-cent spaces as one.

Thus, if the program had:

char __argvc = ’ ’;

then the parm string, ’a parm string’, under TSO or BATCH would generate theargv[] array:

argv[1] "a"argv[2] "parm"argv[3] "string"argv[4] NULL

Disabling runtime options for BATCH and TSO

Normally, when executing in a TSO or BATCH environment, any value in the PARMstring up to the first right slash is examined for runtime options.

If needed, you can disable this check by defining the runopt integer variable atglobal scope, with a value of 0, as in:

int __runopt = 0;

If runopt is defined, and it has a zero value, then the initial runtime startupprocessing will not look for any runtime options, and the entire string will be usedto produce the argc and argv values passed to the main() function.

Systems/C C Library 43

Page 62: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

Controlling stack space allocation

The Systems/C runtime library allocates space used at runtime for per-functionareas. This space is the runtime “stack”. The runtime doesn’t allocate a separatespace for each function, instead allocating and managing this space in blocks ofstorage.

The initial block of storage is called the ISTK (initial stack allocation.) If this blockis sufficiently large for the entire run of the program, no other memory will needto be allocated. Creating a sufficiently large block can greatly improve runtimeperformance.

The initial stack allocation can be specified in the #pragma prolkey of the main()or other entry-point function. When the Systems/C library begins execution, it usesthe value specified in the ISTK=n prologue key for the initial allocation size.

For example,

#pragma prolkey(main,"ISTK=4096")main(){

specifies that the initial stack allocated when this program is begun is 4096 bytes.

As a program runs, more stack space may be dynamically required. The Systems/Cruntime system automatically allocates and manages that space as needed. Thisspace is called the extension stack, or ESTK.

However, small and frequent allocations can result in degraded performance. Ifindicated, it may be prudent to specify a particular stack extension on a function,to cause the library to pre-allocate a larger extension should one be needed. Thiscan be done using the ESTK=n prologue key.

For example:

#pragma prolkey(lotsofstack,"ESTK=16384")lotsofstack(){

specifies that when lotsofstack() is invoked, should a stack extension be required,the allocated space will be at least 16384 bytes in size.

44 Systems/C C Library

Page 63: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

Specifying the runtime storage SUBPOOL

By default, the Systems/C runtime allocates stack and heap memory in the defaultsubpool.

However, this can be altered by specifing #pragma prolkey setting SP=n on themain() or other entry-point function.

The subpool value is a numeric.

For example,

#pragma prolkey(main,"DCALL=YES,SP=123")myfunc(){

specifies that memory allocated by the Direct-CALL function myfunc() be allocatedfrom sub-pool #123.

Specifying the runtime KEY

Systems/C programs begin execution in the default key setting. Specifying the#pragma prolkey setting KEY=val will cause the runtime library to switch to thespecified key and begin execution. When the runtime is complete, for example, aDirect-CALL environment terminates, the key will be reset to the value that waspresent on entry to the function.

val can be either the keyword ENTRY or a numeric key value.

For example:

#pragma prolkey(func,"DCALL=YES,KEY=8")func()

specifies that just before func() is invoked, the current hardware protection keysaved, and the set to 8. On return from func(), the key will be restored to thesaved value.

Controlling access to Unix System Services

On z/OS, when a Unix System Service is required the runtime library invokes theappropriate assembler interface. For example, to open a file in the Hierarchical FileSystem (HFS), the runtime library would invoke the BPX1OPN service.

Systems/C C Library 45

Page 64: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

When a Unix System Service is invoked, it causes the z/OS task to become ’dubbed’;which is undesirable in some cases, and simply not allowed in others. In particular,this is not allowed in a CICS environment.

To provide control over this, the runtime library defines an int variable namedNOBPX.

NOBPX is initialized to 0 indicating that Unix System Service functions are allowed.

Assigning any non-zero value to NOBPX will cause the runtime library to disallowUnix System Service functions, failing the function with errno set to ENOSYS.

This can be particularly useful in a Direct-CALL CICS environment, where UnixSystem Service functions are not allowed.

Note that the runtime library may attempt to invoke Unix System Services due toruntime library requirements, even if the user’s program does not directly invokethese services.

Signal Handling

A Systems/C program supports several style of signal management. Using anlibrary-established ESTAE exit to catch signal-producing hardware interrupts, aswell as supporting the OpenEdition ”SIR” style of signal handling.

When a Systems/C program is initiated via an exec(2) function, the OpenEditionstyle of signals is assumed, as this would be in a POSIX environment.

Otherwise, the use of an ESTAE to recognize hardware interrupts and generatea signal is controlled by the TRAP setting on the prologue macro of the main()function. TRAP defaults to OFF (the previous behavior.) Specifying the #pragmaprolkey setting TRAP=ON causes the Systems/C library to establish an ESTAE exitto handle hardware interrupts and raise an appropriate signal.

You can also use the runtime option of ”TRAP(ON)” or ”TRAP(OFF)” to override theprogram setting on the prologue macro.

Note that in a POSIX environment (execution was initiated via exex(2)), an ESTAEexit is required and the setting of the TRAP value will be forced to ON. Also the ESTAEexit is required for pthread processing.

Considerations for SIGABND processing

In the Dignus runtime on z/OS when the ESTAE exit is established, a SIGABNDsignal is raised when an ABEND is issued. The SIGABND can be handled with aSIGABND signal handler established by either the signal(3) or sigaction(2) functions.

46 Systems/C C Library

Page 65: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

The signal hander can use the abendcode(3) and rsncode(3) functions to querythe abend and reason codes associated with the ABEND.

Returning from the signal handler causes the processor state to be restored to theinstruction that caused the ABEND, where the ABEND will be re-issued. If theSIGABND signal handler remains active, then it will be re-invoked, essentially causinga loop. This is consistent with signal processing in UNIX environments.

If the signal state for SIGABND is SIG DFL then normal abend processing will occur(the ABEND will be ”percolated”).

SIG IGN is invalid for SIGABND signals; as a SIGABEND cannot be ignored.

The Dignus stack management routine issues an ABEND 978 for the out-of-stacksituation. To establish a signal handler for that it is necessary to use the sigalt-stack(3) and sigaction(2) functions to provide a separate stack area for executing ofthe handler. Otherwise, an ABEND 978 is immediately percolated as there is nostack on which to execute the signal handler.

An example of how to catch an ABEND 978 is provided in the appendix.

OpenEdition

Linking under OpenEdition

A Systems/C program can either be linked into a PDS, PDSE or into the HiearchicalFile System (HFS.

Under USS, to link a Systems/C program, first the program is processed with theSystems/C pre-linker (PLINK, to produce an output object module. Then, thefinal linking can use the USS cc command to link. To use the cc command link intothe HFS, the “-e //” option should be added.

For example,

plink -o prog1.obj prog1.o -S"objs_rent/&M"cc -e // -o prog1 prog1.obj

would pre-link the program prog1.o including the re-entrant Systems/C libraryobjects, then the “cc -e //” command would complete the link, producing theprogram prog1.

Note that if the library objects need not be present in the HFS; the PLINK com-mand can reference the library PDS, as in:

plink -o prog1.obj prog1.o -S"//DSN:DIGNUS.LIBCR.OBJ(&M)"

Systems/C C Library 47

Page 66: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

Alternatively, a batch linking process can specify that the final output from the IBMbinder reside in the HFS. Simply adjust the SYSLMOD DD definition appropriately. Forexample, to cause the IBM binder to write to the HFS file /users/employee/prog1,an appropriate SYSLMOD definition might be:

//SYSLMOD DD PATH=’/u/rivers/PLINK20/test/prog’,// PATHOPTS=(OWRONLY,OCREAT),// PATHMODE=(SIRWXO,SIRWXG,SIRWXU)

Running under OpenEdition

When a Systems/C program is executed via the exec() function, the Systems/Cruntime start-up processes the command-line arguments in a typical UNIX-stylefashion. Also, the Systems/C runtime correctly initializes the environment valuesfrom the environment pointers specified in the exec() invocation.

The isPosixOn(2) function can be used to determine if the program was started viaexec() and thus, mostly likely, under the OpenEdition shell. For example:

if(isPosixOn()) {printf("I was started under USS\n");

} else {printf("I was started under BATCH or TSO\n");

}

When programs are started via exec(), the default file “style” ( style) is set to"//HFS:". So that any file name which doesn’t explicitly specifically specify adifferent style is assumed to be an //HFS:-style file.

Programs started via exec() inherit the first 3 file descriptors from the parent pro-cess. So the values of fd0nm, fd1nm, fd2nm, fd0atr, fd1atr and fd2atrdo not apply. If a program needs to adjust these default file descriptors, the stan-dard freopen(3) approach should be used. See the freopen(3) function descriptionfor more information.

Programs executing in the OpenEdition environment use BPX-style signal handling.

Data locations

Systems/C data address ranges are not restricted in any fashion, data can re-side above the 2-gigabyte “bar”, or above the 16-megabyte “line” or below the16-megabyte “line”.

48 Systems/C C Library

Page 67: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

Data in Systems/C programs is in three general areas, the “HEAP”, which is dataallocated via malloc() function calls, the “STACK”, which is local data allocatedto each function, and the “PRV”, which contains file-scoped re-entrant data. Alsonote that the library provides a separate mechanism for dynamic management of“heap” memory in a particular address range, via malloc31() and malloc24.

Each of these locations can be specified by additional #pragma prolkey statementson program entry points, either the main() function entry point, or a DCALL entrypoint.

The default locations for the HEAP, STACK and PRV in z/Architecture programs(programs where the main() function was compiled with the –march=zarch optionenabled) is above the 2-gigabyte “bar”. Otherwise, the default is below the 2-gigabyte “bar”.

If the –famode=any, or –famode=31 or –famode=24 option was specified on the com-pilation of the main() function for z/Architecture programs, the default locationswill be below the 2-gigabyte “bar”.

Each of the HEAP, STACK and PRV locations can be specifically defined by addingLOCHEAP=loc, LOCSTACK=loc and LOCPRC=loc to the entry-point’s prologue macro us-ing #pragma prolkey. The values for loc are 24, 31, ANY and 64. ANY is equivalentto 31.

For example, if the following #pragma prolkey was specified for a main() com-piled with –march=zarch, and no –famode option was specified, then the Systems/Cruntime could allocate the PRV and HEAP data above the 2-gigabyte “bar”, butSTACK data would be restricted to below.

#pragma prolkey(main,"LOCSTACK=31")int main(int argc, char *argv[]){...

Stand alone function

The Systems/C and Systems/C++ compilers can be used to create programs thatuse your own entry and exit linkage. Such code cannot be linked with the Systems/Cruntime because the Systems/C runtime assumes that the Systems/C linkage hasbeen employed.

However, some functions can be safely linked into such an environment.

Systems/C C Library 49

Page 68: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

Compiler invoked routines

When not compiling in z/Arch mode (–march=zarch is not specified), the C andC++ compilers use “helper” functions to accomplish some 64-bit arithmetic. Thesefunctions are:

@@MULU64 64-bit unsigned multiply@@MULI64 64-bit signed multiply@@DIVU64 64-bit unsigned divide/modulus@@DIVI64 64-bit signed divide/modulus

These function only assume that register 13 points to a typical save area (80 bytes)and can safely be used in a typical environment. These functions can be found inthe Systems/C library and can be linked with your own code (provided R13 pointsto a typical save area in your own linkage.)

Initializing re-entrant data

When compiling with the —frent option, or more generally, in the presence of anyrent data, the Systems/C and Systems/C++ compilers generate a re-entrant ini-

tialization section which is gathered together by the pre-linker PLINK. PLINKplaces its information in a CSECT named @@RINIT#. If that symbol is not resolved,then the program required no re-entrant initializations.

At initial program start-up, the Systems/C runtime examines this section and, afterallocating the re-entrant data, performs the various initializations indicated.

If it is desired to have initialized re-entrant data within your own runtime environ-ment, then this same operation needs to be performed.

The Systems/C runtime provides the @@SARNTI function (stand-alone re-entrantinitialization) to accomplish this task. After allocating re-entrant data, the programshould initialize the data area to zeros and then invoke @@SARNTI with the addressof the re-entrant data, the PLINK-generated re-entrant initialization section andsome other parameters as described below.

The size of the re-entrant data can be obtained using a CXD relocation.

@@SARNTI is “stand alone” in that it requires no other runtime and uses standardOS linkage. When linked from the 31-bit runtime library @@SARNTI assumes thatR13 points to a typical 80-byte save area, and further assumes that R1 points to atypical OS-linkage parameter block. When linked from the 64-bit runtime library@@SARNTI assumes that R13 is a 64-bit pointer that points to a Format-4 64-bitstyle save area, and that R1 is a 64-bit pointer that points to a parameter blockthat contains 64-bit pointers.

The parameters for @@SARNTI are:

50 Systems/C C Library

Page 69: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

stack address of at least 1024 bytes used for stack spaceprv address of allocated rent dataentries address of PLINK-generated initializers

The first parameter (the stack space used by @@SARNTI) must be a least 1024 byteslong.

The second parameter is the address of the memory allocated to contain the PRV.That memory must be initialized to all zeros before invoking @@SARNTI.

The third parameter is the address of the @@RINIT# section containing the PLINK-generated initialization data.

@@SARNTI returns a zero (0) in register R15 if it is successful, otherwise it returns anon-zero value in R15. The current return codes are:

0 successful initialization4 invalid/unsupported initializers

On return from @@SARNTI the temporary stack space passed as the first parameteris unused by the Systems/C runtime and may be released or reused.

For example, the following snippet of code shows how to allocate the re-entrant datasection for a 31-bit environment, initialize it to zero and then invoke @@SARNTI. The64-bit environment would be similar except that the parameters addressed by R1would be 64-bit pointers.

WXTRN @@RINIT#...L 6,=A(@@RINIT#)LTR 6,6BZ NONE nothing to do?L 4,RENT_SIZEGETMAIN RC,LV=(4) allocate reentrant dataLR 5,1LR 0,1L 1,RENT_SIZELA 14,0(0,0)LA 15,0(0,0)MVCL 0,14 zero-out rent data (assuming it’s not too large)LA 1,PARMSLA 7,STACK stack spaceST 7,0(0,1) first parmLR 7,5 addr of rent dataST 7,4(0,1) 2nd parmLR 7,6 addr of initializersST 7,8(0,1) 3rd parmL 15,=V(@@SARNTI)BALR 14,15

Systems/C C Library 51

Page 70: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

LTR 15,15BZ DONE... problems; initialization failed

NONE DS 0HDONE DS 0H

...RENT_SIZE CXDSTACK DS 0D

DS CL1024 stack spacePARMS DS 0D

DS 1A address of stackDS 1A address of PRVDS 1A address of rent

52 Systems/C C Library

Page 71: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

User ABEND codes issued bythe runtime

The Systems/C library can issue a small number of user ABENDs, due to variousstart-up and other situations where it is impossible to continue running and no otherdiagnostic facility is available.

These diagnostics are issued using the ABEND macro in z/OS, with the given ABENDnumber.

These values should not be employed by user code as they indicate issues particularto the Systems/C runtime environment.

The following list describes the ABEND number and the situation where it arises:

135 A dd number could not be allocated in the table of DD names; this isdeprecated and will be eliminated in a future release.

136 The table for managing DD names cannot be allocated. This is likelydue to insufficent available memory. This is deprecated and will beeliminated in a future release.

178 The initial memory allocation for a dynamic storage area (DSA) set-upfailed, likely due to insufficient available memory, the program cannotrun.

278 The first memory segment allocation failed, likely due to insufficientavailable memory, the program cannot run.

279 Insufficient memory was available to set up the program name, argvarray or environ array at program start-up.

378 Returning the allocated re-entrant variable data space to the operatingsystem failed at program termination. This is likely due to a programmemory overlay detected at the end of execution.

478 Returning an allocated stack segment to the operating system failed.This is likely due to a program memory overlay detected at the endof execution.

Systems/C C Library 53

Page 72: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

555 An invalid or corrupt handle was passed to a DCALL=SUPPLIEDfunction.

578 Returning the initial memory allocation to the operating system failed.This is likely due to a program memory overlay detected at the endof execution.

678 Re-entrant variable initialization failed. This is either a compiler orlibrary problem and should be reported to Dignus.

978 The stack management routines were unable to allocate further mem-ory to expand the stack segment. ABEND 978 can be ”caught”by a SIGABND handler only if the library has established as ESTAE(TRAP(ON) is true) and an alternate execution stack is provided forthe signal handling function.

801 64-bit program start failed. This is typically caused by linking codecompiled for 31-bit with the 64-bit Dignus runtime. When linking withthe 64-bit runtime, the –mlp64 option must be used on the DCC andDCXX compiler command lines.

54 Systems/C C Library

Page 73: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

Systems/C C Library functions

The Systems/C library provides the ANSI standard functions, as well as severalextensions which aide in the porting of other programs to the mainframe.

The Systems/C library is compiled using the standard Systems/C prologue andepilogue macros. The Systems/C library environment would need to be establishedif these functions are to be included in a Systems/C program that uses an alternatestack frame layout.

This section provides an overview of the C library functions, the return values andother common definitions and concepts.

The function return types and parameters, as well as the requisite #include filesare described in the SYNOPSIS section. The function is then described, followed bythe possible values of the global variable errno. Also, related functions are namedin the SEE ALSO section. If the function conforms to any particular standards,that will be noted in the STANDARDS section.

The run-time library is also divided into sections for easy reference.

Systems/C C Library 55

Page 74: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

System Functions

System functions are those that are typically implemented by the operating systemon UNIX platforms.

These are implemented in the Systems/C C run-time library as best as the hostoperating system allows.

Several of the system functions described below depend on IBM’s OpenEdition As-sembler Callable Services. If these services are not available, the functions can fail,typically setting the global variable errno to EOPNOTSUPP (operation is not sup-ported.) For more information about OpenEdition services, see the IBM “OS/390OpenEdition Assembler Callable Services” manual and related IBM documentation.

56 Systems/C C Library

Page 75: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

ACCESS(2)

NAME

access – check access permissions of an //HFS:-style file or pathname

SYNOPSIS

#include <unistd.h>

intaccess(const char *path, int mode);

DESCRIPTION

The access() function checks the accessibility of the file named by path for theaccess permissions indicated by mode. The value of mode is the bitwise inclusiveOR of the access permissions to be checked (R OK for read permission, W OK for writepermission and X OK for execute/search permission) or the existence test, F OK. Allcomponents of the pathname path are checked for access permissions (includingF OK).

RETURN VALUES

If path cannot be found or if any of the desired access modes would not be granted,then a -1 value is returned; otherwise a 0 value is returned.

ERRORS

Access to the file is denied if:

[ENOTDIR] A component of the path prefix is not a directory.

[ENAMETOOLONG] A component of a pathname exceeded 255 characters, or an entirepath name exceeded 1023 characters.

[ENOENT] The named file does not exist.

[ELOOP] Too many symbolic links were encountered in translating the path-name.

[EROFS] Write access is requested for a file on a read-only file system.

Systems/C C Library 57

Page 76: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

[ETXTBSY] Write access is requested for a pure procedure (shared text) filepresently being executed.

[EACCES] Permission bits of the file mode do not permit the requested access,or search permission is denied on a component of the path pre-fix. The owner of a file has permission checked with respect to the“owner” read, write, and execute mode bits, members of the file’sgroup other than the owner have permission checked with respectto the “group” mode bits, and all others have permissions checkedwith respect to the “other” mode bits.

[EFAULT] Path points outside the process’s allocated address space.

[EIO] An I/O error occurred while reading from or writing to the filesystem.

[ENOTSUPP] The access() function is not supported on this type of path name.

SEE ALSO

chmod(2), open(2), stat(2)

STANDARDS

The access() function call is expected to conform to IEEE Std1003.1-1990(“POSIX”) for a path in the HFS.

CAVEAT

access() is a potential security hole due to race conditions and should never be used.Setuid and setgid applications should restore the effective uid or gid and performactions directly rather than use access() to simulate access checks for the real userof group id.

access() only operates on //HFS:-style files. If the access() function is applied tonon-//HFS: style files, the return value will be set to -1, and errno will be set toEOPNOTSUPP.

58 Systems/C C Library

Page 77: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

CHDIR(2)

NAME

chdir, fchdir - change current //HFS:-style working directory

SYNOPSIS

#include <unistd.h>

intchdir(const char *path);

intfchdir(int fd);

DESCRIPTION

The path argument points to the pathname of a directory. The chdir() functioncauses the named directory to become the current working directory, that is, thestarting point for path searches of pathnames not beginning with a slash, ‘/’.

The fchdir() function causes the directory referenced by fd to become the currentworking directory, the starting point for path searches of pathnames not beginningwith a slash, ‘/’.

In order for a directory to become the current directory, a process must have execute(search) access to the directory.

RETURN VALUES

Upon successful completion, the value 0 is returned; otherwise the value -1 is re-turned and the global variable errno is set to indicate the error.

ERRORS

chdir() will fail and the current working directory will be unchanged if one or moreof the following are true:

[ENOTDIR] A component of the path prefix is not a directory.

Systems/C C Library 59

Page 78: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

[ENAMETOOLONG] A component of a pathname exceeded 255 characters, or an entirepath name exceeded 1023 characters.

[ENOENT] The named directory does not exist.

[ELOOP] Too many symbolic links were encountered in translating the path-name.

[EACCES] Search permission is denied for any component of the path name.

[EFAULT] Path points outside the process’s allocated address space.

[EIO] An I/O error occurred while reading from or writing to the filesystem.

fchdir() will fail and the current working directory will be unchanged if one or moreof the following are true:

[EACCES] Search permission is denied for the directory referenced by the filedescriptor.

[ENOTDIR] The file descriptor does not reference a directory.

[EBADF] The argument fd is not a valid file descriptor.

SEE ALSO

chroot(2)

STANDARDS

The chdir() function call is expected to conform to ISO/IEC 9945-1:1990(“POSIX.1”).

60 Systems/C C Library

Page 79: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

CHMOD(2)

NAME

chmod, fchmod - change mode of an //HFS:-style file

SYNOPSIS

#include <sys/stat.h>

intchmod(const char *path, mode_t mode);

intfchmod(int fd, mode_t mode);

DESCRIPTION

The file permission bits of the file named specified by path or referenced by the filedescriptor fd are changed to mode. The chmod() function verifies that the processowner (user) either owns the file specified by path (or fd), or is the super-user. Thechmod() function follows symbolic links to operate on the target of the link ratherthan the link itself.

A mode is created from or’d permission bit masks defined in <sys/stat.h>:

#define S_IRWXU 0000700 /* RWX mask for owner */#define S_IRUSR 0000400 /* R for owner */#define S_IWUSR 0000200 /* W for owner */#define S_IXUSR 0000100 /* X for owner */

#define S_IRWXG 0000070 /* RWX mask for group */#define S_IRGRP 0000040 /* R for group */#define S_IWGRP 0000020 /* W for group */#define S_IXGRP 0000010 /* X for group */

#define S_IRWXO 0000007 /* RWX mask for other */#define S_IROTH 0000004 /* R for other */#define S_IWOTH 0000002 /* W for other */#define S_IXOTH 0000001 /* X for other */

#define S_ISUID 0004000 /* set user id on execution */#define S_ISGID 0002000 /* set group id on execution */#define S_ISVTX 0001000 /* sticky bit */

Systems/C C Library 61

Page 80: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

#ifndef _POSIX_SOURCE#define S_ISTXT 0001000#endif

Setting the S ISUID bit indicates that when the file is executed, the process’s effectiveuser-id is set to the file’s owner user-id, so that the process appears to be runningunder the user-id of the file’s owner.

Settin the S ISGID bit indicates that when the file is executed, the process’s effectivegroup-id is that of file’s owner group-id.

RETURN VALUE

Upon successful completion, the value 0 is returned; otherwise the value -1 is re-turned and the global variable errno is set to indicate the error.

ERRORS

chmod() will fail and the file mode will be unchanged if:

[ENOTDIR] A component of the path prefix is not a directory.

[ENAMETOOLONG] A component of a pathname exceeded 255 characters, or an entirepath name exceeded 1023 characters.

[ENOENT] The named file does not exist.

[EACCES] Search permission is denied for a component of the path prefix.

[ELOOP] Too many symbolic links were encountered in translating the path-name.

[EPERM] The effective user ID does not match the owner of the file and theeffective user ID is not the super-user.

[EROFS] The named file resides on a read-only file system.

[EFAULT] Path points outside the process’s allocated address space.

[EIO] An I/O error occurred while reading from or writing to the filesystem.

fchmod() will fail if:

[EBADF] The descriptor is not valid.

62 Systems/C C Library

Page 81: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

[EINVAL] fd refers to a socket, not to a file.

[EROFS] The file resides on a read-only file system.

[EIO] An I/O error occurred while reading from or writing to the filesystem.

SEE ALSO

chown(2), open(2), stat(2)

STANDARDS

The chmod() function call is expected to conform to ISO/IEC 9945-1:1990(“POSIX.1”).

Systems/C C Library 63

Page 82: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

CHOWN(2)

NAME

chown, fchown, lchown – change owner and group of an //HFS:-style file

SYNOPSIS

#include <unistd.h>

intchown(const char *path, uid_t owner, gid_t group);

intfchown(int fd, uid_t owner, gid_t group);

intlchown(const char *path, uid_t owner, gid_t group);

DESCRIPTION

The owner ID and group ID of the file named by path or referenced by fd is changedas specified by the arguments owner and group. The owner of a file may change thegroup to a group of which he or she is a member, but the change owner capabilityis restricted to the super-user.

chown() clears the set-user-id and set-group-id bits on the file to prevent accidentalor mischievous creation of set-user-id and set-group-id programs if not executed bythe super-user. chown() follows symbolic links to operate on the target of the linkrather than the link itself.

lchown() is similar to chown() but does not follow symbolic links.

One of the owner or group id’s may be left unchanged by specifying it as -1.

RETURN VALUES

Upon successful completion, the value 0 is returned; otherwise the value -1 is re-turned and the global variable errno is set to indicate the error.

64 Systems/C C Library

Page 83: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

ERRORS

chown() and lchown() will fail and the file will be unchanged if:

[ENOTDIR] A component of the path prefix is not a directory.

[ENAMETOOLONG] A component of a pathname exceeded 255 characters, or an entirepath name exceeded 1023 characters.

[ENOENT] The named file does not exist.

[EACCES] Search permission is denied for a component of the path prefix.

[ELOOP] Too many symbolic links were encountered in translating the path-name.

[EPERM] The effective user ID is not the super-user.

[EROFS] The named file resides on a read-only file system.

[EFAULT] Path points outside the process’s allocated address space.

[EIO] An I/O error occurred while reading from or writing to the filesystem.

fchown() will fail if:

[EBADF] fd does not refer to a valid descriptor.

[EINVAL] fd refers to a socket, not a file.

[EPERM] The effective user ID is not the super-user.

[EROFS] The named file resides on a read-only file system.

[EIO] An I/O error occurred while reading from or writing to the filesystem.

SEE ALSO

chmod(2)

STANDARDS

The chown() function call is expected to conform to ISO/IEC 9945-1:1990(“POSIX.1”).

Systems/C C Library 65

Page 84: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

CHROOT(2)

NAME

chroot - change root directory

SYSNOPSIS

#include <unistd.h>

intchroot(const char *dirname);

DESCRIPTION

dirname is the address of the pathname of an //HFS:-style directory, terminated byan ASCII NUL. chroot() causes dirname to become the root directory, that is, thestarting point for path searches of pathnames beginning with ‘/’.

In order for a directory to become the root directory a process must have execute(search) access for that directory.

It should be noted that chroot() has no effect on the process’s current directory.

This call is restricted to the super-user.

Upon successful completion, a value of 0 is returned. Otherwise, a value of -1 isreturned and errno is set to indicate an error.

ERRORS

chroot() will fail and the root directory will be unchanged if:

[ENOTDIR] A component of the path name is not a directory.

[EPERM] The effective user ID is not the super-user, or one or more file de-scriptors are open directories.

[ENAMETOOLONG] A component of a pathname exceeded 255 characters, or an entirepath name exceeded 1023 characters.

[ENOENT] The named directory does not exist.

[EACCES] Search permission is denied for any component of the path name.

66 Systems/C C Library

Page 85: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

[ELOOP] Too many symbolic links were encountered in translating the path-name.

[EFAULT] dirname points outside the process’s allocated address space.

[EIO] An I/O error occurred while reading from or writing to the filesystem.

SEE ALSO

chdir(2)

Systems/C C Library 67

Page 86: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

CLOCK GETTIME(2)

NAME

clock gettime, clock settime, clock getres – get/set/calibrate date and time

SYNOPSIS

#include <sys/time.h>

intclock_gettime(clockid_t clock_id, struct timespec *tp);

intclock_settime(clockid_t clock_id, const struct timespec *tp);

intclock_getres(clockid_t clock_id, struct timespec *tp);

DESCRIPTION

The clock gettime() and clock settime() allow the calling process to retrieve orset the value used by a clock which is specified by clock id.

Only the CLOCK REALTIME clock is supported by this implementation. The clock idargument can only be that value. The CLOCK REALTIME clock increments as a wallclock should.

The structure pointed to by tp is defined in ¡sys/time.h¿ as:

struct timespec {time_t tv_sec; /* seconds */long tv_nsec; /* and nanoseconds */

};

The system TOD clock is set during the initial program load or via operator com-mands. The clock settime() function verifies its arguments but always returns an-1 with errno set to EPERM.

The resolution (granularity) of a clock is returned by the clock getres() systemcall. This value is placed in a (non-NULL) *tp.

68 Systems/C C Library

Page 87: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

RETURN VALUES

Upon successful completion, the value 0 is returned; otherwise the value -1 is re-turned and the global variable errno is set to indicate the error.

ERRORS

The following error codes may be set in errno:

[EINVAL] The clock id argument was not a valid value.

[EFAULT] The *tp argument address referenced invalid memory.

[EPERM] The process is not allowed to set the time.

SEE ALSO

ctime(3)

STANDARDS

The clock gettime(), clock settime(), and clock getres() system calls conformto IEEE Std 1003.1b-1993 (“POSIX.1”).

Systems/C C Library 69

Page 88: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

CLOSE(2)

NAME

close - delete a descriptor

SYNOPSIS

#include <unistd.h>

intclose(int d);

DESCRIPTION

The close() call deletes a descriptor from the per-process object reference table. Ifthis is the last reference to the underlying object, the object will be deactivated. Forexample, on the last close of a file the current seek pointer associated with the fileis lost; on the last close of a socket(2) associated naming information and queueddata are discarded.

When a process exits, all associated file descriptors are freed, but since there is alimit on active descriptors per processes, the close() function call is useful when alarge quantity of file descriptors are being handled.

RETURN VALUES

Upon successful completion, a value of 0 is returned. Otherwise, a value of -1 isreturned and the global integer variable errno is set to indicate the error.

IMPLEMENTATION NOTES

When closing a file that has a partial written record, Systems/C will pad the recordto the LRECL size and write the data. The padding byte used depends on howthe file was opened. For O TEXT files, the padding byte is the space character. Fornon-O TEXT files, the padding byte is the NUL character, zero.

ERRORS

close() will fail if:

70 Systems/C C Library

Page 89: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

[EBADF] d is not an active descriptor.

[EINTR] An interrupt was received.

SEE ALSO

fcntl(2), open(2),

STANDARDS

The close() function call is expected to conform to IEEE Std1003.1-1990(“POSIX”), as closely as possible given the host operating system environment.

Systems/C C Library 71

Page 90: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

DCALL ENV(2)

NAME

dcall env - retrieve direct-call environment pointer

SYNOPSIS

#include <machine/dcall.h>

void * __dcall_env(void)

DESCRIPTION

The dcall env() function returns the current environment pointer which can beused by subsequent

DCALL=SUPPLIED

functions.

The dcall env() function is typically used in the

DCALL=ALLOCATE

function to make the environment pointer available to the allocation function tosave for later use.

72 Systems/C C Library

Page 91: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

DDNFIND(2)

NAME

ddnfind, ddnext - determine DSN’s associated with a DD name.

SYNOPSIS

#include <machine/syscio.h>

void *ddnfind(char *ddn, char *dsn);

void *ddnnext(void *token, char *dsn);

DESCRIPTION

The ddnfind() and ddnnext() functions are used to retrieve a DATA SET name(DSN) name(s) allocated to a DD name (DD). ddnfind() retrieves the first DSN as-sociated with the DD ddn, and saves it in the location specified by dsn. ddnfind()returns a token, which is then passed to subsequent calls to ddnnext(). The Sys-tems/C file prefix (//DDN:) should not be specified in the ddn parameter.

ddnnext() is used to retrieve subsequent DSNs associated with the DD ddn.ddnnext() accepts the token created from the ddnfind() function, and returnsthe token that should be used on a subsequent call to ddnnext().

When the list of DSNs has been exhausted, dnnext() returns NULL and releases thespace associated with token.

The storage allocated for dsn should be sufficiently large to contain any valid DSNname. The Systems/C file prefix (//DSN:) is not returned in dsn.

IMPLEMENTATION NOTES

The ddnfind() and ddnnext() functions examine the job JFCB control block todetermine the associated DSN. If the DD is associated with a HFS file, then thereturned name will appear as “...PATH=.SPECIFIED...”.

Systems/C C Library 73

Page 92: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

RETURN VALUES

ddnfind() returns a pointer to the allocate token if the ddn is located, NULL if theddn does not exist, or (void *)(-1) if there insufficient space to allocate the token.If successful, ddnfind() places the first DSN name in the storage addressed by dsn.

ddnnext() returns the token and places the DSN name in the storage addressed bydsn. At the end of the list of DSN names, ddnnext() returns NULL.

SEE ALSO

osddinfo(2)

74 Systems/C C Library

Page 93: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

DYNALL(2)

NAME

dynalloc - allocate a data set

SYNOPSIS

#include <machine/dynit.h>

int__dynall(__dyn_t *parms);

intdynalloc(__dyn_t *parms);

int__dynfre(__dyn_t *parms);

intdynfree(__dyn_t *parms);

void__dyninit(__dyn_t *parms);

DESCRIPTION

The dynall function is used to dynamically allocate MVS data sets, dynfre isused to unallocate an MVS data set. dynalloc is an alias for dynall and dynfreeis an alias for dynfre.

dynall creates the SVC 99 parameter list based on the fields of the incoming parmsstructure and then employs the SVC 99 facility to invoke the allocate function.

dynfre creates the SVC 99 parameter list based on the fields of the incoming parmsstructure and then employs the SVC 99 facility to invoke the deallocate function.

In each case, the parms argument points to a dyn t structure that contains thefollowing fields:

char *ddname DD name. If the string is 8 question marks, then it indicates the areawhere the system-generated ddname is returned, otherwise the stringis truncated at 8 characters and upper-cased before being passed tothe SVC 99 interface.

Systems/C C Library 75

Page 94: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

char *dsname data set name. The string has a maximum length of 1023 charactersand is upper cased before being passed to the SVC 99 interface.

int sysout sysout dataset, set to DEF CLASS for the default SYSOUT class

char *sysoutname program name for SYSOUT

char *member member name of a PDS/PDSE

int status data set status, can be one of the following:

DISP OLD

DISP MOD

DISP NEW

DISP SHR

int normdisp data set’s normal disposition, can be on of:

DISP UNCATLG

DISP CATLG

DISP DELETE

DISP KEEP

int conddisp data set’s conditional disposition, can be one of the following:

DISP UNCATLG

DISP CATLG

DISP DELETE

DISP KEEP

char *unit unit name

char *volser a comma-separated list of volume serial numbers

int volseq volume sequence number

int volcount maximum volume count

int label type of tape label , can be one of the following:

LABEL NL no label

LABEL SL IBM standard label

LABEL NSL non-standard label

LABEL SUL both IBM standard and user label

LABEL BLP bypass label processing

LABEL LTM check and bypass leading tape mark

LABEL AL ANSI standard label

LABEL AUL ANSI standard and user label

76 Systems/C C Library

Page 95: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

int dsorg data set organization, can be one of the following:

DSORG unknown unknown organization

DSORG U unmoveable

DSORG VSAM VSAM

DSORG GS graphics

DSORG PO partioned organization

DSORG POU partioned organization unmoveable

DSORG MQ message processing queue

DSORG CQ direct access message queue

DSORG CX communication line group

DSORG DA direct access

DSORG DAU direct access unmoveable

DSORG PS phsyical sequential

DSORG PSU phsyical sequential unmoveable

DSORG IS indexed sequential (deprecated)

DSORG ISU indexed sequential unmoveable (deprecated)

int alcunit unit of space allocation, one of the following:

CYL Cylinders

TRK Tracks

int primary primary space allocation

int secondary secondary space allocation

int recfm record format, one of, or a combination of the following,

M

A

S

B

D

V

F

U

FB

VB

FBS

VBS

long long blksize block size

Systems/C C Library 77

Page 96: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

int lrecl logical record length, 0x8000 indicates ’X’ for BSAM and QSAM al-locations.

char *volrefds volume serial reference

char *dcbrefds DSNAME for DCB reference

char *dcbrefdd DDNAME for DCB reference

unsigned int flags miscellaneous flags, a combination of the following:

CLOSE close on free

RELEASE release unused space

PERM

CONTIG request contiguous space

ROUND round allocation sizes

TERM device is a terminal

DUMMY DSN

HOLDQ

WAIT

char *password data set password

int dirblk number of directory blocks

int avgblk average block length

char *storclass SMS storage class

char *mgntclass SMS management class

char *dataclass SMS data class

int recorg VSAM dataset organization , one of the following:

KS

ES

RR

LS

int keylength VSAM key length

int keyoffset VSAM key offset

int rls VSAM record level sharing flags, one of the following:

RLS NRI no read integrity

RLS CR consistent read

RLS CRE consistent read explicit

78 Systems/C C Library

Page 97: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

char *refdd copy attributes from referenced DDNAME

char *like copy attributes from DSNAME

int dsntype Type attribute of PDS or PDSE, one of the following:

DSNT LARGE large format, greater than 65535 trks

DSNT BASIC basic format data set

DSNT EXTPREF extended format preferred

DSNT EXTREQ extended format required

DSNT HFS HFS file system

DSNT PIPE FIFO special pipe

DSNT PDS PDS

DSNT LIBRARY PDSE

char *pathame path name

int pathopts path options, one of the following:

PATH OSYNC

PATH OCREAT

PATH OEXCL

PATH ONOCTTY

PATH OTRUNC

PATH OAPPEND

PATH ONONBLOCK

PATH ORDWR

PATH ORDONLY

PATH OWRONLY

int pathmode path mode, one or a combination of the following:

PATH SISUID

PATH SIGUID

PATH SIRUSR

PATH SIWUSR

PATH SIXUSR

PATH SIRWXU

PATH SIRGRP

PATH SIWGRP

PATH SIXGRP

PATH SIWRXG

PATH SIROTH

Systems/C C Library 79

Page 98: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

PATH SIWOTH

PATH SIXOTH

PATH SIWRXO

int pathndisp path normal disposition, can be one of the following:

DISP DELETE

DISP KEEP

int pathcdisp path conditional disposition , can be one of the following:

DISP DELETE

DISP KEEP

char * ptr31 * ptr31 miscitems extra text units

struct S99RBX * ptr31 rbx SVC99 RBX (request block extension) pointer

struct S99EMPARMS * ptr31 emsparmlist pointer to messages

int infocode SVC 99 returned info code

int errcode SVC 99 returned error code

The dyn t structure must be initialized before invoking dynall or dynfre. Thisis accomplised using the dyninit macro, or by using the DYN T INITIALIZERmacro. Unpredictable results may occur if the structure isn’t properly initialized.

The miscitems, rbx and emsparmlist fields can be used to pass additional informationto underlying SVC99 service. For more information about these, and the underly-ing SVC99 service, consult the IBM ”z/OS MVS Programm Authorized AssemblerServices Guide” and the svc99(2) documentation.

The dynfre function deallocates a z/OS data set based on the values passed viathe parms parameter. The only fields in the given dyn t structure used by dynfreare:

char *ddname

char *dsname

char *member

char *pathname

char *normdisp

char *pathndisp

char *miscitems

all other fields are ignored.

80 Systems/C C Library

Page 99: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

EXAMPLES

This program dynamically allocates a file named ”MYNAME.MY.DATASET”, withan allocation unit of CYL, a primary quantity of 2 and a secondary quantity of 1,with a logical record length of 121, a block size of 12100 and a fixed record ASAformat.

#include <stdio.h>#include <stdlib.h>#include <string.h>#include <machine/dynit.h>#include <machine/svc99.h>

int main () {__dyn_t ip;

__dyninit(&ip);

ip.ddname = "mydd"; /* MYDD DD */ip.dsname = "MYNAME.MY.DATASET"; /* DSN=’MYNAME.MY.DATASET’ */ip.status = __DISP_NEW; /* DISP=(NEW,CATLG) */ip.normdisp = __DISP_CATLG;ip.alcunit = __CYL; /* SPACE=(CYL,(2,1)), */ip.primary = 2;ip.secondary = 1;ip.dirblk = 1;ip.flags = __RELEASE & __CONTIG; /* RLSE,CONTIG) */ip.dsorg = __DSORG_PO; /* DCB=(DSORG=PO, */ip.recfm = _F_ + _B_ + _A_; /* RECFM=FBA, */ip.lrecl = 121; /* LRECL=121, */ip.blksize = 12100; /* BLKSIZE=12100) */

if (dynalloc(&ip) != 0) {int err, inf;err = ip.errcode;inf = ip.infocode;printf("Dynalloc failed with error code 0x%04x (%d), "

"info code 0x%04x (%d)\n", err, inf);}

}

To deallocate a file:

#include <stdio.h>

Systems/C C Library 81

Page 100: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

#include <stdlib.h>#include <string.h>#include <machine/dynit.h>

intmain(void){__dyn_t ip = __DYN_T_INITIALIZER;

ip.ddname = "mydd";dynfree(&ip);

}

RETURN VALUES

The dynalloc() function returns -1 if it was unable to allocate enough memory tobuild the parameters for the svc99() function.

Otherwise, it returns the return code from the invocation of svc99().

ISSUES

The dynalloc and dynfree functions are only available on z/OS.

SEE ALSO

”z/OS MVS Programm Authorized Assembler Services Guide”, malloc31(3),svc99(3).

82 Systems/C C Library

Page 101: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

DUP(2)

NAME

dup, dup2 - duplicate an existing file descriptor

SYNOPSIS

#include <unistd.h>

intdup(int olddd)

intdup2(int olddd, int newdd)

DESCRIPTION

dup() duplicates an existing object descriptor and returns its value to the callingprocess (newd = dup(oldd)). The argument oldd is a small non-negative integerindex in the per-process descriptor table. The value must be less than the size ofthe table, which is returned by getdtablesize(2). The new descriptor returned bythe call is the lowest numbered descriptor currently not in use by the process.

The object referenced by the descriptor does not distinguish between oldd and newdin any way. Thus if newd and oldd are duplicate references to an open file, read(2),write(2) and lseek(2) calls all move a single pointer into the file, and append mode,non-blocking I/O and synchronous I/O options are shared between the references.If a separate pointer into the file is desired, a different object reference to the filemust be obtained by issuing an additional open(2) call.

In dup2(), the value of the new descriptor newd is specified. If this descriptor isalready in use and oldd != newd, the descriptor is first deallocated as if a close(2)call had been used. If oldd is not a valid descriptor, then newd is not closed. If oldd== newd and oldd is a valid descriptor, then dup2() is successful, and does nothing.

RETURN VALUES

The value -1 is returned if an error occurs in either call. The external variableerrno indicates the cause of the error.

Systems/C C Library 83

Page 102: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

ERRORS

dup() and dup2() fail if:

[EBADF] oldd or newd is not a valid active descriptor.

[EMFILE] Too many descriptors are active.

[ENOMEM] Insufficient memory was available.

SEE ALSO

close(2), fcntl(2), getdtablesize(2), open(2)

STANDARDS

The dup() and dup2() function calls are expected to conform to IEEE Std1003.1-1990 (“POSIX”), as closely as possible given the constraints of the host operatingsystem.

84 Systems/C C Library

Page 103: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

EXECVE(2)

NAME

execve - execute a file

SYNOPSIS

#include <unistd.h>

intexecve(const char *path, char *const argv[], char *const envp[]);

DESCRIPTION

execve() transforms the calling process into a new process. The new process isconstructed from an ordinary //HFS:-style file, whose name is pointed to by path,called the new process file. This file is either an executable object file, or a file ofdata for an interpreter.

An interpreter file begins with a line of the form:

#! <interpreter> [<arg>]

When an interpreted file is is execve()’d, the system actually execve’s the spec-ified interpreter. If the optional arg is specified, it becomes the first argument tothe interpreter, and the name of the originally execve()’d file becomes the sec-ond argument; otherwise, the name of the originally execve()’d file becomes thefirst argument. The original arguments are shifted over to become the subsequentarguments. The zero’th argument is set to the specified interpreter.

The argument argv is a pointer to a NULL-terminated array of character pointers tonul-terminated character strings. These strings construct the argument list to bemade available to the new process. At least one argument must be present in thearray; by custom, the first element should be the name of the executed program (forexample, the last component of path).

The argument envp is also a pointer to a NULL-terminated array of character pointersto nul-terminated strings. A pointer to this array is normally stored in the globalvariable environ. These strings pass information to the new process that is notdirectly an argument to the command.

//HFS:-style file descriptors open in the calling process image remain open in the newprocess image, except for those for which the close-on-exec flag is set (see close(2)

Systems/C C Library 85

Page 104: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

and fcntl(2)). File descriptors not associated with //HFS:-style files are closed asif the close-on-exec flag was set. Descriptors that remain open are unaffected byexecve().

Signals set to be ignored in the calling process are set to be ignored in the newprocess. Signals which are set to be caught in the calling process image are set todefault action in the new process image. Blocked signals remain blocked regardlessof changes to the signal action. The signal stack is reset to be undefined.

If the set-user-ID mode bit of the new process image file is set (see chmod(2)),the effective user ID of the new process image is set to the owner ID of the newprocess image file. If the set-group-ID mode bit of the new process image file isset, the effective group ID of the new process image is set to the group ID of thenew process image file. (The effective group ID is the first element of the grouplist.) The real user ID, real group ID and other group IDs of the new process imageremain the same as the calling process image. After any set-user-ID and set-group-ID processing, the effective user ID is recorded as the saved set-user-ID, and theeffective group ID is recorded as the saved set- group-ID. These values may be usedin changing the effective IDs later (see setuid(2)).

The set-ID bits are not honored if the respective file system has the SSTFNOSUIDoption enabled or if the new process file is an interpreter file.

The new process also inherits the following attributes from the calling process:

process ID see getpid(2)

parent process ID see getppid(2)

process group ID see getpgrp(2)

access groups see getgroups(2)

working directory see chdir(2)

root directory see chroot(2)

control terminal

resource usages see getrusage(2)

interval timers

resource limits see getrlimit(2)

file mode mask see umask(2)

signal mask

When a program is executed as a result of an execve() call, the lower-level servicepasses a parameter list, which is pointed to by regiter 1. The parameter list consistsof the following parameter addresses, with the high-order bit set in the last value.

86 Systems/C C Library

Page 105: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

R1 Parameter list_______ _________________________|@Plist |______ ____ |@Argument count |______ Argument count|_______| | |_________________________|

| |@Argument length list |______ Argument length list| |_________________________|| |@Argument data list |______ Argument data list| |_________________________|| |@Environment count |______ Environment count| |_________________________|| |@Environment length list |______ Environment length| |_________________________|| |@Environment data list |______ Environment data list| |_________________________||_____|@Plist (high_order = ’1’)|______ Parameter list

|_________________________| (Self_pointer)

The Systems/C runtime recognizes this entry style and transforms the parametersinto the standard:

main(argc, argv, envp)int argc;char **argv, **envp;

where argc is the number of elements in argv (the “arg count”) and argv points tothe array of character pointers to the arguments themselves.

For entry into Systems/C programs, the argv and envp array elements are assumedto be nul-terminated.

RETURN VALUES

As the execve() function overlays the current process image with a new processimage the successful call has no process to return to. If execve() does return tothe calling process an error has occurred; the return value will be -1 and the globalvariable errno is set to indicate the error.

ERRRORS

execve() will fail and return to the calling process if:

[ENOTDIR] A component of either path prefix is not a directory.

Systems/C C Library 87

Page 106: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

[ENAMETOOLONG] A component of a pathname exceeded 255 characters, or an entirepath name exceeded 1023 characters.

[ENAMETOOLONG] When invoking an interpreted script, the interpreter name exceedsMAXSHELLCMDLEN characters.

[ENOENT] The new process file does not exist.

[ELOOP] Too many symbolic links were encountered in translating the path-name.

[EACCES] Search permission is denied for a component of the path prefix.

[EACCES] The new process file is not an ordinary file.

[EACCES] The new process file mode denies execute permission.

[ENOEXEC] The new process file has the appropriate access permission, but isnot in the proper format to be a process image.

[ENOMEM] The new process requires more virtual memory than is allowed bythe imposed maximum.

[E2BIG] The number of bytes in the new process’ argument list is larger thanthe system-imposed limit.

[EFAULT] Path, argv, or envp point to an illegal address.

[EIO] An I/O error occurred while reading from the file system.

SEE ALSO

fork(2), exit(2), execl(3), exit(3), The BPX1EXC service in the IBM publication“OpenEdition Assembler Callable Services”.

88 Systems/C C Library

Page 107: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

EXIT(2)

NAME

exit - terminate the calling program

SYNOPSIS

#include <unistd.h>

void_exit(int status);

DESCRIPTION

The exit() function terminates a program with the following consequences:

• All of the descriptors open in the calling process are closed. This may entaildelays, for example, waiting for output to drain.

• All allocated memory for the programs stack and heap space is released.

• For OpenEdition (POSIX) programs, if the parent OpenEdition process of thecalling process has an outstanding wait(2) call or catches the SIGCHLD signal,it is notified of the calling process’s termination and the status is set as definedby wait(2).

• For OpenEdition (POSIX) programs, the parent process-ID of all of the callingprocess’s existing child processes are set to 1; the initialization process inheritseach of these processes.

• For OpenEdition (POSIX) programs, if the termination of the process causesany process group to become orphaned (usually because the parents of allmembers of the group have now exited), and if any member of the orphanedgroup is stopped, the SIGHUP signal and the SIGCONT signal are sent to allmembers of the newly-orphaned process group.

• For OpenEdition (POSIX) programs, if the process is a controlling process,the SIGHUP signal is sent to the foreground process group of the controllingterminal, and all current access to the controlling terminal is revoked.

• For DCALL environments, the environment is destroyed and cannot be usedagain via DCALL=SUPPLIED.

Most C programs call the library routine exit(3), which flushes buffers, closesstreams, unlinks temporary files, etc., before calling exit().

Systems/C C Library 89

Page 108: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

RETURN VALUES

exit() can never return.

SEE ALSO

fork(2), wait(2), exit(3)

STANDARDS

The exit() function call is expected to conform to ISO/IEC 9945-1:1990(“POSIX.1”) as much as the host system allows.

90 Systems/C C Library

Page 109: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

FCNTL(2)

NAME

fcntl - file control

SYNOPSIS

#include <fcntl.h>

intfcntl(int fd, int cmd, ...)

DESCRIPTION

fcntl() provides for control over descriptors. The argument fd is a descriptor to beoperated on by cmd as described below. Depending on the value of cmd, fcntl cantake an additional third argument int arg.

F GETFL Get descriptor status flags, as described below (arg is ignored).

F SETFL Set descriptor status flags to arg.

F GETFD Get the file descriptor flags (FD LEAVEONCLOSE or FD FREEONCLOSE,or both) associated with the DSN/DDN file descriptor.

F SETFD Set the leave-on-close (FD LEAVEONCLOSE) and/or free-on-close(FD FREEONCLOSE) flags associated with the DSN/DDN file descrip-tor. If the FD LEAVEONCLOSE bit is set in arg, then when the asso-ciated file is closed, the LEAVE option will be specified on the MVSCLOSE macro. If the FD FREEONCLOSE bit is set in arg, then whenthe associated file is closed, the FREE option will be specified on theMVS CLOSE macro.

RETURN VALUES

Upon successful completion, the value returned depends on cmd as follows:

F GETFL Value of flags.

F GETFD Value of flags.

other Value other than -1.

Otherwise, a value of -1 is returned and errno is set to indicate the error.

Systems/C C Library 91

Page 110: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

ERRORS

fcntl() will fail if:

[EBADF] fd is not a valid open file descriptor.

SEE ALSO

close(2), getdtablesize(2), open(2)

92 Systems/C C Library

Page 111: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

FLDATA(2)

NAME

fldata - retrieve low-level file information

SYNOPSIS

#include <machine/syscio.h>

intfldata(int fd, char *buf, int bufsize, fldata_t *info);

DESCRIPTION

The fldata() function examines the open file descriptor fd and returns informationabout the file. If the file descriptor was generated by a call to open(2), (or indirectlyvia fopen(3)), then fldata() returns the original name specified on the open()function call in buf, up to bufsize characters. The fldata() function does not appenda NUL character to buf.

fldata() also sets various fields of the fldata t structure with information from theopen file. The fldata t structure (shown below) is defined in <machine/syscio.h>.

typedef struct __fileData {/* Record formats */unsigned int __recfmF:1; /* Fixed Records */unsigned int __recfmV:1; /* Variable Records */unsigned int __recfmU:1; /* Undefined Records */unsigned int __recfmS:1; /* Spanned */unsigned int __recfmBlk:1; /* Blocked data set */unsigned int __recfmASA:1; /* ASA print control characters */unsigned int __recfmM:1; /* Machine control character *//* Data Set organization */

unsigned int __dsorgPO:1; /* PDS */unsigned int __dsorgPDSmem:1; /* PDS member specified on open */unsigned int __dsorgPDSdir:1;unsigned int __dsorgPS:1; /* sequential file */unsigned int __dsorgConcat:1;unsigned int __dsorgMem:1;unsigned int __dsorgHiper:1;unsigned int __dsorgTemp:1;unsigned int __dsorgVSAM:1;unsigned int __dsorgHFS:1; /* HFS file */

Systems/C C Library 93

Page 112: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

unsigned int __dsorgPDSE:1;/* How was the file opened? */

unsigned int __openmode:2;unsigned int __modeflag:4;unsigned int __vsamRLS:3;unsigned int __reserv1:8;

__device_t __device;unsigned long __blksize;unsigned long __maxreclen;unsigned short __vsamtype;unsigned long __vsamkeylen;unsigned long __vsamRKP;char * __dsname;unsigned int __reserv2;

} fldata_t;

The fields of fldata t are as follows:

recfmF Set to 1 for fixed-length records

recfmV Set to 1 for variable-length records

recvmU Set to 1 for undeifned-length records

recfmS Set to 1 for spanned records

recfmBlk Set to 1 for blocked records

recfmASA Set to 1 if the file uses ASA print-control characters

recfmM Set to 1 if the file uses machine print-control characters

dsorgPO Set to 1 for a PDS file

dsorgPDSmem Set to 1 for PDS members

dsorgPDSdir Set to 1 for PDS or PDSE directory

dsorgPS Set to 1 for sequential files

dsorgConcat Set to 1 for concatenated sequential files

dsorgHFS Set to 1 for HFS files.

dsorgPDSE Set to 1 if the file is a PDSE

openmode How the files was opened, one of TEXT, BINARY or RECORD

modeflag How the file is altered or used, can be APPEND, READ, UPDATE,WRITE. These values can be logically OR’d together.

94 Systems/C C Library

Page 113: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

device The low-level “device driver” handling this file, one of DISK,TERMINAL, SOCKET or HFS

blksize Block size of the file

maxreclen Record length of the file (1-32760); or 2147483647 for an LRECL=XVariable Spanned file.

dsname For //DDN:-style files, this is set to a pointer to the NUL-terminatedDSN-name associated with the file. If the DD-name is a concatena-tion, this contains the first DSN-name in the concatenation. If thename passed to open(2) was not a //DDN:-style name, this field willbe NULL.

RETURN VALUES

If successful, fldata() returns the number of characters copied into buf (which maybe zero.) Otherwise, fldata() returns -1 and sets the global variable errno toindicate the error.

ERRORS

fldata() will fail if:

[EBADF] fd is not a valid descriptor.

[EFAULT Either buf or info specifies an invalid address.

[ENOSYS Couldn’t determine the associated DSN name for a //DDN:-stylename

Furthermore, for //HFS:-style files, fldata() can fail under the same conditions thatfstat(2) can fail.

SEE ALSO

open(2), fstat(2), ddnfind(2), fileno(3)

ISSUES

The dsname field is statically allocated in the library and should be saved betweencalls to fldata.

Systems/C C Library 95

Page 114: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

The fldata t structure defines fields not currently supported by the Systems/Clibrary (e.g. VSAM-related fields.) These are provided for compatibility with IBM’sfldata function. Note that the IBM fldata function operates on FILE streamsnot file descriptors and has a slightly different parameter list.

96 Systems/C C Library

Page 115: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

FORK(2)

NAME

fork - create a new process

SYNOPSIS

#include <sys/types.h>#include <unistd.h>

pid_tfork(void);

DESCRIPTION

fork() causes creation of a new process. The new process (child process) is an exactcopy 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 (i.e. the process ID of theparent process.)

• The child process has its own copy of the parent’s descriptors. These descrip-tors reference the same underlying objects, so that, for instance, file pointersin file objects are shared between the child and the parent, so that an lseek(2)on a descriptor in the child process can affect a subsequent read(2) or write(2)by the parent. This descriptor copying is also used by the shell to establishstandard input and output for newly created processes as well as to set uppipes.

Any file descriptors associated with non //HFS:-style files are closed in thechild process.

• The child process’ resource utilizations are set to 0.

• All interval timers are cleared

• Any file locks previous set by the parent are not inherited by the child.

• The child has no pending signals.

Systems/C C Library 97

Page 116: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

RETURN VALUES

Upon successful completion, fork() returns a value of 0 to the child process andreturns the process ID of the child process to the parent process. Otherwise, a valueof -1 is returned to the parent process, no child process is created, and the globalvariable errno is set to indicate the error.

ERRORS

fork() will fail and no child process will be created if:

[EAGAIN] The system-imposed limit on the total number of processes underexecution would be exceeded.

[EAGAIN] The user is not the super user, and the “soft” resource limit on thenumber of per-user processes has been exhausted.

[ENOMEM] There is insufficient space for the new process.

SEE ALSO

execve(2), wait(2)

98 Systems/C C Library

Page 117: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

FSYNC(2)

NAME

fsync - synchronise changes to a file

SYNOPSIS

#include <unistd.h>

intfsync(int fd);

DESCRIPTION

For //HFS:-style files, fsync() causes all modified data and attributes of fd to bemoved to a permanent storage device. This normally results in all in-core modifiedcopies of buffers for the associated file to be written to a disk.

fsync() should be used by programs that require a file to be in a known state, forexample, in building a simple transaction facility.

Because of internal operating system buffering, for non-//HFS:-style files, thefsync() function fails with a -1 return code, and errno set to EIO.

RETURN VALUES

The fsync() function returns the value 0 if successful; otherwise the value -1 isreturned and the global variable errno is set to indicate the error.

ERRORS

The fsync() function fails if:

[EBADF] fd is not a valid descriptor.

[EINVAL] fd refers to something that is not a regular file.

[EIO] An I/O error occurred while reading from or writing to the filesystem.

Systems/C C Library 99

Page 118: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

SEE ALSO

sync(2)

100 Systems/C C Library

Page 119: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

GET CPUID(2)

NAME

get cpuid() - return the IBM CPU identifier

SYNOPSIS

#include <machine/tiot.h>

int __get_cpuid(char *buff);

DESCRIPTION

The get cpuid() function returns the current CPU identifier as a nul-terminatedstring in the buffer addressed by buff. Buff must be at least 11 bytes long (10 bytesfor the identifier, with a terminating zero.)

The CPU ID contains the serial number, followed by the model number.

RETURN VALUES

The get cpuid() function always returns the value 0. The CPU ID is containedin the string buff.

Systems/C C Library 101

Page 120: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

GETITIMER(2)

NAME

getitimer, setitimer – get/set value of interval timer

SYNOPSIS

#include <sys/time.h>#define ITIMER_REAL 0#define ITIMER_VIRTUAL 1#define ITIMER_PROF 2

intgetitimer(int which, struct itimerval *value);

intsetitimer(int which, const struct itimerval *value,

struct itimerval *ovalue);

DESCRIPTION

The system provides each process with three interval timers, defined in ¡sys/time.h¿.The getitimer() system call returns the current value for the timer specified inwhich in the structure at value. The setitimer() system call sets a timer to thespecified value (returning the previous value of the timer if ovalue is not a nullpointer).

A timer value is defined by the itimerval structure:

struct itimerval {struct timeval it_interval; /* timer interval */struct timeval it_value; /* current value */

};

If it value is non-zero, it indicates the time to the next timer expiration. If it intervalis non-zero, it 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. Settingit interval to 0 causes a timer to be disabled after its next expiration (assumingit value is non-zero).

Time values smaller than the resolution of the system clock are rounded up to thisresolution.

102 Systems/C C Library

Page 121: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

The ITIMER REAL timer decrements in real time. A SIGALRM signal is delivered whenthis timer expires.

The ITIMER VIRTUAL timer decrements in process virtual time. It runs only whenthe process is executing. A SIGVTALRM signal is delivered when it expires.

The ITIMER PROF timer decrements both in process virtual time and when thesystem is running on behalf of the process. It is designed to be used by inter-preters in statistically profiling the execution of interpreted programs. Each timethe ITIMER PROF timer expires, the SIGPROF signal is delivered. Because this signalmay interrupt in-progress system calls, programs using this timer must be preparedto restart interrupted system calls.

The maximum number of seconds allowed for it interval and it value in setitimer()is 100000000.

NOTES

Three macros for manipulating time values are defined in ¡sys/time.h¿. Thetimerclear() macro sets a time value to zero, timerisset() tests if a time valueis non-zero, and timercmp() compares two time values.

The underlying IBM implementation uses the MVS STIMERM interface, if the numberof concurrent STIMERM SET requests for the current task is exceeded, the programcan abnormally end.

RETURN VALUES

Upon successful completion, the value 0 is returned; otherwise the value -1 is re-turned and the global variable errno is set to indicate the error.

ERRORS

The getitimer() and setitimer() system calls will fail if:

[EFAULT] The value argument specified a bad address.

[EINVAL] The value argument specified a time that was too large to be handledor was negative.

[ENOSYS] POSIX signals were not enabled for the program and are requiredfor delivering the signal when the timer expires.

Systems/C C Library 103

Page 122: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

SEE ALSO

gettimeofday(2), select(2)

104 Systems/C C Library

Page 123: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

GETDTABLESIZE(2)

NAME

getdtablesize - get descriptor table size

SYNOPSIS

#include <unistd.h>

intgetdtablesize(void)

DESCRIPTION

Each process has a fixed size descriptor table, which is guaranteed to have at least 20slots. The entries in the descriptor table are numbered with small integers startingat 0. The call getdtablesize() returns the size of this table.

SEE ALSO

close(2), dup(2), open(2)

Systems/C C Library 105

Page 124: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

GETGID(2)

NAME

getgid, getegid - get group process identification

SYNOPSIS

#include <sys/types.h>#include <unistd.h>

gid_tgetgid(void);

gid_tgetegid(void);

DESCRIPTION

The getgid() function returns the real group ID of the calling process, getegid()returns the effective group ID of the calling process.

The real group ID is specified at login time.

The real group ID is the group of the user who invoked the program. As theeffective group ID gives the process additional permissions during the execution of“set-group-ID” mode processes, getgid() is used to determine the real-user-id ofthe calling process.

ERRORS

As long as UNIX System Services are available, the getgid() and getegid() func-tions are always successful, and no return value is reserved to indicate an error.

SEE ALSO

getuid(2), setgid(2), setregid(2)

STANDARDS

The getgid() and getegid() function calls are expected to conform to ISO/IEC9945-1:1990 (“POSIX.1”), as closely as the host system allows.

106 Systems/C C Library

Page 125: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

GETGROUPS(2)

NAME

getgroups - get group access list

SYNOPSIS

#include <sys/types.h>#include <unistd.h>

intgetgroups(int gidsetlen, gid_t *gidset);

DESCRIPTION

getgroups() gets the current group access list of the user process and stores it inthe array gidset. The parameter gidsetlen indicates the number of entries that maybe placed in gidset. getgroups() returns the actual number of groups returnedin gidset. No more than NGROUPS MAX will ever be returned. If gidsetlen is zero,getgroups() returns the number of supplementary group IDs associated with thecalling process without modifying the array pointed to by gidset.

RETURN VALUES

A successful call returns the number of groups in the group set. A value of -1indicates that an error occurred, and the error code is stored in the global variableerrno.

ERRORS

The possible errors for getgroups() are:

[EINVAL] The argument gidsetlen is smaller than the number of groups in thegroup set.

[EFAULT] The argument gidset specifies an invalid address.

SEE ALSO

setgroups(2)

Systems/C C Library 107

Page 126: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

GETLOGIN(2)

NAME

getlogin - get login name

SYNOPSIS

#include <unistd.h>

char *getlogin(void);

DESCRIPTION

The getlogin() routine returns the login name of the user associated with thecurrent session. The name is normally associated with a login step at the time asession is created, and is inherited by all processes descended from the login shell.(This is true even if some of those processes assume another user ID.)

RETURN VALUES

If a call to getlogin() succeeds, it returns a pointer to a NUL-terminated string ina static buffer, or NULL if the name has not been set.

ERRORS

If OpenEdition services are available, getlogin() should not fail. If OpenEditionservices are available, and the request fails getlogin() will terminate the programwith an abend.

STANDARDS

getlogin() conforms to ISO/IEC 9945-1:1996 (“POSIX.1”).

108 Systems/C C Library

Page 127: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

GETPID(2)

NAME

getpid, getppid - get parent or calling process identification

SYNOPSIS

#include <sys/types.h>#include <unistd.h>

pid_tgetpid(void);

pid_tgetppid(void);

DESCRIPTION

getpid() returns the process ID of the calling process. Though the ID is guaranteedto be unique, it should NOT be used for constructing temporary file names, forsecurity reasons; see mkstemp(3) instead.

getppid() returns the process ID of the parent of the calling process.

ERRORS

If OpenEdition services are available, the getpid() and getppid() functions arealways succesful, and no return value is reserved to indicate an error.

If OpenEdition services are not available, getpid() and getppid() return zero, andthe global variable errno is set to the value ENOSYS.

STANDARDS

The getpid() and getppid() function calls are expected to conform to ISO/IEC9945-1:1990 (“POSIX.1”) as closely as the host operating system allows.

Systems/C C Library 109

Page 128: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

GETPGRP(2)

NAME

getpgrp - get process group

SYNOPSIS

#include <unistd.h>

pid_tgetpgrp(void);

pid_tgetpgid(pid_t pid);

DESCRIPTION

The process group of the current process is returned by getpgrp(). The processgroup of the process identified by pid is returned by getpgid(). If pid is zero,getpgid() returns the process group of the current process.

Process groups are used for distribution of signals, and by terminals to arbitraterequests for their input: processes that have the same process group as the terminalare foreground and may read, while others will block with a signal if they attemptto read.

This call is thus used by programs to create process groups in implementing jobcontrol. The tcgetpgrp(3) and tcsetpgrp(3) calls are used to get/set the processgroup of the control terminal.

RETURN VALUES

The getpgrp() call always succeeds. Upon successful completion, the getpgid()call returns the process group of the specified process; otherwise, it returns a valueof -1 and sets errno to indicate the error.

ERRORS

getpgid() will succeed unless:

[EPERM] pid is not in the same session as the calling process

[ESRCH] there is no process whose process ID equals pid

110 Systems/C C Library

Page 129: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

SEE ALSO

getsid(2), setpgid(2)

STANDARDS

The getpgrp()(f)unction call is expected to conform to ISO/IEC 9945-1:1990(“POSIX.1”) as closely as the host system allows.

Systems/C C Library 111

Page 130: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

GETPRIORITY(2)

NAME

getpriority, setpriority - get/set program scheduling priority

SYNOPSIS

#include <sys/time.h>#include <sys/resource.h>

intgetpriority(int which, int who);

intsetpriority(int which, int who, int prio);

DESCRIPTION

The scheduling priority of the process, process group, or user, as indicated by whichand who is obtained with the getpriority() call and set with the setpriority() call.Which is one of PRIO PROCESS, PRIO PGRP, or PRIO USER, and who is interpretedrelative to which (a process identifier for PRIO PROCESS, process group identifier forPRIO PGRP, and a user ID for PRIO USER). A zero value of who denotes the currentprocess, process group, or user. Prio is a value in the range -20 to 19. The defaultpriority is 0; lower priorities cause more favorable scheduling.

The getpriority() call returns the highest priority (lowest numerical value) enjoyedby any of the specified processes. The setpriority() call sets the priorities of allof the specified processes to the specified value. Only the super-user may lowerpriorities.

RETURN VALUES

Since getpriority() can legitimately return the value -1, it is necessary to clear theexternal variable errno prior to the call, then check it afterward to determine if a-1 is an error or a legitimate value.

The setpriority() function returns the value 0 if successful; otherwise the value -1is returned and the global variable errno is set to indicate the error.

112 Systems/C C Library

Page 131: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

ERRORS

getpriority() and setpriority() will fail if:

[EINVAL] Which was not one of PRIO PROCESS, PRIO PGRP, or PRIO USER.

[EINVAL] Who is not a alid process ID, group ID or user ID.

[ENOSYS] The system does not support this function, or the installation hasnot enabled it.

[ESRCH] No process was located using the which and who values specified.

In addition to the errors indicated above, setpriority() will fail if:

[EPERM] A process was located, but neither its effective nor real user IDmatched the effective user ID of the caller.

[EACCES] A non super-user attempted to lower a process priority.

SEE ALSO

nice(3), fork(2)

Systems/C C Library 113

Page 132: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

GETPRV(2)

NAME

getprv - return the current Pseudo Register Vector address

SYNOPSIS

#pragma map (__getprv,"@@GETPRV")void *__getprv(void);

This function does not appear in any header file, thus, the #pragma map statementmust be properly provided to use it.

DESCRIPTION

The getprv() function returns the address of the current Pseudo Register Vector(PRV). The PRV contains global re-entrant data.

Typically getprv() is used in conjunction with #pragmaprokley(...,"DCALL=ALLOCATE,PRV=0") functions for creating stack envi-ronments that share the same global variables.

114 Systems/C C Library

Page 133: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

GETRUSAGE(2)

NAME

getrusage - get information about resource utilization

SYNOPSIS

#include <sys/types.h>#include <sys/time.h>#include <sys/resource.h>#define RUSAGE_SELF 0#define RUSAGE_CHILDREN -1

intgetrusage(int who, struct rusage *rusage);

DESCRIPTION

getrusage() returns information describing the resources utilized by the cur-rent process, or all its terminated child processes. The who parameter is eitherRUSAGE SELF or RUSAGE CHILDREN. The buffer to which rusage points will be filledin with the following structure:

struct rusage {struct timeval ru_utime; /* user time used */struct timeval ru_stime; /* system time used */

}

The fields are interpreted as follows:

ru utime the total amount of time spent executing in user mode.

ru stime the total amount of time spent in the system executing on be-half of the process(es).

RETURN VALUES

The getrusage() function returns the value 0 if successful; otherwise the value -1is returned and the global variable errno is set to indicate the error.

Systems/C C Library 115

Page 134: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

ERRORS

The getrusage() function will fail if:

[EINVAL] The who parameter is not a valid value. gitem[[EFAULT]] The ad-dress specified by the rusage parameter is not in a valid part of theprocess address space.

SEE ALSO

gettimeofday(2), wait(2)

116 Systems/C C Library

Page 135: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

GETSID(2)

NAME

getsid - get process session

SYNOPSIS

#include <unistd.h>

pid_tgetsid(pid_t pid);

DESCRIPTION

The session ID of the process identified by pid is returned by getsid(). If pid iszero, getsid() returns the session ID of the current process.

RETURN VALUES

Upon successful completion, the function getsid() returns the session ID of thespecified process; otherwise, it returns a value of -1 and sets errno to indicate anerror.

ERRORS

getsid() will succeed unless:

[EPERM] pid is not in the same session as the calling process.

[ESRCH] there is no process with a process ID equal to pid.

SEE ALSO

getpgid(2), getpgrp(2), setpgid(2), setsid(2)

Systems/C C Library 117

Page 136: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

GETTIMEOFDAY(2)

NAME

gettimeofday - get date and time

SYNOPSIS

#include <sys/time.h>

intgettimeofday(struct timeval *tp, struct timezone *tzp);

DESCRIPTION

The system’s notion of the current Greenwich time and the current time zone isobtained with the gettimeofday() call. The time is expressed in seconds andmicroseconds since midnight (0 hour), January 1, 1970. The resolution of the systemclock is hardware dependent, and the time may be updated continuously or in“ticks”. If tp or tzp is NULL, the associated time information will not be returned.

The structure pointed to by tp and tzp are defined in <sys/time.h> as:

struct timeval {long tv_sec; /* seconds since Jan. 1, 1970 */long tv_usec; /* and microseconds */

};

struct timezone {int tz_minuteswest; /* minutes west of Greenwich */int tz_dsttime; /* type of dst correction */

};

The timezone structure indicates the local time zone (measured in minutes of timewestward from Greenwich), and a flag that, if nonzero, indicates that DaylightSaving time applies locally during the appropriate part of the year.

The Systems/C runtime on OS/390 and z/OS assumes the system clock is set toGreenwhich time (not local time), and uses the CVTTZ value to determine the time-zone offset.

118 Systems/C C Library

Page 137: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

RETURN VALUES

Upon successful completion, the value 0 is returned; otherwise the value -1 is re-turned and the global variable errno is set to indicate the error.

ERRORS

The following error codes may be set in errno:

[EFAULT] An argument address referenced invalid memory.

SEE ALSO

ctime(3)

Systems/C C Library 119

Page 138: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

GETUID(2)

NAME

getuid, geteuid - get user identification

SYNOPSIS

#include <unistd.h>#include <sys/types.h>

uid_tgetuid(void);

uid_tgeteuid(void);

DESCRIPTION

The getuid() function returns the real user ID of the calling process. The geteuid()function returns the effective user ID of the calling process.

The real user ID is that of the user who has invoked the program. As the effectiveuser ID gives the process additional permissions during execution of “set-user-ID”mode processes, getuid() is used to determine the real-user-id of the calling process.

ERRORS

As long as the UNIX System Services are available, the getuid() and geteuid()functions are always successful, and no return value is reserved to indicate an error.

SEE ALSO

getgid(2), setgid(2), setreuid(2), setuid(2)

STANDARDS

The geteuid() and getuid() function calls are expected to conform to ISO/IEC9945-1:1990 (“POSIX.1”), as close as the host system allows.

120 Systems/C C Library

Page 139: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

GRANTPT(2)

NAME

grantpt - grant access to a slave pseudoterminal

SYNOPSIS

#include <stdlib.h>

intgrantpt(int filedes);

DESCRIPTION

The grantpt() function changes the ownership and mode of a slave pseudoterminal.filedes is a file descriptor that is the result of an open(2) of the corresponding masterpseudoterminal.

Secure connections can be provided by using grantpt() and unlockpt(2), or bysimply issuing the first open against the slave pseudoterminal from the userid orprocess that opened the master terminal.

RETURN VALUE

If successful, grantpt() returns the value 0, otherwise a -1 is returned and the globalvariable errno is set to indicate the error.

ERRORS

grantpt() will fail it:

[EACCESS] grantpt() has already been issued on this descriptor, or the slavepseudoterminal has already been opened.

[EBADF] filedes is invalid

[EINVAL] filedes is not a master pseudoterminal

[ENOENT] The slave pseudoterminal was not found.

SEE ALSO

ptsname(3), unlockpt(2)

Systems/C C Library 121

Page 140: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

ISPOSIXON(2)

NAME

isPosixOn - determine if the OpenMVS functions are available

SYNOPSIS

#include <unistd.h>

int__isPosixOn(void);

DESCRIPTION

The isPosixOn() function returns 1 if the OpenMVS system functions are avail-able and the program is executing in a POSIX environment, otherwise it returns0.

122 Systems/C C Library

Page 141: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

JOBNAME(2)

NAME

jobname - return the current jobname

SYNOPSIS

#include <machine/tiot.h>

char *__jobname(void);

char *__jobname_r(char *buf);

DESCRIPTION

The jobname() function returns the current jobname of the executing programon MVS, OS/390 and z/OS. The value returned is a pointer to a NUL-terminatedstring. Trailing blanks are removed from the name returned by the operating system.

jobname() returns a pointer to a static area, care should be taken to copy thisvalue before invoking jobname() again and when using jobname() in a multi-tasking environment.

jobname r() places the job name in the area addressed by buf. buf must be atleast 9 characters in size. jobname r() returns buf.

SEE ALSO

stepname(2), procname(2), userid(2) querydub(2)

Systems/C C Library 123

Page 142: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

KILL(2)

NAME

kill - send signal to a program or process

SYNOPSIS

#include <sys/types.h>#include <signal.h>

intkill(pid_t pid, int sig);

DESCRIPTION

The kill() function sends the signal given by sig to pid, a process or a group ofprocesses. Sig may be one of the valid signals, or it may be 0, in which case errorchecking is performed but no signal is actually sent. This can be used to check thevalidity of pid.

When running under OpenEdition, and pid is not the same process ID as the call-ing program, the BPX1KIL service is used to send the signal to a different processor process group. Otherwise, pid is ignored, and the signal is sent to the callingprogram.

For a process to have permission to send a signal to a process designated by pid,the real or effective user ID of the receiving process must match that of the sendingprocess or the user must have appropriate privileges (such as given by a set-user-IDprogram or the user is the super-user). A single exception is the signal SIGCONT,which may always be sent to any descendant of the current process.

If pid is greater than zero, sig is sent to the process whose ID is equal to pid.

If pid is zero, sig is sent to all processes whose group is equal to the process groupID of the sender, and for which the process has permission.

If pid is -1, and the user has super-user privileges, the signal is sent to all processesexcluding the process with ID 1 (usually init), and the process sending the signal.If the user is noto the super user, the signal is sent to tall processes with the sameuid as the user excluding the process sending the signal. No error is returend if anyprocess could be signaled.

If pid is negative, but not -1, the signal is sent to all processes whose process groupID is equal to the absolute value of pid.

124 Systems/C C Library

Page 143: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

If sig is SIGABRT and SIGABRT signals have not been caught via the signal() function,and the program is not running under OpenEdition, then a function call tracebackwill be generated on the STDERR stream, and the program will issue a user X’DCC’or 3532 ABEND.

RETURN VALUES

The kill() function returns the value 0 if successful; otherwise the value -1 is returnedand the global variable errno is set to indicate the error.

ERRORS

kill() will fail and no signal will be sent if:

[EINVAL] Sig is not a valid signal number.

[ESRCH] No process can be found corresponding to that specified by pid.

[ESRCH] The process id was given as 0 but the sending process does not havea process group.

[EPERM] The sending process is not the super-user and its effective user iddoes not match the effective user-id of the receiving process. Whensignaling a process group, this error is returned if any members ofthe group could not be signaled.

SEE ALSO

getpgrp(2), getpid(2), raise(3)

STANDARDS

The kill() function call is expected to conform to ISO/IEC 9945-1:1990 (“POSIX.1”)as closely as the host operating system allows.

Systems/C C Library 125

Page 144: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

LINK(2)

NAME

link - make a hard file link

SYNOPSIS

#include <unistd.h>

intlink(const char *name1, const char *name2);

DESCRIPTION

The link() function call atomically creates the specified directory entry (hard link)name2 with the attributes of the underlying object pointed at by name1. If the linkis successful, the link count of the underlying object is incremented, and name1 andname2 share equal access and rights to the underlying object.

If name1 is removed, the file name2 is not deleted and the link count of the under-lying object is decremented.

Name1 must exist for the hard link to succeed and both name1 and name2 must bein the same file system. name1 may not be a directory.

RETURN VALUES

The link() function returns the value 0 if successful; otherwise the value -1 is re-turned and the global variable errno is set to indicate the error.

ERRORS

link() will fail and no link will be created if:

[ENOTDIR] A component of either path prefix is not a directory.

[ENAMETOOLONG] A component of either pathname exceeded 255 characters, or entirelength of either path name exceeded 1023 characters.

[ENOENT] A component of either path prefix does not exist.

126 Systems/C C Library

Page 145: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

[EOPNOTSUPP] The file system containing the file named by name1 does not supportlinks.

[EMLINK] The link count of the file named by name1 would exceed 32767.

[EACCES] A component of either path prefix denies search permission.

[EACCES] The requested link requires writing in a directory with a mode thatdenies write permission.

[ELOOP] Too many symbolic links were encountered in translating one of thepathnames.

[ENOENT] The file named by name1 does not exist.

[EEXIST] The link named by name2 does exist.

[EPERM] The file named by name1 is a directory.

[EXDEV] The link named by name2 and the file named by name1 are ondifferent file systems.

[ENOSPC] The directory in which the entry for the new link is being placedcannot be extended because there is no space left on the file systemcontaining the directory.

[EDQUOT] The directory in which the entry for the new link is being placedcannot be extended because the user’s quota of disk blocks on thefile system containing the directory has been exhausted.

[EIO] An I/O error occurred while reading from or writing to the filesystem to make the directory entry.

[EROFS] The requested link requires writing in a directory on a read-only filesystem.

[EFAULT] One of the pathnames specified is outside the process’s allocatedaddress space.

SEE ALSO

pathconf(2), readlink(2), symlink(2), unlink(2)

STANDARDS

The link() function call is expected to conform to ISO/IEC 9945-1:1990(“POSIX.1”) as closely as the host operating system allows.

Systems/C C Library 127

Page 146: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

LSEEK(2)

NAME

lseek - reposition read/write file offset

SYNOPSIS

#include <unistd.h>

off_tlseek(int filedes, off_t offset, int whence)

DESCRIPTION

The lseek() function repositions the offset of the file descriptor fildes to the argu-ment offset according to the directive whence. The argument fildes must be an openfile descriptor. lseek() repositions the file position pointer associated with the filedescriptor fildes as follows:

• If whence is SEEK SET, the offset is set to offset bytes.

• If whence is SEEK CUR, the offset is set to its current location plus offset bytes.

• If whence is SEEK END, the offset is set to the size of the file plus offset bytes.

The lseek() function allows the file offset to be set beyond the end of the existingend-of-file of the file. If data is later written at this point, subsequent reads of thedata in the gap return bytes of zeros (until data is actually written into the gap).

Some devices are incapable of seeking. The value of the pointer associated with sucha device is undefined.

RETURN VALUES

Upon successful completion, lseek() returns the resulting offset location as mea-sured in bytes from the beginning of the file. Otherwise, a value of -1 is returnedand errno is set to indicate the error.

128 Systems/C C Library

Page 147: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

ERRORS

lseek() will fail and the file position pointer will remain unchanged if:

[EBADF] Fildes is not an open file descriptor.

[ESPIPE] Fildes is associated with a pipe, socket, or FIFO.

[EINVAL] Whence is not a proper value.

SEE ALSO

dup(2), open(2)

ISSUES

This document’s use of whence is incorrect English, but is maintained for historicalreasons.

There are limitations to the Systems/C lseek() support for non-HFS files, due toimplementing a byte offset file abstraction in the OS/390 and z/OS environments.lseek(fd, 0, SEEK CUR) is supported for any file. This returns the internal bytecount (the number of bytes read or written.) lseek(fd, n, SEEK CUR) is supportedif the corresponding SEEK SET lseek operation is supported. That is, the value ofn is added to the current position to determine a new offset. If lseek with theSEEK SET option on the computed offset succeeds, this succeeds. lseek(fd, 0,SEEK SET) succeeds on any non-HFS file for which the NOTE and POINT service isvalid. lseek(fd, n, SEEK SET) succeeds for any non-HFS file opened with theO RDONLY mode and for which the NOTE and POINT service is valid. This will notextend the file size as the file is opened read-only. Seeking past the end of file on aread-only file will return -1 and set errno to EINVAL.

lseek(fd, 0, SEEK END) is supported for non-HFS O RDONLY files. This is can bean expensive operation because the entire file must be read to determine its lengthin bytes.

These limitations similarly affect the fseek() function, which uses lseek() in itsimplementation.

STANDARDS

The lseek() function call is expected to conform to IEEE Std1003.1-1990(“POSIX”) as closely as the host operating system allows.

Systems/C C Library 129

Page 148: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

MKDIR(2)

NAME

mkdir – make a directory file

SYNOPSIS

#include <sys/types.h>#include <sys/stat.h>

intmkdir(const char *path, mode_t mode);

DESCRIPTION

The HFS directory path is created with the access permissions specified by modeand restricted by the umask(2) of the calling process.

The directory’s owner ID is set to the process’s effective user ID.

RETURN VALUES

The mkdir() unction returns the value 0 if successful; otherwise the value -1 isreturned and the global variable errno is set to indicate the error.

ERRORS

mkdir() will fail and no directory will be created if:

[ENOTDIR] A component of the path prefix is not a directory.

[ENAMETOOLONG] A component of a pathname exceeded 255 characters, or an entirepath name exceeded 1023 characters.

[ENOENT] A component of the path prefix does not exist.

[EACCES] Search permission is denied for a component of the path prefix, orwrite permission is denied on the parent directory of the directoryto be created.

[ELOOP] Too many symbolic links were encountered in translating the path-name.

130 Systems/C C Library

Page 149: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

[EROFS] The named file resides on a read-only file system.

[EEXIST] The named file exists.

[ENOSPC] The new directory cannot be created because there is no space lefton the file system that will contain the directory.

[ENOSPC] There are no free inodes on the file system on which the directoryis being created.

[EDQUOT] The new directory cannot be created because the user’s quota ofdisk blocks on the file system that will con tain the directory hasbeen exhausted.

[EDQUOT] The user’s quota of inodes on the file system on which the directoryis being created has been exhausted.

[EIO] An I/O error occurred while making the directory entry or allocatingthe inode.

[EIO] An I/O error occurred while reading from or writing to the filesystem.

[EFAULT] Path points outside the process’s allocated address space.

SEE ALSO

chmod(2), stat(2), umask(2)

STANDARDS

The mkdir() function call is expected to conform to IEEE Std1003.1-1990(“POSIX”) as closely as the host operating system allows.

Systems/C C Library 131

Page 150: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

MKFIFO(2)

NAME

mkfifo - make a fifo file

SYNOPSIS

#include <sys/types.h>#include <sys/stat.h>

intmkfifo(const char *path, mode_t mode);

DESCRIPTION

mkfifo() creates a new fifo file with name path. The access permissions are specifiedby mode and restricted by the umask(2) of the calling process.

The fifo’s owner ID is set to the process’s effective user ID. The fifo’s group ID isset to that of the parent directory in which it is created.

RETURN VALUES

The mkfifo() function returns the value 0 if successful; otherwise the value -1 isreturned and the global variable errno is set to indicate the error.

ERRORS

mkfifo() will fail and no fifo will be created if:

[ENOTSUPP] The system does not support Unix Systems Services.

[ENOTSUP] The specified path is not in the HFS file system.

[ENOTDIR] A component of the path prefix is not a directory.

[ENAMETOOLONG] A component of a pathname exceeded 255 characters, or an entirepath name exceeded 1023 characters.

[ENOENT] A component of the path prefix does not exist.

[EACCES] Search permission is denied for a component of the path prefix.

132 Systems/C C Library

Page 151: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

[ELOOP] Too many symbolic links were encountered in translating the path-name.

[EROFS] The named file resides on a read-only file system.

[EEXIST] The named file exists.

[ENOSPC] The directory in which the entry for the new fifo is being placedcannot be extended because there is no space left on the file systemcontaining the directory.

[ENOSPC] There are no free inodes on the file system on which the fifo is beingcreated.

[EDQUOT] The directory in which the entry for the new fifo is being placedcannot be extended because the user’s quota of disk blocks on thefile system containing the directory has been exhausted.

[EDQUOT] The user’s quota of inodes on the file system on which the fifo isbeing created has been exhausted.

[EIO] An I/O error occurred while making the directory entry or allocatingthe inode.

[EIO] An I/O error occurred while reading from or writing to the filesystem.

[EFAULT] Path points outside the process’s allocated address space.

SEE ALSO

chmod(2), mknod(2), stat(2), umask(2)

STANDARDS

The mkfifo() function call is expected to conform to ISO/IEC 9945-1:1990(“POSIX.1”) as closely as the host operating system allows.

Systems/C C Library 133

Page 152: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

MKNOD(2)

NAME

mknod - make an //HFS:-style special file node

SYNOPSIS

#include <unistd.h>

intmknod(const char *path, mode_t mode, dev_t dev);

DESCRIPTION

The HFS filesystem node path is created with the file type and access permissionsspecified in mode. The access permissions are modified by the process’s umask value.

If mode indicates a block or character special file, dev is a configuration dependentspecification denoting a particular device on the system. Otherwise, dev is ignored.

mknod() requires super-user privileges.

RETURN VALUES

The mknod() function returns the value 0 if successful; otherwise the value -1 isreturned and the global variable errno is set to indicate the error.

ERRORS

mknod() will fail and the file will be not created if:

[ENOTDIR] A component of the path prefix is not a directory.

[ENAMETOOLONG] A component of a pathname exceeded 255 characters, or an entirepath name exceeded 1023 characters.

[ENOENT] A component of the path prefix does not exist.

[EACCES] Search permission is denied for a component of the path prefix.

[ELOOP] Too many symbolic links were encountered in translating the path-name.

134 Systems/C C Library

Page 153: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

[EPERM] The process’s effective user ID is not super-user.

[EIO] An I/O error occurred while making the directory entry or allocatingthe inode.

[ENOSPC] The directory in which the entry for the new node is being placedcannot be extended because there is no space left on the file systemcontaining the directory.

[ENOSPC] There are no free inodes on the file system on which the node isbeing created.

[EDQUOT] The directory in which the entry for the new node is being placedcannot be extended because the user’s quota of disk blocks on thefile system containing the directory has been exhausted.

[EDQUOT] The user’s quota of inodes on the file system on which the node isbeing created has been exhausted.

[EROFS] The named file resides on a read-only file system.

[EEXIST] The named file exists.

[EFAULT] Path points outside the process’s allocated address space.

[EINVAL] Creating anything else than a character special file, regular file,FIFO or directory is not supported.

SEE ALSO

chmod(2)), mkfifo(2), stat(2), umask(2)

Systems/C C Library 135

Page 154: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

MMAP(2)

NAME

mmap - allocate memory, or map files or devices into memory

SYNOPSIS

#include <sys/types.h>#include <sys/mman.h>

void *mmap(void *addr, size_t len, int prot, int flags, int fd, off_t offset);

DESCRIPTION

The mmap() function causes the pages starting at addr and continuing for at mostlen bytes to be mapped from the //HFS: object described by fd, starting at byteoffset offset. If len is not a multiple of the pagesize, the mapped region may extendpast the specified range, or mmap() may fail. Any such extension beyond the endof the mapped object will be zero-filled.

If addr is non-zero, it is used a a hit to the system. (As a convenience to the system,the actual address of the region may differ from the address supplied.) If addr iszero, an address will be selected by the system. The actual starting address of theregion is returned. A successful mmap deletes any previous mapping in the allocatedaddress range.

The protections (region accessibility) are specified in the prot argument by or’ingthe following values:

PROT NONE Pages may not be accessed.

PROT READ Pages may be read.

PROT WRITE Pages may be written.

PROT EXEC Pages may be executed.

The flags parameter specifies the type of the mapped object, mapping options andwether modifications made to the mapped copy of the page are private to the processor are to be shared with other references. Sharing, mapping type and options arespecified in the flags argument by or’ing the following values:

136 Systems/C C Library

Page 155: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

MAP FIXED Do not permit the system to select a different address than the onespecified. If the specified address cannot be used, mmap() will fail.If MAP FIXED is specified, addr must be a multiple of the pagesize.Use of this option is discouraged.

MAP PRIVATE Modifications are private.

MAP SHARED Modifications are shared.

The close(2) function does not unmap pages, see munmap(2) for further information.

RETURN VALUES

Upon successful completion, mmap() returns a pointer to the mapped region. Oth-erwise, a value of MAP FAILED is returned and errno is set to indicate the error.

ERRORS

mmap() will fail if:

[EACCES] The flag PROT READ was specified as part of the prot parameter andfd was not open for reading. The flags MAP SHARED and PROT WRITEwere specified as part of the flags and prot parameters and fd wasnot open for writing.

[EAGAIN] Te caller is not in PSW key 8.

[EBADF] fd is not a valid open file descriptor.

[EINVAL] MAP FIXED was specified and the addr parameter was not pagealigned, or part of the desired address space resides out of the validaddress spce for a user process.

[EINVAL] len was negative.

[EINVAL] offset was not page-aligned.

[EINVAL] flags or prot were invalid.

[ENODEV] fd refers to a non-supported file type.

[ENOMEM] MAP FIXED was specified and the addr parameter wasn’t available.The system has reached the mmap limit.

[ENOSYS] MAP PRIVATE was specified, but the hardware doesn’t support it.

[ENXIO] The address range is not valid for the file.

Systems/C C Library 137

Page 156: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

SEE ALSO

mprotect(2), msync(2), munmap(2).

138 Systems/C C Library

Page 157: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

MPROTECT(2)

NAME

mprotect - control the protection of pages

SYNOPSIS

#include <sys/types.h>#include <sys/mman.h>

intmprotect(const void *addr, size_t len, int prot);

DESCRIPTION

The mprotect() system call changes the specified pages to have protection prot.Not all implementations will guarantee protection on a page basis; the granularityof protection changes may be as large as an entire region.

Currently these protection bits are known, which can be combined, OR’d together:

PROT NONE No permissions at all.

PROT READ The pages can be read.

PROT WRITE The pages can be written.

PROT EXEC The pages can be executed.

RETURN VALUES

The mprotect() function returns the value 0 if successful; otherwise the value -1 isreturned and the global variable errno is set to indicate the error.

ERRORS

The mprotect() function will fail if:

[EINVAL] The virtual address range specified by the addr and len argumentsis not valid.

[EACCES] The calling process was not allowed to change the protection to thevalue specified by the prot argument.

Systems/C C Library 139

Page 158: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

SEE ALSO

msync(2), munmap(2)

140 Systems/C C Library

Page 159: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

MSYNC(2)

NAME

msync - synchronize a mapped region

SYNOPSIS

#include <sys/types.h>#include <sys/mman.h>

intmsync(void *addr, size_t len, int flags);

DESCRIPTION

The msync() system call writes any modified pages back to the filesystem andupdates the file modification time. If len is 0, all modified pages within the re-gion containing addr will be flushed; if len is non-zero, only those pages containingaddr and len-1 succeeding locations will be examined. The flags argument may bespecified as follows:

MS ASYNC Return immediately

MS SYNC Perform synchronous writes

MS INVALIDATE Invalidate all cached data

RETURN VALUES

The msync() function returns the value 0 if successful; otherwise the value -1 isreturned and the global variable errno is set to indicate the error.

ERRORS

msync() will fail if:

[EINVAL] addr is not a multiple of the hardware page size.

[EINVAL] len is too large or negative.

[EINVAL] flags was both MS ASYNC and MS INVALIDATE. Only one of these flagsis allowed.

[EIO] An I/O error occurred while writing to the file system.

Systems/C C Library 141

Page 160: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

SEE ALSO

mprotect(2), munmap(2)

142 Systems/C C Library

Page 161: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

MSGCTL(2)

NAME

msgctl - message control operations

SYNOPSIS

#include <sys/types.h>#include <sys/ipc.h>#include <sys/msg.h>

intmsgctl(int msqid, int cmd, struct msqid_ds *buf);

DESCRIPTION

The msgctl() system call performs some control operations on the message queuespecified by msqid.

Each message queue has a data structure associated with it, parts of which maybe altered by msgctl() and parts of which determine the actions of msgctl().The data structure is defined in <sys/msg.h> and contains (amongst others) thefollowing members:

struct msqid_ds {struct ipc_perm msg_perm; /* msg queue permission bits */struct msg *msg_first; /* first message in the queue */struct msg *msg_last; /* last message in the queue */u_long msg_cbytes; /* number of bytes in use on the queue */u_long msg_qnum; /* number of msgs in the queue */u_long msg_qbytes; /* max # of bytes on the queue */pid_t msg_lspid; /* pid of last msgsnd() */pid_t msg_lrpid; /* pid of last msgrcv() */time_t msg_stime; /* time of last msgsnd() */long msg_pad1;time_t msg_rtime; /* time of last msgrcv() */long msg_pad2;time_t msg_ctime; /* time of last msgctl() */long msg_pad3;long msg_pad4[4];

};

Systems/C C Library 143

Page 162: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

The ipc perm structure used inside the shmid ds structure is defined in<sys/ipc.h> and looks like this:

struct ipc_perm {ushort cuid; /* creator user id */ushort cgid; /* creator group id */ushort uid; /* user id */ushort gid; /* group id */ushort mode; /* r/w permission */ushort seq; /* sequence # (to generate unique msg/sem/shm id) */key_t key; /* user specified msg/sem/shm key */

};

The operations to be performed by msgctl() is specified in cmd and is one of:

IPC STAT Gather information about the message queue and place it in the structurepointed to by buf.

IPC SET Set the value of the msg perm.uid, msg perm.gid, and msg qbytes fieldsin the structure associated with msqid. The values are taken from the corre-sponding fields in the structure pointed to by buf. his operation can only beexecuted by the super-user, or a process that has an effective user id equal toeither msg perm.cuid or msg perm.uid in the data structure associated withthe message queue. The value of msg qbytes can only be increased by thesuper-user. Values for msg qbytes that exceed the system limit are silentlytruncated to that limit.

IPC RMID Remove the message queue specified by msqid and destroy the data associ-ated with it. Only the super-user or a process with an effective uid equal tothe msg perm.cuid or msg perm.uid values in the data structure associatedwith the queue can do this.

The permission to read from or write to a message queue (see msgsnd(2) and ms-grcv(2)) is determined by the msg perm.mode field in the same way as is done withfiles (see chmod(2)), but the effective uid can match either the msg perm.cuid fieldor the msg perm.uid field, and the effective gid can match either msg perm.cgid ormsg perm.gid.

RETURN VALUES

The msgctl() function returns the value 0 if successful; otherwise the value -1 isreturned and the global variable errno is set to indicate the error.

144 Systems/C C Library

Page 163: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

ERRORS

The msgctl() function will fail if:

[EPERM] The cmd argument is equal to IPC SET or IPC RMID and the calleris not the super-user, nor does the effective uid match either themsg perm.uid or msg perm.cuid fields of the data structure associ-ated with the message queue.

An attempt is made to increase the value of msg qbytes throughIPC SET but the caller is not the super-user.

[EACCES] The command is IPC STAT and the caller has no read permission forthis message queue.

[EINVAL] The msqid argument is not a valid message queue identifier.

cmd is not a valid command.

[EFAULT] The buf argument specifies an invalid address.

SEE ALSO

msgget(2), msgrcv(2), msgsnd(2)

ISSUES

The underlying IBM Unix Systems Services does not support the seq and key fieldsof the ipc perm structure, nor the msg first, msg last or msg cbytes field of themsqid ds. They are provided for compatibility and will always be zero.

Systems/C C Library 145

Page 164: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

MSGGET(2)

NAME

msgget - get message queue

SYNOPSIS

#include <sys/types.h>#include <sys/ipc.h>#include <sys/msg.h>

intmsgget(key_t key, int msgflg);

DESCRIPTION

The msgget() function returns the message queue identifier associated with key. Amessage queue identifier is a unique integer greater than zaero.

A message queue is created if either key is equal to IPC PRIVATE, or key does nothave a message queue identifier associated with it, and the IPC CREAT bit is set inmsgflg.

If a new message queue is created, the data structure associated with it (the msgid dsstructure, see msgctl(2)) is initialized as follows:

• msg perm.cuid and msg perm.uid are set to the effective uid of the callingprocess.

• msg perm.gid and msg perm.cgid are set to the effective gid of the callingprocess.

• msg perm.mode is set to the lower 9 bits of msgflg.

• msg cbytes, msg qnum, msg lspid, msg lrpid, msg rtime and msg stime areset to 0.

• msg qbytes is set to the system wide maximum value for the number of bytesin a queue (MSGMNB).

• msg ctime is set to the current time.

RETURN VALUES

Upon successful completion a positive message queue identifier is returned. Other-wise, -1 is returned and the global variable errno is set to indicate the error.

146 Systems/C C Library

Page 165: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

ERRORS

[EACCES] A message queue is already associated with key and the caller hasno permission to access it.

[EEXIST] Both IPC CREAT and IPC EXCL are set in msgflg, and a messagequeue is already associated with key.

[ENOSPC] A new message queue could not be created because the system limitfor the number of message queues has been reached.

[ENOENT] IPC CREAT was not set in msgflg and no message queue associatedwith key was found.

SEE ALSO

msgctl(2), msgrcv(2), msgsnd(2)

Systems/C C Library 147

Page 166: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

MSGRCV(2)

msgrcv - receive a message from a message queue

SYNOPSIS

#include <sys/types.h>#include <sys/ipc.h>#include <sys/msg.h>

intmsgrcv(int msqid, void *msgp, size_t msgsz, long msgtyp, int msgflg);

DESCRIPTION

The msgrcv() function receives a message from the message queue specified inmsqid, and places it into the structure pointed to by msgp. This structure shouldconsist of the following members:

long mtype; /* message type */char mtext[1]; /* body of message */

mtype is an integer greater than 0 that can be used for selecting messages, mtext isan array of bytes, with a size up to that of the system limit.

The value of msgtyp has one of the following meanings:

• The msgtyp argument is greater than 0. The first message of type msgtyp willbe received.

• The msgtyp argument is equal to 0. The first message on the queue will bereceived.

• The msgtyp argument is less than 0. The first message of the lowest messagetype that is less than or equal to the absolute value of msgtyp will be received.

The msgsz argument specifies the maximum length of the requested message. If thereceived message has a length greater than msgsz it will be silently truncated if theMSG NOERROR flag is set in msgflg, otherwise an error will be returned.

If no matching message is present on the message queue specified by msqid, thebehavior of msgrcv() depends on whether the IPC NOWAIT flag is set in msgflag ornot. If IPC NOWAIT is set, msgrcv() will immediately return a value of -1, and seterrno to ENOMSG. If IPC NOWAIT is not set, the calling process will be blocked until:

148 Systems/C C Library

Page 167: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

• A message of the requested type becomes available on the message queue.

• The message queue is removed, in which case -1 will be returned, and errnoset to EINVAL.

• A signal is received and caught. -1 is returned, and errno set to EINTR.

If a message is is successfully received, the data structure associated with msqid isupdated as follows:

• msg lrpid is set to the pid of the caller.

• msg lrtime is set to the current time.

• msg qnum is decremented by 1.

RETURN VALUES

Upon successful completion, msgrcv() returns the number of bytes received intothe mtext field of the structure pointed to by msgp. Otherwise, -1 is returned, anderrno set to indicate the error.

ERRORS

The msgrcv() function will fail if:

[EINVAL] The msqid argument is not a valid message queue identifier.

The msgsz argument is less than 0.

[E2BIG] A matching message was received, but its size was greater thanmsgsz and the MSG NOERROR flag was not set in msgflg.

[EACCES] The calling process does not have read access to the message queue.

[EFAULT] The msgp argument points to an invalid address.

[EIDRM] The message queue was removed while msgrcv() was waiting for amessage of the requested type to become available on it.

[EINTR] The system call was interrupted by the delivery of a signal.

[ENOMSG] There is no message of the requested type available on the messagequeue, and IPC NOWAIT is set in msgflg.

SEE ALSO

msgctl(2), msgget(2), msgsnd(2)

Systems/C C Library 149

Page 168: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

MSGSND(2)

NAME

msgsnd - send a message to a message queue

SYNOPSIS

#include <sys/types.h>#include <sys/ipc.h>#include <sys/msg.h>

intmsgsnd(int msqid, void *msgp, size_t msgsz, int msgflg);

DESCRIPTION

The msgsnd() function sends a message to the message queue specified in msqid.msgp points to a structure containing the message. This structure should consist ofthe following members:

long mtype; /* message type */char mtext[1]; /* body of message */

mtype is an integer greater than 0 that can be used for selecting messages (seemsgrcv(2)), mtext is an array of bytes, with a size up to the system limit.

If the number of bytes already on the message queue plus msgsz is bigger than themaximum number of bytes on the message queue (msg qbytes, see msgctl(2)), orthe number of messages on all queues system-wide is already equal to the systemlimit, msgflg determines the action of msgsnd(). If msgflg has IPC NOWAIT mask setin it, the call will return immediately. If msgflg does not have IPC NOWAIT(s)etin it, the call will block until:

• The condition which caused the call to block does no longer exist. The messagewill be sent.

• The message queue is removed, in which case -1 will be returned, and errnois set to EINVAL.

• The caller catches a signal. The call returns with errno set to EINTR.

After a successful call, the data structure associated with the message queue isupdated in the following way:

150 Systems/C C Library

Page 169: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

• msg qnum is incremented by 1.

• msg lspid is set to the pid of the calling process.

• msg stime is set to the current time.

RETURN VALUES

The msgsnd() function returns the value 0 if successful; otherwise the value -1 isreturned and the global variable errno is set to indicate the error.

ERRORS

msgsnd() will fail if:

[EINVAL] msqid is not a valid message queue identifier

msgsz is less than 0, or greater than msg qbytes.

mtype is not greater than 0.

[EACCES] The calling process does not have write access to the message queue.

[EAGAIN] There was no space for this message either on the queue, or in thewhole system, and IPC NOWAIT was set in msgflg.

[EFAULT] msgp points to an invalid address.

[EIDRM] The message queue was removed while msgsnd() was waiting fora resource to become available in order to deliver the message.

[EINTR] The system call was interrupted by the delivery of a signal.

SEE ALSO

msgctl(2), msgget(2), msgrcv(2)

Systems/C C Library 151

Page 170: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

MUNMAP(2)

NAME

munmap - remove a mapping

SYNOPSIS

#include <sys/types.h>#include <sys/mman.h>

intmunmap(void *addr, size_t len);

DESCRIPTION

The munmap() system call deletes the mapping for the specified address range, andcauses further references to addresses within the range to generate invalid memoryreferences.

RETURN VALUES

The munmap() returns the value 0 if successful; otherwise the value -1 is returnedand the global variable errno is set to indicate the error.

ERRORS

munmap() will fail if:

[EINVAL] The addr parameter was not page aligned, the len parameter wasnegative, or some part of the region being unmapped is outside thevalid address range for a process.

SEE ALSO

mmap(2), mprotect(2), msync(2)

152 Systems/C C Library

Page 171: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

NANOSLEEP(2)

NAME

nanosleep – suspend process execution for an interval measured in nanoseconds

SYNOPSIS

#include <time.h>

intnanosleep(const struct timespec *rqtp, struct timespec *rmtp);

DESCRIPTION

The nanosleep() system call causes the process to sleep for the specified time.An unmasked signal will cause it to terminate the sleep early, regardless of theSA RESTART value on the interrupting signal.

RETURN VALUES

If the nanosleep() system call returns because the requested time has elapsed, thevalue returned will be zero.

If the nanosleep() system call returns due to the delivery of a signal, the valuereturned will be -1, and the global variable errno will be set to indicate the in-terruption. If rmtp is non-NULL, the timespec structure it references is updated tocontain the unslept amount (the request time minus the time actually slept).

ERRORS

The nanosleep() system call fails if:

[EFAULT] Either rqtp or rmtp points to memory that is not a valid part of theprocess address space.

[EINTR] The nanosleep() system call was interrupted by the delivery of asignal.

[EINVAL] The rqtp argument specified a nanosecond value less than zero orgreater than or equal to 1000 million.

[ENOSYS] The nanosleep() system call is not supported by this implementa-tion.

Systems/C C Library 153

Page 172: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

IMPLEMENTATION

The nanosleep() function requires the use of BPX signals to interrupt the processbefore the timeout occurs. If BPX signals are not enabled, the nanosleep() functionwill wait until the specified time has elapsed.

SEE ALSO

sigsuspend(2), sleep(3)

STANDARDS

The nanosleep() system call conforms to IEEE Std 1003.1b-1993 (“POSIX.1”).

154 Systems/C C Library

Page 173: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

OPEN(2)

NAME

open - open or create a file for reading or writing

SYNOPSIS

#include <fcntl.h>

intopen(const char *path, int flags, ...)

DESCRIPTION

The file name specified by path is opened for reading and/or writing as specified bythe argument flags and the file descriptor returned to the calling process. The flagsargument may indicate the file is to be created if it does not exist (by specifying theO CREAT flag). In this case open requires a third argument mode t mode.

The flags specified are formed by or’ing the following values

O RDONLY open for reading only

O WRONLY open for writing only

O RDWR open for reading and writing

O NONBLOCK do not block on open

O APPEND append on each write

O CLOEXEC close the file on exec

O CREAT create file if it does not exist

O TRUNC truncate size to 0

O EXCL error if create and file exists

O SHLOCK atomically obtain a shared lock

O EXLOCK atomically obtain an exclusive lock

O BINARY specifies that I/O is to be done in binary mode, not texttranslation.

O TEXT (default) specify that I/O is to be done with text translation.

Systems/C C Library 155

Page 174: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

O ATTR An extra char * argument is found after the mode argument.This argument can be applied to non-HFS files, and specifiesfile attributes to use in the OS/390 DCB.

Opening a file with O APPEND set causes each write on the file to be appended to theend. If O TRUNC is specified and the file exists, the file is truncated to zero length.If O EXCL is set with O CREAT and the file already exists, open() returns an error.This may be used to implement a simple exclusive access locking mechanism. If theO NONBLOCK flag is specified and the open() call would result in the process beingblocked for some reason (e.g., waiting for carrier on a dialup line), open() returnsimmediately. The first time the process attempts to perform I/O on the open file itwill block (not currently implemented).

For HFS files, if the O CLOEXEC flag is set, then the FD CLOEXEC flag will be set;otherwise it is cleared.

If O BINARY is specified, the bytes retrieved from the operating system are passedto the program without further processing.

If O TEXT is specified, on input, trailing blanks are deleted and a new-line is ap-pended. On output, the new-line marks the end of the record, with trailing blanksappended to complete an output record.

When opening a file, a lock with flock(2) semantics can be obtained by settingO SHLOCK for a shared lock, or O EXLOCK for an exclusive lock. If creating a filewith O CREAT, the request for the lock will never fail (provided that the underlyingfilesystem supports locking).

If successful, open() returns a non-negative integer, termed a file descriptor. Itreturns -1 on failure. The file pointer used to mark the current position within thefile is set to the beginning of the file.

The system imposes a limit on the number of file descriptors open simultaneouslyby one process. Getdtablesize(2) returns the current system limit.

PATH NAMES

The Systems/C open() function uses path name prefixes to determine how to al-locate the file. A path name prefix consists of two slashes, followed by the prefixstyle name, followed by a colon (// style:). If a prefix is not specified, and the pathname begins with a single slash (/), or the path name begins with the two charactersperiod (.) and then slash (/), the file is treated as if the //HFS: prefix had beenspecified. Otherwise, the current default style is used.

The current default style is found in the global valriable extern char * style,and may be changed by assigning a new value to that variable. When a Systems/C

156 Systems/C C Library

Page 175: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

program is invoked from either a TSO or BATCH environment, the default value ofstyle is //DDN:.

When a Systems/C program is invoked via the exec function (i.e. under OpenEdi-tion), the default value of style is //HFS:.

The styles currently supported include:

//DSN: The specified path is a fully qualified dataset name on OS/390.

//DDN: The specified path is a DDN allocated via a JCL DD card, or the TSOALLOCATE command.

//HFS: The specified path is a file that resides in the Hiearchical File System(HFS).

Both //DSN: and //DDN: style names may also specify PDS member names, sur-rounded by parentheses.

DCB ATTRIBUTES

If the O ATTR bit is set in the flags argument, and the style is not //HFS:, then thiscall to open is understood to have four arguments; the forth is a character stringwhich describes the DCB attributes to initially use for the OS/390 OPEN service.All four arguments must be present if O ATTR is set.

These attributes are used to provide DCB during an OPEN EXIT on the OS/390OPEN system service. Thus they can be used to provide default values when theyare not present on DD cards, or can provide appropriate values when creating a newdata set.

The format of that string is a comma separated list of NAME=VALUE pairs.

The following names and values are currently supported:

blksize integer block size.

blocks No parameter. blocks specifies allocations are in blocks. Maybe abbreviated as blks or blk.

bufno integer number of buffers. bufno specifies the number of buffersto specify when allocating a non-HFS data set.

cylinders No parameter. cylinders specifies allocations are in cylinders.May be abbreviated as cyls or cyl.

Systems/C C Library 157

Page 176: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

directory integer specifying the number of directory blocks for a newPDS. If the value is omitted, directory blocks will not be spec-ified when allocating the new PDS.

catalog Indicates the file should be added to the system catalog. Maybe abbreviated as catlg.

delete The file should be deleted when it is deallocated.

keep The file is kept when it is deallocated.

keylen integer specifying the key length value in the DCB.

lrecl integer representing the logical record length, or the character’X’ indicating a record length larger than 32760 for VariableSpanned files.

ncp integer representing the NCP value for BSAM I/O (number ofoutstanding READ/WRITE requests before a CHECK.) Thisis also the number of I/O buffers the library will allocate whenmulti-buffering I/O is allowed.

preopen No parameter. preopen indicates that the values specified asattributes should apply to the DCB before opening the file, thus”overriding” any JCL specification.

noseek No parameter. Indicates that the file positioning function(lseek(2)) will not be used on the returned file descriptor.When noseek is true, the MACRF option on a BSAM OPENwill not indicate the use of NOTE and POINT, and thus thefile can read LARGE format data sets. Reading/writing ofLARGE format data sets also requires the BLOCKTOKEN-SIZE(NOREQUIRE) in SYS1.PARMLIB. noseek is also re-quired for multi-buffer support (if seeking is needed, only oneI/O buffer is used.)

primary integer specifying the primary allocation size. May be abbrevi-ated as pri.

recfm specifies the record format, either f, fa, fb, fs, fba, fbs, fsa,fbsa, v, vb, vs, vbs or u is supported.

secondary integer specifying the secondary allocation size. May be abbre-viated as sec

rlse No parameter. Indicates any unused space for a new data setbe returned (this is the default setting.)

norlse No parameter. Indicates any unused space for a new data setnot be returned

tracks No parameter. tracks specifies allocations are in tracks. Maybe abbreviated as trks or trk

158 Systems/C C Library

Page 177: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

type keyword specifying type of I/O. Currently, the record keywordis supported to indirect record I/O (e.g. type=record). Whenused with open(2), this attribute sets the O RECIO flag.

uncatlg Indicates the file should removed from the system catalog. Maybe abbreviated as uncatlg.

unit character string that specifies the device name.

verbose No parameter. Causes allocation messages to appear in thesystem log. The default is not verbose.

volser character string representing the volume serial identifier. Maybe abbreviated as vol.

volseq integer specify the volume sequence number.

Invalid NAME=VALUE pairs are silently ignored.

Note that preopen, blocks, cylinders and tracks NAMEs have no VALUE spec-ified, and that the VALUE is optional on the directory NAME.

For example, the following code will open //DDN:MYDD for binary input with ablksize of 3200 and an lrecl of 80:

open("//DDN:MYDD", O_RDONLY|_O_ATTR|_O_BINARY,0, "blksize=3200,lrecl=80");

CREATING //DSN: FILES

Files can be created by the Systems/C runtime when the O CREAT flag is specified.Many of the O ATTR flags only apply when creating files.

For example, if the O ATTR string specifies that a file is fixed block, but an existingfile opened for input is variable blocked, the library will continue as if the file werevariable blocked.

If a file doesn’t exist, the initial allocation sizes and attributes may be specified inthe JCL or ALLOC statement, via the O ATTR string, or may be calculated by theSystems/C library.

Attributes are combined from these sources in the following order.

If the ”preopen” attribute is not enabled, then the value from the JCL or ALLOCstatement are used first. If ”preopen” is specified, then the values specified in theO ATTR string are used first. That is, if ”preopen” is specified, the constructed DCBis initialized with any values specified in O ATTR, otherwise it is not. If during OPENprocessing (in the OPEN exit routine), values are not provided then the ones specified

Systems/C C Library 159

Page 178: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

from the O ATTR string are used. For any values still not defined, the following rulesare used to calculate default values.

If RECFM is unspecified and the file is opened for output with the O BINARY flag,then a RECFM=FB will be used. If the file is opened for output without the O BINARYflag, then the device is queried. If the device is a terminal, RECFM=U will be used,otherwise RECFM=FBA will be used. If the RECFM remains unspecified for an inputfile, further processing stops and the OPEN will likely fail with a errno set to EIO.

If both BLKSIZE and LRECL remain unspecified (both are zero) then the libraryexamines the RECFM to determine these values. If RECFM=U, then BLKSIZE will bethe maximum blocksize for the device, and LRECL will be zero. If RECFM=F thenBLKSIZE=LRECL=80 will be used. If RECFM=FB then LRECL will be the 80 and BLKSIZEwill be the largest blocksize that is possible for the device. If RECFM=V then theBLKSIZE will be the maximum blocksize that is possible for the device, and LRECLwill be the lessedr of BLKSIZE-4 and 1028.

If LRECL is provided, but BLKSIZE is not, then for RECFM=U files, the BLKSIZE becomesLRECL and LRECL is set to zero. For RECFM=F files, the BLKSIZE is set to be the sameas the LRECL, and for RECFM=FB files, the BLKSIZE is set to be the largest multipleof the LRECL that can fit in the maximum blocksize of the device. For RECFM=V filesthe BLKSIZE is set to LRECL+4.

If LRECL is not provided, but BLKSIZE is, then for RECFM=U, LRECL is set to 0. ForRECM=F and RECFM=FB, LRECL is set to be the BLKSIZE value. For RECFM=V files,LRECL is set to the lesser of BLKSIZE-4 and 1028.

For BSAM I/O, if the DCB has a DCBNCP value of 0 or 1 and the ncp attribute wasused and it specifies a value larger than 1, then the specified ncp attribute value isused.

For example, the following statement creates a new file RECFM=FB, USER.FILE, spec-ifying that the primary allocation is 1000 blocks, the secondary allocation is 500blocks, the record length is 80 and the block size is 800 (note the specification ofO CREAT which causes the library to create the file if it doesn’t exist):

open("//DSN:USER.FILE", O_WRONLY|O_CREAT|_O_ATTR|_O_BINARY,0,

"recfm=fb,blksize=800,lrecl=80,blks,primary=1000,secondary=500");

Note that combining values via the O ATTR string and JCL or other sources maycreate conflicting values that cause the open() to fail. For example, if the JCLonly specifies LRECL=133 and the program provides an attribute string that specifies"recfm=fb,lrecl=80,blksize=8000", then the resulting combined attributes willbe RECFM=FB,LRECL=133,BLKSIZE=8000 which is invalid because the BLKSIZE is nota multiple of the LRECL. In such a situation, the "preopen" attribute can be usedto indicate that the values specified in the O ATTR string take precedence over thevalues from the JCL.

160 Systems/C C Library

Page 179: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

To ensure a file does not previously exist, use the O EXCL flag. If O EXCL is specifiedin combination with O CREAT, and the file already exists, the open() function willreturn -1 and indicate the error in errno.

RECORD I/O

Typically, the C model of I/O is simply a stream of bytes; without considerationof record lengths or boundaries. The Systems/C runtime presents this abstractionto the C program, managing block and record considerations internally. Thus, forexample, a read(2) request of 500 bytes will internally deblock a file, and gather 500bytes, crossing any record boundaries as needed.

However, there are situations in mainframe programming environemnts where it ishelpful to manage data in terms of records. Specifying O RECIO in the flags causesthe Systems/C runtime to respect record boundaries. If O RECIO a write(2) requestwill only write a record-sized portion of data. Similarly, a read(2) request will onlyread a record-sized portion of data. After each I/O operation, the file pointer movesto the next record boundary. The ”type=record” attribute can be used as well asO RECIO. The ”type=record” attribute causes the O RECIO flag to be set.

The read(2), write(2), sections have more information on different semantics whenO RECIO is present in flags. The fopen(3), fread(3), fwrite(3) sections have moreinformation on different semantics when the type=record attribute is specified.Note that type=record attribute enables record I/O for fopen(3), fread(3), fwrite(3)while the O RECIO flag enables record I/O for open(2), read(2) and write(2). Whentype=record attribute is specified in open(2), it is translated to the O RECIO flag.

IMPLEMENTATION NOTES

Because fopen(3) uses open(2) to access files, the path prefixes discussed above arealso valid for fopen(3) path names. Furthermore, any attributes string fopen(3)receives is similar simply passed to open(2).

O APPEND mode is only supported on sequential files. An open of a PDS memberwith O APPEND will cause a runtime abend when the file is subsequently closed.

RETURN VALUES

If successful, open() returns a non-negative integer, termed a file descriptor. Itreturns -1 on failure, and sets errno to indicate the error.

ERRORS

The named file is opened unless:

Systems/C C Library 161

Page 180: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

[ENOTDIR] A component of the path prefix is not a directory.

[ENAMETOOLONG] A component of a pathname was too large for the given path prefixstyle, or an entire path name exceeded 1023 characters.

[ENOENT] O CREAT is not set and the named file does not exist.

[ENOENT] A component of the path name that must exist does not exist.

[EACCES] Search permission is denied for a component of the path prefix.

[EACCES] The required permissions (for reading and/or writing) are deniedfor the given flags.

[EACCES] O CREAT is specified, the file does not exist, and creation of the filewas not permitted.

[ELOOP] Too many symbolic links were encountered in translating the path-name.

[EISDIR] The named file is a directory or PDS, and the arguments specify itis to be opened for writing.

[EROFS] The named file resides on a read-only file system, and the file is tobe modified.

[EMFILE] The process has already reached its limit for open file descriptors.

[ENFILE] The system file table is full.

[ENOMEM] There was insufficient memory available to allocate the supportingdata structures needed.

[ENXIO] The named file is a character special or block special file, and thedevice associated with this special file does not exist.

[EINTR] The open() operation was interrupted by a signal.

[EOPNOTSUPP] O SHLOCK or O EXLOCK is specified but the underlying filesystem doesnot support locking.

[ENOSPC] O CREAT is specified, the file does not exist, and the directory orPDS in which the entry for the new file is being placed cannot beextended because there is no space left on the file system containingthe directory, or the PDS containing the member.

[EDQUOT] O CREAT is specified, the file does not exist, and the user’s allocationquota on the file system on which the file is being created has beenexhausted.

[EFTYPE] An attempt was made to open a Format-F file where the LRECLwas not a multiple of the BLKSIZE, or a blocked Format-V filewhere the LRECL was not less than BLKSIZE-4.

162 Systems/C C Library

Page 181: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

[EIO] An I/O error occurred while making the directory entry or allocatingthe PDS directory entry for O CREAT.

[EFAULT] Path points outside the process’s allocated address space.

[EEXIST] O CREAT and O EXCL were specified and the file exists.

[EOPNOTSUPP] An attempt was made to open a socket (not currently implemented).

[EINVAL] An attempt was made to open a descriptor with an illegal combi-nation of O RDONLY, O WRONLY, and O RDWR.

SEE ALSO

close(2), dup(2), getdtablesize(2), lseek(2), setmode(2),read(2), write(2)

Systems/C C Library 163

Page 182: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

OSDDINFO(2)

NAME

osddinfo - retrieve information about a dataset from a DD name.

SYNOPSIS

#include <machine/syscio.h>

int osddinfo(char *ddname, char dsname[45], char member[9],char *recfm_p, int *lrecl_p, int *blksize_p);

DESCRIPTION

The osddinfo() function is used to retrieve data set information based on the givenddname. ddname is a NUL-terminated character string specifying the DD name ofthe data set.

The remaining parameters are pointers to areas to contain return information. Ifthe pointers are NULL, then osddinfo() does not store the value. Because somevalues may require invocation of additional operating systems services, it is best tomake these NULL if the information is not required.

The data set name associated with the DD name ddname is stored in the areapointed-to by dsname.

If the DD name is allocated to a member of a PDS, the member name is stored inthe area pointed-to by member. If a PDS member is not allocated to the DD name,the empty string is stored there.

The area pointed to by a non-NULL recfm p will contain the record-format flag of thefile. Possible values are defined in the ¡machine/syscio.h¿ header file and include:

RECFM U Undefined length records

RECFM F Fixed length records

RECFM V Variable length records

RECFM D Variable length ASCII records

RECFM T Track overflow

RECFM B Blocked records

RECFM S Spanned or Standard records

164 Systems/C C Library

Page 183: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

RECFM A ASA control characters are present

RECFM M Machine control characters are present

The values for these are the defined by the JFCB DSECT.

Note that RECFM U is defined as RECFM F logically OR’d with RECFM V. So, care mustbe taken to test for RECFM U before testing for RECFM F or RECFM V.

The area pointed to by a non-NULL lrecl p contains the data sets logical record length,or 0. If the record format can be determined, and it is Variable Spanned, and therecord length is defined as LRECL=X, then the special value LRECL X is returned.LRECL X is defined in the ¡machine/syscio.h¿ header file.

The area pointed to by a non-NULL blksize p contains the data sets block size, or 0.

RETURN VALUES

The osddinfo() return 0 if the DD name is defined and the information can beretrieved. If osddinfo() cannot retrieve the information, or can’t allocate sufficientmemory to operate, it returns -1.

IMPLEMENTATION NOTES

The osddinfo() function uses the RJFJCB service to determine the dataset name andmember associated with a DD name. If the allocation that created the JFCB controlblock did not include RECFM/LRECL/BLKSIZE statements, then osddinfo() usesthe OBTAIN service to retrieve the information from the VTOC.

SEE ALSO

ddnfind(2), ddnnext(2)

Systems/C C Library 165

Page 184: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

PASSWD(2)

NAME

passwd - verify or change a user password

SYNOPSIS

#include <pwd.h>

int__passwd(const char *username, const char *oldpass, const char *newpass);

DESCRIPTION

passwd() verifies or changes the password of the user specified by username. Old-pass contains the current password and must always be present. Newpass optionallycontains the new password, or can be NULL.

If newpass is non-NULL, then the old password is verified, and if it matches newpassbecomes the new password.

If newpass is NULL, then the old password is simply verified, and the passwordremains unchanged.

RETURN VALUES

If successful, passwd() returns a 0, otherwise -1 is returned and the global variableerrno is set to indicate the error.

ERRORS

passwd() The passwd() function will fail if:

[EACCES] The password in oldpass is not authorized.

[EINVAL] The username, oldpass or newpass is invalid. username, oldpass andnewpass must be 1 to 8 characters in length.

[ENEEDAUTH] The BPX.DAEMON facility is defined, but the current program is isnot considered controled by a security product (e.g. RACF.)

166 Systems/C C Library

Page 185: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

[EPERM] The caller does not have permission for this operation. See theBPX.DAEMON class in the IBM “OpenEdition Planning” manual.

[ESRCH] The specified username was not found.

SEE ALSO

getpwent(2), endpwent(3)

Systems/C C Library 167

Page 186: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

PATHCONF(2)

NAME

pathconf, fpathconf - get configurable pathname variables for //HFS: files

SYNOPSIS

#include <unistd.h>

longpathconf(const char *path, int name);

longfpathconf(int fd, int name);

DESCRIPTION

The pathconf() and fpathconf() functions provide a method for applications todetermine the current value of a configurable system limit or option variable asso-ciated with a pathname or file descriptor.

For pathconf(), the path argument is the name of an //HFS:-style file or directory.For fpathconf(), the fd argument is an open file descriptor that references an//HFS:-style file or directory. The name argument specifies the system variable tobe queried. Symbol constants for each name value are found in the include file<unistd.h>.

The availalble values are as follows:

PC LINK MAX The maximum file link count.

PC MAX CANON The maximum number of bytes in terminal canonical input line.

PC MAX INPUT The minimum maximum number of bytes for which space is availablein a terminal input queue.

PC NAME MAX The maximum number of bytes in a file name.

PC PATH MAX The maximum number of bytes in a pathname.

PC PIPE BUF The maximum number of bytes which will be written atomically to apipe.

PC CHOWN RESTRICTED Return 1 if appropriate privileges are required for thechown(2) system call, otherwise 0.

168 Systems/C C Library

Page 187: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

PC NO TRUNC Return 1 if file names longer than KERN NAME MAX are truncated.

PC VDISABLE Returns the terminal character disabling value.

RETURN VALUES

if the call to pathconf() or fpathconf() is not successful, -1 is returned an errnois set appropriately. Otherwise, if the variable is associated with functionality thatdoes not have a limit in the system, -1 is returned and errno is not modified.Otherwise, the current variable value is returned.

ERRORS

If any of the following conditions occur, the pathconf() and fpathconf() functionsshall return -1 and set errno to the corresponding value.

[EINVAL] The value of the name argument is invalid.

[EINVAL] The implementation does not support an association of the variablename with the associated file.

pathconf() will fail if:

[ENOTDIR] A component of the path prefix is not a directory.

[ENAMETOOLONG] A component of a pathname exceeded 255 characters, or anentire path name exceeded 1023 characters.

[ENOENT] The named file does not exist.

[EACCES] Search permission is denied for a component of the path prefix.

[ELOOP] Too many symbolic links were encountered in translating the path-name.

[EIO] An I/O error occurred while reading from or writing to the filesystem.

fpathconf() will fail if:

[EBADF] fd is not a valid open file descriptor.

[EIO] An I/O error occurred while reading from or writing to the filesystem.

Systems/C C Library 169

Page 188: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

PIPE(2)

NAME

pipe, pipe2 - create descriptor pair for interprocess communication

SYNOPSIS

#include <unistd.h>

intpipe(int fildes[2]);

intpipe2(int fildes[2], int flags);

The pipe() function creates a “pipe”, which is an object allowing bidirectional dataflow, and allocates a pair of file descriptors.

The pipe2() function allows control over the attributes of the file descriptors viathe flags argument. Values for flags are constructed by a bitwise-inclusive OR offlags from the following list, defined in ¡fcntl.h¿:

O CLOEXEC Set the close-on-exec flag for the new file descriptors.

O NONBLOCK Set the non-blocking flag for the ends of the pipe.

If the flags argument is 0, the behavior is identical to a call to pipe().

The first descriptor is used as the “read end” of the pipe, the second is the “writeend”, so that data written to filedes[1] appears on (i.e. can be read from) fileds[0].This allows the output of one program to be sent to another program: the source’sstandard output can be set up to be the “write end” of the pipe, and the sink’sstandard input is set up to tbe the “read end” of the pipe. The pipe itself persistsuntil all its associated descriptors are closed.

A pipe that has had an end closed is considered “widowed.” Writing on such a pipemay cause the writing process to receive a SIGPIPE signal. Widowing a pipe is theonly way to deliver end-of-file to a reader: after the reader consumes any buffereddata, reading a widowed pipe returns a zero count.

IMPLEMENTATION NOTES

The pipe2() function calls the pipe() system call and then calls fcntl to set theappropriate flags.

170 Systems/C C Library

Page 189: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

RETURN VALUES

The pipe() function will fail if:

[EMFILE] Too many descriptors are active.

[ENFILE] The system file table is full.

[EFAULT] The fildes buffer is in an invalid area of the process’s address space.

SEE ALSO

read(2), write(2)

Systems/C C Library 171

Page 190: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

PROCNAME(2)

NAME

procname - return the current procedure name

SYNOPSIS

#include <machine/tiot.h>

char *__procname(void);

DESCRIPTION

The procname() function returns the current JCL procedure name of the exe-cuting program on MVS, OS/390 and z/OS. The value returned is a pointer to aNUL-terminated string. Trailing blanks are removed.

If the program was invoked directly, the returned name will be the empty string.

procname() returns a pointer to a static area, care should be taken to copy thisvalue before invoking procname() again.

SEE ALSO

jobname(2), stepname(2), userid(2)

172 Systems/C C Library

Page 191: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

QUERYDUB(2)

NAME

querydub - return the current procedure name

SYNOPSIS

#include <unistd.h>

int __querydub(void);

DESCRIPTION

The querydub() function returns BPX ”dub” status of the current task, indicat-ing if the task has already been dubbed, or can possibly be dubbed.

RETURN VALUES

If successful, querydub() returns one of these values:

QDB DUBBED FIRST The task has already been dubbed. This task and this RB causedthe dub.

QDB DUBBED The task has already been dubbed. Another task or another RBcaused the dub.

QDB DUB MAY FAIL The task has not been dubbed, and any attempt to do so mightfail (typically due to bad or missing authorizations.)

QDB DUB OKAY The task has not been dubbed, and any attempt will likely succeed.

QDB DUB AS PROCESS The task has not beed dubbed, but its address space has. Adub of this task will result in a new process.

QDB DUB AS THREAD The task has not been dubbed, but its address space has. Adub of this task will result in a new thread within the process.

If not successful, querydub() returns -1 and sets an error condition in errno.

SEE ALSO

isPosixOn(2)

Systems/C C Library 173

Page 192: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

READ(2)

NAME

read - read input

SYNOPSIS

#include <sys/types.h>#include <sys/uio.h>#include <unistd.h>

size_tread(int d, void *buf, size_t nbytes)

DESCRIPTION

read() attempts to read nbytes of data from the object referenced by the descriptord into the buffer pointed to by buf.

On objects capable of seeking, the read() starts at a position given by the pointerassociated with d (see lseek(2)). Upon return from read(), the pointer is incre-mented by the number of bytes actually read.

Objects that are not capable of seeking always read from the current position. Thevalue of the pointer associated with such an object is undefined.

Upon successful completion, read() and readv() return the number of bytes actu-ally read and placed in the buffer. The system guarantees to read the number ofbytes requested if the descriptor references a normal file that has that many bytesleft before the end-of-file, but in no other case.

IMPLEMENTATION NOTES

If a file descriptor has been opened in O TEXT mode (the default), and referencesrecord-structured (non-//HFS: and non-socket) file, records will be read from theassociated file, with trailing blanks removed, and a new-line character appended.If the lrecl of the file is 1, or the file descriptor is a socket, or the file descriptorreferences an HFS file, the bytes are read as if O BINARY had been specified.

If the file descriptor has been opened with O RECIO flag, and the file descriptor ref-erences a record-structured file, then the read operation is performed using “recordI/O”. In this situation, the read will read the next record in the file, returning thatmany bytes. If nbytes is smaller than the record length, the file pointer will beadvanced to the start of the next record.

174 Systems/C C Library

Page 193: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

RETURN VALUES

If successful, the number of bytes actually read is returned. Upon reading end-of-file, zero is returned. Otherwise, a -1 is returned and the global variable errno isset to indicate the error.

When reading from a file with variable-length records using “record I/O”, it ispossible to encounter a zero-length record. Instead of returning zero (which wouldindicate end-of-file), the read() function will return -1 and set errno to EAGAIN.Thus, a program reading variable-length records can distinguish between end-of-fileand a zero-length record.

ERRORS

read() will succeed unless:

[EBADF] d is not a valid file or socket descriptor open for reading.

[EFAULT] buf points outside the allocated address space.

[EIO] An I/O error occurred while reading from the file system.

[EINTR] A read from a slow device was interrupted before any data arrivedby the delivery of a signal.

[EINVAL] The pointer associated with d was negative.

[EAGAIN] The file was marked for non-blocking I/O, and no data were readyto be read, or the file is a variable-length record file using recordI/O and a zero-length record was encountered.

[ENXIO] The file is not a supported I/O format.

SEE ALSO

dup(2), fcntl(2), open(2)

STANDARDS

The read() function call is expected to conform to IEEE Std1003.1-1990(“POSIX”), as closely as the host file system allows.

Systems/C C Library 175

Page 194: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

READLINK(2)

NAME

readlink – read value of an //HFS:-style symbolic link

SYNOPSIS

#include <unistd.h>

intreadlink(const char *path, char *buf, int bufsiz);

DESCRIPTION

readlink() places the contents of the symbolic link path in the buffer buf, whichhas size bufsiz. The readlink() function does not append a NUL character to buf.

RETURN VALUES

The call returns the count of characters placed in the buffer if it succeeds, or a -1 ifan error occurs, placing the error code in the global variable errno.

ERRORS

readlink() will fail if:

[ENOTDIR] A component of the path prefix is not a directory.

[ENAMETOOLONG] A component of a pathname exceeded 255 characters, or an entirepath name exceeded 1023 characters.

[ENOENT] The named file does not exist.

[EACCES] Search permission is denied for a component of the path prefix.

[ELOOP] Too many symbolic links were encountered in translating the path-name.

[EINVAL] The named file is not a symbolic link.

[EIO] An I/O error occurred while reading from the file system.

[EFAULT] Buf extends outside the process’s allocated address space.

176 Systems/C C Library

Page 195: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

RENAME(2)

NAME

rename - change the name of a file

SYNOPSIS

#include <stdio.h>

intrename(const char *from, const char *to);

DESCRIPTION

rename() causes the file named from to be renamed as to. If to exists, it is firstremoved. Both from and to must be of the same type (that is, both DSN names,or both PDS members, or both HFS directories or both HFS non-directories), andmust reside on the same file system. The types of from and to are determined bythe Systems/C file naming conventions. See open(2) for more information regardingSystems/C file names.

IMPLEMENTATION NOTES

Only renaming of //DSN:-style and //HFS:-style names are supported in this release.

//DSN: style files must be entirely contained with 5 volumes, or rename() will fail.

RETURN VALUES

A 0 value is returned if the operation succeeds, otherwise rename() returns -1 andthe global variable errno indicates the reason for the failure.

ERRORS

rename() will fail and neither of the argument files will be affected if:

[ENAMETOOLONG] For HFS files, a component of either name exceeded 255 characters,or the entire length of either path name exceeded 1023 characters.

Systems/C C Library 177

Page 196: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

[ENAMETOOLONG] For DSN files, a name was longer than 44 characters.

[ENOENT] A component of the from path does not exist, or a path prefix of todoes not exist.

[EACCES] For HFS files, A component of either path prefix denies search per-mission.

[EACCES] For DSN files, the VTOC LOCATE macro indicates an acces viola-tion.

[EACCES] The requested link requires writing in an HFS directory, a PDSdirectory or a VTOC with a mode that denies write permission.

[EPERM] For DSN files, permission was not granted to uncatalog the fromname, or permission was not granted to catalog the to name.

[EPERM] For DSN files, permission was not granted to perform the RENAMEoperation.

[EPERM] The HFS directory containing from is marked sticky, and neitherthe containing directory nor from are owned by the effective userID.

[EPERM] For HFS files, the to file exists, the HFS directory containing to ismarked sticky, and neither the containing directory nor to are ownedby the effective user ID.

[ELOOP] Too many symbolic links were encountered in translating eitherpathname for HFS files.

[ENOMEM] For DSN files, insufficient memory was available to perform theoperation.

[ENOSYS] For DSN files, the from spans more than 5 volumes.

[ENOSYS] The rename operation involves unsupported file types.

[ENOTDIR] A component of either path prefix is not a directory for HFS files.

[ENOTDIR] from is an HFS directory, but to is not an HFS directory.

[EISDIR] to is an HFS directory, but from is not a HFS directory

[EXDEV] The link named by to and the file named by from are on differentlogical devices (file systems). Or, the file types of to and from do notmatch (i.e. to is a DSN and from is a DDN.) Note that this errorcode will not be returned if the implementation permits cross-devicelinks.

[ENOSPC] The HFS directory, or VTOC, or PDS directory in which the entryfor the new name is being placed cannot be extended because thereis no space left.

178 Systems/C C Library

Page 197: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

[EDQUOT] The HFS directory in which the entry for the new name is beingplaced cannot be extended because the user’s quota of disk blockson the file system containing the directory has been exhausted.

[EIO] An I/O error occurred while making or updating an HFS directoryentry, or a VTOC or a PDS directory.

[EROFS] The requested link requires writing in an HFS directory, VTOC orPDS directory on a read-only file system.

[EFAULT] Either the from or to argument is NULL, or either from or to was apointer outside of the allocated address space.

[EINVAL] from is an invalid name.

[ENOTEMPTY] to is a directory and is not empty.

SEE ALSO

open(2)

STANDARDS

The rename() function call is expected to conform to ISO/IEC 9945-1:1990(“POSIX.1”) as closely as the host operating system allows.

Systems/C C Library 179

Page 198: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

RMDIR(2)

NAME

rmdir – remove a directory file

SYNOPSIS

#include <unistd.h>

intrmdir(const char *path);

DESCRIPTION

rmdir() removes an HFS directory file whose name is given by path. The directroymust not have any entries other that ‘.’ and ‘..’.

RETURN VALUES

The rmdir() function returns the value 0 if successful; otherwise the value -1 isreturned and the global variable errno is set to indicate the error.

ERRORS

The named file is removed unless:

[ENOTDIR] A component of the path is not a directory.

[ENAMETOOLONG] A component of a pathname exceeded 255 characters, or an entirepath name exceeded 1023 characters.

[ENOENT] The named directory does not exist.

[ELOOP] Too many symbolic links were encountered in translating the path-name.

[ENOTEMPTY] The named directory contains files other than ‘.’ and ‘..’ in it.

[EACCES] Search permission is denied for a component of the path prefix.

[EACCES] Write permission is denied on the directory containing the link tobe removed.

180 Systems/C C Library

Page 199: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

[EPERM] The directory containing the directory to be removed is markedsticky, and neither the containing directory nor the directory to beremoved are owned by the effective user ID.

[EBUSY] The directory to be removed is the mount point for a mounted filesystem.

[EIO] An I/O error occurred while deleting the directory entry or deallo-cating the inode.

[EROFS] The directory entry to be removed resides on a read- only file system.

[EFAULT] Path points outside the process’s allocated address space.

SEE ALSO

mkdir(2), unlink(2)

Systems/C C Library 181

Page 200: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

SCHED YIELD(2)

NAME

sched yield – yield processor

SYNOPSIS

#include <sched.h>

intsched_yield(void);

DESCRIPTION

The sched yield() system call forces the running process to relinquish the processoruntil it again becomes the head of its process list. It takes no arguments.

RETURN VALUES

The sched yield() function returns the value 0 if successful; otherwise the value-1 is returned and the global variable errno is set to indicate the error.

ERRORS

On failure errno will be set to the corresponding value:

[ENOSYS] The system is not configured to support this functionality.

STANDARDS

The sched yield() system call conforms to IEEE Std 1003.1b-1993 (“POSIX.1”).

182 Systems/C C Library

Page 201: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

SEMCTL(2)

NAME

semctl - control operations on a semaphore set

SYNOPSIS

#include <sys/types.h>#include <sys/ipc.h>#include <sys/sem.h>

intsemctl(int semid, int semnum, int cmd, ...);

DESCRIPTION

semctl() performs the operation indicated by cmd on the semaphore set indicatedby semid. A fourth argument, a union semun arg, is required for certain valuesof cmd. For the commands that use the arg parameter, union semun is defined asfollows:

union semun {int val; /* value for SETVAL */struct semid_ds *buf; /* buffer for IPC_STAT & IPC_SET */u_short *array; /* array for GETALL & SETALL */

};

Commands are performed as follows:

IPC STAT Fetch the semaphore set’s struct semid ds, storing it in the mem-ory pointed to by arg.buf.

IPC SET Changes the sem perm.uid, sem perm.gid, and sem perm.modemembers of the semaphore set’s struct semid ds to match thoseof the struct pointed to by arg.buf. The calling process’s effectiveuid must match either sem perm.uid or sem perm.cuid, or it musthave superuser privileges.

IPC RMID Immediately removes the semaphore set from the system. Thecalling process’s effective uid must equal the semaphore set’ssem perm.uid or sem perm.cuid, or the process must have supe-ruser privileges.

Systems/C C Library 183

Page 202: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

GETVAL Return the value of semaphore number semnum.

SETVAL Set the value of semaphore number semnum to arg.val.

GETPID Return the pid of the last process to perform an operation onsemaphore number semnum.

GETNCNT Return the number of processes waiting for semaphore number sem-num’s value to become greater than its current value.

GETZCNT Return the number of processes waiting for semaphore number sem-num’s value to become 0.

GETALL Fetch the value of all of the semaphores in the set into the arraypointed to by arg.array.

SETALL Set the values of all of the semaphores in the set to the values inthe array pointed to by arg.array.

The struct semid ds is defined as follows:

struct semid_ds {struct ipc_perm sem_perm; /* operation permission struct */struct sem *sem_base; /* pointer to first semaphore in set */u_short sem_nsems; /* number of sems in set */time_t sem_otime; /* last operation time */long sem_pad1; /* SVABI/386 says I need this here */time_t sem_ctime; /* last change time */

/* Times measured in secs since *//* 00:00:00 GMT, Jan. 1, 1970 */

long sem_pad2; /* SVABI/386 says I need this here */long sem_pad3[4]; /* SVABI/386 says I need this here */

};

The sem base field is provided for compatibility with other operating systems, buton OS/390 and z/OS, this field will always be NULL.

RETURN VALUES

On success, when cmd is one of GETVAL, GETPID, GETNCNT or GETZCNT, semctl()returns the corresponding value; otherwise, 0 is returned. On failure, -1 is returned,and errno is set to indicate the error.

184 Systems/C C Library

Page 203: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

ERRORS

semctl() will fail if:

[EINVAL] No semaphore set corresponds to semid.

[EINVAL] semnum is not in the range of valid semaphores for given semaphoreset.

[EPERM] The calling process’s effective uid does not match the uid of thesemaphore set’s owner or creator.

[EACCES] Permission denied due to mismatch between operation and mode ofsemaphore set.

SEE ALSO

semget(2), semop(2)

Systems/C C Library 185

Page 204: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

SEMGET(2)

NAME

semget - obtain a semaphore id

SYNOPSIS

#include <sys/types.h>#include <sys/ipc.h>#include <sys/sem.h>

intsemget(key_t key, int nsems, int flag);

DESCRIPTION

Based on the values of key and flag, semget() returns the identifier of a newlycreated or previously existing set of semaphores. The key is analogous to a filename:it provides a handle that names an IPC object. There are three ways to specify akey:

• IPC PRIVATE may be specified, in which case a new IPC object will be created.

• An integer constant may be specified. If no IPC object corresponding to keyis specified and the IPC CREAT bit is set in flag, a new one will be created.

• ftok() may be used to generate a key from a pathname. See ftok(3).

The mode of the newly created IPC object is determined by OR’ing the followingconstants into the flag parameter:

SEM R Read access for user.

SEM A Alter access for user.

(SEM R>>3) Read access for group.

(SEM A>>3) Alter access for group.

(SEM R>>6) Read access for other.

(SEM A>>6) Alter access for other.

If a new set of semaphores is being created, nsems is used to indicate the numberof semaphores the set should contain. Otherwise, nsems may be specified as 0.

186 Systems/C C Library

Page 205: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

RETURN VALUES

semget() returns the id of a semaphore set if successful; otherwise, -1 is returnedand errno is set to indicate the error.

ERRORS

semget() will fail if:

[EACCES] Access permission failure.

[EEXIST] IPC CREAT and IPC EXCL were specified, and a semaphore set cor-responding to key already exists.

[EINVAL] The number of semaphores requested exceeds the system imposedmaximum per set.

[ENOSPC] Insufficiently many semaphores are available.

[ENOSPC] The system could not allocate a struct semid ds.

[ENOENT] No semaphore set was found corresponding to key, and IPC CREATwas not specified.

SEE ALSO

semctl(2), semop(2), ftok(3)

Systems/C C Library 187

Page 206: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

SEMOP(2)

NAME

semop - atomic array of operations on a semaphore set

SYNOPSIS

#include <sys/types.h>#include <sys/ipc.h>#include <sys/sem.h>

intsemop(int semid, struct sembuf array[], unsigned nops);

DESCRIPTION

semop() atomically performs the array of operations indicated by array on thesemaphore set indicated by semid. The length of array is indicated by nops. Eachoperation is encoded in a struct sembuf, which is defined as follows:

struct sembuf {u_short sem_num; /* semaphore # */short sem_op; /* semaphore operation */short sem_flg; /* operation flags */

};

For each element in array, sem op and sem flg determine an operation to beperformed on semaphore number sem num in the set. The values SEM UNDO andIPC NOWAIT may be OR’ed into the sem flg member in order to modify the behav-ior of the given operation.

The operation performed depends as follows on the value of sem op:

• When sem op is positive, the semaphore’s value is incremented by sem op’svalue. If SEM UNDO is specified, the semaphore’s adjust on exit value is decre-mented by sem op’s value. A positive value for sem op generally correspondsto a process releasing a resource associated with the semaphore.

• The behavior when sem op is negative depends on the current value of thesemaphore:

188 Systems/C C Library

Page 207: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

– If the current value of the semaphore is greater than or equal to theabsolute value of sem op, then the value is decremented by the absolutevalue of sem op. If SEM UNDO is specified, the semaphore’s adjust on exitvalue is incremented by the absolute value of sem op.

– If the current value of the semaphore is less than sem op’s value, one ofthe following happens:

∗ If IPC NOWAIT was specified, then semop() returns immediately witha return value of EAGAIN.

∗ If some other process has removed the semaphore with the IPC RMIDoption of semctl(), then fnnamesemop() returns immediately witha return value of EINVAL.

∗ Otherwise, the calling process is put to sleep until the semaphore’svalue is greater than or equal to the absolute value of sem op. Whenthis condition becomes true, the semaphore’s value is decrementedby the absolute value of sem op, and the semaphore’s adjust on exitvalue is incremented by the absolute value of sem op.

A negative value for sem op generally means that a process is waiting fora resource to become available.

• When sem op is zero, the process waits for the semaphore’s value to becomezero. If it is already zero, the call to semop() can return immediately. Oth-erwise, the calling process is put to sleep until the semaphore’s value becomeszero.

For each semaphore a process has in use, the operating system maintains an ‘adjuston exit’ value, as alluded to earlier. When a process exits, either voluntarily orinvoluntarily, the adjust on exit value for each semaphore is added to the semaphore’svalue. This can be used to insure that a resource is released if a process terminatesunexpectedly.

RETURN VALUES

The semop() function returns the value 0 if successful; otherwise the value -1 isreturned and the global variable errno is set to indicate the error.

ERRORS

semop() will fail if:

[EINVAL] No semaphore set corresponds to semid.

[EACCES] Permission denied due to mismatch between operation and mode ofsemaphore set.

Systems/C C Library 189

Page 208: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

[EAGAIN] The semaphore’s value was less than sem op, and IPC NOWAIT wasspecified.

[E2BIG] Too many operations were specified.

[EFBIG] sem num was not in the range of valid semaphores for the set.

SEE ALSO

semctl(2), semget(2)

190 Systems/C C Library

Page 209: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

SETGROUPS(2)

NAME

setgroups - set group access list

SYNOPSIS

#include <sys/param.h>#include <unistd.h>

intsetgroups(int ngroups, const gid_t *gidset);

DESCRIPTION

setgroups() sets the group access list of the current user process according to thearray gidset. The parameter ngroups indicates the number of entries in the arrayand must be no more than NGROUPS, as defined in <sys/param.h>.

Only the super-user may set new groups.

RETURN VALUES

The setgroups() function returns the value 0 if successful; otherwise the value -1is returned and the global variable errno is set to indicate the error.

ERRORS

The setgroups() call will fail if:

[EPERM] The caller is not the super-user.

[EFAULT] The address specified for gidset is outside the process address space.

SEE ALSO

getgroups(2)

Systems/C C Library 191

Page 210: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

SETMODE(2)

NAME

setmode - sets the file text vs. binary translation mode.

SYNOPSIS

#include <fcntl.h>

int_setmode(int d, int mode)

DESCRIPTION

setmode() alters the binary vs. text flag of the file descriptor d, setting it to thegiven mode. setmode returns the previous mode value.

mode must be either O TEXT or O BINARY. O TEXT sets the file descriptor to textmode, O BINARY to binary mode. See open(2) for a description of these I/O trans-lation modes.

setmode() is typically used to change the default translation mode of stdin andstdout, but can be used on any open file. setmode() should be applied beforeperforming any input or output on the file descriptor.

RETURN VALUES

If successful, the previous mode value is returned. Otherwise, a -1 is returned andthe global variable errno is set to indicate the error.

ERRORS

setmode() will succeed unless:

[EBADF] d is not a valid, open file descriptor.

[EINVAL] mode is not O TEXT nor O BINARY.

SEE ALSO

fcntl(2), open(2), read(2), write(2)

192 Systems/C C Library

Page 211: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

SETPGID(2)

NAME

setpgid, setpgrp - set process group

SYNOPSIS

#include <unistd.h>

intsetpgid(pid_t pid, pid_t pgrp);

intsetpgrp(pid_t pid, pid_t pgrp);

DESCRIPTION

setpgid() sets the process group of the specified process pid to the specified pgrp.If pid is zero, then the call applies to the current process.

If the invoker is not the super-user, then the affected process must have the sameeffective user-id as the invoker or be a descendant of the invoking process.

RETURN VALUES

The setpgid() function returns the value 0 if successful; otherwise the value -1 isreturned and the global variable errno is set to indicate the error.

ERRORS

setpgid() will fail and the process group will not be altered if:

[EACCES] Pid is a valid child of the current process, but pid has been ex-ecve(2)’d. Access to the target process was denied.

[EINVAL] pgrp is an invalid process group.

[EPERM] The effective user ID of the requested process is different from that ofthe caller and the process is not a descendent of the calling process.

[ESRCH] The requested process does not exist.

Systems/C C Library 193

Page 212: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

SEE ALSO

getpgrp(2)

STANDARDS

The setpgid() function call is expected to conform to ISO/IEC 9945-1:1990(“POSIX.1”) as closely as the host system allows.

COMPATIBILITY

setpgrp() is identical to setpgid(), and is provided for calling convention compat-ibility with historical versions of BSD UNIX.

194 Systems/C C Library

Page 213: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

SETREGID(2)

NAME

setregid - set real and effective group ID

SYNOPSIS

#include <unistd.h>

intsetregid(gid_t rgid, gid_t egid);

DESCRIPTION

The real and effective group ID’s of the current process are set to the arguments.Unprivileged users may change the real group ID to the effective group ID andvice-versa; only the super-user may make other changes.

Supplying a value of -1 for either the real or effective group ID forces the system tosubstitute the current ID in place of the -1 parameter.

Historically, the setregid() function was intended to allow swapping the real andeffective group IDs in set-group-ID programs to temporarily relinquish the set-group-ID value. This function did not work correctly, and its purpose is now better servedby the use of the setegid() function (see setuid(2)).

When setting the real and effective group IDs to the same value, the standardsetgid() function is preferred.

RETURN VALUES

The setregid() function returns the value 0 if successful; otherwise the value -1 isreturned and the global variable errno is set to indicate the error.

ERRORS

[EAGAIN] A RACF failure has occured.

[EINVAL] One of the parms is an invalid user id.

[EPERM] The current process is not the super-user and a change other thanchanging the effective group-id to the real group-id was specified.

Systems/C C Library 195

Page 214: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

SEE ALSO

getgid(2), setegid(2), setgid(2), setuid(2)

196 Systems/C C Library

Page 215: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

SETREUID(2)

NAME

setreuid - set real and effective user ID’s

SYNOPSIS

#include <unistd.h>

intsetreuid(uid_t ruid, uid_t euid);

DESCRIPTION

The real and effective user IDs of the current process are set according to the argu-ments. If ruid or euid is -1, the current uid is filled in by the system. Unprivilegedusers may change the real user ID to the effective user ID and vice-versa; only thesuper-user may make other changes.

The setreuid() function has been used to swap the real and effective user IDs inset-user-ID programs to temporarily relinquish the set-user-ID value. This purposeis now better served by the use of the seteuid() function (see setuid(2)).

When setting the real and effective user IDs to the same value, the standard setuid()function is preferred.

RETURN VALUES

The setreuid() function returns the value 0 if successful; otherwise the value -1 isreturned and the global variable errno is set to indicate the error.

ERRORS

[EAGAIN] A RACF failure has occured.

[EINVAL] One of the parms is an invalid user id.

[EPERM] The current process is not the super-user and a change other thanchanging the effective user-id to the real user-id was specified.

SEE ALSO

getuid(2), seteuid(2), setuid(2)

Systems/C C Library 197

Page 216: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

SETSID(2)

NAME

setsid - create session and set process group ID

SYNOPSIS

#include <unistd.h>

pid_tsetsid(void);

DESCRIPTION

The setsid() function creates a new session. The calling process is the session leaderof the new session, is the process group leader of a new process group and has nocontrolling terminal. The calling process is the only process in either the session orthe process group.

RETURN VALUES

Upon successful completion, the setsid() function returns the value of the processgroup ID of the new process group, which is the same as the process ID of the callingprocess. If an error occurs, setsid() returns -1 and the global variable errno is setto indicate the error.

ERRORS

The setsid() function will fail if:

[EPERM] The calling process is already a process group leader, or the processgroup ID of a process other than the calling process matches theprocess ID of the calling process.

SEE ALSO

setpgid(2), tcgetpgrp(3), tcsetpgrp(3)

198 Systems/C C Library

Page 217: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

STANDARDS

The setsid() function is expected to be compliant with the ISO/IEC 9945-1:1990(“POSIX.1”) specification as closely as the host system allows.

Systems/C C Library 199

Page 218: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

SETUID(2)

NAME

setuid, seteuid, setgid, setegid - set user and group ID

SYNOPSIS

#include <sys/types.h>#include <unistd.h>

intsetuid(uid_t uid);

intseteuid(uid_t euid);

intsetgid(gid_t gid);

intsetegid(gid_t egid);

DESCRIPTION

The setuid() function sets the real and effective user IDs and the saved set-user-IDof the current process to the specified value. The setuid() function is permitted ifthe specified ID is equal to the real user ID or the effective user ID of the process,or if the effective user ID is that of the super user.

The setgid() function sets the real and effective group IDs and the saved set-group-ID of the current process to the specified value. The setgid() function is permittedif the specified ID is equal to the real group ID or the effective group ID of theprocess, or if the effective user ID is that of the super user.

The seteuid() function (setegid()) sets the effective user ID (group ID) of thecurrent process. The effective user ID may be set to the value of the real user ID orthe saved set-user-ID (see execve(2)); in this way, the effective user ID of a set-user-ID executable may be toggled by switching to the real user ID, then re-enabled byreverting to the set-user-ID value. Similarly, the effective group ID may be set tothe value of the real group ID or the saved set-group-ID.

200 Systems/C C Library

Page 219: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

RETURN VALUES

Upon successful completion, the value 0 is returned; otherwise the value -1 is re-turned and the global variable errno is set to indicate the error.

ERRORS

The functions will fail if:

[EAGAIN] A problem in RACF access occurred.

[EINVAL] An invalid user (group) id was specified.

[EPERM] The user is not the super user and the ID specified is not the real,effective ID, or saved ID.

SEE ALSO

getgid(2), getuid(2), setregid(2), setreuid(2)

STANDARDS

The setuid() and setgid() functions are compliant with the ISO/IEC 9945-1:1990(“POSIX.1”) specification with POSIX SAVED IDS not defined with the permittedextensions from Appendix B.4.2.2. The seteuid() and setegid() functions are ex-tensions based on the POSIX concept of POSIX SAVED IDS, and have been proposedfor a future revision of the standard.

Systems/C C Library 201

Page 220: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

SHMAT(2)

NAME

shmat, shmdt - attach or detach shared memory

SYNOPSIS

#include <machine/param.h>#include <sys/types.h>#include <sys/ipc.h>#include <sys/shm.h>

void *shmat(int shmid, void *addr, int flag);

intshmdt(void *addr);

DESCRIPTION

shmat() attaches the shared memory segment identified by shmid to the callingprocess’s address space. The address where the segment is attached is determinedas follows:

• If addr is 0, the segment is attached at an address selected by the system.

• If addr is nonzero and SHM RND is not specified in flag, the segment is attachedthe specified address.

• If addr is specified and SHM RND is specified, addr is rounded down to thenearest multiple of SHMLBA.

shmdt() detaches the shared memory segment at the address specified by addr fromthe calling process’s address space.

RETURN VALUES

Upon success, shmat() returns the address where the segment is attached; other-wise, -1 is returned and errno is set to indicate the error.

The shmdt() function returns the value 0 if successful; otherwise the value -1 isreturned and the global variable errno is set to indicate the error.

202 Systems/C C Library

Page 221: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

ERRORS

shmat() will fail if:

[EINVAL] No shared memory segment was found corresponding to shmid.

[EINVAL] addr was not an acceptable address.

SEE ALSO

shmctl(2), shmget(2)

Systems/C C Library 203

Page 222: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

SHMCTL(2)

NAME

shmctl - shared memory control

SYNOPSIS

#include <machine/param.h>#include <sys/types.h>#include <sys/ipc.h>#include <sys/shm.h>

intshmctl(int shmid, int cmd, struct shmid_ds *buf);

DESCRIPTION

The shmctl() function performs the action specified by cmd on the shared memorysegment identified by shmid:

IPC STAT Fetch the segment’s struct shmid ds, storing it in the memorypointed to by buf.

IPC SET Changes the shm perm.uid, shm perm.gid, and shm perm.modemembers of the segment’s struct shmid ds to match those of thestruct pointed to by buf. The calling process’s effective uid mustmatch either shm perm.uid or shm perm.cuid, or it must have su-peruser privileges.

IPC RMID Removes the segment from the system. The removal will not takeeffect until all processes having attached the segment have exited;however, once the IPC RMID operation has taken place, no furtherprocesses will be allowed to attach the segment. For the oper-ation to succeed, the calling process’s effective uid must matchshm perm.uid or shm perm.cuid, or the process must have supe-ruser privileges.

The shmid ds struct is defined as follows:

struct shmid_ds {struct ipc_perm shm_perm; /* operation permission structure */int shm_segsz; /* size of segment in bytes */

204 Systems/C C Library

Page 223: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

pid_t shm_lpid; /* process ID of last shared memory op */pid_t shm_cpid; /* process ID of creator */short shm_nattch; /* number of current attaches */time_t shm_atime; /* time of last shmat() */time_t shm_dtime; /* time of last shmdt() */time_t shm_ctime; /* time of last change by shmctl() */void *shm_internal; /* sysv stupidity */

};

The shm internal field is provided for compatibility with other functions.

RETURN VALUES

The shmctl() function returns the value 0 if successful; otherwise the value -1 isreturned and the global variable errno is set to indicate the error.

ERRORS

shmctl() will fail if:

[EINVAL] Invalid operation, or no shared memory segment was found corre-sponding to shmid.

[EPERM] The calling process’s effective uid does not match the uid of theshared memory segment’s owner or creator.

[EACCES] Permission denied due to mismatch between operation and mode ofshared memory segment.

SEE ALSO

shmat(2), shmdt(2), shmget(2), ftok(3)

Systems/C C Library 205

Page 224: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

SHMGET(2)

NAME

shmget - obtain a shared memory identifier

SYNOPSIS

#include <machine/param.h>#include <sys/types.h>#include <sys/ipc.h>#include <sys/shm.h>

intshmget(key_t key, int size, int flag);

DESCRIPTION

Based on the values of key and flag, shmget() returns the identifier of a newlycreated or previously existing shared memory segment. The key is analogous to afilename: it provides a handle that names an IPC object. There are three ways tospecify a key:

• IPC PRIVATE may be specified, in which case a new IPC object will be created.

• An integer constant may be specified. If no IPC object corresponding to keyis specified and the IPC CREAT bit is set in flag, a new one will be created.

• ftok() may be used to generate a key from a pathname. See ftok(3).

The mode of a newly created IPC object is determined by OR’ing the followingconstants into the flag parameter:

SHM R Read access for user.

SHM W Write access for user.

(SHM R>>3) Read access for group.

(SHM W>>3) Write access for group.

(SHM R>>6) Read access for other.

(SHM W>>6) Write access for other.

When creating a new shared memory segment, size indicates the desired size of thenew segment in bytes. The size of the segment may be rounded up to a multipleconvenient to the system (i.e., the page size).

206 Systems/C C Library

Page 225: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

RETURN VALUES

Upon successful completion, shmget() returns the positive integer identifier of ashared memory segment. Otherwise, -1 is returned and errno set to indicate theerror.

ERRORS

shmget() will fail if:

[EINVAL] Size specified is greater than the size of the previously existing seg-ment. Size specified is less than the system imposed minimum, orgreater than the system imposed maximum.

[ENOENT] No shared memory segment was found matching key, and IPC CREATwas not specified.

[ENOSPC] The system was unable to allocate enough memory to satisfy therequest.

[EEXIST] IPC CREAT and IPC EXCL were specified, and a shared memory seg-ment corresponding to key already exists.

SEE ALSO

shmat(2), shmctl(2), shmdt(2), ftok(3)

Systems/C C Library 207

Page 226: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

SIGACTION(2)

NAME

sigaction – software signal facilities

SYNOPSIS

#include <signal.h>

struct sigaction {union {

void (*__sa_handler)(int);void (*__sa_sigaction)(int, struct __siginfo *, void *);

} __sigaction_u; /* signal handler */int sa_flags; /* see signal options below */sigset_t sa_mask; /* signal mask to apply */

};

#define sa_handler __sigaction_u.__sa_handler#define sa_sigaction __sigaction_u.__sa_sigaction

intsigaction(int sig, const struct sigaction * restrict act,

struct sigaction * restrict oact);

int __abendcode(void);int __rsncode(void);

DESCRIPTION The system defines a set of signals that may be delivered to aprocess. Signal delivery resembles the occurrence of a hardware interrupt: thesignal is normally blocked from further occurrence, the current process context issaved, and a new one is built. A process may specify a handler to which a signalis delivered, or specify that a signal is to be ignored. A process may also specifythat a default action is to be taken by the system when a signal occurs. A signalmay also be blocked, in which case its delivery is postponed until it is unblocked.The action to be taken on delivery is determined at the time of delivery. Normally,signal handlers execute on the current stack of the process. This may be changed,on a per-handler basis, so that signals are taken on a special signal stack.

Signal routines normally execute with the signal that caused their invocationblocked, but other signals may yet occur. A global signal mask defines the setof signals currently blocked from delivery to a process. The signal mask for a pro-cess is initialized from that of its parent (normally empty). It may be changed witha sigprocmask(2) call, or when a signal is delivered to the process.

208 Systems/C C Library

Page 227: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

When a signal condition arises for a process, the signal is added to a set of signalspending for the process. If the signal is not currently blocked by the process then itis delivered to the process. Signals may be delivered any time a process enters theoperating system (e.g., during a system call, page fault or trap, or clock interrupt). Ifmultiple signals are ready to be delivered at the same time, any signals that could becaused by traps are delivered first. Additional signals may be processed at the sametime, with each appearing to interrupt the handlers for the previous signals beforetheir first instructions. The set of pending signals is returned by the sigpending(2)system call. When a caught signal is delivered, the current state of the process issaved, a new signal mask is calculated (as described below), and the signal handleris invoked. The call to the handler is arranged so that if the sig- nal handling routinereturns normally the process will resume execution in the context from before thesignal’s delivery. If the process wishes to resume in a different context, then it mustarrange to restore the previous context itself.

When a signal is delivered to a process a new signal mask is installed for the durationof the process’ signal handler (or until a sigprocmask(2) system call is made). Thismask is formed by taking the union of the current signal mask set, the signal to bedelivered, and the signal mask associated with the handler to be invoked.

The sigaction() system call assigns an action for a signal specified by sig. If act isnon-zero, it specifies an action (SIG DFL, SIG IGN, or a handler routine) and maskto be used when delivering the specified signal. If oact is non-zero, the previoushandling information for the signal is returned to the user.

Once a signal handler is installed, it normally remains installed until another sigac-tion() system call is made, or an execve(2) is performed. A signal-specific defaultaction may be reset by setting sa handler to SIG DFL. The defaults are process ter-mination, possibly with core dump; no action; stopping the process; or continuingthe process. See the signal list below for each signal’s default action. If sa handleris SIG DFL, the default action for the signal is to discard the signal, and if a signal ispending, the pending signal is discarded even if the signal is masked. If sa handler isset to SIG IGN current and pending instances of the signal are ignored and discarded.

Options may be specified by setting sa flags. The meaning of the various bits is asfollows:

SA NOCLDSTOP If this bit is set when installing a catching function for the SIGCHLDsignal, the SIGCHLD signal will be generated only when a child process exits,not when a child process stops.

SA NOCLDWAIT If this bit is set when calling sigaction() for the SIGCHLD signal, thesystem will not create zombie processes when children of the calling processexit. If the calling process subsequently issues a wait(2) (or equivalent), itblocks until all of the calling process’s child processes terminate, and thenreturns a value of -1 with errno set to ECHILD. The same effect of avoidingzombie cre- ation can also be achieved by setting sa handler for SIGCHLD toSIG IGN.

Systems/C C Library 209

Page 228: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

SA ONSTACK If this bit is set, the system will deliver the signal to the process on asignal stack, specified with sigaltstack(2).

SA NODEFER If this bit is set, further occurrences of the delivered signal are notmasked during the execution of the handler.

SA RESETHAND If this bit is set, the handler is reset back to SIG DFL at the momentthe signal is delivered.

SA RESTART See paragraph below.

SA SIGINFO If this bit is set, the handler function is assumed to be pointed to bythe sa sigaction member of struct sigaction and should match the prototypeshown above or as below in EXAMPLES. This bit should not be set whenassigning SIG DFL or SIG IGN.

If a signal is caught during some system calls, the call may be forced to terminatewith the error EINTR, the call may return with a data transfer shorter than requested,or the call may be restarted. Restart of pending calls is requested by setting theSA RESTART bit in sa flags.

After a fork(2) or vfork(2) all signals, the signal mask, the signal stack, and therestart/interrupt flags are inherited by the child.

The execve(2) system call reinstates the default action for all signals which werecaught and resets all signals to be caught on the user stack. Ignored signals remainignored; the signal mask remains the same; signals that restart pending system callscontinue to do so.

The following is a list of all signals with names as in the include file <signal.h>:

NAME Default Action DescriptionSIGHUP terminate process terminal line hangupSIGINT terminate process interrupt programSIGQUIT create core image quit programSIGILL create core image illegal instructionSIGTRAP create core image trace trapSIGABRT create core image abort(3) call (formerly SIGIOT)SIGEMT create core image emulate instruction executedSIGFPE create core image floating-point exceptionSIGKILL terminate process kill programSIGBUS create core image bus errorSIGSEGV create core image segmentation violationSIGSYS create core image non-existent system call invokedSIGPIPE terminate process write on a pipe with no readerSIGALRM terminate process real-time timer expiredSIGTERM terminate process software termination signalSIGURG discard signal urgent condition present on

210 Systems/C C Library

Page 229: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

socketSIGSTOP stop process stop (cannot be caught or

ignored)SIGTSTP stop process stop signal generated from

keyboardSIGCONT discard signal continue after stopSIGCHLD discard signal child status has changedSIGTTIN stop process background read attempted from

control terminalSIGTTOU stop process background write attempted to

control terminalSIGIO discard signal I/O is possible on a descriptor

(see fcntl(2))SIGXCPU terminate process cpu time limit exceeded (see

setrlimit(2))SIGXFSZ terminate process file size limit exceeded (see

setrlimit(2))SIGVTALRM terminate process virtual time alarm (see

setitimer(2))SIGPROF terminate process profiling timer alarm (see

setitimer(2))SIGWINCH discard signal Window size changeSIGINFO discard signal status request from keyboardSIGUSR1 terminate process User defined signal 1SIGUSR2 terminate process User defined signal 2SIGDANGER terminate processSIGTHSTOP terminate processSIGTHCONT terminate processSIGTRACE terminate processSIGDCE terminate processSIGDUMP terminate processSIGABND terminate process ABEND was encounteredSIGPOLL terminate processSIGIOERR terminate process

NOTE

The sa mask field specified in act is not allowed to block SIGKILL, SIGSTOP orSIGABND. Any attempt to do so will be silently ignored.

It is good practice to make a copy of the global variable errno and restore it beforereturning from the signal handler. This protects against the side effect of errnobeing set by functions called from inside the signal handler.

Systems/C C Library 211

Page 230: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

SIGABND Notes

The signal SIGABND can be used to establish a signal handler function to invokewhen an ABEND is encountered. The Dignus runtime defines the two functionsabendcode and rsncode that can be used to retrieve the ABEND and REA-

SON codes from the ABEND information. These values are only valid within thesignal handler.

Returning from a SIGABND handler restores execution at the point of the ABENDand will result in an infinite loop if the handler remains in effect. That is, thehandler returns, the processor state is restored to the instruction that issued theABEND, the ABEND occurs and the signal handler is re-entered. If the state of theSIGABND handler is SIG DFL then the ABEND will be percolated to be processed inthe normal manner.

The SA RESETHAND flag can be used to set the SIGABND to SIG DFL on entry tothe signal handler; so that the handler may be executed once and then when theprocessor state is restored, normal ABEND handling will occur.

The Systems/C library issues an ABEND 978 when stack space has been exhausted.In order to be invoked for an ABEND 978, the signal handler must be defined toexecute on the alternate signal stack; or the ABEND 978 will simply be re-issuedto percolate via normal ABEND processing.

non-POSIX signal handling

For POSIX environment programs, the system defaults to using the POSIX sig-nal handling interfaces in z/OS. In non-POSIX environments (BATCH/TSO), thesystem defaults to non-POSIX signal handling.

In non-POSIX signal handling, the TRAP(ON) option must be available to enablerecognition of SIGILL, SIGSEGV, SIGFPE and SIGABND. When TRAP is ON, theruntime environment establishes an ESTAE exit to process these events and presentthe signals to the program. When TRAP is OFF, no ESTAE is established andnormal system ABEND processing will occur without a signal being generated.

Also in a non-POSIX environment, the raise(3) function may be used to initiatea signal within a program, but since POSIX signal handling is not enabled, theprogram will not be able to receive a signal from an external process.

RETURN VALUES

The sigaction() function returns the value 0 if successful; otherwise the value -1 isreturned and the global variable errno is set to indicate the error.

212 Systems/C C Library

Page 231: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

EXAMPLES

There are two possible prototypes the handler may match:

ANSI C:

void handler(int);

POSIX SA SIGINFO:

void handler(int, siginfo_t *info, ucontext_t *uap);

The handler function should match the SA SIGINFO prototype if the SA SIGINFO bitis set in sa flags. It then should be pointed to by the sa sigaction member of structsigaction. Note that you should not assign SIG DFL or SIG IGN this way.

If the SA SIGINFO flag is not set, the handler function should match the ANSI Cprototype and be pointed to by the sa handler member of struct sigaction.

The sig argument is the signal number, one of the SIG... values from <signal.h>.

The uap argument to a POSIX SA SIGINFO handler points to an instance ofucontext t.

ERRORS

The sigaction() system call will fail and no new signal handler will be installed ifone of the following occurs:

[EFAULT] Either act or oact points to memory that is not a valid part of theprocess address space.

[EINVAL] The sig argument is not a valid signal number.

[EINVAL] An attempt is made to ignore or supply a handler for SIGKILL orSIGSTOP.

[EINVAL] An attempt is made to ignore SIGABND.

SEE ALSO

kill(2), ptrace(2), sigaltstack(2), sigblock(2), sigpause(2), sigpending(2), sigproc-mask(2), sigsetmask(2), sigsuspend(2), wait(2), fpsetmask(3), setjmp(3), siginter-rupt(3), sigsetops(3), ucontext(3)

Systems/C C Library 213

Page 232: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

STANDARDS

The sigaction() system call is expected to conform to ISO/IEC 9945-1:1990(“POSIX.1”).

214 Systems/C C Library

Page 233: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

SIGPENDING(2)

NAME

sigpending – get pending signals

SYNOPSIS

#include <signal.h>

intsigpending(sigset_t *set);

DESCRIPTION

The sigpending() system call returns a mask of the signals pending for delivery tothe calling process in the location indicated by set. Signals may be pending becausethey are currently masked, or transiently before delivery (although the latter caseis not normally detectable).

RETURN VALUES

The sigpending()— function returns the value 0 if successful; otherwise the value-1 is returned and the global variable errno is set to indicate the error.

ERRORS

The sigpending() system call will fail if:

[EFAULT] The set argument specified an invalid address.

[ENOSYS] The caller is not running in a POSIX environment.

SEE ALSO

sigaction(2), sigprocmask(2), sigsuspend(2), sigsetops(2)

STANDARDS

The sigpending() system call is expected to conform to ISO/IEC 9945-1:1990(“POSIX.1”).

Systems/C C Library 215

Page 234: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

SIGPROCMASK(2)

NAME

sigprocmask – manipulate current signal mask

SYNOPSIS

#include <signal.h>

intsigprocmask(int how, const sigset_t * restrict set,

sigset_t * restrict oset);

DESCRIPTION

The sigprocmask() system call examines and/or changes the current signal mask(those signals that are blocked from delivery). Signals are blocked if they are mem-bers of the current signal mask set.

If set is not null, the action of sigprocmask() depends on the value of the howargument. The signal mask is changed as a function of the specified set and thecurrent mask. The function is specified by how using one of the following valuesfrom ¡signal.h¿:

SIG BLOCK The new mask is the union of the current mask and the specified set.

SIG UNBLOCK The new mask is the intersection of the current mask and the comple-ment of the specified set.

SIG SETMASK The current mask is replaced by the specified set.

If oset is not null, it is set to the previous value of the signal mask. When set isnull, the value of how is insignificant and the mask remains unset providing a wayto examine the signal mask without modification.

The system quietly disallows SIGKILL or SIGSTOP to be blocked.

RETURN VALUES

The sigprocmask() function returns the value 0 if successful; otherwise the value-1 is returned and the global variable errno is set to indicate the error.

216 Systems/C C Library

Page 235: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

ERRORS

The sigprocmask() system call will fail and the signal mask will be unchanged ifone of the following occurs:

[EINVAL] The how argument has a value other than those listed here.

SEE ALSO

kill(2), sigaction(2), sigpending(2), sigsuspend(2), fpsetmask(3), sigsetops(3)

STANDARDS

The sigprocmask() system call is expected to conform to ISO/IEC 9945-1:1990(“POSIX.1”).

Systems/C C Library 217

Page 236: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

SIGSUSPEND(2)

NAME

sigsuspend – atomically release blocked signals and wait for interrupt

SYNOPSIS

#include <signal.h>

intsigsuspend(const sigset_t *sigmask);

DESCRIPTION

The sigsuspend() system call temporarily changes the blocked signal mask to theset to which sigmask points, and then waits for a signal to arrive; on return theprevious set of masked signals is restored. The signal mask set is usually empty toindicate that all signals are to be unblocked for the duration of the call.

In normal usage, a signal is blocked using sigprocmask(2) to begin a critical sec-tion, variables modified on the occurrence of the signal are examined to determinethat there is no work to be done, and the process pauses awaiting work by usingsigsuspend() with the previous mask returned by sigprocmask(2).

RETURN VALUES

The sigsuspend function requires POSIX signal handling, if POSIX signal handlingis not enabled, sigsuspend immediately returns -1 with errno set to ENOSYS.

Otherwise, the sigsuspend() system call will terminate by being interrupted, re-turning -1 with errno set to EINTR.

SEE ALSO

sigaction(2), sigpending(2), sigprocmask(2), sigsetops(3)

STANDARDS

The sigsuspend() system call is expected to conform to ISO/IEC 9945-1:1990(“POSIX.1”).

FreeBSD 6.2 May 16, 1995 FreeBSD 6.2

218 Systems/C C Library

Page 237: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

SIGWAIT(2)

NAME

sigwait – select a set of signals

SYNOPSIS

#include <signal.h>

intsigwait(const sigset_t * restrict set, int * restrict sig);

DESCRIPTION

The sigwait() system call selects a set of signals, specified by set. If none of theselected signals are pending, sigwait() waits until one or more of the selected signalshas been generated. Then sigwait() atomically clears one of the selected signalsfrom the set of pending signals for the process and sets the location pointed to bysig to the signal number that was cleared.

The signals specified by set should be blocked at the time of the call to sigwait().

IMPLEMENATION NOTES

The sigwait() function depends on POSIX signals, if they are not enabled sigwait()immediately returns the value ENOSYS.

RETURN VALUES

If successful, sigwait() returns 0 and sets the location pointed to by sig to thecleared signal number. Otherwise, an error number is returned.

ERRORS

The sigwait() system call will fail if:

[EINVAL] The set argument specifies one or more invalid signal numbers.

[ENOSYS] sigwait() is invoked with POSIX signals disabled.

Systems/C C Library 219

Page 238: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

SEE ALSO

sigaction(2), sigpending(2), sigsuspend(2), pause(3), pthread sigmask(3)

STANDARDS

The sigwait() function conforms to ISO/IEC 9945-1:1996 (“POSIX.1”).

220 Systems/C C Library

Page 239: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

STAT(2)

NAME

stat, lstat, fstat - get //HFS: file status

SYNOPSIS

#include <sys/types.h>#include <sys/stat.h>

intstat(const char *path, struct stat *sb);

intlstat(const char *path, struct stat *sb);

intfstat(int fd, struct stat *sb);

DESCRIPTION

The stat() function obtains information about the file pointed to by path. Read,write or execute permission of the named file is not required, but all directorieslisted in the path name leading to the file must be searchable.

lstat() is similar to stat() except in the case where the named file is a symboliclink, in which case lstat() returns information about the link, while stat() returnsinformation about the file the link references.

The fstat() function obtains the same information about an open file known by thefile descriptor fd.

stat() and lstat() may only be applied to //HFS:-style files. fstat() can only beused in combination with a file descriptor associated with an //HFS:-style file.

The sb argument is a pointer to a stat() structure as defined by <sys/stat.h>(shown below) and into which information is placed concerning the file.

struct stat {dev_t st_dev; /* inode’s device */ino_t st_ino; /* inode’s number */mode_t st_mode; /* inode protection mode */nlink_t st_nlink; /* number of hard links */

Systems/C C Library 221

Page 240: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

uid_t st_uid; /* user ID of the file’s owner */gid_t st_gid; /* group ID of the file’s group */dev_t st_rdev; /* device type */

#ifndef _POSIX_SOURCEstruct timespec st_atimespec; /* time of last access */struct timespec st_mtimespec; /* time of last data modification */struct timespec st_ctimespec; /* time of last file status change */

#elsetime_t st_atime; /* time of last access */long st_atimensec; /* nsec of last access */time_t st_mtime; /* time of last data modification */long st_mtimensec; /* nsec of last data modification */time_t st_ctime; /* time of last file status change */long st_ctimensec; /* nsec of last file status change */

#endifoff_t st_size; /* file size, in bytes */int64_t st_blocks; /* blocks allocated for file */u_int32_t st_blksize; /* optimal blocksize for I/O */u_int32_t st_flags; /* user defined flags for file */u_int32_t st_gen; /* file generation number */

};

The time-related fields of struct stat are as follows:

st atime Time when file data last accessed. Changed by the mknod(2),utime(2) and read(2) system calls.

st mtime Time when file data last modified. Changed by the mknod(2),utime(2) and write(2) system calls.

st ctime Time when file status was last changed. Changed by the chmod(2),chown(2), link(2), mknod(2), rename(2), unlink(2), utime(2) andwrite(2) system calls.

If POSIX SOURCE is not defined, the time-related fields are defined as:

#ifndef _POSIX_SOURCE#define st_atime st_atimespec.tv_sec#define st_mtime st_mtimespec.tv_sec#define st_ctime st_ctimespec.tv_sec#endif

The size-related fields of struct stat are as follows:

st blksize The optimal I/O block size for the file.

222 Systems/C C Library

Page 241: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

st blocks The actual number of blocks allocated for the file in 512-byte units.This number may be zero.

The status information word st mode has the following bits:

#define S_IFMT 0170000 /* type of file */#define S_IFIFO 0010000 /* named pipe (fifo) */#define S_IFCHR 0020000 /* character special */#define S_IFDIR 0040000 /* directory */#define S_IFBLK 0060000 /* block special */#define S_IFREG 0100000 /* regular */#define S_IFLNK 0120000 /* symbolic link */#define S_IFSOCK 0140000 /* socket */#define S_IFWHT 0160000 /* whiteout */#define S_ISUID 0004000 /* set user id on execution */#define S_ISGID 0002000 /* set group id on execution */#define S_ISVTX 0001000 /* save swapped text even after use */#define S_IRUSR 0000400 /* read permission, owner */#define S_IWUSR 0000200 /* write permission, owner */#define S_IXUSR 0000100 /* execute/search permission, owner */

For a list of access modes, see <sys/stat.h>, access(2) and chmod(2).

RETURN VALUES

Upon successful completion, the value 0 is returned; otherwise the value -1 is re-turned and the global variable errno is set to indicate the error.

ERRORS

stat() and lstat() will fail if:

[ENOTDIR] A component of the path prefix is not a directory.

[ENAMETOOLONG] A component of a pathname exceeded 255 characters, or an entirepath name exceeded 1023 characters.

[ENOENT] The named file does not exist.

[EACCES] Search permission is denied for a component of the path prefix.

[ELOOP] Too many symbolic links were encountered in translating the path-name.

[EFAULT] sb or name points to an invalid address.

Systems/C C Library 223

Page 242: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

[EIO] An I/O error occurred while reading from or writing to the filesystem.

fstat() will fail if:

[EBADF] fd is not a valid open file descriptor.

[EFAULT] sb points to an invalid address.

[EIO] An I/O error occurred while reading from or writing to the filesystem.

SEE ALSO

access(2), chmod(2), chown(2), utime(2), symlink(2)

STANDARDS

The stat() and fstat() function calls are expected to conform to ISO/IEC 9945-1:1990 (“POSIX.1”) for //HFS:-style files.

224 Systems/C C Library

Page 243: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

STEPNAME(2)

NAME

stepname - return the current step name of the running program

SYNOPSIS

#include <machine/tiot.h>

char *__stepname(void);

DESCRIPTION

The stepname() function returns the current JCL step name of the executingprogram on MVS, OS/390 and z/OS. The value returned is a pointer to a NUL-terminated string. Trailing blanks are removed.

stepname() returns a pointer to a static area, care should be taken to copy thisvalue before invoking stepname() again.

SEE ALSO

jobname(2), procname(2), userid(2)

Systems/C C Library 225

Page 244: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

SYMLINK(2)

NAME

symlink – make symbolic link to a file

SYNOPSIS

#include <unistd.h>

intsymlink(const char *name1, const char *name2);

DESCRIPTION

A symbolic link name2 is created to name1 (name2 is the name of the file created,name1 is the string used in creating the symbolic link). Either name may be an//HFS:-style arbitrary path name; the files need not be on the same file system.

RETURN VALUES

The symlink() function returns the value 0 if successful; otherwise the value -1 isreturned and the global variable errno is set to indicate the error.

ERRORS

The symbolic link succeeds unless:

[ENOTDIR] A component of the name2 prefix is not a directory.

[ENAMETOOLONG] A component of either pathname exceeded 255 characters, or theentire length of either path name exceeded 1023 characters.

[ENOENT] The named file does not exist.

[EACCES] A component of the name2 path prefix denies search permission.

[ELOOP] Too many symbolic links were encountered in translating the path-name.

[EEXIST] Name2 already exists.

226 Systems/C C Library

Page 245: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

[EIO] An I/O error occurred while making the directory entry for name2,or allocating the inode for name2, or writing out the link contentsof name2.

[EROFS] The file name2 would reside on a read-only file system.

[ENOSPC] The directory in which the entry for the new symbolic link is beingplaced cannot be extended because there is no space left on the filesystem containing the directory.

[ENOSPC] The new symbolic link cannot be created because there is no spaceleft on the file system that will contain the symbolic link.

[EDQUOT] The directory in which the entry for the new symbolic link is beingplaced cannot be extended because the user’s quota of disk blockson the file system containing the directory has been exhausted.

[EDQUOT] The new symbolic link cannot be created because the user’s quotaof disk blocks on the file system that will contain the symbolic linkhas been exhausted.

[EDQUOT] The user’s quota of inodes on the file system on which the symboliclink is being created has been exhausted.

[EIO] An I/O error occurred while making the directory entry or allocatingspace.

[EFAULT] Name1 or name2 points outside the process’s allocated addressspace.

SEE ALSO

link(2), lstat(2), readlink(2), unlink(2)

Systems/C C Library 227

Page 246: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

SVC99(2)

NAME

svc99 - issue SVC99/DYNALLOC macro

SYNOPSIS

#include <machine/svc99.h>

int__svc99(__S99RB *request_block_ptr);

DESCRIPTION

The svc99 function is used to execute the MVS SVC 99 or DYNALLOC interface.This low-level operating system interface provides for dynamically allocating or deal-locating a resource, concatenating or deconcatenating data sets, or retrieving infor-mation about a data set.

The request block ptr points to a S99RB structure that contains the following fields:

S99RBLN Length (initialized to 20). output.

S99VERB SVC99 action code.

S99FLAG1 FLAGS action code.

S99ERROR Error code.

S99INFO Information reason code.

S99TXTPP 31-bit pointer to array of text units.

S99S99X 31-bit pointer to request block extension (RBX).

S99FLAGS2 FLAGS2 field-bit pointer to request block extension.

The request block ptr, any text units and the request block extension must beallocated in 31-bit addressable storage. ( malloc31() can be employed in 64-bitprograms to allocate 31-bit addressable storage.)

The S99TXTPP field points to an array of ”Text Units” that provide further param-eters and information to the DYNALLOC request, e.g. DDNAME, DSNAME, DSORG,etc...

228 Systems/C C Library

Page 247: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

A Text Unit begins with a 2-byte key that is the code for the information. The keyis followed by a 2-byte field indicating the number of elements of the Text Unit (thisis often simply 1.) Each element is a length-prefixed ”blob” of data. The data is a2-byte length field followed by the data bytes. This data is called the Text Unit’s”parameter.”

The S99TXTPP field of the S99RB structure points to an array of pointers to textunits. The end of this array is marked with the high-order bit set (the VL-bit.)Thus, the basic structure is:

S99RBptr -> S99RB

S99RB+----------------+| ... ||----------------| Text Units| S99TXTPP | ----> +-----------------+|----------------| | 0 | TxtUnit Ptr | --> TXTUNIT #0| ... | | --------------- |+----------------+ ...

| 0 | TxtUnit Ptr | --> TXTUNIT #n-1| --------------- || 8 | TxtUnit Ptr | --> TXTUNIT #n+-----------------+

For more information about the DYNALLOC macro, ”Text Units” and other functionssvc99() provides - refer to the ”z/OS MVS Programm Authorized Assembler

Services Guide” from IBM.

EXAMPLES

This program dynamically allocates a file named ”MYFILE.EXAMPLE”, with anallocation unit of TRACK, a primary quantity of 20 and a secondary quantity of 1,with a logical record length of 80, a block size of 80 and a fixed record format.

#include <stdio.h>#include <machine/svc99.h>

intmain(void){

int rc;__S99RB request_block;char *tus[10] = { /* array of text unit pointers */

Systems/C C Library 229

Page 248: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

/* TU # Data Data *//* Code Elems Len */"\0\x02" "\0\x01" "\0\x0E" "MYFILE.EXAMPLE", /* DSN=MYFILE.EXAMPLE */"\0\x05" "\0\x01" "\0\x01" "\x02", /* DISP=(,CATLG) */"\0\x07" "\0\0", /* SPACE=(TRK,.. */"\0\x0A" "\0\x01" "\0\x03" "\0\0\x14", /* primary=20 */"\0\x0B" "\0\x01" "\0\x03" "\0\0\x01", /* secondary=1 */"\0\x15" "\0\x01" "\0\x05" "SYSDA", /* UNIT=SYSDA */"\0\x30" "\0\x01" "\0\x02" "\0\x50", /* BLKSIZE=80 */"\0\x3C" "\0\x01" "\0\x02" "\x40\0", /* DSORG=PS */"\0\x42" "\0\x01" "\0\x02" "\0\x50", /* LRECL=80 */"\0\x49" "\0\x01" "\0\x01" "\x80" /* RECFM=F */

};

/* The last element of the Text Units array must have *//* it’s VL-bit set */tus[9] = (char *) (((unsigned int)tus[9]) | 0x80000000);

/* Set up the SVC99 request block */memset(&request_block, 0, sizeof(request_block));request_block.S99RBLEN = 20; /* always set to 20 */request_block.S99RBVERB = S99VRBAL; /* Allocation */request_block.S99FLAG1 |= S99NOCNV; /* Do not use an existing allocation */request_block.S99TXTPP = tus;

rc = __svc99(&request_block);if(rc != 0) {

printf(" SVC99 failed - Error code = %d Information code = %d\n,request_block.S99ERROR, request_block.S99INFO);

}}

230 Systems/C C Library

Page 249: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

The following example demonstrates how to retrieve information about a file usingthe information retrieval function of the DYNALLOC interface. It provides a functionthat, given a Data Set Name displays the Data Set Organization:

#include <stdio.h>#include <machine/svc99.h>

/*** Interpret the DSORG value returned from SVC 99 Inquire DALRTORG* query**/char *DSORG_name(int dsorg){switch(dsorg) {

case 0x0000: return "**UNKNOW**"; break;case 0x0004: return "TR"; break; /* TCAM 3705 */case 0x0008: return "VSAM"; break; /* VSAM */case 0x0020: return "TQ"; break; /* TCAM message queue */case 0x0040: return "TX"; break; /* TCAM line group */case 0x0080: return "GS"; break; /* Graphics */case 0x0200: return "PO"; break; /* Partitioned Organization */case 0x0300: return "POU"; break; /* Partitioned Organization */

/* Unmovable */case 0x0400: return "MQ"; break; /* Government of message */

/* transfer to or from *//* telecommunications *//* message processing queue */

case 0x0800: return "CQ"; break; /* Direct access message *//* queue */

case 0x1000: return "CX"; break; /* Communication line group */case 0x2000: return "DA"; break; /* Direct Access */case 0x2100: return "DAU"; break; /* Direct Access Unmovable */case 0x4000: return "PS"; break; /* Physical Sequential */case 0x4100: return "PSU"; break; /* Physical Sequential */

/* Unmovable */case 0x8000: return "IS"; break; /* Indexed Sequential? */case 0x8100: return "ISU"; break; /* Indexed Sequential Unmovable?*/default: return "???"; break;

}}

/** get_DSN_org()* Given a DS name - get the data set organization

Systems/C C Library 231

Page 250: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

**/get_DSN_org(char *dsn){

int dsorg, rc;

/* TXT UNITs */unsigned char TUdsname[100] = {

0, DINDSNAM, /* KEY - DSNAME */0, 1, /* # of entries (1) */0, 0, /* length of entry (set below) */

/* remaining space used for the DSNAME (set below) */} ;

unsigned char TUdsorg[] = {0, DINRTORG, /* KEY - request DSORG */0, 1, /* # of entries (1) */0, 2, /* parm length of 2 */0, 0 /* the parm bytes */

} ;

/* TXT units array */unsigned char **TextUnits[] = { TUdsname,

(char **)(((int)TUdsorg) | 0x80000000) /* VL-bit */};

__S99RBX request_block_extension = {"S99RBX",0x01,0x00, /* No messages */

} ;

__S99RB request_block = {20, /* length - always 20 */S99VRBIN, /* S99VERB - Inquire function */0, /* S99FLAG1 */0, /* S99ERROR */0, /* S99INFO */&TextUnits, /* S99TXTPP */&request_block_extension, /* S99S99X */0 /* S99FLAG2 */

} ;

/* Set the DS NAME - up to 94 characters, blank padded *//* IBM allows 44 characters here, but we have extra *//* space to allow the user to use quotes, etc.. */{int i, len;

232 Systems/C C Library

Page 251: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

char *cp;i=0;len = 0;cp = dsn;while(*cp) {

if(i<94) {TUdsname[i+6] = *cp;i++;len++;

}cp++;

}/* blank pad remaining bytes */for(;i<94;i++) TUdsname[i+6] = ’ ’;

/* Set the length of the TU data */TUdsname[4] = (len >> 8);TUdsname[5] = len;

}

rc = __svc99(&request_block);if(rc == 0 && request_block_extension.S99EERR == 0 &&

request_block_extension.S99EINFO == 0) {/* Get the DSORG flag from the DINRTORG TextUnit */

/* DYNALLOC doesn’t fail the request if it can’t *//* determine the DSORG, so you should check the Request Block *//* Extension. */

dsorg = (TUdsorg[6] << 8) | TUdsorg[7];printf("get_DSN_org(\"%s\") - returned DSORG is 0x%04x (%s)\n",

dsn, dsorg, DSORG_name(dsorg));} else {

printf("get_DSN_org(\"%s\") - SVC99 failed - rc is %d\n", dsn, rc);printf(" S99ERROR is 0x%04x\n", request_block.S99ERROR);if(request_block.S99ERROR == 0x0440) {

/* DSN or Pathname not found */printf(" DSN not found\n");

}printf(" S99INFO is 0x%04x\n", request_block.S99INFO);printf(" S99EERR is 0x%04x\n", request_block_extension.S99EERR);printf(" S99EINFO is 0x%04x\n", request_block_extension.S99EINFO);

}}

Systems/C C Library 233

Page 252: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

RETURN VALUES

The svc99() function returns the value 0 if successful; -1 on error, otherwise itreturns the return code from the SVC 99 invocation.

In a 64-bit environment, svc99() verifies that the given request block address isin 31-bit addressable; if not it returns -1.

ISSUES

The svc99 function is only available on z/OS.

SEE ALSO

”z/OS MVS Programm Authorized Assembler Services Guide”, malloc31(3),dynall(2).

234 Systems/C C Library

Page 253: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

SYNC(2)

NAME

sync - schedule //HFS: filesystem updates

SYNOPSIS

#include <unistd.h>

voidsync(void);

DESCRIPTION

The sync() function forces a write of dirty (modified) file system buffers in memorycache out to disk. The operating system keeps this information in memory to reducethe number of disk I/O transfers required by the system.

The function fsync(2) may be used to synchronize individual file descriptors for//HFS:-style files.

sync() schedules the write of file system updates, and may return before all writingis complete.

RETURN VALUES

The sync() function returns the value 0 if successful; otherwise the value -1 isreturned.

SEE ALSO

fsync(2)

Systems/C C Library 235

Page 254: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

TRUNCATE(2)

NAME

truncate, ftruncate - truncate or extend a file to a specified length

SYNOPSIS

#include <unistd.h>

inttruncate(const char *path, off_t length);

intftruncate(int fd, off_t length);

DESCRIPTION

truncate() causes the file named by path or referenced by fd to be truncated orextended to length bytes in size. If the file was larger than this size, the extra datais lost. If the file was smaller than this size, it will be extended as if by writing byteswith the value zero. With ftruncate(), the file must be open for writing.

For non-//HFS:-style names, truncate() is implemented by opening the file andinvoking ftruncate().

RETURN VALUES

Upon successful completion, the value 0 is returned; otherwise the value -1 is re-turned and the global variable errno is set to indicate the error.

ERRORS

truncate() succeeds unless:

[ENOTDIR] A component of the path prefix is not a directory.

[ENAMETOOLONG] A component of a pathname exceeded 255 characters, or an entirepath name exceeded 1023 characters.

[ENOENT] The named file does not exist.

236 Systems/C C Library

Page 255: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

[EACCES] Search permission is denied for a component of the path prefix.

[EACCES] The named file is not writable by the user.

[ELOOP] Too many symbolic links were encountered in translating the path-name.

[EISDIR] The named file is a directory.

[EROFS] The named file resides on a read-only file system.

[EIO] An I/O error occurred updating the file.

[EFAULT] Path points outside the process’s allocated address space.

ftruncate() succeeds unless:

[EBADF] The fd is not a valid descriptor.

[EINVAL] The fd references a socket, not a file.

[EINVAL] The fd is not open for writing.

[EIO] An I/O error occurred updating the file.

SEE ALSO

open(2)

ISSUES

Use of truncate() to extend a file is not portable.

Systems/C C Library 237

Page 256: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

UMASK(2)

NAME

umask – set file creation mode mask for //HFS:-style files

SYNOPSIS

#include <sys/stat.h>

mode_tumask(mode_t numask);

DESCRIPTION

The umask() function sets the process’s file mode creation mask to numask andreturns the previous value of the mask. The 9 low-order access permission bits ofnumask are used by system calls, including open(2), mkdir(2), and mkfifo(2), to turnoff corresponding bits requested in file mode for //HFS:-style files. (See chmod(2)).This clearing allows each user to restrict the default access to his files.

Child POSIX processes inherit the mask of the calling process.

RETURN VALUES

If OpenEdition services are available, the previous value of the file mode mask isreturned. Otherwise, a value of zero is returned.

ERRORS

If OpenEdition services are not available, umask() returns a value of zero and setserrno to ENOSYS.

ISSUES

Unfortunately, there is no way to distinguish a return value of 0 from an intendedfile mask value of 0. In typical POSIX implementations, umask() cannot fail.

238 Systems/C C Library

Page 257: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

UNLINK(2)

NAME

unlink – remove HFS: directory entries or //DSN: files

SYNOPSIS

#include <unistd.h>

intunlink(const char *path);

DESCRIPTION

For //HFS:-style files, the unlink() function removes the link named by path fromits directory and decrements the link count of the file which was referenced by thelink. If that decrement reduces the link count of the file to zero, and no processhas the file open, then all resources associated with the file are reclaimed. If one ormore process have the file open when the last link is removed, the link is removed,but the removal of the file is delayed until all references to it have been closed. pathmay not be a directory.

For //DSN:-style files, the unlink() function removes the entry by invoking the OSDYNALLOC service to allocate a the entry with a disposition of DELETE. unlink()then uses DYNALLOC to un-allocate the file, causing it to be deleted.

unlink() is only supported for //HFS: and //DSN:-style file names.

RETURN VALUES

The unlink() function returns the value 0 if successful; otherwise the value -1 isreturned and the global variable errno is set to indicate the error.

ERRORS

The unlink() succeeds unless:

[ENOTDIR] A component of the path prefix is not a directory.

[ENAMETOOLONG] A component of a pathname exceeded 255 characters, or an entirepath name exceeded 1023 characters.

Systems/C C Library 239

Page 258: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

[ENOENT] The named file does not exist.

[EACCES] Search permission is denied for a component of the path prefix.

[EACCES] Write permission is denied on the directory containing the link tobe removed.

[ELOOP] Too many symbolic links were encountered in translating the path-name.

[EPERM] The named file is a directory.

[EPERM] The directory containing the file is marked sticky, and neither thecontaining directory nor the file to be removed are owned by theeffective user ID.

[EBUSY] The entry to be unlinked is the mount point for a mounted filesystem.

[EIO] An I/O error occurred while deleting the directory entry or deallo-cating the inode.

[EIO] The DYNALLOC service failed for //DSN:-style files.

[EROFS] The named file resides on a read-only file system.

[EFAULT] Path points outside the process’s allocated address space.

SEE ALSO

close(2), link(2), rmdir(2)

ISSUES

The unlink() function only supports un-linking of //DSN: or //HFS:-style files.

240 Systems/C C Library

Page 259: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

UNLOCKPT(2)

NAME

unlockpt - pseudo-terminal access function

SYNOPSIS

#include <stdlib.h>

intunlockpt(int filedes);

DESCRIPTION

The unlockpt() unlocks a slave pseudoterminal from its master counterpart, allow-ing the slave to opened. filedes is a file descriptor that is the result of an open(2) ofthe master pseudoterminal.

Secure connections can be provided by using grantpt(2) and unlockpt(), or bysimply issuing the first open against the slave pseudoterminal from the userid orprocess that opened the master terminal.

RETURN VALUES

If successful, unlockpt() returns the value 0, otherwise a -1 is returned and theglobal variable errno is set to indicate the error.

ERRORS

unlockpt() will fail if:

[EACCESS] Either a grantpt(2) has not yet been issued, or unlockpt() hasalready been issued.

[EBADF] filedes is invalid, or was not opened for writing

[EINVAL] filedes is not a master pseudoterminal

SEE ALSO

grantpt(2), ptsname(3)

Systems/C C Library 241

Page 260: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

USERID(2)

NAME

userid - return the current user name

SYNOPSIS

#include <machine/tiot.h>

char *__userid(void);

DESCRIPTION

The userid() function returns the current user name of the executing programon OS/390 and z/OS. The value returned is a pointer to a NUL-terminated string.Trailing blanks are removed from the name returned by the system.

userid() returns a pointer to a static area, care should be taken to copy this valuebefore invoking userid() again.

RETURN VALUES

If successful, userid() returns a pointer to a static area that contains the currentused id. If the user id is unavailable, userid() returns NULL.

SEE ALSO

jobname(2), stepname(2), procname(2)

242 Systems/C C Library

Page 261: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

UTIMES(2)

NAME

utimes, futimes - set //HFS: file access and modification times

SYNOPSIS

#include <sys/time.h>

intutimes(const char *path, const struct timeval *times);

intfutimes(int fd, const struct timeval *times);

DESCRIPTION

The access and modification times of the //HFS: file named by path or referencedby fd are changed as specified by the argument times.

If times is NULL, the access and modification times are set to the current time. Thecaller must be the owner of the file, have permission to write the file, or be thesuper-user.

If times is non-NULL, it is assumed to point to an array of two timeval structures.The access time is set to the value of the first element, and the modification time isset to the value of the second element. The caller must be the owner of the file orbe the super-user.

RETURN VALUES

Upon successful completion, the value 0 is returned; otherwise the value -1 is re-turned and the global variable errno is set to indicate the error.

ERRORS

utimes() will fail if:

[EACCES] Search permission is denied for a component of the path prefix; orthe times argument is NULL and the effective user ID of the processdoes not match the owner of the file, and is not the super-user, andwrite access is denied.

Systems/C C Library 243

Page 262: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

[EFAULT] path or times points outside the process’s allocated address space.

[EIO] An I/O error occurred while reading or writing the affected inode.

[ELOOP] Too many symbolic links were encountered in translating the path-name.

[ENAMETOOLONG] A component of a pathname exceeded NAME MAX characters, or anentire path name exceeded PATH MAX characters.

[ENOENT] The named file does not exist.

[ENOTDIR] A component of the path prefix is not a directory.

[EPERM] The times argument is not NULL and the calling process’s effectiveuser ID does not match the owner of the file and is not the super-user.

[EROFS] The file system containing the file is mounted read-only.

futimes() will fail if:

[EBADF] fd does not refer to a valid descriptor.

Either function will fail if:

[EACCES] The times argument is NULL and the effective user ID of the processdoes not match the owner of the file, and is not the super-user, andwrite access is denied.

[EFAULT] times points outside the process’s allocated address space.

[EIO] An I/O error occurred while reading or writing the affected fileinformation.

[EPERM] The times argument is not NULL and the calling process’s effectiveuser ID does not match the owner of the file and is not the super-user.

[EROFS] The file system containing the file is mounted read-only.

SEE ALSO

stat(2), utime(3)

244 Systems/C C Library

Page 263: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

VFORK(2)

NAME

vfork – spawn new process in a virtual memory efficient way

SYNOPSIS

#include <unistd.h>

pid_tvfork(void);

DESCRIPTION

The vfork() system call can be used to create new processes without fully copy-ing the address space of the old process. It is useful when the purpose of fork(2)would have been to create a new system context for an execve(2). The vfork()function differs from fork(2) in that the child may ”borrow” the parent’s memoryand thread of control until a call to execve(2) or an exit (either by a call to exit(2)or abnormally). The parent process may be suspended while the child is using itsresources.

The vfork() system call returns 0 in the child’s context and (later) the pid of thechild in the parent’s context.

The vfork() system call can normally be used just like fork(2). It does not work,however, to return while running in the child’s context from the procedure thatcalled vfork() since the eventual return from vfork() would then return to a nolonger existent stack frame. The only function calls allowed in the child process arean execve(2) to load a new program image or exit(2) to exit the child.

RETURN VALUES

Same as for fork(2).

SEE ALSO

execve(2), manref exit2, manreffork2, manrefwait2, manrefexit3

Systems/C C Library 245

Page 264: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

ISSUES

The vfork() function has been marked as obsolete and may be removed from futurestandards. Portable programs should use the fork(2) function.

246 Systems/C C Library

Page 265: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

WAIT(2)

NAME

wait, waitpid, wait3 - wait for process termination

SYNOPSIS

#include <sys/types.h>#include <sys/wait.h>

pid_twait(int *status);

#include <sys/time.h>#include <sys/resource.h>

pid_twaitpid(pid_t wpid, int *status, int options);

pid_twait3(int *status, int options, struct rusage *rusage);

DESCRIPTION

The wait() function suspends execution of its calling process until status informationis available for a terminated child process, or a signal is received. On return from asuccessful wait() call, the status area contains termination information about theprocess that exited as defined below.

For waitpid() the wpid parameter specifies the set of child processes for which towait. If wpid is -1, the call waits for any child process. If wpid is 0, the call waitsfor any child process in the process group of the caller. If wpid is greater than zero,the call waits for the process with process id wpid. If wpid is less than -1, the callwaits for any process whose process group id equals the absolute value of wpid.

For waitpid() and wait3(), the status parameter is defined below. The optionsparameter contains the bitwise OR of any of the following options. The WNOHANGoption is used to indicate that the call should not block if there are no processesthat wish to report status. If the WUNTRACED option is set, children of the currentprocess that are stopped due to a SIGTTIN, SIGTTOU, SIGTSTP, or SIGSTOPsignal also have their status reported.

For wait3(), if rusage is non-zero, a summary of the resources used by the termi-nated process and all its children is returned.

Systems/C C Library 247

Page 266: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

When the WNOHANG option is specified and no processes wish to report status,wait3() returns a process id of 0.

The wait() call is identical to waitpid() with an options value of zero.

The following macros may be used to test the manner of exit of the process. Oneof the first three macros will evaluate to a non-zero (true) value:

WIFEXITED(status) True if the process terminated normally by a call to exit(2) orexit(3).

WIFSIGNALED(status) True if the process terminated due to receipt of a signal.

WIFSTOPPED(status) True if the process has not terminated, but has stopped andcan be restarted. This macro can be true only if the wait call speci-fied the WUNTRACED option or if the child process is being traced.

Depending on the values of those macros, the following macros produce the remain-ing status information about the child process:

WEXITSTATUS(status) If WIFEXITED(status) is true, evaluates to the low-order 8bits of the argument passed to exit(2) or exit(3) by the child.

WTERMSIG(status) If WIFSIGNALED(status) is true, evaluates to the number of thesignal that caused the termination of the process.

WCOREDUMP(status) If WIFSIGNALED(status) is true, evaluates as true if the termi-nation of the process was accompanied by the creation of a core filecontaining an image of the process when the signal was received.

WSTOPSIG(status) If WIFSTOPPED(status) is true, evaluates to the number of thesignal that caused the process to stop.

NOTES

A status of 0 indicates normal termination.

If a parent process terminates without waiting for all of its child pro- cesses toterminate, the remaining child processes are assigned the par- ent process 1 ID (theinit process ID).

If a signal is caught while any of the wait() calls are pending, the call may beinterrupted or restarted when the signal-catching routine returns, depending on theoptions in effect for the signal.

248 Systems/C C Library

Page 267: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

RETURN VALUES

If wait() returns due to a stopped or terminated child process, the process ID ofthe child is returned to the calling process. Otherwise, a value of -1 is returned anderrno is set to indicate the error.

If wait3(), or waitpid() returns due to a stopped or terminated child process, theprocess ID of the child is returned to the calling process. If there are no children notpreviously awaited, -1 is returned with errno set to ECHILD. Otherwise, if WNOHANGis specified and there are no stopped or exited children, 0 is returned. If an error isdetected or a caught signal aborts the call, a value of -1 is returned and errno isset to indicate the error.

ERRORS

wait() will fail and return immediately if:

[ECHILD] The calling process has no existing unwaited-for child processes.

[EFAULT] The status or rusage arguments point to an illegal address. (Maynot be detected before exit of a child process.)

[EINTR] The call was interrupted by a caught signal, or the signal did nothave the SA RESTART flag set.

STANDARDS

The wait() and waitpid() functions are defined by POSIX; wait3() is not specifiedby POSIX. The WCOREDUMP() macro is an extension to the POSIX interface.

SEE ALSO

exit(2), exit(3)

Systems/C C Library 249

Page 268: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

WRITE(2)

NAME

write - write output

SYNOPSIS

#include <sys/types.h>#include <sys/uio.h>#include <unistd.h>

size_twrite(int d, const void *buf, size_t nbytes)

DESCRIPTION

write() attempts to write nbytes of data to the object referenced by the descriptord from the buffer pointed to by buf.

On objects capable of seeking, the write() starts at a position given by the pointerassociated with d, see lseek(2). Upon return from write(), the pointer is incre-mented by the number of bytes which were written.

Objects that are not capable of seeking always write from the current position. Thevalue of the pointer associated with such an object is undefined.

When using non-blocking I/O on objects such as sockets that are subject to flowcontrol, or when the file is opened with O RECIO flag, write() may write fewer bytesthan requested; the return value must be noted, and the remainder of the operationshould be retried when possible.

IMPLEMENTATION NOTES

When writing to objects which have been opened in O TEXT mode (the default in theSystems/C library), and the associated file is a record-structured file (non //HFS:and non-socket), records are padded with blanks after a new-line is encountered up tothe record length. If the record if completely filled before a new-line is encountered,the record is completed and subsequent text appears on the next record, i.e. text“wraps around”. Any padding bytes added are not reflected in the return value. Ifthe lrecl of the file is 1 , writes are performed as if the file had been opened withO BINARY specified.

250 Systems/C C Library

Page 269: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

If the file descriptor has been opened with O RECIO flag, then the write operationis performed using “record I/O”. In this situation, the operation will write onlyrecord length bytes, any bytes in the buffer past the record length are discarded. Ifthe output file is a variable-length record, then the write will generate the properrecord-length specification based on the nbytes specified. For files with a fixed recordlength, if nbytes specifies a value smaller than the record length, the remainder ofthe record is filled with NUL (zero) bytes. Also note that a write of zero bytes toa variable record length file when using “record I/O” will generate a record with azero record length. Care should be taken to ensure that is the desired result as otherprograms that read the file may be confused by the zero record length record. Afterthe write operation, the file pointer will be advanced to start of the next record.

RETURN VALUES

Upon successful completion the number of bytes which were written is returned.Otherwise a -1 is returned and the global variable errno is set to indicate the error.

ERRORS

write() will fail and the file pointer will remain unchanged if:

[EAGAIN] The file was marked for non-blocking I/O, and no data could bewritten immediately.

[EBADF] d is not a valid descriptor open for writing.

[EDQUOT] The user’s quota of disk blocks on the file system containing the filehas been exhausted.

[EINVAL] The pointer associated with d was negative.

[EIO] An I/O error occurred while reading from or writing to the filesystem.

[ENOSPC] There is no free space remaining on the file system containing thefile.

[ENXIO] The file is not a supported I/O format.

SEE ALSO

fcntl(2), lseek(2), open(2)

Systems/C C Library 251

Page 270: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

STANDARDS

The write() function call is expected to conform to IEEE Std1003.1-1990(“POSIX”), as close as the host file system makes possible.

252 Systems/C C Library

Page 271: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

TCP/IP related functions

The functions described here are related to the TCP/IP implementation in theSystems/C library.

The functions described here are implemented in terms of the IBM TCP/IP im-plementation on OS/390. The descriptions include features which may not yet beavailable on that implementation (e.g. the address family AF UNIX is not supportedin IBM’s implementation.) The description of these features are provided for com-pleteness.

Systems/C C Library 253

Page 272: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

ACCEPT(2)

NAME

accept - accept a connection on a socket

SYNOPSIS

#include <sys/types.h>#include <sys/socket.h>

intaccept(int s, struct sockaddr *addr, socklen_t *addrlen)

DESCRIPTION

The argument s is a socket that has been created with socket(2), bound to anaddress with bind(2), and is listening for connections after a listen(2). The accept()argument extracts the first connection request on the queue of pending connections,creates a new socket with the same properties of s and allocates a new file descriptorfor the socket. If no pending connections are present on the queue, and the socket isnot marked as non-blocking, accept() blocks the caller until a connection is present.If the socket is marked non-blocking and no pending connections are present on thequeue, accept() returns an error as described below. The accepted socket may notbe used to accept more connections. The original socket s remains open.

The argument addr is a result parameter that is filled in with the address of the con-necting entity, as known to the communications layer.The exact format of the addrparameter is determined by the domain in which the communication is occurring.The addrlen is a value-result parameter; it should initially contain the amount ofspace pointed to by addr; on return it will contain the actual length (in bytes) of theaddress returned. This call is used with connection-based socket types, currentlywith SOCK STREAM.

It is possible to select(2) a socket for the purposes of doing an accept() by selectingit for read.

For certain protocols which require an explicit confirmation, such as ISO orDATAKIT, accept() can be thought of as merely dequeueing the next connectionrequest and not implying confirmation. Confirmation can be implied by a normalread or write on the new file descriptor, and rejection can be implied by closing thenew socket.

One can obtain user connection request data without confirming the connection byissuing a recvmsg(2) call with an msg iovlen of 0 and a nonzero msg controllen,

254 Systems/C C Library

Page 273: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

or by issuing a getsockopt(2) request. Similarly,one can provide user connectionrejection information by issuing a sendmsg(2) call with providing only the controlinformation, or by calling setsockopt(2).

RETURN VALUES

The call returns -1 on error. If it succeeds, it returns a non-negative integer that isa descriptor for the accepted socket.

ERRORS

The accept() will fail if:

[EBADF] The descriptor is invalid.

[EINTR] The accept() operation was interrupted.

[EMFILE] The per-process descriptor table is full.

[ENFILE] The system file table is full.

[ENOTSOCK] The descriptor references a file, not a socket.

[EINVAL] listen(2) has not been called on the socket descriptor.

[EFAULT] The addr parameter is not in a writable part of the user addressspace.

[EWOULDBLOCK] The socket is marked non-blocking and no connections are presentto be accepted.

SEE ALSO

bind(2), connect(2), getpeername(2), listen(2), select(2), socket(2)

Systems/C C Library 255

Page 274: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

BIND(2)

NAME

bind - assign a local protocol address to a socket.

SYNOPSIS

#include <sys/types.h>#include <sys/socket.h>

intbind(int s, const struct sockaddr *addr, socklen_t addrlen)

DESCRIPTION

bind() assigns the local protocol address to a socket. When a socket is created withsocket(2) it exists in an address family space but has no protocol address assigned.bind() requests that addr be assigned to the socket.

NOTES

Binding an address in the UNIX domain creates a socket in the file system thatmust be deleted by the caller when it is no longer needed (using unlink(2)). UNIXdomain sockets are currently unsupported in IBM’s TCP/IP implementation, onwhich the Systems/C library is based. The documentation related to UNIX domainsockets is included for completeness.

The rules used in address binding vary between communication domains.

RETURN VALUES

If the bind is successful, a 0 value is returned. A return value of -1 indicates anerror, which is further specified in the global errno.

ERRORS

The bind() call will fail if:

[EBADF] s is not a valid descriptor.

256 Systems/C C Library

Page 275: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

[ENOTSOCK] s is not a socket.

[EADDRNOTAVAIL] The specified address is not available from the local machine.

[EADDRINUSE] The specified address is already in use.

[EACCES] The requested address is protected, and the current user has inad-equate permission to access it.

[EFAULT] The addr parameter is not in a valid part of the user address space.

The following errors are specific to binding addresses in the UNIX domain.

[ENOTDIR] A component of the path prefix is not a directory.

[ENAMETOOLONG] A component of a pathname exceeded 255 characters, or an entirepath name exceeded 1023 characters.

[ENOENT] A prefix component of the path name does not exist.

[ELOOP] Too many symbolic links were encountered in translating thepath-name.

[EIO] An I/O error occurred while making the directory entry or allocatingthe inode.

[EROFS] The name would reside on a read-only file system.

[EISDIR] An empty pathname was specified.

SEE ALSO

connect(2), getsockname(2), listen(2), socket(2)

Systems/C C Library 257

Page 276: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

CONNECT(2)

NAME

connect - initiate a connection on a socket

SYNOPSIS

#include <sys/types.h>#include <sys/socket.h>

intconnect(int s, const struct sockaddr *name, socklen_t namelen)

DESCRIPTION

The parameter s is a socket. If it is of type SOCK DGRAM, this call specifies the peerwith which the socket is to be associated; this address is that to which datagramsare to be sent, and the only address from which datagrams are to be received. If thesocket is of type SOCK STREAM, this call attempts to make a connection to anothersocket.

The other socket is specified by name, which is an address in the communicationsspace of the socket. Each communications space interprets the name parameterin its own way. Generally, stream sockets may successfully connect() only once;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.

RETURN VALUES

If the connection or binding succeeds, 0 is returned. Otherwise a -1 is returned,and a more specific error code is stored in errno.

ERRORS

The connect() call fails if:

[EBADF] s is not a valid descriptor.

[ENOTSOCK] s is a descriptor for a file, not a socket.

258 Systems/C C Library

Page 277: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

[EADDRNOTAVAIL] The specified address is not available on this machine.

[EAFNOSUPPORT] Addresses in the specified address family cannot be used with thissocket.

[EISCONN] The socket is already connected.

[ETIMEDOUT] connection establishment timed out without establishing a connec-tion.

[ECONNREFUSED] The attempt to connect was forcefully rejected.

[ENETUNREACH] The network isn’t reachable from this host.

[EADDRINUSE] The address is already in use.

[EFAULT] The name parameter specifies an area outside the process addressspace.

[EINPROGRESS] The socket is non-blocking and the connection cannot be completedimmediately. It is possible to select(2) for completion by selectingthe socket for writing.

[EALREADY] The socket is non-blocking and a previous connection attempt hasnot yet been completed.

The following errors are specific to connecting names in the UNIX domain. Theseerrors may not apply in future versions of the UNIX IPC domain. Also, they arenot currently support in the IBM TCP/IP implementation.

[ENOTDIR] A component of the path prefix is not a directory.

[ENAMETOOLONG] A component of a pathname exceeded 255 characters, or an entirepath name exceeded 1023 characters.

[ENOENT] The named socket does not exist.

[EACCES] Search permission is denied for a component of the path prefix.

[EACCES] Write access to the named socket is denied.

[ELOOP] Too many symbolic links were encountered in translating the path-name.

SEE ALSO

accept(2), getpeername(2), getsockname(2), select(2), socket(2)

Systems/C C Library 259

Page 278: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

GETCLIENTID(2)

NAME

getclientid - get the identifier for the calling application

SYNOPSIS

#include <sys/socket.h>#include <sys/types.h>

int getclientid(int domain, struct clientid *clientid);

int __getclientid(int domain, struct clientid *clientid);

DESCRIPTION

The getclientid() function call returns the identifier by which the calling appli-cation is known to the TCP/IP address space. The clientid can be used in thegivesocket(2) and takesocket(2) calls. However, this function is supplied for use byexisting programs that depend on the address space name returned.

domain is the address domain requested.

clientid as a pointer to the struct clientid to be filled.

The getclientid() function returns the process identifier (PID) format of theclientid structure. This version provides improved performance and integrity overthe getclientid() function. getclientid() is only available if BPX sockets arebeing used.

See givesocket(2) for more information regarding the clientid structure.

RETURN VALUES

On success, getclientid() returns 0. getclientid() returns -1 on failure and setserrno to indicate the error:

[EFAULT] clientid points outside the caller’s allocated address space.

[ENOSYS] getclientid was invoked when the EZASMI socket interface wasbeing used.

260 Systems/C C Library

Page 279: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

GETHOSTID(2)

NAME

gethostid - get unique identifier of current host

SYNOPSIS

#include <unistd.h>

longgethostid(void)

DESCRIPTION

gethostid() returns the 32-bit identifier for the current host. Historically, this hasbeen the unique DARPA internet address for the local machine.

RETURN VALUES

If the call fails, a value of -1 is returned and an error code may be placed in theglobal location errno. However, -1 is also a valid host id value.

ERRORS

The following errors may be returned by gethostid():

[ENOMEM] There is inadequate memory to initialize the TCP/IP system

[EINVAL] The TCP/IP subsystem name is invalid

[ENOSYS] The TCP/IP system is not available

SEE ALSO

gethostname(2)

Systems/C C Library 261

Page 280: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

ISSUES

32 bits for the unique identifier is too small. On UNIX systems, the return value -1is not reserved; furthermore, -1 may be a correct return value for the host identifier.errno should be set to zero before the call to gethostid() and then examined ifgethostid() return -1.

262 Systems/C C Library

Page 281: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

GETHOSTNAME(2)

NAME

gethostname - get name of current host

SYNOPSIS

#include <unistd.h>

intgethostname(char *name, int namelen)

DESCRIPTION

gethostname() returns the standard host name for the current host.. The pa-rameter namelen specifies the size of the name array. The returned name is null-terminated unless insufficient space is provided.

RETURN VALUES

If the call succeeds a value of 0 is returned. If the call fails, a value of -1 is returnedand an error code is placed in the global location errno.

ERRORS

The following errors may be returned by gethostname():

[EFAULT] The name or namelen parameter gave an invalid address.

SEE ALSO

gethostid(2)

ISSUES

Host names are limited to MAXHOSTNAMELEN (from <sys/param.h>) characters, cur-rently 256.

Systems/C C Library 263

Page 282: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

GETPEERNAME(2)

NAME

getpeername - get name of connected peer

SYNOPSIS

#include <sys/types.h>#include <sys/socket.h>

intgetpeername(int s, struct sockaddr *name, socklen_t *namelen)

DESCRIPTION

getpeername() returns the name of the peer connected to socket s. The namelenparameter should be initialized to indicate the amount of space pointed to by name.On return it contains the actual size of the name returned (in bytes). The name istruncated if the buffer provided is too small.

RETURN VALUES

A 0 is returned if the call succeeds, -1 if it fails.

ERRORS

The call succeeds unless:

[EBADF] The argument s is not a valid descriptor.

[ENOTSOCK] The argument s is a file, not a socket.

[ENOTCONN] The socket is not connected.

[ENOBUFS] Insufficient resources were available in the system to perform theoperation.

[EFAULT] The name parameter points to memory not in a valid part of theprocess address space.

SEE ALSO

accept(2), bind(2), getsockname(2), socket(2)

264 Systems/C C Library

Page 283: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

GETSOCKNAME(2)

NAME

getsockname - get socket name

SYNOPSIS

#include <sys/types.h>#include <sys/socket.h>

intgetsockname(int s, struct sockaddr *name, socklen_t *namelen)

DESCRIPTION

getsockname() returns the current name for the specified socket. The namelenparameter should be initialized to indicate the amount of space pointed to by name.On return it contains the actual size of the name returned (in bytes).

RETURN VALUES

A 0 is returned if the call succeeds, -1 if it fails.

ERRORS

The call succeeds unless:

[EBADF] The argument s is not a valid descriptor.

[ENOTSOCK] The argument s is a file, not a socket.

[ENOBUFS] Insufficient resources were available in the system to perform theoperation.

[EFAULT] The name parameter points to memory not in a valid part of theprocess address space.

SEE ALSO

bind(2), getpeername(2), socket(2)

Systems/C C Library 265

Page 284: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

ISSUES

Names bound to sockets in the UNIX domain are inaccessible; getsockname()returns a zero length name.

266 Systems/C C Library

Page 285: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

GETSOCKOPT(2)

NAME

getsockopt, setsockopt - get and set options on sockets

SYNOPSIS

#include <sys/types.h>#include <sys/socket.h>

intgetsockopt(int s, int level, int optname,void *optval, socklen_t *optlen)

intsetsockopt(int s, int level, int optname,const void *optval, socklen_t optlen)

DESCRIPTION

getsockopt() and setsockopt() manipulate the options associated with a socket.Options may exist at multiple protocol levels; they are always present at the upper-most “socket” level.

When manipulating socket options the level at which the option resides and thename of the option must be specified. To manipulate options at the socket level,level is specified as SOL SOCKET. To manipulate options at any other level the protocolnumber of the appropriate protocol controlling the option is supplied. For example,to indicate that an option is to be interpreted by the TCP protocol, level should beset to the protocol number of TCP; see getprotoent(3)

The parameters optval and optlen are used to access option values for setsockopt().For getsockopt() they identify a buffer in which the value for the requested op-tion(s) are to be returned. For getsockopt(), optlen is a value-result parameter,initially containing the size of the buffer pointed to by optval, and modified on returnto indicate the actual size of the value returned. If no option value is to be suppliedor returned, optval may be NULL.

optname and any specified options are passed uninterpreted to the appropriate pro-tocol module for interpretation. The include file <sys/socket.h> contains defini-tions for socket level options, described below. Options at other protocol levels varyin format and name.

Systems/C C Library 267

Page 286: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

Most socket-level options utilize an int parameter for optval. For setsockopt(),the parameter should be non-zero to enable a boolean option, or zero if the op-tion is to be disabled. SO LINGER uses a struct linger parameter, defined in<sys/socket.h>, which specifies the desired state of the option and the linger inter-val (see below). SO SNDTIMEO and SO RCVTIMEO use a struct timeval parameter,defined in <sys/time.h>.

The following options are recognized at the socket level. Except as noted, each maybe examined with getsockopt() and set with setsockopt().

SO DEBUG enables recording of debugging information

SO REUSEADDR enables local address reuse

SO REUSEPORT enables duplicate address and port bindings

SO KEEPALIVE enables keep connections alive

SO DONTROUTE enables routing bypass for outgoing messages

SO LINGER linger on close if data present

SO BROADCAST enables permission to transmit broadcast messages

SO OOBINLINE enables reception of out-of-band data in band

SO SNDBUF set buffer size for output

SO RCVBUF set buffer size for input

SO SNDLOWAT set minimum count for output

SO RCVLOWAT set minimum count for input

SO SNDTIMEO set timeout value for output

SO RCVTIMEO set timeout value for input

SO TYPE get the type of the socket (get only)

SO ERROR get and clear error on the socket (get only)

SO DEBUG enables debugging in the underlying protocol modules. SO REUSEADDRindicates that the rules used in validating addresses supplied in a bind(2) call shouldallow reuse of local addresses. SO REUSEPORT allows completely duplicate bindingsby multiple processes if they all set SO REUSEPORT before binding the port. Thisoption permits multiple instances of a program to each receive UDP/IP multicastor broadcast datagrams destined for the bound port. SO KEEPALIVE enables theperiodic transmission of messages on a connected socket. Should the connectedparty fail to respond to these messages, the connection is considered broken andprocesses using the socket are notified via a SIGPIPE signal when attempting to senddata. SO DONTROUTE indicates that outgoing messages should bypass the standard

268 Systems/C C Library

Page 287: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

routing facilities. Instead, messages are directed to the appropriate network interfaceaccording to the network portion of the destination address.

SO LINGER controls the action taken when unsent messages are queued on socketand a close(2) is performed. If the socket promises reliable delivery of data andSO LINGER is set, the system will block the process on the close(2) attempt until itis able to transmit the data or until it decides it is unable to deliver the information(a timeout period, termed the linger interval, is specified in seconds in the setsock-opt() call when SO LINGER is requested). If SO LINGER is disabled and a close(2)is issued, the system will process the close in a manner that allows the process tocontinue as quickly as possible.

The option SO BROADCAST requests permission to send broadcast datagrams on thesocket. Broadcast was a privileged operation in earlier versions of some systems.With protocols that support out-of-band data, the SO OOBINLINE option requeststhat out-of-band data be placed in the normal data input queue as received; it willthen be accessible with recv(2) or read(2) calls without the MSG OOB flag. Someprotocols always behave as if this option is set. SO SNDBUF and SO RCVBUF areoptions to adjust the normal buffer sizes allocated for output and input buffers,respectively. The buffer size may be increased for high-volume connections, or maybe decreased to limit the possible backlog of incoming data.

SO SNDLOWAT is an option to set the minimum count for output operations. Mostoutput operations process all of the data supplied by the call, delivering data to theprotocol for transmission and blocking as necessary for flow control. Nonblockingoutput operations will process as much data as permitted subject to flow controlwithout blocking, but will process no data if flow control does not allow the smallerof the low water mark value or the entire request to be processed. A select(2)operation testing the ability to write to a socket will return true only if the lowwater mark amount could be processed. The default value for SO SNDLOWAT is setto a convenient size for network efficiency, often 1024. SO RCVLOWAT is an optionto set the minimum count for input operations. In general, receive calls will blockuntil any (non-zero) amount of data is received, then return with the smaller of theamount available or the amount requested. The default value for SO RCVLOWAT is1. If SO RCVLOWAT is set to a larger value, blocking receive calls normally wait untilthey have received the smaller of the low water mark value or the requested amount.Receive calls may still return less than the low water mark if an error occurs, a signalis caught, or the type of data next in the receive queue is different from that whichwas returned.

SO SNDTIMEO is an option to set a timeout value for output operations. It acceptsa struct timeval parameter with the number of seconds and microseconds usedto limit waits for output operations to complete. If a send operation has blockedfor this much time, it returns with a partial count or with the error EWOULDBLOCKif no data were sent. In the current implementation, this timer is restarted eachtime additional data are delivered to the protocol, implying that the limit appliesto output portions ranging in size from the low water mark to the high water markforoutput. SO RCVTIMEO is an option to set a timeout value for input operations. It

Systems/C C Library 269

Page 288: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

accepts a struct timeval parameter with the number of seconds and microsecondsused to limit waits for input operations to complete. In the current implementation,this timer is restarted each time additional data are received by the protocol, andthus the limit is in effect an inactivity timer. If a receive operation has been blockedfor this much time without receiving additional data, it returns with a short countor with the error EWOULDBLOCK if no data were received.

Finally, SO TYPE and SO ERROR are options used only with getsockopt(). SO TYPEreturns the type of the socket, such as SOCK STREAM; it is useful for servers thatinherit sockets on startup. SO ERROR returns any pending error on the socket andclears the error status. It may be used to check for asynchronous errors on connecteddatagram sockets or for other asynchronous errors.

IMPLEMENTATION NOTES

Although many options are described here, only the ones available with IBMTCP/IP are actually supported. Consult the IBM TCP/IP documentation for moreinformation.

RETURN VALUES

A 0 is returned if the call succeeds, -1 if it fails.

ERRORS

The call succeeds unless:

[EBADF] The argument s is not a valid descriptor.

[ENOTSOCK] The argument s is a file, not a socket.

[ENOPROTOOPT] The option is unknown at the level indicated.

[EFAULT] The address pointed to by optval is not in a valid part of the processaddress space. For getsockopt(), this error may also be returnedif optlen is not in a valid part of the process address space.

SEE ALSO

ioctl(2), socket(2), getprotoent(3)

270 Systems/C C Library

Page 289: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

GIVESOCKET(2)

NAME

givesocket - Tell TCP/IP to make the socket available

SYNOPSIS

#include <sys/socket.h>int givesocket(int d, struct clientid *clientid,int *token);

DESCRIPTION

givesocket() instructs TCP/IP to create a token indicating that the specified socketdescriptor d is available to a takesocket() call issued by another program. Thecreated token is returned via the token pointer, and should be used in a subsequenttakesocket() call. Any connected stream socket can be given.

This is typically used by a master/driving program which uses accept() to handleincoming connections, then uses givesocket() to “give” the sockets to the appli-cation programs that actually handle the data. The token set by givesocket() ispassed to the application program to use in a takesocket() call.

The master program passes a clientid structure to the TCP/IP system to identifythe receiver of the socket.

clientid is of the form:

struct clientid {int domain;union {

char name[8];struct {

int NameUpper;pid_t pid;

} c_pid;} c_name;char subtaskname[8];

struct {char type;union {

char specific[19];

Systems/C C Library 271

Page 290: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

struct {char unused[3];int SockToken;

} c_close;} c_func;

} c_reserved;};

domain is the domain of the input socket descriptor.

If the clientid was set by a getclientid() call, c name.name can be set to the ap-plication program’s address space name, left-justified and padded with blanks. Theapplication program can run in the same address space as the master program, inwhich case this field is set to the master program’s address space. Or, c name.namecan be set to blanks, so any OS/390 address space can take the socket.

If the clientid was set by a getclientid() call, subtaskname can be set to the taskidentifier of the taker. This, combined with a c name.name value, allows only a pro-cess with this c name.name and subtaskname to take the socket. Or, subtasknamecan be set to blanks. If c name.name has a value and subtaskname is blank, anytask with that c name.name can take the socket.

c reserved.type can be set to SO CLOSE, to indicate the socket should be auto-matically closed by givesocket(), and a unique socket identifying token is to bereturned in c close.SockToken. The c close.SockToken should be passed to thetaking program to be used as input to takesocket() instead of the socket descriptor.The now closed socket descriptor could be re-used by the time the takesocket() iscalled, so the c close.SockToken should be used for takesocket().

c close.SockToken is a unique socket identifying token returned by givesocketto be used as input to takesocket(), instead of the socket descriptor whenc reserved.type has been set to SO CLOSE.

c reserved specifies binary zeros if an automatic close of a socket is not to be doneby givesocket().

Using name and subtaskname for givesocket/takesocket:

1. The giving program calls getclientid() to obtain its client ID. The givingprogram calls givesocket() to make the socket available for a takesocket()call. The giving program passes its client ID along with the token for thedescriptor of the socket to be given to the taking program by the takingprogram’s startup parameter list.

2. The taking program calls takesocket(), specifying the giving program’s clientID and socket descriptor token.

272 Systems/C C Library

Page 291: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

3. Waiting for the taking program to take the socket, the giving program usesselect() to test the given socket for an exception condition. When select() re-ports that an exception condition is pending, the giving program calls close()to free the given socket.

4. If the giving program closes the socket before a pending exception condition isindicated, the TCP connection is immediately reset, and the taking program’scall to takesocket() is unsuccessful. Calls other than the close() call issuedon a given socket return -1, with errno set to EBADF.

Note: For backward compatibility, a client ID can point to the struct client IDstructure obtained when the target program calls getclientid(). In this case, onlythe target program, and no other programs in the target program’s address space,can take the socket.

RETURN VALUES

On success, givesocket() returns 0. On error, givesocket() returns -1 and setserrno to the specific error.

[EBADF] The descriptor d was not a valid socket descriptor.

[EFAULT] The clientid parameter points outside the caller’s allocated addressspace.

[EINVAL] The clientid parameter does not specify a valid client id or the do-main doesn’t match the domain of the input socket descriptor.

NOTES

This givesocket() function is different from other C libraries available on OS/390,in that it returns the token to pass to takesocket() as a third parameter. Whenporting programs from other C implementations, be sure to take this difference intoaccount.

SEE ALSO

accept(2), close(2), getclientid(2), listen(2), select(2), takesocket(2)

Systems/C C Library 273

Page 292: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

IOCTL(2)

NAME

ioctl - control device

SYNOPSIS

#include <sys/ioctl.h>

intioctl(int d, unsigned long request, ...)

DESCRIPTION

The ioctl() function manipulates the underlying device parameters of special files.In particular, many operating characteristics of character special files (e.g. termi-nals) may be controlled with ioctl() requests. The argument d must be an open filedescriptor.

The third argument to ioctl is traditionally named char *argp. Most uses of ioctlhowever, require the third argument to be a caddr t or an int.

An ioctl request has encoded in it whether the argument is an “in” parameter or“out” parameter, and the size of the argument argp in bytes. Macros and definesused in specifying an ioctl request are located in the file <sys/ioctl.h>.

IMPLEMENTATION NOTES

The Systems/C ioctl() is implemented using the IBM TCP/IP ioctl interface, andthus only supports those IOCTLs that interface provides:

FIONBIO Sets or clears blocking status.

FIONREAD Returns the number of immediately readablebytes for the socket.

SIOCADDRT Adds a specified routing table entry.

SIOCATMARK Determines whether the current location in theinput data is pointing to out-of-band data.

SIOCDELRT Deletes a specified routine table entry.

274 Systems/C C Library

Page 293: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

SIOCGIFADDR Requests the network interface address for aninterface name.

SIOCGIFBRDADDR Requests the network interface broadcast ad-dress for an interface name.

SIOCGIFCONF Requests the network interface configuration.The configuration consists of a variable numberof 32-byte arrays.

SIOCGIFDSTADDR Requests the network interface destination ad-dress.

SIOCGIFFLAGS Requests the network interface flags.

SIOCGIFMETRIC Requests the network interface routing metric.

SIOCGIFNETMASK Requests the network interface network mask.

SIOCSIFMETRIC Sets the network interface routing metric.

SIOCSIFDSTADDR Sets the network interface destination address.

SIOCSIFFLAGS Sets the network interface flags.

SIOCTTLSCTL Query or control the use of AT-TLS informa-tion for a connection.

RETURN VALUES

If an error has occurred, a value of -1 is returned and errno is set to indicate theerror.

ERRORS

ioctl() will fail if:

[EBADF] d is not a valid descriptor.

[ENOTTY] d is not associated with a character special device.

[ENOTTY] The specified request does not apply to the kind of object that thedescriptor d references.

[EINVAL] Request or argp is not valid.

[ENOMEM] Insufficient memory is available to satisfy the request.

[EPROTOYPE] Socket is not TCP.

Systems/C C Library 275

Page 294: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

[EINVAL] Invalid parameters passed to request.

[EPERM] Permission denied for request.

[ENOTCONN] Operation attempted on socket that wasn’t connected.

[EPIPE] Request was made on socket that is no longer establihed.

[EOPNOSUPP] Request is not supported.

[EACCESS] Access denied for request.

[EALREADY] Request is already made or is in process.

[EPROTO] Invalid protocol specified in request.

[EINPROGRESS] A socket handshake is in progress.

[EWOULDBLOCK] The socket is non-blocking and an SSL handshake is in progress.

[ENOBUFS] The specified return area is too small.

The errno value can also be set according to the return value from the underlyingIBM implementation. Consult the IBM “IP Communications Server” documenta-tion for the particular ioctl() request and possible errno settings.

276 Systems/C C Library

Page 295: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

LISTEN(2)

NAME

listen - listen for connections on a socket

SYNOPSIS

#include <sys/types.h>#include <sys/socket.h>

intlisten(int s, int backlog)

DESCRIPTION

To accept connections, a socket is first created with socket(2), a willingness to acceptincoming connections and a queue limit for incoming connections are specified withlisten(), and then the connections are accepted with accept(2). The listen() callapplies only to sockets of type SOCK STREAM or SOCK SEQPACKET.

The backlog parameter defines the maximum length the queue of pending connec-tions may grow to. If a connection request arrives with the queue full the client mayreceive an error with an indication of ECONNREFUSED, or, if the underlying protocolsupports retransmission, the request may be ignored so that retries may succeed.

RETURN VALUES

A 0 return value indicates success; -1 indicates an error.

ERRORS

listen() will fail if:

[EBADF] The argument s is not a valid descriptor.

[ENOTSOCK] The argument s is not a socket.

[EOPNOTSUPP] The socket is not of a type that supports the operation listen().

SEE ALSO

accept(2), connect(2), socket(2), sysctl(3)

Systems/C C Library 277

Page 296: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

POLL(2)

NAME

poll – synchronous I/O multiplexing

SYNOPSIS

#include <poll.h>

intpoll(struct pollfd fds[], nfds_t nfds, int timeout);

DESCRIPTION

The poll function examines a set of file descriptors to see if some of them are readyfor I/O. The fds argument is a pointer to an array of pollfd structures as defined in¡poll.h¿ (shown below). The nfds argument determines the size of the fds array.

struct pollfd {int fd; /* file descriptor */short events; /* events to look for */short revents; /* events returned */

};

The fields of struct pollfd are as follows:

fd File descriptor to poll. If fd is equal to -1 then reventsis cleared (set to zero), and that pollfd is not checked.

events Events to poll for. (See below.)

revents Events which may occur. (See below.)

The event bitmasks in events and revents have the following bits:

POLLIN Data other than high priority data may be read withoutblocking.

POLLRDNORM Normal data may be read without blocking.

278 Systems/C C Library

Page 297: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

POLLRDBAND Data with a non-zero priority may be read withoutblocking.

POLLPRI High priority data may be read without blocking.

POLLOUT

POLLWRNORM Normal data may be written without blocking.

POLLWRBAND Data with a non-zero priority may be written withoutblocking.

POLLERR An exceptional condition has occurred on the device orsocket. This flag is always checked, even if not presentin the events bitmask.

POLLHUP The device or socket has been disconnected. This flag isalways checked, even if not present in the events bitmask.Note that POLLHUP and POLLOUT should never bepresent in the revents bitmask at the same time.

POLLNVAL The file descriptor is not open. This flag is alwayschecked, even if not present in the events bitmask.

If timeout is neither zero nor INFTIM (-1), it specifies a maximum interval to wait forany file descriptor to become ready, in milliseconds. If timeout is INFTIM (-1), thepoll blocks indefinitely. If timeout is zero, then poll will return without blocking.

RETURN VALUES

The poll system call returns the number of descriptors that are ready for I/O, or-1 if an error occurred. If the time limit expires, poll returns 0. If poll returnswith an error, including one due to an interrupted system call, the fds array will beunmodified.

COMPATIBILITY

This implementation is an emulation based on the select(2) function.

ERRORS

An error return from poll() indicates:

[EFAULT] The fds argument points outside the process’s allocatedaddress space.

Systems/C C Library 279

Page 298: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

[EINTR] A signal was delivered before the time limit expired andbefore any of the selected events occurred.

[EINVAL] The specified time limit is negative.

SEE ALSO

accept(2), connect(2), kqueue(2), read(2), recv(2), select(2), send(2), write(2)

280 Systems/C C Library

Page 299: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

RECV(2)

NAME

recv, recvfrom, recvmsg - receive a message from a socket

SYNOPSIS

#include <sys/types.h>#include <sys/socket.h>

ssize_trecv(int s, void *buf, size_t len, int flags)

ssize_trecvfrom(int s, void *buf, size_t len, int flags,struct sockaddr *from, int *fromlen)

ssize_trecvmsg(int s, struct msghdr *msg, int flags)

DESCRIPTION

recvfrom() and recvmsg() are used to receive messages from a socket, and maybe used to receive data on a socket whether or not it is connection-oriented.

If from is non-nil, and the socket is not connection-oriented, the source address ofthe message is filled in. fromlen is a value-result parameter, initialized to the size ofthe buffer associated with from, and modified on return to indicate the actual sizeof the address stored there.

The recv() call is normally used only on a connected socket (see connect(2)) and isidentical to recvfrom() with a nil from parameter. As it is redundant, it may notbe supported in future releases.

All three routines return the length of the message on successful completion. Ifa message is too long to fit in the supplied buffer, excess bytes may be discardeddepending on the type of socket the message is received from (see socket(2)).

If no messages are available at the socket, the receive call waits for a message toarrive, unless the socket is nonblocking (see fcntl(2)) in which case the value -1 isreturned and the external variable errno set to EAGAIN. The receive calls normallyreturn any data available, up to the requested amount, rather than waiting forreceipt of the full amount requested; this behavior is affected by the socket-leveloptions SO RCVLOWAT and SO RCVTIMEO described in getsockopt(2).

Systems/C C Library 281

Page 300: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

The select(2) call may be used to determine when more data arrive.

The flags argument to a recv call is formed by or’ing one or more of the values:

MSG OOB process out-of-band data

MSG PEEK peek at incoming message

MSG WAITALL wait for full request or error

The MSG OOB flag requests receipt of out-of-band data that would not be receivedin the normal data stream. Some protocols place expedited data at the head ofthe normal data queue, and thus this flag cannot be used with such protocols. TheMSG PEEK flag causes the receive operation to return data from the beginning ofthe receive queue without removing that data from the queue. Thus, a subsequentreceive call will return the same data. The MSG WAITALL flag requests that theoperation block until the full request is satisfied. However, the call may still returnless data than requested if a signal is caught, an error or disconnect occurs, or thenext data to be received is of a different type than that returned.

The recvmsg() call uses a msghdr structure to minimize the number of di-rectly supplied parameters. This structure has the following form, as defined in<sys/socket.h>:

struct msghdr {caddr_t msg_name; /* optional address */u_int msg_namelen; /* size of address */struct iovec *msg_iov; /* scatter/gather */

/* array */u_int msg_iovlen; /* # elements in */

/* msg_iov */caddr_t msg_control; /* ancillary data, */

/* see below */u_int msg_controllen; /* ancillary data, */

/* buffer len */int msg_flags; /* flags on */

/* received message */};

Here msg name and msg namelen specify the destination address if the socket isunconnected; msg name may be given as a null pointer if no names are desired orrequired. msg iov and msg iovlen describe scatter gather locations, as discussedin read(2). msg control, which has length msg controllen, points to a buffer forother protocol control related messages or other miscellaneous ancillary data. Themessages are of the form:

282 Systems/C C Library

Page 301: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

struct cmsghdr {u_int cmsg_len; /* data byte count, */

/* including hdr */int cmsg_level; /* originating */

/* protocol */int cmsg_type; /* protocol-specific */

/* type *//* followed by

u_char cmsg_data[]; */};

As an example, one could use this to learn of changes in the data-stream inXNS/SPP, or in ISO, to obtain user-connection-request data by requesting a recvmsgwith no data buffer provided immediately after an accept() call.

Process credentials can also be passed as ancillary data for AF UNIX domain socketsusing a cmsg type of SCM CREDS. In this case, cmsg data should be a structure oftype cmsgcred, which is defined in <sys/socket.h> as follows:

struct cmsgcred {pid_t cmcred_pid; /* PID of */

/* sending process */uid_t cmcred_uid; /* real UID of */

/* sending process */uid_t cmcred_euid; /* effective UID of */

/* sending process */gid_t cmcred_gid; /* real GID of */

/* sending process */short cmcred_groups; /* number or groups */gid_t cmcred_groups[CMGROUP_MAX]; /* groups */

};

[Note that AF UNIX domain sockets are currently not supported in the Systems/CTCP/IP library, as they are unsupported by the IBM TCP/IP implemention. Thisinformation is provided for reference.]

The kernel will fill in the credential information of the sending process and deliverit to the receiver.

The msg flags field is set on return according to the message received. MSG EORindicates end-of-record; the data returned completed a record (generally used withsockets of type SOCK SEQPACKET). MSG TRUNC indicates that the trailing portion of adatagram was discarded because the datagram was larger than the buffer supplied.MSG CTRUNC indicates that some control data were discarded due to lack of spacein the buffer for ancillary data. MSG OOB is returned to indicate that expedited orout-of-band data were received.

Systems/C C Library 283

Page 302: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

RETURN VALUES

These calls return the number of bytes received, or -1 if an error occurred. Notethat a return value of 0 indicates the connection has been closed (no bytes received.)

ERRORS

The calls fail if:

[EBADF] The argument s is an invalid descriptor.

[ENOTCONN] The socket is associated with a connection-oriented protocol andhas not been connected (see connect(2) and accept(2)).

[ENOTSOCK] The argument s does not refer to a socket.

[EAGAIN] The socket is marked non-blocking, and the receive operation wouldblock, or a receive timeout had been set, and the time-out expiredbefore data were received.

[EINTR] The receive was interrupted by delivery of a signal before any datawere available.

[EFAULT] The receive buffer pointer(s) point outside the process’s addressspace.

SEE ALSO

getsockopt(2), read(2), select(2), socket(2)

284 Systems/C C Library

Page 303: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

SELECT(2)

NAME

select - synchronous I/O multiplexing

SYNOPSIS

#include <sys/types.h>#include <sys/time.h>#include <unistd.h>

intselect(int nfds, fd_set *readfds, fd_set *writefds,fd_set *exceptfds, struct timeval *timeout)

FD_SET(fd, &fdset)

FD_CLR(fd, &fdset)

FD_ISSET(fd, &fdset)

FD_ZERO(&fdset)

DESCRIPTION

select() examines the I/O descriptor sets whose addresses are passed in readfds,writefds, and exceptfds to see if some of their descriptors are ready for reading, areready for writing, or have an exceptional condition pending, respectively. The onlyexceptional condition detectable is out-of-band data received on a socket. The firstnfds descriptors are checked in each set; i.e., the descriptors from 0 through nfds-1 inthe descriptor sets are examined. On return, select() replaces the given descriptorsets with subsets consisting of those descriptors that are ready for the requestedoperation. select() returns the total number of ready descriptors in all the sets.

The descriptor sets are stored as bit fields in arrays of integers. The following macrosare provided for manipulating such descriptor sets:

FD ZERO(&fdset) initializes a descriptor setfdset to the null set.

FD SET(fd, &fdset) includes a particular de-scriptor fd in fdset.

FD CLR(fd, &fdset) removes fd from fdset.

Systems/C C Library 285

Page 304: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

FD ISSET(fd, &fdset) is non-zero if fd is a mem-ber of fdset, zero other-wise.

The behavior of these macros is undefined if a descriptor value is less than zeroor greater than or equal to FD SETSIZE, which is normally at least equal to themaxmum number of descriptors supported by the system.

If timeout is a non-nil pointer, it specifies a maximum interval to wait for the selectionto complete. If timeout is a NULL pointer, the select blocks indefinitely. To effect apoll, the timeout argument should be non-NULL, pointing to a zero-valued timevalstructure.

Any of readfds, writefds, and exceptfds may be given as NULL pointers if no descriptorsare of interest.

RETURN VALUES

select() returns the number of ready descriptors that are contained in the descriptorsets, or -1 if an error occurred. If the time limit expires, select() returns 0. If se-lect() returns with an error, including one due to an interrupted call, the descriptorsets will be unmodified.

ERRORS

An error return from select() indicates:

[EBADF] One of the descriptor sets specified an invalid descriptor.

[EINTR] A signal was delivered before the time limit expired and before anyof the selected events occurred.

[EINVAL] The specified time limit is invalid. One of its components is negativeor too large.

[EINVAL] nfds was invalid.

SEE ALSO

accept(2), connect(2), getdtablesize(2), gettimeofday(2), read(2), recv(2), send(2),write(2)

286 Systems/C C Library

Page 305: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

NOTES

The default size of FD SETSIZE is currently 1024. In order to accommodate programswhich might potentially use a larger number of open files with select() , it is possibleto increase this size by having the program define FD SETSIZE before the inclusionof any header which includes <sys/types.h>.

If nfds is greater than the number of open files, select() is not guaranteed to examinethe unused file descriptors. For historical reasons, select() will always examine thefirst 256 descriptors.

ISSUES

select() should probably return the time remaining from the original timeout, ifany, by modifying the time value in place. This may be implemented in futureversions of the system. Thus, it is unwise to assume that the timeout value will beunmodified by the select() call.

Systems/C C Library 287

Page 306: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

SELECTEX(2)

NAME

selectex - synchronous I/O multiplexing with extensions for message queues

SYNOPSIS

#include <sys/types.h>#include <sys/time.h>#include <unistd.h>

intselectex(int nfds, fd_set *readfds, fd_set *writefds,fd_set *exceptfds, struct timeval *timeout,int *ecbptr)

DESCRIPTION

The selectex() call operates in a manner similar to select(2), except that it providesan extension to allow for using an ECB that defines an event not described by thedescriptors in the readfds, writefds or exceptfds.

selectex() monitors activity on the file descriptors until a timeout occurs, or untilthe ECB is posted.

See select(2) for more information and a description of the nfds, readfds, writefds,exceptfds and timeout parameters and return values.

If non-NULL, ecbptr can be a pointer to a single ECB or a list of ECBs. If ecbptr isNULL, selectex() is equivalent to select(2).

To specify a single ECB, the high-order bit of ecbptr must be ’0’. To specify a listof up to 59 ECBS, the high-order bit of ecbptr must be ’1’. The high-order bit ofthe last pointer in the list must be ’1’.

SEE ALSO

select(2)

288 Systems/C C Library

Page 307: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

SEND(2)

NAME

send, sendto, sendmsg - send a message from a socket

SYNOPSIS

#include <sys/types.h>#include <sys/socket.h>

ssize_tsend(int s, const void *msg, size_t len, int flags)

ssize_tsendto(int s, const void *msg, size_t len, int flags,const struct sockaddr *to, socklen_t tolen)

ssize_tsendmsg(int s, const struct msghdr *msg, int flags)

DESCRIPTION

send(), sendto(), and sendmsg() are used to transmit a message to anothersocket. send() may be used only when the socket is in a connected state, whilesendto() and sendmsg() may be used at any time.

The address of the target is given by to with tolen specifying its size. The length ofthe message is given by len. If the message is too long to pass atomically throughthe underlying protocol, the error EMSGSIZE is returned, and the message is nottransmitted.

No indication of failure to deliver is implicit in a send(). Locally detected errorsare indicated by a return value of -1.

If no messages space is available at the socket to hold the message to be transmitted,then send() normally blocks, unless the socket has been placed in non-blocking I/Omode. The select(2) call may be used to determine when it is possible to send moredata.

The flags parameter may include one or more of the following:

#define MSG_OOB 0x1 /* process out-of-band *//* data */

Systems/C C Library 289

Page 308: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

#define MSG_PEEK 0x2 /* peek at incoming *//* message */

#define MSG_DONTROUTE 0x4 /* bypass routing, *//* use direct interface */

#define MSG_EOR 0x8 /* data completes record */#define MSG_EOF 0x100 /* data completes */

/* transaction */

The flag MSG OOB is used to send “out-of-band” data on sockets that support thisnotion (e.g. SOCK STREAM); the underlying protocol must also support “out-of-band”data. MSG EOR is used to indicate a record mark for protocols which support theconcept. MSG EOF requests that the sender side of a socket be shut down, and thatan appropriate indication be sent at the end of the specified data; this flag is onlyimplemented for SOCK STREAM sockets in the PF INET protocol family, and is usedto implement Transaction TCP. [Note that the Systems/C library depends on theIBM TCP/IP implementation, which may not implement this and other features.]MSG DONTROUTE is usually used only by diagnostic or routing programs.

See recv(2) for a description of the msghdr structure.

RETURN VALUES

The call returns the number of characters sent, or -1 if an error occurred.

ERRORS

send(), sendto(), and sendmsg() fail if:

[EBADF] An invalid descriptor was specified.

[EACCES] The destination address is a broadcast address, and SO BROADCASThas not been set on the socket.

[ENOTSOCK] The argument s is not a socket.

[EFAULT] An invalid user space address was specified for a parameter.

[EMSGSIZE] The socket requires that message be sent atomically, and the size ofthe message to be sent made this impossible.

[EAGAIN] The socket is marked non-blocking and the requested operationwould block.

[ENOBUFS] The system was unable to allocate an internal buffer. The operationmay succeed when buffers become available.

290 Systems/C C Library

Page 309: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

[ENOBUFS] The output queue for a network interface was full. This generallyindicates that the interface has stopped sending, but may be causedby transient congestion.

[EHOSTUNREACH] The remote host was unreachable.

ISSUES

These functions are implemented with the IBM TCP/IP interface. Not all facilitiesdescribed here may be available.

Because sendmsg() doesn’t necessarily block until the data has been transferred,it is possible to transfer an open file descriptor across an AF UNIX domain socket(see recv(2)), then close() it before it has actu ally been sent, the result being thatthe receiver gets a closed file descriptor. It is left to the application to implementan acknowledgment mechanism to prevent this from happening.

SEE ALSO

getsockopt(2), recv(2), select(2), socket(2), write(2)

Systems/C C Library 291

Page 310: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

SETSOCKPARM(2)

NAME

setsockparm - define IBM TCP/IP socket function parameters

SYNOPSIS

#include <sys/types.h>#include <sys/socket.h>

void__setsockparm(int opt, ...)

DESCRIPTION

setsockparm() is used to provide low-level initialization options to the underlyingIBM TCP/IP implementation.

The call(s) to setsockparm must be made before any other socket calls.

The opt parameter describes an option to set.

The following options are supported:

SP TCPNAME Defines the job name to be used during socket initializa-tion. The value following the opt parameter is a pointerto a null-terminated character string

SP ADSNAME Defines the address name to be used during socket ini-tialization The value following the opt parameter is apointer to a null-terminated character string.

SP SUBTASK Defines the subtask name. The subtask name is a fieldup to 8 characters which identifies the subtask. Usefulfor address spaces that contain multiple subtasks.

EXAMPLE

This example defines the TCP job name to be "TCPIP" and the address name to be"TSO001":

292 Systems/C C Library

Page 311: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

char tcpname[9] = "TCPIP";char adsname[9] = "TSO0001";

__setsockparm(__SP_TCPNAME, tcpname);__setsockparm(__SP_ADSNAME, adsname);

SEE ALSO

See the IBM Communications Server: IP Application Programming Interface Guidefor a complete description of the valid values for the TCP/IP JOB and addressnames.

Systems/C C Library 293

Page 312: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

SOCKET(2)

NAME

socket - create an endpoint for communication

SYNOPSIS

#include <sys/types.h>#include <sys/socket.h>

intsocket(int domain, int type, int protocol)

DESCRIPTION

socket() creates an endpoint for communication and returns a descriptor.

The domain parameter specifies a communications domain within which communi-cation will take place; this selects the protocol family which should be used. Thesefamilies are defined in the include file <sys/socket.h>.

The currently understood formats are

PF LOCAL (Host-internal protocols, formerly called PF UNIX),

PF INET (ARPA Internet protocols),

PF ISO (ISO protocols),

PF CCITT (ITU-T protocols, like X.25),

PF NS (Xerox Network Systems protocols)

[Note, the Systems/C TCP/IP implementation relies on the IBM TCP/IP imple-mentation, which only provides PF INET, PF UNIX and PF RAW. The other communi-cation domains are provided for reference.]

These communication domains were previously named AF UNIX, AF INET, AF ISO,AF CCITT and AF NS. The older names are provided for compatibility.

The socket has the indicated type, which specifies the semantics of communication.Currently defined types are:

• SOCK STREAM

294 Systems/C C Library

Page 313: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

• SOCK DGRAM

• SOCK RAW

• SOCK SEQPACKET

• SOCK RDM

[Note, the Systems/C TCP/IP implementation depends on the IBM implementa-tion, which only provides SOCK STREAM, SOCK DGRAM and SOCK RAW. Information onthe other socket types is included for reference.]

A SOCK STREAM type provides sequenced, reliable, two-way connection based bytestreams. An out-of-band data transmission mechanism may be supported. ASOCK DGRAM socket supports datagrams (connectionless, unreliable messages of afixed (typically small) maximum length). A SOCK SEQPACKET socket may providea sequenced, reliable, two-way connection-based data transmission path for data-grams of fixed maximum length; a consumer may be required to read an entirepacket with each read system call. This facility is protocol specific, and presentlyimplemented only for PF NS. SOCK RAW sockets provide access to internal networkprotocols and interfaces. The types SOCK RAW, which is available only to the super-user, and SOCK RDM, which is planned, but not yet implemented, are not describedhere.

The protocol specifies a particular protocol to be used with the socket. Normallyonly a single protocol exists to support a particular socket type within a givenprotocol family. However, it is possible that many protocols may exist, in whichcase a particular protocol must be specified in this manner. The protocol number touse is particular to the communication domain in which communication is to takeplace. Some possible values for protocol are 0, IPPROTO UDP or IPPROTO TCP.

Sockets of type SOCK STREAM are full-duplex byte streams, similar to pipes. A streamsocket must be in a connected state before any data may be sent or received on it. Aconnection to another socket is created with a connect(2) call. Once connected, datamay be transferred using read(2) and write(2) calls or some variant of the send(2)and recv(2) calls. (Some protocol families, such as the Internet family, support thenotion of an “implied connect,” which permits data to be sent piggy-backed onto aconnect operation by using the sendto(2) call.) When a session has been completed aclose(2) may be performed. Out-of-band data may also be transmitted as describedin send(2) and received as described in recv(2).

The communications protocols used to implement a SOCK STREAM insure that datais not lost or duplicated. If a piece of data for which the peer protocol has bufferspace cannot be successfully transmitted within a reasonable length of time, thenthe connection is considered broken and calls will indicate an error with -1 returnsand with ETIMEDOUT as the specific code in the global variable errno. The protocolsoptionally keep sockets “warm” by forcing transmissions roughly every minute inthe absence of other activity. An error is then indicated if no response can be elicitedon an otherwise idle connection for a extended period (e.g. 5 minutes). A SIGPIPE

Systems/C C Library 295

Page 314: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

signal is raised if a process sends on a broken stream; this causes naive processes,which do not handle the signal, to exit. SOCK SEQPACKET sockets employ the samesystem calls as SOCK STREAM sockets. The only difference is that read(2) calls willreturn only the amount of data requested, and any remaining in the arriving packetwill be discarded. SOCK DGRAM and SOCK RAW sockets allow sending of datagramsto correspondents named in send(2) calls. Datagrams are generally received withrecvfrom(2), which returns the next datagram with its return address.

The operation of sockets is controlled by socket level options. These options aredefined in the file <sys/socket.h>. Setsockopt(2) and getsock opt(2) are used toset and get options, respectively.

RETURN VALUES

A -1 is returned if an error occurs, otherwise the return value is a descriptor refer-encing the socket.

ERRORS

The socket() call fails if:

[EPROTONOSUPPORT] The protocol type or the specified protocol is not supportedwithin this domain.

[EMFILE] The per-process descriptor table is full.

[ENFILE] The system file table is full.

[EACCES] Permission to create a socket of the specified type and/or protocolis denied.

[ENOBUFS] Insufficient buffer space is available. The socket cannot be createduntil sufficient resources are freed.

IMPLEMENTATION NOTES

Although many options are described here, only the ones available with IBMTCP/IP are actually supported. Consult the IBM TCP/IP documentation for moreinformation.

SEE ALSO

accept(2), bind(2), connect(2), getpeername(2), getsockname(2), getsockopt(2),ioctl(2), listen(2), read(2), recv(2), select(2), send(2), shutdown(2), socketpair(2),write(2), getprotoent(3)

296 Systems/C C Library

Page 315: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

SHUTDOWN(2)

NAME

shutdown - shut down part of a full-duplex connection

SYNOPSIS

#include <sys/types.h>#include <sys/socket.h>

intshutdown(int s, int how)

DESCRIPTION

The shutdown() call causes all or part of a full-duplex connection on the socketassociated with s to be shut down. If how is SHUT RD (0), further receives willbe disallowed. If how is SHUT WR (1), further sends will be disallowed. If how isSHUT RDWR (2), further sends and receives will be disallowed.

RETURN VALUES

A 0 is returned if the call succeeds, -1 if it fails.

ERRORS

The call succeeds unless:

[EBADF] s is not a valid descriptor.

[ENOTSOCK] s is a file, not a socket.

[ENOTCONN] The specified socket is not connected.

SEE ALSO

connect(2), socket(2)

Systems/C C Library 297

Page 316: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

STANDARDS

The shutdown() function is expected to comply with IEEE P1003.1g (“POSIX”),when finalized.

298 Systems/C C Library

Page 317: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

TAKESOCKET(3)

NAME

takesocket - acquire a socket from another program

SYNOPSIS

#include <sys/types.h>#include <socket.h>

int takesocket(struct clientid *clientid,int token);

DESCRIPTION

The takesocket() function acquires a socket from another program viathe tokenpassed from the other program. Typically, the other program passes its client ID andgivesocket token, and/or process id (PID), to your program through your program’sstartup parameter list.

clientid is a pointer to the clientid of the application from which you are taking asocket.

token is the token generated by a givesocket() call, which represents the socket tobe taken.

If your program is using the PID to ensure integrity between givesocket() andtakesocket(), before issuing the takesocket() call, your program should set thec pid.pid field of the clientid structure to the PID of the giving program (i.e.program that issued the givesocket() call). This identifies the process from whichthe socket is to be taken. If the c reserved.type field of the clientid structurewas set to SO CLOSE on the givesocket() call, c close.SockToken of the clientidstructure should be used as input to takesocket() instead of the normal socketdescriptor. See givesocket(2) for a description of the clientid structure.

RETURN VALUE

takesocket() returns the new socket descriptor, or -1 on error. If the return valueis -1, errno is set to:

[EACCES] The other application did not give the socket to this application.

[EBADF] The token parameter does not specify a valid token from the otherapplication, or the socket has already been taken.

Systems/C C Library 299

Page 318: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

[EFAULT] The clientid parameter points outside the process’s allocated ad-dress space.

[EINVAL] The clientid parameter does not specify a valid client identifier.Either the client process cannot be found, or the client exists, buthas no outstanding “given” sockets.

[EMFILE] The file descriptor table is full.

SEE ALSO

getclientid(2), givesocket(2)

300 Systems/C C Library

Page 319: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

Gen Library

Historically, the “gen” portion of a C library are those files which are automaticallygenerated, or which are generated in a platform-specific manner. For the Systems/Clibrary, the distinction isn’t as meaningful as it may be on other platforms.

Systems/C C Library 301

Page 320: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

ATOE(3)

NAME

atoe, etoa, stratoe, stretoa, strnatoe, strnetoa, bcopy atoe, bcopy etao- ASCII/EBCDIC character translation functions

SYNOPSIS

#include <machine/atoe.h>

unsigned int __atoe(unsigned int char);

unsigned int __etoa(unsigned int char);

void __stratoe(unsigned char * string);

void __stretoa(unsigned char * string);

void __strnatoe(unsigned char *string, int len);

void __strnetoa(unsigned char *string, int len);

void __bcopy_atoe(unsigned char *src, unsigned char *dst, int len);

void __bcopy_etoa(unsigned char *src, unsigned char *dst, int len);

DESCRIPTION

The atoe() and etoa() functions translate a value in the range 0-255 to/fromASCII and EBCDIC. The translation table employed is the same used by the Sys-tems/C compiler and utilties, and assumes the IBM 1047 code page.

The stratoe() and stretoa() functions apply the translation directly to a NUL-terminate string.

The strnatoe() and strnetoa() functions apply the translation to a string; thetranslation stops when either the NUL terminating character is discovered, or thelength len is reached.

The bcopy atoe() and bcopy etoa() functions copy len bytes from the srcaddress to the dst address, translating the bytes as they are copied. If len is zero,no bytes are copied.

302 Systems/C C Library

Page 321: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

SEE ALSO

bcopy(3), strcpy(3), strncpy(3)

Systems/C C Library 303

Page 322: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

TO XX(3)

NAME

to b1, to b2, to b4, to d1, to d2, to d4, to h1, to h2, to h4 - floatingpoint conversion functions

SYNOPSIS

These functions don’t appear in any header file, thus, the #pragma map statementsmust be properly provided to use them.

#ifdef __cplusplusextern "C" {#endif /* __cplusplus */

#pragma map(__to_b1, "@@TO@B1")float __to_b1(unsigned int flags, void *input_p)

#pragma map(__to_b2, "@@TO@B2")double __to_b2(unsigned int flags, void *input_p)

#pragma map(__to_b4, "@@TO@B4")long double __to_b4(unsigned int flags, void *input_p)

#pragma map(__to_d1, "@@TO@D1")_Decimal32 __to_d1(unsigned int flags, void *input_p)

#pragma map(__to_d2, "@@TO@D2")_Decimal64 __to_d2(unsigned int flags, void *input_p)

#pragma map(__to_d4, "@@TO@D4")_Decimal128 __to_d4(unsigned int flags, void *input_p)

#pragma map(__to_h1, "@@TO@H1")float __to_h1(unsigned int flags, void *input_p)

#pragma map(__to_h2, "@@TO@H2")double __to_h2(unsigned int flags, void *input_p)

#pragma map(__to_h4, "@@TO@H4")long double __to_h4(unsigned int flags, void *input_p)

#ifdef __cplusplus}

304 Systems/C C Library

Page 323: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

#endif /* __cplusplus */

DESCRIPTION

These functions convert the input floating point value addressed by input p, return-ing an IEEE (BFP), Decimal Floating Point (DFP) or Hexadecimal Floating point(HFP) value. The to b1, to b2 and to b4 functions return IEEE (BFP)values of the specified return type. The to d1, to d2 and to d4 return Dec-imal Floating Point (DFP) values of the given sizes. The to h1, to h2 andto h4 return Hexadecimal Floating Point (HFP) values of the given sizes. The

flags parameter provides flags indicating the type of the input value addressed byinput p.

These functions do not require any particular hardware architecture support, andno hardware floating point exceptions are raised.

The value of the flags parameter describes the input parameter and the requestedrounding mode of the result. These two values are OR’d together to create thevalue. For the type of input parameter, one of the following values should be used:

0x000 HFP float

0x100 HFP double

0x200 HFP long double

0x500 BFP float

0x600 BFP double

0x700 BFP long double

0x800 DFP Decimal32

0x900 DFP Decimal64

0xA00 DFP Decimal128

The following values should be used to indicate the rounding mode:

0x00 Round to Nearest Ties Even

0x08 Round to Nearest Ties Even

0x09 Round Toward Zero

0x0A Round Toward +Infinity

Systems/C C Library 305

Page 324: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

0x0B Rount Toward -Infinity

0x0C Round to Nearest, Ties Away from Zero

0x0D Round to Nearest, Ties Toward from Zero

0x0E Round Away from Zero

0x0F Round Prepare for Shorter Precision

If the conversion specified in conv flag is not valid a divide-by-zero exception israised. Otherwise, no other exceptions are raised.

SEE ALSO

An explanation of the rounding modes can be found in the z/Architecture Principlesof Operations.

306 Systems/C C Library

Page 325: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

ALARM(3)

NAME

alarm – set signal timer alarm

SYNOPSIS

#include <unistd.h>

unsigned intalarm(unsigned int seconds);

DESCRIPTION

This interface is made obsolete by setitimer(2).

The alarm() function sets a timer to deliver the signal SIGALRM to the callingprocess after the specified number of seconds. If an alarm has already been set withalarm() but has not been delivered, another call to alarm() will supersede theprior call. The request alarm(0) voids the current alarm and the signal SIGALRMwill not be delivered.

Due to setitimer(2) restriction the maximum number of seconds allowed is100000000.

RETURN VALUES

The return value of alarm() is the amount of time left on the timer from a previouscall to alarm(). If no alarm is currently set, the return value is 0.

SEE ALSO

setitimer(2), sigaction(2), sigpause(2), sigvec(2), signal(3), sleep(3)

Systems/C C Library 307

Page 326: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

ASSERT(3)

NAME

assert - expression verification macro

SYNOPSIS

#include <assert.h>

assert(expression)

DESCRIPTION

The assert() macro tests the given expression and if it is false, the calling processis terminated. A diagnostic message is written to stderr and the function abort(3)is called effectively terminating the program.

If expression is true, the assert() macro does nothing.

The assert() macro may be removed at compile time with the -DNDEBUG option,see the -D option description in the compiler documentation.

DIAGNOSTICS

The following diagnostic message is written to stderr if expression is false:

"assertion \"%s\" failed: file \"%s\", line %d\n", \"expression", __FILE__, __LINE__

SEE ALSO

abort(3)

308 Systems/C C Library

Page 327: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

BITSTRING(3)

NAME

bit alloc, bit clear, bit decl, bit ffs, bit nclear, bit nset, bit set, bitstr size, bit test- bit-string manipulation macros

SYMNOPSIS

#include <bitstring.h>

bitstr_t *bit_alloc(int nbits);

voidbit_decl(bitstr_t *name, int nbits);

voidbit_clear(bitstr_t *name, int bit);

voidbit_ffc(bitstr_t *name, int nbits, int *value);

voidbit_ffs(bitstr_t *name, int nbits, int *value);

voidbit_nclear(bitstr_t *name, int start, int stop);

voidbit_nset(bitstr_t *name, int start, int stop);

voidbit_set(bitstr_t *name, int bit);

intbitstr_size(int nbits);

intbit_test(bitstr_t *name, int bit);

DESCRIPTION

These macros operate on strings of bits.

Systems/C C Library 309

Page 328: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

The macro bit alloc() returns a pointer of type “bitstr t *” to sufficient spaceto store nbits bits, or NULL if no space is available.

The macro bit decl() allocates sufficient space to store nbits bits on the stack.

The macro bitstr size() returns the number of elements of type bitstr t neces-sary to store nbits bits. This is useful for copying bit strings.

The macros bit clear() and bit set() clear or set the zero-based numbered bitbit, in the bit string name.

The bit nset() and bit nclear() macros set or clear the zero-based numberedbits from start through stop in the bit string name.

The bit test() macro evaluates to non-zero if the zero-based numbered bit bit ofbit string name is set, and zero otherwise.

The bit ffs() macro stores in the location referenced by value the zero-basednumber of the first bit set in the array of nbits bits referenced by name. If no bitsare set, the location referenced by value is set to -1.

The macro bit ffc() stores in the location referenced by value the zero-basednumber of the first bit not set in the array of nbits bits referenced by name. If allbits are set, the location referenced by value is set to -1.

The arguments to these macros are evaluated only once and may safely have sideeffects.

EXAMPLES

#include <limits.h>#include <bitstring.h>

...#define LPR_BUSY_BIT 0#define LPR_FORMAT_BIT 1#define LPR_DOWNLOAD_BIT 2...#define LPR_AVAILABLE_BIT 9#define LPR_MAX_BITS 10

make_lpr_available(){

bitstr_t bit_decl(bitlist, LPR_MAX_BITS);...bit_nclear(bitlist, 0, LPR_MAX_BITS - 1);...

310 Systems/C C Library

Page 329: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

if (!bit_test(bitlist, LPR_BUSY_BIT)) {bit_clear(bitlist, LPR_FORMAT_BIT);bit_clear(bitlist, LPR_DOWNLOAD_BIT);bit_set(bitlist, LPR_AVAILABLE_BIT);

}}

SEE ALSO

memory(3)

Systems/C C Library 311

Page 330: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

CLOCK(3)

NAME

clock - determine processor time used

SYNOPSIS

#include <time.h>

clock_tclock(void)

DESCRIPTION

The clock() function determines the amount of processor time used since the invo-cation of the calling process, measured in CLOCKS PER SEC’s of a second.

RETURN VALUES

The clock() function returns the amount of time used unless an error occurs, inwhich case the return value is -1.

STANDARDS

The clock() function conforms to ISO/IEC 9899:1990 (“ISO C90”).

312 Systems/C C Library

Page 331: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

CTERMID(3)

NAME

ctermid – generate terminal pathname

SYNOPSIS

#include <stdio.h>

char *ctermid(char *buf);

char *ctermid_r(char *buf);

DESCRIPTION

The ctermid() function generates a string, that, when used as a pathname, refersto the current controlling terminal of the calling process.

If buf is the NULL pointer, a pointer to a static area is returned. Otherwise, thepathname is copied into the memory referenced by buf. The argument buf is assumedto be at least L ctermid (as defined in the include file <stdio.h>) bytes long.

The ctermid r() function provides the same functionality as ctermid() exceptthat if buf is a NULL pointer, NULL is returned.

The current implementation simply returns ‘/dev/tty’ when running underOpenEdition. In any other environment, it returns the empty string.

RETURN VALUES

Upon successful completion, a non-NULL pointer is returned. Otherwise, a NULLpointer is returned and the global variable errno is set to indicate the error.

ERRORS

The current implementation detects no error conditions.

Systems/C C Library 313

Page 332: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

SEE ALSO

ttyname(3)

STANDARDS

The ctermid() function conforms to IEEE Std 1003.1-1988 (“POSIX.1”).

ISSUES

By default the ctermid() function writes all information to an internal static object.Subsequent calls to ctermid() will modify the same object.

314 Systems/C C Library

Page 333: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

DIRECTORY(3)

NAME

opendir, readdir, rewinddir, closedir, dirfd - directory operations

SYNOPSIS

#include <sys/types.h>#include <dirent.h>

DIR *opendir(const char *filename);

struct dirent *readdir(DIR *dirp);

voidrewinddir(DIR *dirp);

intclosedir(DIR *dirp);

intdirfd(DIR *dirp);

DESCRIPTION

The opendir() function opens the //HFS:-style directory named by filename, as-sociates a directory stream with it and returns a pointer to be used to identify thedirectory stream in subsequent operations. The pointer NULL is returned if file-name cannot be accessed, or if it cannot malloc(3) enough memory to hold thedirectory stream and related information.

The readdir() function returns a pointer to the next directory entry. It returnsNULL upon reaching the end of the directory.

The rewinddir() function resets the position of the named directory stream to thebeginning of the directory.

The closedir() function closes the named directory stream and frees the structureassociated with the dirp pointer, returning 0 on success. On failure, -1 is returnedand the global variable errno is set to indicate the error.

The dirfd() function returns the integer file descriptor associated with the nameddirectory stream, see open(2).

Systems/C C Library 315

Page 334: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

Sample code which searches a directory for entry “name” is:

len = strlen(name);dirp = opendir(".");while ((dp = readdir(dirp)) != NULL)

if (dp->d_namlen == len && !strcmp(dp->d_name, name)) {(void)closedir(dirp);return FOUND;

}(void)closedir(dirp);return NOT_FOUND;

SEE ALSO

close(2), lseek(2), open(2), read(2)

316 Systems/C C Library

Page 335: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

DLOPEN(3)

NAME

dlopen, dlsym, dlfunc, dlerror, dlclose – programmatic interface to dynamic linking

SYNOPSIS

#include <dlfcn.h>

void *dlopen(const char *path, int mode);

void *dlsym(void * restrict handle, const char * restrict symbol);

dlfunc_tdlfunc(void * restrict handle, const char * restrict symbol);

const char *dlerror(void);

intdlclose(void *handle);

DESCRIPTION

These functions provide a simple programmatic interface to the services of theDignus shared libraries. Operations are provided to add new shared objects toa program’s address space, to obtain the address bindings of symbols defined bysuch objects, and to remove such objects when their use is no longer required.

Contact Dignus for information regarding how to construct shared objects using thethe PLINK utility.

The dlopen() function provides access to the shared object in path, returning adescriptor that can be used for later references to the object in calls to dlsym()and dlclose(). If path was not in the address space prior to the call to dlopen(), itis placed in the address space. If path has already been placed in the address spacein a previous call to dlopen(), it is not added a second time, although a referencecount of dlopen() operations on path is maintained. A null pointer supplied forpath is interpreted as a reference to the main executable of the process. The modeargument controls the way in which external function references from the loadedobject are bound to their referents. It must contain one of the following values,possibly ORed with additional flags which will be described subsequently:

Systems/C C Library 317

Page 336: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

RTLD NOW All external function references are bound imme-diately by dlopen().

RTLD NOW is used to ensure any undefined symbols are discovered during the call todlopen().

One of the following flags may be ORed into the mode argument:

RTLD GLOBAL Symbols from this shared object and its directedacyclic graph (DAG) of needed objects will beavailable for resolving undefined references fromall other shared objects.

RTLD LOCAL Symbols in this shared object and its DAG ofneeded objects will be available for resolving un-defined references only from other objects in thesame DAG. This is the default, but it may bespecified explicitly with this flag.

If dlopen() fails, it returns a null pointer, and sets an error condition which maybe interrogated with dlerror().

The dlsym() function returns the address binding of the symbol described in thenull-terminated character string symbol, as it occurs in the shared object identifiedby handle. The symbols exported by objects added to the address space by dlopen()can be accessed only through calls to dlsym(). Such symbols do not supersede anydefinition of those sym bols already present in the address space when the object isloaded, nor are they available to satisfy normal dynamic linking references.

If dlsym() is called with the special handle RTLD DEFAULT, the search for the symbolfollows the algorithm used for resolving undefined symbols when objects are loaded.The objects searched are as follows, in the given order:

1. The referencing object itself (or the object from which the call todlsym() is made.)

2. All objects loaded at program start-up.

3. All objects loaded via dlopen() with the RTLD GLOBAL flag set in themode argument.

4. All objects loaded via dlopen() which are in needed-object DAGsthat also contain the referencing object.

If dlsym() is called with the special handle RTLD NEXT, then the search for thesymbol is limited to the shared objects which were loaded after the one issuingthe call to dlsym(). Thus, if the function is called from the main program, all

318 Systems/C C Library

Page 337: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

the shared libraries are searched. If it is called from a shared library, all subsequentshared libraries are searched. RTLD NEXT is useful for implementing wrappers aroundlibrary functions. For example, a wrapper function getpid() could access the “real”getpid() with dlsym(RTLD NEXT, "getpid"). (Actually, the dlfunc() interface,below, should be used, since getpid() is a function and not a data object.)

If dlsym() is called with the special handle RTLD SELF, then the search for thesymbol is limited to the shared object issuing the call to dlsym() and those sharedobjects which were loaded after it.

The dlsym() function returns a null pointer if the symbol cannot be found, andsets an error condition which may be queried with dlerror().

The dlerror() function returns a null-terminated character string describing thelast error that occurred during a call to dlopen(), dladdr(), dlinfo(), dlsym(),dlfunc(), or dlclose(). If no such error has occurred, dlerror() returns a nullpointer. At each call to dlerror(), the error indication is reset. Thus in the caseof two calls to dlerror(), where the second call follows the first immediately, thesecond call will always return a null pointer.

The dlclose() function deletes a reference to the shared object refer enced by handle.If the reference count drops to 0, the object is removed from the address space,and handle is rendered invalid. If dlclose() is successful, it returns a value of 0.Otherwise it returns -1, and sets an error condition that can be interrogated withdlerror().

NOTES

Shared objects require special compilation and linking procedures. Contact Dignusfor more information.

ERRORS

The dlopen(), dlsym(), and dlfunc() functions return a null pointer in the eventof errors. The dlclose() function returns 0 on success, or -1 if an error occurred.Whenever an error has been detected, a message detailing it can be retrieved via acall to dlerror().

SEE ALSO

PLINK in the Systems/C utilities manual.

Systems/C C Library 319

Page 338: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

ERR(3)

NAME

err, verr, errc, verrc, errx, verrx, warn, vwarn, warnc, vwarnc, warnx, vwarnx,err set exit, err set file - formatted error messages

SYNOPSIS

#include <err.h>

voiderr(int eval, const char *fmt, ...);

voiderr_set_exit(void (*exitf)(int));

voiderr_set_file(void *vfp);

voiderrc(int eval, int code, const char *fmt, ...);

voiderrx(int eval, const char *fmt, ...);

voidwarn(const char *fmt, ...);

voidwarnc(int code, const char *fmt, ...);

voidwarnx(const char *fmt, ...);

#include <stdarg.h>

voidverr(int eval, const char *fmt, va_list args);

voidverrc(int eval, int code, const char *fmt, va_list args);

voidverrx(int eval, const char *fmt, va_list args);

320 Systems/C C Library

Page 339: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

voidvwarn(const char *fmt, va_list args);

voidvwarnc(int code, const char *fmt, va_list args);

voidvwarnx(const char *fmt, va_list args);

DESCRIPTION

The err() and warn() family of functions display a formatted error message on thestandard error output, or on another file specified using the err set file() function.In all cases, the last component of the program name, a colon character, and aspace are output. If the fmt argument is not NULL, the printf(3) -like formattederror message is output. The output is terminated by a newline character.

The err(), errc(), verr(), verrc(), warn(), warnc(), vwarn(), and vwarnc()functions append an error message obtained from strerror(3) based on a code or theglobal variable errno, preceded by another colon and space unless the fmt argumentis NULL.

In the case of the errc(), verrc(), warnc(), and vwarnc() functions, the codeargument is used to look up the error message.

The err(), verr(), warn(), and vwarn() functions use the global variable errnoto look up the error message.

The errx() and warnx() functions do not append an error message.

The err(), verr(), errc(), verrc(), errx(), and verrx() functions do not return,but exit with the value of the argument eval. It is recommended that the standardvalues defined in sysexits(3) be used for the value of eval. The err set exit()function can be used to specify a function which is called before exit(3) to performany necessary cleanup; passing a null function pointer for exitf resets the hook todo nothing. The err set file() function sets the output stream used by the otherfunctions. Its vfp argument must be either a pointer to an open stream (possiblyalready converted to void *) or a null pointer (in which case the output stream isset to standard error).

EXAMPLES

Display the current errno information string and exit:

Systems/C C Library 321

Page 340: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

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);

Warn of an error:

if ((fd = open(raw_device, O_RDONLY, 0)) == -1)warnx("%s: %s: trying the block device",

raw_device, strerror(errno));if ((fd = open(block_device, O_RDONLY, 0)) == -1)

err(1, "%s", block_device);

Warn of an error without using the global variable errno:

error = my_function(); /* returns a value from <errno.h> */if (error != 0)

warnc(error, "my_function");

SEE ALSO

exit(3), fmtmsg(3), printf(3), strerror(3), sysexits(3)

322 Systems/C C Library

Page 341: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

EXEC(3)

NAME

execl, execlp, execle, execv, execvp - execute a file

SYNOPSIS

#include <unistd.h>

extern char **environ;

intexecl(const char *path, const char *arg, ...);

intexeclp(const char *file, const char *arg, ...);

intexecle(const char *path, const char *arg, ...);

intexecv(const char *path, char *const argv[]);

intexecvp(const char *file, char *const argv[]);

DESCRIPTION

The exec family of functions replaces the current process image with a new processimage. The functions described in this manual page are front-ends for the functionexecve(2). (See the manual page for execve(2) for detailed information about thereplacement of the current process.)

The initial argument for these functions is the //HFS:-style pathname of a file whichis to be executed.

The const char *arg and subsequent ellipses in the execl(), execlp(), and exe-cle() functions can be thought of as arg0, arg1, ..., argn. Together they describea list of one or more pointers to nul-terminated strings that represent the argumentlist available to the executed program. The first argument, by convention, shouldpoint to the file name associated with the file being executed. The list of argumentsmust be terminated by a NULL pointer.

Systems/C C Library 323

Page 342: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

The execv(), and execvp() functions provide an array of pointers to nul-terminatedstrings that represent the argument list available to the new program. The firstargument, by convention, should point to the file name associated with the filebeing executed. The array of pointers must be terminated by a NULL pointer.

The execle() function also specify the environment of the executed process byfollowing the NULL pointer that terminates the list of arguments in the argumentlist or the pointer to the argv array with an additional argument. This additionalargument is an array of pointers to nul-terminated strings and must be terminatedby a NULL pointer. The other functions take the environment for the new processimage from the external variable environ in the current process.

Some of these functions have special semantics.

The functions execlp() and execvp() will duplicate the actions of the shell insearching for an executable file if the specified file name does not contain a slash“/” character. The search path is the path specified in the environment by “PATH”variable. If this variable isn’t specified, the default path is set according to thePATH DEFPATH definition in <paths.h>, which is set to “/usr/bin:/bin”. In addi-tion, certain errors are treated specially.

If an error is ambiguous (for simplicity, we shall consider all errors except ENOEXEC asbeing ambiguous here, although only the critical error EACCES is really ambiguous),then these functions will act as if they stat the file to determine whether the fileexists and has suitable execute permissions. If it does, they will return immediatelywith the global variable errno restored to the value set by execve(). Otherwise, thesearch will be continued. If the search completes without performing a successfulexecve() or terminating due to an error, these functions will return with the globalvariable errno set to EACCES or ENOENT according to whether at least one file withsuitable execute permissions was found.

If the header of a file isn’t recognized (the attempted execve() returned ENOEXEC),these functions will execute the shell with the path of the file as its first argument.(If this attempt fails, no further searching is done.)

RETURN VALUES

If any of the exec() functions returns, an error will have occurred. The return valueis -1, and the global variable errno will be set to indicate the error.

ERRORS

The execl(), execle(), execlp() and execvp() functions may fail and set errnofor any of the errors specified for the library functions execve(2) and malloc(3).

The execv() function may fail and set errno for any of the errors specified for thelibrary function execve(2).

324 Systems/C C Library

Page 343: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

SEE ALSO

execve(2)

STANDARDS

The execl(), execv(), execle(), execlp() and execvp() functions conform toIEEE Std 1003.1-1988 (“POSIX.1”).

Systems/C C Library 325

Page 344: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

FMTCHECK(3)

NAME

fmtcheck - sanitizes user-supplied printf(3)-style format string

SYNOPSIS

#include <stdio.h>

const char *fmtcheck(const char *fmt_suspect, const char *fmt_default);

DESCRIPTION

The fmtcheck() scans fmt suspect and fmt default to determine if fmt suspect willconsume the same argument types as fmt default and to ensure that fmt suspect isa valid format string.

The printf(3) family of functions cannot verify the types of arguments that theyare passed at run-time. In some cases, it is useful or necessary to use a user-supplied format string with no guarantee that the format string matches the specifiedarguments.

The fmtcheck() function was designed to be used in these cases, as in:

printf(fmtcheck(user_format, standard_format), arg1, arg2);

In the check, field widths, fillers, precisions, etc. are ignored (unless the field widthor precision is an asterisk ‘*’ instead of a digit string). Also, any text other thanthe format specifiers is completely ignored.

RETURN VALUES

If fmt suspect is a valid format and consumes the same argument types as fmt default,then the fmtcheck() will return fmt suspect. Otherwise, it will return fmt default.

SEE ALSO

printf(3)

326 Systems/C C Library

Page 345: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

ISSUES

The fmtcheck() function does not understand all of the conversions that printf(3)does.

Systems/C C Library 327

Page 346: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

FMTMSG(3)

NAME

fmtmsg - display a detailed diagnostic message

SYNOPSIS

#include <fmtmsg.h>

intfmtmsg(long classification, const char *label, int severity,

const char *text, const char *action, const char *tag);

DESCRIPTION

The fmtmsg() function displays a detailed diagnostic message, based on the sup-plied arguments, to stderr and/or the system console.

The classification argument is the bitwise inclusive OR of zero or one of the manifestconstants from each of the classification groups below. The Output classificationgroup is an exception since both MM PRINT and MM CONSOLE may be specified.

Output

MM PRINT Output should take place on stderr.

MM CONSOLE Output should take place on the system console.

Source of Condition (Major)

MM HARD The source of the condition is hardware related.

MM SOFT The source of the condition is software related.

MM FIRM The source of the condition is firmware related.

Source of Condition (Minor)

MM APPL The condition was detected at the application level.

MM UTIL The condition was detected at the utility level.

MM OPSYS The condition was detected at the operating system level.

328 Systems/C C Library

Page 347: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

Status

MM RECOVER The application can recover from the condition.

MM NRECOV The application is unable to recover from the condition.

Alternatively, the MM NULLMC manifest constant may be used to specify no classifi-cation.

The label argument indicates the source of the message. It is made up of two fieldsseparated by a colon (‘:’). The first field can be up to 10 bytes, and the second fieldcan be up to 14 bytes. The MM NULLLBL manifest constant may be used to specifyno label.

The severity argument identifies the importance of the condition. One of the fol-lowing manifest constants should be used for this argument.

MM HALT The application has confronted a serious fault and is halting.

MM ERROR The application has detected a fault.

MM WARNING The application has detected an unusual condition, that could beindicative of a problem.

MM INFO The application is providing information about a non-error condi-tion.

MM NOSEV No severity level supplied.

The text argument details the error condition that caused the message. There is nolimit on the size of this character string. The MM NULLTXT manifest constant maybe used to specify no text.

The action argument details how the error-recovery process should begin. Uponoutput, fmtmsg() will prefix “TO FIX:” to the beginning of the action argument.The MM NULLACT manifest constant may be used to specify no action.

The tag argument should reference online documentation for the message. Thisusually includes the label and a unique identifying number. An example tag is“BSD:ls:168”. The MM NULLTAG manifest constant may be used to specify no tag.

RETURN VALUES

The fmtmsg() function returns MM OK upon success, MM NOMSG to indicate output tostderr failed, MM NOCON to indicate output to the system console failed, or MM NOTOKto indicate output to stderr and the system console failed.

Systems/C C Library 329

Page 348: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

ENVIRONMENT

The MSGVERB (message verbosity) environment variable specifies which argumentsto fmtmsg() will be output to stderr, and in which order. MSGVERB should bea colon (‘:’) separated list of identifiers. Valid identifiers include: label, severity,text, action, and tag. If invalid identifiers are specified or incorrectly separated,the default message verbosity and ordering will be used. The default ordering isequivalent to a MSGVERB with a value of “label:severity:text:action:tag”.

EXAMPLES

The code:

fmtmsg(MM_UTIL | MM_PRINT, "BSD:ls", MM_ERROR,"illegal option -- z", "refer to manual", "BSD:ls:001");

will output:

BSD:ls: ERROR: illegal option -- zTO FIX: refer to manual BSD:ls:001

to stderr.

The same code, with MSGVERB set to “text:severity:action:tag”, produces:

illegal option -- z: ERRORTO FIX: refer to manual BSD:ls:001

STANDARDS

The fmtmsg() function conforms to IEEE Std 1003.1-2001 (“POSIX.1”).

ISSUES

Specifying MM NULLMC for the classification argument makes little sense, since with-out an output specified, fmtmsg() is unable to do anything useful.

In order for fmtmsg() to output to the system console, the effective user musthave appropriate permission to write to /dev/console. This means that on mostsystems fmtmsg() will return MM NOCON unless the effective user is root, or has otherappropriate permissions.

330 Systems/C C Library

Page 349: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

FNMATCH(3)

NAME

fnmatch - match filename or pathname

SYNOPSIS

#include <fnmatch.h>

intfnmatch(const char *pattern, const char *string, int flags);

DESCRIPTION

The fnmatch() function matches patterns according to the rules used by the shell.It checks the string specified by the string argument to see if it matches the patternspecified by the pattern argument.

The flags argument modifies the interpretation of pattern and string. The value offlags is the bitwise inclusive OR of any of the following constants, which are definedin the include file <fnmatch.h>.

FNM NOESCAPE Normally, every occurrence of a backslash (‘́) followed by a characterin pattern is replaced by that character. This is done to negate anyspecial meaning for the character. If the FNM NOESCAPE flag is set,a backslash character is treated as an ordinary character.

FNM PATHNAME Slash characters in string must be explicitly matched by slashes inpattern. If this flag is not set, then slashes are treated as regularcharacters.

FNM PERIOD Leading periods in string must be explicitly matched by periodsin pattern. If this flag is not set, then leading periods are treatedas regular characters. The definition of “leading” is related to thespecification of FNM PATHNAME. A period is always “leading” if it isthe first character in string. Additionally, if FNM PATHNAME is set, aperiod is leading if it immediately follows a slash.

FNM LEADING DIR Ignore “/*” rest after successful pattern matching.

FNM CASEFOLD Ignore case distinctions in both the pattern and the string.

Systems/C C Library 331

Page 350: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

RETURN VALUES

The fnmatch() function returns zero if string matches the pattern specified bypattern, otherwise, it returns the value FNM NOMATCH.

SEE ALSO

glob(3), regex(3)

STANDARDS

The fnmatch() function conforms to IEEE Std 1003.2 (“POSIX.2”).

ISSUES

The pattern ‘*’ matches the empty string, even if FNM PATHNAME is specified.

332 Systems/C C Library

Page 351: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

FTOK(3)

NAME

ftok - create IPC identifier from //HFS:-style path name

SYNOPSIS

#include <sys/types.h>#include <sys/ipc.h>

key_tftok(const char *path, int id);

DESCRIPTION

The ftok() function attempts to create a unique key suitable for use with themsgget(3), semget(2) and shmget(2) functions given the //HFS:-style path of anexisting file and a user-selectable id.

The specified path must specify an existing HFS file that is accessible to the callingprocess or the call will fail. Also, note that links to files will return the same key,given the same id.

RETURN VALUES

The ftok() function will return -1 if path does not exist, is not an HFS file, or if itcannot be accessed by the calling process.

ISSUES

The returned key is computed based on the device minor number and inode of thespecified path in combination with the lower 8 bits of the given id. Thus it is quitepossible for the routine to return duplicate keys.

Systems/C C Library 333

Page 352: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

GETCWD(3)

NAME

getcwd, getwd – get working directory pathname

SYNOPSIS

#include <unistd.h>

char *getcwd(char *buf, size_t size);

char *getwd(char *buf);

DESCRIPTION

The getcwd() function copies the absolute pathname of the current working di-rectory into the memory referenced by buf and returns a pointer to buf. The sizeargument is the size, in bytes, of the array referenced by buf.

If buf is NULL, space is allocated as necessary to store the pathname. This spacemay later be free(3)’d.

The function getwd() is a compatibility routine which calls getcwd() with its bufargument and a size of MAXPATHLEN (as defined in the include file <sys/param.h>).Obviously, buf should be at least MAXPATHLEN bytes in length.

RETURN VALUES

Upon successful completion, a pointer to the pathname is returned. Otherwise aNULL pointer is returned and the global variable errno is set to indicate the error.In addition, getwd() copies the error message associated with errno into the memoryreferenced by buf.

ERRORS

The getcwd() function will fail if:

[EACCES] Read or search permission was denied for a component of the path-name.

334 Systems/C C Library

Page 353: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

[EINVAL] The size argument is zero.

[ENOENT] A component of the pathname no longer exists.

[ENOMEM] Insufficient memory is available.

[ERANGE] The size argument is greater than zero but smaller than the lengthof the pathname plus 1.

Systems/C C Library 335

Page 354: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

GETCONTEXT(3)

NAME

getcontext, setcontext – get and set user thread context

SYNOPSIS

#include <ucontext.h>

intgetcontext(ucontext_t *ucp);

intsetcontext(const ucontext_t *ucp);

DESCRIPTION

The getcontext() function saves the current thread’s execution context in thestructure pointed to by ucp. This saved context may then later be restored bycalling setcontext().

The setcontext() function makes a previously saved thread context the currentthread context, i.e., the current context is lost and setcontext() does not return.Instead, execution continues in the context specified by ucp, which must have beenpreviously initialized by a call to getcontext(), makecontext(3), or by being passedas an argument to a signal handler (see sigaction(2)).

If ucp was initialized by getcontext(), then execution continues as if the originalgetcontext() call had just returned (again).

If ucp was initialized by makecontext(3), execution continues with the invoca-tion of the function specified to makecontext(3). When that function returns,ucp->uc link determines what happens next: if ucp->uc link is NULL, the pro-cess exits; otherwise, setcontext(ucp->uc link) is implicitly invoked.

If ucp was initialized by the invocation of a signal handler, execution continues atthe point the thread was interrupted by the signal.

RETURN VALUES

If successful, getcontext() returns zero and setcontext() does not return; other-wise -1 is returned.

336 Systems/C C Library

Page 355: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

ERRORS

No errors are defined for getcontext() or setcontext().

IMPLEMENTATION NOTES

The getcontext() and setcontext() functions take advantage of the EXTRACTPSW (EPSW) and RESUME PROGRAM (RP) instructions. These are available in allz/Architecture and most ESA/390 environments. These functions will not oper-ate in environments that don’t provide those instructions.

SEE ALSO

sigaction(2), sigaltstack(2), makecontext(3), ucontext(3)

Systems/C C Library 337

Page 356: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

GETGRENT(3)

getgrent, getgrnam, getgrgid, setgroupent, setgrent, endgrent - group database op-erations

SYNOPSIS

#include <sys/types.h>#include <grp.h>

struct group *getgrent(void);

struct group *getgrnam(const char *name);

struct group *getgrgid(gid_t gid);

intsetgroupent(int stayopen);

intsetgrent(void);

voidendgrent(void);

DESCRIPTION

These functions operate on the group database. Each entry of the database ismapped to the structure group found in the include file <grp.h>:

struct group {char *gr_name; /* group name */char *gr_passwd; /* group password */int gr_gid; /* group id */char **gr_mem; /* group members */

};

The functions getgrnam() and getgrgid() search the group database for the givengroup name pointed to by name or the group id specifeid by gid, respectively, re-turning the first one encountered. Identical group names or group gids may resultin undefined behavior.

338 Systems/C C Library

Page 357: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

The getgrent() function sequentially reads the group database and is intended forprograms that wish to step through the complete list of groups.

The setgroupent() function opens the database, or rewinds it if it is already open.It is provided for compatibility with popular UNIX systems.

The setgrent() function resets the data base to the beginning so that subsequentcalls to getgrent() start from the beginning.

The endgrent() function resets the data base to the beginning.

RETURN VALUES

The functions getgrent(), getgrnam(), and getgrgid(), return a pointer to thegroup entry if successful; if end-of-file is reached or an error occurs a NULL pointeris returned. The functions setgroupent() and setgrent() return the value 1 ifsuccessful, otherwise the value 0 is returned. The function endgrent() has noreturn value.

SEE ALSO

getpwent(3)

NOTES

The functions getgrent(), getgrnam() and getgrgid() leave their results in aninternal static object and return a pointer to that object. Subsequent calls to thesame function will modify the same object.

Systems/C C Library 339

Page 358: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

GETPROGNAME(3)

NAME

getprogname, setprogname - get or set the program name

SYNOPSIS

#include <stdlib.h>

const char *getprogname(void);

voidsetprogname(const char *progname);

DESCRIPTION

The getprogname() and setprogname() functions manipulate the name of thecurrent program. They are used by error-reporting routines to produce consistentoutput.

The getprogname() function returns the name of the program. If the name hasnot been set yet, it will return NULL.

The setprogname() function sets the name of the program to be the last compo-nent of the progname argument. Since a pointer to the given string is kept as theprogram name, it should not be modified for the rest of the program’s lifetime.

At program start-up, the Systems/C runtime attempts to determine, from the oper-ating system, the name of the program. If the name can be determined, the name ofthe program is set by the start-up code that is run before main(); thus, running set-progname() is not always necessary. Programs that desire maximum portabilityshould still call it. On some operating systems, these functions may be implementedin a portability library. Calling setprogname() allows the aforementioned systemsto learn the program name without modifications to the start-up code.

340 Systems/C C Library

Page 359: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

GETPWENT(3)

NAME

getpwent, getpwnam, getpwuid, setpassent, setpwent, endpwent - password databaseoperations

SYNOPSIS

#include <sys/types.h>#include <pwd.h>

struct passwd *getpwent(void);

struct passwd *getpwnam(const char *login);

struct passwd *getpwuid(uid_t uid);

intsetpassent(int stayopen);

voidsetpwent(void);

voidendpwent(void);

DESCRIPTION

These functions operate on the OpenEdition password database. Each entry inthe password database is mapped to the structure passwd found in the include file<pwd.h>:

struct passwd {char *pw_name; /* user name */char *pw_passwd; /* encrypted password */uid_t pw_uid; /* user uid */gid_t pw_gid; /* user gid */time_t pw_change; /* password change time */char *pw_class; /* user access class */

Systems/C C Library 341

Page 360: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

char *pw_gecos; /* Honeywell login info */char *pw_dir; /* home directory */char *pw_shell; /* default shell */time_t pw_expire; /* account expiration */int pw_fields; /* internal: fields filled in */

};

The functions getpwnam() and getpwuid() search the password database for thegiven login name or user uid, respectively, always returning the first one encountered.

The getpwent() function sequentially reads the password database and is intendedfor programs that wish to process the complete list of users.

The setpassent() function is provided for compatibility with popular UNIX plat-forms. It causes getpwent() to “rewind” to the beginning of the database.

The setpwent() function resets the database so that the next call to getpwent()starts over at the beginning.

The endpwent() function is used to indicate the end of database access. It alsoresets the database so that the next call to getpwent() starts over at the beginning.

Because of how passwords are managed on OS/390 and z/OS, the password field ofthe returned structure will always point to the string "*".

RETURN VALUES

The functions getpwent(), getpwnam(), and getpwuid(), return a valid pointerto a passwd structure on success and a NULL pointer if the end of the database isreached or an error occurs. The setpassent() function returns 0 on failure and 1on success. The endpwent() and setpwent() functions have no return value.

SEE ALSO

getlogin(2), getgrent(3)

ISSUES

The functions getpwent(), getpwnam(), and getpwuid(), leave their results inan internal static object and return a pointer to that object. Subsequent calls tothe same function will modify the same object.

342 Systems/C C Library

Page 361: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

GLOB(3)

NAME

glob, globfree - generate //HFS: pathnames matching a pattern

SYNOPSIS

#include <glob.h>

intglob(const char *pattern, int flags, int (*errfunc)(const char *, int),

glob_t *pglob);

voidglobfree(glob_t *pglob);

DESCRIPTION

The glob() function is a pathname generator that implements the rules for file namepattern matching used by the shell.

The include file <glob.h> defines the structure type glob t, which contains at leastthe following fields:

typedef struct {int gl_pathc; /* count of total paths so far */int gl_matchc; /* count of paths matching pattern */int gl_offs; /* reserved at beginning of gl_pathv */int gl_flags; /* returned flags */char **gl_pathv; /* list of paths matching pattern */

} glob_t;

The argument pattern is a pointer to an //HFS:-style pathname pattern to be ex-panded. The glob() argument matches all accessible pathnames against the patternand creates a list of the pathnames that match. In order to have access to a path-name, glob() requires search permission on every component of a path except thelast and read permission on each directory of any filename component of patternthat contains any of the special characters ‘*’, ‘?’ or ‘[’.

The glob() argument stores the number of matched pathnames into the gl pathcfield, and a pointer to a list of pointers to pathnames into the gl pathv field. Thefirst pointer after the last pathname is NULL. If the pattern does not match anypathnames, the returned number of matched paths is set to zero.

Systems/C C Library 343

Page 362: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

It is the caller’s responsibility to create the structure pointed to by pglob. Theglob() function allocates other space as needed, including the memory pointed toby gl pathv.

The argument flags s used to modify the behavior of glob(). The value of flags isthe bitwise inclusive OR of any of the following values defined in <glob.h>:

GLOB APPEND Append pathnames generated to the ones from a previous call (orcalls) to glob(). The value of gl pathc will be the total matchesfound by this call and the previous call(s). The pathnames are ap-pended to, not merged with the pathnames returned by the previouscall(s). Between calls, the caller must not change the setting of theGLOB DOOFFS flag, nor change the value of gl offs when GLOB DOOFFSis set, nor (obviously) call globfree() for pglob.

GLOB DOOFFS Make use of the gl offs field. If this flag is set, gl offs is usedto specify how many NULL pointers to prepend to the beginning ofthe gl pathv field. In other words, gl pathv will point to gl offsNULL pointers, followed by gl pathc pathname pointers, followed bya NULL pointer.

GLOB ERR Causes glob() to return when it encounters a directory that it can-not open or read. Ordinarily, glob() continues to find matches.

GLOB MARK Each pathname that is a directory that matches pattern has a slashappended.

GLOB NOCHECK If pattern does not match any pathname, then glob() returns a listconsisting of only pattern, with the number of total pathnames setto 1, and the number of matched pathnames set to 0. The effect ofbackslash escaping is present in the pattern returned.

GLOB NOESCAPE By default, a backslash (‘́) character is used to escape the followingcharacter in the pattern, avoiding any special interpretation of thecharacter. If GLOB NOESCAPE is set, backslash escaping is disabled.

GLOB NOSORT By default, the pathnames are sorted in ascending order; this flagprevents that sorting (speeding up glob()).

The following values may also be included in flags, however, they are non-standardextensions to IEEE Std 103.2 (“POSIX.2”).

GLOB ALTDIRFUNC The following additional fields in the pglob structure have beeninitialized with alternate functions for glob() to use to open, read,and close directories and to get stat information on names found inthose directories.

344 Systems/C C Library

Page 363: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

void *(*gl_opendir)(const char * name);struct dirent *(*gl_readdir)(void *);void (*gl_closedir)(void *);int (*gl_lstat)(const char *name, struct stat *st);int (*gl_stat)(const char *name, struct stat *st);

GLOB BRACE Pre-process the pattern string to expand ‘pat,pat,...’ strings likecsh(1). The pattern ‘’ is left unexpanded for historical reasons (andcsh(1) does the same thing to ease typing of find(1) patterns).

GLOB MAGCHAR Set by the glob() function if the pattern included globbing char-acters. See the description of the usage of the gl matchc structuremember for more details.

GLOB NOMAGIC Is the same as GLOB NOCHECK but it only appends the pattern if itdoes not contain any of the special characters “*”, “?” or “[”.GLOB NOMAGIC is provided to simplify implementing the historiccsh(1) globbing behavior and should probably not be used anywhereelse.

GLOB TILDE Expand patterns that start with ‘ ’ to user name home directories.

GLOB LIMIT Limit the total number of returned pathnames to the value pro-vided in gl matchc (default ARG MAX). This option should be set forprograms that can be coerced into a denial of service attack viapatterns that expand to a very large number of matches, such as along string of ‘*/../*/..’.

If, during the search, a directory is encountered that cannot be opened or readand errfunc is non-NULL, glob() calls (*errfunc)(path, errno). This may beunintuitive: a pattern like ‘*/Makefile’ will try to stat(2) ‘foo/Makefile’ even if ‘foo’is not a directory, resulting in a call to errfunc. The error routine can suppressthis action by testing for ENOENT and ENOTDIR; however, the GLOB ERR flag will stillcause an immediate return when this happens.

If errfunc returns non-zero, glob() stops the scan and returns GLOB ABORTED aftersetting gl pathc and gl pathv to reflect any paths already matched. This also happensif an error is encountered and GLOB ERR is set in flags, regardless of the return valueof errfunc, if called. If GLOB ERR is not set and either errfunc is NULL or errfuncreturns zero, the error is ignored.

The globfree() function frees any space associated with pglob from a previous call(s)to glob().

RETURN VALUES

On successful completion, glob() returns zero. In addition the fields of pglob containthe values described below:

Systems/C C Library 345

Page 364: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

gl patch contains the total number of matched pathnames so far. Thisincludes other matches from previous invocations of glob() ifGLOB APPEND was specified.

gl matchc contains the number of matched pathnames in the current invoca-tion of glob().

gl flags contains a copy of the flags argument with the bit GLOB MAGCHAR setif pattern contained any of the special characters “*”, “?” or “[”,cleared if not.

gl pathv contains a pointer to a NULL-terminated list of matched pathnames.However, if gl pathc is zero, the contents of gl pathv are unde-fined.

If glob() terminates due to an error, it sets the global variable errno and returns oneof the following non-zero constants, which are defined in the include file <glob.h>:

GLOB NOSPACE An attempt to allocate memory failed, or if errno was 0 GLOB LIMITwas specified in the flags and pglob->gl matchc or more patternswere matched.

GLOB ABORTED The scan was stopped because an error was encountered and eitherGLOB ERR was set or (*errfunc)() returned non-zero.

GLOB NOMATCH The pattern did not match a pathname and GLOB NOCHECK was notset.

The arguments pglob->gl pathc and pglob->gl pathv are still set as specifiedabove.

EXAMPLES

A rough equivalent of ‘ls -l *.c *.h’ can be obtained with the following code:

glob_t g;

g.gl_offs = 2;glob("*.c", GLOB_DOOFFS, NULL, &g);glob("*.h", GLOB_DOOFFS | GLOB_APPEND, NULL, &g);g.gl_pathv[0] = "ls";g.gl_pathv[1] = "-l";execvp("ls", g.gl_pathv);

SEE ALSO

fnname(3), regexp(3)

346 Systems/C C Library

Page 365: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

STANDARDS

The glob() function is expected to be IEEE Std 1003.2 (“POSIX.2”) compati-ble with the exception that the flags GLOB ALTDIRFUNC, GLOB BRACE, GLOB LIMIT,GLOB MAGCHAR, GLOB NOMAGIC, and GLOB TILDE, and the fields gl matchc andgl flags should not be used by applications striving for strict POSIX conformance.

ISSUES

Patterns longer than MAXPATHLEN may cause unchecked errors.

The glob() argument may fail and set errno for any of the errors specified for thelibrary routines stat(2), closedir(3), opendir(3), readdir(3), malloc(3), and free(3).

Systems/C C Library 347

Page 366: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

HCREATE(3)

NAME

hcreate, hdestroy, hsearch – manage hash search table

SYNOPSIS

#include <search.h>

inthcreate(size_t nel);

voidhdestroy(void);

ENTRY *hsearch(ENTRY item, ACTION action);

DESCRIPTION

The hcreate(), hdestroy(), and hsearch() functions manage hash search tables.

The hcreate() function allocates sufficient space for the table, and the applicationshould ensure it is called before hsearch() is used. The nel argument is an estimateof the maximum number of entries that the table should contain. This number maybe adjusted upward by the algorithm in order to obtain certain mathematicallyfavorable circumstances.

The hdestroy() function disposes of the search table, and may be followed byanother call to hcreate(). After the call to hdestroy(), the data can no longer beconsidered accessible. The hdestroy() function calls free(3) for each comparisonkey in the search table but not the data item associated with the key.

The hsearch() function is a hash-table search routine. It returns a pointer intoa hash table indicating the location at which an entry can be found. The itemargument is a structure of type ENTRY (defined in the <search.h> header) containingtwo pointers: item.key points to the comparison key (a char *), and item.data(a void *) points to any other data to be associated with that key. The comparisonfunction used by hsearch() is strcmp(3). The action argument is a member ofan enumeration type ACTION indicating the disposition of the entry if it cannot befound in the table. ENTER indicates that the item should be inserted in the table atan appropriate point. FIND indicates that no entry should be made. Unsuccessfulresolution is indicated by the return of a NULL pointer.

348 Systems/C C Library

Page 367: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

The comparison key (passed to hsearch() as item.key) must be allocated usingmalloc(3) if action is ENTER and hdestroy() is called.

RETURN VALUES

The hcreate() function returns 0 if it cannot allocate sufficient space for the table;otherwise, it returns non-zero.

The hdestroy() function does not return a value.

The hsearch() function returns a NULL pointer if either the action is FIND and theitem could not be found or the action is ENTER and the table is full.

ERRORS

The hcreate() and hsearch() functions may fail if:

[ENOMEM] Insufficient storage space is available.

EXAMPLES

The following example reads in strings followed by two numbers and stores them ina hash table, discarding duplicates. It then reads in strings and finds the matchingentry in the hash table and prints it out.

#include <stdio.h>#include <search.h>#include <string.h>#include <stdlib.h>

struct info { /* This is the info stored in the table */int age, room; /* other than the key. */

};

#define NUM_EMPL 5000 /* # of elements in search table. */

intmain(void){char str[BUFSIZ]; /* Space to read string */struct info info_space[NUM_EMPL]; /* Space to store employee info. */struct info *info_ptr = info_space; /* Next space in info_space. */ENTRY item;

Systems/C C Library 349

Page 368: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

ENTRY *found_item; /* Name to look for in table. */char name_to_find[30];int i = 0;

/* Create table; no error checking is performed. */(void) hcreate(NUM_EMPL);

while (scanf("%s%d%d", str, &info_ptr->age,&info_ptr->room) != EOF && i++ < NUM_EMPL) {

/* Put information in structure, and structure in item. */item.key = strdup(str);item.data = info_ptr;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;

}

SEE ALSO

bsearch(3), lsearch(3), malloc(3), strcmp(3), tsearch(3)

STANDARDS

The hcreate(), hdestroy(), and hsearch() functions conform to X/Open Porta-bility Guide Issue 4.2 (“XPG4.2”).

350 Systems/C C Library

Page 369: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

ISSUES

The interface permits the use of only one hash table at a time.

Systems/C C Library 351

Page 370: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

ISATTY(3)

NAME

isatty - determine if a file descriptor is associated with a terminal

SYNOPSIS

#include <unistd.h>

intisatty(int fd);

DESCRIPTION

The isatty() function determines if the file descriptor fd refers to a valid terminaltype device.

If the file descriptor is associated with a DD that is allocated to a terminal, or if thefile descriptor is associated with an OpenEdition I/O descriptor that represents atty, isatty() returns a non-zero value (“true”).

RETURN VALUES

isatty() returns 0 if the descriptor fd is not associated with a terminal, non-zerootherwise.

352 Systems/C C Library

Page 371: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

LSEARCH(3)

NAME

lsearch, lfind - linear searching routines

SYNOPSIS

#include <sys/types.h>

char *lsearch(const void *key, const void *base, size_t *nelp, size_t width,

int (*compar)(void *, void *));

char *lfind(const void *key, const void *base, size_t *nelp, size_t width,

int (*compar)(void *, void *));

DESCRIPTION

This interface was obsolete before it was written.

The functions lsearch(), and lfind() provide basic linear searching functionality.

Base is the pointer to the beginning of an array. The argument nelp is the currentnumber of elements in the array, where each element is width bytes long. The comparfunction is a comparison routine which is used to compare two elements. It takestwo arguments which point to the key object and to an array member, in that order,and must return an integer less than, equivalent to, or greater than zero if the keyobject is considered, respectively, to be less than, equal to, or greater than the arraymember.

The lsearch() and lfind() functions return a pointer into the array referenced bybase where key is located. If key does not exist, lfind() will return a NULL pointerand lsearch() will add it to the array. When an element is added to the array bylsearch() the location referenced by the argument nelp is incremented by one.

SEE ALSO

bsearch(3)

Systems/C C Library 353

Page 372: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

MAKECONTEXT(3)

NAME

makecontext, swapcontext – modify and exchange user thread contexts

SYNOPSIS

#include <ucontext.h>

voidmakecontext(ucontext_t *ucp, void (*func)(void), int argc, ...);

intswapcontext(ucontext_t *oucp, const ucontext_t *ucp);

DESCRIPTION

The makecontext() function modifies the user thread context pointed to by ucp,which must have previously been initialized by a call to getcontext(3) and had astack allocated for it. The context is modified so that it will continue execution byinvoking func() with the arguments provided. The argc argument must be equal tothe number of additional arguments provided to makecontext() and also equal tothe number of arguments to func(), or else the behavior is undefined.

The ucp->uc link argument must be initialized before calling makecontext() anddetermines the action to take when func() returns: if equal to NULL, the processexits; otherwise, setcontext(ucp->uc link) is implicitly invoked.

The swapcontext() function saves the current thread context in *oucp and makes*ucp the currently active context.

RETURN VALUES

If successful, swapcontext() returns zero; otherwise -1 is returned and the globalvariable errno is set appropriately.

ERRORS

The swapcontext() function will fail if:

[ENOMEM] There is not enough stack space in ucp to complete the operation.

354 Systems/C C Library

Page 373: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

SEE ALSO

setcontext(3), ucontext(3)

Systems/C C Library 355

Page 374: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

NICE(3)

NAME

nice - set program scheduling priority

SYNOPSIS

#include <unistd.h>

intnice(int incr);

DESCRIPTION

This interface is obsoleted by setpriority(2).

The nice() function obtains the scheduling priority of the process from the systemand sets it to the priority value specified in incr. The priority is a value in the range-20 to 19. The default priority is 0; lower priorities cause more favorable scheduling.Only the super-user may lower priorities.

Children inherit the priority of their parent processes via fork(2).

SEE ALSO

fork(2), setpriority(2)

356 Systems/C C Library

Page 375: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

POPEN(3)

NAME

popen, pclose - process I/O

SYNOPSIS

#include <stdio.h>

FILE *popen(const char *command, const char *type);

intpclose(FILE *stream);

DESCRIPTION

The popen() function “opens” a process by creating a pipe, forking, and invokingthe shell. Since a pipe is by definition unidirectional, the type argument may specifyonly reading or writing, not both; the resulting stream is correspondingly read-onlyor write-only.

The command argument is a pointer to a null-terminated string containing a shellcommand line. This command is passed to /bin/sh using the -c flag; interpretation,if any, is performed by the shell. The mode argument is a pointer to a null-terminatedstring which must be either "r" for reading or "w" for writing.

The return value from popen() is a normal standard I/O stream in all respectssave that it must be closed with pclose() rather than fclose(3). Writing to sucha stream writes to the standard input of the command; the command’s standardoutput is the same as that of the process that called popen(), unless this is alteredby the command itself. Conversely, reading from a “popened” stream reads thecommand’s standard output, and the command’s standard input is the same asthat of the process that called popen().

Note that output popen() streams are fully buffered by default.

The pclose() function waits for the associated process to terminate and returns theexit status of the command as returned by waitpid(2).

RETURN VALUE

The popen() function returns NULL if the fork(2) or pipe(2) calls fail, or if it cannotallocate memory.

Systems/C C Library 357

Page 376: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

The pclose() function returns -1 if stream is not associated with a “popened”command, if stream is already “pclosed”, or if waitpid(2) returns an error.

ERRORS

The popen() function does not reliably set errno.

SEE ALSO

fork(2), pipe(2), fflush(3), fclose(3), fopen(3), stdio(3), system(3)

ISSUES

Since the standard input of a command opened for reading shares its seek offset withthe process that called popen(), if the original process has done a buffered read,the command’s input position may not be as expected. Similarly, the output froma command opened for writing may become intermingled with that of the originalprocess. The latter can be avoided by calling fflush(3) before popen().

Failure to execute the shell is indistinguishable from the shell’s failure to executecommand, or an immediate exit of the command. The only hint is an exit status of127.

The popen() argument always calls sh.

358 Systems/C C Library

Page 377: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

POSIX SPAWN(3)

NAME

posix spawn, posix spawnp - spawn a process

SYNOPSIS

#include <spawn.h>

intposix_spawn(pid_t *restrict pid, const char *restrict path,

const posix_spawn_file_actions_t *file_actions,const posix_spawnattr_t *restrict attrp, char *const argv[restrict],char *const envp[restrict]);

intposix_spawnp(pid_t *restrict pid, const char *restrict file,

const posix_spawn_file_actions_t *file_actions,const posix_spawnattr_t *restrict attrp, char *const argv[restrict],char *const envp[restrict]);

DESCRIPTION

The posix spawn() and posix spawnp() functions create a new process (childprocess) from the specified process image. The new process image is constructedfrom a regular executable file called the new process image file.

When a C program is executed as the result of this call, it is entered as a C-languagefunction call as follows:

int main(int argc, char *argv[]);

where argc is the argument count and argv is an array of character pointers to thearguments themselves. In addition, the variable:

extern char **environ;

points to an array of character pointers to the environment strings.

The argument argv is an array of character pointers to null-terminated strings.The last member of this array is a null pointer and is not counted in argc. These

Systems/C C Library 359

Page 378: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

strings constitute the argument list available to the new process image. The value inargv[0] should point to a filename that is associated with the process image beingstarted by the posix spawn() or posix spawnp() function.

The argument envp is an array of character pointers to null-terminated strings.These strings constitute the environment for the new process image. The environ-ment array is terminated by a null pointer.

The path argument to posix spawn() is a pathname that identifies the new processimage file to execute.

The file parameter to posix spawnp() is used to construct a pathname that iden-tifies the new process image file. If the file parameter contains a slash character, thefile parameter is used as the pathname for the new process image file. Otherwise,the path prefix for this file is obtained by a search of the directories passed as theenvironment variable “PATH”. If this variable is not specified, the default path is setaccording to the PATH DEFPATH definition in ¡paths.h¿, which is set to

“/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/sbin:/usr/local/bin”.

If file actions is a null pointer, then file descriptors open in the calling process remainopen in the child process, except for those whose close-on-exec flag FD CLOEXECis set (see fcntl()). For those file descriptors that remain open, all attributes ofthe corresponding open file descriptions, including file locks (see fcntl()), remainunchanged.

If file actions is not NULL, then the file descriptors open in the child process are thoseopen in the calling process as modified by the spawn file actions object pointed toby file actions and the FD CLOEXEC flag of each remaining open file descriptor afterthe spawn file actions have been processed. The effective order of processing thespawn file actions are:

1. The set of open file descriptors for the child process initially arethe same set as is open for the calling process. All attributes ofthe corresponding open file descriptions, including file locks (seefcntl()), remain unchanged.

2. The signal mask, signal default actions, and the effective user andgroup IDs for the child process are changed as specified in the at-tributes object referenced by attrp.

3. The file actions specified by the spawn file actions object are per-formed in the order in which they were added to the spawn fileactions object.

4. Any file descriptor that has its FD CLOEXEC flag set (see fcntl()) isclosed.

360 Systems/C C Library

Page 379: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

All non-posix file descriptors are closed and unavailable to the child process.

The posix spawnattr t spawn attributes object type is defined in <spawn.h>. Itcontains the attributes defined below.

If the POSIX SPAWN SETPGROUP flag is set in the spawn-flags attribute of the objectreferenced by attrp, and the spawn-pgroup attribute of the same object is non-zero,then the child’s process group is as specified in the spawn-pgroup attribute of theobject referenced by attrp.

As a special case, if the POSIX SPAWN SETPGROUP flag is set in the spawn-flags at-tribute of the object referenced by attrp, and the spawn-pgroup attribute of thesame object is set to zero, then the child is in a new process group with a processgroup ID equal to its process ID.

If the POSIX SPAWN SETPGROUP flag is not set in the spawn-flags attribute of theobject referenced by attrp, the new child process inherits the parent’s process group.

The POSIX SPAWN RESETIDS flag in the spawn-flags attribute of the object referencedby attrp governs the effective user ID of the child process. If this flag is not set,the child process inherits the parent process’ effective user ID. If this flag is set, thechild process’ effective user ID is reset to the parent’s real user ID. In either case, ifthe set-user-ID mode bit of the new process image file is set, the effective user ID ofthe child process becomes that file’s owner ID before the new process image beginsexecution.

The POSIX SPAWN RESETIDS flag in the spawn-flags attribute of the object referencedby attrp also governs the effective group ID of the child process. If this flag is notset, the child process inherits the parent process’ effective group ID. If this flag isset, the child process’ effective group ID is reset to the parent’s real group ID. Ineither case, if the set-group-ID mode bit of the new process image file is set, theeffective group ID of the child process becomes that file’s group ID before the newprocess image begins execution.

If the POSIX SPAWN SETSIGMASK flag is set in the spawn-flags attribute of the objectreferenced by attrp, the child process initially has the signal mask specified in thespawn-sigmask attribute of the object referenced by attrp.

If the POSIX SPAWN SETSIGDEF flag is set in the spawn-flags attribute of the objectreferenced by attrp, the signals specified in the spawn-sigdefault attribute of thesame object is set to their default actions in the child process. Signals set to thedefault action in the parent process is set to the default action in the child process.

Signals set to be caught by the calling process is set to the default action in thechild process.

Signals set to be ignored by the calling process image is set to be ignored by thechild process, unless otherwise specified by the POSIX SPAWN SETSIGDEF flag beingset in the spawn-flags attribute of the object referenced by attrp and the signalsbeing indicated in the spawn-sigdefault attribute of the object referenced by attrp.

Systems/C C Library 361

Page 380: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

If the value of the attrp pointer is NULL, then the default values are used.

All process attributes, other than those influenced by the attributes set in the objectreferenced by attrp as specified above or by the file descriptor manipulations specifiedin file actions, appear in the new process image as though vfork() had been calledto create a child process and then execve() had been called by the child process toexecute the new process image.

The implementation uses vfork(), thus the fork handlers are not run whenposix spawn() or posix spawnp() is called.

RETURN VALUES

Upon successful completion, posix spawn() and posix spawnp() return the pro-cess ID of the child process to the parent process, in the variable pointed to by anon-NULL pid argument, and return zero as the function return value. Otherwise,no child process is created, no value is stored into the variable pointed to by pid,and an error number is returned as the function return value to indicate the error.If the pid argument is a null pointer, the process ID of the child is not returned tothe caller.

ERRORS

1. If posix spawn() and posix spawnp() fail for any of the reasonsthat would cause vfork() or one of the exec to fail, an error valueis returned as described by vfork() and exec, respectively (or, ifthe error occurs after the calling process successfully returns, thechild process exits with exit status 127).

2. If POSIX SPAWN SETPGROUP is set in the spawn-flags attributeof the object referenced by attrp, and posix spawn() orposix spawnp() fails while changing the child’s process group, anerror value is returned as described by setpgid() (or, if the error oc-curs after the calling process successfully returns, the child processexits with exit status 127).

3. If the file actions argument is not NULL, and specifies any dup2 oropen actions to be performed, and if posix spawn() or posix spawnp()fails for any of the reasons that would cause dup2() or open() tofail, an error value is returned as described by dup2() and open(),respectively (or, if the error occurs after the calling process success-fully returns, the child process exits with exit status 127).

An open file action may, by itself, result in any of the errors described by dup2(),in addition to those described by open(). This implementation ignores any errorsfrom close(), including trying to close a descriptor that is not open.

362 Systems/C C Library

Page 381: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

SEE ALSO

close(2), dup2(2), execve(2), fcntl(2), open(2), setpgid(2), vfork(2),posix spawn file actions addclose(3), posix spawn file actions adddup2(3),posix spawn file actions addopen(3), posix spawn file actions destroy(3),posix spawn file actions init(3), posix spawnattr destroy(3),posix spawnattr getflags(3), posix spawnattr getpgroup(3),posix spawnattr getsigdefault(3), posix spawnattr getsigmask(3),posix spawnattr init(3), posix spawnattr setflags(3), posix spawnattr setpgroup(3),posix spawnattr setsigdefault(3), posix spawnattr setsigmask(3)

STANDARDS

The posix spawn() and posix spawnp() functions conform to IEEE Std 1003.1-2001 (“POSIX.1”), except that they ignore all errors from close(). A future updateof the Standard is expected to require that these functions not fail because a filedescriptor to be closed (via posix spawn file actions addclose()) is not open.

The optional scheduling related functions described in the standard are not availableon z/OS and not implemented.

Systems/C C Library 363

Page 382: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

POSIX SPAWNATTR GETFLAGS(3)

NAME

posix spawnattr getflags, posix spawnattr setflags - get and set the spawn-flags at-tribute of a spawn attributes object

SYNOPSIS

#include <spawn.h>

intposix_spawnattr_getflags(const posix_spawnattr_t *restrict attr,

short *restrict flags);

intposix_spawnattr_setflags(posix_spawnattr_t *attr, short flags);

DESCRIPTION

The posix spawnattr getflags() function obtains the value of the spawn-flagsattribute from the attributes object referenced by attr.

The posix spawnattr setflags() function sets the spawn-flags attribute in an ini-tialized attributes object referenced by attr.

The spawn-flags attribute is used to indicate which process attributes areto be changed in the new process image when invoking posix spawn() orposix spawnp(). It is the bitwise-inclusive OR of zero or more of the followingflags (see posix spawn()):

POSIX_SPAWN_RESETIDS

POSIX_SPAWN_SETPGROUP

POSIX_SPAWN_SETSIGDEF

POSIX_SPAWN_SETSIGMASK

These flags are defined in <spawn.h>. The default value of this attribute is as if noflags were set.

364 Systems/C C Library

Page 383: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

RETURN VALUES

The posix spawnattr getflags() and posix spawnattr setflags() functions re-turn zero.

SEE ALSO

posix spawn(3), posix spawnattr destroy(3), posix spawnattr init(3),posix spawnp(3)

STANDARDS

The posix spawnattr getflags() and posix spawnattr setflags() functionsconform to IEEE Std 1003.1-2001 (“POSIX.1”).

Systems/C C Library 365

Page 384: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

POSIX SPAWNATTR GETPGROUP(3)

NAME

posix spawnattr getpgroup, posix spawnattr setpgroup - get and set the spawn-pgroup attribute of a spawn attributes object

SYNOPSIS

#include <spawn.h>

intposix_spawnattr_getpgroup(const posix_spawnattr_t *restrict attr,

pid_t *restrict pgroup);

intposix_spawnattr_setpgroup(posix_spawnattr_t *attr, pid_t pgroup);

DESCRIPTION

The posix spawnattr getpgroup() function obtains the value of the spawn-pgroup attribute from the attributes object referenced by attr.

The posix spawnattr setpgroup() function sets the spawn-pgroup attribute inan initialized attributes object referenced by attr.

The spawn-pgroup attribute represents the process group to be joined by the newprocess image in a spawn operation (if POSIX SPAWN SETPGROUP is set in the spawn-flags attribute). The default value of this attribute is zero.

RETURN VALUES

The posix spawnattr getpgroup() and posix spawnattr setpgroup() func-tions return zero.

SEE ALSO

posix spawn(3), posix spawnattr destroy(3), posix spawnattr init(3),posix spawnp(3)

366 Systems/C C Library

Page 385: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

STANDARDS

The posix spawnattr getpgroup() and posix spawnattr setpgroup() func-tions conform to IEEE Std 1003.1-2001 (“POSIX.1”).

Systems/C C Library 367

Page 386: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

POSIX SPAWNATTR GETSIGDEFAULT(3)

NAME

posix spawnattr getsigdefault, posix spawnattr setsigdefault - get and set thespawn-sigdefault attribute of a spawn attributes object

SYNOPSIS

#include <spawn.h>

intposix_spawnattr_getsigdefault(const posix_spawnattr_t *restrict attr,

sigset_t *restrict sigdefault);

intposix_spawnattr_setsigdefault(posix_spawnattr_t *attr,

const sigset_t *restrict sigdefault);

\dparagraph{DESCRIPTION}The \fnname{posix\_spawnattr\_getsigdefault()} function obtains the value of thespawn-sigdefault attribute from the attributes object referenced by \lvar{attr}.

The \fnname{posix\_spawnattr\_setsigdefault()} function sets the spawn-sigdefaultattribute in an initialized attributes object referenced by \lvar{attr}.

The spawn-sigdefault attribute represents the set of signals to be forcedto default signal handling in the new process image (if{\tt POSIX\_SPAWN\_SETSIGDEF} is set in the spawn-flags attribute) by a spawnoperation. The default value of this attribute is an empty signal set.

\dparagraph{RETURN VALUES}The \fnname{posix\_spawnattr\_getsigdefault()} and \fnname{posix\_spawnattr\_setsigdefault()} functions return zero.

\dparagraph{SEE ALSO\manref{posix\_spawn}{3}, \manref{posix\_spawnattr\_destroy}{3},\manref{posix\_spawnattr\_getsigmask}{3}, \manref{posix\_spawnattr\_init}{3},\manref{posix\_spawnattr\_setsigmask}{3}, \manref{posix\_spawnp}{3}

\dparagraph{STANDARDS}The \fnname{posix\_spawnattr\_getsigdefault()}and \fnname{posix\_spawnattr\_setsigdefault()} functions conform to IEEE Std 1003.1-2001 (‘‘POSIX.1’’).

\dmansection{POSIX\_SPAWNATTR\_GETSIGMASK(3)}

\dparagraph{NAME}

368 Systems/C C Library

Page 387: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

posix\_spawnattr\_getsigmask, posix\_spawnattr\_setsigmask - get and set the spawn-sigmask attribute of a spawn attributes object

\dparagraph{SYNOPSIS}\begin{verbatim}#include <spawn.h>

intposix_spawnattr_getsigmask(const posix_spawnattr_t *restrict attr,

sigset_t *restrict sigmask);

intposix_spawnattr_setsigmask(posix_spawnattr_t *attr,

const sigset_t *restrict sigmask);

DESCRIPTION

The posix spawnattr getsigmask() function obtains the value of the spawn-sigmask attribute from the attributes object referenced by attr.

The

posix spawnattr setsigmask()

function sets the spawn-sigmask attribute in an initialized attributes object refer-enced by attr.

The spawn-sigmask attribute represents the signal mask in effect in the new processimage of a spawn operation (if POSIX SPAWN SETSIGMASK is set in the spawn-flagsattribute). The default value of this attribute is unspecified.

RETURN VALUES

The posix spawnattr getsigmask() and posix spawnattr setsigmask() func-tions return zero.

SEE ALSO

posix spawn(3), posix spawnattr destroy(3), posix spawnattr getsigmask(3),posix spawnattr init(3), posix spawnattr setsigmask(3), posix spawnp(3)

Systems/C C Library 369

Page 388: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

STANDARDS

The posix spawnattr getsigmask() and posix spawnattr setsigmask() func-tions conform to IEEE Std 1003.1-2001 (“POSIX.1”).

370 Systems/C C Library

Page 389: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

POSIX SPAWNATTR INIT(3)

NAME

posix spawnattr init, posix spawnattr destroy - initialize and destroy spawn at-tributes object

SYNOPSIS

#include <spawn.h>

intposix_spawnattr_init(posix_spawnattr_t * attr);

intposix_spawnattr_destroy(posix_spawnattr_t * attr);

DESCRIPTION

The posix spawnattr init() function initializes a spawn attributes object attr withthe default value for all of the individual attributes used by the implementation.Initializing an already initialized spawn attributes object may cause memory to beleaked.

The posix spawnattr destroy() function destroys a spawn attributes object. Adestroyed attr attributes object can be reinitialized using posix spawnattr init().The object should not be used after it has been destroyed.

A spawn attributes object is of type posix spawnattr t (defined in <spawn.h>) andis used to specify the inheritance of process attributes across a spawn operation.

The resulting spawn attributes object (possibly modified by setting individ-ual attribute values), is used to modify the behavior of posix spawn() orposix spawnp(). After a spawn attributes object has been used to spawn a pro-cess by a call to a posix spawn() or posix spawnp(), any function affecting theattributes object (including destruction) will not affect any process that has beenspawned in this way.

RETURN VALUES

Upon successful completion, posix spawnattr init() andposix spawnattr destroy() return zero; otherwise, an error number isreturned to indicate the error.

Systems/C C Library 371

Page 390: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

ERRORS

The posix spawnattr init() function will fail if:

[ENOMEM] Insufficient memory exists to initialize the spawn attributes object.

SEE ALSO

posix spawn(3), posix spawnp(3)

STANDARDS

The posix spawnattr init() and posix spawnattr destroy() functions conformto IEEE Std 1003.1-2001 (“POSIX.1”).

372 Systems/C C Library

Page 391: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

POSIX SPAWN FILE ACTIONS ADDOPEN(3)

NAME

posix spawn file actions addopen, posix spawn file actions adddup2,posix spawn file actions addclose - add open, dup2 or close action to spawn fileactions object

LIBRARY Standard C Library (libc, -lc)

SYNOPSIS

#include <spawn.h>

intposix_spawn_file_actions_addopen(posix_spawn_file_actions_t * file_actions,

int fildes, const char *restrict path, int oflag, mode_t mode);

intposix_spawn_file_actions_adddup2(posix_spawn_file_actions_t * file_actions,

int fildes, int newfildes);

intposix_spawn_file_actions_addclose(posix_spawn_file_actions_t * file_actions,

int fildes);

DESCRIPTION

These functions add an open, dup2 or close action to a spawn file actions object.

A spawn file actions object is of type posix spawn file actions t (defined in<spawn.h>) and is used to specify a series of actions to be performed by aposix spawn() or posix spawnp() operation in order to arrive at the set of openfile descriptors for the child process given the set of open file descriptors of theparent.

A spawn file actions object, when passed to posix spawn() or posix spawnp(),specify how the set of open file descriptors in the calling process is transformed into aset of potentially open file descriptors for the spawned process. This transformationis as if the specified sequence of actions was performed exactly once, in the contextof the spawned process (prior to execution of the new process image), in the orderin which the actions were added to the object; additionally, when the new processimage is executed, any file descriptor (from this new set) which has its FD CLOEXECflag set is closed (see posix spawn()).

Systems/C C Library 373

Page 392: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

The posix spawn file actions addopen() function adds an open action to theobject referenced by file actions that causes the file named by path to be opened (asif

open(path, oflag, mode)

had been called, and the returned file descriptor, if not fildes, had been changed tofildes) when a new process is spawned using this file actions object. If fildes wasalready an open file descriptor, it is closed before the new file is opened.

The string described by path is copied by theposix spawn file actions addopen() function.

The posix spawn file actions adddup2() function adds a dup2 action to theobject referenced by file actions that causes the file descriptor fildes to be duplicatedas newfildes (as if

dup2(fildes, newfildes)

had been called) when a new process is spawned using this file actions object, exceptthat the FD CLOEXEC flag for newfildes is cleared even if fildes is equal to newfildes.The difference from dup2() is useful for passing a particular file descriptor to aparticular child process.

The posix spawn file actions addclose() function adds a close action to the ob-ject referenced by file actions that causes the file descriptor fildes to be closed (asif

close(fildes)

had been called) when a new process is spawned using this file actions object.

RETURN VALUES

Upon successful completion, these functions return zero; otherwise, an error numberis returned to indicate the error.

ERRORS

These functions fail if:

[EBADF] The value specified by fildes or newfildes is negative.

[ENOMEM] Insufficient memory exists to add to the spawn file actions object.

374 Systems/C C Library

Page 393: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

SEE ALSO

close(2), manrefdup22, manrefopen2, manrefposix spawn3,posix spawn file actions destroy(3), manrefposix spawn file actions init3,posix spawnp(3)

STANDARDS

The posix spawn file actions addopen(),posix spawn file actions adddup2() andposix spawn file actions addclose() functions conform to IEEEStd 1003.1-2001 (“POSIX.1”), with the exception of the behavior ofposix spawn file actions adddup2() if fildes is equal to newfildes (clearingFD CLOEXEC). A future update of the Standard is expected to require this behavior.

Systems/C C Library 375

Page 394: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

POSIX SPAWN FILE ACTIONS INIT(3)

NAME

posix spawn file actions init, posix spawn file actions destroy - initialize and de-stroy spawn file actions object

SYNOPSIS

#include <spawn.h>

intposix_spawn_file_actions_init(posix_spawn_file_actions_t * file_actions);

intposix_spawn_file_actions_destroy(posix_spawn_file_actions_t * file_actions);

DESCRIPTION

The posix spawn file actions init() function initialize the object referenced byfile actions to contain no file actions for posix spawn() or posix spawnp(). Ini-tializing an already initialized spawn file actions object may cause memory to beleaked.

The posix spawn file actions destroy() function destroy the object referencedby file actions; the object becomes, in effect, uninitialized. A destroyed spawn fileactions object can be reinitialized using posix spawn file actions init(). Theobject should not be used after it has been destroyed.

RETURN VALUES

Upon successful completion, these functions return zero; otherwise, an error numberis returned to indicate the error.

ERRORS

The posix spawn file actions init() function will fail if:

[ENOMEM] Insufficient memory exists to initialize the spawn file actions object.

376 Systems/C C Library

Page 395: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

SEE ALSO

posix spawn(3), posix spawn file actions addclose(3),posix spawn file actions adddup2(3), posix spawn file actions addopen(3),posix spawnp(3)

STANDARDS The posix spawn file actions init() andposix spawn file actions destroy() functions conform to IEEE Std1003.1-2001 (“POSIX.1”).

Systems/C C Library 377

Page 396: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

PSELECT(3)

NAME

pselect – synchronous I/O multiplexing a la POSIX.1g

SYNOPSIS

#include <sys/select.h>

int pselect(int nfds,fd_set * restrict readfds, fd_set * restrict writefds,fd_set * restrict exceptfds,const struct timespec * restrict timeout,const sigset_t * restrict newsigmask);

DESCRIPTION

The pselect() function was introduced by IEEE Std 1003.1g-2000 (“POSIX.1”) asa slightly stronger version of select(2). The nfds, readfds, writefds, and exceptfdsarguments are all identical to the analogous arguments of select(). The time-out argument in pselect() points to a const struct timespec rather than the(modifiable) struct timeval used by select(); as in select(), a null pointer maybe passed to indicate that pselect() should wait indefinitely.i Finally, newsigmaskspecifies a signal mask which is set while waiting for input. When pselect() returns,the original signal mask is restored.

See select(3) for a more detailed discussion of the semantics of this interface, andfor macros used to manipulate the fd set data type.

IMPLEMENTATION NOTES

The pselect() function is implemented in the C library as a wrapper around se-lect().

RETURN VALUES

The pselect() function returns the same values and under the same conditions asselect().

378 Systems/C C Library

Page 397: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

ERRORS

The pselect() function may fail for any of the reasons documented for select(3) and(if a signal mask is provided) sigprocmask(2).

SEE ALSO

poll(2), select(3), sigprocmask(2)

STANDARDS

The pselect() function conforms to IEEE Std 1003.1-2001 (“POSIX.1”).

Systems/C C Library 379

Page 398: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

PSIGNAL(3)

NAME

psignal, strsignal, sys siglist, sys signame - system signal messages

SYNOPSIS

#include <signal.h>

voidpsignal(unsigned sig, const char *s);

extern const char * const sys_siglist[];extern const char * const sys_signame[];

#include <string.h>

char *strsignal(int sig);

DESCRIPTION

The psignal() and strsignal() functions locate the descriptive message string fora signal number.

The strsignal() function accepts a signal number argument sig and returns a pointerto the corresponding message string.

The psignal() function accepts a signal number argument sig and writes it to thestandard error file descriptor. If the argument s is non-NULL and does not pointto the null character, s is written to the standard error file descriptor prior to themessage string, immediately followed by a colon and a space. If the signal numberis not recognized, the string "Unknown signal" is produced.

The message strings can be accessed directly through the external arraysys siglist, indexed by recognized signal numbers. The external arraysys signame is used similarly and contains short, lower-case abbreviations for sig-nals which are useful for recognizing signal names in user input. The defined variableNSIG contains a count of the strings in sys siglist and sys signame.

SEE ALSO

perror(3), strerror(3)

380 Systems/C C Library

Page 399: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

PTSNAME(3)

NAME

ptsname - get the pathname of a slave pty (pseudo-terminal)

SYNOPSIS

#include <stdlib.h>

char *ptsname(int filedes);

DESCRIPTION

ptsname() returns the name of the slave pseudo-terminal associated with a masterterminal device referenced by the open filedes.

The minor numbers of the slave and master device will be the same.

RETURN VALUE

If successful, ptsname() returns the NUL-terminated name of the complete pathname of the slave device, otherwise a NULL pointer is returned and the global variableerrno is set to indicate the error.

ERRORS

As well as the errors described in stat(2), ptsname() will fail if:

[ENOTTY] filedes is not associated with a tty or does not represent a masterpty.

[ENOTTY] The associated slave device was not present in the system, indicatinga configuration error.

SEE ALSO

grantpt(2), unlockpt(2)

Systems/C C Library 381

Page 400: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

ISSUES

The ptsname() function leaves its result in an internal static object and returns apointer to that object. Subsequent calls to ptsname() will modify the same object.

382 Systems/C C Library

Page 401: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

PAUSE(3)

NAME

pause – stop until signal

SYNOPSIS

#include <unistd.h>

intpause(void);

DESCRIPTION

Pause() is made obsolete by sigsuspend(2).

The pause() function forces a process to pause until a signal is received from eitherthe kill(2) function or an interval timer. Upon termination of a signal handler startedduring a pause(), the pause() call will return.

RETURN VALUES

Always returns -1.

IMPLEMENTATION NODES

The pause() function requires POSIX signals. If POSIX signals are not availble,pause() immediately returns a -1 with errno set to ENOSYS.

ERRORS

The pause() function always returns -1 and sets the errno value to:

[EINTR] The call was interrupt.

[ENOSYS] POSIX signals were not available.

SEE ALSO

kill(2), select(2), sigsuspend(2)

Systems/C C Library 383

Page 402: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

QUEUE(3)

NAME

SLIST EMPTY, SLIST ENTRY, SLIST FIRST, SLIST FOREACH,SLIST HEAD,SLIST INIT, SLIST INSERT AFTER, SLIST INSERT HEAD, SLIST NEXT,SLIST REMOVE HEAD, SLIST REMOVE, STAILQ EMPTY, STAILQ ENTRY,STAILQ FIRST, STAILQ FOREACH, STAILQ HEAD, STAILQ INIT,STAILQ INSERT AFTER, STAILQ INSERT HEAD, STAILQ INSERT TAIL,STAILQ LAST, STAILQ NEXT, STAILQ REMOVE HEAD,STAILQ REMOVE, LIST EMPTY, LIST ENTRY, LIST FIRST,LIST FOREACH, LIST HEAD, LIST INIT, LIST INSERT AFTER,LIST INSERT BEFORE, LIST INSERT HEAD, LIST NEXT,LIST REMOVE, TAILQ EMPTY, TAILQ ENTRY, TAILQ FIRST,TAILQ FOREACH, TAILQ FOREACH REVERSE, TAILQ HEAD, TAILQ INIT,TAILQ INSERT AFTER, TAILQ INSERT BEFORE, TAILQ INSERT HEAD,TAILQ INSERT TAIL, TAILQ LAST, TAILQ NEXT, TAILQ PREV,TAILQ REMOVE, CIRCLEQ EMPTY, CIRCLEQ ENTRY, CIRCLEQ FIRST,CIRCLEQ FOREACH, CIRCLEQ FOREACH REVERSE, CIRCLEQ HEAD,CIRCLEQ INIT, CIRCLEQ INSERT AFTER, CIRCLEQ INSERT BEFORE,CIRCLEQ INSERT HEAD, CIRCLEQ INSERT TAIL, CIRCLE LAST, CIR-CLE NEXT, CIRCLE PREV, CIRCLEQ REMOVE - implementations ofsingly-linked lists, singly-linked tail queues, lists, tail queues, and circular queues

SYNOPSIS

#include <sys/queue.h>

SLIST_EMPTY(SLIST_HEAD *head);

SLIST_ENTRY(TYPE);

SLIST_FIRST(SLIST_HEAD *head);

SLIST_FOREACH(TYPE *var, SLIST_HEAD *head, SLIST_ENTRY NAME);

SLIST_HEAD(HEADNAME, TYPE);

SLIST_INIT(SLIST_HEAD *head);

SLIST_INSERT_AFTER(TYPE *listelm, TYPE *elm, SLIST_ENTRY NAME);

SLIST_INSERT_HEAD(SLIST_HEAD *head, TYPE *elm, SLIST_ENTRY NAME);

SLIST_NEXT(TYPE *elm, SLIST_ENTRY NAME);

384 Systems/C C Library

Page 403: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

SLIST_REMOVE_HEAD(SLIST_HEAD *head, SLIST_ENTRY NAME);

SLIST_REMOVE(SLIST_HEAD *head, TYPE *elm, TYPE, SLIST_ENTRY NAME);

STAILQ_EMPTY(STAILQ_HEAD *head);

STAILQ_ENTRY(TYPE);

STAILQ_FIRST(STAILQ_HEAD *head);

STAILQ_FOREACH(TYPE *var, STAILQ_HEAD *head, STAILQ_ENTRY NAME);

STAILQ_HEAD(HEADNAME, TYPE);

STAILQ_INIT(STAILQ_HEAD *head);

STAILQ_INSERT_AFTER(STAILQ_HEAD *head, TYPE *listelm, TYPE *elm,STAILQ_ENTRY NAME);

STAILQ_INSERT_HEAD(STAILQ_HEAD *head, TYPE *elm, STAILQ_ENTRY NAME);

STAILQ_INSERT_TAIL(STAILQ_HEAD *head, TYPE *elm, STAILQ_ENTRY NAME);

STAILQ_LAST(STAILQ_HEAD *head);

STAILQ_NEXT(TYPE *elm, STAILQ_ENTRY NAME);

STAILQ_REMOVE_HEAD(STAILQ_HEAD *head, STAILQ_ENTRY NAME);

STAILQ_REMOVE(STAILQ_HEAD *head, TYPE *elm, TYPE, STAILQ_ENTRY NAME);

LIST_EMPTY(LIST_HEAD *head);

LIST_ENTRY(TYPE);

LIST_FIRST(LIST_HEAD *head);

LIST_FOREACH(TYPE *var, LIST_HEAD *head, LIST_ENTRY NAME);

LIST_HEAD(HEADNAME, TYPE);

LIST_INIT(LIST_HEAD *head);

LIST_INSERT_AFTER(TYPE *listelm, TYPE *elm, LIST_ENTRY NAME);

LIST_INSERT_BEFORE(TYPE *listelm, TYPE *elm, LIST_ENTRY NAME);

Systems/C C Library 385

Page 404: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

LIST_INSERT_HEAD(LIST_HEAD *head, TYPE *elm, LIST_ENTRY NAME);

LIST_NEXT(TYPE *elm, LIST_ENTRY NAME);

LIST_REMOVE(TYPE *elm, LIST_ENTRY NAME);

TAILQ_EMPTY(TAILQ_HEAD *head);

TAILQ_ENTRY(TYPE);

TAILQ_FIRST(TAILQ_HEAD *head);

TAILQ_FOREACH(TYPE *var, TAILQ_HEAD *head, TAILQ_ENTRY NAME);

TAILQ_FOREACH_REVERSE(TYPE *var, TAILQ_HEAD *head, HEADNAME,TAILQ_ENTRY NAME);

TAILQ_HEAD(HEADNAME, TYPE);

TAILQ_INIT(TAILQ_HEAD *head);

TAILQ_INSERT_AFTER(TAILQ_HEAD *head, TYPE *listelm, TYPE *elm,TAILQ_ENTRY NAME);

TAILQ_INSERT_BEFORE(TYPE *listelm, TYPE *elm, TAILQ_ENTRY NAME);

TAILQ_INSERT_HEAD(TAILQ_HEAD *head, TYPE *elm, TAILQ_ENTRY NAME);

TAILQ_INSERT_TAIL(TAILQ_HEAD *head, TYPE *elm, TAILQ_ENTRY NAME);

TAILQ_LAST(TAILQ_HEAD *head, HEADNAME);

TAILQ_NEXT(TYPE *elm, TAILQ_ENTRY NAME);

TAILQ_PREV(TYPE *elm, HEADNAME, TAILQ_ENTRY NAME);

TAILQ_REMOVE(TAILQ_HEAD *head, TYPE *elm, TAILQ_ENTRY NAME);

CIRCLEQ_EMPTY(CIRCLEQ_HEAD *head);

CIRCLEQ_ENTRY(TYPE);

CIRCLEQ_FIRST(CIRCLEQ_HEAD *head);

CIRCLEQ_FOREACH(TYPE *var, CIRCLEQ_HEAD *head, CIRCLEQ_ENTRY NAME);

386 Systems/C C Library

Page 405: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

CIRCLEQ_FOREACH_REVERSE(TYPE *var, CIRCLEQ_HEAD *head,CIRCLEQ_ENTRY NAME);

CIRCLEQ_HEAD(HEADNAME, TYPE);

CIRCLEQ_INIT(CIRCLEQ_HEAD *head);

CIRCLEQ_INSERT_AFTER(CIRCLEQ_HEAD *head, TYPE *listelm, TYPE *elm,CIRCLEQ_ENTRY NAME);

CIRCLEQ_INSERT_BEFORE(CIRCLEQ_HEAD *head, TYPE *listelm, TYPE *elm,CIRCLEQ_ENTRY NAME);

CIRCLEQ_INSERT_HEAD(CIRCLEQ_HEAD *head, TYPE *elm, CIRCLEQ_ENTRY NAME);

CIRCLEQ_INSERT_TAIL(CIRCLEQ_HEAD *head, TYPE *elm, CIRCLEQ_ENTRY NAME);

CIRCLEQ_LAST(CIRCLEQ_HEAD *head);

CIRCLEQ_NEXT(TYPE *elm, CIRCLEQ_ENTRY NAME);

CIRCLE_PREV(TYPE *elm, CIRCLEQ_ENTRY NAME);

CIRCLEQ_REMOVE(CIRCLEQ_HEAD *head, TYPE *elm, CIRCLEQ_ENTRY NAME);

DESCRIPTION

These macros define and operate on five types of data structures: singly-linked lists,singly-linked tail queues, lists, tail queues, and circular queues. All five structuressupport the following functionality:

1. Insertion of a new entry at the head of the list.

2. Insertion of a new entry after any element in the list.

3. O(1) removal of an entry from the head of the list.

4. O(n) removal of any entry in the list.

5. Forward traversal through the list.

Singly-linked lists are the simplest of the five data structures and support only theabove functionality. Singly-linked lists are ideal for applications with large datasetsand few or no removals, or for implementing a LIFO queue.

Singly-linked tail queues add the following functionality:

1. Entries can be added at the end of a list.

Systems/C C Library 387

Page 406: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

However:

1. All list insertions must specify the head of the list.

2. Each head entry requires two pointers rather than one.

3. Code size is about 15

Singly-linked tailqs are ideal for applications with large datasets and few or noremovals, or for implementing a FIFO queue.

All doubly linked types of data structures (lists, tail queues, and circle queues)additionally allow:

1. Insertion of a new entry before any element in the list.

2. O(1) removal of any entry in the list.

However:

1. Each elements requires two pointers rather than one.

2. Code size and execution time of operations (except for removal) is about twicethat of the singly-linked data-structures.

Linked lists are the simplest of the doubly linked data structures and support onlythe above functionality over singly-linked lists.

Tail queues add the following functionality:

1. Entries can be added at the end of a list.

2. They may be traversed backwards, from tail to head.

However:

1. All list insertions and removals must specify the head of the list.

2. Each head entry requires two pointers rather than one.

3. Code size is about 15

Circular queues add the following functionality:

1. Entries can be added at the end of a list.

2. They may be traversed backwards, from tail to head.

388 Systems/C C Library

Page 407: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

However:

1. All list insertions and removals must specify the head of the list.

2. Each head entry requires two pointers rather than one.

3. The termination condition for traversal is more complex.

4. Code size is about 40

In the macro definitions, TYPE is the name of a user defined structure, that mustcontain a field of type SLIST ENTRY, STAILQ ENTRY, LIST ENTRY, TAILQ ENTRY, orCIRCLEQ ENTRY, named NAME. The argument HEADNAME is the name of a userdefined structure that must be declared using the macros SLIST HEAD, STAILQ HEAD,LIST HEAD, TAILQ HEAD, or CIRCLEQ HEAD. See the examples below for further ex-planation of how these macros are used.

SINGLY-LINKED LISTS

A singly-linked list is headed by a structure defined by the SLIST HEAD macro. Thisstructure contains a single pointer to the first element on the list. The elements aresingly linked for minimum space and pointer manipulation overhead at the expenseof O(n) removal for arbitrary elements. New elements can be added to the list afteran existing element or at the head of the list. An SLIST HEAD structure is declaredas follows:

SLIST_HEAD(HEADNAME, TYPE) head;

where HEADNAME is the name of the structure to be defined, and TYPE is thetype of the elements to be linked into the list. A pointer to the head of the list canlater be declared as:

struct HEADNAME *headp;

(The names head and headp are user selectable.)

The macro SLIST EMPTY evaluates to true if there are no elements in the list.

The macro SLIST ENTRY declares a structure that connects the elements in the list.

The macro SLIST FIRST returns the first element in the list of NULL if the list isempty.

The macro SLIST FOREACH traverses the list referenced by head in the forward di-rection, assigning each element in turn to var

The macro SLIST INIT initializes the list referenced by head.

Systems/C C Library 389

Page 408: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

The macro SLIST INSERT HEAD inserts the new element elm at the head of the list.

The macro SLIST INSERT AFTER inserts the new element elm after the element lis-telm.

The macro SLIST NEXT returns the next element in the list.

The macro SLIST REMOVE HEAD removes the element elm from the head of the list.For optimum efficiency, elements being removed from the head of the list shouldexplicitly use this macro instead of the generic SLIST REMOVE macro.

The macro SLIST REMOVE removes the element elm from the list.

SINGLY-LINKED LIST EXAMPLE

SLIST_HEAD(slisthead, entry) head;struct slisthead *headp; /* Singly-linked List head. */struct entry {

...SLIST_ENTRY(entry) entries; /* Singly-linked List. */...

} *n1, *n2, *n3, *np;

SLIST_INIT(&head); /* Initialize the list. */

n1 = malloc(sizeof(struct entry)); /* Insert at the head. */SLIST_INSERT_HEAD(&head, n1, entries);

n2 = malloc(sizeof(struct entry)); /* Insert after. */SLIST_INSERT_AFTER(n1, n2, entries);

SLIST_REMOVE(&head, n2, entry, entries);/* Deletion. */free(n2);

n3 = SLIST_FIRST(&head);SLIST_REMOVE_HEAD(&head, entries); /* Deletion. */free(n3);

/* Forward traversal. */SLIST_FOREACH(np, &head, entries)

np-> ...

while (!SLIST_EMPTY(&head)) { /* List Deletion. */n1 = SLIST_FIRST(&head);SLIST_REMOVE_HEAD(&head, entries);free(n1);

}

390 Systems/C C Library

Page 409: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

SINGLY-LINKED TAIL QUEUES

A singly-linked tail queue is headed by a structure defined by the STAILQ HEADmacro. This structure contains a pair of pointers, one to the first element in the tailqueue and the other to the last element in the tail queue. The elements are singlylinked for minimum space and pointer manipulation overhead at the expense of O(n)removal for arbitrary elements. New elements can be added to the tail queue afteran existing element, at the head of the tail queue, or at the end of the tail queue.A STAILQ HEAD structure is declared as follows:

STAILQ_HEAD(HEADNAME, TYPE) head;

where HEADNAME is the name of the structure to be defined, and TYPE is thetype of the elements to be linked into the tail queue. A pointer to the head of thetail queue can later be declared as:

struct HEADNAME *headp;

(the names head and headp are user selectable.)

The macro STAILQ EMPTY evaluates to true if there are no items on the tail queue.

The macro STAILQ ENTRY declares a structure that connects the elements in the tailqueue.

The macro STAILQ FIRST returns the first item on the tail queue or NULL if the tailqueue is empty.

The macro STAILQ FOREACH traverses the tail queue referenced by head in the for-ward direction, assigning each element in turn to var.

The macro STAILQ INIT initializes the tail queue referenced by head.

The macro STAILQ INSERT HEAD inserts the new element elm at the head of the tailqueue.

The macro STAILQ INSERT TAIL inserts the new element elm at the end of the tailqueue.

The macro STAILQ INSERT AFTER inserts the new element elm after the elementlistelm.

The macro STAILQ LAST returns the last item on the tail queue. If the tail queue isempty the return value is undefined.

The macro STAILQ NEXT returns the next item on the tail queue, or NULL this itemis the last.

Systems/C C Library 391

Page 410: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

The macro STAILQ REMOVE HEAD removes the element elm from the head of thetail queue. For optimum efficiency, elements being removed from the head of thetail queue should use this macro explicitly rather than the generic STAILQ REMOVEmacro.

The macro STAILQ REMOVE removes the element elm from the tail queue.

SINGLY-LINKED TAIL QUEUE EXAMPLE

STAILQ_HEAD(stailhead, entry) head;struct stailhead *headp; /* Singly-linked tail queue head. */struct entry {

...STAILQ_ENTRY(entry) entries; /* Tail queue. */...

} *n1, *n2, *n3, *np;

STAILQ_INIT(&head); /* Initialize the queue. */

n1 = malloc(sizeof(struct entry)); /* Insert at the head. */STAILQ_INSERT_HEAD(&head, n1, entries);

n1 = malloc(sizeof(struct entry)); /* Insert at the tail. */STAILQ_INSERT_TAIL(&head, n1, entries);

n2 = malloc(sizeof(struct entry)); /* Insert after. */STAILQ_INSERT_AFTER(&head, n1, n2, entries);

/* Deletion. */STAILQ_REMOVE(&head, n2, entry, entries);free(n2);

/* Deletion from the head */n3 = STAILQ_FIRST(&head);STAILQ_REMOVE_HEAD(&head, entries);free(n3);

/* Forward traversal. */STAILQ_FOREACH(np, &head, entries)

np-> .../* TailQ Deletion. */

while (!STAILQ_EMPTY(&head)) {n1 = STAILQ_HEAD(&head);STAILQ_REMOVE_HEAD(&head, entries);free(n1);

}

392 Systems/C C Library

Page 411: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

/* Faster TailQ Deletion. */n1 = STAILQ_FIRST(&head);while (n1 != NULL) {

n2 = STAILQ_NEXT(n1, entries);free(n1);n1 = n2;

}STAILQ_INIT(&head);

LISTS

A list is headed by a structure defined by the LIST HEAD macro. This structurecontains a single pointer to the first element on the list. The elements are doublylinked so that an arbitrary element can be removed without traversing the list.New elements can be added to the list after an existing element, before an existingelement, or at the head of the list. A LIST HEAD structure is declared as follows:

LIST_HEAD(HEADNAME, TYPE) head;

where HEADNAME is the name of the structure to be defined, and TYPE is thetype of the elements to be linked into the list. A pointer to the head of the list canlater be declared as:

struct HEADNAME *headp;

(The names head and headp are user selectable.)

The macro LIST EMPTY valuates to true if their are no elements in the list.

The macro LIST ENTRY declares a structure that connects the elements in the list.

The macro LIST FIRST returns the first element in the list or NULL if the list isempty.

The macro LIST FOREACH traverses the list referenced by head in the forward direc-tion, assigning each element in turn to var.

The macro LIST INIT initializes the list referenced by head.

The macro LIST INSERT HEAD inserts the new element elm at the head of the list.

The macro LIST INSERT AFTER inserts the new element elm after the element listelm.

The macro LIST INSERT BEFORE inserts the new element elm before the elementlistelm.

The macro LIST NEXT returns the next element in the list, or NULL if this is the last.

The macro LIST REMOVE removes the element elm from the list.

Systems/C C Library 393

Page 412: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

LIST EXAMPLE

LIST_HEAD(listhead, entry) head;struct listhead *headp; /* List head. */struct entry {

...LIST_ENTRY(entry) entries; /* List. */...

} *n1, *n2, *n3, *np;

LIST_INIT(&head); /* Initialize the list. */

n1 = malloc(sizeof(struct entry)); /* Insert at the head. */LIST_INSERT_HEAD(&head, n1, entries);

n2 = malloc(sizeof(struct entry)); /* Insert after. */LIST_INSERT_AFTER(n1, n2, entries);

n3 = malloc(sizeof(struct entry)); /* Insert before. */LIST_INSERT_BEFORE(n2, n3, entries);

LIST_REMOVE(n2, entries); /* Deletion. */free(n2);

/* Forward traversal. */LIST_FOREACH(np, &head, entries)

np-> ...

while (!LIST_EMPTY(&head)) { /* List Deletion. */n1 = LIST_FIRST(&head);LIST_REMOVE(n1, entries);free(n1);

}

n1 = LIST_FIRST(&head); /* Faster List Delete. */while (n1 != NULL) {

n2 = LIST_NEXT(n1, entries);free(n1);n1 = n2;

}LIST_INIT(&head);

TAIL QUEUES

A tail queue is headed by a structure defined by the TAILQ HEAD macro. Thisstructure contains a pair of pointers, one to the first element in the tail queue and

394 Systems/C C Library

Page 413: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

the other to the last element in the tail queue. The elements are doubly linked sothat an arbitrary element can be removed without traversing the tail queue. Newelements can be added to the tail queue after an existing element, before an existingelement, at the head of the tail queue, or at the end of the tail queue. A TAILQ HEADstructure is declared as follows:

TAILQ_HEAD(HEADNAME, TYPE) head;

where HEADNAME is the name of the structure to be defined, and TYPE is thetype of the elements to be linked into the tail queue. A pointer to the head of thetail queue can later be declared as:

struct HEADNAME *headp;

(The names head and headp are user selectable.)

The macro TAILQ EMPTY evaluates to true if there are no items on the tail queue.

The macro TAILQ ENTRY declares a structure that connects the elements in the tailqueue.

The macro TAILQ FIRST returns the first item on the tail queue or NULL if the tailqueue is empty.

The macro TAILQ FOREACH traverses the tail queue referenced by head in the forwarddirection, assigning each element in turn to var.

The macro TAILQ FOREACH REVERSE traverses the tail queue referenced by head inthe reverse direction, assigning each element in turn to var.

The macro TAILQ INIT initializes the tail queue referenced by head.

The macro TAILQ INSERT HEAD inserts the new element elm at the head of the tailqueue.

The macro TAILQ INSERT TAIL inserts the new element elm at the end of the tailqueue.

The macro TAILQ INSERT AFTER inserts the new element elm after the element lis-telm.

The macro TAILQ INSERT BEFORE inserts the new element elm before the elementlistelm.

The macro TAILQ LAST returns the last item on the tail queue. If the tail queue isempty the return value is undefined.

Systems/C C Library 395

Page 414: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

The macro TAILQ NEXT returns the next item on the tail queue, or NULL if this itemis the last.

The macro TAILQ PREV returns the previous item on the tail queue, or NULL if thisitem is the first.

The macro TAILQ REMOVE removes the element elm from the tail queue.

TAIL QUEUE EXAMPLE

TAILQ_HEAD(tailhead, entry) head;struct tailhead *headp; /* Tail queue head. */struct entry {

...TAILQ_ENTRY(entry) entries; /* Tail queue. */...

} *n1, *n2, *n3, *np;

TAILQ_INIT(&head); /* Initialize the queue. */

n1 = malloc(sizeof(struct entry)); /* Insert at the head. */TAILQ_INSERT_HEAD(&head, n1, entries);

n1 = malloc(sizeof(struct entry)); /* Insert at the tail. */TAILQ_INSERT_TAIL(&head, n1, entries);

n2 = malloc(sizeof(struct entry)); /* Insert after. */TAILQ_INSERT_AFTER(&head, n1, n2, entries);

n3 = malloc(sizeof(struct entry)); /* Insert before. */TAILQ_INSERT_BEFORE(n2, n3, entries);

TAILQ_REMOVE(&head, n2, entries); /* Deletion. */free(n2);

/* Forward traversal. */TAILQ_FOREACH(np, &head, entries)

np-> .../* Reverse traversal. */

TAILQ_FOREACH_REVERSE(np, &head, tailhead, entries)np-> ...

/* TailQ Deletion. */while (!TAILQ_EMPTY(head)) {

n1 = TAILQ_FIRST(&head);TAILQ_REMOVE(&head, n1, entries);free(n1);

}/* Faster TailQ Deletion. */

396 Systems/C C Library

Page 415: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

n1 = TAILQ_FIRST(&head);while (n1 != NULL) {

n2 = TAILQ_NEXT(n1, entries);free(n1);n1 = n2;

}TAILQ_INIT(&head);

CIRCULAR QUEUES

A circular queue is headed by a structure defined by the CIRCLEQ HEAD macro. Thisstructure contains a pair of pointers, one to the first element in the circular queue andthe other to the last element in the circular queue. The elements are doubly linkedso that an arbitrary element can be removed without traversing the queue. Newelements can be added to the queue after an existing element, before an existingelement, at the head of the queue, or at the end of the queue. A CIRCLEQ HEADstructure is declared as follows:

CIRCLEQ_HEAD(HEADNAME, TYPE) head;

where HEADNAME is the name of the structure to be defined, and TYPE is thetype of the elements to be linked into the circular queue. A pointer to the head ofthe circular queue can later be declared as:

struct HEADNAME *headp;

(The names head and headp are user selectable.)

The macro CIRCLEQ EMPTY evaluates to true if there are no items on the circle queue.

The macro CIRCLEQ ENTRY declares a structure that connects the elements in thecircular queue.

The macro CIRCLEQ FIRST returns the first item on the circle queue.

The macro CICRLEQ FOREACH traverses the circle queue referenced by head in theforward direction, assigning each element in turn to var.

The macro CICRLEQ FOREACH REVERSE traverses the circle queue referenced by headin the reverse direction, assigning each element in turn to var.

The macro CIRCLEQ INIT initializes the circular queue referenced by head.

The macro CIRCLEQ INSERT HEAD inserts the new element elm at the head of thecircular queue.

Systems/C C Library 397

Page 416: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

The macro CIRCLEQ INSERT TAIL inserts the new element elm at the end of thecircular queue.

The macro CIRCLEQ INSERT AFTER inserts the new element elm after the elementlistelm.

The macro CIRCLEQ INSERT BEFORE inserts the new element elm before the elementlistelm.

The macro CIRCLEQ LAST returns the last item on the circle queue.

The macro CIRCLEQ NEXT returns the next item on the circle queue.

The macro CIRCLEQ PREV returns the previous item on the circle queue.

The macro CIRCLEQ REMOVE removes the element elm from the circular queue.

CIRCULAR QUEUE EXAMPLE

CIRCLEQ_HEAD(circleq, entry) head;struct circleq *headp; /* Circular queue head. */struct entry {

...CIRCLEQ_ENTRY(entry) entries; /* Circular queue. */...

} *n1, *n2, *np;

CIRCLEQ_INIT(&head); /* Initialize the circular queue. */

n1 = malloc(sizeof(struct entry)); /* Insert at the head. */CIRCLEQ_INSERT_HEAD(&head, n1, entries);

n1 = malloc(sizeof(struct entry)); /* Insert at the tail. */CIRCLEQ_INSERT_TAIL(&head, n1, entries);

n2 = malloc(sizeof(struct entry)); /* Insert after. */CIRCLEQ_INSERT_AFTER(&head, n1, n2, entries);

n2 = malloc(sizeof(struct entry)); /* Insert before. */CIRCLEQ_INSERT_BEFORE(&head, n1, n2, entries);

CIRCLEQ_REMOVE(&head, n1, entries); /* Deletion. */free(n1);

/* Forward traversal. */CIRCLEQ_FOREACH(np, &head, entries)

np-> .../* Reverse traversal. */

398 Systems/C C Library

Page 417: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

CIRCLEQ_FOREACH_REVERSE(np, &head, entries)np-> ...

/* CircleQ Deletion. */while (CIRCLEQ_FIRST(&head) != (void *)&head) {

n1 = CIRCLEQ_HEAD(&head);CIRCLEQ_REMOVE(&head, n1, entries);free(n1);

}/* Faster CircleQ Deletion. */

n1 = CIRCLEQ_FIRST(&head);while (n1 != (void *)&head) {

n2 = CIRCLEQ_NEXT(n1, entries);free(n1);n1 = n2;

}CIRCLEQ_INIT(&head);

Systems/C C Library 399

Page 418: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

RAISE(3)

NAME

raise - send a signal to the current program or process

SYNOPSIS

#include <signal.h>

intraise(int sig);

DESCRIPTION

The raise() function sends the signal sig to the current process.

When running under OpenEdition, raise() is the same as kill(getpid(), sig).

RETURN VALUES

The raise() function returns the value 0 if successful; otherwise the value -1 isreturned and the global variable errno is set to indicate the error.

ERRORS

The raise() function may fail and set errno for any of the errors specified for thelibrary functions getpid(2) and kill(2).

STANDARDS

The raise() function conforms to ISO/IEC 9899:1990 (“ISO C90”).

400 Systems/C C Library

Page 419: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

SEM DESTROY(3)

NAME

sem destroy – destroy an unnamed semaphore

SYNOPSIS

#include <semaphore.h>

intsem_destroy(sem_t *sem);

DESCRIPTION

The sem destroy() function destroys the unnamed semaphore pointed to by sem.After a successful call to sem destroy(), sem is unusable until reinitialized byanother call to sem init(3).

RETURN VALUES

The sem destroy() function returns the value 0 if successful; otherwise the value-1 is returned and the global variable errno is set to indicate the error.

ERRORS

The sem destroy() function will fail if:

[EINVAL] The sem argument points to an invalid semaphore.

[EBUSY] There are currently threads blocked on the semaphore that sempoints to.

SEE ALSO

sem init(3)

STANDARDS

The sem destroy() function conforms to ISO/IEC 9945-1:1996 (“POSIX.1”).

Systems/C C Library 401

Page 420: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

SEM GETVALUE(3)

NAME

sem getvalue – get the value of a semaphore

SYNOPSIS

#include <semaphore.h>

intsem_getvalue(sem_t * restrict sem, int * restrict sval);

DESCRIPTION

The sem getvalue() function sets the variable pointed to by sval to the cur-rent value of the semaphore pointed to by sem, as of the time that the call tosem getvalue() is actually run.

RETURN VALUES

The sem getvalue() function returns the value 0 if successful; otherwise the value-1 is returned and the global variable errno is set to indicate the error.

ERRORS

The sem getvalue() function will fail if:

[EINVAL] The sem argument points to an invalid semaphore.

SEE ALSO

sem post(3), sem trywait(3), sem wait(3)

402 Systems/C C Library

Page 421: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

STANDARDS

The sem getvalue() function conforms to ISO/IEC 9945-1:1996 (“POSIX.1”).

The value of the semaphore is never negative, even if there are threads blocked onthe semaphore. POSIX is somewhat ambiguous in its wording with regard to whatthe value of the semaphore should be if there are blocked waiting threads, but thisbehavior is conformant, given the wording of the specification.

Systems/C C Library 403

Page 422: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

SEM INIT(3)

NAME

sem init – initialize an unnamed semaphore

SYNOPSIS

#include <semaphore.h>

intsem_init(sem_t *sem, int pshared, unsigned int value);

DESCRIPTION

The sem init() function initializes the unnamed semaphore pointed to by sem tohave the value value. A non-zero value for pshared specifies a shared semaphore thatcan be used by multiple processes, which this implementation is not capable of.

Following a successful call to sem init(), sem can be used as an argument in sub-sequent calls to sem wait(3), sem trywait(3), sem post(3), and sem destroy(3). Thesem argument is no longer valid after a successful call to sem destroy(3).

RETURN VALUES

The sem init() function returns the value 0 if successful; otherwise the value -1 isreturned and the global variable errno is set to indicate the error.

ERRORS

The sem init() function will fail if:

[EINVAL] The value argument exceeds SEM VALUE MAX.

[ENOSPC] Memory allocation error.

[EPERM] Unable to initialize a shared semaphore.

SEE ALSO

sem destroy(3), sem getvalue(3), sem post(3), sem trywait(3), sem wait(3)

404 Systems/C C Library

Page 423: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

STANDARDS

The sem init() function conforms to ISO/IEC 9945-1:1996 (“POSIX.1”).

This implementation does not support shared semaphores, and reports this fact bysetting errno to EPERM. This is perhaps a stretch of the intention of POSIX, butis compliant, with the caveat that sem init() always reports a permissions errorwhen an attempt to create a shared semaphore is made.

Systems/C C Library 405

Page 424: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

SEM OPEN(3)

NAME

sem open, sem close, sem unlink – named semaphore operations

SYNOPSIS

#include <semaphore.h>

sem_t *sem_open(const char *name, int oflag, ...);

intsem_close(sem_t *sem);

intsem_unlink(const char *name);

DESCRIPTION

The sem open() function creates or opens the named semaphore specified byname. The returned semaphore may be used in subsequent calls to sem getvalue(3),sem wait(3), sem trywait(3), sem post(3), and sem close()(.)

The following bits may be set in the oflag argument:

O CREAT Create the semaphore if it does not already exist.

The third argument to the call to sem open() must be oftype mode t and specifies the mode for the semaphore. Onlythe S IWUSR, S IWGRP, and S IWOTH bits are examined; it isnot possible to grant only “read” permission on a semaphore.The mode is modified according to the process’s file creationmask; see umask(2).

The fourth argument must be an unsigned int and specifiesthe initial value for the semaphore, and must be no greaterthan SEM VALUE MAX.

O EXCL Create the semaphore if it does not exist. If the semaphorealready exists, sem open() will fail. This flag is ignoredunless O CREAT is also specified.

406 Systems/C C Library

Page 425: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

The sem close() function closes a named semaphore that was opened by a call tosem open().

The sem unlink() function removes the semaphore named name. Resources al-located to the semaphore are only deallocated when all processes that have thesemaphore open close it.

RETURN VALUES

If successful, the sem open() function returns the address of the opened semaphore.If the same name argument is given to multiple calls to sem open() by the sameprocess without an intervening call to sem close(), the same address is returnedeach time. If the semaphore cannot be opened, sem open() returns SEM FAILEDand the global variable eaerrno is set to indicate the error.

The sem close() and sem unlink() functions return the value 0 if successful; oth-erwise the value -1 is returned and the global variable errno is set to indicate theerror.

ERRORS

The sem open() function will fail if:

[EACCESS] The semaphore exists and the permissions specified by oflag at thetime it was created deny access to this process.

[EACCESS] The semaphore does not exist, but permission to create it is denied.

[EEXIST] O CREAT and O EXCL are set but the semaphore already exists.

[EINTR] The call was interrupted by a signal.

[EINVAL] The sem open() operation is not supported for the given name.

[EINVAL] The value argument is greater than SEM VALUE MAX.

[ENAMETOOLONG] The name argument is too long.

[ENFILE] The system limit on semaphores has been reached.

[ENOENT] O CREAT is set but the named semaphore does not exist.

[ENOSPC] There is not enough space to create the semaphore.

The sem close() function will fail if:

[EINVAL] The sem argument is not a valid semaphore.

Systems/C C Library 407

Page 426: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

The sem unlink() function will fail if:

[EACCESS] Permission is denied to unlink the semaphore.

[ENAMETOOLONG] The specified name is too long.

[ENOENT] The named semaphore does not exist.

SEE ALSO

close(2), open(2), umask(2), unlink(2), sem getvalue(3), sem post(3),sem trywait(3), sem wait(3)

STANDARDS

The sem open(), sem close(), and sem unlink() functions conform to ISO/IEC9945-1:1996 (“POSIX.1”).

ISSUES

This implementation places strict requirements on the value of name: it must beginwith a slash (‘/’), contain no other slash characters, and be less than 14 charactersin length not including the terminating null character.

This implementation creates a file in the /tmp directory, which may clash with otherprocesses using the same name.

408 Systems/C C Library

Page 427: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

SEM POST(3)

NAME

sem post – increment (unlock) a semaphore

SYNOPSIS

#include <semaphore.h>

intsem_post(sem_t *sem);

DESCRIPTION

The sem post() function increments (unlocks) the semaphore pointed to by sem.If there are threads blocked on the semaphore when sem post() is called, thena thread that has been blocked on the semaphore will be allowed to return fromsem wait().

The sem post() function is signal-reentrant and may be called within signal han-dlers.

RETURN VALUES

The sem post() function returns the value 0 if successful; otherwise the value -1 isreturned and the global variable errno is set to indicate the error.

ERRORS

The sem post() function will fail if:

[EINVAL] The sem argument points to an invalid semaphore.

SEE ALSO

sem getvalue(3), sem trywait(3), sem wait(3)

Systems/C C Library 409

Page 428: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

STANDARDS

The sem post() function conforms to ISO/IEC 9945-1:1996 (“POSIX.1”).

SEM TIMEDWAIT(3)

NAME

sem timedwait - lock a semaphore

SYNOPSIS

#include <semaphore.h>#include <time.h>

intsem_timedwait(sem_t *sem, const struct timespec *abs_timeout);

DESCRIPTION

The sem timedwait() function locks the semaphore referenced by sem, as in thesem wait(3) function. However, if the semaphore cannot be locked without waitingfor another process or thread to unlock the semaphore by performing a sem post(3)function, this wait will be terminated when the specified timeout expires.

The timeout will expire when the absolute time specified by abs timeout passes, asmeasured by the clock on which timeouts are based (that is, when the value of thatclock equals or exceeds abs timeout), or if the absolute time specified by abs timeouthas already been passed at the time of the call.

Note that the timeout is based on the CLOCK REALTIME clock.

The validity of the abs timeout is not checked if the semaphore can be locked im-mediately.

RETURN VALUES

The sem timedwait() function returns zero if the calling process successfully per-formed the semaphore lock operation on the semaphore designated by sem. If thecall was unsuccessful, the state of the semaphore is unchanged, and the functionreturns a value of -1 and sets the global variable errno to indicate the error.

410 Systems/C C Library

Page 429: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

ERRORS

The sem timedwait() function will fail if:

[EINVAL] The sem argument does not refer to a valid semaphore, or the pro-cess or thread would have blocked, and the abs timeout parameterspecified a nanoseconds field value less than zero or greater than orequal to 1000 million.

[ETIMEDOUT] The semaphore could not be locked before the specified timeoutexpired.

[EINTR] A signal interrupted this function.

SEE ALSO

sem post(3), sem trywait(3), sem wait(3)

STANDARDS

The sem timedwait() function conforms to IEEE Std 1003.1-2004 (“POSIX.1”).

Systems/C C Library 411

Page 430: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

SEM WAIT(3)

NAME

sem wait, sem trywait – decrement (lock) a semaphore

SYNOPSIS

#include <semaphore.h>

intsem_wait(sem_t *sem);

intsem_trywait(sem_t *sem);

DESCRIPTION

The sem wait() function decrements (locks) the semaphore pointed to by sem, butblocks if the value of sem is zero, until the value is non-zero and the value can bedecremented.

The sem trywait() function decrements (locks) the semaphore pointed to by semonly if the value is non-zero. Otherwise, the semaphore is not decremented and anerror is returned.

RETURN VALUES

Upon successful completion, the value 0 is returned; otherwise the value -1 is re-turned and the global variable errno is set to indicate the error.

ERRORS

The sem wait() and sem trywait() functions will fail if:

[EINVAL] The sem argument points to an invalid semaphore.

Additionally, sem trywait() will fail if:

[EAGAIN] The semaphore value was zero, and thus could not be decremented.

412 Systems/C C Library

Page 431: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

SEE ALSO

sem getvalue(3), sem post(3)

STANDARDS

The sem wait() and sem trywait() functions conform to ISO/IEC 9945-1:1996(“POSIX.1”).

Systems/C C Library 413

Page 432: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

SIGNAL(3)

NAME

signal – simplified software signal facilities

SYNOPSIS

#include <signal.h>

void (*signal(int sig, void (*func)(int)))(int);

or in Dignus’s equivalent but easier to read typedef’d version:

typedef void (*sig_t) (int); sig_tsignal(int sig, sig_t func);

DESCRIPTION

This signal() facility is a simplified interface to the more general sigaction(2) facility.

Signals allow the manipulation of a process from outside its domain as well asallowing the process to manipulate itself or copies of itself (children). There aretwo general types of signals: those that cause termination of a process and thosethat do not. Signals which cause termination of a program might result from anirrecoverable error or might be the result of a user at a terminal typing the ‘interrupt’character. Signals are used when a process is stopped because it wishes to access itscontrol terminal while in the background. Signals are optionally generated when aprocess resumes after being stopped, when the status of child processes changes, orwhen input is ready at the control terminal. Most signals result in the terminationof the process receiving them if no action is taken; some signals instead cause theprocess receiving them to be stopped, or are simply discarded if the process has notrequested otherwise. Except for the SIGKILL and SIGSTOP signals, the signal()function allows for a signal to be caught, to be ignored, or to generate an interrupt.These signals are defined in the file <signal.h>:

No Name Default Action Description1 SIGHUP terminate process terminal line hangup2 SIGINT terminate process interrupt program3 SIGQUIT create core image quit program4 SIGILL create core image illegal instruction5 SIGTRAP create core image trace trap

414 Systems/C C Library

Page 433: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

6 SIGABRT create core image abort program (formerly SIGIOT)7 SIGEMT create core image emulate instruction executed8 SIGFPE create core image floating-point exception9 SIGKILL terminate process kill program10 SIGBUS create core image bus error11 SIGSEGV create core image segmentation violation12 SIGSYS create core image non-existent system call invoked13 SIGPIPE terminate process write on a pipe with no reader14 SIGALRM terminate process real-time timer expired15 SIGTERM terminate process software termination signal16 SIGURG discard signal urgent condition present on

socket17 SIGSTOP stop process stop (cannot be caught or

ignored)18 SIGTSTP stop process stop signal generated from

keyboard19 SIGCONT discard signal continue after stop20 SIGCHLD discard signal child status has changed21 SIGTTIN stop process background read attempted from

control terminal22 SIGTTOU stop process background write attempted to

control terminal23 SIGIO discard signal I/O is possible on a descriptor

(see \manref{fcntl}{2})24 SIGXCPU terminate process cpu time limit exceeded (see

\manref{setrlimit}{2})25 SIGXFSZ terminate process file size limit exceeded (see

\manref{setrlimit}{2}))26 SIGVTALRM terminate process virtual time alarm (see

setitimer(2) - unavailable)27 SIGPROF terminate process profiling timer alarm (see

setitimer(2) - unavailable)28 SIGWINCH discard signal Window size change29 SIGINFO discard signal status request from keyboard30 SIGUSR1 terminate process User defined signal 131 SIGUSR2 terminate process User defined signal 232 SIGTHR terminate process thread interrupt33 SIGDANGER terminate process34 SIGTHSTOP terminate process thread interrupt35 SIGTHCONT terminate process thread interrupt37 SIGTRACE terminate process38 SIGDCE terminate process39 SIGDUMP terminate process40 SIGABND terminate process ABEND encountered51 SIGPOLL terminate process52 SIGIOERR terminate process

Systems/C C Library 415

Page 434: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

The sig argument specifies which signal was received. The func procedure allows auser to choose the action upon receipt of a signal. To set the default action of thesignal to occur as listed above, func should be SIG DFL. A SIG DFL resets the defaultaction. To ignore the signal func should be SIG IGN. This will cause subsequentinstances of the signal to be ignored and pending instances to be discarded. IfSIG IGN is not used, further occurrences of the signal are automatically blocked andfunc is called.

The handled signal is unblocked when the function returns and the process continuesfrom where it left off when the signal occurred. Unlike previous signal facilities, thehandler func() remains installed after a signal has been delivered.

For some system calls, if a signal is caught while the call is executing and thecall is prematurely terminated, the call is automatically restarted. (The handler isinstalled using the SA RESTART flag with sigaction(2).)

When a process which has installed signal handlers forks, the child process inheritsthe signals. All caught signals may be reset to their default action by a call to theexecve(2) function; ignored signals remain ignored.

If a process explicitly specifies SIG IGN as the action for the signal SIGCHLD, thesystem will not create zombie processes when children of the calling process exit.As a consequence, the system will discard the exit status from the child processes.If the calling process subsequently issues a call to wait(2) or equivalent, it will blockuntil all of the calling process’s children terminate, and then return a value of -1with errno set to ECHILD.

See sigaction(2) for a list of functions that are considered safe for use in signalhandlers.

RETURN VALUES

The previous action is returned on a successful call. Otherwise, SIG ERR is returnedand the global variable errno is set to indicate the error.

ERRORS

The signal() function will fail and no action will take place if one of the followingoccur:

errlist

[EINVAL] The sig argument is not a valid signal number.

[EINVAL] An attempt is made to ignore or supply a handler for SIGKILL,SIGSTOP or SIGABND.

416 Systems/C C Library

Page 435: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

IMPLEMENTATION

signal() is implemented using the sigaction(2) facility.

For more information about POSIX signals and how that interacts with the Dignusruntime environment, see sigaction(2).

SEE ALSO

kill(1), kill(2), ptrace(2), sigaction(2), sigaltstack(2), sigprocmask(2), sigsuspend(2),wait(2), fpsetmask(3), setjmp(3), siginterrupt(3), tty(4)

Systems/C C Library 417

Page 436: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

SIGSETOPS(3)

NAME

sigemptyset, sigfillset, sigaddset, sigdelset, sigismember – manipulate signal sets

SYNOPSIS

#include <signal.h>

intsigemptyset(sigset_t *set);

intsigfillset(sigset_t *set);

intsigaddset(sigset_t *set, int signo);

intsigdelset(sigset_t *set, int signo);

intsigismember(const sigset_t *set, int signo);

DESCRIPTION

These functions manipulate signal sets stored in a sigset t. Either sigemptyset()or sigfillset() must be called for every object of type sigset t before any otheruse of the object.

The sigemptyset() function initializes a signal set to be empty.

The sigfillset() function initializes a signal set to contain all signals.

The sigdelset() function deletes the specified signal signo from the signal set.

The sigismember() function returns whether a specified signal signo is containedin the signal set.

RETURN VALUES

The sigismember() function returns 1 if the signal is a member of the set, 0otherwise. The other functions return 0 upon success. A -1 return value indicatesan error occurred and the global variable errno is set to indicate the reason.

418 Systems/C C Library

Page 437: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

ERRORS

These functions could fail if one of the following occurs:

[EINVAL] signo has an invalid value.

SEE ALSO

kill(2), sigaction(2), sigpending(2), sigprocmask(2), sigsuspend(2)

STANDARDS

These functions are defined by IEEE Std 1003.1-1988 (“POSIX.1”).

Systems/C C Library 419

Page 438: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

SETJMP(3)

NAME

sigsetjmp, siglongjmp, setjmp, longjmp, setjmp, longjmp - non-local jumps

SYNOPSIS

#include <setjmp.h>

intsigsetjmp(sigjmp_buf env, int savemask);

voidsiglongjmp(sigjmp_buf env, int val);

intsetjmp(jmp_buf env);

voidlongjmp(jmp_buf env, int val);

int_setjmp(jmp_buf env);

void_longjmp(jmp_buf env, int val);

DESCRIPTION

The sigsetjmp(), setjmp(), and setjmp() functions save their calling environ-ment in env. Each of these functions returns 0.

The corresponding longjmp() functions restore the environment saved by theirmost recent respective invocations of the setjmp() function. They then return sothat program execution continues as if the corresponding invocation of the setjmp()call had just returned the value specified by val, instead of 0.

Pairs of calls may be intermixed, i.e., both sigsetjmp() and siglongjmp() andsetjmp() and longjmp() combinations may be used in the same program, however,individual calls may not, e.g. the env argument to setjmp() may not be passed tosiglongjmp().

The longjmp() routines may not be called after the routine which called thesetjmp() routines returns.

420 Systems/C C Library

Page 439: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

All accessible objects have values as of the time longjmp() routine was called,except that the values of objects of automatic storage invocation duration thatdo not have the volatile type and have been changed between the setjmp()invocation and longjmp() call are indeterminate.

The setjmp()/longjmp() pairs save and restore the signal mask whilesetjmp()/ longjmp() pairs save and restore only the register set and the stack.

(See sigprocmask(2).)

The sigsetjmp()/siglongjmp() function pairs save and restore the signal mask ifthe argument savemask is non-zero, otherwise only the register set and the stack aresaved.

SEE ALSO

sigaction(2), sigaltstack(2), signal(3)

STANDARDS

The setjmp() and longjmp() functions conform to ISO/IEC 9899:1990 (“ISOC90”). The sigsetjmp() and siglongjmp() functions conform to IEEE Std 1003.1-1988 (“POSIX.1”).

Systems/C C Library 421

Page 440: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

SLEEP(3)

NAME

sleep – suspend process execution for an interval measured in seconds

SYNOPSIS

#include <unistd.h>

unsigned intsleep(unsigned int seconds);

DESCRIPTION

The sleep() function suspends execution of the calling process until either secondsseconds have elapsed or a signal is delivered to the process and its action is to invokea signal-catching function or to terminate the process. System activity may lengthenthe sleep by an indeterminate amount.

In the USS/POSIX environment, this function is implemented directly via theBPX1SLP/BPX4SLP functions, in a batch or TSO environment this function isimplemented with a select() call with a specified timeout value. This allows for useof the SIGALRM signal in USS/POSIX environments.

RETURN VALUES

In USS/POSIX environments, if the sleep() function returns because the requestedtime has elapsed, the value returned will be zero. If the sleep() function returnsdue to the delivery of a signal, the value returned will be the unslept amount (therequested time minus the time actually slept) in seconds.

In batch or TSO environments, sleep() always returns 0.

STANDARDS

The sleep() function conforms to ISO/IEC 9945-1:1990 (“POSIX.1”).

422 Systems/C C Library

Page 441: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

SYSCONF(3)

NAME

sysconf - get configurable system variables

SYNOPSIS

#include <unistd.h>

longsysconf(int name);

DESCRIPTION

This interface is defined by IEEE Std 1003.1-1988 (“POSIX.1”). This implementa-tion does not support all of the POSIX-defined function, but a limited subset.

The sysconf() function provides a method for applications to determine the currentvalue of a configurable system limit or option variable. The name argument specifiesthe system variable to be queried. Symbolic constants for each name value are foundin the include file <unistd.h>.

The available values in this implementation are:

SC CHILD MAX Returns zero for the Systems/C runtime.

SC CLK TCK The frequency of the statistics clock in ticks per second.

SC OPEN MAX The maximum number of open files.

RETURN VALUES

If the call to sysconf() is not successful, -1 is returned and errno is set appropri-ately. Otherwise, if the variable is associated with functionality that is not sup-ported, -1 is returned and errno is not modified. Otherwise, the current variablevalue is returned.

ERRORS

The sysconf() function may fail and set errno if the library cannot determine avalue. In addition, the following error may be reported:

[EINVAL] The value of the name argument is invalid.

Systems/C C Library 423

Page 442: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

SEE ALSO

getdtablesize(2)

ISSUES

The Systems/C sysconf() implementation is not POSIX conforming.

424 Systems/C C Library

Page 443: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

TCGETPGRP(3)

NAME

tcgetpgrp - get foreground process group ID

SYNOPSIS

#include <sys/types.h>#include <unistd.h>

pid_ttcgetpgrp(int fd);

DESCRIPTION

The tcgetpgrp() function returns the value of the process group ID of the fore-ground process group associated with the terminal device. If there is no foregroundprocess group, tcgetpgrp() returns an invalid process ID.

ERRORS

If an error occurs, tcgetpgrp() returns -1 and the global variable errno is set toindicate the error, as follows:

[EBADF] The fd argument is not a valid file descriptor.

[ENOTTY] The calling process does not have a controlling termi nal or theunderlying terminal device represented by fd is not the controllingterminal.

SEE ALSO

setpgid(2), setsid(2), tcsetpgrp(3)

STANDARDS

The tcgetpgrp() function is expected to be compliant with the IEEE Std 1003.1-1988 (“POSIX.1”) specification.

Systems/C C Library 425

Page 444: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

TCSENDBREAK(3)

NAME

tcsendbreak, tcdrain, tcflush, tcflow - line control functions

SYNOPSIS

#include <termios.h>

inttcdrain(int fd);

inttcflow(int fd, int action);

inttcflush(int fd, int action);

inttcsendbreak(int fd, int len);

DESCRIPTION

The tcdrain() function waits until all output written to the terminal referenced byfd has been transmitted to the terminal.

The tcflow() function suspends transmission of data to or the reception of datafrom the terminal referenced by fd depending on the value of action. The value ofaction must be one of the following:

TCOFF Suspend output.

TCOON Restart suspended output.

TCIOFF Transmit a STOP character, which is intended to cause the terminalto stop transmitting data to the system.

TCION Transmit a START character, which is intended to cause the termi-nal to start transmitting data to the system.

The tcflush() function discards any data written to the terminal referenced byfd which has not been transmitted to the terminal, or any data received from theterminal but not yet read, depending on the value of action. The value of actionmust be one of the following:

426 Systems/C C Library

Page 445: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

TCIFLUSH Flush data received but not read.

TCOFLUSH Flush data written but not transmitted.

TCIOFLUSH Flush both data received but not read and data written but nottransmitted.

The tcsendbreak() function transmits a continuous stream of zero-valued bits forthe specified len to the terminal referenced by fd.

RETURN VALUES

Upon successful completion, all of these functions return a value of zero.

ERRORS

If any error occurs, a value of -1 is returned and the global variable errno is set toindicate the error, as follows:

[EBADF] The fd argument is not a valid file descriptor.

[EINVAL] The action argument is not a proper value.

[ENOTTY] The file associated with fd is not a terminal.

[EINTR] A signal interrupted the tcdrain() function.

SEE ALSO

tcsetattr(3)

STANDARDS

The tcsendbreak(), tcdrain(), tcflush() and tcflow() functions are expected tobe compliant with the IEEE Std 1003.1-1988 (“POSIX.1”) specification.

Systems/C C Library 427

Page 446: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

TCSETATTR(3)

NAME

cfgetispeed, cfsetispeed, cfgetospeed, cfsetospeed, cfsetspeed, cfmakeraw, tcgetattr,tcsetattr - manipulating the termios structure

SYNOPSIS

#include <termios.h>

speed_tcfgetispeed(const struct termios *t);

intcfsetispeed(struct termios *t, speed_t speed);

speed_tcfgetospeed(const struct termios *t);

intcfsetospeed(struct termios *t, speed_t speed);

intcfsetspeed(struct termios *t, speed_t speed);

voidcfmakeraw(struct termios *t);

inttcgetattr(int fd, struct termios *t);

inttcsetattr(int fd, int action, const struct termios *t);

DESCRIPTION

The cfmakeraw(), tcgetattr() and tcsetattr() functions are provided for gettingand setting the termios structure.

The cfgetispeed(), cfsetispeed(), cfgetospeed(), cfsetospeed() and cfset-speed() functions are provided for getting and setting the baud rate values inthe termios structure. The effects of the functions on the terminal as describedbelow do not become effective, nor are all errors detected, until the tcsetattr()

428 Systems/C C Library

Page 447: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

function is called. Certain values for baud rates set in the termios structure andpassed to tcsetattr() have special meanings. These are discussed in the portion ofthe manual page that describes the tcsetattr() function.

GETTING AND SETTING THE BAUD RATE

The input and output baud rates are found in the termios structure. The unsignedinteger speed t is typedef’d in the include file <termios.h>. The value of the integercorresponds directly to the baud rate being represented, however, the followingsymbolic values are defined.

#define B0 0#define B50 50#define B75 75#define B110 110#define B134 134#define B150 150#define B200 200#define B300 300#define B600 600#define B1200 1200#define B1800 1800#define B2400 2400#define B4800 4800#define B9600 9600#define B19200 19200#define B38400 38400#ifndef _POSIX_SOURCE#define EXTA 19200#define EXTB 38400#endif /*_POSIX_SOURCE */

The cfgetispeed() function returns the input baud rate in the termios structurereferenced by tp.

The cfsetispeed() function sets the input baud rate in the termios structure refer-enced by tp to speed.

The cfgetospeed() function returns the output baud rate in the termios structurereferenced by tp.

The cfsetospeed() function sets the output baud rate in the termios structurereferenced by tp to speed.

The cfsetspeed() function sets both the input and output baud rate in the termiosstructure referenced by tp to speed.

Systems/C C Library 429

Page 448: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

Upon successful completion, the functions cfsetispeed(), cfsetospeed(), and cf-setspeed() return a value of 0. Otherwise, a value of -1 is returned and the globalvariable errno is set to indicate the error.

GETTING AND SETTING THE TERMIOS STATE

This section describes the functions that are used to control the general terminalinterface. Unless otherwise noted for a specific command, these functions are re-stricted from use by background processes. Attempts to perform these operationsshall cause the process group to be sent a SIGTTOU signal. If the calling processis blocking or ignoring SIGTTOU signals, the process is allowed to perform theoperation and the SIGTTOU signal is not sent.

In all the functions, although fd is an open file descriptor, the functions affect theunderlying terminal file, not just the open file description associated with the par-ticular file descriptor.

The cfmakeraw() function sets the flags stored in the termios structure to a statedisabling all input and output processing, giving a “raw I/O path”. It should benoted that there is no function to reverse this effect. This is because there are avariety of processing options that could be re-enabled and the correct method is foran application to snapshot the current terminal state using the function tcgetattr(),setting raw mode with cfmakeraw() and the subsequent tcsetattr(), and thenusing another tcsetattr() with the saved state to revert to the previous terminalstate.

The tcgetattr() function copies the parameters associated with the terminal ref-erenced by fd in the termios structure referenced by tp. This function is allowedfrom a background process, however, the terminal attributes may be subsequentlychanged by a foreground process.

The tcsetattr() function sets the parameters associated with the terminal from thetermios structure referenced by tp. The action field is created by or’ing the followingvalues, as specified in the include file <termios.h>.

TCSANOW The change occurs immediately

TCSADRAIN The change occurs after all output written to fd has been trans-mitted to the terminal. This value of action should be used whenchanging parameters that affect output.

TCSAFLUSH The change occurs after all output written to fd has been transmit-ted to the terminal. Additionally, any input that has been receivedbut not read is discarded.

TCSASOFT If this value is or’ed into the action value, the values of c cflag,c ispeed, and c ospeedfields are ignored.

430 Systems/C C Library

Page 449: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

The 0 baud rate is used to terminate the connection. If 0 is specified as the outputspeed to the function tcsetattr(), modem control will no longer be asserted on theterminal, disconnecting the terminal.

If zero is specified as the input speed to the function tcsetattr(), the input baudrate will be set to the same value as that specified by the output baud rate.

If tcsetattr() is unable to make any of the requested changes, it returns -1 and setserrno. Otherwise, it makes all of the requested changes it can. If the specified inputand output baud rates differ and are a combination that is not supported, neitherbaud rate is changed.

Upon successful completion, the functions tcgetattr() and tcsetattr() return avalue of 0. Otherwise, they return -1 and the global variable errno is set to indicatethe error, as follows:

[EBADF] The fd argument to tcgetattr() or tcsetattr() was not a valid filedescriptor.

[EINTR] The tcsetattr() function was interuppted by a signal.

[EINVAL] The action argument to the tcsetattr() function was not valid,or an attempt was made to change an attribute represented in thetermios structure to an unsupported value.

[ENOTTY] The file associated with the fd argument to tcgetattr() or tcse-tattr() is not a terminal.

SEE ALSO

tcsendbreak(3)

STANDARDS

The cfgetispeed(), cfsetispeed(), cfgetospeed(), cfsetospeed(), tcgetattr()and tcsetattr() functions are expected to be compliant with the IEEE Std 1003.1-1988 (“POSIX.1”) specification. The cfmakeraw() and cfsetspeed() functions,as well as the TCSASOFT option to the tcsetattr() function are extensions to theIEEE Std 1003.1-1988 (“POSIX.1”) specification.

Systems/C C Library 431

Page 450: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

TCSETPGRP(3)

NAME

tcsetpgrp - set foreground process group ID

SYNOPSIS

#include <sys/types.h>#include <unistd.h>

inttcsetpgrp(int fd, pid_t pgrp_id);

DESCRIPTION

If the process has a controlling terminal, the tcsetpgrp() function sets the fore-ground process group ID associated with the terminal device to pgrp id. The termi-nal device associated with fd must be the controlling terminal of the calling processand the controlling terminal must be currently associated with the session of thecalling process. The value of pgrp id must be the same as the process group ID of aprocess in the same session as the calling process.

RETURN VALUES

The tcsetpgrp() function returns the value 0 if successful; otherwise the value -1is returned and the global variable errno is set to indicate the error.

ERRORS

The tcsetpgrp() function will fail if:

[EBADF] The fd argument is not a valid file descriptor.

[EINVAL] An invalid value of pgrp id was specified.

[ENOTTY] The calling process does not have a controlling terminal, or the filerepresented by fd is not the controlling terminal, or the control-ling terminal is no longer associated with the session of the callingprocess.

[EPERM] The pgrp id argument does not match the process group ID of aprocess in the same session as the calling process.

432 Systems/C C Library

Page 451: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

SEE ALSO

setpgid(2), setsid(2), tcgetpgrp(3)

STANDARDS

The tcsetpgrp() function is expected to be compliant with the IEEE Std 1003.1-1988 (“POSIX.1”) specification.

Systems/C C Library 433

Page 452: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

THRD CREATE(3)

NAME

call once, cnd broadcast, cnd destroy, cnd init, cnd signal, cnd timedwait,cnd wait, mtx destroy, mtx init, mtx lock, mtx timedlock, mtx trylock, mtx unlock,thrd create, thrd current, thrd detach, thrd equal, thrd exit, thrd join, thrd sleep,thrd yield, tss create, tss delete, tss get, tss set - C11 threads interface

SYNOPSIS

#include <threads.h>

voidcall_once(once_flag *flag, void (*func)(void));

intcnd_broadcast(cnd_t *cond);

voidcnd_destroy(cnd_t *cond);

intcnd_init(cnd_t *cond);

intcnd_signal(cnd_t *cond);

intcnd_timedwait(cnd_t * restrict cond, mtx_t * restrict mtx,

const struct timespec * restrict ts);

intcnd_wait(cnd_t *cond, mtx_t *mtx);

voidmtx_destroy(mtx_t *mtx);

intmtx_init(mtx_t *mtx, int type);

intmtx_lock(mtx_t *mtx);

intmtx_timedlock(mtx_t * restrict mtx, const struct timespec * restrict ts);

434 Systems/C C Library

Page 453: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

intmtx_trylock(mtx_t *mtx);

intmtx_unlock(mtx_t *mtx);

intthrd_create(thrd_t *thr, int (*func)(void *), void *arg);

thrd_tthrd_current(void);

intthrd_detach(thrd_t thr);

intthrd_equal(thrd_t thr0, thrd_t thr1);

_Noreturn voidthrd_exit(int res);

intthrd_join(thrd_t thr, int *res);

intthrd_sleep(const struct timespec *duration, struct timespec *remaining);

voidthrd_yield(void);

inttss_create(tss_t *key, void (*dtor)(void *));

voidtss_delete(tss_t key);

void *tss_get(tss_t key);

inttss_set(tss_t key, void *val);

Systems/C C Library 435

Page 454: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

DESCRIPTION

As of ISO/IEC 9899:2011 (“ISO C11”), the C standard includes an API for writingmultithreaded applications. Since POSIX.1 already includes a threading API thatis used by virtually any multithreaded application, the interface provided by the Cstandard can be considered superfluous.

In this implementation, the threading interface is therefore implemented as a light-weight layer on top of existing interfaces. The functions to which these routines aremapped, are listed in the following table. Please refer to the documentation of thePOSIX equivalent functions for more information.

Function POSIX equivalent

call once() pthread once(3)

cnd broadcast() pthread cond broadcast(3)

cnd destroy() pthread cond destroy(3)

cnd init() pthread cond init(3)

cnd signal() pthread cond signal(3)

cnd timedwait() pthread cond timedwait(3)

cnd wait() pthread cond wait(3)

mtx destroy() pthread mutex destroy(3)

mtx init() pthread mutex init(3)

mtx lock() pthread mutex lock(3)

mtx timedlock() pthread mutex timedlock(3)

mtx trylock() pthread mutex trylock(3)

mtx unlock() pthread mutex unlock(3)

thrd create() pthread create(3)

thrd current() pthread self(3)

thrd detach() pthread detach(3)

thrd equal() pthread equal(3)

thrd exit() pthread exit(3)

thrd join() pthread join(3)

thrd sleep() nanosleep(2)

436 Systems/C C Library

Page 455: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

thrd yield() pthread yield(3)

tss create() pthread key create(3)

tss delete() pthread key delete(3)

tss get() pthread getspecific(3)

tss set() pthread setspecific(3)

DIFFERENCES WITH POSIX EQUIVALENTS

The thrd exit() function returns an integer value to the thread calling thrd join(),whereas the pthread exit() function uses a pointer.

The mutex created by mtx init() can be of type mtx plain or mtx timed to dis-tinguish between a mutex that supports mtx timedlock(). This type can be or’dwith mtx recursive to create a mutex that allows recursive acquisition. Theseproperties are normally set using pthread mutex init()’s attr parameter.

RETURN VALUES

If successful, the cnd broadcast(), cnd init(), cnd signal(), cnd timedwait(),cnd wait(), mtx init(), mtx lock(), mtx timedlock(), mtx trylock(),mtx unlock(), thrd create(), thrd detach(), thrd equal(), thrd join(),thrd sleep(), tss create() and tss set() functions return thrd success. Oth-erwise an error code will be returned to indicate the error.

The thrd current() function returns the thread ID of the calling thread.

The tss get() function returns the thread-specific data value associated with thegiven key. If no thread-specific data value is associated with key, then the valueNULL is returned.

ERRORS

The cnd init() and thrd create() functions will fail if:

thrd nonmem The system has insufficient memory.

The cnd timedwait() and mtx timedlock() functions will fail if:

thrd timedout The system time has reached or exceeded the time specified in tsbefore the operation could be completed.

Systems/C C Library 437

Page 456: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

The mtx trylock() function will fail if:

thrd busy The mutex is already locked.

In all other cases, these functions may fail by returning general error codethrd error.

SEE ALSO

nanosleep(2), pthread(3)

STANDARDS

These functions are expected to conform to ISO/IEC 9899:2011 (“ISO C11”).

438 Systems/C C Library

Page 457: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

TIME(3)

NAME

time - get time of day

SYNOPSIS

#include <time.h>

time_ttime(time_t *tloc)

DESCRIPTION

The time() function returns the value of time in seconds since 0 hours, 0 minutes,0 seconds, January 1, 1970, Coordinated Universal Time.

A copy of the time value may be saved to the area indicated by the pointer tloc. Iftloc is a NULL pointer, no value is stored.

Upon successful completion, time() returns the value of time. Otherwise a valueof ((time t) -1) is returned and the global variable errno is set to indicate theerror.

ERRORS

The following error codes may be set in errno:

[EFAULT] An argument address referenced invalid memory.

SEE ALSO

gettimeofday(2), ctime(3)

Systems/C C Library 439

Page 458: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

TIMES(3)

NAME

times - process times

SYNOPSIS

#include <sys/times.h>

clock_ttimes(struct tms *tp);

DESCRIPTION

This interface is obsoleted by getrusage(2) and gettimeofday(2).

The times() function returns the value of time in CLK TCK’s of a second since 0hours, 0 minutes, 0 seconds, January 1, 1970, Coordinated Universal Time.

It also fills in the structure pointed to by tp with time-accounting information.

The tms structure is defined as follows:

struct tms {clock_t tms_utime;clock_t tms_stime;clock_t tms_cutime;clock_t tms_cstime;

};

The elements of this structure are defined as follows:

tms utime The CPU time charged for the execution of user instructions.

tms stime The CPU time charged for execution by the system on behalf of theprocess.

tms cutime The sum of the tms utimes and tms cutimes of the child processes.

tms cstime The sum of the tms stimes and tms cstimes of the child processes.

All times are in CLK TCK’s of a second.

If an error occurs, times() returns the value ((clock t)-1), and sets errno toindicate the error.

440 Systems/C C Library

Page 459: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

ERRORS

The times() function may fail and set the global variable errno for any of the errorsspecified for the library routines getrusage(2) and gettimeofday(2).

SEE ALSO

getrusage(2), gettimeofday(2), wait(2)

STANDARDS

The times() function conforms to IEEE Std 1003.1-1988 (“POSIX.1”) as closely asthe host system allows.

Systems/C C Library 441

Page 460: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

TIMEZONE(3)

NAME

timezone - return the timezone abbreviation

SYNOPSIS

char *timezone(int zone, int dst);

DESCRIPTION

This interface is for compatibility only; it is impossible to reliably map timezone’sarguments to a time zone abbreviation. See ctime(3).

The timezone() function returns a pointer to a time zone abbreviation for thespecified zone and dst values. Zone is the number of minutes west of GMT and dstis non-zero if daylight savings time is in effect.

SEE ALSO

ctime(3)

442 Systems/C C Library

Page 461: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

TPUT(3)

NAME

tput - issue the TPUT macro

SYNOPSIS

#include <machine/tput.h>void__tput(int len, char *buffer)

DESCRIPTION

The tput() function invokes the z/OS TPUT macro, passing the given length lenand buffer address buffer.

Consult the IBM documentation for the TPUT macro for more information.

Systems/C C Library 443

Page 462: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

TRACEBACK(3)

NAME

traceback - provide a function traceback

SYNOPSIS

#include <stdio.h>#include <machine/trcback.h>

void__traceback(FILE *f);

void__tbfrom(void *stack_ptr, void message(char *, void *), void *user_data);

DESCRIPTION

The traceback() function provides a function-level traceback of the call stackfrom the calling function.

traceback() writes the traceback on the file descriptor specified by f. The trace-back information is kept in the Systems/C pre-prologue area. The traceback()function walks the stack frame backwards, printing the name found in the per-prologue area.

The tbfrom() function provides a user-controlled mechanism to access the trace-back. The tbfrom() function will invoke the message function for each line oftraceback information generated. The first parameter to the message function will bea NUL-terminated character string. The 2nd parameter will be the value of user datapassed into tbfrom(). The stack ptr parameter to tbfrom() is the stack pointerwhere the traceback should begin. Typically this is the current register 13.

For example, the traceback() function can be implemented as:

#include <machine/trcback.h>#include <stdio.h>#include <stdlib.h>

/** one_line()* Print one line to the the FILE pointer* passed in a user-data

444 Systems/C C Library

Page 463: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

**/static voidone_line(char *mess, void *user){

FILE *fp;

fp = (FILE *)user;fprintf(fp, "%s\n", mess);fflush(fp);

}

voidtraceback(FILE *f){

__register(13) void *r13; /* current stack pointer */

__tbfrom(r13, one_line, f);}

SEE ALSO

funopen(3), fopen(3)

Systems/C C Library 445

Page 464: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

TSEARCH(3)

NAME

tsearch, tfind, tdelete, twalk – manipulate binary search trees

SYNOPSIS

#include <search.h>

void *tdelete(const void *key, void **rootp,

int (*compar) (const void *, const void *));

void *tfind(const void *key, void **rootp,

int (*compar) (const void *, const void *));

void *tsearch(const void *key, void **rootp,

int (*compar) (const void *, const void *));

voidtwalk(const void *root, void (*compar) (const void *, VISIT, int));

DESCRIPTION

The tdelete(), tfind(), tsearch(), and twalk() functions manage binary searchtrees based on algorithms T and D from Knuth (6.2.2). The comparison functionpassed in by the user has the same style of return values as strcmp(3).

tfind() searches for the datum matched by the argument key in the binary treerooted at rootp, returning a pointer to the datum if it is found and NULL if it is not.

tsearch() is identical to tfind() except that if no match is found, key is insertedinto the tree and a pointer to it is returned. If rootp points to a NULL value a newbinary search tree is created.

tdelete() deletes a node from the specified binary search tree and returns a pointerto the parent of the node to be deleted. It takes the same arguments as tfind() andtsearch(). If the node to be deleted is the root of the binary search tree, rootp willbe adjusted.

twalk() walks the binary search tree rooted in root and calls the function action oneach node. Action is called with three arguments: a pointer to the current node,

446 Systems/C C Library

Page 465: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

a value from the enum typedef enum { preorder, postorder, endorder, leaf} VISIT; specifying the traversal type, and a node level (where level zero is theroot of the tree).

SEE ALSO

bsearch(3), hsearch(3), lsearch(3)

RETURN VALUES

The tsearch() function returns NULL if allocation of a new node fails (usually dueto a lack of free memory).

tfind(), tsearch(), and tdelete() functions return NULL if rootp is NULL or thedatum cannot be found.

The twalk() function returns no value.

Systems/C C Library 447

Page 466: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

TTYNAME(3)

NAME

ttyname - get name of associated terminal (tty) from file descriptor

SYNOPSIS

#include <unistd.h>

char *ttyname(int fd);

DESCRIPTION

The ttyname() function operates on the system file descriptors for terminal typedevices. These descriptors are not related to the standard I/O FILE typedef, butrefer to the special device files found in /dev and named /dev/ttyxx

The ttyname() function gets the related device name of a file descriptor for whichisatty() is true, and the file descriptor is associated with an //HFS:-style file.isatty() can return true for non-//HFS: files when the DCB indicates that the file isassociated with a TSO terminal.

RETURN VALUES

The ttyname() function returns the null terminated name if the device is foundand isatty() is true, and the file descriptor is an //HFS:-style file; otherwise a NULLpointer is returned.

ISSUES

The ttyname() function leaves its result in an internal static object and returns apointer to that object. Subsequent calls to ttyname() will modify the same object.

448 Systems/C C Library

Page 467: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

UCONTEXT(3)

NAME

ucontext – user thread context

SYNOPSIS

#include <ucontext.h>

DESCRIPTION

The ucontext t type is a structure type suitable for holding the context for a userthread of execution. A thread’s context includes its stack, saved registers, and listof blocked signals.

The ucontext t structure contains at least these fields:

ucontext t *uc link context to assume when this one returns

sigset t uc sigmask signals being blocked

stack t uc stack stack area

mcontext t uc mcontext saved registers

The uc link field points to the context to resume when this context’s entry pointfunction returns. If uc link is equal to NULL, then the program exits when thiscontext returns.

The uc mcontext field is machine-dependent and should be treated as opaque byportable applications.

The following functions are defined to manipulate ucontext t structures:

int getcontext(ucontext_t *);int setcontext(const ucontext_t *);void makecontext(ucontext_t *, void (*)(void), int, ...);int swapcontext(ucontext_t *, const ucontext_t *);

SEE ALSO

sigaltstack(2), getcontext(3), makecontext(3)

Systems/C C Library 449

Page 468: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

UNAME(3)

NAME

uname - get system identification

SYNOPSIS

#include <sys/utsname.h>

intuname(struct utsname *name);

DESCRIPTION

The uname() function stores nul-terminated strings of information identifying thecurrent system into the structure referenced by name.

The utsname struction is defined in the <sys/utsname.h> header file, and containsthe following members:

sysname Name of the operating system implementation.

nodename Network name of this machine.

release Release level of the operating system.

version Version level of the operating system.

machine Machine hardware platform.

RETURN VALUES

The unname() function returns the value 0 if successful; otherwise the value -1 isreturned and the global variable errno is set to indicate the error.

The only error value possible from uname() is ENOSYS, which can occur if OpenEdi-tion services are not available.

STANDARDS

The uname() function conforms to IEEE Std 1003.1-1988 (“POSIX.1”) as closelyas the host system allows.

450 Systems/C C Library

Page 469: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

USLEEP(3)

NAME

usleep – suspend process execution for an interval measured in microseconds

SYNOPSIS

#include <unistd.h>

intusleep(useconds_t microseconds);

DESCRIPTION

The usleep() function suspends execution of the calling process until either mi-croseconds microseconds have elapsed or a signal is delivered to the process and itsaction is to invoke a signal-catching function or to terminate the process. Systemactivity may lengthen the sleep by an indeterminate amount.

This function is implemented using nanosleep(2) by pausing for microseconds mi-croseconds or until a signal occurs. Consequently, in this implementation, sleepinghas no effect on the state of process timers, and there is no special handling forSIGALRM.

RETURN VALUES

The usleep() function returns the value 0 if successful; otherwise the value -1 isreturned and the global variable errno is set to indicate the error.

ERRORS

The usleep() function will fail if:

[EINTR] A signal was delivered to the process and its action was to invoke asignal-catching function.

SEE ALSO

nanosleep(2), sleep(3)

Systems/C C Library 451

Page 470: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

UTIME(3)

NAME

utime - set //HFS:-style file times

SYNOPSIS

#include <sys/types.h>#include <utime.h>

intutime(const char *file, const struct utimbuf *timep);

DESCRIPTION

This interface is obsoleted by utimes(2).

The utime() function sets the access and modification times of the named file fromthe structures in the argument array timep.

If the times are specified (the timep argument is non-NULL) the caller must be theowner of the file or be the super-user.

If the times are not specified (the timep argument is NULL) the caller must be theowner of the file, have permission to write the file, or be the super-user.

ERRORS

The utime() function may fail and set errno for any of the errors specified for thelibrary function utimes(2).

SEE ALSO

stat(2), utimes(2)

STANDARDS

The utime() function conforms to IEEE Std 1003.1-1988 (“POSIX.1”).

452 Systems/C C Library

Page 471: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

WORDEXP(3)

NAME

wordexp - perform shell-style word expansions

SYNOPSIS

#include <wordexp.h>

intwordexp(const char * restrict words, wordexp_t * restrict we, int flags);

voidwordfree(wordexp_t *we);

DESCRIPTION

The wordexp() function performs shell-style word expansion on words and placesthe list of words into the we wordv member of we, and the number of words intowe wordc.

The flags argument is the bitwise inclusive OR of any of the following constants:

WRDE APPEND Append the words to those generated by a previous call to word-exp().

WRDE DOOFFS As many NULL pointers as are specified by the we offs memberof we are added to the front of we wordv.

WRDE NOCMD Disallow command substitution in words. See the note in ISSUESbefore using this.

WRDE REUSE The we argument was passed to a previous successful call towordexp() but has not been passed to wordfree(). The im-plementation may reuse the space allocated to it.

WRDE SHOWERR Do not redirect shell error messages to /dev/null.

WRDE UNDEF Report error on an attempt to expand an undefined shell variable.

The wordexp t structure is defined in <wordexp.h> as:

Systems/C C Library 453

Page 472: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

typedef struct {size_t we_wordc; /* count of words matched */char **we_wordv; /* pointer to list of words */size_t we_offs; /* slots to reserve in we_wordv */

} wordexp_t;

The wordfree() function frees the memory allocated by wordexp().

IMPLEMENTATION NOTES

The wordexp() function is implemented as a wrapper around an invocation of thePOSIX shell.

RETURN VALUES

The wordexp() function returns zero if successful, otherwise it returns one of thefollowing error codes:

WRDE BADCHAR The words argument contains one of the following unquoted char-acters: <newline>, ‘|’, ‘&’, ‘;’, ‘<’, ‘>’, ‘(’, ‘)’, ‘{’, ‘}’.

WRDE BADVAL An attempt was made to expand an undefined shell variable andWRDE UNDEF is set in flags.

WRDE CMDSUB An attempt was made to use command substitution andWRDE NOCMD is set in flags.

WRDE NOSPACE Not enough memory to store the result.

WRDE NOSYS Functionality not supported on this system, errno will also beset to ENOSYS enough memory to store the result.

WRDE SYNTAX Shell syntax error in words.

The wordfree() function returns no value.

ENVIRONMENT

IFS Field separator.

454 Systems/C C Library

Page 473: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

EXAMPLES

Invoke the editor on all .c files in the current directory and /etc/motd (error checkingomitted):

wordexp_t we;

wordexp("${EDITOR:-vi} *.c /etc/motd", &we, 0);execvp(we.we_wordv[0], we.we_wordv);

DIAGNOSTICS

Diagnostic messages from the shell are written to the standard error output ifWRDE SHOWERR is set in flags.

SEE ALSO

fnmatch(3), glob(3), popen(3), system(3)

STANDARDS

The wordexp() and wordfree() functions conform to IEEE Std 1003.1-2001(“POSIX.1”).

ISSUES

Do not pass untrusted user data to wordexp(), regardless of whether theWRDE NOCMD flag is set. The wordexp() function attempts to detect input thatwould cause commands to be executed before passing it to the shell but it does notuse the same parser so it may be fooled.

The current wordexp() implementation does not recognize multibyte characters,since the shell (which it invokes to perform expansions) does not.

Systems/C C Library 455

Page 474: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

WTO(3)

NAME

wto - issue the WTO macro

SYNOPSIS

#include <machine/wto.h>void__wto(int len, char *buffer)

DESCRIPTION

The wto() function invokes the z/OS WTO macro, passing the given length lenand buffer address buffer.

Consult the IBM documentation for the WTO macro for more information.

456 Systems/C C Library

Page 475: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

Locale Library

The locale library provides functions for manipulating character values in a localespecific fashion. It provides functions that define the locale, test various charactervalues for belong to specific classes of characters and formatting various items basedon the locale setting.

Systems/C C Library 457

Page 476: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

BTOWC(3)

NAME

btowc, wctob - convert between wide and single-byte characters

SYNOPSIS

#include <wchar.h>

wint_tbtowc(int c);

intwctob(wint_t c);

DESCRIPTION

The btowc() function converts a single-byte character into a correspond- ing widecharacter. If the character is EOF or not valid in the initial shift state, btowc()returns WEOF.

The wctob() function converts a wide character into a corresponding sin- gle-bytecharacter. If the wide character is WEOF or not able to be rep- resented as a singlebyte in the initial shift state, wctob() returns WEOF.

SEE ALSO

mbrtowc(3), multibyte(3), wcrtomb(3)

STANDARDS

The btowc() and wctob() functions conform to IEEE Std 1003.1-2001(“POSIX.1”).

458 Systems/C C Library

Page 477: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

CTYPE(3)

NAME

isalnum, isalpha, isascii, isblank, iscntrl, isdigit, isgraph, islower, isprint, ispunct,isspace, isupper, isxdigit, toascii tolower, toupper, - character classification macros

SYNOPSIS

#include <ctype.h>

intisalnum(int c)

intisalpha(int c)

intisascii(int c)

intiscntrl(int c)

intisdigit(int c)

intisgraph(int c)

intislower(int c)

intisprint(int c)

intispunct(int c)

intisspace(int c)

intisupper(int c)

intisxdigit(int c)

Systems/C C Library 459

Page 478: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

inttoascii(int c)

inttolower(int c)

inttoupper(int c)

DESCRIPTION

The above functions perform character tests and conversions on the integer c. Theyare available as macros, defined in the include file ¡ctype.h¿, or as true functions inthe C library. See the specific manual pages for more information.

SEE ALSO

isalnum(3), isalpha(3), isascii(3), isblank(3), iscntrl(3), isdigit(3), isgraph(3),islower(3), isprint(3), ispunct(3), isspace(3), isupper(3), isxdigit(3), toascii(3),tolower(3), toupper(3)

STANDARDS

These functions, except for isblank(), toupper(), tolower() and toascii(), con-form to ISO/IEC 9899:1990 (“ISO C90”).

460 Systems/C C Library

Page 479: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

ISALNUM(3)

NAME

isalnum - alphanumeric character test

SYNOPSIS

#include <ctype.h>

intisalnum(int c)

DESCRIPTION

The isalnum() function tests for any character for which isalpha(3) or isdigit(3) istrue.

RETURN VALUES

The isalnum() function returns zero if the character tests false and returns non-zeroif the character tests true.

SEE ALSO

ctype(3), isalpha(3), isdigit(3)

STANDARDS

The isalnum() function conforms to ISO/IEC 9899:1990 (“ISO C90”).

Systems/C C Library 461

Page 480: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

ISALPHA(3)

NAME

isalpha - alphabetic character test

SYNOPSIS

#include <ctype.h>

intisalpha(int c)

DESCRIPTION

The isalpha() function tests for any character for which isupper(3) or slower(3) istrue.

RETURN VALUES

The isalpha() function returns zero if the character tests false and returns non-zeroif the character tests true.

SEE ALSO

ctype(3), islower(3), isupper(3)

STANDARDS

The isalpha() function conforms to ISO/IEC 9899:1990 (“ISO C90”).

462 Systems/C C Library

Page 481: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

ISASCII(3)

NAME

isascii - test for ASCII character

SYNOPSIS

#include <ctype.h>

intisascii(int c)

DESCRIPTION

The isascii() function tests for an ASCII character, based on the EBCDIC characterset. That is, isascii returns a non-zero value for any EBCDIC character which, whenconverted to ASCII, would have a value less than or equal to 0177.

The conversion from EBCDIC to ASCII follows the C compiler’s conversion table.

SEE ALSO

ctype(3),

STANDARDS

The isascii() function conforms to ISO/IEC 9899:1990 (“ISO C90”).

Systems/C C Library 463

Page 482: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

ISBLANK(3)

NAME

isblank - space or tab character test

SYNOPSIS

#include <ctype.h>

intisblank(int c)

DESCRIPTION

The isblank() function tests for a space or tab character.

RETURN VALUES

The isblank() function returns zero if the character tests false and returns non-zeroif the character tests true.

SEE ALSO

ctype(3)

464 Systems/C C Library

Page 483: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

ISCNTRL(3)

NAME

iscntrl - control character test

SYNOPSIS

#include <ctype.h>

intiscntrl(int c)

DESCRIPTION

The iscntrl() function tests for any control character.

RETURN VALUES

The iscntrl() function returns zero if the character tests false and returns non-zeroif the character tests true.

SEE ALSO

ctype(3),

STANDARDS

The iscntrl() function conforms to ISO/IEC 9899:1990 (“ISO C90”).

Systems/C C Library 465

Page 484: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

ISDIGIT(3)

NAME

isdigit - decimal-digit character test

SYNOPSIS

#include <ctype.h>

intisdigit(int c)

DESCRIPTION

The isdigit() function tests for any decimal-digit character.

RETURN VALUES

The isdigit() function returns zero if the character tests false and returns non-zeroIf the character tests true.

SEE ALSO

ctype(3),

STANDARDS

The isdigit() function conforms to ISO/IEC 9899:1990 (“ISO C90”).

466 Systems/C C Library

Page 485: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

ISGRAPH(3)

NAME

isgraph - printing character test (space character exclusive)

SYNOPSIS

#include <ctype.h>

intisgraph(int c)

DESCRIPTION

The isgraph() function tests for any printing character except space.

RETURN VALUES

The isgraph() function returns zero if the character tests false and returns non-zeroIf the character tests true.

SEE ALSO

ctype(3),

STANDARDS

The isgraph() function conforms to ISO/IEC 9899:1990 (“ISO C90”).

Systems/C C Library 467

Page 486: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

ISLOWER(3)

NAME

islower - lower-case character test

SYNOPSIS

#include <ctype.h>

intislower(int c)

DESCRIPTION

The islower() function tests for any lower-case letters.

RETURN VALUES

The islower() function returns zero if the character tests false and returns non-zeroif the character tests true.

SEE ALSO

ctype(3),

STANDARDS

The islower() function conforms to ISO/IEC 9899:1990 (“ISO C90”).

468 Systems/C C Library

Page 487: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

ISPRINT(3)

NAME

isprint - printing character test (space character inclusive)

SYNOPSIS

#include <ctype.h>

intisprint(int c)

DESCRIPTION

The isprint() function tests for any printing character including space (’ ’).

RETURN VALUES

The isprint() function returns zero if the character tests false and returns non-zeroif the character tests true.

SEE ALSO

ctype(3),

STANDARDS

The isprint() function conforms to ISO/IEC 9899:1990 (“ISO C90”).

Systems/C C Library 469

Page 488: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

ISPUNCT(3)

NAME

ispunct - punctuation character test

SYNOPSIS

#include <ctype.h>

intispunct(int c)

DESCRIPTION

The ispunct() function tests for any printing character except for space (’ ’) or acharacter for which isalnum(3) is true.

RETURN VALUES

The ispunct() function returns zero if the character tests false and returns non-zeroif the character tests true.

SEE ALSO

ctype(3),

STANDARDS

The ispunct() function conforms to ISO/IEC 9899:1990 (“ISO C90”).

470 Systems/C C Library

Page 489: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

ISSPACE(3)

NAME

isspace - white-space character test

SYNOPSIS

#include <ctype.h>

intisspace(int c)

DESCRIPTION

The isspace() function tests for the standard white-space characters.

RETURN VALUES

The isspace() function returns zero if the character tests false and returns non-zeroif the character tests true.

SEE ALSO

ctype(3),

STANDARDS

The isspace() function conforms to ISO/IEC 9899:1990 (“ISO C90”).

Systems/C C Library 471

Page 490: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

ISUPPER(3)

NAME

isupper - upper-case character test

SYNOPSIS

#include <ctype.h>

intisupper(int c)

DESCRIPTION

The isupper() function tests for any upper-case letter.

RETURN VALUES

The isupper() function returns zero if the character tests false and returns non-zeroif the character tests true.

SEE ALSO

ctype(3)

STANDARDS

The isupper() function conforms to ISO/IEC 9899:1990 (“ISO C90”).

472 Systems/C C Library

Page 491: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

ISWALNUM(3)

NAME

iswalnum, iswalpha, iswascii, iswblank, iswcntrl, iswdigit, iswgraph, iswhexnum-ber, iswideogram, iswlower, iswnumber, iswphonogram, iswprint, iswpunct, iswrune,iswspace, iswspecial, iswupper, iswxdigit - wide character classification utilities

SYNOPSIS

#include <wctype.h>intiswalnum(wint_t wc);

intiswalpha(wint_t wc);

intiswascii(wint_t wc);

intiswblank(wint_t wc);

intiswcntrl(wint_t wc);

intiswdigit(wint_t wc);

intiswgraph(wint_t wc);

intiswhexnumber(wint_t wc);

intiswideogram(wint_t wc);

intiswlower(wint_t wc);

intiswnumber(wint_t wc);

intiswphonogram(wint_t wc);

Systems/C C Library 473

Page 492: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

intiswprint(wint_t wc);

intiswpunct(wint_t wc);

intiswrune(wint_t wc);

intiswspace(wint_t wc);

intiswspecial(wint_t wc);

intiswupper(wint_t wc);

intiswxdigit(wint_t wc);

DESCRIPTION

The above functions are character classification utility functions, for use with widecharacter (wchar t or wint t). See the description for the similarly-named singlebyte classfunctions (e.g. isalnum(3)) for details.

RETURN VALUES

The functions return zero if the character tests false and return non-zero if thecharacter tests true.

SEE ALSO

isalnum(3), isalpha(3), isascii(3), isblank(3), iscntrl(3), isdigit(3), isgraph(3),ishexnumber(3), isideogram(3), islower(3), isnumber(3), isphonogram(3), isprint(3),ispunct(3), isrune(3), isspace(3), isspecial(3), isupper(3), isxdigit(3), wctype(3)

STANDARDS

These functions functions conform to ISO/IEC 9899:1999 (“ISO C99”), ex-cept iswascii(), iswhexnumber(), iswideogram(), iswnumber(), iswphono-

474 Systems/C C Library

Page 493: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

gram(), iswrune() and iswspecial(), which are Systems/C extensions.

CAVEATS

The result of these functions is undefined unless the argument is WEOF or a validwchar t value for the current locale.

Systems/C C Library 475

Page 494: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

ISXDIGIT(3)

NAME

isxdigit - hexadecimal-digit character test

SYNOPSIS

#include <ctype.h>

intisxdigit(int c)

DESCRIPTION

The isxdigit() function tests for any hexadecimal-digit character.

RETURN VALUES

The isxdigit() function returns zero if the character tests false and returns non-zeroif the character tests true.

SEE ALSO

ctype(3)

STANDARDS

The isxdigit() function conforms to ISO/IEC 9899:1990 (“ISO C90”).

476 Systems/C C Library

Page 495: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

MBLEN(3)

NAME

mblen - get number of bytes in a character

SYNOPSIS

#include <stdlib.h>

intmblen(const char *mbchar, size_t nbytes);

DESCRIPTION

The mblen() function computes the length in bytes of a multibyte character mbcharaccording to the current conversion state. Up to nbytes bytes are examined.

A call with a null mbchar pointer returns nonzero if the current locale requires shiftstates, zero otherwise; if shift states are required, the shift state is reset to the initialstate.

RETURN VALUES

If mbchar is NULL, the mblen() function returns nonzero if shift states are supported,zero otherwise.

Otherwise, if mbchar is not a null pointer, mblen() either returns 0 if mbcharrepresents the null wide character, or returns the number of bytes processed inmbchar, or returns -1 if no multibyte character could be recognized or converted. Inthis case, mblen()’s internal conversion state is undefined.

ERRORS

The mblen() function will fail if:

EILSEQ An invalid multibyte sequence was detected.

EINVAL The internal conversion state is not valid.

Systems/C C Library 477

Page 496: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

SEE ALSO

mbrlen(3), mbtowc(3), multibyte(3)

STANDARDS

The mblen() function conforms to ISO/IEC 9899:1999 (“ISO C99”).

478 Systems/C C Library

Page 497: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

MBRLEN(3)

NAME

mbrlen - get number of bytes in a character (restartable)

SYNOPSIS

#include <wchar.h>

size_tmbrlen(const char * restrict s, size_t n, mbstate_t * restrict ps);

DESCRIPTION

The mbrlen() function inspects at most n bytes pointed to by s to determine thenumber of bytes needed to complete the next multibyte character.

The mbstate t argument, ps, is used to keep track of the shift state. If it is NULL,mbrlen() uses an internal, static mbstate t object, which is initialized to the initialconversion state at program startup.

It is equivalent to:

mbrtowc(NULL, s, n, ps);

Except that when ps is a NULL pointer, mbrlen() uses its own static, internalmbstate t object to keep track of the shift state.

RETURN VALUES

The mbrlen() functions returns:

0 The next n or fewer bytes represent the null wide character (L’0’). item[>0] The next n or fewer bytes represent a valid charac-ter, mbrlen() returns the number of bytes used to complete themultibyte character.

EFAULT locale was NULL.

(size t)-2 The next n contribute to, but do not complete, a valid multibytecharacter sequence, and all n bytes have been processed.

(size t)-1 An encoding error has occurred. The next n or fewer bytes donot contribute to a valid multibyte character.

Systems/C C Library 479

Page 498: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

EXAMPLES

A function that calculates the number of characters in a multibyte character string:

size_tnchars(const char *s){

size_t charlen, chars;mbstate_t mbs;

chars = 0;memset(&mbs, 0, sizeof(mbs));while ((charlen = mbrlen(s, MB_CUR_MAX, &mbs)) != 0 &&

charlen != (size_t)-1 && charlen != (size_t)-2) {s += charlen;chars++;

}

return (chars);}

ERRORS

The mbrlen() function will fail if:

EILSEQ An invalid multibyte sequence was detected.

EINVAL The conversion state is invalid.

SEE ALSO

mblen(3), mbrtowc(3), multibyte(3)

STANDARDS

The mbrlen() function conforms to ISO/IEC 9899:1999 (“ISO C99”).

480 Systems/C C Library

Page 499: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

MBRTOWC(3)

NAME

mbrtowc - convert a character to a wide-character code (restartable)

SYNOPSIS

#include <wchar.h>

size_tmbrtowc(wchar_t * restrict pwc, const char * restrict s, size_t n,

mbstate_t * restrict ps);

DESCRIPTION

The mbrtowc() function inspects at most n bytes pointed to by s to determine thenumber of bytes needed to complete the next multibyte character. If a charactercan be completed, and pwc is not NULL, the wide character which is represented bys is stored in the wchar t it points to.

If s is NULL, mbrtowc() behaves as if pwc was NULL, s was an empty string ("")and n was 1.

The mbstate t argument, ps, is used to keep track of the shift state. If it is NULL,mbrtowc() uses an internal, static mbstate t object, which is initialized to theinitial conversion state at program startup.

RETURN VALUES

The mbrtowc() function returns:

0 The next n or fewer bytes represent the null wide character (L’0’).

>0 The next n or fewer bytes represent a valid character, mbrtowc()returns the number of bytes used to complete the multibyte char-acter.

(size t)-2 The next n contribute to, but do not complete, a valid multibytecharacter sequence, and all n bytes have been processed.

(size t)-1 An encoding error has occurred. The next n or fewer bytes donot contribute to a valid multibyte character.

Systems/C C Library 481

Page 500: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

ERRORS

The mbrtowc() function will fail if:

EILSEQ An invalid multibyte sequence was detected.

EINVAL The conversion state is invalid.

SEE ALSO

mbtowc(3), multibyte(3), setlocale(3), wcrtomb(3)

STANDARDS

The mbrtowc() function conforms to ISO/IEC 9899:1999 (“ISO C99”).

482 Systems/C C Library

Page 501: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

MBSINIT(3)

NAME

mbsinit - determine conversion object status

SYNOPSIS

#include <wchar.h>

intmbsinit(const mbstate_t *ps);

DESCRIPTION

The mbsinit() function determines whether the mbstate t object pointed to by psdescribes an initial conversion state.

RETURN VALUES

The mbsinit() function returns non-zero if ps is NULL or describes an initial con-version state, otherwise it returns zero.

STANDARDS

The mbsinit() function conforms to ISO/IEC 9899:1999 (“ISO C99”).

Systems/C C Library 483

Page 502: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

MBSRTOWCS(3)

NAME

mbsrtowcs, mbsnrtowcs - convert a character string to a wide-character string(restartable)

SYNOPSIS

#include <wchar.h>

size_tmbsrtowcs(wchar_t * restrict dst, const char ** restrict src, size_t len,

mbstate_t * restrict ps);

size_tmbsnrtowcs(wchar_t * restrict dst, const char ** restrict src,

size_t nms, size_t len, mbstate_t * restrict ps);

DESCRIPTION

The mbsrtowcs() function converts a sequence of multibyte characters pointed toindirectly by src into a sequence of corresponding wide characters and stores at mostlen of them in the wchar t array pointed to by dst, until it encounters a terminatingnull character (’0’).

If dst is NULL , no characters are stored.

If dst is not NULL, the pointer pointed to by src is updated to point to the characterafter the one that conversion stopped at. If conversion stops because a null characteris encountered, *src is set to NULL.

The mbstate t argument, ps, is used to keep track of the shift state. If it is NULL,mbsrtowcs() uses an internal, static mbstate t object, which is initialized to theinitial conversion state at program startup.

The mbsnrtowcs() function behaves identically to mbsrtowcs(), except that con-version stops after reading at most nms bytes from the buffer pointed to by src.

RETURN VALUES

The mbsrtowcs() and mbsnrtowcs() functions return the number of wide char-acters stored in the array pointed to by dst if successful, otherwise it returns(size t)-1.

484 Systems/C C Library

Page 503: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

ERRORS

The mbsrtowcs() and mbsnrtowcs() functions will fail if:

EILSEQ An invalid multibyte sequence was encountered.

EINVAL The conversion state is invalid.

SEE ALSO

mbrtowc(3), mbstowcs(3), multibyte(3), wcsrtombs(3)

STANDARDS

The mbsrtowcs() function conforms to ISO/IEC 9899:1999 (“ISO C99”).

The mbsnrtowcs() function is an extension to the standard.

Systems/C C Library 485

Page 504: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

MULTIBYTE(3)

NAME

multibyte – multibyte and wide character manipulation functions

SYNOPSIS

#include <limits.h>#include <stdlib.h>#include <wchar.h>

DESCRIPTION

The basic elements of some written natural languages, such as Chinese, cannot berepresented uniquely with single C chars. The C standard supports two differentways of dealing with extended natural language encodings: wide characters andmultibyte characters. Wide characters are an internal representation which allowseach basic element to map to a single object of type wchar t. Multibyte charactersare used for input and output and code each basic element as a sequence of C chars.Individual basic elements may map into one or more (up to MB LEN MAX) bytes in amultibyte character.

The current locale (setlocale(3)) governs the interpretation of wide and multibytecharacters. The locale category LC CTYPE specifically controls this interpretation.The wchar t type is wide enough to hold the largest value in the wide characterrepresentations for all locales.

Multibyte strings may contain ‘shift’ indicators to switch to and from particularmodes within the given representation. If explicit bytes are used to signal shifting,these are not recognized as separate characters but are lumped with a neighboringcharacter. There is always a distinguished ‘initial’ shift state. Some functions (e.g.,mblen(3), mbtowc(3) and wctomb(3)) maintain static shift state internally, whereasothers store it in an mbstate t object passed by the caller. Shift states are undefinedafter a call to setlocale(3) with the LC CTYPE or LC ALL categories.

For convenience in processing, the wide character with value 0 (the null wide char-acter) is recognized as the wide character string terminator, and the character withvalue 0 (the null byte) is recognized as the multibyte character string terminator.Null bytes are not permitted within multibyte characters.

The C library provides the following functions for dealing with multibyte characters:

mblen(3) get number of bytes in a character

486 Systems/C C Library

Page 505: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

mbrlen(3) get number of bytes in a character (restartable)

mbrtowc(3) convert a character to a wide-character code (restartable)

mbsrtowcs(3) convert a character string to a wide-character string (restartable)

mbstowcs(3) convert a character string to a wide-character string

mbtowc(3) convert a character to a wide-character code

wcrtomb(3) convert a wide-character code to a character (restartable)

wcstombs(3) convert a wide-character string to a character string

wcsrtombs(3) convert a wide-character string to a character string (restartable)

wctomb(3) convert a wide-character code to a character

SEE ALSO

setlocale(3), stdio(3), big5(5), euc(5), gb18030(5), gb2312(5), gbk(5), mskanji(5),utf8(5)

STANDARDS

These functions conform to ISO/IEC 9899:1999 (“ISO C99”).

Systems/C C Library 487

Page 506: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

RUNE(3)

NAME

setrunelocale, setinvalidrune, sgetrune, sputrune - rune support for C

SYNOPSIS

#include <rune.h>#include <errno.h>

intsetrunelocale(char *locale)

voidsetinvalidrune(rune_t rune)

rune_tsgetrune(const char *string, size_t n,char const **result)

intsputrune(rune_t rune, char *string, size_t n,char **result)

#include <stdio.h>

longfgetrune(FILE *stream)

intfungetrune(rune_t rune, FILE *stream)

intfputrune(rune_t rune, FILE *stream)

DESCRIPTION

The setrunelocale() controls the type of encoding used to represent runes as multi-byte strings as well as the properties of the runes as defined in ¡ctype.h¿. The localeargument indicates which locale to load. If the locale is successfully loaded, 0 isreturned, otherwise an errno value is returned to indicate the type of error.

The setinvalidrune() function sets the value of the global value INVALID RUNE tobe rune.

488 Systems/C C Library

Page 507: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

The sgetrune() function tries to read a single multibyte character from string,which is at most n bytes long. If sgetrune() is successful, the rune is returned.If result is not NULL, *result will point to the first byte which was not convertedin string. If the first n bytes of string do not describe a full multibyte character,INVALID RUNE is returned and *result will point to string. If there is an encodingerror at the start of string, INVALID RUNE is returned and *result will point tothe second character of string.

The sputrune() function tries to encode rune as a multibyte string and store it atstring, but no more than n bytes will be stored. If result is not NULL, *result willbe set to point to the first byte in string following the new multibyte character. Ifstring is NULL, *result will point to (char *)0 + x, where x is the number of bytesthat would be needed to store the multibyte value. If the multibyte character wouldconsist of more than n bytes and result is not NULL, *result will be set to NULL.In all cases, sputrune() will return the number of bytes which would be needed tostore rune as a multibyte character.

The fgetrune() function operates the same as sgetrune() with the exception thatit attempts to read enough bytes from stream to decode a single rune. It returnseither EOF on end of file, INVALID RUNE on an encoding error, or the rune decodedif all went well.

The fungetrune() function pushes the multibyte encoding, as provided by spu-trune(), of rune onto stream such that the next fgetrune() call will return rune.It returns EOF if it fails and 0 on success.

The fputrune() function writes the multibyte encoding of rune, as provided bysputrune(), onto stream. It returns EOF on failure and 0 on success.

RETURN VALUES

The setrunelocale() function returns one of the following values:

0 setrunelocale() was successful.

EFAULT locale was NULL.

ENOENT The locale could not be found.

EFTYPE The file found was not a valid file.

EINVAL The encoding indicated by the locale was unknown.

The sgetrune() function either returns the rune read or INVALID RUNE. The spu-trune() function returns the number of bytes needed to store rune as a multibytestring.

Systems/C C Library 489

Page 508: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

SEE ALSO

mbrune(3), setlocale(3)

NOTE

The ANSI C type wchar t is the same as rune t. Rune t was chosen to accent thepurposeful choice of not basing the system with the ANSI C primitives, which were,shall we say, less aesthetic.

The setrunelocale() function and the other non-ANSI rune functions were inspiredby Plan 9 from Bell Labs as a much more sane alternative to the ANSI multibyteand wide character support.

All of the ANSI multibyte and wide character support functions are built using therune functions.

490 Systems/C C Library

Page 509: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

SETLOCALE(3)

NAME

setlocale, localeconv - natural language formatting for C

SYNOPSIS

#include <locale.h>

char *setlocale(int category, const char *locale)

struct lconv *localeconv(void)

DESCRIPTION

The setlocale() function sets the C library’s notion of natural language formattingstyle for particular sets of routines. Each such style is called a ‘locale’ and is invokedusing an appropriate name passed as a C string. The localeconv() routine returnsthe current locale’s parameters for formatting numbers.

The setlocale() function recognizes several categories of routines. These are thecategories and the sets of routines they select:

LC ALL Set the entire locale generically.

LC COLLATE Set a locale for string collation routines. This controlsalphabetic ordering in strcoll() and strxfrm().

LC CTYPE Set a locale for the ctype(3), mbrune(3), multibyte(3)and rune(3) functions. This controls recognition ofupper and lower case, alphabetic or non-alphabeticcharacters, and so on. The real work is done by thesetrunelocale() function.

LC MONETARY Set a locale for formatting monetary values; this af-fects the localeconv() function.

LC NUMERIC Set a locale for formatting numbers. This controls theformatting of decimal points in input and output offloating point numbers in functions such as printf()and scanf(), as well as values returned by locale-conv().

Systems/C C Library 491

Page 510: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

LC TIME Set a locale for formatting dates and times using thestrftime() function.

Only three locales are defined by default, the empty string "" which denotes thenative environment, and the "C" and "POSIX" locales, which denote the C languageenvironment. A locale argument of NULL causes setlocale() to return the currentlocale. By default, C programs start in the "C" locale. The only function in thelibrary that sets the locale is setlocale(); the locale is never changed as a side effectof some other routine.

The localeconv() function returns a pointer to a structure which provides param-eters for formatting numbers, especially currency values:

struct lconv {char *decimal_point;char *thousands_sep;char *grouping;char *int_curr_symbol;char *currency_symbol;char *mon_decimal_point;char *mon_thousands_sep;char *mon_grouping;char *positive_sign;char *negative_sign;char int_frac_digits;char frac_digits;char p_cs_precedes;char p_sep_by_space;char n_cs_precedes;char n_sep_by_space;char p_sign_posn;char n_sign_posn;

};

The individual fields have the following meanings:

decimal point The decimal point character, except for currencyvalues.

thousands sep The separator between groups of digits before thedecimal point, except for currency values.

grouping The sizes of the groups of digits, except for cur-rency values. This is a pointer to a vector of in-tegers, each of size char, representing group sizefrom low order digit groups to high order (right

492 Systems/C C Library

Page 511: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

to left). The list may be terminated with 0 orCHAR MAX. If the list is terminated with 0, thelast group size before the 0 is repeated to accountfor all the digits. If the list is terminated withCHAR MAX, no more grouping is performed.

int curr symbol The standardized international currency symbol.

currency symbol The local currency symbol.

mon decimal point The decimal point character for currency values.

mon thousands sep The separator for digit groups in currency values.

mon grouping Like grouping but for currency values.

positive sign The character used to denote nonnegative cur-rency values, usually the empty string.

negative sign The character used to denote negative currencyvalues, usually a minus sign.

int frac digits The number of digits after the decimal point inan international-style currency value.

frac digits The number of digits after the decimal point inthe local style for currency values.

p cs precedes 1 if the currency symbol precedes the currencyvalue for nonnegative values, 0 if it follows.

p sep by space 1 if a space is inserted between the currency sym-bol and the currency value for nonnegative values,0 otherwise.

n cs precedes Like p cs precedes but for negative values.

n sep by space Like p sep by space but for negative values.

p sign posn The location of the positive sign with respect to anonnegative quantity and the currency symbol,coded as follows:

0 Parentheses around the entire string.

1 Before the string.

2 After the string.

3 Just before currency symbol.

4 Just after currency symbol.

n sign posn Like p sign posn but for negative currency val-ues.

Systems/C C Library 493

Page 512: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

Unless mentioned above, an empty string as a value for a field indicates a zerolength result or a value that is not in the current locale. A CHAR MAX result similarlydenotes an unavailable value.

RETURN VALUES

The setlocale() function returns NULL and fails to change the locale if the givencombination of category and locale makes no sense. The localeconv() functionreturns a pointer to a static object which may be altered by later calls to setlocale()or localeconv().

SEE ALSO

colldef(1), mklocale(1), ctype(3), mbrune(3), multibyte(3), rune(3), stroll(3),strxfrm(3)

STANDARDS

The setlocale() and localeconv() functions conform to ISO/IEC 9899:1990 (“ISOC90”).

ISSUES

The current implementation supports only the "C" and "POSIX" locales for all butthe LC COLLATE, LC CTYPE, and LC TIME categories.

In spite of the gnarly currency support in localeconv(), the standards don’t includeany functions for generalized currency formatting.

Use of LC MONETARY could lead to misleading results until we have a real time cur-rency conversion function. LC NUMERIC and LC TIME are personal choices and shouldnot be wrapped up with the other categories.

494 Systems/C C Library

Page 513: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

TOASCII(3)

NAME

toascii - convert a byte to 7-bit ASCII

SYNOPSIS

#include <ctype.h>

inttoascii(int c)

DESCRIPTION

The toascii() function strips all but the low 7 bits from a letter, including parityor other marker bits.

RETURN VALUES

The toascii() function always returns a valid ASCII character.

SEE ALSO

isalnum(3), isalpha(3), isascii(3), iscntrl(3), isdigit(3), isgraph(3), slower(3), is-print(3), ispunct(3), isspace(3), isupper(3), isxdigit(3), stdio(3), tolower(3), toup-per(3)

NOTE

This function makes little sense for an EBCDIC character, but is provided for com-patibility.

Systems/C C Library 495

Page 514: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

TOLOWER(3)

NAME

tolower - upper case to lower case letter conversion

SYNOPSIS

#include <ctype.h>

inttolower(int c)

DESCRIPTION

The tolower() function converts an upper-case letter to the corresponding lower-case letter.

RETURN VALUES

If the argument is an upper-case letter, the tolower() function returns the cor-responding lower-case letter if there is one; otherwise the argument is returnedunchanged.

SEE ALSO

isalnum(3), isalpha(3), isascii(3), iscntrl(3), isdigit(3), isgraph(3), slower(3), is-print(3), ispunct(3), isspace(3), isupper(3), isxdigit(3), stdio(3), toascii(3), toup-per(3)

STANDARDS

The tolower() function conforms to ISO/IEC 9899:1990 (“ISO C90”).

496 Systems/C C Library

Page 515: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

TOUPPER(3)

NAME

toupper - lower case to upper case letter conversion

SYNOPSIS

#include <ctype.h>

inttoupper(int c)

DESCRIPTION

The toupper() function converts a lower-case letter to the corresponding upper-caseletter. If the argument is a lower-case letter, the toupper() function returns thecorresponding upper-case letter if there is one; otherwise the argument is returnedunchanged.

SEE ALSO

isalnum(3), isalpha(3), isascii(3), iscntrl(3), isdigit(3), isgraph(3), slower(3),isprint(3), ispunct(3), isspace(3), isupper(3), isxdigit(3), stdio(3), toascii(3),tolower(3)

STANDARDS

The toupper() function conforms to ISO/IEC 9899:1990 (“ISO C90”).

Systems/C C Library 497

Page 516: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

TOWLOWER(3)

NAME

towlower - upper case to lower case letter conversion (wide character version)

SYNOPSIS

#include <wctype.h>

wint_ttowlower(wint_t wc);

DESCRIPTION

The towlower() function converts an upper-case letter to the corresponding lower-case leteter.

RETURN VALUES

If the argument is an upper-case letter, the towlower() function returns the cor-responding lower-case letter if there is one; otherwise the arugmnet is returnedunchanged.

SEE ALSO

iswlower(3), tolower(3), towupper(3), wctrans(3)

STANDARDS

The towlower() function conforms to ISO/IEC 9899:1999 (“ISO C99”).

498 Systems/C C Library

Page 517: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

TOWUPPER(3)

NAME

towupper - lower case to upper case letter conversion (wide character version)

SYNOPSIS

#include <wctype.h>

wint_ttowupper(wint_t wc);

DESCRIPTION

The towupper() function converts a lower-case letter to the corresponding upper-case letter.

RETURN VALUES

If the argument is a lower-case letter, the towupper() function returns the cor-responding upper-case letter if there is one; otherwise the argument is returnedunchanged.

SEE ALSO

iswupper(3), toupper(3), towlower(3), wctrans(3)

STANDARDS

The towupper() function conforms to ISO/IEC 9899:1999 (“ISO C99”).

Systems/C C Library 499

Page 518: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

WCSTOL(3)

NAME

wcstol, wcstoul, wcstoll, wcstoull, wcstoimax, wcstoumax - convert a wide characterstring value to a long, unsigned long, long long, unsigned long long, intmax tor uintmax t integer

SYNOPSIS

#include <wchar.h>

longwcstol(const wchar_t * restrict nptr, wchar_t ** restrict endptr,

int base);

unsigned longwcstoul(const wchar_t * restrict nptr, wchar_t ** restrict endptr,

int base);

long longwcstoll(const wchar_t * restrict nptr, wchar_t ** restrict endptr,

int base);

unsigned long longwcstoull(const wchar_t * restrict nptr, wchar_t ** restrict endptr,

int base);

#include <inttypes.h>

intmax_twcstoimax(const wchar_t * restrict nptr, wchar_t ** restrict endptr,

int base);

uintmax_twcstoumax(const wchar_t * restrict nptr, wchar_t ** restrict endptr,

int base);

DESCRIPTION

The wcstol(), wcstoul(), wcstoll(), wcstoull(), wcstoimax() and wc-stoumax() functions are wide-character versions of the strtol(), strtoul(), str-toll(), strtoull(), strtoimax() and strtoumax() functions, respectively. Refer totheir manual pages (for example strtol(3)) for details.

500 Systems/C C Library

Page 519: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

SEE ALSO

strtol(3), strtoul(3)

STANDARDS

The wcstol(), wcstoul(), wcstoll(), wcstoull(), wcstoimax() and wc-stoumax() functions conform to ISO/IEC 9899:1999 (“ISO C99”).

Systems/C C Library 501

Page 520: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

WCTRANS(3)

NAME

towctrans, wctrans - wide character mapping functions

SYNOPSIS

wint_ttowctrans(wint_t wc, wctrans_t desc);

wctrans_twctrans(const char *charclass);

DESCRIPTION

The wctrans() function returns a value of type wctrans t which represents the re-quested wide character mapping operation and may be used as the second argumentfor calls to towctrans().

The following character mapping names are recognized:

tolower toupper

The towctrans() function transliterates the wide character wc according to themapping described by desc.

RETURN VALUES

The towctrans() function returns the transliterated character if successful, other-wise it returns the character unchanged and sets errno.

The wctrans() function returns non-zero if successful, otherwise it returns zero andsets errno.

EXAMPLES

Reimplement towupper() in terms of towctrans() and wctrans():

502 Systems/C C Library

Page 521: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

wint_tmytowupper(wint_t wc){return (towctrans(wc, wctrans("toupper")));}

ERRORS

The towctrans() function will fail if:

EINVAL The supplied desc argument is invalid.

The wctrans() function will fail if:

EINVAL The requested mapping name is invalid.

SEE ALSO

tolower(3), toupper(3), wctype(3)

STANDARDS

The towctrans() and wctrans() functions conform to ISO/IEC 9899:1999 (“ISOC99”).

Systems/C C Library 503

Page 522: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

WCTYPE(3)

NAME

iswctype, wctype - wide character class functions

SYNOPSIS

#include <wctype.h>

intiswctype(wint_t wc, wctype_t charclass);

wctype_twctype(const char *property);

DESCRIPTION

The wctype() function returns a value of type wctype t which represents the re-quested wide character class and may be used as the second argument for calls toiswctype().

The following character class names are recognized:

alnum cntrl ideogram print specialalpha digit lower punct upperblank graph phonogram space xdigit

The iswctyp() function checks whether the wide character wc is in the characterclass charclass.

RETURN VALUES

The iswctype() function returns non-zero if and only if wc has the property de-scribed by charclass, or charclass is zero.

The wctype() function returns 0 if property is invalid, otherwise it returns a valueof type wctype t that can be used in subsequent calls to iswctype().

504 Systems/C C Library

Page 523: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

EXAMPLE

Reimplement iswalpha(3) in terms of iswctype() and wctype():

intmyiswalpha(wint_t wc){return (iswctype(wc, wctype("alpha")));}

SEE ALSO

ctype(3)

STANDARDS

The iswctype() and wctype() functions conform to ISO/IEC 9899:1999 (“ISOC99”). The “ideogram”, “phonogram” and “special” character classes are exten-sions.

Systems/C C Library 505

Page 524: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

WCWIDTH(3)

NAME

wcwidth - number of column positions of a wide-character code

SYNOPSIS

intwcwidth(wchar_t wc);

DESCRIPTION

The wcwidth() function determines the number of column positions required todisplay the wide character wc.

RETURN VALUES

The wcwidth() function returns 0 if the wc argument is a null wide character(L’\0’), -1 if wc is not printable, otherwise it returns the number of column positionsthe character occupies.

SEE ALSO

iswprint(3), wcswidth(3)

STANDARDS

The wcwidth() function conforms to ISO/IEC 9899:1999 (“ISO C99”).

506 Systems/C C Library

Page 525: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

Math library

The math library contains implementations of the transcendental functions andother support routines for manipulating floating point values.

Systems/C C Library 507

Page 526: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

MATH(3)

NAME

math - introduction to mathematical library functions

DESCRIPTION

These functions constitute the C math library.

Declarations for these functions may be obtained from the include file <math.h>.

508 Systems/C C Library

Page 527: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

LIST OF FUNCTIONS

Name Appears on Page DescriptionisBFP isBFP(3) determine floating-point for-

matacos acos(3) arc cosine functionacosf acos(3) arc cosine functionacosl acos(3) arc cosine functionacosh acosh(3) inverse hyperbolic functionacoshf acosh(3) inverse hyperbolic functionacoshl acosh(3) inverse hyperbolic functionasin asin(3) arc sine functionasinf asin(3) arc sine functionasinl asin(3) arc sine functionasinh asinh(3) inverse hyperbolic functionasinhf asinh(3) inverse hyperbolic functionasinhl asinh(3) inverse hyperbolic functionatan atan(3) arc tangent function of one

variableatanf atan(3) arc tangent function of one

variableatanl atan(3) arc tangent function of one

variableatanh atanh(3) inverse hyperbolic functionatanhf atanh(3) inverse hyperbolic functionatanhl atanh(3) inverse hyperbolic functionatan2 atan2(3) arc tangent function of two

variablesatan2f atan2(3) arc tangent function of two

variablesatan2l atan2(3) arc tangent function of two

variablescbrt sqrt(3) cube rootcbrtf sqrt(3) cube rootcbrtl sqrt(3) cube rootceil ceil(3) integer no less thanceilf ceil(3) integer no less thanceill ceil(3) integer no less thancopysign copysign(3) copy signcopysignf copysign(3) copy signcopysignl copysign(3) copy signcos cos(3) trigonometric functioncosf cos(3) trigonometric functioncosl cos(3) trigonometric functioncosh cosh(3) hyperbolic cosine functioncoshf cosh(3) hyperbolic cosine functioncoshl cosh(3) hyperbolic cosine function

Systems/C C Library 509

Page 528: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

Name Appears on Page Descriptionerf erf(3) error functionerff erf(3) error functionerfl erf(3) error functionerfc erf(3) complementary error functionerfcf erf(3) complementary error functionerfcl erf(3) complementary error functionexp exp(3) exponential ex

exp2 exp(3) exponential 2x

exp2f exp(3) exponential 2x

exp2l exp(3) exponential 2x

expf exp(3) exponential ex

expl exp(3) exponential ex

expm1 exp(3) ex − 1expm1f exp(3) ex − 1expm1f exp(3) ex − 1fabs fabs(3) absolute valuefabsf fabs(3) absolute valuefabsl fabs(3) absolute valuefdim fdim(3) positive difference functionsfdimf fdim(3) positive difference functionsfdiml fdim(3) positive difference functionsfeenableexcept feenableexcept(3) floating point exception

maskingfloor floor(3) integer no greater thanfloorf floor(3) integer no greater thanfloorl floor(3) integer no greater thanfma fma(3) fused multiply-addfmaf fma(3) fused multiply-addfmal fma(3) fused multiply-addfmax fmax(3) floating-point maximum and

minimum functionsfmaxf fmax(3) floating-point maximum and

minimum functionsfmaxl fmax(3) floating-point maximum and

minimum functionsfmin fmax(3) floating-point maximum and

minimum functionsfminf fmax(3) floating-point maximum and

minimum functionsfminl fmax(3) floating-point maximum and

minimum functionsfmod fmod(3) floating-point remainder

functionsfmodf fmod(3) floating-point remainder

functionsfmodl fmod(3) floating-point remainder

functionsfpclassify fpclassify(3) classify a floating-point num-

ber510 Systems/C C Library

Page 529: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

Name Appears on Page Descriptionfrexp frexp(3) convert to fraction and inte-

gral componentsfrexpf frexp(3) convert to fraction and inte-

gral componentsfrexpl frexp(3) convert to fraction and inte-

gral componentshypot hypot(3) Euclidean distanceilogb ilogb(3) extract exponentilogbf ilogb(3) extract exponentilogbl ilogb(3) extract exponentisfinite fpclassify(3) classify a floating-point num-

berisgreater isgreater(3) compare two floating-point

numbersisgreaterequal isgreater(3) compare two floating-point

numbersisinf fpclassify(3) classify a floating-point num-

berisless isgreater(3) compare two floating-point

numbersislessequal isgreater(3) compare two floating-point

numbersislessgreater isgreater(3) compare two floating-point

numbersisnan fpclassify(3) classify a floating-point num-

berisnormal fpclassify(3) classify a floating-point num-

berisunordered isgreater(3) compare two floating-point

numbersldexp ldexp(3) multiply by integral power of

2ldexpf ldexp(3) multiply by integral power of

2ldexpl ldexp(3) multiply by integral power of

2lgamma lgamma(3) log gamma functionlgammaf lgamma(3) log gamma functionlgammal lgamma(3) log gamma functionllrint lrint(3) convert to integerllrintf lrint(3) convert to integerllrintl lrint(3) convert to integerllround lround(3) convert to nearest integral

valuellroundf lround(3) convert to nearest integral

valuellroundl lround(3) convert to nearest integral

value

Systems/C C Library 511

Page 530: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

Name Appears on Page Descriptionlog log(3) natural logarithm ln(x)logf log(3) natural logarithm ln(x)logl log(3) natural logarithm ln(x)log10 log(3) logarithm to base 10 log10(x)log10f log(3) logarithm to base 10 log10(x)log10l log(3) logarithm to base 10 log10(x)log2 log(3) logarithm to base 2 log2(x)log2f log(3) logarithm to base 2 log2(x)log2l log(3) logarithm to base 2 log2(x)logb ilogb(3) extract exponentlogbf ilogb(3) extract exponentlogbl ilogb(3) extract exponentlog1p log(3) ln(1 + x)log1pf log(3) ln(1 + x)log1pl log(3) ln(1 + x)lrint lrint(3) convert to integerlrintf lrint(3) convert to integerlrintl lrint(3) convert to integerlround lround(3) convert to nearest integral

valuelroundf lround(3) convert to nearest integral

valuelroundl lround(3) convert to nearest integral

valuemodf modf(3) extract signed integral

and fractional values fromfloating-point number

modff modf(3) extract signed integraland fractional values fromfloating-point number

modfl modf(3) extract signed integraland fractional values fromfloating-point number

nan nan(3) quiet NaNsnanf nan(3) quiet NaNsnanl nan(3) quiet NaNsnearbyint rint(3) round to integral value in

floating-point formatnearbyintf rint(3) round to integral value in

floating-point formatnearbyintl rint(3) round to integral value in

floating-point formatnextafter nextafter(3) next representable valuenextafterf nextafter(3) next representable valuenextafterl nextafter(3) next representable valuenexttoward nextafter(3) next representable valuenexttowardf nextafter(3) next representable valuenexttowardl nextafter(3) next representable value

512 Systems/C C Library

Page 531: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

Name Appears on Page Descriptionpow exp(3) exponential xy

powf exp(3) exponential xy

powl exp(3) exponential xy

remainder remainder(3) minimal residue functionsremainderf remainder(3) minimal residue functionsremainderl remainder(3) minimal residue functionsremquo remainder(3) minimal residue functionsremquof remainder(3) minimal residue functionsremquol remainder(3) minimal residue functionsrint rint(3) round to integral value in

floating-point formatrintf rint(3) round to integral value in

floating-point formatrintl rint(3) round to integral value in

floating-point formatround round(3) round to nearest integral

valueroundf round(3) round to nearest integral

valueroundl round(3) round to nearest integral

valuescalbln scalbn(3) adjust exponentscalblnf scalbn(3) adjust exponentscalblnl scalbn(3) adjust exponentscalbn scalbn(3) adjust exponentscalbnf scalbn(3) adjust exponentscalbnl scalbn(3) adjust exponentsignbit signbit(3) determine whether a floating-

point number’s sign is nega-tive

sin sin(3) trigonometric functionsinf sin(3) trigonometric functionsinl sin(3) trigonometric functionsinh sinh(3) hyperbolic functionsinhf sinh(3) hyperbolic functionsinhl sinh(3) hyperbolic functionsqrt sqrt(3) square rootsqrtf sqrt(3) square rootsqrtl sqrt(3) square roottan tan(3) trigonometric functiontanf tan(3) trigonometric functiontanl tan(3) trigonometric functiontanh tanh(3) hyperbolic functiontanhf tanh(3) hyperbolic functiontanhl tanh(3) hyperbolic function

Systems/C C Library 513

Page 532: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

Name Appears on Page Descriptiontgamma lgamma(3) gamma functiontgammaf lgamma(3) gamma functiontgammal lgamma(3) gamma functiontrunc trunc(3) nearest integral value with

magnitude less than or equalto |x|

truncf trunc(3) nearest integral value withmagnitude less than or equalto |x|

truncl trunc(3) nearest integral value withmagnitude less than or equalto |x|

NOTES

These library functions support both the HFP (Hexadecimal Floating Point) formatand BFP (IEEE Binary Floating Point) formats. The selection of the format is eithermade at compile time via compiler options, or at runtime based on the return valueof the isBFP() function.

SEE ALSO

An explanation of the HFP and BFP floating point formats is provided in thez/Architecture Principles of Operations, IBM publication SA22-7200.

isBFP(3)

514 Systems/C C Library

Page 533: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

FP CAST(3)

NAME

fp cast - floating point cast function

SYNOPSIS

#include <machine/IEEE754.h>

int__fp_cast(int mode, void *src_ptr, int src_kind,

void *targ_ptr, int targ_kind);

DESCRIPTION

The fp cast() function adjusts the size of a floating point number from thesrc kind to the targ kind sizes. fp cast() will convert the floating point value atthe address specified in src ptr to the target size and save the result at the addressspecified in targ ptr.

The mode parameter indicates one of FP BFP MODE or FP HFP MODE for either BFPor HFP values.

The src kind and targ kind parameters indicate the size of the source and tar-get floating point number. Each should be one of FP FLOAT, FP DOUBLE orFP LONG DOUBLE.

RETURN VALUES

The fp cast() function returns 0 on success.

If any of mode, src kind or targ kind is invalid fp cast() returns -1.

SEE ALSO

isbfp(3)

Systems/C C Library 515

Page 534: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

ISBFP(3)

NAME

isBFP, fp swapmode, fp setmode - floating point format functions

SYNOPSIS

#include <machine/IEE754.h>

int__isBFP(void);

int__fp_swapmode(int newmode);

void__fp_setmode(int newmode);

DESCRIPTION

The isBFP() function determines the current selection of the floating-point for-mat. The runtime library maintains a selection state of either BFP or HFP or ”un-determined.” When isBPF() is invoked, if the state is ”undetermined”, then thecompile-time setting of the caller is investigated to determine the mode. isBFP()returns 1 if the mode is specifically set to BFP, or the caller is determined to beBFP, 0 for HFP.

The fp swapmode() function is used to return the current library floating pointstate, and set a new one. It can be used to retain the current mode, set a new one,perform some operations and then restore the previous mode.

The fp setmode() function sets a particular state.

The state values are

FP MODE RESET The mode is determined by the caller.

FP HFP MODE The mode is HFP.

FP BFP MODE The mode is BFP.

Many of the library functions use isBFP() to determine if the operation is toproceed in BFP or HFP format.

516 Systems/C C Library

Page 535: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

RETURN VALUES

The isBFP() function returns 1 if the current mode is FP BFP MODE or if thecurrent mode is FP MODE RESET and the caller has been determined to be compiledfor BFP values; otherwise it returns zero.

The fp swapmode() function returns the current mode state setting.

The current mode is thread-specific and is inherited from the parent thread when anew thread is created.

SEE ALSO

fp cast(3)

Systems/C C Library 517

Page 536: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

ACOS(3)

NAME

acos, acosf, acosl - arc cosine functions

SYNOPSIS

#include <math.h>

doubleacos(double x);

floatacosf(float x);

long doubleacosl(long double x);

DESCRIPTION

The acos(), acosf() and acosl() functions computes the principal value of the arccosine of x. A domain error occurs for arguments not in the range [−1,+1].

RETURN VALUES

The acos(), acosf() and acosl() functions return the arc cosine in the range [0, π]radians. If |x| > 1,

The acos(), acosf() and acosl() functions may set the global variable errno toEDOM and a reserved operand fault may be generated.

SEE ALSO

asin(3), atan(3), atan2(3), cos(3), cosh(3), math(3), sin(3), sinh(3), tan(3), tanh(3)

STANDARDS

The acos() function conforms to ISO/IEC 9899:1990 (“ISO C90”).

The acosf() and acosl() functions conform to ISO/IEC 9899:1999 (“ISO C99”).

518 Systems/C C Library

Page 537: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

ACOSH(3)

NAME

acosh, acoshf, acoshl - inverse hyperbolic cosine function

SYNOPSIS

#include <math.h>

doubleacosh(double x);

floatacoshf(float x);

long doubleacoshl(long double x);

DESCRIPTION

The acosh(), acoshf() and acoshl() functions computes the inverse hyperboliccosine of the real argument x. If the argument is less than 1, these functions raisean invalid exception and for BFP values return a NaN, for HFP alues these functionsreturn 0.0.

RETURN VALUES

The acosh(), acoshf() and acoshl() functions return the inverse hyperbolic cosineof x.

SEE ALSO

asinh(3), atanh(3), exp(3), math(3)

STANDARDS

The acosh(), acoshf() and acoshl() functions conform to ISO/IEC 9899:1999(“ISO C99”).

Systems/C C Library 519

Page 538: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

SCALBN(3)

NAME

scalbln, scalblnf, scalblnl, scalbn, scalbnf, scalbnl – adjust exponent

SYNOPSIS

#include <math.h>

doublescalbln(double x, long n);

floatscalblnf(float x, long n);

long doublescalblnl(long double x, long n);

doublescalbn(double x, int n);

floatscalbnf(float x, int n);

long doublescalbnl(long double x, int n);

DESCRIPTION

These routines return x ∗ (2 ∗ ∗n) computed by exponent manipulation.

SEE ALSO

math(3)

STANDARDS

These routines conform to ISO/IEC 9899:1999 (“ISO C99”).

520 Systems/C C Library

Page 539: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

ASIN(3)

NAME

asin, asinf, asinl - arc sine functions

SYNOPSIS

#include <math.h>

doubleasin(double x);

floatasinf(float x);

long doubleasinl(long double x);

DESCRIPTION

The asin(), asinf() and asinl() functions computes the principal value of the arcsine of x. A domain error occurs for arguments not in the range [−1,+1].

RETURN VALUES

The asin(), asinf() and asinl() functions return the arc sine in the range[−π

2 ,+π2

]radians.

SEE ALSO

acos(3), atan(3), atan2(3), cos(3), cosh(3), math(3), sin(3), sinh(3), tan(3), tanh(3)

STANDARDS

The asin() function conforms to ISO/IEC 9899:1990 (“ISO C90”).

The asinf() and asinl() functions conform to ISO/IEC 9899:1999 (“ISO C99”).

Systems/C C Library 521

Page 540: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

ASINH(3)

NAME

asinh, asinhf, asinhl - inverse hyperbolic sine function

SYNOPSIS

#include <math.h>

doubleasinh(double x);

floatasinhf(float x);

long doubleasinhl(long double x);

DESCRIPTION

The asinh(), asinhf() and asinhl() functions compute the inverse hyperbolic sineof the real argument x.

RETURN VALUES

The asinh(), asinhf() and asinhl() functions return the inverse hyperbolic sine ofx.

SEE ALSO

acosh(3), atanh(3), exp(3), math(3)

STANDARDS

The asinh(), asinhf() and asinhl() functions conform to ISO/IEC 9899:1999 (“ISOC99”).

522 Systems/C C Library

Page 541: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

ATAN(3)

NAME

atan, atanf, atanl - arc tangent functions of one variable

SYNOPSIS

#include <math.h>

doubleatan(double x);

floatatanf(float x);

long doubleatanl(long double x);

DESCRIPTION

The atan(), atanf() and atanl() functions compute the principal value of the arctangent of x.

RETURN VALUES

The atan(), atanf() and atanl() functions return the arc tangent in the range[−π

2 ,+π2

]radians.

SEE ALSO

acos(3), asin(3), atan2(3), cos(3), cosh(3), math(3), sin(3), sinh(3), tan(3), tanh(3)

STANDARDS

The atan() function conforms to ISO/IEC 9899:1990 (“ISO C90”).

The atanf() and atanl() functions conform to ISO/IEC 9899:1999 (“ISO C99”).

Systems/C C Library 523

Page 542: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

ATAN2(3)

NAME

atan2, atan2f, atan2l - arc tangent functions of two variables

SYNOPSIS

#include <math.h>

doubleatan2(double y, double x);

floatatan2f(float y, float x);

long doubleatan2l(long double y, long double x);

DESCRIPTION

The atan2(), atan2f() and atan2l() functions compute the principal value ofarctan

( yx

), using the signs of both arguments to determine the quadrant of the

return value.

RETURN VALUES

The atan2(), atan2f() and atan2l() functions if successful, return arctan( y

x

)in

the range [−π, π] radians. If both x and y are zero, the global variable errno is setto EDOM.

atan2(y, x) = arctan( yx) if x > 0

sign(y)(π − arctan

(∣∣ yx

∣∣)) if x < 00 if x = y = 0sign(y)π

2 if x = 0 6= y

NOTES

The functions atan2(), atan2f() and atan2l() defines “if x > 0, atan2(0, 0) = 0.”On some systems, atan2(0, 0) may generate an error message. The reasons forassigning a value to atan2(0, 0) are these:

524 Systems/C C Library

Page 543: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

• Programs that test arguments to avoid computing atan2(0, 0) must be in-different to its value. Programs that require it to be invalid are vulnerable todiverse reactions to that invalidity on diverse computer systems.

• The atan2() function is used mostly to convert from rectangular (x, y) topolar (r, θ) coordinates that must satisfy x = r cos θ and y = r sin θ. Theseequations are satisfied when (x = 0, y = 0) is mapped to (r = 0, θ = 0). Ingeneral, conversions to polar coordinates should be computed thus:

r = hypot(x,y); /* ... = sqrt(x*x+y*y) */theta = atan2(y,x);

• The foregoing formulas need not be altered to cope in a reasonable way withsigned zeros and infinities on a machine that conforms to IEEE 754. Theversions of hypot(3) and atan2() provided for such a machine are designedto handle all cases. That is why atan2(±0,−0) = ±π for instance. In generalthe formulas above are equivalent to these:

r = sqrt(x*x+y*y); if (r == 0) x = copysign(1,x);

SEE ALSO

acos(3), asin(3), atan(3), cos(3), cosh(3), math(3), sin(3), sinh(3), tan(3), tanh(3)

STANDARDS

The atan2() function conforms to ISO/IEC 9899:1990 (“ISO C90”).

The atan2f() and atan2l() functions conform to ISO/IEC 9899:1999 (“ISO C99”).

Systems/C C Library 525

Page 544: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

ATANH(3)

NAME

atanh, atanhf, atanhl - inverse hyperbolic tangent function

SYNOPSIS

#include <math.h>

doubleatanh(double x);

floatatanhf(float x);

long doubleatanhl(long double x);

DESCRIPTION

The atanh(), atanhf() and atanhl() functions compute the inverse hyperbolictangent of the real argument x.

RETURN VALUES

The atanh(), atanhf() and atanhl() functions return the inverse hyperbolic tan-gent of x if successful. If the argument has the value 1.0, HUGE VAL is returned, ifthe argument is -1.0, -HUGE VAL is returned. If the absolute value of the argument isgreater than 1.0, a DOMAIN error is indicated and for BFP values a NaN is returned,for HFP values 0.0 is returned.

SEE ALSO

acosh(3), asinh(3), exp(3), fenv(3), math(3)

STANDARDS

The atanh(), atanhf() and atanhl() functions conform to ISO/IEC 9899:1999(“ISO C99”).

526 Systems/C C Library

Page 545: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

CEIL(3)

NAME

ceil, ceilf, ceill – smallest integral value greater than or equal to x

SYNOPSIS

#include <math.h>

doubleceil(double x);

floatceilf(float x);

long doubleceill(long double x);

DESCRIPTION

The ceil(), ceilf() and ceill() functions compute the smallest integral value greaterthan or equal to x, expressed as a floating-point number.

SEE ALSO

abs(3), fabs(3), floor(3), math(3), rint(3), round(3), trunc(3)

STANDARDS

The ceil() function conforms to ISO/IEC 9899:1990 (“ISO C90”). The ceilf() andceill() functions conform to ISO/IEC 9899:1999 (“ISO C99”).

Systems/C C Library 527

Page 546: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

COPYSIGN(3)

NAME

copysign, copysignf, copysignl - copy sign

SYNOPSIS

#include <math.h>

doublecopysign(double x, double y);

floatcopysignf(float x, float y);

long doublecopysignl(long double x, long double y);

DESCRIPTION

The copysign(), copysignf() and copysignl() functions return x with its signchanged to y’s.

SEE ALSO

fabs(3), fdim(3), math(3)

STANDARDS

The copysign(), copysignf(), and copysignl() routines conform to ISO/IEC9899:1999 (“ISO C99”).

528 Systems/C C Library

Page 547: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

COS(3)

NAME

cos, cosf, cosl - cosine functions

SYNOPSIS

#include <math.h>

doublecos(double x);

floatcosf(double x);

long doublecosl(long double x);

DESCRIPTION

The cos(), cosf() and cosl() functions compute the cosine of x (measured in radi-ans). A large magnitude argument may yield a result with little or no significance.

RETURN VALUES

The cos(), cosf() and cosl() functions return the cosine value.

SEE ALSO

acos(3), asin(3), atan(3), atan2(3), cosh(3), math(3), sin(3), sinh(3), tan(3), tanh(3)

STANDARDS

The cos() function conforms to ISO/IEC 9899:1990 (“ISO C90”).

The cosf() and cosl() functions conform to ISO/IEC 9899:1999 (“ISO C99”).

Systems/C C Library 529

Page 548: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

COSH(3)

NAME

cosh, coshf, coshl - hyperbolic cosine function

SYNOPSIS

#include <math.h>

doublecosh(double x);

floatcoshf(float x);

long doublecoshl(long double x);

DESCRIPTION

The cosh(), coshf() and coshl() functions compute the hyperbolic cosine of x.

RETURN VALUES

The cosh(), coshf() and coshl() functions returns the hyperbolic cosine.

SEE ALSO

acos(3), asin(3), atan(3), atan2(3), cos(3), math(3), sin(3), sinh(3), tan(3), tanh(3)

STANDARDS

The cosh() function conforms to ISO/IEC 9899:1990 (“ISO C90”).

The coshf() and coshl() functions conform to ISO/IEC 9899:1999 (“ISO C99”).

530 Systems/C C Library

Page 549: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

ERF(3)

NAME

erf, erff, erfl, erfc, erfcf, erfcl – error function operators

SYNOPSIS

#include <math.h>

doubleerf(double x);

floaterff(float x);

long doubleerfl(long double x);

doubleerfc(double x);

floaterfcf(float x);

long doubleerfcf(long double x);

DESCRIPTION

These functions calculate the error function of x.

The erf(), erff() and erfl() functions calculate the error function of x; where

erf(x) =2√π

∫ x

0e−t2 dt

The erfc(), erfcf() and erfcfl() functions calculate the complementary error func-tion of x; that is erfc() subtracts the result of the error function erf(x) from 1.0.This is useful, since for large x places disappear.

SEE ALSO

math(3)

Systems/C C Library 531

Page 550: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

STANDARDS

The functions conform to ISO/IEC 9899:1999 (“ISO C99”).

532 Systems/C C Library

Page 551: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

EXP(3)

NAME

exp, expf, expl, exp2, exp2f, exp2l, expm1, expm1f, expm1l, pow, powf, powl -exponential and power functions

SYNOPSIS

#include <math.h>

doubleexp(double x);

floatexpf(float x);

long doubleexpl(long double x);

doubleexp2(double x);

floatexp2f(float x);

long doubleexp2l(long double x);

doubleexpm1(double x);

floatexpm1f(float x);

floatexpm1f(float x);

doublepow(double x, double y);

floatpowf(float x, float y);

long doublepowl(long double x, long double y);

Systems/C C Library 533

Page 552: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

DESCRIPTION

The exp(), expf() and expfl() functions compute the exponential value of thegiven argument x.

The exp2(), exp2f() and exp2l() functions compute the base 2 exponential valueof the given argument x.

The expm1(), expm1f() and expm1l() functions compute the value exp(x)-1.0accurately even for tiny argument x.

The pow(), powf() and powl() functions compute the value of x to the exponenty.

ERROR (due to Roundoff etc.)

exp(), expm1(0), exp2(integer) and pow(integer,integer) are exact providedthey are representable. Otherwise the error in these functions is generally below oneulp.

RETURN VALUES

These functions will return the appropriate computation unless an error occurs oran argument is out of range. The functions exp(), expm1() and pow() detectif the computed value will overflow, set the global variable errno to ERANGE. Thefunction pow(x, y) checks to see if x < 0 and y is not an integer, in the event thisis true, the global variable errno is set to EDOM for HFP values or return a NaN forBFP values.

NOTES

The function pow(x, 0) returns x0 = 1 for all x including x = 0, ∞ (not found forIBM HFP format) and NaN (not found in IBM HFP format).

Previous implementations of pow() may have defined x0 to be undefined in someor all of these cases. Here are reasons for returning x0 = 1:

• Any program that already tests whether x is zero (or infinite or NaN) beforecomputing x0 cannot care whether 00 = 1 or not. Any program that dependsupon 00 to be invalid is dubious anyway since that expression’s meaning and,if invalid, its consequences vary from one computer system to another.

534 Systems/C C Library

Page 553: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

• Some Algebra texts (e.g. Sigler’s) define x0 = 1 for all x, including x = 0. Thisis compatible with the convention that accepts a0 as the value of polynomial

p(x) = a0x0 + a1x

1 + a2x2 + · · ·+ anxn

at x = 0 rather than reject a000 as invalid.

• Analysts will accept 00 = 1 despite that xy can approach anything or nothingas x and y approach 0 independently. The reason for setting 00 = 1 anywayis this:

If x(z) and y(z) are any functions analytic (expandable in powerseries) in z around z = 0, and if there x(0) = y(0) = 0, thenx(z)y(z) → 1 as z → 0.

• If 00 = 1, then ∞0 = 100 = 1 too; and then NaN0 = 1 too because x0 = 1 for

all finite and infinite x, i.e., independently of x.

SEE ALSO

fenv(3), ldexp(3), log(3), math(3)

STANDARDS

These functions conform to ISO/IEC 9899:1999 (“ISO C99”).

Systems/C C Library 535

Page 554: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

FABS(3)

NAME

fabs, fabsf, fabsl – floating-point absolute value functions

SYNOPSIS

#include <math.h>

doublefabs(double x);

floatfabsf(float x);

long doublefabsl(long double x);

DESCRIPTION

The fabs(), fabsf() and fabsl() functions compute the absolute value of a floating-point number x.

RETURN VALUES

The fabs(), fabsf() and fabsl() functions return the absolute value of x.

SEE ALSO

abs(3), ceil(3), floor(3), math(3), rint(3)

STANDARDS

The fabs() function conforms to ISO/IEC 9899:1990 (“ISO C90”). The fabsf()and fabsl() functions conform to ISO/IEC 9899:1999 (“ISO C99”).

536 Systems/C C Library

Page 555: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

FDIM(3)

NAME

fdim, fdimf, fdiml – positive difference functions

SYNOPSIS

#include <math.h>

doublefdim(double x, double y);

floatfdimf(float x, float y);

long doublefdiml(long double x, long double y);

DESCRIPTION

The fdim(), fdimf(), and fdiml() functions return the positive difference betweenx and y. That is, if x-y is positive, then x-y is returned. If either x or y is a NaN,then a NaN is returned. Otherwise, the result is +0.0.

Overflow or underflow may occur if and only if the exact result is not representablein the return type. No other exceptions are raised.

SEE ALSO

fabs(3), fmax(3), fmin(3), math(3)

STANDARDS

The fdim(), fdimf(), and fdiml() functions conform to ISO/IEC 9899:1999 (“ISOC99”).

Systems/C C Library 537

Page 556: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

FEENABLEEXCEPT(3)

NAME

feenableexcept, fedisableexcept, fegetexcept – floating-point exception masking

SYNOPSIS

#include <fenv.h>#pragma STDC FENV_ACCESS ON

intfeenableexcept(int excepts);

intfedisableexcept(int excepts);

intfegetexcept(void);

DESCRIPTION

The feenableexcept() and fedisableexcept() functions unmask and mask (re-spectively) exceptions specified in excepts. The fegetexcept() function returns thecurrent exception mask. All exceptions are masked by default.

Floating-point operations that produce unmasked exceptions will trap, and aSIGFPE will be delivered to the process. By installing a signal han- dler for SIGFPE,applications can take appropriate action immediately without testing the exceptionflags after every operation. Note that the trap may not be immediate, but it shouldoccur before the next floating- point instruction is executed.

For all of these functions, the possible types of exceptions include those describedin fenv(3). Some architectures may define other types of floating-point exceptions.

RETURN VALUES

The feenableexcept(), fedisableexcept(), and fegetexcept() functions returna bitmap of the exceptions that were unmasked prior to the call.

SEE ALSO

sigaction(2), feclearexcept(3), feholdexcept(3), fenv(3), feupdateenv(3)

538 Systems/C C Library

Page 557: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

ISSUES

Functions in the standard library may trigger exceptions multiple times as a re-sult of intermediate computations; however, they generally do not trigger spuriousexceptions.

No interface is provided to permit exceptions to be handled in nontrivial ways.There is no uniform way for an exception handler to access information about theexception-causing instruction, or to determine whether that instruction should bereexecuted after returning from the handler.

Systems/C C Library 539

Page 558: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

FLOOR(3)

NAME

floor, floorf, floorl – largest integral value less than or equal to x

SYNOPSIS

#include <math.h>

doublefloor(double x);

floatfloorf(float x);

long doublefloorl(long double x);

DESCRIPTION

The floor(), floorf() and floorl() functions compute the largest integral value lessthan or equal to x, expressed as a floating-point number.

SEE ALSO

abs(3), ceil(3), fabs(3), math(3), rint(3), round(3), trunc(3)

STANDARDS

The floor() function conforms to ISO/IEC 9899:1990 (“ISO C90”).

The floorf() and floorl() functions conform to ISO/IEC 9899:1999 (“ISO C99”).

540 Systems/C C Library

Page 559: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

FMA(3)

NAME

fma, fmaf, fmal – fused multiply-add

SYNOPSIS

#include <math.h>

doublefma(double x, double y, double z);

floatfmaf(float x, float y, float z);

long doublefmal(long double x, long double y, long double z);

DESCRIPTION

The fma(), fmaf(), and fmal() functions return (x * y) + z, computed with onlyone rounding error. Using the ordinary multiplication and addition operators, bycontrast, results in two roundings: one for the intermediate product and one for thefinal result.

For instance, the expression 1.2e100 * 2.0e208 - 1.4e308 produces infinity due tooverflow in the intermediate product, whereas fma(1.2e100, 2.0e208, -1.4e308) re-turns approximately 1.0e308 (for IEEE values.)

The fused multiply-add operation is often used to improve the accuracy of cal-culations such as dot products. It may also be used to improve performance onmachines that implement it natively. The macros FP FAST FMA, FP FAST FMAF andFP FAST FMAL may be defined in ¡math.h¿ to indicate that fma(), fmaf(), andfmal() (respectively) have comparable or faster speed than a multiply operationfollowed by an add operation.

SEE ALSO

fenv(3), math(3)

Systems/C C Library 541

Page 560: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

STANDARDS

The fma(), fmaf(), and fmal() functions conform to ISO/IEC 9899:1999 (“ISOC99”). A fused multiply-add operation with virtually identical characteristics ap-pears in IEEE draft standard 754R.

542 Systems/C C Library

Page 561: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

FMAX(3)

NAME

fmax, fmaxf, fmaxl, fmin, fminf, fminl – floating-point maximum and minimumfunctions

SYNOPSIS

#include <math.h>

doublefmax(double x, double y);

floatfmaxf(float x, float y);

long doublefmaxl(long double x, long double y);

doublefmin(double x, double y);

floatfminf(float x, float y);

long doublefminl(long double x, long double y);

DESCRIPTION

The fmax(), fmaxf(), and fmaxl() functions return the larger of x and y, andlikewise, the fmin(), fminf(), and fminl() functions return the smaller of x and y.They treat +0.0 as being larger than -0.0. If one argument is a NaN, then the otherargument is returned. If both arguments are NaNs, then the result is a NaN. Theseroutines do not raise any floating-point exceptions.

SEE ALSO

fabs(3), fdim(3), math(3)

Systems/C C Library 543

Page 562: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

STANDARDS

The fmax(), fmaxf(), fmaxl(), fmin(), fminf(), and fminl() functions conformto ISO/IEC 9899:1999 (“ISO C99”).

544 Systems/C C Library

Page 563: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

FMOD(3)

NAME

fmod, fmodf, fmodl – floating-point remainder functions

SYNOPSIS

#include <math.h>

doublefmod(double x, double y);

floatfmodf(float x, float y);

long doublefmodl(long double x, long double y);

DESCRIPTION

The fmod(), fmodf() and fmodl() functions compute the floating-point remainderof x

y .

RETURN VALUES

The fmod(), fmodf() and fmodl() functions return the value x − i ∗ y for someinteger i such that, if y is non-zero, the result has the same sign as x and magnitudeless than the magnitude of y. If y is zero, whether a domain error occurs or thefmod() function returns zero is implementation-defined and depends on the use ofIEEE or HFP values.

SEE ALSO

math(3)

STANDARDS

The fmod() function conforms to ISO/IEC 9899:1990 (“ISO C90”).

The fmodf(), and fmodl() functions conform to ISO/IEC 9899:1999 (“ISO C99”).

Systems/C C Library 545

Page 564: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

FPCLASSIFY(3)

name

fpclassify, isfinite, isinf, isnan, isnormal - classify a floating-point number

SYNOPSIS

#include <math.h>

intfpclassify(real-floating x);

intisfinite(real-floating x);

intisinf(real-floating x);

intisnan(real-floating x);

intisnormal(real-floating x);

DESCRIPTION

The fpclassify() macro takes an argument of x and returns one of the followingmanifest constants.

FP INFINITE Indicates that x is an infinite number.

FP NAN Indicates that x is not a number (NaN).

FP NORMAL Indicates that x is a normalized number.

FP SUBNORMAL Indicates that x is a denormalized number.

FP ZERO Indicates that x is zero (0 or -0).

The isfinite() macro returns a non-zero value if and only if its argument has a finite(zero, subnormal, or normal) value. The isinf(), isnan(), and isnormal() macrosreturn non-zero if and only if x is an infinity, NaN, or a non-zero normalized number,respectively. Note that HFP values do not support infinity or NaN.

546 Systems/C C Library

Page 565: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

SEE ALSO

isgreater(3), math(3), signbit(3)

STANDARDS

The fpclassify(), isfinite(), isinf(), isnan(), and isnormal() macros conform toISO/IEC 9899:1999 (“ISO C99”).

Systems/C C Library 547

Page 566: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

FREXP(3)

NAME

frexp, frexpf, frexpl – convert floating-point number to fractional and integral com-ponents

SYNOPSIS

#include <math.h>

doublefrexp(double value, int *exp);

floatfrexpf(float value, int *exp);

long doublefrexpl(long double value, int *exp);

DESCRIPTION

The frexp(), frexpf() and frexpl() functions break a floating-point number intoa normalized fraction and an integral power of 2. They store the integer in the intobject pointed to by exp.

RETURN VALUES

These functions return the value x, such that x is a double with magnitude in theinterval [1/2, 1) or zero, and value equals x times 2 raised to the power *exp. Ifvalue is zero, both parts of the result are zero.

SEE ALSO

ldexp(3) math(3), modf(3)

STANDARDS

The frexp(), frexpf() and frexpl() functions conform to ISO/IEC 9899:1999 (“ISOC99”).

548 Systems/C C Library

Page 567: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

HYPOT(3)

NAME

hypot, hypotf, hypotl - euclidean distance functions

SYNOPSIS

#include <math.h>

doublehypot(double x, double y);

floathypotf(float x, float y);

long doublehypotl(long double x, long double y);

DESCRIPTION

The hypot(), hypotf() and hypotl() functions compute√

x2 + y2 in such a waythat underflow will not happen, and overflow occurs only if the final result deservesit.

hypot(∞, v) = hypot(v,∞) = +∞ for all v, including NaN. (∞ and NAN are notfound in the IBM HFP format).

SEE ALSO

math(3), sqrt(3)

STANDARDS

The hypot(), hypotf() hypotl() functions conform to ISO/IEC 9899:1999 (“ISOC99”).

Systems/C C Library 549

Page 568: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

ILOGB(3)

NAME

ilogb, ilogbf, ilogbl, logb, logbf, logbl – extract exponent

SYNOPSIS

#include <math.h>

intilogb(double x);

intilogbf(float x);

intilogbl(long double x);

doublelogb(double x);

floatlogbf(float x);

long doublelogbl(long double x);

DESCRIPTION

ilogb(), ilogbf() and ilogbl() return x’s exponent in integer format. ForBFP (IEEE) values ilogb(+-infinity) returns INT MAX, ilogb(+-NaN) returnsFP ILOGBNAN . ilogb(0) returns FP ILOGB0.

logb(), logbf(), and logbl() return x’s exponent in floating-point format with thesame precision as x. For BFP (IEEE) values logb(+-infinity) returns +infinity. If x is+/-0, logb(), logbf(), and logbl() return -HUGE VAL, -HUGE VALF and -HUGE VALLrespectively.

BFP values have a radix of 2 and HFP values have a radix of 16; the return exponentvalues are in the radix of the format (FLT RADIX defined in <float.h>).

SEE ALSO

frexp(3), math(3), scalbn(3)

550 Systems/C C Library

Page 569: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

STANDARDS

The ilogb(), ilogbf(), ilogbl(), logb(), logbf(), and logbl() routines conform toISO/IEC 9899:1999 (“ISO C99”).

Systems/C C Library 551

Page 570: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

ISGREATER(3)

NAME

isgreater, isgreaterequal, isless, islessequal, islessgreater, isunordered – compare twofloating-point numbers

SYNOPSIS

#include <math.h>

intisgreater(real-floating x, real-floating y);

intisgreaterequal(real-floating x, real-floating y);

intisless(real-floating x, real-floating y);

intislessequal(real-floating x, real-floating y);

intislessgreater(real-floating x, real-floating y);

intisunordered(real-floating x, real-floating y);

DESCRIPTION

Each of the macros isgreater(), isgreaterequal(), isless(), islessequal(), andislessgreater() take arguments x and y and return a non-zero value if and only ifits nominal relation on x and y is true. These macros always return zero if eitherargument is not a number (NaN), but unlike the corresponding C operators, theynever raise a floating point exception.

The isunordered() macro takes arguments x and y and returns non-zero if andonly if neither x nor y are NaNs. For any pair of floating-point values, one of therelationships (less, greater, equal, unordered) holds.

Note that HFP floating-point values do not support NaN, therefor isunordered()is always false for HFP values.

552 Systems/C C Library

Page 571: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

SEE ALSO

fpclassify(3), math(3), signbit(3)

STANDARDS

The isgreater(), isgreaterequal(), isless(), islessequal(), islessgreater(), andisunordered() macros conform to ISO/IEC 9899:1999 (“ISO C99”).

Systems/C C Library 553

Page 572: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

LDEXP(3)

NAME

ldexp, ldexpf, ldexpl - multiply floating-point number by integral power of 2

SYNOPSIS

#include <math.h>

doubleldexp(double x, int exp);

floatldexpf(float x, int exp);

long doubleldexpl(long double x, int exp);

DESCRIPTION

The ldexp(), ldexpf(), and ldexpl() functions multiply a floating-point numberby an integral power of 2.

RETURN VALUES

These functions return the value of x times 2 raied to the power exp.

SEE ALSO

frexp(3), math(3), modf(3)

STANDARDS

The ldexp(), ldexpf() and ldexpl() functions conform to ISO/IEC 9899:1999(“ISO C99”).

554 Systems/C C Library

Page 573: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

LGAMMA(3)

NAME

lgamma, lgamma r, lgammaf, lgammaf r, lgammal, lgammal r, tgamma, tgammaf,tgammal - log gamma functions, gamma functions

SYNOPSIS

#include <math.h>

extern int signgam;

doublelgamma(double x);

doublelgamma_r(double x, int *signgamp);

floatlgammaf(float x);

floatlgammaf_r(float x, int *signgamp);

doubletgamma(double x);

floattgammaf(float x);

long doubletgammal(long double x);

DESCRIPTION

lgamma(x), lgammaf(x), and lgammal(x) functions return ln |Γ(x)|.

The external integer signgam returns the sign of Γ(x).

lgamma r(x,signgamp), lgammaf r(x,signgamp), and lgammal r(x,signgamp)provide the same functionality as lgamma(x), lgammaf)x) and lgammal(x)but thecaller must provide an integer to store the sign of Γ(x).

The tgamma(x), tgammaf(x), and tgammal(x) functions return Γ(x) with no effecton signgam.

Systems/C C Library 555

Page 574: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

IDIOSYNCRASIES

Do not use the expression “g = signgam*exp(lgamma(x))” to compute g = Γ(x).Instead use a program like this (in C):

lg = lgamma(x); g = signgam*exp(lg);

Only after lgamma() has returned can signgam be correct.

For arguments in its range tgamma() is preferred, as for positive arguments it isaccurate to within one unit in the last place. Exponentiation of lgamma() will loseup to 10 significant bits.

RETURN VALUES

tgamma(), tgammaf(), tgammal(), lgamma(), lgammaf(), lgammal(),lgamma r(), lgammaf r(), lgammal r(), return appropriate values unless anargument is out of range. Overflow will occur for sufficiently large positive val-ues, and non-positive integers. For large non-integer negative values, tgamma(),tgammaf() and tgammal() will underflow.

SEE ALSO

math(3)

STANDARDS

The lgamma(), lgammaf(), lgammal(), tgamma(), tgammaf() and tgam-mal() functions are expected to conform to ISO/IEC 9899:1999 (“ISO C99”).

556 Systems/C C Library

Page 575: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

LOG(3)

NAME

log, logf, logl, log10, log10f, log10l, log1p, log1pf, log1pl, log2, log2f, log2l - logarithmfunctions

SYNOPSIS

#include <math.h>

doublelog(double x);

floatlogf(float x);

long doublelogl(long double x);

doublelog10(double x);

floatlog10f(float x);

long doublelog10l(long double x);

doublelog1p(double x);

floatlog1pf(float x);

long doublelog1pl(long double x);

doublelog2(double x);

floatlog2f(float x);

long doublelog2l(long double x);

Systems/C C Library 557

Page 576: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

DESCRIPTION

The log(), logf() and logl() functions compute the natural logarithm of x.

The log10(), log10f() and log10l() functions compute the logarithm base 10 of x.

The log1p(), log1pf() and log1pl() functions compute the natural logarithm of1+x. Computing the natural logarithm as log1p(x) is more accurate than computingit as log(1 + x) when x is close to zero.

The log2(), log2f() and log2l() functions compute the logarithm base 2 of x.

RETURN VALUES

These functions return the requested logarithm; the logarithm of 1 is +0. Anattempt to take the logarithm of +-0 results in a divide-by-zero exception, and-HUGE VAL is returned. Otherwise, attempting to take the logarithm of a negativenumber results in an invalid exception and a return value of NaN for BFP valuesand 0 for HFP values.

SEE ALSO

exp(3), ilogb(3), math(3), pow(3)

STANDARDS

The log(), logf(), logl(), log10(), log10f(), log10l(), log1p(), log1pf(),log1pl(), log2(), log2f() and log2l() functions conform to ISO/IEC 9899:1999(“ISO C99”).

558 Systems/C C Library

Page 577: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

LRINT(3)

NAME

llrint, llrintf, llrintl, lrint, lrintf, lrintl - convert to integer

SYNOPSIS

#include <math.h>

long longllrint(double x);

long longllrintf(float x);

long longllrintl(long double x);

longlrint(double x);

longlrintf(float x);

longlrintl(long double x);

DESCRIPTION

The lrint() function returns the integer nearest to its argument x according to thecurrent rounding mode. If the rounded result is too large to be represented as a longvalue, an invalid exception is raised and the return value is undefined. Otherwise,if x is not an integer, lrint() raises an inexact exception. When the rounded resultis representable as a long, the expression

lrint(x)

is equivalent to

(long)rint(x)

Systems/C C Library 559

Page 578: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

(although the former may be more efficient).

The llrint(), llrintf(), llrintl(), lrintf(), and lrintl() functions differ from lrint()only in their input and output types.

SEE ALSO

lround(3), math(3), rint(3), round(3)

STANDARDS

These functions conform to ISO/IEC 9899:1999 (“ISO C99”).

560 Systems/C C Library

Page 579: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

LROUND(3)

NAME

llround, llroundf, llroundl, lround, lroundf, lroundl - convert to nearest integral value

SYNOPSIS

#include <math.h>

long longllround(double x);

long longllroundf(float x);

long longllroundl(long double x);

longlround(double x);

longlroundf(float x);

longlroundl(long double x);

DESCRIPTION

The lround() function returns the integer nearest to its argument x, roundingaway from zero in halfway cases. If the rounded result is too large to be representedas a long value, an invalid exception is raised and the return value is undefined.Otherwise, if x is not an integer, lround() may raise an inexact exception. Whenthe rounded result is representable as a long, the expression

lround(x)

is equivalent to

(long)round(x)

Systems/C C Library 561

Page 580: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

(although the former may be more efficient).

The llround(), llroundf(), llroundl(), lroundf() and lroundl() functions differfrom lround() only in their input and output types.

SEE ALSO

lrint(3), math(3), rint(3), round(3)

STANDARDS

The llround(), llroundf(), llroundl(), lround(), lroundf(), and lroundl() func-tions conform to ISO/IEC 9899:1999 (“ISO C99”).

562 Systems/C C Library

Page 581: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

MODF(3)

NAME

modf, modff, modfl - extract signed integral and fractional values from floating-pointnumber

SYNOPSIS

#include <math.h>

doublemodf(double value, double *iptr);

floatmodff(float value, float *iptr);

long doublemodfl(long double value, long double *iptr);

DESCRIPTION

The modf(), modff(), and modfl() functions break the argument value into inte-gral and fractional parts, each of which has the same sign as the argument. It storesthe integral part as a floating point number in the object pointed to by iptr.

RETURN VALUES

These functions return the signed fractional part of value.

SEE ALSO

frexp(3), ldexp(3), math(3)

STANDARDS

The modf(), modff(), and modfl() functions conform to ISO/IEC 9899:1999(“ISO C99”).

Systems/C C Library 563

Page 582: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

NAN(3)

NAME

nan, nanf, nanl - quiet NaNs

SYNOPSIS

#include <math.h>

doublenan(const char *s);

floatnanf(const char *s);

long doublenanl(const char *s);

DESCRIPTION

The NAN macro expands to a quiet NaN (Not A Number). Similarly, each of thenan(), nanf() and nanl() functions generate a quiet NaN value without raisingan invalid exception. The argument s should point to either an empty string ora hexadecimal representation of a non-negative integer (e.g., ”0x1234”.) In thelatter case, the integer is encoded in some free bits in the representation of the NaN,which sometimes store machine-specific information about why a particular NaN wasgenerated. There are 22 such bits available for float variables, 51 bits for doublevariables, and at least 51 bits for a long double. If s is improperly formatted orrepresents an integer that is too large, then the particular encoding of the quiet NaNthat is returned is indeterminate.

Only BFP floating-point supports NaN values. When HFP is enabled, these functionsreturn 0.0.

COMPATIBILITY

Calling these functions with a non-empty string isn’t portable. Another implemen-tation may translate the string into a different NaN encoding, and furthermore, themeaning of a given NaN encoding varies across machine architectures.

564 Systems/C C Library

Page 583: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

SEE ALSO

fenv(3), isnan(3), math(3), strtod(3)

STANDARDS

The nan(), nanf(), and nanl() functions and the NAN macro conform to ISO/IEC9899:1999 (“ISO C99”).

Systems/C C Library 565

Page 584: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

NEXTAFTER(3)

NAME

nextafter, nextafterf, nextafterl, nexttoward, nexttowardf, nexttowardl - next rep-resentable value

SYNOPSIS

#include <math.h>

doublenextafter(double x, double y);

floatnextafterf(float x, float y);

long doublenextafterl(long double x, long double y);

doublenexttoward(double x, long double y);

floatnexttowardf(float x, long double y);

long doublenexttowardl(long double x, long double y);

DESCRIPTION

These functions return the next machine representable number from x in directiony. The returned value may not be normalized, for either HFP or BFP.

SEE ALSO

math(3)

STANDARDS

The nextafter(), nextafterf(), nextafterl(), nexttoward(), nexttowardf(),and nexttowardl() routines conform to ISO/IEC 9899:1999 (“ISO C99”).

566 Systems/C C Library

Page 585: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

REMAINDER(3)

NAME

remainder, remainderf, remainderl, remquo, remquof, remquol - minimal residuefunctions

SYNOPSIS

#include <math.h>

doubleremainder(double x, double y);

floatremainderf(float x, float y);

long doubleremainderl(long double x, long double y);

doubleremquo(double x, double y, int *quo);

floatremquof(float x, float y, int *quo);

long doubleremquol(long double x, long double y, int *quo);

DESCRIPTION

remainder(), remainderf(), remainderl(), remquo(), remquof(), andremquol() return the remainder r := x - n*y where n is the integer nearest theexact value of x/y; moreover if —n - x/y— = 1/2 then n is even. Consequently theremainder is computed exactly and —r— ¡= —y—/2. But attempting to take theremainder when y is 0 or x is +-infinity is an invalid operation that produces a NaN.

The remquo(), remquof(), and remquol() functions also store the last k bits ofn in the location pointed to by quo, provided that n exists. The number of bits k isplatform-specific, but is guaranteed to be at least 3.

SEE ALSO

fmod(3), math(3)

Systems/C C Library 567

Page 586: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

STANDARDS

The remainder(), remainderf(), remainderl(), remquo(), remquof(), andremquol() routines conform to ISO/IEC 9899:1999 (“ISO C99”).

568 Systems/C C Library

Page 587: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

RINT(3)

NAME

nearbyint, nearbyintf, nearbyintl, rint, rintf, rintl - round to integral value infloating-point format

SYNOPSIS

#include <math.h>

doublenearbyint(double x);

floatnearbyintf(float x);

long doublenearbyintl(long double x);

doublerint(double x);

floatrintf(float x);

long doublerintl(long double x);

DESCRIPTION

The rint(), rintf(), and rintl() functions return the integral value nearest to x. ForBFP values, the rounding is performed according to the prevailing rounding mode.For HFP values, the rounding mode is always round-toward-zero. These functionsraise an inexact exception when the original argument is not an exact integer.

The nearbyint(), nearbyintf(), and nearbyintl() functions perform the sameoperation, except that they do not raise an inexact exception.

SEE ALSO

abs(3), ceil(3), fabs(3), fenv(3), floor(3), lrint(3), lround(3), math(3), round(3)

Systems/C C Library 569

Page 588: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

STANDARDS

These functions conform to ISO/IEC 9899:1999 (“ISO C99”).

570 Systems/C C Library

Page 589: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

ROUND(3)

NAME

round, roundf, roundl - round to nearest integral value

SYNOPSIS

#include <math.h>

doubleround(double x);

floatroundf(float x);

long doubleroundl(long double x);

DESCRIPTION

The round(), roundf(), and roundl() functions return the nearest integral valueto x; if x lies halfway between two integral values, then these functions return theintegral value with the larger absolute value (i.e., they round away from zero).

SEE ALSO

ceil(3), floor(3), lrint(3), lround(3), math(3), rint(3), trunc(3)

STANDARDS

These functions conform to ISO/IEC 9899:1999 (“ISO C99”).

Systems/C C Library 571

Page 590: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

SIGNBIT(3)

NAME

signbit - determine whether a floating-point number’s sign is negative

SYNOPSIS

#include <math.h>

intsignbit(real-floating x);

DESCRIPTION

The signbit() macro takes an argument of x and returns non-zero if the value of itssign is negative, otherwise 0.

SEE ALSO

fpclassify(3), math(3)

STANDARDS

The signbit() macro conforms to ISO/IEC 9899:1999 (“ISO C99”).

572 Systems/C C Library

Page 591: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

SIN(3)

NAME

sin, sinf, sinl - sine functions

SYNOPSIS

#include <math.h>

doublesin(double x);

floatsinf(float x);

long doublesinl(long double x);

DESCRIPTION

The sin(), sinf() and sinl() functions compute the sine of x (measured in radians).A large magnitude argument may yield a result with little or no significance.

RETURN VALUES

The sin(), sinf() and sinl() functions return the sine value.

SEE ALSO

acos(3), asin(3), atan(3), atan2(3), cos(3), cosh(3), math(3), sinh(3), tan(3), tanh(3)

STANDARDS

The sin() function conforms to ISO/IEC 9899:1990 (“ISO C90”).

The sinf() and sinl() functions conform to ISO/IEC 9899:1999 (“ISO C99”).

Systems/C C Library 573

Page 592: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

SINH(3)

NAME

sinh, sinhf, sinhl - hyperbolic sine function

SYNOPSIS

#include <math.h>

doublesinh(double x);

floatsinhf(float x);

long doublesinhl(long double x);

DESCRIPTION

The sinh(), sinhf() and sinhl() functions computes the hyperbolic sine of x.

RETURN VALUES

The sinh(), sinhf() and sinhl() functions return the hyperbolic sine value.

SEE ALSO

acos(3), asin(3), atan(3), atan2(3), cos(3), cosh(3), math(3), sin(3), tan(3), tanh(3)

STANDARDS

The sinh() function conforms to ISO/IEC 9899:1990 (“ISO C90”).

The sinhf() and sinhl() functions conform to ISO/IEC 9899:1999 (“ISO C99”).

574 Systems/C C Library

Page 593: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

SQRT(3)

NAME

cbrt, cbrtf, sqrt, sqrtf, sqrtl – cube root and square root functions

SYNOPSIS

#include <math.h>

doublecbrt(double x);

floatcbrtf(float x);

doublesqrt(double x);

floatsqrtf(float x);

long doublesqrtl(long double x);

DESCRIPTION

The cbrt(), cbrtf() and cbrtl() functions compute the cube root of x.

The sqrt(), sqrtf() and sqrtl() functions compute the non-negative square root ofx.

RETURN VALUES

The cbrt(), cbrtf() and cbrtl() functions return the requested cube root. Thesqrt(), sqrtf() and sqrtl() functions return the requested square root unless anerror occurs. An attempt to take the square root of a negative x causes an error; inthis event, the global variable errno is set to EDOM and 0.0 is returned, or for BFPvalues a NaN is returned.

SEE ALSO

fenv(3), math(3)

Systems/C C Library 575

Page 594: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

STANDARDS

The sqrt() function conforms to ISO/IEC 9899:1990 (“ISO C90”).

The cbrt(), cbrtf(), cbrtl(), sqrtf() and sqrtl() functions conforms to ISO/IEC9899:1999 (“ISO C99”).

576 Systems/C C Library

Page 595: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

TAN(3)

NAME

tan, tanf, tanl - tangent functions

SYNOPSIS

#include <math.h>

doubletan(double x);

floattanf(float x);

long doubletanl(long double x);

DESCRIPTION

The tan(), tanf() and tanl() functions compute the tangent of x (measured in ra-dians). A large magnitude argument may yield a result with little or no significance.

RETURN VALUES

The tan(), tanf() and tanl() functions return the tangent value.

SEE ALSO

acos(3), asin(3), atan(3), atan2(3), cos(3), cosh(3), math(3), sin(3), sinh(3), tanh(3)

STANDARDS

The tan() function conforms to ISO/IEC 9899:1990 (“ISO C90”).

The tanf() and tanl() functions conform to ISO/IEC 9899:1999 (“ISO C99”).

STANDARDS

Systems/C C Library 577

Page 596: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

TANH(3)

NAME

tanh, tanhf, tanhl - hyperbolic tangent function

SYNOPSIS

#include <math.h>

doubletanh(double x)

floattanhf(float x)

long doubletanhl(long double x)

DESCRIPTION

The tanh(), tanhf() and tanhl() functions compute the hyperbolic tangent of x.

RETURN VALUES

The tanh(), tanhf() and tanhl() functions return the hyperbolic tangent value.

SEE ALSO

acos(3), asin(3), atan(3), atan2(3), cos(3), cosh(3), math(3), sin(3), sinh(3), tan(3)

STANDARDS

The tanh() function conforms to ISO/IEC 9899:1990 (“ISO C90”).

The tanhf() and tanhl() functions conform to ISO/IEC 9899:1999 (“ISO C99”).

578 Systems/C C Library

Page 597: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

TRUNC(3)

NAME

trunc, truncf, truncl - nearest integral value with magnitude less than or equal to|x|

SYNOPSIS

#include <math.h>

doubletrunc(double x);

floattruncf(float x);

long doubletruncl(long double x);

DESCRIPTION

The trunc(), truncf() and truncl() functions return the nearest integral valuewith magnitude less than or equal to |x|. They are equivalent to rint(), rintf(),and rintl(), respectively, in the FE TOWARDZERO rounding mode.

SEE ALSO

ceil(3), fesetround(3), floor(3), math(3), nextafter(3), rint(3), round(3)

STANDARDS

The trunc(), truncf(), and truncl() functions conform to ISO/IEC 9899:1999(“ISO C99”).

Systems/C C Library 579

Page 598: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

Standard I/O Library

The ANSI C standard provides for a set of input and output functions known asthe Standard I/O Library.

580 Systems/C C Library

Page 599: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

STDIO(3)

NAME

stdio - standard input/output library functions

SYNOPSIS

#include <stdio.h>FILE *stdin;FILE *stdout;FILE *stderr;

DESCRIPTION

The standard I/O library provides a simple and efficient buffered stream I/O in-terface. Input and output is mapped into logical data streams and the physicalI/O characteristics are concealed. The functions and macros are listed below; moreinformation is available from the individual man pages.

A stream is associated with an external file (which may be a physical device) byopening a file, which may involve creating a new file. Creating an existing file causesits former contents to be discarded. If a file can support positioning requests (suchas a disk file, as opposed to a terminal) then a file position indicator associated withthe stream is positioned at the start of the file (byte zero), unless the file is openedwith append mode. If append mode is used, the position indicator will be placedthe end-of-file. The position indicator is maintained by subsequent reads, writes andpositioning requests. All input occurs as if the characters were read by successivecalls to the fgetc(3) function; all output takes place as if all characters were read bysuccessive calls to the fputc(3) function.

A file is disassociated from a stream by closing the file. Output streams are flushed(any unwritten buffer contents are transferred to the host environment) before thestream is disassociated from the file. The value of a pointer to a FILE object isindeterminate after a file is closed (garbage).

A file may be subsequently reopened, by the same or another program execution,and its contents reclaimed or modified (if it can be repositioned at the start). If themain function returns to its original caller, or the exit(3) function is called, all openfiles are closed (hence all output streams are flushed) before program termination.Other methods of program termination such as abort(3) do not bother to close filesproperly.

This implementation makes a distinction between “text” and “binary” streams.Records written in non-binary mode are padded after a new-line is written to fill

Systems/C C Library 581

Page 600: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

the record. If no new-line is written before the record length is exhausted, the recordwill be “split”. That is, when the record length is reached, the record will be writtenand a new one started.

At program startup, three streams are predefined and need not be opened explicitly:

• standard input (for reading conventional input)

• standard output (for writing conventional output) and

• standard error (for writing diagnostic output).

These streams are abbreviated stdin, stdout and stderr. Initially, the standarderror stream is unbuffered, the standard input and output streams are fully bufferedif and only if the streams do not refer to an interactive or “terminal” device, asdetermined by the isatty(3) function. In fact, all freshly-opened streams that referto terminal device default to line buffering, and pending output to such streamsis written automatically whenever an such an input stream is read. Note thatthis applies only to “true reads”; if the read request can be satisfied by existingbuffered data, no automatic flush will occur. In these cases, or when a large amountof computation is done after printing part of a line on an output terminal, it isnecessary to fflush(3) the standard output before going off and computing so thatthe output will appear.

Alternatively, these defaults may be modified via the setvbuf(3) function.

The SYNOPSIS sections of the following information indicate which include filesare to be used, what the compiler declaration for the function looks like and whichexternal variables are of interest.

The following are defined as macros; these names may not be re-used withoutfirst removing their current definitions with #undef: BUFSIZ, EOF, FILENAME MAX,FOPEN MAX, L cuserid, L ctermid, L tmpnam, NULL, SEEK END, SEEK SET, SEEK CUR,TMP MAX, clearerr, feof, ferror, fileno, reopen, fwopen, getc, getchar, putc,putchar, stderr, stdin, stdout. Function versions of the macro functions feof(),ferror(), clearerr(), fileno(), getc(), getchar(), putc(), and putchar() existand will be used if the macros definitions are explicitly removed.

SEE ALSO

close(2), open(2), read(2), write(2)

ISSUES

The standard buffered functions do not interact well with certain other library andsystem functions, especially abort(3).

582 Systems/C C Library

Page 601: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

STANDARDS

The stdio library conforms to ISO/IEC 9899:1990 (“ISO C90”).

LIST OF FUNCTIONS

Function Description

clearerr check and reset stream status

fclose close a stream

fdopen stream open functions

feof check and reset stream status

ferror check and reset stream status

fflush flush a stream

fgetc get next character or word from input stream

fgetln get a line from a stream

fgetpos reposition a stream

fgets get a line from a stream

fileno check and reset stream status

fopen stream open functions

fprintf formatted output conversion

fpurge flush a stream

fputc output a character or word to a stream

fputs output a line to a stream

fread binary stream input/output

freopen stream open functions

fropen open a stream

fscanf input format conversion

fseek reposition a stream

fsetpos reposition a stream

ftell reposition a stream

funopen open a stream

Systems/C C Library 583

Page 602: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

fwopen open a stream

fwrite binary stream input/output

getc get next character or word from input stream

getchar get next character or word from input stream

getdelim get a line from a stream

getline get a line from a stream

gets get a line from a stream

getw get next character or word from input stream

mkstemp create unique temporary file

mktemp create unique temporary file

perror system error messages

printf formatted output conversion

putc output a character or word to a stream

putchar output a character or word to a stream

puts output a line to a stream

putw output a character or word to a stream

remove remove directory entry

rewind reposition a stream

scanf input format conversion

setbuf stream buffering operations

setbuffer stream buffering operations

setlinebuf stream buffering operations

setvbuf stream buffering operations

snprintf formatted output conversion

sprintf formatted output conversion

sscanf input format conversion

strerror system error messages

sys errlist system error messages

sys nerr system error messages

584 Systems/C C Library

Page 603: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

tempnam temporary file routines

tmpfile temporary file routines

tmpnam temporary file routines

ungetc un-get character from input stream

vfprintf formatted output conversion

vfscanf input format conversion

vprintf formatted output conversion

vscanf input format conversion

vsnprintf formatted output conversion

vsprintf formatted output conversion

vsscanf input format conversion

Systems/C C Library 585

Page 604: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

FCLOSE(3)

NAME

fclose - close a stream

SYNOPSIS

#include <stdio.h>

intfclose(FILE *stream)

DESCRIPTION

The fclose() function dissociates the named stream from its underlying file or setof functions. If the stream was being used for output, any buffered data is writtenfirst, using fflush(3).

RETURN VALUES

Upon successful completion 0 is returned. Otherwise, EOF is returned and the globalvariable errno is set to indicate the error. In either case no further access to thestream is possible.

ERRORS

[EBADF] The argument stream is not an open stream.

The fclose() function may also fail and set errno for any of the errors specified forthe routines close(2) or fflush(3).

SEE ALSO

close(2), fflush(3), fopen(3), setbuf(3)

STANDARDS

The fclose() function conforms to ISO/IEC 9899:1990 (“ISO C90”).

586 Systems/C C Library

Page 605: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

FERROR(3)

NAME

clearerr, feof, ferror, fileno - check and reset stream status

SYNOPSIS

#include <stdio.h>

voidclearerr(FILE *stream)

intfeof(FILE *stream)

intferror(FILE *stream)

intfileno(FILE *stream)

DESCRIPTION

The function clearerr() clears the end-of-file and error indicators for the streampointed to by stream.

The function feof() tests the end-of-file indicator for the stream pointed to bystream, returning non-zero if it is set. The end-of-file indicator can only be clearedby the function clearerr().

The function ferror() tests the error indicator for the stream pointed to by stream,returning non-zero if it is set. The error indicator can only be reset by the clearerr()function.

The function fileno() examines the argument stream and returns its integer de-scriptor.

ERRORS

These functions should not fail and do not set the external variable errno.

Systems/C C Library 587

Page 606: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

SEE ALSO

open(2), stdio(3)

STANDARDS

The functions clearerr(), feof(), and ferror() conform to ISO/IEC 9899:1990(“ISO C”).

588 Systems/C C Library

Page 607: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

FFLUSH(3)

NAME

fflush, fpurge - flush a stream

SYNOPSIS

#include <stdio.h>

intfflush(FILE *stream)

intfpurge(FILE *stream)

DESCRIPTION

The function fflush() forces a write of all buffered data for the given output orupdate stream via the stream’s underlying write function. The open status of thestream is unaffected.

If the stream argument is NULL, fflush() flushes all open output streams.

The function fpurge() erases any input or output buffered in the given stream. Foroutput streams this discards any unwritten output. For input streams this discardsany input read from the underlying object but not yet obtained via getc(3). Thisincludes any text pushed back via ungetc.

RETURN VALUES

Upon successful completion 0 is returned. Otherwise, EOF is returned and the globalvariable errno is set to indicate the error.

ERRORS

[EBADF] Stream is not an open stream, or, in the case of fflush(), not astream open for writing.

The function fflush() may also fail and set errno for any of the errors specified forthe routine write(2).

Systems/C C Library 589

Page 608: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

SEE ALSO

write(2), fclose(3), fopen(3), setbuf(3)

STANDARDS

The fflush() function conforms to ISO/IEC 9899:1990 (“ISO C90”).

590 Systems/C C Library

Page 609: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

FGETLN(3)

NAME

fgetln - get a line from a stream

SYNOPSIS

#include <stdio.h>

char *fgetln(FILE *stream, size_t *len)

DESCRIPTION

The fgetln() function returns a pointer to the next line from the stream referencedby stream. This line is not a C string as it does not end with a terminating NULcharacter. The length of the line, including the final newline, is stored in the memorylocation to which len points. (Note, however, that if the line is the last in a file thatdoes not end in a newline, the returned text will not contain a newline.)

RETURN VALUES

Upon successful completion a pointer is returned; this pointer becomes invalid afterthe next I/O operation on stream (whether successful or not) or as soon as thestream is closed. Otherwise, NULL is returned. The fgetln() function does notdistinguish between end-of-file and error; the routines feof(3) and ferror(3) must beused to determine which occurred. If an error occurs, the global variable errno is setto indicate the error. The end-of-file condition is remembered, even on a terminal,and all subsequent attempts to read will return NULL until the condition is clearedwith clearerr(3).

The text to which the returned pointer points may be modified provided that nochanges are made beyond the returned size. These changes are lost as soon as thepointer becomes invalid.

ERRORS

[EBADF] The argument stream is not a stream open for reading.

The fgetln() function may also fail and set errno for any of the errors specified forthe routines fflush(3), mallow(3), read(2), stat(2), or realloc(3).

Systems/C C Library 591

Page 610: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

SEE ALSO

ferror(3), fgets(3), fopen(3), putc(3)

592 Systems/C C Library

Page 611: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

FGETWLN(3)

NAME

fgetwln - get a line of wide characters from a stream

SYNOPSIS

#include <stdio.h>#include <wchar.h>

wchar_t *fgetwln(FILE * restrict stream, size_t * restrict len)

DESCRIPTION

The fgetwln() function returns a pointer to the next line from the stream referencedby stream. This line is not a standard wide character string as it does not end with aterminating null wide character. The length of the line, including the final newline,is stored in the memory location to which len points. (Note, however, that if theline is the last in a file that does not end in a newline, the returned text will notcontain a newline.)

RETURN VALUES

Upon successful completion a pointer is returned; this pointer becomes invalid afterthe next I/O operation on stream (whether successful or not) or as soon as thestream is closed. Otherwise, NULL is returned. The fgetwln() function does notdistinguish between end-of-file and error; the routines feof(3) and ferror(3) must beused to determine which occurred. If an error occurs, the global variable errno is setto indicate the error. The end-of-file condition is remembered, even on a terminal,and all subsequent attempts to read will return NULL until the condition is clearedwith clearerr(3).

The text to which the returned pointer points may be modified, provided that nochanges are made beyond the returned size. These changes are lost as soon as thepointer becomes invalid.

ERRORS

[EBADF] The argument stream is not a stream open for reading.

The fgetwln() function may also fail and set errno for any of the errors specifiedfor the routines mbrtowc(3), realloc(3), or read(2).

Systems/C C Library 593

Page 612: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

SEE ALSO

ferror(3), fgetln(3), fgetws(3), fopen(3)

594 Systems/C C Library

Page 613: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

GETLINE(3)

NAME

getdelim, getline - get a line from a stream

SYNOPSIS

#define _WITH_GETLINE

#include <stdio.h>

ssize_tgetdelim(char ** restrict linep, size_t * restrict linecapp,int delimiter, FILE * restrict stream);

ssize_tgetline(char ** restrict linep, size_t * restrict linecapp,FILE * restrict stream);

DESCRIPTION

The getdelim() function reads a line from stream, delimited by the character delim-iter. The getline() function is equivalent to getdelim() with the newline characteras the delimiter. The delimiter character is included as part of the line, unless theend of the file is reached.

The caller may provide a pointer to a malloc’d buffer for the line in *linep, and thecapacity of that buffer in *linecapp. These functions expand the buffer as needed,as if via realloc(). If linep points to a NULL pointer, a new buffer will be allocated.In either case, *linep and *linecapp will be updated accordingly.

RETURN VALUES

The getdelim() and getline() functions return the number of characters stored inthe buffer, excluding the terminating NUL character. The value -1 is returned if anerror occurs, or if end-of-file is reached.

EXAMPLES

The following code fragment reads lines from a file and writes them to standardoutput. The fwrite() function is used in case the line contains embedded NULcharacters.

Systems/C C Library 595

Page 614: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

char *line = NULL;size_t linecap = 0;ssize_t linelen;while ((linelen = getline(&line, &linecap, fp)) > 0)fwrite(line, linelen, 1, stdout);free(line);

COMPATIBILITY

Many application writers used the name getline before the getline() functionwas introduced in IEEE Std 1003.1 (“POSIX.1”), so a prototype is not providedby default in order to avoid compatibility problems. Applications that wish to usethe getline() function described herein should either request a strict IEEE Std1003.1-2008 (“POSIX.1”) environment by defining the macro POSIX C SOURCE tothe value 200809 or greater, or by defining the macro WITH GETLINE, prior to theinclusion of ¡stdio.h¿. For compatibility with GNU libc, defining either BSD SOURCEor GNU SOURCE prior to the inclusion of ¡stdio.h¿ will also make getline() available.

ERRORS

These functions may fail if:

[EINVAL] Either linep or linecapp is NULL.

[EOVERFLOW] No delimiter was found in the first SSIZE MAX characters.

These functions may also fail due to any of the errors specified for fgets() andmalloc().

SEE ALSO

fgetln(3), fgets(3), malloc(3)

STANDARDS

The getdelim() and getline() functions conform to IEEE Std 1003.1-2008(“POSIX.1”).

ISSUES

There are no wide character versions of getdelim() or getline().

596 Systems/C C Library

Page 615: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

FGETS(3)

NAME

fgets, gets - get a line from a stream

SYNOPSIS

#include <stdio.h>

char *fgets(char *str, int size, FILE *stream)

char *gets(char *str)

DESCRIPTION

The fgets() function reads at most one less than the number of characters specifiedby size from the given stream and stores them in the string str. Reading stops whena newline character is found, at end-of-file or error. The newline, if any, is retained.If any characters are read and there is no error, a ’\0’ character is appended toend the string.

The gets() function is equivalent to fgets() with an infinite size and a stream ofstdin, except that the newline character (if any) is not stored in the string. It isthe caller’s responsibility to ensure that the input line, if any, is sufficiently short tofit in the string.

RETURN VALUES

Upon successful completion, fgets() and gets() return a pointer to the string. Ifend-of-file occurs before any characters are read, they return NULL and the buffercontent is unchanged. If an error occurs, they return NULL and the buffer contentis indeterminate. The fgets() and gets() functions do not distinguish betweenend-of-file and error, and callers must use feof(3) and ferror(3) to determine whichoccurred.

ERRORS

[EBADF] The given stream is not a readable stream.

Systems/C C Library 597

Page 616: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

The function fgets() may also fail and set errno for any of the errors specified forthe routines fflush(3), fstat(2), read(2), or malloc(3).

The function gets() may also fail and set errno for any of the errors specified forthe routine getchar(3).

SEE ALSO

feof(3), ferror(3), fgetln(3)

STANDARDS

The functions fgets() and gets() conform to ISO/IEC 9899:1990 (“ISO C90”).

ISSUES

Since it is usually impossible to ensure that the next input line is less than somearbitrary length, and because overflowing the input buffer is almost invariably asecurity violation, programs should NEVER use gets().

The gets() function exists purely to conform to ISO/IEC 9899:1990 (“ISO C90”).

598 Systems/C C Library

Page 617: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

FGETWS(3)

NAME

fgetws - get a line of wide characters from a stream

SYNOPSIS

#include <stdio.h>#include <wchar.h>

wchar_t *fgetws(wchar_t * restrict ws, int n, FILE * restrict fp)

DESCRIPTION

The fgetws() function reads at most one less than the number of characters specifiedby n from the given fp and stores them in the wide character string ws. Readingstops when a newline character is found, at end-of-file or error. The newline, if any,is retained. If any characters are read and there is no error, a ’\0’ character isappended to end the string.

RETURN VALUES

Upon successful completion, fgetws() returns ws. If end-of-file occurs before anycharacters are read, fgetws() returns NULL and the buffer contents remain un-changed. If an error occurs, fgetws() returns NULL and the buffer contents areindeterminate. The fgetws() function does not distinguish between end-of-file anderror, and callers must use feof(3) and ferror(3) to determine which occurred.

ERRORS

The fgetws() function will fail if:

[EBADF] The given fp argument is not a readable stream.

[EILSEQ] The data obtained from the input stream does not form a validmultibyte character.

The function fgetws() may also fail and set errno for any of the errors specifiedfor the routines fflush(3), fstat(2), read(2), or malloc(3).

Systems/C C Library 599

Page 618: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

SEE ALSO

feof(3), ferror(3), fgets(3)

STANDARDS

The fgetws() function conforms to IEEE Std 1003.1-2001 (“POSIX.1”).

600 Systems/C C Library

Page 619: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

FOPEN(3)

NAME

fopen, fdopen, freopen - stream open functions

SYNOPSIS

#include <stdio.h>

FILE *fopen(char *path, char *mode)

FILE *fdopen(int fildes, char *mode)

FILE *freopen(char *path, char *mode, FILE *stream)

DESCRIPTION

The fopen() function opens the file whose name is the string pointed to by pathand associates a stream with it.

The argument mode points to a string beginning with one of the following sequences(Additional characters may follow these sequences.):

“r” Open text file for reading. The stream is positioned at the beginning of thefile.

“r+” Open for reading and writing. The stream is positioned at the beginning ofthe file.

“w” Truncate file to zero length or create text file for writing. The stream ispositioned at the beginning of the file.

“w+” Open for reading and writing. The file is created if it does not exist, otherwiseit is truncated. The stream is positioned at the beginning of the file.

“a” Open for writing. The file is created if it does not exist. The stream ispositioned at the end of the file.

“a+” Open for reading and writing. The file is created if it does not exist. Thestream is positioned at the end of the file.

Systems/C C Library 601

Page 620: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

The mode string can also include the letter “b” either as a third character or asa character between the characters in any of the two-character strings describedabove. The “b” indicates that I/O should be performed in binary mode, instead ofthe default text mode.

If a comma is found after the mode specification, the remaining text is taken to beDCB attributes which will be passed to the open(2) function. See open(2) for adescription of these attributes.

Reads and writes may be intermixed on read/write streams in any order, and do notrequire an intermediate seek as in other versions of studio. This is not portable toother systems. However; ANSI C requires that a file positioning function intervenebetween output and input, unless an input operation encounters end-of-file.

The fdopen() function associates a stream with the existing file descriptor, fildes.The mode of the stream must be compatible with the mode of the file descriptor.

The freopen() function opens the file whose name is the string pointed to by pathand associates the stream pointed to by stream with it. The original stream (ifit exists) is closed. The mode argument is used just as in the fopen() function.The primary use of the freopen() function is to change the file associated with astandard text stream (stderr, stdin, or stdout).

RECORD I/O

If the type=record attribute is specified after the mode specification; the lower-levelfile descriptor will be processed in “record I/O” mode. In this mode, the file is setto non-buffering to directly pass write requests to the lower level write functions.Any read processing should reset the file buffer to a buffer size sufficient to handlethe expected record length of the file. See the fread(3) and fwrite(3) sections formore information regarding record I/O.

RETURN VALUES

Upon successful completion fopen(), fdopen() and freopen() return a FILEpointer. Otherwise, NULL is returned and the global variable errno is set to in-dicate the error.

EXAMPLE

The following opens the file specified by the character pointer output file name,for text output. Note that it uses the DCB attributes string to specify that the fileformat should be FIXED BLOCKED, with a block size of 8000 and a logical recordlength of 80:

602 Systems/C C Library

Page 621: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

char *output_file_name;FILE *output_file;

...output_file = fopen(output_file_name,

"w,recfm=fb,blksize=8000,lrecl=80");

ERRORS

[EINVAL] The mode provided to fopen(), fdopen(), or freopen() was in-valid.

The fopen(), fdopen() and freopen() functions may also fail and set errno forany of the errors specified for the routine malloc(3).

The fopen() function may also fail and set errno for any of the errors specified forthe routine open(2).

The fdopen() function may also fail and set errno for any of the errors specifiedfor the routine fcntl(2).

The freopen() function may also fail and set errno for any of the errors specifiedfor the routines open(2), fclose(3) and fflush(3).

SEE ALSO

open(2), fclose(3), fseek(3), funopen(3)

ISSUES

fopen() is based on open(). Any restrictions mentioned on the open(3) descriptionapply to fopen().

STANDARDS

The fopen() and freopen() functions conform to ISO/IEC 9899:1990 (“ISO C90”).The fdopen() function conforms to IEEE Std1003.1-1988 (“POSIX”).

Systems/C C Library 603

Page 622: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

FPUTS(3)

NAME

fputs, puts - output a line to a stream

SYNOPSIS

#include <stdio.h>

intfputs(const char *str, FILE *stream)

intputs(const char *str)

DESCRIPTION

The function fputs() writes the string pointed to by str to the stream pointed toby stream.

The function puts() writes the string str, and a terminating newline character, tothe stream stdout.

RETURN VALUES

The fputs() function returns 0 on success and EOF on error; puts() returns anonnegative integer on success and EOF on error.

ERRORS

[EBADF] The stream supplied is not a writable stream.

The functions fputs() and puts() may also fail and set errno for any of the errorsspecified for the routines write(2).

SEE ALSO

ferror(3), putc(3), stdio(3)

604 Systems/C C Library

Page 623: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

STANDARDS

The functions fputs() and puts() conform to ISO/IEC 9899:1990 (“ISO C90”).

Systems/C C Library 605

Page 624: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

FPUTWS(3)

NAME

fputws - output a line of wide characters to a stream

SYNOPSIS

#include <stdio.h>#include <wchar.h>

intfputws(const wchar_t * restrict ws, FILE * restrict fp)

DESCRIPTION

The fputws() function writes the wide character string pointed to by ws to thestream pointed to by fp.

RETURN VALUES

The fputws() function returns 0 on success and -1 on error.

ERRORS

The fputws() function will fail if:

[EBADF] The fp argument supplied is not a writable stream.

The fputws() function may also fail and set errno for any of the errors specifiedfor the routine write(2).

SEE ALSO

ferror(3), fputs(3), putwc(3), stdio(3)

STANDARDS

The fputws() function conforms to IEEE Std 1003.1-2001 (“POSIX.1”).

606 Systems/C C Library

Page 625: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

FREAD(3)

NAME

fread, fwrite - binary stream input/output

SYNOPSIS

#include <stdio.h>

size_tfread(void *ptr, size_t size, size_t nmemb,FILE *stream)

size_tfwrite(const void *ptr, size_t size, size_t nmemb,FILE *stream)

DESCRIPTION

The function fread() reads nmemb objects, each size bytes long, from the streampointed to by stream, storing them at the location given by ptr.

The function fwrite() writes nmemb objects, each size bytes long, to the streampointed to by stream, obtaining them from the location given by ptr.

RECORD I/O

If the stream was opened with the attribute of type=record, then the lower-levelread/write operation is performed in “record I/O” mode. Furthermore, the streamis set to be unbuffered.

For fwrite(), the unbuffered stream causes the specified number of bytes (size *nmemb) to be directly passed to the write() operation and written as one record. Asubsequent fwrite() will advance to the next output record.

For fread(), the unbuffered stream will cause a read of 1 byte from each record inthe input file. Thus, for fread(), the buffer should be reset using setvbuf(3), to asize that is appropriate for the expected maximum input record length. Then, thelower-level read operation will fill this buffer with a single record, and that bufferwill used to satisfy the fread() request. When record-I/O is employed, every callto fread() forces a refresh of the input buffer by invoking read(2) to read the nextrecord.

Systems/C C Library 607

Page 626: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

For example, to read a variable-length file MYFILE a record a time; where the maxi-mum record length in MYFILE is 8000 bytes:

char record[8000];FILE *f;int num_read, rec_len;

/* open the binary file in record-I/O mode */f = fopen("MYFILE", "rb,type=record");

/* set the input buffering to be record-sized */setvbuf(f, NULL, _IOFBF, 8000);

/* read a record */num_read = fread(record, 1, 8000, f);

Note that the size value in this example is set to 1, and the number of elements(nmemb) is set to 8000, allowing fread() to return the number of bytes read on therecord.

RETURN VALUES

The functions fread() and fwrite() advance the file position indicator for thestream by at least the number of bytes read or written. They return the num-ber of objects read or written. If an error occurs, or the end-of-file is reached, thereturn value is a short object count (or zero).

The function fread() does not distinguish between end-of-file and error. Callersmust use feof(3) and ferror(3) to determine which occurred. The function fwrite()returns a value less than nmemb only if a write error has occurred, or the the amountof data is larger than the maximum record length when using “record I/O”.

When reading from a variable-length record using “record I/O” (type=record), itis possible to read a zero-length record. In this case, there is no data read; which istypically the situation end-of-file. In this event, the lower-level read() will set theerror condition, with errno set to EAGAIN. Thus, programs using fread() readingfrom variable-length input with type=record need to be aware that ferror()(3) willbe true for zero-length input records. The error should be cleared with clearerr()(3)to proceed to the next record. This approach allows the program to distinguishbetween reading a zero-length record and reaching end-of-file.

Writing to variable-length record files cannot produce a zero-length record. If it isdesired to produce zero-length records in the resulting output file, then the write()(2)function with type=record should be used.

608 Systems/C C Library

Page 627: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

SEE ALSO

read(2), write(2)

STANDARDS

The functions fread() and fwrite() conform to ISO/IEC 9899:1990 (“ISO C90”).

Systems/C C Library 609

Page 628: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

FSEEK(3)

NAME

fgetpos, fseek, fseeko, fsetpos, ftell, ftello, rewind - reposition a stream

SYNOPSIS

#include <stdio.h>

intfseek(FILE *stream, long offset, int whence)

longftell(FILE *stream)

voidrewind(FILE *stream)

intfgetpos(FILE *stream, fpos_t *pos)

intfsetpos(FILE *stream, fpos_t *pos)

intfseeko(FILE *stream, off_t offset, int whence);

off_tftello(FILE *stream);

DESCRIPTION

The fseek() function sets the file position indicator for the stream pointed to bystream. The new position, measured in bytes, is obtained by adding offset bytesto the position specified by whence. If whence is set to SEEK SET, SEEK CUR, orSEEK END, the offset is relative to the start of the file, the current position indicator,or end-of-file, respectively. A successful call to the fseek() function clears the end-of-file indicator for the stream and undoes any effects of the ungetc(3) function onthe same stream.

The ftell() function obtains the current value of the file position indicator for thestream pointed to by stream.

610 Systems/C C Library

Page 629: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

The rewind() function sets the file position indicator for the stream pointed to bystream to the beginning of the file. It is equivalent to:

(void)fseek(stream, 0L, SEEK_SET)

except that the error indicator for the stream is also cleared (see clearerr(3)).

The fseeko() function is identical to fseek(), except it takes an off t argumentinstead of a long. Likewise, the ftello() function is identical to ftell(), except itreturns an off t.

The fgetpos() and fsetpos() functions are alternate interfaces equivalent to ftell()and fseek() (with whence set to SEEK SET), setting and storing the current valueof the file offset into or from the object referenced by pos. The fpos t object maybe a complex object and these routines may be the only way to reposition a textstream in a portable fashion.

RETURN VALUES

The rewind() function returns no value.

The fgetpos(), fseek(), fseeko() and fsetpos() functions return the value 0 ifsuccessfu; otherwise the value -1 is returned and the global variable errno is set toindicate the error.

Upon successful completion, ftell() and ftello() return the current offset. Other-wise, -1 is returned and the global variable errno is set to indicate the error.

ISSUES

These functions depend on lseek(2). Any restrictions provided in the lseek(2) de-scription apply to these functions as well.

ERRORS

[EBADF] The stream specified is not a seekable stream.

[EINVAL] The whence argument to fseek() was not SEEK SET, SEEK END, orSEEK CUR.

The function fgetpos(), fseek(), fseeko(), fsetpos(), ftell() and ftello() may alsofail and set errno for any of the errors specified for the routines flush(3), fstat(2),lseek(2), and malloc(3).

Systems/C C Library 611

Page 630: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

SEE ALSO

lseek(2)

STANDARDS

The fgetpos(), fsetpos(), fseek(), ftell(), and rewind() functions conform toISO 9899: 1990 (“ISO C90”).

The fseeko() and ftello() functions conform to Version 2 of the Single UNIX Spec-ification (“SUSv2”).

612 Systems/C C Library

Page 631: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

FUNOPEN(3)

NAME

funopen, fropen, fwopen - open a stream

SYNOPSIS

#include <stdio.h>

FILE *funopen(const void *cookie,int (*readfn)(void *, char *, int),int (*writefn)(void *, const char *, int),fpos_t (*seekfn)(void *, fpos_t, int),int (*closefn)(void *))

FILE *fropen(void *cookie,int (*readfn)(void *, char *, int))

FILE *fwopen(void *cookie,int (*writefn)(void *, const char *, int))

DESCRIPTION

The funopen() function associates a stream with up to four “I/O functions”. Eitherreadfn or writefn must be specified; the others can be given as an appropriately-typedNULL pointer. These I/O functions will be used to read, write, seek and close thenew stream.

In general, omitting a function means that any attempt to perform the associatedoperation on the resulting stream will fail. If the close function is omitted, closingthe stream will flush any buffered output and then succeed.

The calling conventions of readfn, writefn, seekfn and closefn must match those,respectively, of read(2), write(2), seek(2), and close(2) with the single exceptionthat they are passed the cookie argument specified to funopen() in place of thetraditional file descriptor argument.

Read and write I/O functions are allowed to change the underlying buffer on fullybuffered or line buffered streams by calling setvbuf(3). They are also not requiredto completely fill or empty the buffer. They are not, however, allowed to changestreams from unbuffered to buffered or to change the state of the line buffering flag.

Systems/C C Library 613

Page 632: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

They must also be prepared o have read or write calls occur on buffers other thanthe one most recently specified.

All user I/O functions can report an error by returning -1. Additionally, all of thefunctions should set the external variable errno appropriately if an error occurs.

An error on closefn() does not keep the stream open.

As a convenience, the include file <stdio.h> defines the macros frozen() andfwopen() as calls to funopen() with only a read or write function specified.

RETURN VALUES

Upon successful completion, funopen() returns a FILE pointer. Otherwise, NULLis returned and the global variable errno is set to indicate the error.

ERRORS

[EINVAL] The funopen() function was called without either a read or writefunction. The funopen() function may also fail and set errno forany of the errors specified for the routine malloc(3).

SEE ALSO

fcntl(2), open(2), fclose(3), fopen(3), fseek(3), setbuf(3)

614 Systems/C C Library

Page 633: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

FWIDE(3)

NAME

fwide - get/set orientation of a stream

SYNOPSIS

#include <stdio.h>#include <wchar.h>

intfwide(FILE *stream, int mode)

DESCRIPTION

The fwide() function determines the orientation of the stream pointed at by stream.

If the orientation of stream has already been determined, fwide() leaves it un-changed. Otherwise, fwide() sets the orientation of stream according to mode.

If mode is less than zero, stream is set to byte-oriented. If it is greater than zero,stream is set to wide-oriented. Otherwise, mode is zero, and stream is unchanged.

RETURN VALUES

The fwide() function returns a value according to orientation after the call offwide(); a value less than zero if byte-oriented, a value greater than zero if wide-oriented, and zero if the stream has no orientation.

SEE ALSO

ferror(3), fgetc(3), fgetwc(3), fopen(3), fputc(3), fputwc(3), freopen(3), stdio(3)

STANDARDS

The fwide() function conforms to ISO/IEC 9899:1999 (“ISO C99”).

Systems/C C Library 615

Page 634: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

GETC(3)

NAME

fgetc, getc, getchar, getw - get next character or word from input stream

SYNOPSIS

#include <stdio.h>

intfgetc(FILE *stream)

intgetc(FILE *stream)

intgetchar()

intgetw(FILE *stream)

DESCRIPTION

The fgetc() function obtains the next input character (if present) from the streampointed at by stream, or the next character pushed back on the stream via ungetc(3).

The getc() function acts essentially identically to fgetc(), but is a macro thatexpands in-line.

The getchar() function is equivalent to: getc with the argument stdin.

The getw() function obtains the next int (if present) from the stream pointed atby stream.

RETURN VALUES

If successful, these routines return the next requested object from the stream. If thestream is at end-of-file or a read error occurs, the routines return EOF. The routinesfeof(3) and ferror(3) must be used to distinguish between end-of-file and error. If anerror occurs, the global variable errno is set to indicate the error. The end-of-filecondition is remembered, even on a terminal, and all subsequent attempts to readwill return EOF until the condition is cleared with clearerr(3).

616 Systems/C C Library

Page 635: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

SEE ALSO

ferror(3), fopen(3), fread(3), putc(3), ungetc(3)

STANDARDS

The fgetc(), getc() and getchar() functions conform to ISO/IEC 9899:1990 (“ISOC90”).

ISSUES

Since EOF is a valid integer value, feof(3) and ferror(3) must be used to check forfailure after calling getw(). The size and byte order of an int varies from onemachine to another, and getw() is not recommended for portable applications.

Systems/C C Library 617

Page 636: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

GETWC(3)

NAME

fgetwc, getwc, getwchar - get next wide character from input stream

SYNOPSIS

#include <stdio.h>#include <wchar.h>

wint_tfgetwc(FILE *stream)

wint_tgetwc(FILE *stream)

wint_tgetwchar()

DESCRIPTION

The fgetwc() function obtains the next input wide character (if present) from thestream pointed at by stream, or the next character pushed back on the stream viaungetwc(3).

The getwc() function acts essentially identically to fgetwc().

The getwchar() function is equivalent to getwc() with the argument stdin.

RETURN VALUES

If successful, these routines return the next wide character from the stream. If thestream is at end-of-file or a read error occurs, the routines return WEOF. The routinesfeof(3) and ferror(3) must be used to distinguish between end-of-file and error. If anerror occurs, the global variable errno is set to indicate the error. The end-of-filecondition is remembered, even on a terminal, and all subsequent attempts to readwill return WEOF until the condition is cleared with clearerr(3).

SEE ALSO

ferror(3), fopen(3), fread(3), getc(3), putwc(3), stdio(3), ungetwc(3)

618 Systems/C C Library

Page 637: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

STANDARDS

The fgetwc(), getwc() and getwchar() functions conform to ISO/IEC 9899:1999(“ISO C99”).

Systems/C C Library 619

Page 638: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

MKTEMP(3)

NAME

mktemp - make temporary file name (unique)

SYNOPSIS

#include <unistd.h>

char *mktemp(char *template);

intmkstemp(char *template);

intmkstemps(char *template, int suffixlen);

char *mkdtemp(char *template);

DESCRIPTION

The mktemp() function takes the given file name template and overwrites a por-tion of it to create a file name. This file name is guaranteed not to exist at the timeof function invocation and is suitable for use by the application. The template maybe any //HFS:-style file name with some number of ‘Xs’ appended to it, for exam-ple /tmp/temp.XXXXXX. The trailing ‘Xs’ are replaced with a unique alphanumericcombination. The number of unique file names mktemp() can return dependson the number of ‘Xs’ provided; six ‘Xs’ will result in mktemp() selecting one of56800235584 (62 ** 6) possible temporary file names.

The mkstemp() function makes the same replacement to the template and createsthe template file, mode 0600, returning a file descriptor opened for reading andwriting. This avoids the race between testing for a file’s existence and opening itfor use.

The mkstemps() function acts the same as mkstemp(), except it permitsa suffix to exist in the template. The template should be of the form/tmp/tmpXXXXXXsuffix. mkstemps() is told the length of the suffix string.

The mkdtemp() function makes the same replacement to the template as in mk-temp(3) and creates the template directory, mode 0700.

620 Systems/C C Library

Page 639: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

RETURN VALUES

The mktemp() and mkdtemp() functions return a pointer to the template onsuccess and NULL on failure. The mkstemp() and mkstemps() functions return-1 if no suitable file could be created. If either call fails an error code is placed inthe global variable errno.

ERRORS

The mkstemp(), mkstemps() and mkdtemp() functions may set errno to oneof the following values:

[ENOTDIR] The pathname portion of the template is not an existing directory.

The mkstemp(), mkstemps() and mkdtemp() functions may also set errno toany value specified by the stat(2) function.

The mkstemp() and mkstemps() functions may also set errno to any value spec-ified by the open(2) function.

The mkdtemp() function may also set errno to any value specified by the mkdir(2)function.

NOTES

The mktemp(), mkstemp(), mkstemps() and mkdtemp() functions only re-turn //HFS:-style names, and thus require OpenEdition services.

A common problem that results in abnormal termination is that the program-mer passes in a read-only string to mktemp(), mkstemp(), mkstemps() ormkdtemp(). This is common with programs that were developed before ISO/IEC9899:1990 (“ISO C90”) compilers were common. For example, calling mkstemp()with an argument of "/tmp/tempfile.XXXXXX" may result in abnormal terminationdue to mkstemp() attempting to modify the string constant that was given.

ISSUES

This family of functions produces filenames which can be guessed, though the riskis minimized when large numbers of ‘Xs’ are used to increase the number of possibletemporary filenames. This makes the race in mktemp(), between testing for afile’s existence (in the mktemp() function call) and opening it for use (later inthe user application) particularly dangerous from a security perspective. Whenever

Systems/C C Library 621

Page 640: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

it is possible, mkstemp() should be used instead, since it does not have the racecondition. If mkstemp() cannot be used, the filename created by mktemp()should be created using the O EXCL flag to open(2) and the return status of the callshould be tested for failure. This will ensure that the program does not continueblindly in the event that an attacker has already created the file with the intentionof manipulating or reading its contents.

SEE ALSO

chmod(2), getpid(2), mkdir(2), open(2), stat(2)

622 Systems/C C Library

Page 641: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

PRINTF(3)

NAME

printf, fprintf, sprintf, snprintf, asprintf, vprintf, vfprintf, vsprintf, vsnprintf,vasprintf - formatted output conversion

SYNOPSIS

#include <stdio.h>

intprintf(const char *format, ...)

intfprintf(FILE *stream, const char *format, ...)

intsprintf(char *str, const char *format, ...)

intsnprintf(char *str, size_t size, const char *format,...)

intasprintf(char **ret, const char *format, ...)

#include <stdarg.h>

intvprintf(const char *format, va_list ap)

intvfprintf(FILE *stream, const char *format, va_list ap)

intvsprintf(char *str, char *format, va_list ap)

intvsnprintf(char *str, size_t size, const char *format,va_list ap)

intvasprintf(char **ret, const char *format, va_list ap)

Systems/C C Library 623

Page 642: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

DESCRIPTION

The printf() family of functions produces output according to a format as describedbelow. The printf() and vprintf() functions write output to stdout, the standardoutput stream; fprintf() and vfprintf() write output to the given output stream;sprintf(), snprintf(), vsprintf(), and vsnprintf() write to the character stringstr; and asprintf() and vasprintf() dynamically allocate a new string with mal-loc(3) / realloc(3).

These functions write the output under the control of a format string that specifieshow subsequent arguments (or arguments accessed via the variable-length argumentfacilities of stdarg(3)) are converted for output.

These functions return the number of characters printed (not including the trailing’\0’ used to end output to strings).

asprintf() and vasprintf() return a pointer to a buffer sufficiently large to hold thestring in the ret argument; This pointer should be passed to free(3) to release theallocated storage when it is no longer needed. If sufficient space cannot be allocated,asprintf() and vasprintf() will return -1 and set ret to be a NULL pointer.

snprintf() and vsnprintf() will write at most size-1 of the characters printed intothe output string (the size’th character then gets the terminating ’\0’); if the returnvalue is greater than or equal to the size argument, the string was too short andsome of the printed characters were discarded.

The sprintf() and vsprintf() functions effectively assume an infinite size.

The format string is composed of zero or more directives: ordinary characters (not%), which are copied unchanged to the output stream and conversion specifications,each of which results in fetching zero or more subsequent arguments. Each conver-sion specification is introduced by the character %. The arguments must correspondproperly (after type promotion) with the conversion specifier. After the %, the fol-lowing appear in sequence:

• Zero or more of the following flags:

– A # character specifying that the value should be converted to an “alter-nate form.” For c, d, i, n, p, s, and u, conversions, this option has noeffect. For o conversions, the precision of the number is increased to forcethe first character of the output string to a zero (except if a zero valueis printed with an explicit precision of zero). For x and X conversions, anon-zero result has the string ’0x’ (or ’0X’ for X conversions) pretendedto it. For e, E, f, g, and G, conversions, the result will always containa decimal point, even if no digits follow it (normally, a decimal pointappears in the results of those conversions only if a digit follows). For gand G conversions, trailing zeros are not removed from the result as theywould otherwise be.

624 Systems/C C Library

Page 643: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

– A zero ‘0’ character specifying zero padding. For all conversions except n,the converted value is padded on the left with zeros rather than blanks.If a precision is given with a numeric conversion (d, i, o, u, i, x, and X),the ‘0’ flag is ignored.

– A negative field width flag ‘-’ indicates the converted value is to be leftadjusted on the field boundary. Except for n conversions, the convertedvalue is padded on the right with blanks, rather than on the left withblanks or zeros. A ‘-’ overrides a ‘0’ if both are given.

– A space, specifying that a blank should be left before a positive numberproduced by a signed conversion (d, e, E, f, g, G, or i).

– A ‘+’ character specifying that a sign always be placed before a numberproduced by a signed conversion. A ‘+’ overrides a space if both are used.

• An optional decimal digit string specifying a minimum field width. If theconverted value has fewer characters than the field width, it will be paddedwith spaces on the left (or right, if the left-adjustment flag has been given) tofill out the field width.

• An optional precision, in the form of a period ‘.’ followed by an optional digitstring. If the digit string is omitted, the precision is taken as zero. This givesthe minimum number of digits to appear for d, i, o, u, x, and X conversions, thenumber of digits to appear after the decimal-point for e, E, and f conversions,the maximum number of significant digits for g and G conversions, or themaximum number of characters to be printed from a string for s conversions.

• The optional character h, specifying that a following d, i, o, u, x, or X conver-sion corresponds to a short int or unsigned short int argument, or thata following n conversion corresponds to a pointer to a short int argument.

• The optional character l (ell) specifying that a following d, i, o, u, x, or Xconversion applies to a pointer to a long int or unsigned long int argu-ment, or that a following n conversion corresponds to a pointer to a long intargument.

• The optional characters ll (ell ell), specifying that a following d, i, o, u, x, orX conversion corresponds to a long long or unsigned long long argument,or that a following n conversion corresponds to a pointer to a long longargument. The deprecated character q specifies the same behavior. Programsshould use ll instead.

• The character L specifying that a following e, E, f, g, or G conversion corre-sponds to a long double argument.

• A character that specifies the type of conversion to be applied.

A field width or precision, or both, may be indicated by an asterisk ‘*’ instead of adigit string. In this case, an int argument supplies the field width or precision. Anegative field width is treated as a left adjustment flag followed by a positive fieldwidth; a negative precision is treated as though it were missing.

Systems/C C Library 625

Page 644: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

The conversion specifiers and their meanings are:

diouxX The int (or appropriate variant) argument is converted to signed dec-imal (d and i), unsigned octal (o), unsigned decimal (u), or unsignedhexadecimal (x and X) notation. The letters abcdef are used for x con-versions; the letters ABCDEF are used for X conversions. The precision,if any, gives the minimum number of digits that must appear; if theconverted value requires fewer digits, it is padded on the left with zeros.

eE The double argument is rounded and converted in the style [-]d.ddde+-dd where there is one digit before the decimal-point character and thenumber of digits after it is equal to the precision; if the precision is miss-ing, it is taken as 6; if the precision is zero, no decimal-point characterappears. An E conversion uses the letter E (rather than e) to introducethe exponent. The exponent always contains at least two digits; if thevalue is zero, the exponent is 00.

fF The double argument is rounded and converted to decimal notationin the style [-]ddd.ddd, where the number of digits after the decimal-point character is equal to the precision specification. If the precision ismissing, it is taken as 6; if the precision is explicitly zero, no decimal-point character appears. If a decimal point appears, at least one digitappears before it.

gG The double argument is converted in style f or e (or E for G conversions).The precision specifies the number of significant digits. If the precisionis missing, 6 digits are given; if the precision is zero, it is treated as1. Style e is used if the exponent from its conversion is less than -4 orgreater than or equal to the precision. Trailing zeros are removed fromthe fractional part of the result; a decimal point appears only if it isfollowed by at least one digit.

aA The double argument is printed in style [-]h.hhhp+-d, where there is onehexadecimal digit before the hexadecimal point and the number after isequal to the precision specification for the argument; when the precisionis missing, enough digits are produced to convey the argument’s exactdouble-precision floating-point representation.

D The Decimal argument is printed. After the conversion specifier, anargument of (size,prec) must appear specifying the size and precision.

c The int argument is converted to an unsigned char, and the resultingcharacter is written.

s The char * argument is expected to be a pointer to an array of char-acter type (pointer to a string). Characters from the array are writtenup to (but not including) a terminating NUL character; if a precision isspecified, no more than the number specified are written. If a precision

626 Systems/C C Library

Page 645: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

is given, no null character need be present. If the precision is not spec-ified or is greater than the size of the array, the array must contain aterminating NUL character.

p The void * pointer argument is printed in hexadecimal (as if by ‘%#x’or ‘%#lx’).

n The number of characters written so far is stored into the integer in-dicated by the int * (or variant) pointer argument. No argument isconverted.

% A ‘%’ is written. No argument is converted. The complete conversionspecification is ‘%%’.

In no case does a non-existent or small field width cause truncation of a field. If theresult of a conversion is wider than the field width, the field is expanded to containthe conversion result.

EXAMPLES

To print a date and time in the form ‘Sunday, July 3, 10:02’, where weekday andmonth are pointers to strings:

#include <stdio.h>fprintf(stdout, "%s, %s %d, %.2d:%.2d\n",

weekday, month, day, hour, min);

To print PI to five decimal places:

#include <math.h>#include <stdio.h>fprintf(stdout, "pi = %.5f\n", 4 * atan(1.0));

To allocate a 128 byte string and print into it:

#include <stdio.h>#include <stdlib.h>#include <stdarg.h>char *newfmt(const char *fmt, ...){

char *p;va_list ap;if ((p = malloc(128)) == NULL)

Systems/C C Library 627

Page 646: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

return (NULL);va_start(ap, fmt);(void) vsnprintf(p, 128, fmt, ap);va_end(ap);return (p);

}

SEE ALSO

scanf(3)

STANDARDS

The fprintf(), printf(), sprintf(), vprintf(), vfprintf(), and vsprintf() func-tions conform to ISO/IEC 9899:1990 (“ISO C90”).

ISSUES

The effect of padding the %p format with zeros (either by the ‘0’ flag or by spec-ifying a precision), and the benign effect (i.e., none) of the ‘#’ flag on %n and %pconversions, as well as other nonsensical combinations such as %Ld, are not standardsuch combinations should be avoided.

Because sprintf() and vsprintf() assume an infinitely long string, callers must becareful not to overflow the actual space; this is often hard to assure. For safety, pro-grammers should use the snprintf() interface instead. Unfortunately, this interfaceis not portable.

628 Systems/C C Library

Page 647: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

PUTC(3)

NAME

fputc, putc, putchar, putw - output a character or word to a stream

SYNOPSIS

#include <stdio.h>

intfputc(int c, FILE *stream)

intputc(int c, FILE *stream)

intputchar(int c)

intputw(int w, FILE *stream)

DESCRIPTION

The fputc() function writes the character c (converted to an unsigned char) tothe output stream pointed to by stream.

putc() acts essentially identically to fputc(), but is a macro that expands in-line.It may evaluate stream more than once, so arguments given to putc() should notbe expressions with potential side effects.

putchar() is identical to putc() with an output stream of stdout.

The putw() function writes the specified int to the named output stream.

RETURN VALUES

The functions, fputc(), putc() and putchar() return the character written. If anerror occurs, the value EOF is returned. The putw() function returns 0 on success;EOF is returned if a write error occurs, or if an attempt is made to write a read-onlystream.

Systems/C C Library 629

Page 648: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

SEE ALSO

ferror(3), fopen(3), getc(3), stdio(3)

STANDARDS

The functions fputc(), putc(), and putchar(), conform to ISO/IEC 9899:1990(“ISO C”).

CAUTIONS

The size and byte order of an int varies from one machine to another, and putw()is not recommended for portable applications.

630 Systems/C C Library

Page 649: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

PUTWC(3)

NAME

fputwc, putwc, putwchar - output a wide character to a stream

SYNOPSIS

#include <stdio.h>#include <wchar.h>

wint_tfputwc(wchar_t wc, FILE *stream)

wint_tputwc(wchar_t wc, FILE *stream)

wint_tputwchar(wchar_t wc)

DESCRIPTION

The fputwc() function writes the wide character wc to the output stream pointedto by stream.

The putwc() function acts essentially identically to fputwc().

The putwchar() function is identical to putwc() with an output stream of stdout.

RETURN VALUES

The fputwc(), putwc(), and putwchar() functions return the wide character writ-ten. If an error occurs, the value WEOF is returned.

SEE ALSO

ferror(3), fopen(3), getwc(3), putc(3), stdio(3)

STANDARDS

The fputwc(), putwc(), and putwchar() functions conform to ISO/IEC 9899:1999(“ISO C99”).

Systems/C C Library 631

Page 650: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

REMOVE(3)

NAME

remove - remove file system entry

SYNOPSIS

#include <stdio.h>

intremove(const char *path)

DESCRIPTION

The remove() function is an alias for the unlink(2) system call. It deletes the filereferenced by path.

RETURN VALUES

Upon successful completion, remove() returns 0. Otherwise, -1 is returned and theglobal variable errno is set to indicate the error.

ERRORS

The remove() function may fail and set errno for any of the errors specified forthe routine unlink(2).

SEE ALSO

unlink(2)

STANDARDS

The remove() function conforms to ISO/IEC 9899:1990 (“ISO C90”).

632 Systems/C C Library

Page 651: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

SCANF(3)

NAME

scanf, fscanf, sscanf, vscanf, vsscanf, vfscanf - input format conversion

SYNOPSIS

#include <stdio.h>

intscanf(const char *format, ...)

intfscanf(FILE *stream, const char *format, ...)

intsscanf(const char *str, const char *format, ...)

#include <stdarg.h>

intvscanf(const char *format, va_list ap)

intvsscanf(const char *str, const char *format,va_list ap)

intvfscanf(FILE *stream, const char *format, va_list ap)

DESCRIPTION

The scanf() family of functions scans input according to a format as describedbelow. This format may contain conversion specifiers the results from such conver-sions, if any, are stored through the pointer arguments. The scanf() function readsinput from the standard input stream stdin, fscanf() reads input from the streampointer stream, and sscanf() reads its input from the character string pointed toby str. The vfscanf() function is analogous to vfprintf(3) and reads input fromthe stream pointer stream using a variable argument list of pointers (see stdarg(3)).The vscanf() function scans a variable argument list from the standard input andthe vsscanf() function scans it from a string; these are analogous to the vprintf()and vsprintf() functions respectively. Each successive pointer argument must cor-respond properly with each successive conversion specifier (but see ‘suppression’

Systems/C C Library 633

Page 652: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

below). All conversions are introduced by the % (percent sign) character. The for-mat string may also contain other characters. White space (such as blanks, tabs,or newlines) in the format string match any amount of white space, including none,in the input. Everything else matches only itself. Scanning stops when an inputcharacter does not match such a format character. Scanning also stops when aninput conversion cannot be made (see below).

CONVERSIONS

Following the % character introducing a conversion there may be a number of flagcharacters, as follows:

* Suppresses assignment. The conversion that follows occurs as usual, butno pointer is used; the result of the conversion is simply discarded.

hh Indicates that the conversion will be one of dioux or n and the next pointeris a pointer to a char (rather than int).

h Indicates that the conversion will be one of dioux or n and the next pointeris a pointer to a short int (rather than int).

l Indicates either that the conversion will be one of dioux or n and the nextpointer is a pointer to a long int (rather than int), or that the conversionwill be one of efg and the next pointer is a pointer to double (rather thanfloat).

ll Indicates that the conversion will be one of dioux or n and the next pointeris a pointer to a long long int (rather than int).

L Indicates that the conversion will be efg and the next pointer is a pointerto long double. (This type is not implemented; the L flag is currentlyignored.)

j Indicates that the conversion will be one of dioux or n and the next pointeris a pointer to a intmax t (rather than int).

t Indicates that the conversion will be one of dioux or n and the next pointeris a pointer to a ptrdiff t (rather than int).

z Indicates that the conversion will be one of dioux or n and the next pointeris a pointer to a size t (rather than int).

q Indicates that the conversion will be one of dioux or n and the next pointeris a pointer to a long long int (rather than int). This use is deprecated,and will be removed in a future release. The standard defines ll for thispurpose.

634 Systems/C C Library

Page 653: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

In addition to these flags, there may be an optional maximum field width, expressedas a decimal integer, between the % and the conversion. If no width is given, adefault of “infinity” is used (with one exception, below); otherwise at most thismany characters are scanned in processing the conversion. Before conversion begins,most conversions skip white space; this white space is not counted against the fieldwidth.

The following conversions are available:

% Matches a literal ‘%’. That is, ‘%%’ in the format string matches a singleinput ‘%’ character. No conversion is done, and assignment does not occur.

d Matches an optionally signed decimal integer; the next pointer must be apointer to int.

i Matches an optionally signed integer; the next pointer must be a pointerto int. The integer is read in base 16 if it begins with ‘0x’ or ‘0X’, inbase 8 if it begins with ‘0’, and in base 10 otherwise. Only characters thatcorrespond to the base are used.

o Matches an octal integer; the next pointer must be a pointer to unsignedint.

u Matches an optionally signed decimal integer; the next pointer must be apointer to unsigned int.

x Matches an optionally signed hexadecimal integer; the next pointer mustbe a pointer to unsigned int.

e, E, f, F, g, G Matches a floating-point number in the style of strtod(3). Thenext pointer must be a pointer to float (unless l or L is specified.)

s Matches a sequence of non-white-space characters; the next pointer mustbe a pointer to char, and the array must be large enough to accept all thesequence and the terminating NUL character. The input string stops atwhite space or at the maximum field width, whichever occurs first.

c Matches a sequence of width count characters (default 1); the next pointermust be a pointer to char, and there must be enough room for all thecharacters (no terminating NUL is added). The usual skip of leading whitespace is suppressed. To skip white space first, use an explicit space in theformat.

[ Matches a non-empty sequence of characters from the specified set of ac-cepted characters; the next pointer must be a pointer to char, and theremust be enough room for all the characters in the string, plus a terminat-ing NUL character. The usual skip of leading white space is suppressed.The string is to be made up of characters in (or not in) a particular set;the set is defined by the characters between the open bracket [ characterand a close bracket ] character. The set excludes those characters if the

Systems/C C Library 635

Page 654: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

first character after the open bracket is a circumflex ˆ. To include a closebracket in the set, make it the first character after the open bracket orthe circumflex; any other position will end the set. The hyphen character- is also special; when placed between two other characters, it adds allintervening characters to the set. To include a hyphen, make it the lastcharacter before the final close bracket. For instance, ‘[^]0-9-]’ meansthe set ‘everything except close bracket, zero through nine, and hyphen’.The string ends with the appearance of a character not in the (or, with acircumflex, in) set or when the field width runs out.

p Matches a pointer value (as printed by ‘%p’ in printf(3)); the next pointermust be a pointer to void.

n Nothing is expected; instead, the number of characters consumed thus farfrom the input is stored through the next pointer, which must be a pointerto int. This is not a conversion, although it can be suppressed with the *flag.

For backwards compatibility, a “conversion” of ‘%\0’ causes an immediate return ofEOF.

RETURN VALUES

These functions return the number of input items assigned, which can be fewer thanprovided for, or even zero, in the event of a matching failure. Zero indicates that,while there was input available, no conversions were assigned; typically this is dueto an invalid input character, such as an alphabetic character for a ‘%d’ conversion.The value EOF is returned if an input failure occurs before any conversion such asan end-of-file occurs. If an error or end-of-file occurs after conversion has begun,the number of conversions which were successfully completed is returned.

SEE ALSO

getc(3), printf(3), strtod(3), strtol(3), strtoul(3)

STANDARDS

The functions fscanf(), scanf(), and sscanf() conform to ISO/IEC 9899:1990(“ISO C”).

ISSUES

Numerical strings are truncated to 512 characters; for example, %f and %d are im-plicitly %512f and %512d.

636 Systems/C C Library

Page 655: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

SETBUF(3)

NAME

setbuf, setbuffer, setlinebuf, setvbuf - stream buffering operations

SYNOPSIS

#include <stdio.h>

voidsetbuf(FILE *stream, char *buf)

voidsetbuffer(FILE *stream, char *buf, size_t size)

intsetlinebuf(FILE *stream)

intsetvbuf(FILE *stream, char *buf, int mode, size_t size)

DESCRIPTION

The three types of buffering available are unbuffered, block buffered, and linebuffered. When an output stream is unbuffered, information appears on the desti-nation file or terminal as soon as written. When it is block buffered many charactersare saved up and written as a block. When it is line buffered characters are savedup until a newline is output or input is read from any stream attached to a terminaldevice (typically stdin). The function fflush(3) may be used to force the block outearly. (See fclose(3).)

Normally all files are block buffered. When the first I/O operation occurs on a file,malloc(3) is called, and an optimally-sized buffer is obtained. If a stream refers toa terminal (as stdout normally does) it is line buffered. The standard error streamstderr is always unbuffered.

The setvbuf() function may be used to alter the buffering behavior of a stream.The mode parameter must be one of the following three macros:

IONBF unbuffered

IOLBF line buffered

IOFBF fully buffered

Systems/C C Library 637

Page 656: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

The size parameter may be given as zero to obtain deferred optimal-size bufferallocation as usual. If it is not zero, then except for unbuffered files, the buf argumentshould point to a buffer at least size bytes long; this buffer will be used instead ofthe current buffer. If the size argument is not zero but buf is NULL, a buffer of thegiven size will be allocated immediately, and released on close. This is an extensionto ANSI C; portable code should use a size of 0 with any NULL buffer.

The setvbuf() function may be used at any time, but may have peculiar side effects(such as discarding input or flushing output) if the stream is “active.” Portableapplications should call it only once on any given stream, and before any I/O isperformed.

The other three calls are, in effect, simply aliases for calls to setvbuf(). Except forthe lack of a return value, the setbuf() function is exactly equivalent to the call

setvbuf(stream, buf,buf ? _IOFBF : _IONBF, BUFSIZ);

The setbuffer() function is the same, except that the size of the buffer is up tothe caller, rather than being determined by the default BUFSIZ. The setlinebuf()function is exactly equivalent to the call:

setvbuf(stream, (char *)NULL, _IOLBF, 0);

RETURN VALUES

The setvbuf() function returns 0 on success, or EOF if the request cannot be honored(note that the stream is still functional in this case).

The setlinebuf() function returns what the equivalent setvbuf() would have re-turned.

SEE ALSO

fclose(3), fopen(3), fread(3), malloc(3), printf(3), puts(3)

STANDARDS

The setbuf() and setvbuf() functions conform to ISO/IEC 9899:1990 (“ISO C90”).

638 Systems/C C Library

Page 657: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

TMPFILE(3)

NAME

tempnam, tmpfile, tmpnam – //HFS:-style temporary file routines

SYNOPSIS

#include <stdio.h>

FILE *tmpfile(void);

char *tmpnam(char *str);

char *tempnam(const char *tmpdir, const char *prefix);

DESCRIPTION

The tmpfile() function returns a pointer to a stream associated with a file descriptorreturned by the routine mkstemp(3). The created file is unlinked before tmpfile()returns, causing the file to be automatically deleted when the last reference to itis closed. The file is opened with the access value ‘w+’. The file is created inthe directory determined by the environment variable TMPDIR if set. The defaultlocation if TMPDIR is not set is /tmp.

The tmpnam() function returns a pointer to a file name, in the P tmpdir directory,which did not reference an existing file at some indeterminate point in the past.P tmpdir is defined in the include file <stdio.h>. If the argument str is non-NULL,the file name is copied to the buffer it references. Otherwise, the file name is copiedto a static buffer. In either case, tmpnam() returns a pointer to the file name.

The buffer referenced by str is expected to be at least L tmpnam bytes in length.L tmpnam is defined in the include file <stdio.h>.

The tempnam() function is similar to tmpnam(), but provides the ability tospecify the directory which will contain the temporary file and the file name prefix.

The environment variable TMPDIR (if set), the argument tmpdir (if non-NULL), thedirectory P tmpdir and the directory /tmp are tried, in the listed order, as directoriesin which to store the temporary file.

The argument prefix, if non-NULL, is used to specify a file name prefix, which willbe the first part of the created file name. tempnam() allocates memory in which

Systems/C C Library 639

Page 658: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

to store the file name; the returned pointer may be used as a subsequent argumentto free(3).

RETURN VALUES

The tmpfile() function returns a pointer to an open file system on success, and aNULL pointer on error.

The tmpnam() and tempfile() functions return a pointer to a file name on success,and a NULL pointer on error.

ERRORS

The tmpfile() function may fail and set the global variable errno for any of theerrors specified for the library functions fdopen(3) or mkstemp(3).

The tmpnam() function may fail and set errno for any of the errors specified forthe library function mktemp(3).

The tempnam() function may fail and set errno for any of the errors specified forthe library functions malloc(3) or mktemp(3).

SEE ALSO

mkstemp(3), mktemp(3)

STANDARDS

ISSUES

These interfaces are provided for System V and ANSI compatibility only. Theyonly produce //HFS:-style file names, and thus require OpenEdition services. Themkstemp(3) interface is strongly preferred.

There are four important problems with these interfaces (as well as with the historicmktemp(3) interface). First, there is an obvious race between file name selectionand file creation and deletion. Second, most historic implementations provide onlya limited number of possible temporary file names (usually 26) before file names willstart being recycled. Third, the System V implementations of these functions (and ofmktemp(3)) uses the access(2) function to determine whether or not the temporaryfile may be created. This has obvious ramifications for setuid or setgid programs,complicating the portable use of these interfaces in such programs. Finally, there isno specification of the permissions with which the temporary files are created.

640 Systems/C C Library

Page 659: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

This implementation does not have these flaws, but portable software cannot dependon that. In particular, the tmpfile() interface should not be used in softwareexpected to be used on other systems if there is any possibility that the user doesnot wish the temporary file to be publicly readable and writable.

Systems/C C Library 641

Page 660: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

UNGETC(3)

NAME

ungetc - un-get character from input stream

SYNOPSIS

#include <stdio.h>

intungetc(int c, FILE *stream)

DESCRIPTION

The ungetc() function pushes the character c (converted to an unsigned char)back onto the input stream pointed to by stream. The pushed-backed characterswill be returned by subsequent reads on the stream (in reverse order). A successfulintervening call, using the same stream, to one of the file positioning functions(fseek(3), fsetpos(3), or rewind(3)) will discard the pushed back characters.

One character of push-back is guaranteed, but as long as there is sufficient memory,an effectively infinite amount of pushback is allowed.

If a character is successfully pushed-back, the end-of-file indicator for the stream iscleared.

RETURN VALUES

The ungetc() function returns the character pushed-back after the conversion, orEOF if the operation fails. If the value of the argument c character equals EOF, theoperation will fail and the stream will remain unchanged.

SEE ALSO

fseek(3), getc(3), setvbuf(3)

STANDARDS

The ungetc() function conforms to ISO/IEC 9899:1990 (“ISO C90”).

642 Systems/C C Library

Page 661: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

UNGETWC(3)

NAME

ungetwc - un-get wide character from input stream

SYNOPSIS

#include <stdio.h>#include <wchar.h>

wint_tungetwc(wint_t wc, FILE *stream)

DESCRIPTION

The ungetwc() function pushes the wide character wc (converted to an wchar t)back onto the input stream pointed to by stream. The pushed-backed wide char-acters will be returned by subsequent reads on the stream (in reverse order). Asuccessful intervening call, using the same stream, to one of the file positioningfunctions fseek(3), fsetpos(3), or rewind(3) will discard the pushed back wide char-acters.

One wide character of push-back is guaranteed, but as long as there is sufficientmemory, an effectively infinite amount of pushback is allowed.

If a character is successfully pushed-back, the end-of-file indicator for the stream iscleared.

RETURN VALUES

The ungetwc() function returns the wide character pushed-back after the conver-sion, or WEOF if the operation fails. If the value of the argument wc character equalsWEOF, the operation will fail and the stream will remain unchanged.

SEE ALSO

fseek(3), getwc(3)

STANDARDS

The ungetwc() function conforms to ISO/IEC 9899:1999 (“ISO C99”).

Systems/C C Library 643

Page 662: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

WPRINTF(3)

NAME

wprintf, fwprintf, swprintf, vwprintf, vfwprintf, vswprintf - formatted wide characteroutput conversion

SYNOPSIS

#include <stdio.h>#include <wchar.h>

intfwprintf(FILE * restrict stream, const wchar_t * restrict format, ...)

intswprintf(wchar_t * restrict ws, size_t n,

const wchar_t * restrict format, ...)

intwprintf(const wchar_t * restrict format, ...)

#include <stdarg.h>

intvfwprintf(FILE * restrict stream,

const wchar_t * restrict, va_list ap)

intvswprintf(wchar_t * restrict ws, size_t n,

const wchar_t *restrict format, va_list ap)

intvwprintf(const wchar_t * restrict format, va_list ap)

DESCRIPTION

The wprintf() family of functions produces output according to a format as de-scribed below. The wprintf() and vwprintf() functions write output to stdout,the standard output stream; fwprintf() and vfwprintf() write output to the givenoutput stream; swprintf() and vswprintf() write to the wide character string ws.

These functions write the output under the control of a format string that specifieshow subsequent arguments (or arguments accessed via the variable-length argumentfacilities of stdarg(3)) are converted for output.

644 Systems/C C Library

Page 663: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

These functions return the number of characters printed (not including the trailing’\0’ used to end output to strings).

The swprintf() and vswprintf() functions will fail if n or more wide characterswere requested to be written,

The format string is composed of zero or more directives: ordinary characters (not%), which are copied unchanged to the output stream; and conversion specifica-tions, each of which results in fetching zero or more subsequent arguments. Eachconversion specification is introduced by the % character. The arguments must cor-respond properly (after type promotion) with the conversion specifier. After the %,the following appear in sequence:

• An optional field, consisting of a decimal digit string followed by a $, speci-fying the next argument to access. If this field is not provided, the argumentfollowing the last argument accessed will be used. Arguments are numberedstarting at 1. If unaccessed arguments in the format string are interspersedwith ones that are accessed the results will be indeterminate.

• Zero or more of the following flags:

‘#’ The value should be converted to an “alternate form”. For c,d, i, n, p, s, and u conversions, this option has no effect. Foro conversions, the precision of the number is increased to forcethe first character of the output string to a zero (except if a zerovalue is printed with an explicit precision of zero). For x andX conversions, a non-zero result has the string ‘0x’ (or ‘0X’ forX conversions) prepended to it. For a, A, e, E, f, F, g, and Gconversions, the result will always contain a decimal point, evenif no digits follow it (normally, a decimal point appears in theresults of those conversions only if a digit follows). For g and Gconversions, trailing zeros are not removed from the result as theywould otherwise be.

‘0’ (zero) Zero padding. For all conversions except n, the converted value ispadded on the left with zeros rather than blanks. If a precision isgiven with a numeric conversion (d, i, o, u, i, x, and X), the 0 flagis ignored.

‘-’ A negative field width flag; the converted value is to be left adjustedon the field boundary. Except for n conversions, the convertedvalue is padded on the right with blanks, rather than on the leftwith blanks or zeros. A - overrides a 0 if both are given.

‘ ’ (space) A blank should be left before a positive number produced by asigned conversion (a, A, d, e, E, f, F, g, G, or i).

‘+’ A sign must always be placed before a number produced by a signedconversion. A + overrides a space if both are used.

Systems/C C Library 645

Page 664: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

‘’’ Decimal conversions (d, u, or i) or the integral portion of a float-ing point conversion (f or F) should be grouped and separated bythousands using the non-monetary separator returned by locale-conv(3).

• An optional decimal digit string specifying a minimum field width. If theconverted value has fewer characters than the field width, it will be paddedwith spaces on the left (or right, if the left-adjustment flag has been given) tofill out the field width.

• An optional precision, in the form of a period . followed by an optionaldigit string. If the digit string is omitted, the precision is taken as zero.This gives the minimum number of digits to appear for d, i, o, u, x, and Xconversions, the number of digits to appear after the decimal-point for a, A, e,E, f, and F conversions, the maximum number of significant digits for g and Gconversions, or the maximum number of characters to be printed from a stringfor s conversions.

• An optional length modifier, that specifies the size of the argument. Thefollowing length modifiers are valid for the d, i, n, o, u, x, or X conversion:

Modifier d, i o, u, x, X nhh signed char unsigned char signed char *h short unsigned short short *l (ell) long unsigned long long *ll (ell ell) long long unsigned long long long long *j intmax t uintmax t intmax t *t ptrdiff t (see note) ptrdiff t *z (see note) size t (see note)q (deprecated) quad t u quad t quad t *

Note: the t modifier, when applied to a o, u, x, or X conversion, indicates thatthe argument is of an unsigned type equivalent in size to a ptrdiff t. Thez modifier, when applied to a d or i conversion, indicates that the argumentis of a signed type equivalent in size to a size t. Similarly, when applied toan n conversion, it indicates that the argument is a pointer to a signed typeequivalent in size to a size t.

The following length modifier is valid for the a, A, e, E, f, F, g, or G conversion:

Modifier a, A, e, E, f, F, g, GL long double

The following length modifier is valid for the c or s conversion:

Modifier c sl (ell) wint t wchar t *

• A character that specifies the type of conversion to be applied.

A field width or precision, or both, may be indicated by an asterisk ‘*’ or an asteriskfollowed by one or more decimal digits and a ‘$’ instead of a digit string. In thiscase, an int argument supplies the field width or precision. A negative field width

646 Systems/C C Library

Page 665: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

is treated as a left adjustment flag followed by a positive field width; a negativeprecision is treated as though it were missing. If a single format directive mixespositional (nn$) and non-positional arguments, the results are undefined.

The conversion specifiers and their meanings are:

diouxX The int (or appropriate variant) argument is converted to signed dec-imal (d and i), unsigned octal (o), unsigned decimal (u), or unsignedhexadecimal (x and X) notation. The letters abcdef are used for x con-versions; the letters ABCDEF are used for X conversions. The precision,if any, gives the minimum number of digits that must appear; if theconverted value requires fewer digits, it is padded on the left with zeros.

eE The double argument is rounded and converted in the style [-]d.ddde+-ddwhere there is one digit before the decimal-point character and the num-ber of digits after it is equal to the precision; if the precision is missing,it is taken as 6; if the precision is zero, no decimal-point character ap-pears. An E conversion uses the letter ‘E’ (rather than ‘e’) to introducethe exponent. The exponent always contains at least two digits; if thevalue is zero, the exponent is 00.

For a, A, e, E, f, F, g, and G conversions, positive and negative infinityare represented as inf and -inf respectively when using the lowercaseconversion character, and INF and -INF respectively when using theuppercase conversion character. Similarly, NaN is represented as nanwhen using the lowercase conversion, and NAN when using the uppercaseconversion.

fF The double argument is rounded and converted to decimal notationin the style [-]ddd.ddd where the number of digits after the decimal-point character is equal to the precision specification. If the precision ismissing, it is taken as 6; if the precision is explicitly zero, no decimal-point character appears. If a decimal point appears, at least one digitappears before it.

gG The double argument is converted in style f or e (or F or E for G con-versions). The precision specifies the number of significant digits. Ifthe precision is missing, 6 digits are given; if the precision is zero, itis treated as 1. Style e is used if the exponent from its conversion isless than -4 or greater than or equal to the precision. Trailing zeros areremoved from the fractional part of the result; a decimal point appearsonly if it is followed by at least one digit.

aA The double argument is converted to hexadecimal notation in the style[-]0xh.hhhp[+-]d where the number of digits after the hexadecimal-pointcharacter is equal to the precision specification. If the precision is miss-ing, it is taken as enough to exactly represent the floating-point number;if the precision is explicitly zero, no hexadecimal-point character ap-pears. This is an exact conversion of the mantissa+exponent internal

Systems/C C Library 647

Page 666: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

floating point representation; the [-]0xh.hhh portion represents exactlythe mantissa; only denormalized mantissas have a zero value to the leftof the hexadecimal point. The p is a literal character ‘p’; the exponent ispreceded by a positive or negative sign and is represented in decimal, us-ing only enough characters to represent the exponent. The A conversionuses the prefix “0X” (rather than “0x”), the letters “ABCDEF” (ratherthan “abcdef”) to represent the hex digits, and the letter ‘P’ (ratherthan ‘p’) to separate the mantissa and exponent.

D The Decimal argument is printed. After the conversion specifier, anargument of (size,prec) must appear specifying the size and precision.

C Treated as c with the l (ell) modifier.

c The int argument is converted to an unsigned char, then to a wchar tas if by btowc(3), and the resulting character is written.

If the l (ell) modifier is used, the wint t argument is converted to awchar t and written.

S Treated as s with the l (ell) modifier.

s The char * argument is expected to be a pointer to an array of charactertype (pointer to a string) containing a multibyte sequence. Charactersfrom the array are converted to wide characters and written up to (butnot including) a terminating NUL character; if a precision is specified,no more than the number specified are written. If a precision is given,no null character need be present; if the precision is not specified, or isgreater than the size of the array, the array must contain a terminatingNUL character.

If the l (ell) modifier is used, the wchar t * argument is expected to bea pointer to an array of wide characters (pointer to a wide string). Eachwide character in the string is written. Wide characters from the arrayare written up to (but not including) a terminating wide NUL character;if a precision is specified, no more than the number specified are written(including shift sequences). If a precision is given, no null character needbe present; if the precision is not specified, or is greater than the numberof characters in the string, the array must contain a terminating wideNUL character.

p The void * pointer argument is printed in hexadecimal (as if by ‘%#x’or ‘%#lx’).

n The number of characters written so far is stored into the integer in-dicated by the int * (or variant) pointer argument. No argument isconverted.

% A ‘%’ is written. No argument is converted. The complete conversionspecification is ‘%%’.

648 Systems/C C Library

Page 667: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

The decimal point character is defined in the program’s locale (categoryLC NUMERIC).

In no case does a non-existent or small field width cause truncation of a numericfield; if the result of a conversion is wider than the field width, the field is expandedto contain the conversion result.

SECURITY CONSIDERATIONS

Refer to printf(3).

SEE ALSO

btowc(3), fputws(3), printf(3), putwc(3), setlocale(3), wcsrtombs(3), wscanf(3)

STANDARDS

The wprintf(), fwprintf(), swprintf(), vwprintf(), vfwprintf() and vsw-printf() functions conform to ISO/IEC 9899:1999 (“ISO C99”).

Systems/C C Library 649

Page 668: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

WSCANF(3)

NAME

wscanf, fwscanf, swscanf, vwscanf, vswscanf, vfwscanf - wide character input formatconversion

SYNOPSIS

#include <stdio.h>#include <wchar.h>

intwscanf(const wchar_t * restrict format, ...)

intfwscanf(FILE * restrict stream, const wchar_t * restrict format,

...)

intswscanf(const wchar_t * restrict str,

const wchar_t * restrict format, ...)

#include <stdarg.h>

intvwscanf(const wchar_t * restrict format, va_list ap)

intvswscanf(const wchar_t * restrict str,

const wchar_t * restrict format, va_list ap)

intvfwscanf(FILE * restrict stream, const wchar_t * restrict format,

va_list ap)

DESCRIPTION

The wscanf() family of functions scans input according to a format as describedbelow. This format may contain conversion specifiers; the results from such con-versions, if any, are stored through the pointer arguments. The wscanf() functionreads input from the standard input stream stdin, fwscanf() reads input fromthe stream pointer stream, and swscanf() reads its input from the wide charac-ter string pointed to by str. The vfwscanf() function is analogous to vfwprintf(3)

650 Systems/C C Library

Page 669: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

and reads input from the stream pointer stream using a variable argument list ofpointers (see stdarg(3)). The vwscanf() function scans a variable argument listfrom the standard input and the vswscanf() function scans it from a wide char-acter string; these are analogous to the vwprintf() and vswprintf() functionsrespectively. Each successive pointer argument must correspond properly with eachsuccessive conversion specifier (but see the * conversion below). All conversions areintroduced by the % (percent sign) character. The format string may also containother characters. White space (such as blanks, tabs, or newlines) in the formatstring match any amount of white space, including none, in the input. Everythingelse matches only itself. Scanning stops when an input character does not matchsuch a format character. Scanning also stops when an input conversion cannot bemade (see below).

CONVERSIONS

Following the % character introducing a conversion there may be a number of flagcharacters, as follows:

* Suppresses assignment. The conversion that follows occurs as usual, butno pointer is used; the result of the conversion is simply discarded.

hh Indicates that the conversion will be one of dioux or n and the nextpointer is a pointer to a char (rather than int).

h Indicates that the conversion will be one of dioux or n and the nextpointer is a pointer to a short int (rather than int).

l (ell) Indicates that the conversion will be one of dioux or n and the nextpointer is a pointer to a long int (rather than int), that the conversionwill be one of a, e, f, or g and the next pointer is a pointer to double(rather than float), or that the conversion will be one of c or s and thenext pointer is a pointer to an array of wchar t (rather than char).

ll (ell ell) Indicates that the conversion will be one of dioux or n and the nextpointer is a pointer to a long long int (rather than int).

L Indicates that the conversion will be one of a, e, f, or g and the nextpointer is a pointer to long double.

j Indicates that the conversion will be one of dioux or n and the nextpointer is a pointer to a intmax t (rather than int).

t Indicates that the conversion will be one of dioux or n and the nextpointer is a pointer to a ptrdiff t (rather than int).

z Indicates that the conversion will be one of dioux or n and the nextpointer is a pointer to a size t (rather than int).

Systems/C C Library 651

Page 670: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

q (deprecated) Indicates that the conversion will be one of dioux or n andthe next pointer is a pointer to a long long int (rather than int).

In addition to these flags, there may be an optional maximum field width, expressedas a decimal integer, between the % and the conversion. If no width is given, adefault of “infinity” is used (with one exception, below); otherwise at most thismany characters are scanned in processing the conversion. Before conversion begins,most conversions skip white space; this white space is not counted against the fieldwidth.

The following conversions are available:

% Matches a literal ‘%’. That is, “%%” in the format string matches a singleinput ‘%’ character. No conversion is done, and assignment does not occur.

d Matches an optionally signed decimal integer; the next pointer must be apointer to int.

i Matches an optionally signed integer; the next pointer must be a pointerto int. The integer is read in base 16 if it begins with ‘0x’ or ‘0X’, inbase 8 if it begins with ‘0’, and in base 10 otherwise. Only characters thatcorrespond to the base are used.

o Matches an octal integer; the next pointer must be a pointer to unsignedint.

u Matches an optionally signed decimal integer; the next pointer must be apointer to unsigned int.

x, X Matches an optionally signed hexadecimal integer; the next pointer mustbe a pointer to unsigned int.

a, A, e, E, f, F, g, G Matches a floating-point number in the style of wcstod(3). Thenext pointer must be a pointer to float (unless l or L is specified.)

s Matches a sequence of non-white-space wide characters; the next pointermust be a pointer to char, and the array must be large enough to acceptthe multibyte representation of all the sequence and the terminating NULcharacter. The input string stops at white space or at the maximum fieldwidth, whichever occurs first.

If an l qualifier is present, the next pointer must be a pointer to wchar t,into which the input will be placed.

S The same as ls.

c Matches a sequence of width count wide characters (default 1); the nextpointer must be a pointer to char, and there must be enough room forthe multibyte representation of all the characters (no terminating NUL isadded). The usual skip of leading white space is suppressed. To skip whitespace first, use an explicit space in the format.

652 Systems/C C Library

Page 671: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

If an l qualifier is present, the next pointer must be a pointer to wchar t,into which the input will be placed.

C The same as lc.

[ Matches a nonempty sequence of characters from the specified set of ac-cepted characters; the next pointer must be a pointer to char, and theremust be enough room for the multibyte representation of all the charactersin the string, plus a terminating NUL character. The usual skip of leadingwhite space is suppressed. The string is to be made up of characters in (ornot in) a particular set; the set is defined by the characters between theopen bracket [ character and a close bracket ] character. The set excludesthose characters if the first character after the open bracket is a circumflex^. To include a close bracket in the set, make it the first character afterthe open bracket or the circumflex; any other position will end the set.To include a hyphen in the set, make it the last character before the finalclose bracket; some implementations of wscanf() use “A-Z” to representthe range of characters between ‘A’ and ‘Z’. The string ends with the ap-pearance of a character not in the (or, with a circumflex, in) set or whenthe field width runs out.

If an l qualifier is present, the next pointer must be a pointer to wchar t,into which the input will be placed.

p Matches a pointer value (as printed by ‘%p’ in wprintf(3)); the next pointermust be a pointer to void.

n Nothing is expected; instead, the number of characters consumed thus farfrom the input is stored through the next pointer, which must be a pointerto int. This is not a conversion, although it can be suppressed with the *flag.

The decimal point character is defined in the program’s locale (categoryLC NUMERIC).

For backwards compatibility, a “conversion” of ‘%\0’ causes an immediate return ofEOF.

RETURN VALUES

These functions return the number of input items assigned, which can be fewer thanprovided for, or even zero, in the event of a matching failure. Zero indicates that,while there was input available, no conversions were assigned; typically this is dueto an invalid input character, such as an alphabetic character for a ‘%d’ conversion.The value EOF is returned if an input failure occurs before any conversion such asan end-of-file occurs. If an error or end-of-file occurs after conversion has begun,the number of conversions which were successfully completed is returned.

Systems/C C Library 653

Page 672: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

SEE ALSO

fgetwc(3), scanf(3), wcrtomb(3), wcstod(3), wcstol(3), wcstoul(3), wprintf(3)

STANDARDS

The fwscanf(), wscanf(), swscanf(), vfwscanf(), vwscanf() and vswscanf()functions conform to ISO/IEC 9899:1999 (“ISO C99”).

BUGS

In addition to the bugs documented in scanf(3), wscanf() does not support the“A-Z” notation for specifying character ranges with the character class conversion(‘%[’).

654 Systems/C C Library

Page 673: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

The Standard Library

Also present in the ANSI C definition are miscellaneous functions considered tobe part of the “standard” library. This section also describes some Systems/Cextensions which are similar to some of the ANSI standard functions.

Systems/C C Library 655

Page 674: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

FREE24(3)

NAME

free24 - free memory allocated with malloc24

SYNOPSIS

#include <stdlib.h>

void__free24(void * ptr)

DESCRIPTION

The free24() function causes the space pointed to by ptr to be deallocated, thatis, made available for further allocation. If ptr is a null pointer, no action oc-curs. Otherwise, if the argument does not match a pointer earlier returned by themalloc24() function, or if the space has been deallocated by a call to free24(),

then general havoc may occur.

RETURN VALUES

The free24() function returns no value.

SEE ALSO

malloc24(3), malloc(3), free(3), malloc31(3), free31(3)

656 Systems/C C Library

Page 675: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

FREE31(3)

NAME

free31 - free memory allocated with malloc31

SYNOPSIS

#include <stdlib.h>

void__free31(void * ptr)

DESCRIPTION

The free31() function causes the space pointed to by ptr to be deallocated, thatis, made available for further allocation. If ptr is a null pointer, no action oc-curs. Otherwise, if the argument does not match a pointer earlier returned by themalloc31() function, or if the space has been deallocated by a call to free31(),

then general havoc may occur.

RETURN VALUES

The free31() function returns no value.

SEE ALSO

malloc31(3), malloc(3), free(3), malloc24(3), free24(3)

Systems/C C Library 657

Page 676: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

MALLOC24(3)

NAME

malloc24 - allocate memory which is guaranteed to be 24-bit addressable

SYNOPSIS

#include <stdlib.h>

void *__malloc24(size_t size)

DESCRIPTION

The malloc24() function allocates uninitialized space for an object whose size isspecified by size. The malloc24() function maintains lists of free blocks, allocat-ing space from the appropriate list when possible.

Any space returned by the malloc24() function is guaranteed to reside below the16-megabyte “line”, and thus be addressable as a 24-bit address.

Memory space allocated with malloc24() must be returned to the list of availablespace via the free24() function.

RETURN VALUES

The malloc24() function returns a pointer to the allocated space if successful;otherwise a null pointer is returned.

SEE ALSO

free24(3), malloc(3), free(3), malloc31(3), free31(3), memory(3)

658 Systems/C C Library

Page 677: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

MALLOC31(3)

NAME

malloc31 - allocate memory which is guaranteed to be 31-bit addressable

SYNOPSIS

#include <stdlib.h>

void *__malloc31(size_t size)

DESCRIPTION

The malloc31() function allocates uninitialized space for an object whose size isspecified by size. The malloc31() function maintains lists of free blocks, allocat-ing space from the appropriate list when possible.

Any space returned by the malloc31() function is guaranteed to reside below the2-gigabytes “bar”, and thus be addressable with a 31-bit pointer.

Memory space allocated with malloc31() must be returned to the list of availablespace via the free31() function.

RETURN VALUES

The malloc31() function returns a pointer to the allocated space if successful;otherwise a null pointer is returned.

SEE ALSO

free31(3), malloc(3), free(3), malloc24(3), free24(3), memory(3)

Systems/C C Library 659

Page 678: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

ABORT(3)

NAME

abort - cause abnormal program termination

SYNOPSIS

#include <stdlib.h>

voidabort(void)

DESCRIPTION

The abort() function causes abnormal program termination to occur, unless thesignal SIGABRT is being caught and the signal handler does not return.

Any open streams are flushed and closed.

RETURN VALUES

The abort() function never returns.

SEE ALSO

signal(2), exit(3)

660 Systems/C C Library

Page 679: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

ABS(3)

NAME

abs - integer absolute value function

SYNOPSIS

#include <stdlib.h>

intabs(int j)

DESCRIPTION

The abs() function computes the absolute value of the integer j.

RETURN VALUES

The abs() function returns the absolute value.

SEE ALSO

cabs(3), floor(3), imaxabs(3), hypot(3), labs(3), math(3)

STANDARDS

The abs() function conforms to ISO/IEC 9899:1990 (“ISO C90”).

ISSUES

The absolute value of the most negative integer remains negative.

Systems/C C Library 661

Page 680: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

ARC4RANDOM(3)

NAME

arc4random, arc4random stir, arc4random addrandom - arc4 random number gen-erator

SYNOPSIS

#include <stdlib.h>

u_int32_tarc4random(void);

voidarc4random_stir(void);

voidarc4random_addrandom(unsigned char *dat, int datlen);

DESCRIPTION

The arc4random() function uses the key stream generator employed by the arc4cipher, which uses 8*8 8 bit S-Boxes. The S-Boxes can be in about (2**1700) states.The arc4random() function returns pseudo-random numbers in the range of 0 to(2**31)-1, and therefore has twice the range of RAND MAX.

The arc4random stir() function attemps to reads data from a random devicegenerator or other random values and use that data to permute the S-Boxes viaarc4random addrandom().

There is no need to call arc4random stir() before using arc4random(), sincearc4random() automatically initializes itself.

EXAMPLES

The following produces a drop-in replacement for the traditional rand() and ran-dom() functions using arc4random():

#define foo4random() (arc4random() % ((unsigned)RAND_MAX + 1))

662 Systems/C C Library

Page 681: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

SEE ALSO

rand(3), random(3)

HISTORY

RC4 was designed by RSA Data Security, Inc. It was posted anonymously toUSENET and was confirmed to be equivalent by several sources who had accessto the original cipher. Since RC4 used to be a trade secret, the cipher is now referredto as ARC4.

Systems/C C Library 663

Page 682: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

ATEXIT(3)

NAME

atexit - register a function to be called on exit

SYNOPSIS

#include <stdlib.h>

intatexit(void (*function)(void))

DESCRIPTION

The atexit() function registers the given function to be called at program exit,whether via exit(3) or via return from the program’s main(). Functions so registeredare called in reverse order; no arguments are passed. At least 32 functions can alwaysbe registered, and more are allowed as long as sufficient memory can be allocated.

RETURN VALUES

The atexit() function returns the value 0 if successful; otherwise the value -1 isreturned and the global variable errno is set to indicate the error.

ERRORS

[ENOMEM] No memory was available to add the function to the list. The ex-isting list of functions is unmodified.

SEE ALSO

exit(3)

STANDARDS

The atexit() function conforms to ISO/IEC 9899:1990 (“ISO C90”).

664 Systems/C C Library

Page 683: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

ATOF(3)

NAME

atof - convert string to double

SYNOPSIS

#include <stdlib.h>

doubleatof(const char *nptr)

DESCRIPTION

The atof() function converts the initial portion of the string pointed to by nptr todouble representation.

It is equivalent to:

strtod(nptr, (char **)NULL);

SEE ALSO

atoi(3), atol(3), strtod(3), strtol(3), strtoul(3)

STANDARDS

The atof() function conforms to ISO/IEC 9899:1990 (“ISO C90”).

ISSUES

This manual page represents intent instead of actual practice. While it is intendedthat atof() be implemented using strtod(3), this has not yet happened.

In the current system, atof() translates a string in the following form to a double:a string of leading white space, possibly followed by a sign (“+” or “-”), followed bya digit string which may contain one decimal point (“.”), that may be followed byeither of the exponent flags (“E” or “e”), and lastly, followed by a signed or unsignedinteger.

Systems/C C Library 665

Page 684: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

ATOI(3)

NAME

atoi - convert string to integer

SYNOPSIS

#include <stdlib.h>

intatoi(const char *nptr)

DESCRIPTION

The atoi() function converts the initial portion of the string pointed to by nptr tointeger representation.

It is equivalent to:

(int)strtol(nptr, (char **)NULL, 10);

SEE ALSO

atof(3), atol(3), strtod(3), strtol(3), strtoul(3)

STANDARDS

The atoi() function conforms to ISO/IEC 9899:1990 (“ISO C90”).

666 Systems/C C Library

Page 685: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

ATOL(3)

NAME

atol - convert string to long integer

SYNOPSIS

#include <stdlib.h>

longatol(const char *nptr)

long longatoll(const char *nptr);

DESCRIPTION

The atol() function converts the initial portion of the string pointed to by nptr tolong integer representation.

It is equivalent to:

strtol(nptr, (char **)NULL, 10);

The atoll() function converts the initial portion of the string pointed to by nptr tolong long integer representation.

It is equivalent to:

strtoll(nptr, (char **)NULL, 10);

ERRORS

The functions atol() and atoll() need not affect the value of errno on an error.

SEE ALSO

atof(3), atoi(3), strtod(3), strtol(3), strtoul(3)

Systems/C C Library 667

Page 686: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

STANDARDS

The atol() function conforms to ISO/IEC 9899:1990 (“ISO C90”). The atoll()function conforms to ISO/IEC 9899:1999 (“ISO C99”).

668 Systems/C C Library

Page 687: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

BSEARCH(3)

NAME

bsearch - binary search of a sorted table

SYNOPSIS

#include <stdlib.h>

void *bsearch(const void *key, const void *base,size_t nmemb, size_t size,int (*compar) (const void *, const void *))

DESCRIPTION

The bsearch() function searches an array of nmemb objects, the initial member ofwhich is pointed to by base, for a member that matches the object pointed to bykey. The size of each member of the array is specified by size.

The contents of the array should be in ascending sorted order according to thecomparison function referenced by compar. The compar routine is expected to havetwo arguments which point to the key object and to an array member, in thatorder, and should return an integer less than, equal to, or greater than zero if thekey object is found, respectively, to be less than, to match, or be greater than thearray member.

RETURN VALUES

The bsearch() function returns a pointer to a matching member of the array, or anull pointer if no match is found. If two members compare as equal, which memberis matched is unspecified.

SEE ALSO

lsearch(3), qsort(3)

STANDARDS

The bsearch() function conforms to ISO/IEC 9899:1990 (“ISO C90”).

Systems/C C Library 669

Page 688: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

CALLOC(3)

NAME

calloc - allocate clean memory (zero initialized space)

SYNOPSIS

#include <stdlib.h>

void *calloc(size_t nmemb, size_t size)

DESCRIPTION

The calloc() function allocates space for an array of nmemb objects, each of whosesize is size. The space is initialized to all bits zero.

RETURN VALUES

The calloc() function returns a pointer to the allocated space if successful; otherwisea null pointer is returned.

SEE ALSO

malloc(3), realloc(3), free(3),

STANDARDS

The calloc() function conforms to ISO/IEC 9899:1990 (“ISO C90”).

670 Systems/C C Library

Page 689: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

DIV(3)

NAME

div - return quotient and remainder from division

SYNOPSIS

#include <stdlib.h>

div_tdiv(int num, int denom)

DESCRIPTION

The div() function computes the value num/denum and returns the quotient andremainder in a structure named div t that contains two int integer members namedquot and rem. Unlike the implementation defined semantics of normal integer divi-sion, div() provides precise semantics on the quot and rem values.

The sign of quot is the same as the algebraic quotient.

If the division is inexact, the magnitude of the resulting quotient is the largestinteger less than the magnitude of the algebraic quotient.

If the result cannot be represented, the values of quot and rem are undefined.

If the result can be represented, then quot * denom + rem will equal num.

SEE ALSO

imaxdiv(3), ldiv(3), lldiv(3)

STANDARDS

The div() function conforms to ISO/IEC 9899:1990 (“ISO C90”).

Systems/C C Library 671

Page 690: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

ENVIRON(7)

NAME

environ - user environment

SYNOPSIS

extern char **environ;

DESCRIPTION

An array of strings called the environment is made available when a programbegins. By convention, these strings have the form "name=value". When a Sys-tems/C program is initiated via execve(2), these strings are taken from the POSIXenvironment.

The environ variable is the anchor for the getenv(3) family of functions, and shouldnot be otherwised used in programs.

SEE ALSO

execve(2), execle(3), getenv(3), setenv(3), setlocale(3), system(3)

672 Systems/C C Library

Page 691: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

EXIT(3)

NAME

exit - perform normal program termination

SYNOPSIS

#include <stdlib.h>

voidexit(int status)

DESCRIPTION

exit() terminates a process.

Before termination it performs the following functions in the order listed:

1. Call the functions registered with the atexit(3) function, in the reverse order oftheir registration.

2. Flush all open output streams.

3. Close all open streams.

4. Unlink all files created with the tmpfile(3) function.

Passing arbitrary values back to the environment as status is considered bad style.Instead, use the values as described in sysexits(3).

RETURN VALUES

The exit() function never returns.

SEE ALSO

exit(2), atexit(3), intro(3), sysexits(3)

STANDARDS

The exit() function conforms to ISO/IEC 9899:1990 (“ISO C90”).

Systems/C C Library 673

Page 692: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

FREE(3)

NAME

free - free memory allocated with malloc, calloc or realloc

SYNOPSIS

#include <stdlib.h>

voidfree(void *ptr)

DESCRIPTION

The free() function causes the space pointed to by ptr to be deallocated, that is,made available for further allocation. If ptr is a null pointer, no action occurs.Otherwise, if the argument does not match a pointer earlier returned by the calloc,malloc, or realloc function, or if the space has been deallocated by a call to free()or realloc, then general havoc may occur.

RETURN VALUES

The free() function returns no value.

SEE ALSO

calloc(3), malloc(3), realloc(3)

STANDARDS

The free() function conforms to ISO/IEC 9899:1990 (“ISO C90”).

674 Systems/C C Library

Page 693: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

GETENV(3)

NAME

getenv, putenv, setenv, unsetenv - environment variable functions

SYNOPSIS

#include <stdlib.h>

char *getenv(const char *name)

intsetenv(const char *name, const char *value,int overwrite)

intputenv(const char *string)

intunsetenv(const char *name)

DESCRIPTION

These functions set, unset and fetch environment variables from the host environ-ment list. For compatibility with differing environment conventions, the given argu-ments name and value may be appended and prepended, respectively, with an equalsign “=”.

The getenv() function obtains the current value of the environment variable, name.If the variable name is not in the current environment, a null pointer is returned.

The setenv() function inserts or resets the environment variable name in the currentenvironment list. If the variable name does not exist in the list, it is inserted with thegiven value. If the variable does exist, the argument overwrite is tested; if overwriteis zero, the variable is not reset, otherwise it is reset to the given value.

The putenv() function takes an argument of the form “name=value” and is equiv-alent to:

setenv(name, value, 1);

The unsetenv() function deletes all instances of the variable name pointed to byname from the list.

Systems/C C Library 675

Page 694: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

RETURN VALUES

The functions setenv(), putenv() and unsetenv() return zero if successful. Oth-erwise the global variable errno is set to indicate the error and a -1 is returned.

ERRORS

[EINVAL] The function setenv() or unsetenv() failed because the name isa NULL pointer, points to an empty string, or points to a stringcontaining an “=” character.

[ENOMEM] The function setenv() or putenv() failed because they were unableto allocate memory for the environment.

SEE ALSO

environ(7)

STANDARDS

The getenv() function conforms to ISO/IEC 9899:1990 (“ISO C90”).

676 Systems/C C Library

Page 695: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

GETOPT(3)

NAME

getopt - get option character from command line argument list

SYNOPSIS

#include <stdlib.h>

extern char *optarg;extern int optind;extern int optopt;extern int opterr;extern int optreset;

intgetopt(int argc, char * const *argv,const char *optstring)

DESCRIPTION

The getopt() function incrementally parses a command line argument list argv andreturns the next known option character. An option character is known if it hasbeen specified in the string of accepted option characters, optstring.

The option string optstring may contain the following elements: individual charac-ters, and characters followed by a colon to indicate an option argument is to follow.For example, an option string "x" recognizes an option "-x", and an option string"x:" recognizes an option and argument "-x argument". Leading white space in afollowing argument does not affect the operation of getopt().

On return from getopt(), optarg points to an option argument, if it is anticipated,and the variable optind contains the index to the next argv argument for a subse-quent call to getopt(). The variable optopt saves the last known option characterreturned by getopt().

The variable opterr and optind are both initialized to 1. The optind variable maybe set to another value before a set of calls to getopt() in order to skip over moreor less argv entries.

In order to use getopt() to evaluate multiple sets of arguments or to evaluate asingle set of arguments multiple times, the variable optreset must be set to 1 beforethe second and each additional set of calls to getopt(), and the variable optindmust be reinitialized.

Systems/C C Library 677

Page 696: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

The getopt() function returns -1 when the argument list is exhausted, or ’?’ if anon-recognized option is encountered. The interpretation of options in the argumentlist may be canceled by the option “--” (double dash) which causes getopt() tosignal the end of argument processing and return -1. When all options have beenprocessed (i.e., up to the first non-option argument), getopt() returns -1.

DIAGNOSTICS

If the getopt() function encounters a character not found in the string optargor detects a missing option argument it writes an error message to the stderr andreturns ’?’. Setting opterr to a zero will disable these error messages. If optstringhas a leading ‘:’ then a missing option argument causes a ‘:’ to be returned inaddition to suppressing any error messages.

Option arguments are allowed to begin with “-”; this is reasonable but reduces theamount of error checking possible.

EXTENSIONS

The optreset variable was added to make it possible to call the getopt() functionmultiple times. This is an extension to the IEEE Std1003.2 (“POSIX.2”) specifica-tion.

EXAMPLE

extern char *optarg;extern int optind;int bflag, ch, fd;

bflag = 0;while ((ch = getopt(argc, argv, "bf:")) != -1) {

switch(ch) {case ’b’:

bflag = 1;break;

case ’f’:if ((fd = open(optarg, O_RDONLY, 0)) < 0) {

(void)fprintf(stderr,"myname: %s: %s\n",optarg,strerror(errno));

exit(1);}break;

678 Systems/C C Library

Page 697: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

case ’?’:default:usage();

}}argc -= optind;argv += optind;

ISSUES

The getopt() function was once specified to return EOF instead of -1. Thiswas changed by IEEE Std1003.2-1992 (“POSIX.2”) to decouple getopt() from<stdio.h>.

A single dash “-” may be specified as a character in optstring, however it shouldnever have an argument associated with it. This allows getopt() to be used withprograms that expect “-” as an option flag. This practice is wrong, and shouldnot be used in any current development. It is provided for backward compatibilityonly. By default, a single dash causes getopt() to return -1. This is, we believe,compatible with System V.

It is also possible to handle digits as option letters. This allows getopt() to be usedwith programs that expect a number (“-3”) as an option. This practice is wrong,and should not be used in any current development. It is provided for backwardcompatibility only. The following code fragment works in most cases.

int length;char *p;

while((c = getopt(argc, argv, ‘‘0123456789’’)) != -1) {switch (c) {case ’0’: case ’1’: case ’2’: case ’3’:case ’4’: case ’5’: case ’6’: case ’7’:case ’8’: case ’9’:

p = argv[optind - 1];if (p[0] == ’-’ && p[1] == ch && !p[2])

length = atoi(++p);else

length = atoi(argv[optind] + 1);break;

}}

Systems/C C Library 679

Page 698: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

GETSUBOPT(3)

NAME

getsubopt - get sub options from an argument

SYNOPSIS

#include <stdlib.h>

extern char *suboptarg

intgetsubopt(char **optionp, char * const *tokens,char **valuep)

DESCRIPTION

The getsubopt() function parses a string containing tokens delimited by one ormore tab, space or comma (’,’) character. It is intended for use in parsing groups ofoption arguments provided as part of a utility command line.

The argument optionp is a pointer to a pointer to the string. The argument tokensis a pointer to a NULL-terminated array of pointers to strings.

The getsubopt() function returns the zero-based offset of the pointer in the tokensarray referencing a string which matches the first token in the string, or, -1 if thestring contains no tokens or tokens does not contain a matching string.

If the token is of the form “name=value” the location referenced by valuep will beset to point to the start of the “value” portion of the token.

On return from getsubopt(), optionp will be set to point to the start of the nexttoken in the string, or the null at the end of the string if no more tokens are present.The external variable suboptarg will be set to point to the start of the currenttoken, or NULL if no tokens were present. The argument valuep will be set to pointto the “value” portion of the token, or NULL if no “value” portion was present.

EXAMPLE

char *tokens[] = {#define ONE 0

"one",#define TWO 1

680 Systems/C C Library

Page 699: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

"two",NULL

};

...

extern char *optarg, *suboptarg;char *options, *value;

while ((ch = getopt(argc, argv, "ab:")) != -1) {switch(ch) {case ’a’:

/* process ‘‘a’’ option */break;

case ’b’:options = optarg;while (*options) {

switch(getsubopt(&options,tokens, &value)) {case ONE:

/* process "one" sub option */break;

case TWO:/* process "two" sub option */if (!value)

error("no value for two");i = atoi(value);break;

case -1:if (suboptarg)

error("illegal sub option %s",suboptarg);

elseerror("missing sub option");

break;}

}break;

}}

SEE ALSO

getopt(3), strsep(3)

Systems/C C Library 681

Page 700: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

IMAXABS(3)

NAME

imaxabs - return the absolute value of a intmax t integer

SYNOPSIS

#include <inttypes.h>

intmax_timaxabs(intmax_t j)

DESCRIPTION

The imaxabs() function returns the absolute value of the intmax t integer j.

SEE ALSO

abs(3), cabs(3), labs(3), llabs(3), floor(3), math(3)

STANDARDS

The imaxabs() function conforms to ISO/IEC 9899:1999 (“ISO C99”).

682 Systems/C C Library

Page 701: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

IMAXDIV(3)

NAME

imaxdiv - return quotient and remainder from division

SYNOPSIS

#include <inttypes.h>

imaxdiv\_timaxdiv(intmax\_t num, intmax\_t denom)

DESCRIPTION

The imaxdiv() function computes the value num/denum and returns the quotientand remainder in a structure named imaxdiv t that contains two intmax t integermembers named quot (the quotient) and rem (the remainder).

If the result cannot be represented, the values of quot and rem are undefined.

SEE ALSO

div(3), ldiv(3), lldiv(3)

STANDARDS

The imaxdiv() function conforms to ISO/IEC 9899:1999 (“ISO C99”).

Systems/C C Library 683

Page 702: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

LABS(3)

NAME

labs - return the absolute value of a long integer

SYNOPSIS

#include <stdlib.h>

longlabs(long j)

DESCRIPTION

The labs() function returns the absolute value of the long integer j.

SEE ALSO

abs(3), cabs(3), imaxabs(3), floor(3), math(3)

STANDARDS

The labs() function conforms to ISO/IEC 9899:1990 (“ISO C90”).

ISSUES

The absolute value of the most negative integer remains negative.

684 Systems/C C Library

Page 703: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

LDIV(3)

NAME

ldiv - return quotient and remainder from division

SYNOPSIS

#include <stdlib.h>

ldiv_tldiv(long num, long denom)

DESCRIPTION

The ldiv() function computes the value num/denom and returns the quotient andremainder in a structure named ldiv t that contains two long integer membersnamed quot and rem. Unlike the implementation defined semantics of normal longdivision, ldiv() provides precise semantics on the quot and rem values.

The sign of quot is the same as the algebraic quotient.

If the division is inexact, the magnitude of the resulting quotient is the largestinteger less than the magnitude of the algebraic quotient.

If the result cannot be represented, the values of quot and rem are undefined.

If the result can be represented, then quot * denom + rem will equal num.

SEE ALSO

div(3), imaxdiv(3), lldiv(3), math(3)

STANDARDS

The ldiv() function conforms to ISO/IEC 9899:1990 (“ISO C90”).

Systems/C C Library 685

Page 704: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

LLABS(3)

NAME

llabs - returns absolute value

SYNOPSIS

#include <stdlib.h>

long longlong labs(long long j)

DESCRIPTION

The llabs() function returns the absolute value of the long long integer j.

SEE ALSO

abs(3), cabs(3), imaxabs(3), labs(3), floor(3), math(3)

STANDARDS

The llabs() function conforms to ISO/IEC 9899:1999 (“ISO C99”).

ISSUES

The absolute value of the most negative integer remains negative.

686 Systems/C C Library

Page 705: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

LLDIV(3)

NAME

lldiv - return quotient and remainder from division

SYNOPSIS

#include <stdlib.h>

lldiv_tldiv(long long num, long long denom)

DESCRIPTION

The lldiv() function computes the value num/denom and returns the quotient andremainder in a structure named lldiv t that contains two long long integer mem-bers named quot and rem. Unlike the implementation defined semantics of normallong long division, lldiv() provides precise semantics on the quot and rem values.

The sign of quot is the same as the algebraic quotient.

If the division is inexact, the magnitude of the resulting quotient is the largestinteger less than the magnitude of the algebraic quotient.

If the result cannot be represented, the values of quot and rem are undefined.

If the result can be represented, then quot * denom + rem will equal num.

SEE ALSO

div(3), imaxdiv(3), ldiv(3), math(3)

Systems/C C Library 687

Page 706: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

MALLOC(3)

NAME

malloc - general memory allocation function

SYNOPSIS

#include <stdlib.h>

void *malloc(size_t size)

DESCRIPTION

The malloc() function allocates uninitialized space for an object whose size is spec-ified by size. The malloc() function maintains multiple lists of free blocks accordingto various sizes, allocating space from the appropriate list.

The allocated space is suitably aligned (after possible pointer coercion) for storageof any type of object. If the space is of pagesize or larger, the memory returned willbe page-aligned.

RETURN VALUES

The malloc() function returns a pointer to the allocated space if successful; other-wise a null pointer is returned.

SEE ALSO

free(3), calloc(3), alloca(3), realloc(3), memory(3)

STANDARDS

The malloc() function conforms to ISO/IEC 9899:1990 (“ISO C90”).

688 Systems/C C Library

Page 707: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

MEMORY(3)

NAME

malloc, free, realloc, calloc, alloca - general memory allocation operations

SYNOPSIS

#include <stdlib.h>

void *malloc(size_t size)

voidfree(void *ptr)

void *realloc(void *ptr, size_t size)

void *calloc(size_t nelem, size_t elsize)

void *alloca(size_t size)

void *__malloc31(size_t size)

void *__free31(void *ptr);

void *__malloc24(size_t size)

void *__free24(void *ptr);

DESCRIPTION

These functions allocate and free memory for the calling process. They are describedin the individual manual pages.

Systems/C C Library 689

Page 708: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

SEE ALSO

calloc(3), free(3), malloc(3), realloc(3), alloca(3), malloc31(3), free31(3),malloc24(3), free24(3),

STANDARDS

These functions, with the exception of alloca(), malloc31(), free31(),malloc24() and free24() conform to ISO/IEC 9899:1990 (“ISO C90”).

690 Systems/C C Library

Page 709: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

QSORT(3)

NAME

qsort, heapsort, mergesort - sort functions

SYNOPSIS

#include <stdlib.h>

voidqsort(void *base, size_t nmemb, size_t size,int (*compar)(const void *, const void *))

intheapsort(void *base, size_t nmemb, size_t size,int (*compar)(const void *, const void *))

intmergesort(void *base, size_t nmemb, size_t size,int (*compar)(const void *, const void *))

DESCRIPTION

The qsort() function is a modified partition-exchange sort, or quicksort. The heap-sort() function is a modified selection sort. The mergesort() function is a modifiedmerge sort with exponential search intended for sorting data with pre-existing order.

The qsort() and heapsort() functions sort an array of nmemb objects, the initialmember of which is pointed to by base. The size of each object is specified by size.mergesort() behaves similarly, but requires that size be greater than sizeof(void*) / 2.

The contents of the array base are sorted in ascending order according to a compar-ison function pointed to by compar, which requires two arguments pointing to theobjects being compared.

The comparison function must return an integer less than, equal to, or greater thanzero if the first argument is considered to be respectively less than, equal to, orgreater than the second.

The functions qsort() and heapsort() are not stable, that is, if two members com-pare as equal, their order in the sorted array is undefined. The function merge-sort() is stable.

Systems/C C Library 691

Page 710: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

The qsort() function is an implementation of C.A.R. Hoare’s “quicksort” algorithm,a variant of partition-exchange sorting; in particular, see D.E. Knuth’s AlgorithmQ. qsort() takes O N lg N average time. This implementation uses median selectionto avoid its O N**2 worst-case behavior.

The heapsort() function is an implementation of J.W.J. William’s “heapsort” al-gorithm, a variant of selection sorting; in particular, see D.E. Knuth’s AlgorithmH. heapsort() takes O N lg N worst-case time. Its only advantage over qsort() isthat it uses almost no additional memory; while qsort() does not allocate memory,it is implemented using recursion.

The function mergesort() requires additional memory of size nmemb * size bytes;it should be used only when space is not at a premium. mergesort() is optimizedfor data with pre-existing order; its worst case time is O N lg N; its best case is ON.

Normally, qsort() is faster than mergesort() is faster than heapsort(). Memoryavailability and pre-existing order in the data can make this untrue.

RETURN VALUES

The qsort() function returns no value.

Upon successful completion, heapsort() and mergesort() return 0. Otherwise,they return -1 and the global variable errno is set to indicate the error.

ERRORS

The heapsort() function succeeds unless:

[EINVAL] The size argument is zero, or, the size argument to mergesort() isless than “sizeof(void *) / 2”.

[ENOMEM] heapsort() or mergesort() were unable to allocate memory.

COMPATIBILITY

Previous versions of qsort() did not permit the comparison routine itself to callqsort(3). This is no longer true.

692 Systems/C C Library

Page 711: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

SEE ALSO

radixsort(3)

Hoare, C.A.R., “Quicksort”, The Computer Journal, 5:1, pp. 10-15, 1962.

Williams, J.W.J, “Heapsort”, Communications of the ACM, 7:1, pp. 347-348, 1964.

Knuth, D.E., “Sorting and Searching”, The Art of Computer Programming, Vol. 3,pp. 114-123, 145-149, 1968.

Mcilroy, P.M., “Optimistic Sorting and Information Theoretic Complexity”, FourthAnnual ACM-SIAM Symposium on Discrete Algorithms, January 1992.

Bentley, J.L., “Engineering a Sort Function”, [email protected], January1992.

STANDARDS

The qsort() function conforms to ISO/IEC 9899:1990 (“ISO C90”).

Systems/C C Library 693

Page 712: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

RADIXSORT(3)

NAME

radixsort - radix sort

SYNOPSIS

#include <limits.h>#include <stdlib.h>

intradixsort(const unsigned char **base, int nmemb,const unsigned char *table, unsigned endbyte)

intsradixsort(const unsigned char **base, int nmemb,const unsigned char *table, unsigned endbyte)

DESCRIPTION

The radixsort() and sradixsort() functions are implementations of radix sort.

These functions sort an array of pointers to byte strings, the initial member of whichis referenced by base. The byte strings may contain any values; the end of each stringis denoted by the user-specified value endbyte.

Applications may specify a sort order by providing the table argument. If non-NULL, table must reference an array of UCHAR MAX + 1 bytes which contains the sortweight of each possible byte value. The end-of-string byte must have a sort weightof 0 or 255 (for sorting in reverse order). More than one byte may have the samesort weight. The table argument is useful for applications to use when to sortingdifferent characters equally. For example, providing a table with the same weightsfor A-Z as for a-z will result in a case-insensitive sort. If table is NULL, the contentsof the array are sorted in ascending order according to the ASCII order of the bytestrings they reference and endbyte has a sorting weight of 0.

The sradixsort() function is stable, that is, if two elements compare as equal, theirorder in the sorted array is unchanged. The sradixsort() function uses additionalmemory sufficient to hold nmemb pointers.

The radixsort() function is not stable, but uses no additional memory.

These functions are variants of most-significant-byte radix sorting; in particular, seeD.E. Knuth’s Algorithm R and section 5.2.5, exercise 10. They take linear timerelative to the number of bytes in the strings.

694 Systems/C C Library

Page 713: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

RETURN VALUES

Upon successful completion 0 is returned. Otherwise, -1 is returned and the globalvariable errno is set to indicate the error.

ERRORS

[EINVAL] The value of the endbyte element of table is not 0 or 255.

Additionally, the sradixsort() function may fail and set errno for any of the errorsspecified for the library routine malloc(3).

SEE ALSO

qsort(3)

Knuth, D.E., “Sorting and Searching”, The Art of Computer Programming, Vol. 3,pp. 170-178, 1968.

Paige, R., “Three Partition Refinement Algorithms”, SIAM J. Comput., No. 6, Vol.16, 1987.

McIlroy, P., “Computing Systems”, Engineering Radix Sort, Vol. 6:1, pp. 5-27,1993.

Systems/C C Library 695

Page 714: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

RAND(3)

NAME

rand, srand - bad random number generator

SYNOPSIS

#include <stdlib.h>

voidsrand(unsigned seed)

intrand(void)

DESCRIPTION

These interfaces are obsoleted by random(3).

The rand() function computes a sequence of pseudo-random integers in the rangeof 0 to RAND MAX (as defined by the header file <stdlib.h>).

The srand() function sets its argument as the seed for a new sequence of pseudo-random numbers to be returned by rand(). These sequences are repeatable bycalling srand() with the same seed value.

If no seed value is provided, the functions are automatically seeded with a value of1.

SEE ALSO

random(3)

STANDARDS

The rand() and srand() functions conform to ISO/IEC 9899:1990 (“ISO C90”).

696 Systems/C C Library

Page 715: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

RANDOM(3)

NAME

random, srandom, initstate, setstate - better random number generator; routinesfor changing generators

SYNOPSIS

#include <stdlib.h>

longrandom(void)

voidsrandom(unsigned long seed)

char *initstate(unsigned long seed, char *state, long n)

char *setstate(char *state)

DESCRIPTION

The random() function uses a non-linear additive feedback random number gener-ator employing a default table of size 31 long integers to return successive pseudo-random numbers in the range from 0 to (2**31)-1. The period of this randomnumber generator is very large, approximately 16*((2**31)-1).

The random() and srandom() functions have (almost) the same calling sequenceand initialization properties as the rand(3) and srand(3) functions. The differenceis that rand(3) produces a much less random sequence – in fact, the low dozen bitsgenerated by rand go through a cyclic pattern. All the bits generated by random()are usable. For example, ‘random()&01’ will produce a random binary value.

Like rand(3), random() will by default produce a sequence of numbers that can beduplicated by calling srandom() with ‘1’ as the seed.

The initstate() routine allows a state array, passed as an argument, to be initializedfor future use. The size of the state array (in bytes) is used by initstate() to decidehow sophisticated a random number generator it should use – the more state, thebetter the random numbers will be. Current “optimal” values for the amount ofstate information are 8, 32, 64, 128, and 256 bytes; other amounts will be roundeddown to the nearest known amount. Using less than 8 bytes will cause an error. The

Systems/C C Library 697

Page 716: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

seed for the initialization (which specifies a starting point for the random numbersequence, and provides for restarting at the same point) is also an argument. Theinitstate() function returns a pointer to the previous state information array.

Once a state has been initialized, the setstate() routine provides for rapid switchingbetween states. The setstate() function returns a pointer to the previous statearray; its argument state array is used for further random number generation untilthe next call to initstate() or setstate().

Once a state array has been initialized, it may be restarted at a different pointeither by calling initstate(), with the desired seed, the state array, and its size, orby calling both setstate() with the state array and srandom() with the desiredseed. The advantage of calling both setstate() and srandom() is that the size ofthe state array does not have to be remembered after it is initialized.

With 256 bytes of state information, the period of the random number generator isgreater than 2**69 which should be sufficient for most purposes.

DIAGNOSTICS

If initstate() is called with less than 8 bytes of state information, or if setstate()detects that the state information has been garbled, error messages are printed onthe standard error output.

SEE ALSO

rand(3), srand(3), urandom(4)

ISSUES

About 2/3 the speed of rand(3).

The historical implementation used to have a very weak seeding; the random se-quence did not vary much with the seed. The current implementation employs abetter pseudo-random number generator for the initial state calculation.

698 Systems/C C Library

Page 717: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

REALLOC(3)

NAME

realloc - reallocation of memory function

SYNOPSIS

#include <stdlib.h>

void *realloc(void *ptr, size_t size)

DESCRIPTION

The realloc() function changes the size of the object pointed to by ptr to the sizespecified by size. The contents of the object are unchanged up to the lesser of thenew and old sizes. If the new size is larger, the value of the newly allocated portionof the object is indeterminate. If ptr is a null pointer, the realloc() function behaveslike the malloc(3) function for the specified size. Otherwise, if ptr does not match apointer earlier returned by the calloc(3), malloc(3), or reallot() function, or if thespace has been deallocated by a call to the free or realloc() function, unpredictableand usually detrimental behavior will occur. If the space cannot be allocated, theobject pointed to by ptr is unchanged. If size is zero and ptr is not a null pointer,the object it points to is freed.

The realloc() function returns either a null pointer or a pointer to the possiblymoved allocated space.

SEE ALSO

alloca(3), calloc(3), free(3), malloc(3),

STANDARDS

The realloc() function conforms to ISO/IEC 9899:1990 (“ISO C90”).

Systems/C C Library 699

Page 718: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

REALPATH(3)

NAME

realpath - returns the canonicalized absolute //HFS:-style pathname

SYNOPSIS

#include <sys/param.h>#include <stdlib.h>

char *realpath(const char *pathname, char resolved_path[MAXPATHLEN]);

DESCRIPTION

The realpath() function resolves all symbolic links, extra “/” characters and ref-erences to /./ and /../ in the //HFS:-style path specified by pathname, and copiesthe resulting absolute pathname into the memory referenced by resolved path. Theresolved path argument must refer to a buffer capable of storing at least MAXPATHLENcharacters.

The realpath() function will resolve both absolute and relative paths and returnthe absolute pathname corresponding to pathname. All but the last component ofpathname must exist when realpath() is called.

RETURN VALUES

The realpath() function returns resolved path on success. If an error occurs, re-alpath() returns NULL, and resolved path contains the pathname which caused theproblem.

ERRORS

The function realpath() may fail and set the external variable errno for any ofthe errors specified for the library functions chdir(2), close(2), fchdir(2), lstat(2),open(2), readlink(2) and getcwd(3).

SEE ALSO

getcwd(3)

700 Systems/C C Library

Page 719: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

STRTOD(3)

NAME

strtod - convert string to double

SYNOPSIS

#include <stdlib.h>

doublestrtod(const char *nptr, char **endptr);

floatstrtof(const char *nptr, char **endptr);

long doublestrtold(const char *nptr, char **endptr);

DESCRIPTION

These functions function convert the initial portion of the string pointed to by nptrto double, float, and long double representation, respectively.

The expected form of the string is an optional plus (“+”) or minus sign (“-”) followedby a sequence of digits optionally containing a decimal-point character, optionallyfollowed by an exponent. An exponent consists of an “E” or “e”, followed by anoptional plus or minus sign, followed by a sequence of digits.

Alternatively, if the portion of the string following the optional plus or minus signbegins with “INFINITY” or “NAN”, ignoring case, it is interpreted as an infinity or aquiet NaN, respectively. HFP values cannot represent infinity or NaN; in that caseit is interpreted as HUGE VAL and 0.0.

Leading white-space characters in the string (as defined by the isspace(3) function)are skipped.

These functions use the isBFP() function to determine if a BFP (IEEE) or HFPvalue is to be returned.

RETURN VALUES

The strtod(), strtof(), strtold() functions returns the converted value, if any.

Systems/C C Library 701

Page 720: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

If endptr is not NULL, a pointer to the character after the last character used in theconversion is stored in the location referenced by endptr.

If no conversion is performed, zero is returned and the value of nptr is stored in thelocation referenced by endptr.

If the correct value would cause overflow, plus or minus HUGE VAL, HUGE VALF, orHUGE VALL is returned (according to the sign of the value), and ERANGE is stored inerrno. If the correct value would cause underflow, zero is returned and ERANGE isstored in errno.

ERRORS

[ERANGE] Overflow or underflow occurred.

SEE ALSO

atof(3), atoi(3), atol(3), strtol(3), strtoul(3)

STANDARDS

The strtod() function conforms to ISO/IEC 9899:1990 (“ISO C90”).

702 Systems/C C Library

Page 721: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

STRTOL(3)

NAME

strtol, strtoll, strtoimax, strtoq - convert string value to a long, long long,intmax t or quad t integer

SYNOPSIS

#include <stdlib.h>#include <limits.h>

longstrtol(const char *nptr, char **endptr, int base)

longstrtoll(const char *nptr, char **endptr, int base)

#include <inttypes.h>

intmax_tstrtoimax(const char * restrict nptr,

char ** restrict endptr, int base)

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

quad_tstrtoq(const char *nptr, char **endptr, int base)

DESCRIPTION

The strtol() function converts the string in nptr to a long value. The strtoll()functions converts the string in nptr to a long long value. The strtoimax() func-tion converts the string in nptr to a intmax t value. The strtoq() function convertsthe string in nptr to a quad t value. The conversion is done according to the givenbase, which must be between 2 and 36 inclusive, or be the special value 0.

The string may begin with an arbitrary amount of white space (as determined byisspace(3)) followed by a single optional ‘+’ or ‘-’ sign. If base is zero or 16, the stringmay then include a ‘0x’ prefix, and the number will be read in base 16. Otherwise,a zero base is taken as 10 (decimal) unless the next character is ‘0’, in which case itis taken as 8 (octal).

Systems/C C Library 703

Page 722: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

The remainder of the string is converted to a long value in the obvious manner,stopping at the first character which is not a valid digit in the given base. (In basesabove 10, the letter ‘A’ in either upper or lower case represents 10, ‘B’ represents11, and so forth, with ‘Z’ representing 35.)

If endptr is non nil, strtol() stores the address of the first invalid character in*endptr. If there were no digits at all, however, strtol() stores the original valueof nptr in *endptr. Thus, if *nptr is not ’\0’ but **endptr is ’\0’ on return, theentire string was valid.

RETURN VALUES

The strtol(), strtoll() and strtoimax() functions returns the result of the con-version, unless the value would underflow or overflow. If an underflow occurs,strtol() returns LONG MIN, strtoll() returns LLONG MIN and strtoimax() returnsINTMAX MIN. If an overflow occurs, strtol() returns LONG MAX, strtoll() returnsLLONG MAX and strtoimax() returns INTMAX MAX. If an overflow or underflow oc-curs, errno is set to ERANGE.

ERRORS

[ERANGE] The given string was out of range; the value converted has beenclamped.

SEE ALSO

atof(3), atoi(3), atol(3), strtod(3), strtoul(3)

STANDARDS

The strtol() function conforms to ISO/IEC 9899:1990 (“ISO C90”). The strtoll()and strtoimax() functions conform to ISO/IEC 9899:1999 (“ISO C99”). The str-toq() function is deprecated.

ISSUES

Ignores the current locale.

704 Systems/C C Library

Page 723: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

STRTOUL(3)

NAME

strtoul, strtoull, strtoumax, strtouq - convert a string to an unsigned long,unsigned long long, uintmax t or uquad t integer

SYNOPSIS

#include <stdlib.h>#include <limits.h>

unsigned longstrtoul(const char *nptr, char **endptr, int base);

unsigned long longstrtoull(const char *nptr, char **endptr, int base);

#include <inttypes.h>

uintmax_tstrtoumax(const char * restrict nptr,

char ** restrict endptr, int base);

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

u_quad_tstrtouq(const char *nptr, char **endptr, int base);

DESCRIPTION

The strtoul() function converts the string in nptr to an unsigned long value.The strtoull() function converts the string in nptr to an unsigned long longvalue. The strtouq() function converts the string in nptr to a u quad t value. Theconversion is done according to the given base, which must be between 2 and 36inclusive, or be the special value 0.

The string may begin with an arbitrary amount of white space (as determined byisspace(3)) followed by a single optional ‘+’ or ‘-’ sign. If base is zero or 16, the stringmay then include a ‘0x’ prefix, and the number will be read in base 16; otherwise,a zero base is taken as 10 (decimal) unless the next character is ‘0’, in which case itis taken as 8 (octal).

Systems/C C Library 705

Page 724: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

The remainder of the string is converted to an unsigned long value in the obviousmanner, stopping at the end of the string or at the first character that does not pro-duce a valid digit in the given base. (In bases above 10, the letter ‘A’ in either upperor lower case represents 10, ‘B’ represents 11, and so forth, with ‘Z’ representing35.)

If endptr is non nil, strtoul() stores the address of the first invalid character in*endptr. If there were no digits at all, however, strtoul() stores the original valueof nptr in *endptr. (Thus, if *nptr is not ’\0’ but **endptr is ’\0’ on return,the entire string was valid.)

RETURN VALUES

The strtoul(), strtoull() and strtoumax() functions return either the result ofthe conversion or, if there was a leading minus sign, the negation of the result of theconversion, unless the original (non-negated) value would overflow; in the latter case,strtoul() returns ULONG MAX, strtoull() returns ULLONG MAX and strtoumax() re-turns UINTMAX MAX. If the conversion would overflow, the global variable errno isset to ERANGE.

ERRORS

[ERANGE] The given string was out of range; the value converted has beenclamped.

SEE ALSO

strtol(3)

STANDARDS

The strtoul() function conforms to ISO/IEC 9899:1990 (“ISO C90”). The str-toull() and strtoumax() functions conform to ISO/IEC 9899:1999 (“ISO C99”).The strtouq() function is deprecated.

ISSUES

Ignores the current locale.

706 Systems/C C Library

Page 725: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

SYSCONF(3)

NAME

sysconf – get configurable system variables

SYNOPSIS

#include <unistd.h>

longsysconf(int name);

DESCRIPTION

The sysconf() function provides a method for applications to determine the currentvalue of a configurable system limit or option variable. The name argument specifiesthe system variable to be queried. Symbolic constants for each name value are foundin the include file <unistd.h>.

The available values are as follows:

SC ARG MAX The maximum bytes of argument to execve(2).

SC CHILD MAX The maximum number of simultaneous processes per user id.

SC CLK TCK The frequency of the statistics clock in ticks per second.

SC JOB CONTROL Return 1 if job control is available on this system, otherwise-1.

SC NGROUPS MAX The maximum number of supplemental groups.

SC OPEN MAX The maximum number of open files per user id.

SC SAVED IDS Returns 1 if saved set-group and saved set-user ID is available,otherwise -1.

SC MMAP MEM MAX NP Maximum area (in pages) of date space that can allo-cated to mmap().

SC TTY GROUP Return the group number associated with the TTYGROUP set-ting.

SC THREADS MAX NP The maximum number of threads allowed to be createdby pthread create().

Systems/C C Library 707

Page 726: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

SC THREADS TASKS MAX NP The maximum number of MVS TASKs that canbe used to handle threads created by pthread create().

SC TZNAME MAX The minimum maximum number of types supported for thename of a timezone.

SC VERSION The version of IEEE Std 1003.1 (“POSIX.1”) with which the systemattempts to comply.

SC 2 CHAR TERM Return 1 if the system supports at least one terminal typecapable of all operations described in IEEE Std 1003.2 (“POSIX.2”),otherwise -1.

SC PAGESIZE The size of the system page in bytes.

SC PAGE SIZE The size of the system page in bytes.

RETURN VALUES

If the call to sysconf() is not successful, -1 is returned and errno is set appropri-ately. Otherwise, if the variable s associated with functionality that is not supported,-1 is returned and errno is not modified. Otherwise, the current variable value isreturned.

ERRORS

The following error may be reported:

[EINVAL] The value of the name argument is invalid.

STANDARDS

Except for the fact that values returned by sysconf() may change over the lifetime ofthe calling process, this function conforms to IEEE Std 1003.1-1988 (“POSIX.1”).

708 Systems/C C Library

Page 727: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

SYSTEM(3)

NAME

system - pass a command to the POSIX shell

SYNOPSIS

#include <stdlib.h>

intsystem(const char *string);

DESCRIPTION

The system() function hands the argument string to the POSIX command inter-preter sh. The calling process waits for the shell to finish executing the command,ignoring SIGINT and SIGQUIT, and blocking SIGCHLD.

If string is a NULL pointer, system() will return non-zero if the command interpreter(sh) is available, and zero if it is not.

The system() function returns the exit status of the shell as returned by waitpid(2),or -1 if an error occurred when invoking fork(2) or waitpid(2). A return value of127 means the execution of the shell failed.

SEE ALSO

execve(2), fork(2), waitpid(2), popen(3)

STANDARDS

The system() function conforms to ISO/IEC 9899:1990 (“ISO C90”), and is ex-pected to be IEEE Std 1003.2 (“POSIX.2”) compatible.

Systems/C C Library 709

Page 728: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

Standard Time library

The ANSI standard defines several functions for manipulating time values, whichare found in the Standard Time Library.

710 Systems/C C Library

Page 729: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

CTIME(3)

NAME

asctime, asctime r, ctime, ctime r, difftime, gmtime, gmtime r, localtime, local-time r, mktime, timegm - transform binary date and time values

SYNOPSIS

#include <time.h>

extern char *tzname[2];

char *ctime(const time_t *clock);

doubledifftime(time_t time1, time_t time0);

char *asctime(const struct tm *tm);

struct tm *localtime(const time_t *clock);

struct tm *gmtime(const time_t *clock);

time_tmktime(struct tm *tm);

time_ttimegm(struct tm *tm);

char *ctime_r(const time_t *clock, char *buf);

struct tm *localtime_r(const time_t *clock, struct tm *result);

struct tm *gmtime_r(const time_t *clock, struct tm *result);

char *asctime_r(const struct tm *tm, char *buf);

Systems/C C Library 711

Page 730: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

DESCRIPTION

The functions ctime(), gmtime() and localtime() all take as an argument a timevalue representing the time in seconds since the Epoch (00:00:00 UTC, January 1,1970; see time(3)).

The function localtime() converts the time value pointed at by clock, and returnsa pointer to a struct tm (described below) which contains the broken-out timeinformation for the value after adjusting for the current time zone (and any otherfactors such as Daylight Saving Time). Time zone adjustments are performed asspecified by the TZ environment variable (see tzset(3)). The function localtime()uses tzset(3) to initialize time conversion information if tzset(3) has not alreadybeen called by the process.

After filling in the tm structure, localtime() sets the tm isdst’th element of tznameto a pointer to a string that’s the time zone abbreviation to be used with local-time()’s return value.

The function gmtime() similarly converts the time value, but without any timezone adjustment, and returns a pointer to a tm structure (described below).

The ctime() function adjusts the time value for the current time zone in the samemanner as localtime(), and returns a pointer to a 26-character string of the form:

Thu Nov 24 18:22:48 1986\n\0

All the fields have constant width.

The ctime r() function provides the same functionality as ctime() except the callermust provide the output buffer buf to store the result, which must be at least 26characters long. The localtime r() and gmtime r() functions provide the samefunctionality as localtime() and gmtime() respectively, except the caller mustprovide the output buffer result.

The asctime() function converts the broken down time in the structure tm pointedat by *tm to the form shown in the example above.

The asctime r() function provides the same functionality as asctime() except thecaller must provide the output buffer buf to store the reuslt, which must be at least26 characters long.

The functions mktime() and timegm() convert the broken-down time, in thestructure pointer to by tm into a time value with the same encoding as that of thevalues returned by the time(3) function (that is, seconds from the Epoch, UTC). Themktime() function interprets the input structure according to the current timezonesetting (see tzset(3)). The timegm() function interprets the input structure asrepresenting Universal Coordinated Time (UTC).

712 Systems/C C Library

Page 731: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

The original values of the tm wday and tm yday components of the structure areIgnored, and the original values of the other components are not restricted to theirnormal ranges, and will be normalized if needed. For example, October 40 is changedinto November 9, a tm hour of -1 means 1 hour before midnight, tm mday of 0 meansthe day preceding the current month, and tm mon of -2 means 2 months beforeJanuary of tm year. (A positive or zero value for tm isdst causes mktime() topresume initially that summer time (for example, Daylight Saving Time) is or is notin effect for the specified time, respectively. A negative value for tm isdst causesthe mktime() function to attempt to divine whether summer time is in effect forthe specified time. The tm isdst and tm gmtoff members are forced to zero bytimegm().)

On successful completion, the values of the tm wday and tm yday components ofthe structure are set appropriately, and the other components are set to representthe specified calendar time, but with their values forced to their normal ranges; thefinal value of tm mday is not set until tm mon and tm year are determined. Themktime() function returns the specified calendar time; if the calendar time cannotbe represented, it returns -1;

The difftime() function returns the difference between two calendar times, (time1- time0), expressed in seconds.

External declarations as well as the tm structure definition are in the <time.h>include file. The tm structure includes at least the following fields:

int tm_sec; /* seconds (0 - 60) */int tm_min; /* minutes (0 - 59) */int tm_hour; /* hours (0 - 23) */int tm_mday; /* day of month (1 - 31) */int tm_mon; /* month of year (0 - 11) */int tm_year; /* year - 1900 */int tm_wday; /* day of week (Sunday = 0) */int tm_yday; /* day of year (0 - 365) */int tm_isdst; /* is summer time in effect? */char *tm_zone; /* abbreviation of timezone name */long tm_gmtoff; /* offset from UTC in seconds */

The field tm isdst is non-zero if summer time is in effect.

The field tm gmtoff is the offset (in seconds) of the time represented from UTC,with positive values indicating east of the Prime Meridian.

SEE ALSO

gettimeofday(2), getenv(3), time(3), tzset(3)

Systems/C C Library 713

Page 732: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

STANDARDS

The asctime(), ctime(), difftime(), gmtime(), localtime(), and mktime()functions conform to ISO/IEC 9899:1990 (“ISO C90”), and conform to ISO/IEC9945-1:1996 (“POSIX.1”) provided the selected local timezone does not contain aleap-second table.

The asctime r(), ctime r(), gmtime r(), and localtime r() functions are ex-pected to conform to ISO/IEC 9945-1:1996 (“POSIX.1”) (again provided the se-lected local timezone does not contain a leap-second table).

The timegm() function is not specified by any standard; its function cannot becompletely emulated using the standard functions described above.

ISSUES

Except for difftime() and mktime() and the r() variants of the other functions,these functions leave their result in an internal static object and return a pointer tothat object. Subsequent calls to these function will modify the same object.

The C standard provides no mechanism for a program to modify its current localtimezone setting, and the POSIX-standard method is not reentrant. (However,thread-safe implementations are provided in the POSIX threaded environment.)

The tm zone field of a returned tm structure points to a static array of characters,which will also be overwritten by any subsequent calls (as well as by subsequentcalls to tzset(3) and tzsetwall(3)).

Use of the external variable tzname is discouraged; the tm zone entry in the tmstructure is preferred.

714 Systems/C C Library

Page 733: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

STRFTIME(3)

NAME

strftime - format date and time

SYNOPSIS

#include <time.h>

size_tstrftime(char *buf, size_t maxsize, const char *format,const struct tm *timeptr)

DESCRIPTION

The strftime() function formats the information from timeptr into the buffer bufaccording to the string pointed to by format.

The format string consists of zero or more conversion specifications and ordinarycharacters. All ordinary characters are copied directly into the buffer. A conversionspecification consists of a percent sign ‘%’ and one other character.

No more than maxsize characters will be placed into the array. If the total numberof resulting characters, including the terminating null character, is not more thanmaxsize, strftime() returns the number of characters in the array, not counting theterminating null. Otherwise, zero is returned and the buffer content is indeterminate.

Each conversion specification is replaced by the characters as follows which are thencopied into the buffer.

%A is replaced by national representation of the full weekday name.

%a is replaced by national representation of the abbreviated weekday name, wherethe abbreviation is the first three characters.

%B is replaced by national representation of the full month name.

%b is replaced by national representation of the abbreviated month name, where theabbreviation is the first three characters.

%C is replaced by (year / 100) as decimal number; single digits are preceded by azero.

%c is replaced by national representation of time and date (the format is similarwith produced by asctime(3)).

Systems/C C Library 715

Page 734: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

%D is equivalent to “%m/%d/%y”.

%d is replaced by the day of the month as a decimal number (01-31).

%E* POSIX locale extensions. The sequences %Ec %EC %Ex %Ey %EY %Od %Oe %OH%OI %Om %OM %OS %Ou %OU %OV %Ow %OW %Oy are supposed to provide alternaterepresentations.

%e is replaced by the day of month as a decimal number (1-31); single digits arepreceded by a blank.

%G is replaced by a year as a decimal number with century. This year is the onethat contains the greater part of the week (Monday as the first day of the week).

%g is replaced by the same year as in “%G”, but as a decimal number without century(00-99).

%H is replaced by the hour (24-hour clock) as a decimal number (00-23).

%h the same as %b.

%I is replaced by the hour (12-hour clock) as a decimal number (01-12).

%j is replaced by the day of the year as a decimal number (001-366).

%k is replaced by the hour (24-hour clock) as a decimal number (0-23); single digitsare preceded by a blank.

%l is replaced by the hour (12-hour clock) as a decimal number (1-12); single digitsare preceded by a blank.

%M is replaced by the minute as a decimal number (00-59).

%m is replaced by the month as a decimal number (01-12).

%n is replaced by a newline.

%O* the same as %E*.

%p is replaced by national representation of either “ante meridiem” or “post meri-diem” as appropriate.

%R is equivalent to “%H:%M”.

%r is equivalent to “%I:%M:%S %p”.

%S is replaced by the second as a decimal number (00-60).

%s is replaced by the number of seconds since the Epoch, UTC (see mktime(3)).

%T is equivalent to “%H:%M:%S”.

716 Systems/C C Library

Page 735: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

%t is replaced by a tab.

%U is replaced by the week number of the year (Sunday as the first day of the week)as a decimal number (00-53).

%u is replaced by the weekday (Monday as the first day of the week) as a decimalnumber (1-7).

%V is replaced by the week number of the year (Monday as the first day of the week)as a decimal number (01-53). If the week containing January 1 has four or moredays in the new year, then it is week 1; otherwise it is the last week of the previousyear, and the next week is week 1.

%v is equivalent to “%e-%b-%Y”.

%W is replaced by the week number of the year (Monday as the first day of the week)as a decimal number (00-53).

%w is replaced by the weekday (Sunday as the first day of the week) as a decimalnumber (0-6).

%X is replaced by national representation of the time.

%x is replaced by national representation of the date.

%Y is replaced by the year with century as a decimal number.

%y is replaced by the year without century as a decimal number (00-99).

%Z is replaced by the time zone name.

%+ is replaced by national representation of the date and time (the format is similarwith produced by date(1)).

%% is replaced by ‘%’.

SEE ALSO

ctime(3), printf(3), strptime(3)

STANDARDS

The strftime() function conforms to ISO/IEC 9899:1990 (“ISO C90”) with a lot ofextensions including ‘%C’, ‘%D’, ‘%E*’, ‘%e’, ‘%G’, ‘%g’, ‘%h’, ‘%k’, ‘%l’, ‘%n’, ‘%O*’, ‘%R’,‘%r’, ‘%s’, ‘%T’, ‘%t’, ‘%u’, ‘%V’, ‘%+’.

The peculiar week number and year in the replacements of ‘%G’, ‘%g’ and ‘%V’ aredefined in ISO 8601: 1988.

Systems/C C Library 717

Page 736: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

STRPTIME(3)

NAME

strptime - parse date and time string

SYNOPSIS

#include <time.h>

const char *strptime(const char *buf, const char *format,struct tm *timeptr)

DESCRIPTION

The strptime() function parses the string in the buffer buf according to the stringpointed to by format, and fills in the elements of the structure pointed to by timeptr.Thus, it can be considered the reverse operation of strftime(3).

The format string consists of zero or more conversion specifications and ordinarycharacters. All ordinary characters are matched exactly with the buffer, where whitespace in the format string will match any amount of white space in the buffer. Allconversion specifications are identical to those described in strftime(3).

RETURN VALUES

Upon successful completion, strptime() returns the pointer to the first characterin buf that has not been required to satisfy the specified conversions in format. Itreturns NULL if one of the conversions failed.

SEE ALSO

scanf(3), strftime(3)

718 Systems/C C Library

Page 737: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

TIME2POSIX(3)

NAME

time2posix, posix2time - convert seconds since the Epoch

SYNOPSIS

#include <time.h>

time_ttime2posix(const time_t *t)

time_tposix2time(const time_t *t)

DESCRIPTION

IEEE Std1003.1-1988 (“POSIX”) legislates that a time t value of 536457599 shallcorrespond to “Wed Dec 31 23:59:59 GMT 1986.” This effectively implies thatPOSIX time t’s cannot include leap seconds and, therefore, that the system timemust be adjusted as each leap occurs.

If the time package is configured with leap-second support enabled, however, no suchadjustment is needed and time t values continue to increase over leap events (as atrue ‘seconds since...’ value). This means that these values will differ from thoserequired by POSIX by the net number of leap seconds inserted since the Epoch.

Typically this is not a problem as the type time t is intended to be (mostly)opaque - time t values should only be obtained-from and passed-to functions suchas time(2), localtime(3), mktime(3) and difftime(3). However, IEEE Std1003.1-1988 (“POSIX”) gives an arithmetic expression for directly computing a time tvalue from a given date/time, and the same relationship is assumed by some (usu-ally older) applications. Any programs creating/dissecting time t’s using such arelationship will typically not handle intervals over leap seconds correctly.

The time2posix() and posix2time() functions are provided to address this time tmismatch by converting between local time t values and their POSIX equivalents.This is done by accounting for the number of time-base changes that would havetaken place on a POSIX system as leap seconds were inserted or deleted. Theseconverted values can then be used in lieu of correcting the older applications, orwhen communicating with POSIX-compliant systems.

The time2posix() function is single-valued. That is, every local time t correspondsto a single POSIX time t. The posix2time() function is less well-behaved: for a

Systems/C C Library 719

Page 738: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

positive leap second hit the result is not unique, and for a negative leap second hitthe corresponding POSIX time t doesn’t exist, so an adjacent value is returned.Both of these are good indicators of the inferiority of the POSIX representation.

The following table summarizes the relationship between time t and its conversionto, and back from, the POSIX representation over the leap second inserted at theend of June, 1993.

DATE TIME T X=time2posix(T) posix2time(X)

93/06/30 23:59:59 A+0 B+0 A+0

93/06/30 23:59:60 A+1 B+1 A+1 or A+2

93/07/01 00:00:00 A+2 B+1 A+1 or A+2

93/07/01 00:00:01 A+3 B+2 A+3

A leap second deletion would look like...

DATE TIME T X=time2posix(T) posix2time(X)

??/06/30 23:59:58 A+0 B+0 A+0

??/07/01 00:00:00 A+1 B+2 A+1

??/07/01 00:00:01 A+2 B+3 A+2

[Note: posix2time(B+1) → A+0 or A+1]

If leap-second support is not enabled, local time t’s and POSIX time t’s are equiv-alent, and both time2posix() and posix2time() degenerate to the identity func-tion.

SEE ALSO

difftime(3), localtime(3), mktime(3), time(3)

720 Systems/C C Library

Page 739: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

TZSET(3)

NAME

tzset - initialize time conversion information

SYNOPSIS

#include <time.h>

voidtzset(void);

DESCRIPTION

The tzset() function initializes time conversion information used by the libraryroutine localtime(3). The environment variable TZ specifies how this is done.

If TZ does not appear in the environment, or TZ appears in the environment butits value is a null string, Coordinated Universal Time (UTC) is used (without leapsecond correction).

If TZ appears in the environment and its value begins with a colon (‘:’), the rest ofits value is used as a pathname of a tzfile(5)-format file from which to read the timeconversion information. If the first character of the pathname is a slash (‘/’) it isused as an absolute pathname; otherwise, it is used as a pathname relative to thesystem time conversion information directory.

If its value does not begin with a colon, it is first used as the pathname of a file (asdescribed above) from which to read the time conversion information. If that filecannot be read, the value is then interpreted as a direct specification (the format isdescribed below) of the time conversion information.

If the TZ environment variable does not specify a tzfile(5)-format file and cannot beinterpreted as a direct specification, UTC is used.

SPECIFICATION FORMAT

When TZ is used directly as a specification of the time conversion information, itmust have the following syntax (spaces inserted for clarity):

std offset [dst [offset] [, rule]]

Systems/C C Library 721

Page 740: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

Where:

std and dst Three or more bytes that are the designation for the standard (std) orsummer (dst) time zone. Only std is required; if dst is missing, thensummer time does not apply in this locale. Upper and lowercase lettersare explicitly allowed. Any characters except a leading colon (‘:’), digits,comma (‘,’), minus (‘-’), plus (‘+’), and NUL are allowed.

offset Indicates the value one must add to the local time to arrive at Coordi-nated Universal Time. The offset has the form:

hh[:mm[:ss]]

The minutes (mm) and seconds (ss) are optional. The hour (hh) is re-quired and may be a single digit. The offset following std is required.If no offset follows dst, summer time is assumed to be one hour aheadof standard time. One or more digits may be used; the value is alwaysinterpreted as a decimal number. The hour must be between zero and24, and the minutes (and seconds) – if present – between zero and 59.If preceded by a (’-’) the time zone shall be east of the Prime Merid-ian; otherwise it shall be west (which may be indicated by an optionalpreceding (’+’)).

rule Indicates when to change to and back from summer time. The rule hasthe form:

date/time,date/time

where the first date describes when the change from standard to summertime occurs and the second date describes when the change back hap-pens. Each time field describes when, in current local time, the changeto the other time is made.

The format of date is one of the following:

J n The Julian day n (1 ≤ n ≤ 365). Leap days are not counted;that is, in all years – including leap years – February 28 isday 59 and March 1 is day 60. It is impossible to explicitlyrefer to the occasional February 29.

n The zero-based Julian day (0 ≤ n ≤ 365). Leap days arecounted, and it is possible to refer to February 29.

M m.n.d The dth day (0 ≤ d ≤ 6) of week n of month m of the year(1 ≤ n ≤ 5), (1 ≤ m ≤ 12), where week 5 means “the lastd day in month m” which may occur in either the fourth orthe fifth week). Week 1 is the first week in which the d’thday occurs. Day zero is Sunday.The time has the same format as offset except that no leadingsign (’-’) or (’+’) is allowed. The default, if time is not given,is 02:00:00.

722 Systems/C C Library

Page 741: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

For compatibility with System V Release 3.1, a semicolon (‘;’) may be used toseparate the rule from the rest of the specification.

SEE ALSO

gettimeofday(2), ctime(3), getenv(3), time(3), tzfile(5)

Systems/C C Library 723

Page 742: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

TZFILE(5)

NAME

tzfile - timezone information

DESCRIPTION

The time zone information files used by tzset(3) begin with the magic characters“TZif” to identify them as time zone information files, followed by sixteen bytesreserved for future use, followed by four four byte values written in a “standard”byte order (the high-order byte of the value is written first). These values are, inorder:

tzh ttisgmtcnt The number of UTC/local indicators stored in the file.

tzh ttisstdcnt The number of standard/wall indicators stored in thefile.

tzh leapcnt The number of leap seconds for which data is stored inthe file.

tzh timecnt The number of “transition times” for which data isstored in the file.

tzh typecnt The number of “local time types” for which data isstored in the file (must not be zero).

tzh charcnt The number of characters of “time zone abbreviationstrings” stored in the file.

The above header is followed by tzh timecnt four-byte values of type long, sortedin ascending order. These values are written in “standard” byte order. Each isused as a transition time (as returned by time(3)) at which the rules for computinglocal time change. Next come tzh timecnt one-byte values of type unsigned char;each one tells which of the different types of “local time” types described in the fileis associated with the same-indexed transition time. These values serve as indicesinto an array of ttinfo structures that appears next in the file; these structures aredefined as follows:

struct ttinfo {long tt_gmtoff;int tt_isdst;unsigned int tt_abbrind;

};

724 Systems/C C Library

Page 743: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

Each structure is written as a four-byte value for tt gmtoff of type long, in astandard byte order, followed by a one-byte value for tt isdst and a one-byte valuefor tt abbrind. In each structure, tt gmtoff gives the number of seconds to beadded to UTC, tt isdst tells whether tm isdst should be set by localtime(3) andtt abbrind serves as an index into the array of time zone abbreviation charactersthat follow the ttinfo structure(s) in the file.

Then there are tzh leapcnt pairs of four-byte values, written in standard byteorder; the first value of each pair gives the time (as returned by time(3)) at which aleap second occurs; the second gives the total number of leap seconds to be appliedafter the given time. The pairs of values are sorted in ascending order by time.

Then there are tzh ttisstdcnt standard/wall indicators, each stored as a one-bytevalue; they tell whether the transition times associated with local time types werespecified as standard time or wall clock time, and are used when a time zone file isused in handling POSIX-style time zone environment variables.

Finally there are tzh ttisgmtcnt UTC/local indicators, each stored as a one-bytevalue; they tell whether the transition times associated with local time types werespecified as UTC or local time, and are used when a time zone file is used in handlingPOSIX-style time zone environment variables.

localtime(3) uses the first standard-time ttinfo structure in the file (or simplythe first ttinfo structure in the absence of a standard-time structure) if eithertzh timecnt is zero or the time argument is less than the first transition timerecorded in the file.

SEE ALSO

ctime(3), time2posix(3)

Systems/C C Library 725

Page 744: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

String Library

The ANSI C standard defines functions for concatenating, searching, copying andgeneral manipulation of strings. These are found in the String Library.

The Systems/C library also includes the string manipulation functions typicallyfound on BSD UNIX variants.

726 Systems/C C Library

Page 745: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

BCMP(3)

NAME

bcmp - compare byte string

SYNOPSIS

#include <string.h>

intbcmp(const void *b1, const void *b2, size_t len)

DESCRIPTION

The bcmp() function compares byte string b1 against byte string b2, returning zeroif they are identical, non-zero otherwise. Both strings are assumed to be len byteslong. Zero-length strings are always identical.

The strings may overlap.

SEE ALSO

bcmp(3), memcmp(3), strcasecmp(3), strcmp(3), strcoll(3), strxfrm(3)

Systems/C C Library 727

Page 746: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

BCOPY(3)

NAME

bcopy - copy byte string

SYNOPSIS

#include <string.h>

voidbcopy(const void *src, void *dst, size_t len)

DESCRIPTION

The bcopy() function copies len bytes from string src to string dst. The two stringsmay overlap. If len is zero, no bytes are copied.

SEE ALSO

memccpy(3), memcpy(3), memmove(3), strcpy(3), strncpy(3)

728 Systems/C C Library

Page 747: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

BSTRING(3)

NAME

bcmp, bcopy, bzero, memccpy, memchr, memcmp, memcpy, memmove, memset -byte string operations

SYNOPSIS

#include <string.h>

intbcmp(const void *b1, const void *b2, size_t len)

voidbcopy(const void *src, void *dst, size_t len)

voidbzero(void *b, size_t len)

void *memchr(const void *b, int c, size_t len)

intmemcmp(const void *b1, const void *b2, size_t len)

void *memccpy(void *dst, const void *src, int c, size_t len)

void *memcpy(void *dst, const void *src, size_t len)

void *memmove(void *dst, const void *src, size_t len)

void *memset(void *b, int c, size_t len)

DESCRIPTION

These functions operate on variable length strings of bytes. They do not check forterminating null bytes as the routines listed in string(3) do.

See the specific manual pages for more information.

Systems/C C Library 729

Page 748: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

SEE ALSO

bcmp(3), bcopy(3), bzero(3), memccpy(3), memchr(3), memcmp(3), memcpy(3),memmove(3), memset(3)

STANDARDS

The functions memchr(), memcmp(), memcpy(), memmove(), and memset()conform to ISO/IEC 9899:1990 (“ISO C90”).

730 Systems/C C Library

Page 749: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

BZERO(3)

NAME

bzero - write zeroes to a byte string

SYNOPSIS

#include <string.h>

voidbzero(void *b, size_t len)

DESCRIPTION

The bzero() function writes len zero bytes to the string b. If len is zero, bzero()does nothing.

SEE ALSO

memset(3), swab(3)

Systems/C C Library 731

Page 750: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

FFS(3)

NAME

ffs,ffsl - find first bit set in a bit string

SYNOPSIS

#include <string.h>

intffs(int value)

intffsl(long value)

intffsll(long long value)

intfls(int value)

intflsl(long value)

intflsll(long long value)

DESCRIPTION

The ffs(), ffsl() and ffsll() functions find the first (least significant bit) bit set invalue and return the index of that bit.

The fls(), flsl() and flsll() functions find the last (most significant bit) bit set invalue and return the index of that bit.

Bits are numbered starting from 1, starting at the rightmost bit. A return value of0 means that the argument was zero.

SEE ALSO

bitstring(3)

732 Systems/C C Library

Page 751: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

INDEX(3)

NAME

index - locate character in string

SYNOPSIS

#include <string.h>

char *index(const char *s, int c)

DESCRIPTION

The index() function locates the first character matching c (converted to a char)in the null-terminated string s.

RETURN VALUES

A pointer to the character is returned if it is found; otherwise NULL is returned. Ifc is ’\0’, index() locates the terminating ’\0’.

SEE ALSO

memchr(3), rindex(3), strchr(3), strcspn(3), strpbrk(3), strrchr(3), strsep(3), str-spn(3), strstr(3), strtok(3)

Systems/C C Library 733

Page 752: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

MEMCCPY(3)

NAME

memccpy - copy string until character found

SYNOPSIS

#include <string.h>

void *memccpy(void *dst, const void *src, int c, size_t len)

DESCRIPTION

The memccpy() function copies bytes from string src to string dst. If the characterc (as converted to an unsigned char) occurs in the string src, the copy stops and apointer to the byte after the copy of c in the string dst is returned. Otherwise, lenbytes are copied, and a NULL pointer is returned.

SEE ALSO

bcopy(3), memcpy(3), memmove(3), strcpy(3)

734 Systems/C C Library

Page 753: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

MEMCHR(3)

NAME

memchr - locate byte in byte string

SYNOPSIS

#include <string.h>

void *memchr(const void *b, int c, size_t len)

DESCRIPTION

The memchr() function locates the first occurrence of c (converted to an unsignedchar) in string b.

RETURN VALUES

The memchr() function returns a pointer to the byte located, or NULL if no suchbyte exists within len bytes.

SEE ALSO

index(3), rindex(3), strchr(3), strcspn(3), strpbrk(3), strrchr(3), strsep(3), str-spn(3), strstr(3), strtok(3)

STANDARDS

The memchr() function conforms to ISO/IEC 9899:1990 (“ISO C90”).

Systems/C C Library 735

Page 754: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

MEMCMP(3)

NAME

memcmp - compare byte string

SYNOPSIS

#include <string.h>

intmemcmp(const void *b1, const void *b2, size_t len)

DESCRIPTION

The memcmp() function compares byte string b1 against byte string b2. Bothstrings are assumed to be len bytes long.

RETURN VALUES

The memcmp() function returns zero if the two strings are identical, otherwisereturns the difference between the first two differing bytes treated as unsignedchar values, so that ’\200’ is greater than ’\0’, for example. Zero-length stringsare always identical.

SEE ALSO

bcmp(3), strcasecmp(3), strcmp(3), strcoll(3), strxfrm(3)

STANDARDS

The memcmp() function conforms to ISO/IEC 9899:1990 (“ISO C90”).

736 Systems/C C Library

Page 755: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

MEMCPY(3)

NAME

memcpy - copy byte string

SYNOPSIS

#include <string.h>

void *memcpy(void *dst, const void *src, size_t len)

DESCRIPTION

The memcpy() function copies len bytes from string src to string dst.

RETURN VALUES

The memcpy() function returns the original value of dst.

SEE ALSO

bcopy(3), memccpy(3), memmove(3), strcpy(3)

STANDARDS

The memcpy() function conforms to ISO/IEC 9899:1990 (“ISO C90”).

ISSUES

In this implementation the memcpy() function is implemented using bcopy(3),and therefore the strings may overlap. On other systems, or when using the built-in memcpy() function, copying overlapping strings may produce unpredictableresutls.

The built-in memcpy() is expanded, the implementation uses the MVC instructionwhich does produce the same results as the library function when the strings overlap.

Systems/C C Library 737

Page 756: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

MEMMEM(3)

NAME

memmem - locate a byte substring in a byte string

SYNOPSIS

#include <string.h>

void *memmem(const char *big, size_t big_len, const char *little,

size_t little_len);

DESCRIPTION

The memmem() function locates the first occurrence of the byte string little in thebyte string big.

RETURN VALUES

If big len is smaller than little len, if little len is 0, if big len is 0 or if little occursnowhere in big, NULL is returned; otherwise a pointer to the first character of thefirst occurrence of little is returned.

SEE ALSO

memchar(3), strchr(3), strstr(3)

738 Systems/C C Library

Page 757: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

MEMMOVE(3)

NAME

memmove - copy byte string

SYNOPSIS

#include <string.h>

void *memmove(void *dst, const void *src, size_t len)

DESCRIPTION

The memmove() function copies len bytes from string src to string dst. The twostrings may overlap; the copy is always done in a non-destructive manner.

RETURN VALUES

The memmove() function returns the original value of dst.

SEE ALSO

bcopy(3), memccpy(3), memcpy(3), strcpy(3)

STANDARDS

The memmove() function conforms to ISO/IEC 9899:1990 (“ISO C90”).

Systems/C C Library 739

Page 758: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

MEMSET(3)

NAME

memset - write a byte to byte string

SYNOPSIS

#include <string.h>

void *memset(void *b, int c, size_t len)

DESCRIPTION

The memset() function writes len bytes of value c (converted to an unsigned char)to the string b.

RETURNS

The memset() function returns its first argument.

SEE ALSO

bzero(3), swab(3)

STANDARDS

The memset() function conforms to ISO/IEC 9899:1990 (“ISO C90”).

740 Systems/C C Library

Page 759: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

RINDEX(3)

NAME

rindex - locate character in string

SYNOPSIS

#include <string.h>

char *rindex(const char *s, int c)

DESCRIPTION

The rindex() function locates the last character matching c (converted to a char)in the null-terminated string s.

RETURN VALUES

A pointer to the character is returned if it is found; otherwise NULL is returned. Ifc is ’\0’, rindex() locates the terminating ’\0’.

SEE ALSO

index(3), memchr(3), strchr(3), strcspn(3), strpbrk(3), strrchr(3), strep(3), str-spn(3), strstr(3), strtok(3)

Systems/C C Library 741

Page 760: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

STRCASECMP(3)

NAME

strcasecmp, strncasecmp - compare strings, ignoring case

SYNOPSIS

#include <strings.h>

intstrcasecmp(const char *s1, const char *s2)

intstrncasecmp(const char *s1, const char *s2, size_t len)

DESCRIPTION

The strcasecmp() and strncasecmp() functions compare the null-terminatedstrings s1 and s2 and return an integer greater than, equal to, or less than 0, accord-ing as s1 is lexicographically greater than, equal to, or less than s2 after translationof each corresponding character to lower-case. The strings themselves are not mod-ified. The comparison is done using unsigned characters, so that ’\200’ is greaterthan ’\0’.

The strncasecmp() compares at most len characters.

SEE ALSO

bcmp(3), memcmp(3), strcmp(3), strcoll(3), strxfrm(3)

NOTES

The strcasecmp() and strncasecmp() function prototypes existed previously in<string.h> before they were moved to <strings.h> for IEEE Std 1003.1-2001(“POSIX.1”) compliance.

742 Systems/C C Library

Page 761: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

STRCAT(3)

NAME

strcat - concatenate strings

SYNOPSIS

#include <string.h>

char *strcat(char *s, const char *append)

char *strncat(char *s, const char *append, size_t count)

DESCRIPTION

The strcat() and strncat() functions append a copy of the null-terminated stringappend to the end of the null-terminated string s, then add a terminating ’\0’. Thestring s must have sufficient space to hold the result.

The strncat() function appends not more than count characters from append, andthen adds a terminating ’\0’.

RETURN VALUES

The strcat() and strncat() functions return the pointer s.

SEE ALSO

bcopy(3), memccpy(3), memcpy(3), memmove(3), strcpy(3)

STANDARDS

The strcat() and strncat() functions conform to ISO/IEC 9899:1990 (“ISO C90”).

Systems/C C Library 743

Page 762: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

STRCHR(3)

NAME

strchr - locate character in string

SYNOPSIS

#include <string.h>

char *strchr(const char *s, int c)

char *strchrnul(const char *s, int c)

DESCRIPTION

The strchr() function locates the first occurrence of c in the string pointed to bys. The terminating NUL character is considered part of the string. If c is ’\0’,strchr() locates the terminating ’\0’.

The strchrnul() function is identical to strchr() except that if c is not found in sa pointer to the terminating ’\0’ is returned.

RETURN VALUES

The function strchr() returns a pointer to the located character, or NULL if thecharacter does not appear in the string.

strchrnul() returns a pointer to the terminating ’\0’ if the character does notappear in the string.

SEE ALSO

index(3), memchr(3), index(3), strcspn(3), strpbrk(3), strrchr(3), strep(3), str-spn(3), strstr(3), strtok(3)

STANDARDS

The strchr() function conforms to ISO/IEC 9899:1990 (“ISO C90”).

The strchrnul() function is an extension.

744 Systems/C C Library

Page 763: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

STRCMP(3)

NAME

strcmp, strncmp, - compare strings

SYNOPSIS

#include <string.h>

intstrcmp(const char *s1, const char *s2)

intstrncmp(const char *s1, const char *s2, size_t len)

DESCRIPTION

The strcmp() and strncmp() functions lexicographically compare the null- termi-nated strings s1 and s2.

The strncmp() function compares not more then len characters.

RETURN VALUES

The strcmp() and strncmp() return an integer greater than, equal to, or less than0, accordingly as the string s1 is greater than, equal to, or less than the string s2.The comparison is done using unsigned characters, so that ’\200’ is greater than’\0’.

SEE ALSO

bcmp(3), memcmp(3), strcasecmp(3), strcoll(3), strxfrm(3)

STANDARDS

The strcmp() and strncmp() functions conform to ISO/IEC 9899:1990 (“ISOC90”).

Systems/C C Library 745

Page 764: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

STRCOLL(3)

NAME

strcoll - compare strings according to current collation

SYNOPSIS

#include <string.h>

intstrcoll(const char *s1, const char *s2)

DESCRIPTION

The strcoll() function lexicographically compares the null-terminated strings s1 ands2 according to the current locale collation if any. If no locale is current, stroll()calls strcmp().

The stroll() function returns an integer greater than, equal to, or less than 0,accordingly as s1 is greater than, equal to, or less than s2.

SEE ALSO

setlocale(3), strcmp(3), strxfrm(3)

STANDARDS

The strcoll() function conforms to ISO/IEC 9899:1990 (“ISO C90”).

746 Systems/C C Library

Page 765: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

STRCPY(3)

NAME

strcpy - copy strings

SYNOPSIS

#include <string.h>

char *strcpy(char *dst, const char *src)

char *strncpy(char *dst, const char *src, size_t len)

DESCRIPTION

The strcpy() and strncpy() functions copy the string src to dst (including theterminating ’\0’ character).

The strncpy() copies not more than len characters into dst, appending ’\0’ char-acters if src is less than len characters long, and not terminating dst if src is morethan len characters long.

RETURN VALUES

The strcpy() and strncpy() functions return dst.

EXAMPLES

The following sets chararray to "abc\0\0\0":

(void)strncpy(chararray, "abc", 6);

The following sets chararray to "abcdef":

(void)strncpy(chararray, "abcdefgh", 6);

Systems/C C Library 747

Page 766: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

SEE ALSO

bcopy(3), memccpy(3), memcpy(3), memmove(3)

STANDARDS

The strcpy() and strncpy() functions conform to ISO/IEC 9899:1990 (“ISO C90”).

748 Systems/C C Library

Page 767: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

STRCSPN(3)

NAME

strcspn - span the complement of a string

SYNOPSIS

#include <string.h>

size_tstrcspn(const char *s, const char *charset)

DESCRIPTION

The strcspn() function spans the initial part of the null-terminated string s as longas the characters from s do not occur in string charset (it spans the complement ofcharset).

RETURN VALUES

The strcspn() function returns the number of characters spanned.

SEE ALSO

index(3), memchr(3), rindex(3), strchr(3), strpbrk(3), strrchr(3), strep(3), strspn(3),strstr(3), strtok(3)

STANDARDS

The strcspn() function conforms to ISO/IEC 9899:1990 (“ISO C90”).

Systems/C C Library 749

Page 768: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

STRDUP(3)

NAME

strdup - save a copy of a string

SYNOPSIS

#include <string.h>

char *strdup(const char *str)

DESCRIPTION

The strdup() function allocates sufficient memory for a copy of the string str, doesthe copy, and returns a pointer to it. The pointer may subsequently be used as anargument to the function free(3).

If insufficient memory is available, NULL is returned.

SEE ALSO

free(3), malloc(3)

750 Systems/C C Library

Page 769: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

STRERROR(3)

NAME

perror, strerror, sys errlist, sys nerr - system error messages

SYNOPSIS

#include <stdio.h>

voidperror(const char *string)

extern const char * const sys_errlist[];extern const int sys_nerr;

#include <string.h>

char *strerror(int errnum)

DESCRIPTION

The strerror() and perror() functions look up the error message string corre-sponding to an error number.

The strerror() function accepts an error number argument errnum and returns apointer to the corresponding message string.

The perror() function finds the error message corresponding to the current value ofthe global variable errno (intro(2)) and writes it, followed by a newline character,to the standard error file descriptor. If the argument string is non-NULL and doesnot point to the null character, this string is prepended to the message string andseparated from it by a colon and space (“: ”); otherwise, only the error messagestring is printed.

If errnum is not a recognized error number, the error message string will contain“Unknown error: ” followed by the error number in decimal.

The message strings can be accessed directly using the external array sys errlist.The external value sys nerr contains a count of the messages in sys errlist. Theuse of these variables is deprecated; strerror() should be used instead.

Systems/C C Library 751

Page 770: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

ISSUES

For unknown error numbers, the strerror() function will return its result in a staticbuffer which may be overwritten by subsequent calls.

Programs that use the deprecated sys errlist variable often fail to compile becausethey declare it inconsistently.

752 Systems/C C Library

Page 771: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

STRING(3)

NAME

strcat, strncat, strchr, strrchr, strcmp, strncmp, strcasecmp, strncasecmp, strcpy,strncpy, strerror, strlen, strpbrk, strsep, strspn, strcspn, strstr, strtok, index, rindex- string specific functions

SYNOPSIS

#include <string.h>

char *strcat(char *s, const char * append)

char *strncat(char *s, const char *append, size_t count)

char *strchr(const char *s, int c)

char *strrchr(const char *s, int c)

intstrcmp(const char *s1, const char *s2)

intstrncmp(const char *s1, const char *s2, size_t count)

intstrcasecmp(const char *s1, const char *s2)

intstrncasecmp(const char *s1, const char *s2,size_t count)

char *strcpy(char *dst, const char *src)

char *strncpy(char *dst, const char *src, size_t count)

char *strerror(int errno)

Systems/C C Library 753

Page 772: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

size_tstrlen(const char *s)

char *strpbrk(const char *s, const char *charset)

char *strsep(char **stringp, const char *delim)

size_tstrspn(const char *s, const char *charset)

size_tstrcspn(const char *s, const char *charset)

char *strstr(const char *big, const char *little)

char *strtok(char *s, const char *delim)

char *index(const char *s, int c)

char *rindex(const char *s, int c)

DESCRIPTION

The string functions manipulate strings terminated by a null byte.

See the specific manual pages for more information. For manipulating variablelength generic objects as byte strings (without the null byte check), see bstring(3).

Except as noted in their specific manual pages, the string functions do not test thedestination for size limitations.

SEE ALSO

bstring(3), index(3), rindex(3), strcasecmp(3), strcat(3), strchr(3), strcmp(3), str-cpy(3), strcspn(3), strerror(3), strlen(3), strpbrk(3), strrchr(3), strsep(3), strspn(3),strstr(3), strtok(3)

754 Systems/C C Library

Page 773: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

STANDARDS

The strcat(), strncat(), strchr(), strrchr(), strcmp(), strncmp(), strcpy(),strncpy(), strerror(), strlen(), strpbrk(), strsep(), strspn(), strcspn(),strstr(), and strtok() functions conform to ISO/IEC 9899:1990 (“ISO C90”).

Systems/C C Library 755

Page 774: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

STRLCPY(3)

NAME

strlcpy, strlcat - size-bounded string copying and concatenation

SYNOPSIS

#include <string.h>

size_tstrlcpy(char *dst, const char *src, size_t size);

size_tstrlcat(char *dst, const char *src, size_t size);

DESCRIPTION

The strlcpy() and strlcat() functions copy and concatenate strings respectively.They are designed to be safer, more consistent, and less error prone replacementsfor strncpy(3) and strncat(3). Unlike those functions, strlcpy() and strlcat() takethe full size of the buffer (not just the length) and guarantee to NUL-terminate theresult (as long as size is larger than 0 or, in the case of strlcat(), as long as thereis at least one byte free in dst). Note that a byte should be included for the NULin size. Also note that strlcpy() and strlcat() only operate on true “C” strings.This means that for strlcpy() src must be NUL-terminated and for strlcat() bothsrc and dst must be NUL-terminated.

The strlcpy() function copies up to size - 1 characters from the NUL-terminatedstring src to dst, NUL-terminating the result.

The strlcat() function appends the NUL-terminated string src to the end of dst. Itwill append at most size - strlen(dst) - 1 bytes, NUL-terminating the result.

RETURN VALUES

The strlcpy() and strlcat() functions return the total length of the string they triedto create. For strlcpy() that means the length of src. For strlcat() that means theinitial length of dst plus the length of src. While this may seem somewhat confusingit was done to make truncation detection simple.

Note however, that if strlcat() traverses size characters without finding a NUL, thelength of the string is considered to be size and the destination string will not be

756 Systems/C C Library

Page 775: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

NUL-terminated (since there was no space for the NUL). This keeps strlcat() fromrunning off the end of a string. In practice this should not happen (as it means thateither size is incorrect or that dst is not a proper “C” string). The check exists toprevent potential security problems in incorrect code.

EXAMPLES

The following code fragmen illustrates the simple case:

char *s, *p, buf[BUFSIZ];

...

(void)strlcpy(buf, s, sizeof(buf));(void)strlcat(buf, p, sizeof(buf));

To detect truncation, perhaps while building a pathlen, something like the followingmight be used:

char *dir, *file, pname[MAXPATHLEN];

...

if (strlcpy(pname, dir, sizeof(pname)) >= sizeof(pname))goto toolong;

if (strlcat(pname, file, sizeof(pname)) >= sizeof(pname))goto toolong;

Since we know how many characters we copied the first time, we can speed thingsup a bit by using a copy instead of an append:

char *dir, *file, pname[MAXPATHLEN];size_t n;

...

n = strlcpy(pname, dir, sizeof(pname));if (n >= sizeof(pname))

goto toolong;if (strlcpy(pname + n, file, sizeof(pname) - n) >= sizeof(pname) - n)

goto toolong;

However, one may question the validity of such optimizations, as they defeat thewhole purpose of strlcpy() and strlcat().

Systems/C C Library 757

Page 776: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

SEE ALSO

snprintf(3), strncat(3), strncpy(3)

758 Systems/C C Library

Page 777: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

STRLEN(3)

NAME

strlen - find length of string

SYNOPSIS

#include <string.h>

size_tstrlen(const char *s)

DESCRIPTION

The strlen() function computes the length of the string s.

RETURN VALUES

The strlen() function returns the number of characters that precede the terminatingNUL character.

SEE ALSO

string(3)

STANDARDS

The strlen() function conforms to ISO/IEC 9899:1990 (“ISO C90”).

Systems/C C Library 759

Page 778: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

STRPBRK(3)

NAME

strpbrk - locate multiple characters in string

SYNOPSIS

#include <string.h>

char *strpbrk(const char *s, const char *charset)

DESCRIPTION

The strpbrk() function locates in the null-terminated string s the first occurrenceof any character in the string charset and returns a pointer to this character. If nocharacters from charset occur anywhere in s then strpbrk() returns NULL.

SEE ALSO

index(3), memchr(3), rindex(3), strchr(3), strcspn(3), strrchr(3), strep(3), strspn(3),strstr(3), strtok(3)

STANDARDS

The strpbrk() function conforms to ISO/IEC 9899:1990 (“ISO C90”).

760 Systems/C C Library

Page 779: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

STRRCHR(3)

NAME

strrchr - locate character in string

SYNOPSIS

#include <string.h>

char *strrchr(const char *s, int c)

DESCRIPTION

The strrchr() function locates the last occurrence of c (converted to a char) in thestring s. If c is ’\0’, strrchr() locates the terminating ’\0’.

RETURN VALUES

The strrchr() function returns a pointer to the character, or a null pointer if c doesnot occur anywhere in s.

SEE ALSO

index(3), memchr(3), rindex(3), strchr(3), strcspn(3), strpbrk(3), strep(3), str-spn(3), strstr(3), strtok(3)

STANDARDS

The strrchr() function conforms to ISO/IEC 9899:1990 (“ISO C90”).

Systems/C C Library 761

Page 780: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

STRSEP(3)

NAME

strsep - separate strings

SYNOPSIS

#include <string.h>

char *strsep(char **stringp, const char *delim)

DESCRIPTION

The strsep() function locates, in the string referenced by *stringp, the first oc-currence of any character in the string delim (or the terminating ’\0’ character)and replaces it with a ’\0’. The location of the next character after the delimitercharacter (or NULL, if the end of the string was reached) is stored in *stringp. Theoriginal value of *stringp is returned.

An “empty” field, i.e. one caused by two adjacent delimiter characters, can bedetected by comparing the location referenced by the pointer returned in *stringpto ’\0’.

If *stringp is initially NULL, strsep() returns NULL.

EXAMPLES

The following uses strsep() to parse a string, containing tokens delimited by whitespace, into an argument vector:

char **ap, *argv[10], *inputstring;for (ap = argv;

(*ap = strsep(&inputstring, " \t")) != NULL;)if (**ap != ’\0’)

if (++ap >= &argv[10])break;

762 Systems/C C Library

Page 781: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

STRSPN(3)

NAME

strspn - span a string

SYNOPSIS

#include <string.h>

size_tstrspn(const char *s, const char *charset)

DESCRIPTION

The strspn() function spans the initial part of the null-terminated string s as longas the characters from s occur in string charset.

RETURN VALUES

The strspn() function returns the number of characters spanned.

SEE ALSO

index(3), memchr(3), rindex(3), strchr(3), strcspn(3), strpbrk(3), strrchr(3),strsep(3), strstr(3), strtok(3)

STANDARDS

The strspn() function conforms to ISO/IEC 9899:1990 (“ISO C90”).

Systems/C C Library 763

Page 782: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

STRSTR(3)

NAME

strstr, strcasestr, strnstr - locate a substring in a string

SYNOPSIS

#include <string.h>

char *strstr(const char *big, const char *little)

char *strcasestr(const char *big, const char *little);

char *strnstr(const char *big, const char *little, size_t len);

DESCRIPTION

The strstr() function locates the first occurrence of the null-terminated string littlein the null-terminated string big.

The strcasestr() function is similar to strstr(), but ignores the case of both strings.

The strnstr() function locates the first occurrence of the null-terminated stringlittle in the string big, where not more than len characters are searched. Charactersthat appear after a ‘0’ character are not searched. Since the strnstr() function is a Systems/C specificAPI, it should only be used when portability is not a concern.

RETURN VALUES

If little is the empty string, strstr() returns big. If little occurs nowhere in big, NULLis returned. Otherwise a pointer to the first character of the first occurrence of littleis returned.

SEE ALSO

index(3), memchr(3), index(3), strchr(3), strcspn(3), strpbrk(3), strrchr(3),strsep(3), strspn(3), strtok(3)

764 Systems/C C Library

Page 783: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

STANDARDS

The strstr() function conforms to ISO/IEC 9899:1990 (“ISO C90”).

Systems/C C Library 765

Page 784: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

STRTOK(3)

NAME

strtok, strtok r - string tokens

SYNOPSIS

#include <string.h>

char *strtok(char *str, const char *sep)

char *strtok_r(char *str, const char *sep, char **last)

DESCRIPTION

This interface is obsoleted by strsep(3).

The strtok() function is used to isolate sequential tokens in a null-terminated string,str. These tokens are separated in the string by at least one of the characters insep. The first time that strtok() is called str should be specified. Subsequent calls,intended to obtain further tokens from the same string, should pass a null pointerinstead. The separator string, sep, must be supplied each time, and may changebetween calls.

The strtok r() function is a reentrant version of strtok(). The context pointerlast must be provided on each call. strtok r() may also be used to nest two parsingloops within one another, as long as separate context pointers are used.

The strtok() and strtok r() functions return a pointer to the beginning of eachsubsequent token in the string, after replacing the token itself with a NUL character.When no more tokens remain, a null pointer is returned.

EXAMPLE

The following uses strtok r() to parse two strings using separate contexts:

char test[80], blah[80];char *sep = "\/:;=-";char *word, *phrase, *brkt, *brkb;

766 Systems/C C Library

Page 785: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

strcpy(test,"This;is.a:test:of=the/string\tokenizer-function.");

for (word = strtok_r(test, sep, &brkt);word;word = strtok_r(NULL, sep, &brkt))

{strcpy(blah, "blah:blat:blab:blag");

for (phrase = strtok_r(blah, sep, &brkb);phrase;phrase = strtok_r(NULL, sep, &brkb))

{printf("So far we’re at %s:%s\n",

word, phrase);}

}

SEE ALSO

index(3), memchr(3), rindex(3), strchr(3), strcspn(3), strpbrk(3), strrchr(3),strsep(3), strspn(3), strstr(3)

STANDARDS

The strtok() function conforms to ISO/IEC 9899:1990 (“ISO C90”).

ISSUES

The System V strtok(), if handed a string containing only delimiter characters,will not alter the next starting point, so that a call to strtok() with a different (orempty) delimiter string may return a non-NULL value. Since this implementationalways alters the next starting point, such a sequence of calls would always returnNULL.

Systems/C C Library 767

Page 786: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

STRXFRM(3)

NAME

strxfrm - transform a string under locale

SYNOPSIS

#include <string.h>

size_tstrxfrm(char *dst, const char *src, size_t n)

DESCRIPTION

The strxfrm() function transforms a null-terminated string pointed to by src ac-cording to the current locale collation if any, then copies not more than n-1 charac-ters of the resulting string into dst, terminating it with a null character and then re-turns the resulting length. Comparing two strings using strcmp() after strxfrm()is equal to comparing two original strings with strcoll().

ISSUES

Sometimes the behavior of this function is unpredictable.

SEE ALSO

setlocale(3), strcmp(3), strcoll(3)

STANDARDS

The strxfrm() function conforms to ISO/IEC 9899:1990 (“ISO C90”).

768 Systems/C C Library

Page 787: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

SWAB(3)

NAME

swab - swap adjacent bytes

SYNOPSIS

#include <string.h>

voidswab(const void *src, void *dst, size_t len)

DESCRIPTION

The function swab() copies len bytes from the location referenced by src to thelocation referenced by dst, swapping adjacent bytes.

The argument len must be even number.

SEE ALSO

bzero(3), memset(3)

Systems/C C Library 769

Page 788: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

WCSWIDTH(3)

NAME

wcswidth - number of column positions in wide-character string

SYNOPSIS

intwcswidth(const wchar_t *pwcs, size_t n);

DESCRIPTION

The wcswidth() function determins the number of column positions required forthe first n characters of pwcs, or until a null wide character (L’\0’) is encountered.

RETURN VALUES

The wcswidth() function returns 0 if pwcs is an empty string (L""), -1 if a non-printing wide character is encountered, otherwise it returns the number of columnpositions occupied.

SEE ALSO

iswprint(3), wcwidth(3)

STANDARDS

The wcswidth() function conforms to ISO/IEC 9899:1999 (“ISO C99”).

770 Systems/C C Library

Page 789: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

WMEMCHR(3)

NAME

wmemchr, wmemcmp, wmemcpy, wmemmove, wmemset, wcscat, wcschr, wcscmp,wcscpy, wcscspn, wcslcat, wcslcpy, wcslen, wcsncat, wcsncmp, wcsncpy, wcspbrk,wcsrchr, wcsspn, wcsstr - wide character string manipulation operations

SYNOPSIS

#include <wchar.h>

wchar_t *wmemchr(const wchar_t *s, wchar_t c, size_t n);

intwmemcmp(const wchar_t *s1, const wchar_t *s2, size_t n);

wchar_t *wmemcpy(wchar_t * restrict s1, const wchar_t * restrict s2, size_t n);

wchar_t *wmemmove(wchar_t *s1, const wchar_t *s2, size_t n);

wchar_t *wmemset(wchar_t *s, wchar_t c, size_t n);

wchar_t *wcscat(wchar_t * restrict s1, const wchar_t * restrict s2);

wchar_t *wcschr(const wchar_t *s, wchar_t c);

intwcscmp(const wchar_t *s1, const wchar_t *s2);

wchar_t *wcscpy(wchar_t * restrict s1, const wchar_t * restrict s2);

size_twcscspn(const wchar_t *s1, const wchar_t *s2);

size_twcslcat(wchar_t *s1, const wchar_t *s2, size_t n);

size_t

Systems/C C Library 771

Page 790: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

wcslcpy(wchar_t *s1, const wchar_t *s2, size_t n);

size_twcslen(const wchar_t *s);

wchar_t *wcsncat(wchar_t * restrict s1, const wchar_t * restrict s2, size_t n);

intwcsncmp(const wchar_t *s1, const wchar_t * s2, size_t n);

wchar_t *wcsncpy(wchar_t * restrict s1, const wchar_t * restrict s2, size_t n);

wchar_t *wcspbrk(const wchar_t *s1, const wchar_t *s2);

wchar_t *wcsrchr(const wchar_t *s, wchar_t c);

size_twcsspn(const wchar_t *s1, const wchar_t *s2);

wchar_t *wcsstr(const wchar_t *s1, const wchar_t *s2);

DESCRIPTION

The functions implement string manipulation operations over wide character strings.For a detailed description, refer to documents for the respective single-byte coun-terpart, such as memchr(3).

SEE ALSO

memchr(3), memcmp(3), memcpy(3), memmove(3), memset(3), strcat(3), strchr(3),strcmp(3), strcpy(3), strcspn(3), strlcat(3), strlcpy(3), strlen(3), strncat(3),strncmp(3), strncpy(3), strpbrk(3), strrchr(3), strspn(3), strstr(3)

STANDARDS

These functions conform to ISO/IEC 9899:1999 (“ISO C99”), with the exception ofwcslcat() and wcslcpy(), which are extensions.

772 Systems/C C Library

Page 791: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

Regular Expression Library

The Systems/C library includes support for POSIX regular expressions in the regularexpression library. Regular expressions are a very powerful programming paradigmused for text pattern matching.

Systems/C C Library 773

Page 792: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

REGEX(3)

NAME

regcomp, regexec, regerror, regfree, reglen, regcpy - regular-expression library

SYNOPSIS

#include <sys/types.h>#include <regex.h>

int regcomp(regex_t *preg, const char *pattern,int cflags);

int regexec(const regex_t *preg, const char *string,size_t nmatch, regmatch_t pmatch[],int eflags);

size_t regerror(int errcode, const regex_t *preg,char *errbuf, size_t errbuf_size);

void regfree(regex_t *preg);

size_t __reglen(const regex_t *r);

void __regcpy(regex_t *dst, const regex_t *src);

DESCRIPTION

These routines implement POSIX 1003.2 regular expressions (“RE”s); seere format(7). regcomp() compiles an RE written as a string into an internalform, regexec() matches that internal form against a string and reports results,regerror() transforms error codes from either into human-readable messages, andregfree() frees any dynamically-allocated storage used by the internal form of anRE.

Dignus-specific extensions reglen() and regcpy() make it possible to copy aregex t and its internal components into user-allocated memory. reglen() returnsthe length that will be needed to represent its argument as one contiguous block ofmemory, while regcpy() will fill in that memory. regfree() should not be calledon a pointer that has been the destination of regcpy(). Instead, the memoryshould be freed according to whatever specific technique was used to allocate it.

774 Systems/C C Library

Page 793: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

Example of copying:

regex_t src;regcomp(&src, ...);regex_t *dst = my_malloc(__reglen(&src));__regcpy(dst, &src);/* optionally you can regfree(&src) now, and continue to use dst */...my_free(dst);

The header <regex.h> declares two structure types, regex t and rematch t, theformer for compiled internal forms and the latter for match reporting. It also declaresthe four functions, a type regoff t, and a number of constants with names startingwith “REG ”.

regcomp() compiles the regular expression contained in the pattern string, subjectto the flags in cflags, and places the results in the regex t structure pointed to bypreg. Cflags is the bitwise OR of zero or more of the following flags:

REG EXTENDED Compile modern (“extended”) REs, rather than the obsolete(“basic”) REs that are the default.

REG BASIC This is a synonym for 0, provided as a counterpart toREG EXTENDED to improve readability.

REG NOSPEC Compile with recognition of all special characters turned off.All characters are thus considered ordinary, so the “RE” is aliteral string. This is an extension, compatible with but notspecified by POSIX 1003.2, and should be used with cau-tion in software intended to be portable to other systems.REG EXTENDED and REG NOSPEC may not be used in the samecall to regcomp.

REG ICASE Compile for matching that ignores upper/lower case distinc-tions. See re format(7).

REG NOSUB Compile for matching that need only report success or failure,not what was matched.

REG NEWLINE Compile for newline-sensitive matching. By default, newlineis a completely ordinary character with no special meaning ineither REs or strings. With this flag, ‘[^’ bracket expressionsand ‘.’ never match newline, a ‘^’ anchor matches the nullstring after any newline in the string in addition to its normalfunction, and the ‘$’ anchor matches the null string beforeany newline in the string in addition to its normal function.

Systems/C C Library 775

Page 794: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

REG PEND The regular expression ends, not at the first NUL, but justbefore the character pointed to by the re endp member ofthe structure pointed to by preg. The re endp member isof type const char *. This flag permits inclusion of NULsin the RE; they are considered ordinary characters. This isan extension, compatible with but not specified by POSIX1003.2, and should be used with caution in software intendedto be portable to other systems.

When successful, regcomp() returns 0 and fills in the structure pointed to by preg.One member of that structure (other than re endp) is publicized: re nsub, of typesize t, contains the number of parenthesize subexpressions within the RE (exceptthat the value of this member is undefined if the REG NOSUB flag was used). Ifregcomp() fails, it returns a non-zero error code; see DIAGNOSTICS below.

regexec() matches the compiled RE pointed to by preg against the string, subjectto the flags in eflags, and reports results using nmatch, pmatch, and the returnedvalue. The RE must have been compiled by a previous invocation of regcomp().The compiled form is not altered during execution of regexec(), so a single compiledRE can be used simultaneously by multiple threads.

By default, the NUL-terminated string pointed to by string is considered to be thetext of an entire line, minus any terminating newline. The eflags argument is thebitwise OR of zero or more of the following flags:

REG NOTBOL The first character of the string is not the beginning of a line,so the ‘^’ anchor should not match before it. This does notaffect the behavior of newlines under REG NEWLINE.

REG NOTEOL The NUL terminating the string does not end a line, so the‘$’ anchor should not match before it. This does not affectthe behavior of newlines under REG NEWLINE.

REG STARTEND The string is considered to start at string +pmatch[0].rm so and to have a terminating NUL lo-cated at string + pmatch[0].rm eo (there need notactually be a NUL at that location), regardless of the value ofnmatch. See below for the definition of pmatch and nmatch.This is an extension, compatible with but not specified byPOSIX 1003.2, and should be used with caution in softwareintended to be portable to other systems. Note that anon-zero rm so does not imply REG NOTBOL; REG STARTENDaffects only the location of the string, not how it is matched.

See re format(7) for a discussion of what is matched in situations where an RE or aportion thereof could match any of several substrings of string.

776 Systems/C C Library

Page 795: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

Normally, regexec() returns 0 for success and the non-zero code REG NOMATCH forfailure. Other non-zero error codes may be returned in exceptional situations; seeDIAGNOSTICS.

If REG NOSUB was specified in the compilation of the RE, or if nmatch is 0, regexec ig-nores the pmatch argument (but see below for the case where REG STARTEND is speci-fied). Otherwise, pmatch points to an array of nmatch structures of type regmatch t.Such a structure has at least the members rm so and rm eo, both of type regoff t(a signed arithmetic type at least as large as an off t and a ssize t), containingrespectively the offset of the first character of a substring and the offset of the firstcharacter after the end of the substring. Offsets are measured from the beginning ofthe string argument given to regexec(). An empty substring is denoted by equaloffsets, both indicating the character following the empty substring.

The 0th member of the pmatch array is filled in to indicate what substring of stringwas matched by the entire RE. Remaining members report what substring wasmatched by parenthesized subexpressions within the RE; member i reports subex-pression i, with subexpressions counted (starting at 1) by the order of their openingparentheses in the RE, left to right. Unused entries in the array– correspondingeither to subexpressions that did not participate in the match at all, or to subex-pressions that do not exist in the RE (that is, i > preg->re nsub) – have bothrm so and rm eo set to -1. If a subexpression participated in the match severaltimes, the reported substring is the last one it matched. (Note, as an example inparticular, that when the RE ‘(b*)+’ matches ‘bbb’, the parenthesized subexpres-sion matches each of the three ‘b’s and then an infinite number of empty stringsfollowing the last ‘b’, so the reported substring is one of the empties.)

If REG STARTEND is specified, pmatch must point to at least one regmatch t (even ifnmatch is 0 or REG NOSUB was specified), to hold the input offsets for REG STARTEND.Use for output is still entirely controlled by nmatch; if nmatch is 0 or REG NOSUB wasspecified, the value of pmatch[0] will not be changed by a successful regexec().

regerror() maps a non-zero errcode from either regcomp() or regexec() to ahuman-readable, printable message. If preg is non-NULL, the error code should havearisen from use of the regex t pointed to by preg, and if the error code camefrom regcomp, it should have been the result from the most recent regcomp usingthat regex t. (Regerror may be able to supply a more detailed message usinginformation from the regex t.) Regerror places the NUL-terminated message intothe buffer pointed to by errbuf, limiting the length (including the NUL) to at mosterrbuf size bytes. If the whole message won’t fit, as much of it as will fit before theterminating NUL is supplied. In any case, the returned value is the size of bufferneeded to hold the whole message (including terminating NUL). If errbuf size is 0,errbuf is ignored but the return value is still correct.

If the errcode given to regerror() is first ORed with REG ITOA, the “message” thatresults is the printable name of the error code, e.g. REG NOMATCH, rather than anexplanation thereof. If errcode is REG ATOI, then preg shall be non-NULL and there endp member of the structure it points to must point to the printable name of

Systems/C C Library 777

Page 796: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

an error code; in this case, the result in errbuf is the decimal digits of the numericvalue of the error code (0 if the name is not recognized). REG ITOA and REG ATOIare intended primarily as debugging facilities; they are extensions, compatible withbut not specified by POSIX 1003.2, and should be used with caution in softwareintended to be portable to other systems. Be warned also that they are consideredexperimental and changes are possible.

regfree() frees any dynamically-allocated storage associated with the compiled REpointed to by preg. The remaining regex t is no longer a valid compiled RE andthe effect of supplying it to regexec or regerror is undefined.

None of these functions references global variables except for tables of constants; allare safe for use from multiple threads if the arguments are safe.

IMPLEMENTATION CHOICES

There are a number of decisions that 1003.2 leaves up to the implementor, eitherby explicitly saying s“undefined” or by virtue of them being forbidden by the REgrammar.

This implementation treats them as follows.

See re format(7) for a discussion of the definition of case-independent matching.

There is no particular limit on the length of REs, except insofar as memory islimited. Memory usage is approximately linear in RE size, and largely insensitive toRE complexity, except for bounded repetitions. See ISSUES for one short RE usingthem that will run almost any system out of memory.

A backslashed character other than one specifically given a magic meaning by 1003.2(such magic meanings occur only in obsolete [“basic”] REs) is taken as an ordinarycharacter.

Any unmatched [ is a REG EBRACK error.

Equivalence classes cannot begin or end bracket-expression ranges. The endpoint ofone range cannot begin another.

RE DUP MAX, the limit on repetition counts in bounded repetitions, is 255.

A repetition operator (?, *, +, or bounds) cannot follow another repetition operator.A repetition operator cannot begin an expression or subexpression or follow ‘^’ or‘|’.

‘|’ cannot appear first or last in a (sub)expression or after another ‘|’, i.e. anoperand of ‘|’ cannot be an empty subexpression. An empty parenthesized subex-pression, ‘()’, is legal and matches an empty (sub)string. An empty string is not alegal RE.

778 Systems/C C Library

Page 797: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

A ‘{’ followed by a digit is considered the beginning of bounds for a bounded repe-tition, which must then follow the syntax for bounds. A ‘{’ not followed by a digitis considered an ordinary character.

‘^’ and ‘$’ beginning and ending subexpressions in obsolete (“basic”) REs are an-chors, not ordinary characters.

SEE ALSO

re format(7)

POSIX 1003.2, sections 2.8 (Regular Expression Notation) and B.5 (C Binding forRegular Expression Matching).

DIAGNOSTICS

Non-zero error codes from regcomp() and regexec() include the following:

REG NOMATCH regexec() failed to match

REG BADPAT invalid regular expression

REG ECOLLATE invalid collating element

REG ECTYPE invalid character class

REG EESCAPE \ applied to unescapable character

REG ESUBREG invalid backreference number

REG EBRACK brackets [ ] not balanced

REG EPAREN parentheses ( ) not balanced

REG EBRACE braces { } not balanced

REG BADBR invalid repetition count(s) in { }

REG ERANGE invalid character range in [ ]

REG ESPACE ran out of memory

REG BADRPT ?, *, or + operand invalid

REG EMPTY empty (sub)expression

REG ASSERT “can’t happen”–you found a bug

REG INVARG invalid argument, e.g. negative-length string

Systems/C C Library 779

Page 798: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

ISSUES

There is one known functionality issue. The implementation of Internationalizationis incomplete: the locale is always assumed to be the default one of 1003.2, and onlythe collating elements etc. of that locale are available.

Regcomp implements bounded repetitions by macro expansion, which is costly intime and space if counts are large or bounded repetitions are nested. An RE like, say,“((((a{1,100}){1,100}){1,100}){1,100}){1,100}” will (eventually) run almostany existing machine out of swap space.

Due to a mistake in 1003.2, things like ‘a)b’ are legal REs because ‘)’ is a specialcharacter only in the presence of a previous unmatched ‘(’. This can’t be fixed untilthe spec is fixed.

The standard’s definition of back references is vague. For example, does‘a\(\(b\)*\2\)*d’ match ‘abbbd’? Until the standard is clarified, behavior insuch cases should not be relied on.

780 Systems/C C Library

Page 799: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

RE FORMAT(7)

NAME

re format - POSIX 1003.2 regular expressions

DESCRIPTION

Regular expressions (“RE”s), as defined in POSIX 1003.2, come in two forms: mod-ern REs (roughly those of the POSIX utility egrep; 1003.2 calls these “extended”REs) and obsolete REs (roughly those of ed; 1003.2 “basic” Res). Obsolete REsmostly exist for backward compatibility in some old programs; they will be dis-cussed at the end. 1003.2 leaves some aspects of RE syntax and semantics open;‘∗’ marks decisions on these aspects that may not be fully portable to other 1003.2implementations.

A (modern) RE is one∗ or more non-empty∗ branches, separated by ‘|’. It matchesanything that matches one of the branches.

A branch is one∗ or more pieces, concatenated. It matches a match for the first,followed by a match for the second, etc.

A piece is an atom possibly followed by a single∗ ‘*’, ‘+’, ‘?’, or bound. An atomfollowed by ‘*’ matches a sequence of 0 or more matches of the atom. An atomfollowed by ‘+’ matches a sequence of 1 or more matches of the atom. An atomfollowed by ‘?’ matches a sequence of 0 or 1 matches of the atom.

A bound is ‘{’ followed by an unsigned decimal integer, possibly followed by ‘,’possibly followed by another unsigned decimal integer, always followed by ‘}’. Theintegers must lie between 0 and RE DUP MAX (255∗) inclusive, and if there are two ofthem, the first may not exceed the second. An atom followed by a bound containingone integer i and no comma matches a sequence of exactly i matches of the atom. Anatom followed by a bound containing one integer i and a comma matches a sequenceof i or more matches of the atom. An atom followed by a bound containing twointegers i and j matches a sequence of i through j (inclusive) matches of the atom.

An atom is a regular expression enclosed in ‘()’ (matching a match for the regularexpression), an empty set of ‘()’ (matching the null string)∗, a bracket expression(see below), ‘.’ (matching any single character), ‘^’ (matching the null string atthe beginning of a line), ‘$’ (matching the null string at the end of a line), a ‘\’followed by one of the characters ‘^.[$()|*+?{\’ (matching that character takenas an ordinary character), a ‘\’ followed by any other character∗ (matching thatcharacter taken as an ordinary character, as if the ‘\’ had not been present∗), or asingle character with no other significance (matching that character). A ‘{’ followedby a character other than a digit is an ordinary character, not the beginning of abound∗. It is illegal to end an RE with ‘\’.

Systems/C C Library 781

Page 800: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

A bracket expression is a list of characters enclosed in ‘[]’. It normally matchesany single character from the list (but see below). If the list begins with ‘^’, itmatches any single character (but see below) not from the rest of the list. If twocharacters in the list are separated by ‘-’, this is shorthand for the full range ofcharacters between those two (inclusive) in the collating sequence, e.g. ‘[0-9]’ inASCII matches any decimal digit. It is illegal∗ for two ranges to share an endpoint,e.g. ‘a-c-e’. Ranges are very collating-sequence-dependent, and portable programsshould avoid relying on them.

To include a literal ‘]’ in the list, make it the first character (following a possible ‘^’).To include a literal ‘-’, make it the first or last character, or the second endpointof a range. To use a literal ‘-’ as the first endpoint of a range, enclose it in ‘[.’and ‘.]’ to make it a collating element (see below). With the exception of theseand some combinations using ‘[’ (see next paragraphs), all other special characters,including ‘\’, lose their special significance within a bracket expression.

Within a bracket expression, a collating element (a character, a multi-charactersequence that collates as if it were a single character, or a collating-sequence namefor either) enclosed in ‘[.’ and ‘.]’ stands for the sequence of characters of thatcollating element. The sequence is a single element of the bracket expression’s list.A bracket expression containing a multi-character collating element can thus matchmore than one character, e.g. if the collating sequence includes a ‘ch’ collatingelement, then the RE ‘[[.ch.]]*c’ matches the first five characters of ‘chchcc’.

Within a bracket expression, a collating element enclosed in ‘[=’ and ‘=]’ is anequivalence class, standing for the sequences of characters of all collating elementsequivalent to that one, including itself. (If there are no other equivalent collatingelements, the treatment is as if the enclosing delimiters were ‘[.’ and ‘.]’.) Forexample, if ‘x’ and ‘y’ are the members of an equivalence class, then ‘[[=x=]]’,‘[[=y=]]’, and ‘[xy]’ are all synonymous. An equivalence class may not∗ be anendpoint of a range.

Within a bracket expression, the name of a character class enclosed in ‘[:’ and ‘:]’stands for the list of all characters belonging to that class. Standard character classnames are:

alnum digit punctalpha graph spaceblank lower uppercntrl print digit

These stand for the character classes defined in ctype(3). A locale may provideothers. A character class may not be used as an endpoint of a range.

There are two special cases∗ of bracket expressions: the bracket expressions‘[[:<:]]’ and ‘[[:>:]]’ match the null string at the beginning and end of a wordrespectively. A word is defined as a sequence of word characters which is neitherpreceded nor followed by word characters. A word character is an alnum character(as defined by ctype(3)) or an underscore. This is an extension, compatible with

782 Systems/C C Library

Page 801: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

but not specified by POSIX 1003.2, and should be used with caution in softwareintended to be portable to other systems.

In the event that an RE could match more than one substring of a given string,the RE matches the one starting earliest in the string. If the RE could match morethan one substring starting at that point, it matches the longest. Subexpressionsalso match the longest possible substrings, subject to the constraint that the wholematch be as long as possible, with subexpressions starting earlier in the RE takingpriority over ones starting later. Note that higher-level subexpressions thus takepriority over their lower-level component subexpressions.

Match lengths are measured in characters, not collating elements. A null string Isconsidered longer than no match at all. For example, ‘bb*’ matches the three middlecharacters of ‘abbbc’, ‘(wee|week)(knights|nights)’ matches all ten characters of‘weeknights’, when ‘(.*).*’ is matched against ‘abc’ the parenthesized subexpres-sion matches all three characters, and when ‘(a*)*’ is matched against ‘bc’ boththe whole RE and the parenthesized subexpression match the null string.

If case-independent matching is specified, the effect is much as if all case distinc-tions had vanished from the alphabet. When an alphabetic that exists in multiplecases appears as an ordinary character outside a bracket expression, it is effectivelytransformed into a bracket expression containing both cases, e.g. ‘x’ becomes ‘[xX]’.When it appears inside a bracket expression, all case counterparts of it are addedto the bracket expression, so that (e.g.) ‘[x]’ becomes ‘[xX]’ and ‘[^x]’ becomes‘[^xX]’.

No particular limit is imposed on the length of REs∗. Programs intended to beportable should not employ REs longer than 256 bytes, as an implementation canrefuse to accept such REs and remain POSIX-compliant.

Obsolete (“basic”) regular expressions differ in several respects. ‘|’, ‘+’, and ‘?’ areordinary characters and there is no equivalent for their functionality. The delimitersfor bounds are ‘\{’ and ‘\}’, with ‘{’ and ‘}’ by themselves ordinary characters. Theparentheses for nested subexpressions are ‘\(’ and ‘\)’, with ‘(’ and ‘)’ by themselvesordinary characters. ‘^’ is an ordinary character except at the beginning of the REor∗ the beginning of a parenthesized subexpression, ‘$’ is an ordinary characterexcept at the end of the RE or∗ the end of a parenthesized subexpression, and ‘*’ isan ordinary character if it appears at the beginning of the RE or the beginning of aparenthesized subexpression (after a possible leading ‘^’). Finally, there is one newtype of atom, a back reference: ‘\’ followed by a non-zero decimal digit d matchesthe same sequence of characters matched by the dth parenthesized subexpression(numbering subexpressions by the positions of their opening parentheses, left toright), so that (e.g.) ‘\([bc]\)\1’ matches ‘bb’ or ‘cc’ but not ‘bc’.

SEE ALSO

regex(3)

Systems/C C Library 783

Page 802: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

POSIX 1003.2, section 2.8 (Regular Expression Notation).

ISSUES

The current 1003.2 spec says that ‘)’ is an ordinary character in the absence of anunmatched ‘(’; this was an unintentional result of a wording error, and change islikely. Avoid relying on it.

Back references are a dreadful botch, posing major prob lems for efficient implemen-tations. They are also somewhat vaguely defined (does ‘a\(\(b\)*\2\)*d’ match‘abbbd’?). Avoid using them.

1003.2’s specification of case-independent matching is vague. The “one case impliesall cases” definition given above is current consensus among implementors as to theright interpretation.

784 Systems/C C Library

Page 803: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

Net Library

The Net library provides the set of functions related to network operations andTCP/IP.

Systems/C C Library 785

Page 804: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

ADDR2ASCII(3)

NAME

addr2ascii, ascii2addr - Generic address formatting routines

SYNOPSIS

#include <sys/types.h>#include <netinet/in.h>#include <arpa/inet.h>

char *addr2ascii(int af, const void *addrp, int len, char *buf)

intascii2addr(int af, const char *ascii, void *result)

DESCRIPTION

The routines addr2ascii() and ascii2addr() are used to convert network addressesbetween binary form and a printable form appropriate to the address family. Bothfunctions take an af argument, specifying the address family to be used in theconversion process. (Currently, only the AF INET and AF LINK address families aresupported.)

The addr2ascii() function is used to convert binary, network-format addresses intoprintable form. In addition to af, there are three other arguments. The addrpargument is a pointer to the network address to be converted. The len argumentis the length of the addresss. The buf argument is an optional pointer to a caller-allocated buffer to hold the result; if a NULL pointer is passed, addr2ascii() uses astatically-allocated buffer.

The ascii2addr() function performs the inverse operation to addr2ascii(). Inaddition to af, it takes two parameters, ascii and result. The ascii parameter is apointer to the string which is to be converted into binary. The result parameter isa pointer to an appropriate network address structure for the specified family.

The following gives the appropriate structure to use for binary addresses in thespecified family:

AF INET struct in addr (in <netinet/in.h>)

AF LINK struct sockaddr dl (in <net/if dl.h>)

786 Systems/C C Library

Page 805: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

RETURN VALUES

The addr2ascii() function returns the address of the buffer it was passed, or astatic buffer if the NULL pointer was passed; on failure it returns a NULL pointer.The ascii2addr() function returns the length of the binary address in bytes, or -1on failure.

EXAMPLES

The inet(3) functions inet ntoa() and inet aton() could be implemented thusly:

#include <sys/types.h>#include <sys/socket.h>#include <netinet/in.h>#include <arpa/inet.h>

char *inet_ntoa(struct in_addr addr){

return addr2ascii(AF_INET, &addr, sizeof addr, 0);}

intinet_aton(const char *ascii, struct in_addr *addr){

return (ascii2addr(AF_INET, ascii, addr)== sizeof(*addr));

}

In actuality, this cannot be done because add2ascii(0 and ascii2addr() are imple-mented in terms of the inet(3) functions, rather than the other way around.

ERRORS

When a failure is returned, errno is set to one of the following values:

[ENAMETOOLONG] The addr2ascii() routine was passed a len parameter which wasinappropriate for the address family given by af.

[EPROTONOSUPPORT] Either routine was passed an af parameter other than AF INETor AF LINK.

[EINVAL] The string passed to ascii2addr() was improperly formatted foraddress family af.

Systems/C C Library 787

Page 806: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

SEE ALSO

inet(3), linkaddr(3), inet(4)

788 Systems/C C Library

Page 807: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

BYTEORDER(3)

NAME

htonl, htons, ntohl, ntohs - convert values between host and network byte order

SYNOPSIS

#include <arpa/inet.h>

or

#include <netinet/in.h>

uint32_thtonl(uint32_t hostlong)

uint16_thtons(uint16_t hostshort)

uint32_tntohl(uint32_t netlong)

uint16_tntohs(uint16_t netshort)

DESCRIPTION

These routines convert 16 and 32 bit quantities between network byte order andhost byte order. On machines which have a byte order which is the same as thenetwork order, these routines are defined as null macros.

These routines are most often used in conjunction with Internet addresses and portsas returned by gethostbyname(3) and getservent(3).

SEE ALSO

gethostbyname(3), getservent(3)

Systems/C C Library 789

Page 808: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

ETHERS(3)

NAME

ethers, ethers line, ether aton, ether ntoa, ether ntohost, ether hostton - Ethernetaddress conversion and lookup routines.

SYNOPSIS

#include <sys/types.h>#include <sys/socket.h>#include <net/ethernet.h>

intether_line(char *l, struct ether_addr *e, char *hostname)

struct ether_addr *ether_aton(char *a)

char *ether_ntoa(struct ether_addr *n)

intether_ntohost(char *hostname, struct ether_addr *e)

intether_hostton(char *hostname, struct ether_addr *e)

DESCRIPTION

These functions operate on ethernet addresses using an ether addr structure, whichis defined in the header file <netinet/if ether.h>:

/** The number of bytes in an ethernet (MAC)* address.*/#define ETHER_ADDR_LEN 6

/** Structure of a 48-bit Ethernet address.*/struct ether_addr {

790 Systems/C C Library

Page 809: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

u_char octet[ETHER_ADDR_LEN];}

The function ether line() scans l, an string in ethers(5) format and sets e to theethernet address specified in the string and hostname to the hostname. This functionis used to parse lines from the ethers specification file (typically /etc/ethers onUNIX hosts) into their component parts.

The ether aton() function converts a string representation of an ethernet addressinto an ether addr structure. Likewise, ether ntoa() converts an ethernet addressspecified as an ether addr structure into a string.

The ether ntohost() and ether hostton() functions map ethernet addresses totheir corresponding hostnames as specified in the ethers specification file (typically/etc/ethers on UNIX hosts.) ether ntohost() converts from ethernet address tohostname, and ether hostton() converts from hostname to ethernet address.

RETURN VALUES

ether line() returns zero on success and non-zero if it was unable to parse anypart of the supplied line l. It returns the extracted ethernet address in the suppliedether addr structure e and returns the hostname in the supplied string hostname.

On success, ether ntoa() returns a pointer to a string containing the string rep-resentation of an ether address. If it is unable to convert the supplied ether addrstructure, it returns a NULL pointer. Likewise, ether aton() returns a pointer toan ether addr structure on success and a NULL pointer on failure.

The ether ntohost() and ether hostton() functions both return zero on successand non-zero if they were unable to find a match in the ethers database file.

FILES

These functions use the algorithm outlined in the IBM TCP/IP documentation tolocate the ETC.ETHERS file; using the location specified in the TCPIP.DATA file.

NOTES

The user must insure that the hostname strings passed to the ether line(),ether ntohost() and ether hostton() functions are large enough to contain thereturned hostnames.

Systems/C C Library 791

Page 810: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

ISSUES

The ether aton() and ether ntoa() functions return values that are stored instatic memory areas which may be overwritten the next time they are called.

792 Systems/C C Library

Page 811: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

GAI STRERROR(3)

NAME

gai strerror – get error message string from EAI xxx error code

SYNOPSIS

#include <sys/types.h>#include <sys/socket.h>#include <netdb.h>

const char *gai_strerror(int ecode);

DESCRIPTION

The gai strerror() function returns an error message string corresponding to theerror code returned by getaddrinfo(3) or getnameinfo(3).

The following error codes and their meaning are defined in <netdb.h>:

EAI AGAIN temporary failure in name resolution

EAI BADFLAGS invalid value for ai flags

EAI BADHINTS invalid value for hints

EAI FAIL non-recoverable failure in name resolution

EAI FAMILY ai family not supported

EAI MEMORY memory allocation failure

EAI NONAME hostname or servname not provided, or not known

EAI PROTOCOL resolved protocol is unknown

EAI SERVICE servname not supported for ai socktype

EAI SOCKTYPE ai socktype not supported

EAI SYSTEM system error returned in errno

Systems/C C Library 793

Page 812: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

RETURN VALUES

The gai strerror() function returns a pointer to the error message string corre-sponding to ecode. If ecode is out of range, an implementation-specific error messagestring is returned.

SEE ALSO

getaddrinfo(3), getnameinfo(3)

794 Systems/C C Library

Page 813: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

GETADDRINFO(3)

NAME

getaddrinfo, freeaddrinfo – socket address structure to host and service name

SYNOPSIS

#include <sys/types.h>#include <sys/socket.h>#include <netdb.h>

intgetaddrinfo(const char *hostname, const char *servname,

const struct addrinfo *hints, struct addrinfo **res);

voidfreeaddrinfo(struct addrinfo *ai);

DESCRIPTION

The getaddrinfo() function is used to get a list of IP addresses and port numbersfor host hostname and service servname. It is a replacement for and provides moreflexibility than the gethostbyname(3) and getservbyname(3) functions.

The hostname and servname arguments are either pointers to NUL-terminated stringsor the null pointer. An acceptable value for hostname is either a valid host nameor a numeric host address string consisting of a dotted decimal IPv4 address or anIPv6 address. The servname is either a decimal port number or a service name. Atleast one of hostname and servname must be non-null.

hints is an optional pointer to a struct addrinfo, as defined by <netdb.h>:

struct addrinfo {int ai_flags; /* input flags */int ai_family; /* protocol family for socket */int ai_socktype; /* socket type */int ai_protocol; /* protocol for socket */socklen_t ai_addrlen; /* length of socket-address */struct sockaddr *ai_addr; /* socket-address for socket */char *ai_canonname; /* canonical name for service location */struct addrinfo *ai_next; /* pointer to next in list */};

Systems/C C Library 795

Page 814: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

This structure can be used to provide hints concerning the type of socket that thecaller supports or wishes to use. The caller can supply the following structureelements in hints:

ai family The protocol family that should be used. When ai family is set toPF UNSPEC, it means the caller will accept any protocol family supportedby the operating system.

ai socktype Denotes the type of socket that is wanted: SOCK STREAM, SOCK DGRAM,or SOCK RAW. When ai socktype is zero the caller will accept any sockettype.

ai protocol Indicates which transport protocol is desired, IPPROTO UDP orIPPROTO TCP. If ai protocol is zero the caller will accept any protocol.

ai flags ai flags is formed by OR’ing the following values:

AI CANONNAME If the AI CANONNAME bit is set, a successful callto getaddrinfo() will return a NUL-terminatedstring containing the canonical name of the spec-ified hostname in the ai canonname element ofthe first addrinfo structure returned.

AI NUMERICHOST If the AI NUMERICHOST bit is set, it indi cates thathostname should be treated as a numeric stringdefining an IPv4 or IPv6 address and no nameresolution should be attempted.

AI PASSIVE If the AI PASSIVE bit is set it indicates that thereturned socket address structure is intended foruse in a call to bind(2). In this case, if the host-name argument is the null pointer, then the IPaddress portion of the socket address structurewill be set to INADDR ANY for an IPv4 address orIN6ADDR ANY INIT for an IPv6 address.If the AI PASSIVE bit is not set, the returnedsocket address structure will be ready for use in acall to connect(2) for a connection-oriented pro-tocol or connect(2), sendto(2), or sendmsg(2) if aconnectionless protocol was chosen. The IP ad-dress portion of the socket address structure willbe set to the loopback address if hostname is thenull pointer and AI PASSIVE is not set.

All other elements of the addrinfo structure passed via hints must be zero or thenull pointer.

If hints is the null pointer, getaddrinfo() behaves as if the caller provided a structaddrinfo with ai family set to PF UNSPEC and all other elements set to zero or NULL.

796 Systems/C C Library

Page 815: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

After a successful call to getaddrinfo(), *res is a pointer to a linked list of one or moreaddrinfo structures. The list can be traversed by following the ai next pointer in eachaddrinfo structure until a null pointer is encountered. The three members ai family,ai socktype, and ai protocol in each returned addrinfo structure are suitable for acall to socket(2). For each addrinfo structure in the list, the ai addr member pointsto a filled-in socket address structure of length ai addrlen.

This implementation of getaddrinfo() allows numeric IPv6 address notation withscope identifier, as documented in chapter 11 of draft-ietf-ipv6-scoping-arch-02.txt.By appending the percent character and scope identifier to addresses, one can fill thesin6 scope id field for addresses. This would make management of scoped addresseseasier and allows cut-and-paste input of scoped addresses.

At this moment the code supports only link-local addresses with the fo mat. Thescope identifier is hardcoded to the name of the hardware interface associated withthe link (such as ne0). An example is “fe80::1%ne0”, which means “fe80::1 onthe link associated with the ne0 interface”.

The current implementation assumes a one-to-one relationship between the interfaceand link, which is not necessarily true from the specification.

All of the information returned by getaddrinfo() is dynamically allocated: theaddrinfo structures themselves as well as the socket address structures and thecanonical host name strings included in the addrinfo structures.

Memory allocated for the dynamically allocated structures created by a successfulcall to getaddrinfo() is released by the freeaddrinfo() function. The ai pointershould be a addrinfo structure created by a call to getaddrinfo().

RETURN VALUES

getaddrinfo() returns zero on success or one of the error codes listed ingai strerror(3) if an error occurs.

EXAMPLES

The following code tries to connect to “www.kame.net” service “http” via a streamsocket. It loops through all the addresses available, regardless of address family. Ifthe destination resolves to an IPv4 address, it will use an AF INET socket. Similarly,if it resolves to IPv6, an AF INET6 socket is used. Observe that there is no hardcodedreference to a particular address family. The code works even if getaddrinfo() returnsaddresses that are not IPv4/v6.

struct addrinfo hints, *res, *res0;int error;

Systems/C C Library 797

Page 816: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

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) {errx(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, "%s", cause);/*NOTREACHED*/}freeaddrinfo(res0);

The following example tries to open a wildcard listening socket onto service “http”,for all the address families available.

struct addrinfo hints, *res, *res0;int error;int s[MAXSOCK];int nsock;const char *cause = NULL;

memset(&hints, 0, sizeof(hints));hints.ai_family = PF_UNSPEC;

798 Systems/C C Library

Page 817: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

hints.ai_socktype = SOCK_STREAM;hints.ai_flags = AI_PASSIVE;error = getaddrinfo(NULL, "http", &hints, &res0);if (error) {errx(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 (bind(s[nsock], res->ai_addr, res->ai_addrlen) < 0) {cause = "bind";close(s[nsock]);continue;}(void) listen(s[nsock], 5);

nsock++;}if (nsock == 0) {err(1, "%s", cause);/*NOTREACHED*/}freeaddrinfo(res0);

SEE ALSO

bind(2), connect(2), send(2), socket(2), gethostbyname(3), getnameinfo(3), get-servbyname(3), resolver(3)

R. Gilligan, S. Thomson, J. Bound, J. McCann, and W. Stevens, Basic SocketInterface Extensions for IPv6, RFC 3493, February 2003.

S. Deering, B. Haberman, T. Jinmei, E. Nordmark, and B. Zill, IPv6 Scoped AddressArchitecture, internet draft, draft-ietf-ipv6-scoping- arch-02.txt, work in progressmaterial.

Craig Metz, “Protocol Independence Using the Sockets API”, Proceedings of thefreenix track: 2000 USENIX annual technical conference, June 2000.

Systems/C C Library 799

Page 818: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

STANDARDS

The getaddrinfo() function is defined by the IEEE Std 1003.1g-2000 (“POSIX.1”)draft specification and documented in RFC 3493, “Basic Socket Interface Extensionsfor IPv6”.

800 Systems/C C Library

Page 819: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

GETHOSTBYNAME(3)

NAME

gethostbyname, gethostbtname2, gethostbyaddr, gethostent, sethostent, endhos-tent, herror, hstrerror - get network host entry.

SYNOPSIS

#include <netdb.h>

extern int h_errno;

struct hostent *gethostbyname(const char *name)

struct hostent *gethostbyname2(const char *name, int af)

struct hostent *gethostbyaddr(const char *addr, int len, int type)

struct hostent *gethostent(void)

voidsethostent(int stayopen)

voidendhostent(void)

voidherror(const char *string)

const char *hstrerror(int err)

DESCRIPTION

The gethostbyname(), gethostbyname2() and gethostbyaddr() functionseach return a pointer to an object with the following structure describing an in-ternet host referenced by name or by address, respectively. This structure containseither the information obtained from the name server, or broken-out fields froma line in the host information file. If the local name server is not running, theseroutines do a lookup in the host information file.

Systems/C C Library 801

Page 820: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

struct hostent {char *h_name; /* official name of host */char **h_aliases; /* alias list */int h_addrtype; /* host address type */int h_length; /* length of address */char **h_addr_list; /* list of addresses */

/* from name server */}#define h_addr h_addr_list[0] /* address,for */

/* backwards *//* compatibility */

The members of this structure are:

h name Official name of the host.

h aliases A NULL-terminated array of alternate names for the host.

h addrtype The type of address being returned; usually AF INET.

h length The length, in bytes, of the address.

h addr list A NULL-terminated array of network addresses for the host.Host addresses are returned in network byte order.

h addr The first address in h addr list; this is for backward com-patibility.

When using the nameserver, gethostbyname() and gethostaddr() will search forthe named host in the current domain and its parents unless the name ends in adot. If the name contains no dot, and if the environment variable “HOSTALIASES”contains the name of an alias file, the alias file will first be searched for an aliasmatching the input name.

The gethostbyname2() function is an evolution of gethostbyname() which isintended to allow lookups in address families other than AF INET, for exampleAF INET6. Currently the af argument must be specified as AF INET else the functionwill return NULL after having set h errno to NETDB INTERNAL.

The sethostent() function may be used to request the use of a connected TCPsocket for queries. If the stayopen flag is non-zero, this sets the option to send allqueries to the name server using TCP and to retain the connection after each call togethostbyname(), gethostbyname2() or gethostbyaddr(). Otherwise, queriesare performed using UDP datagrams.

The endhostent() function closes the TCP connection.

802 Systems/C C Library

Page 821: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

The herror() function writes a message to the diagnostic output consisting of thestring parameter string, the constant string ": ", and a message corresponding tothe value of h errno.

The hstrerror() function returns a string which is the message text correspondingto the value of the err parameter.

FILES

These functions use the algorithm described in the IBM TCP/IP documentation tolocate the TCPIP.DATA, ETC.HOSTS, ETC.HOST.CONF and ETC.RESOLV.CONF files.

DIAGNOSTICS

Error return status from gethostbyname(), gethostbyname2() and gethost-byaddr() is indicated by return of a NULL pointer. The external integer h errnomay then be checked to see whether this is a temporary failure or an invalid or un-known host. The routine herror() can be used to print an error message describingthe failure. If its argument string is non-NULL, it is printed, followed by a colon anda space. The error message is printed with a trailing newline.

The variable h errno can have the following values:

HOST NOT FOUND No such host is known.

TRY AGAIN This is usually a temporary error and means that the localserver did not receive a response from an authoritative server.A retry at some later time may succeed.

NO RECOVERY Some unexpected server failure was encountered. This is anon-recoverable error.

NO DATA The requested name is valid but does not have an IP address;this is not a temporary error. This means that the name isknown to the name of the server but there is no address asso-ciated with this name. Another type of request to the nameserver using this domain name will result in an answer; forexample, a mail-forwarder may be registered for this domain.

SEE ALSO

resolver(3), IBM TCP/IP documentation

Systems/C C Library 803

Page 822: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

CAVEAT

The gethostent() function reads the next line of the ETC.HOSTS file, opening thefile if necessary.

The sethostent() function opens and/or rewinds the ETC.HOSTS file. If the stayopenargument is non-zero, the file will not be closed after each call to gethostbyname(),gethostbyname2() or gethostbyaddr().

The endhostent() function closes the file.

ISSUES

These functions use static data storage; if the data is needed for future use, it shouldbe copied before any subsequent calls overwrite it. Only the Internet address formatis currently understood.

804 Systems/C C Library

Page 823: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

NSSWITCH LINE(3)

NAME

nsswitch line - process an nsswitch configuration string

SYNOPSIS

#include <nsswitch.h>

int__nsswitch_line(const char *line)

DESCRIPTION

The nsswitch line(), function processes a string as if it were a line of text in theUnix nsswitch.conf configuration file. It is useful for specifying the order in whichDNS resolution techniques should be used by functions such as gethostbyname().The syntax of the string is "database: method1 method2 ...". The only databasethat is currently useful is hosts, which can use the following methods:

files Use ETC.HOSTS file for hostname lookup.

dns Use the DNS resolver built into the Dignus runtime.

ibm Use IBM’s EZASMI or BPX interface for hostname lookup.

The default is "hosts: files dns". To try the IBM resolver first you would callnsswitch line("hosts: ibm files dns").

DIAGNOSTICS

On success, nsswitch line() returns 1. If the string does not conform to therequirements, it returns 0 and sets errno to EINVAL.

NOTES

The name ezasmi was previously used to indicate the IBM EZASMI interface shouldbe employed. With the change of the Dignus runtime to use the BPX socket interface,the name was changed to ibm. The name ezasmi is still accepted, and is equivalentto ibm.

Systems/C C Library 805

Page 824: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

SEE ALSO

gethostbyname(3), IBM TCP/IP documentation

806 Systems/C C Library

Page 825: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

GETIPNODEBYNAME(3)

NAME

getipnodebyname, getipnodebyaddr, freehostent - nodenametoaddress and address-tonodename translation

SYNOPSIS

#include <sys/types.h>#include <sys/socket.h>#include <netdb.h>

struct hostent *getipnodebyname(const char *name, int af, int flags, int *error_num);

struct hostent *getipnodebyaddr(const void *src, size_t len, int af, int *error_num);

voidfreehostent(struct hostent *ptr);

DESCRIPTION

getipnodebyname() and getipnodebyaddr() functions are very similar to geth-ostbyname(3), gethostbyname2(3) and gethostbyaddr(3). The functions cover allthe functionalities provided by the older ones, and provide better interface to pro-grammers. The functions require additional arguments, af, and flags, for specifyingaddress family and operation mode. The additional arguments allow the program-mer to get the address for a nodename, for specific address family (such as AF INETor AF INET6). The functions also require an additional pointer argument, error numto return the appropriate error code, to support thread safe error code returns.

The type and usage of the return value, struct hostent is described in gethostby-name(3).

For getipnodebyname(), the name argument can be either a node name or anumeric address string (i.e. a dotted-decimal IPv4 address or an IPv6 hex address.)The af argument specifies the address family, either AF INET or AF INET6. The flagsargument specifies the types of addresses that are searched for, and the types ofaddresses that are returend. Note that a specifal flags value of AI DEFAULT (definedblow) should handle most applications. That is, porting simple applications to useIPv6 replaces the call

hptr = gethostbyname(name);

Systems/C C Library 807

Page 826: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

with

hptr = getipnodebyname(name, AF INET6, AI DEFAULT, &error_num);

Applications desiring finer control over the types of addresses searched for and re-turned can specify other combinations of the flags argument.

A flags of 0 implies a strict interpretation of the af argument:

• If flags is 0 and af is AF INET, then the caller wants only IPv4 addresses. Aquery is made for A records. If successful, the IPv4 addresses are returned andthe h length member of the hostent structure will be 4, else the functionreturns a NULL pointer.

• If flags is 0 and if af is AF INET6, then the caller wants only IPv6 addresses. Aquery is made for AAAA records. If successful, the IPv6 addresses are returnedand the h length member of the hostent structure will be 16, else the functionreturns a NULL pointer.

Other constants can be logically-ORed into the flags argument to modify behaviorof the function.

• If the AI V4MAPPED flag is specified along with an af of AF INET6, then thecaller will accept IPv4-mapped IPv6 addresses. That is, if no AAAA recordsare found then a query is made for A records and any found are returned asIPv4-mapped IPv6 addresses (h length will be 16). The AI V4MAPPED flag isignored unless af equals AF INET6.

• The AI V4MAPPED CFG flag is the same as the AI V4MAPPED flag only if theunderlying system supports IPv4-mapped IPv6 address.

• If the AI ALL flag is used in conjunction with the AI V4MAPPED flag, andonly used with the IPv6 address family. When AI ALL is logically OR’d withAI V4MAPPED flag then the caller wants all addresses: IPv6 and IPv4-mappedIPv6. A query is first made for AAAA records and if successful, the IPv6 ad-dresses are returned. Another query is then made for A records and any foundare returned as IPv4-mapped IPv6 addresses. h length will be 16. Only ifboth queries fail does the function return a NULL pointer. This flag is ignoredunless af equals AF INET6. If both AI ALL and AI V4MAPPED are specified,AI ALL takes precedence.

• The AI ADDRCONFIG flag specifies that a query for AAAA records should occuronly if the node has at least one IPv6 source address configured and a queryfor A records should occur only if the node has at least one IPv4 source addressconfigured.

808 Systems/C C Library

Page 827: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

For example, if the node has no IPv6 source addresses configured, and afequals AF INET6, and the node name being looked up has both AAAA and Arecords, then: (a) if only AI ADDRCONFIG is specified, the function returns aNULL pointer; (b) if AI ADDRCONFIG | AI V4MAPPED is specified, the A recordsare returned as IPv4-mapped IPv6 addresses;

The special flags value of AI DEFAULT is defined as

#define AI DEFAULT (AI V4MAPPED CFG | AI ADDRCONFIG)

Note that the getipnodebyname() function must allow the name argument to beeither a node name or a literal address string (i.e. a dotted-decimal IPv4 addressor an IPv6 hex address.) this saves applicats from having to call inet pton(3) tohandle literal address strings. When the name argument is a literal address strings,the flags argument is always ignored.

There are four scenarios based on the type of literal address string and the valueof the af argument. The two simple cases are when name is a dotted-decimalIPv4 address and af equals AF INET, or when name is an IPv6 hex address andaf equals AF INET6. The members of the returned hostent structure are: h namepoints to a copy of the name argument, h aliases is a NULL pointer, h addrtypeis a copy of the af argument, h length is either 4 (for AF INET) or 16 (forAF INET6), h addr list[0] is a pointer to the 4-byte or 16-byte binary address,and h addr list[1] is a NULL pointer.

When name is a dotted-decimal IPv4 address and af equals AF INET6, andAI V4MAPPED is specified, an IPv4-mapped IPv6 address is returned: h name pointsto an IPv6 hex address containing the IPv4-mapped IPv6 address, h aliases is aNULL pointer, h addrtype is AF INET6, h length is 16, h addr list[0] is a pointerto the 16-byte binary address, and h addr list[1] is a NULL pointer.

It is an error when name is an IPv6 hex address and af equals AF INET. The func-tion’s return value is a NULL pointer and the value pointed to by error num equalsHOST NOT FOUND.

getipnodebyaddr() takes almost the same argument as gethostbyaddr(3), butadds a pointer to return an error number. Additionally it takes care of IPv4-mappedIPv6 addresses, and IPv4-compatible IPv6 addresses.

getipnodebyname() and getipnodebyaddr() dynamically allocate the structureto be returned to the caller. freehostent() reclaims the memory region allocatedand returned by getipnodebyname() or getipnodebyaddr().

DIAGNOSTICS

getipnodebyname() and getipnodebyaddr() return NULL on errors. The integervalues pointed by error num may then be checked to see if this is a temporary failure

Systems/C C Library 809

Page 828: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

or an invalid or unknown host. The meanings of each error code are described ingethostbyname(3).

SEE ALSO

gethostbyname(3), gethostbyaddr(3)

R. Gilligan, S. Thomson, J. Bound, and W. Stevens, “Basic Socket Interface Exten-sions for IPv6”, RFC2553, March 1999.

STANDARDS

getipnodebyname() and getipnodebyaddr() are documented in “Basic SocketInterface Extensions for IPv6” (RFC2553).

ISSUES

getipnodebyname() and getipnodebyaddr() do not handle scoped IPv6 addressproperly. If you use these functions, your program will not be able to handle scopedIPv6 addresses. For IPv6 address manipulation, getaddrinfo(3) and getnameinfo(3)are recommended.

The current implementation is not thread-safe.

810 Systems/C C Library

Page 829: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

GETNAMEINFO(3)

NAME

getnameinfo – socket address structure to hostname and service name

SYNOPSIS

#include <sys/types.h>#include <sys/socket.h>#include <netdb.h>

intgetnameinfo(const struct sockaddr *sa, socklen_t salen, char *host,

size_t hostlen, char *serv, size_t servlen, int flags);

DESCRIPTION

The getnameinfo() function is used to convert a sockaddr structure to a pair ofhost name and service strings. It is a replacement for and provides more flexibilitythan the gethostbyaddr(3) and getservbyport(3) functions and is the converse of thegetaddrinfo(3)) function.

The sockaddr structure sa should point to either a sockaddr in or sockaddr in6structure (for IPv4 or IPv6 respectively) that is salen bytes long.

The host and service names associated with sa are stored in host and serv whichhave length parameters hostlen and servlen. The maximum value for hostlenis NI MAXHOST and the maximum value for servlen is NI MAXSERV, as defined by<netdb.h>. If a length parameter is zero, no string will be stored. Otherwise,enough space must be provided to store the host name or service string plus a bytefor the NUL terminator.

The flags argument is formed by OR’ing the following values:

NI NOFQDN A fully qualified domain name is not required for local hosts.The local part of the fully qualified domain name is returnedinstead.

NI NUMERICHOST Return the address in numeric form, as if callinginet ntop(3)), instead of a host name.

NI NAMEREQD A name is required. If the host name cannot be found inDNS and this flag is set, a non-zero error code is returned. Ifthe host name is not found and the flag is not set, the addressis returned in numeric form.

Systems/C C Library 811

Page 830: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

NI NUMERICSERV The service name is returned as a digit string representingthe port number.

NI DGRAM Specifies that the service being looked up is a datagram ser-vice, and causes getservbyport(3)) to be called with a secondargument of “udp” instead of its default of “tcp”. This is re-quired for the few ports (512-514) that have different servicesfor UDP and TCP.

This implementation allows numeric IPv6 address notation with scope identifier,as documented in chapter 11 of draft-ietf-ipv6-scoping-arch-02.txt. IPv6 link-localaddress will appear as a string like “fe80::1%ne0”. Refer to getaddrinfo(3) for moreinformation.

RETURN VALUES

getnameinfo() returns zero on success or one of the error codes listed ingai strerror(3) if an error occurs.

EXAMPLES

The following code tries to get a numeric host name, and service name, for a givensocket address. Observe that there is no hardcoded reference to a particular addressfamily.

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 a reverse address mapping:

struct sockaddr *sa; /* input */char hbuf[NI_MAXHOST];

if (getnameinfo(sa, sa->sa_len, hbuf, sizeof(hbuf), NULL, 0,NI_NAMEREQD)) {

errx(1, "could not resolve hostname");

812 Systems/C C Library

Page 831: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

/*NOTREACHED*/}printf("host=%s\n", hbuf);

SEE ALSO

gai strerror(3), getaddrinfo(3), gethostbyaddr(3), getservbyport(3) inet ntop(3), re-solver(3)

R. Gilligan, S. Thomson, J. Bound, and W. Stevens, Basic Socket Interface Exten-sions for IPv6, RFC 2553, March 1999.

S. Deering, B. Haberman, T. Jinmei, E. Nordmark, and B. Zill, IPv6 Scoped AddressArchitecture, internet draft, draft-ietf-ipv6-scoping- arch-02.txt, work in progressmaterial.

Craig Metz, “Protocol Independence Using the Sockets API”, Proceedings of thefreenix track: 2000 USENIX annual technical conference, June 2000.

STANDARDS

The getnameinfo() function is defined by the IEEE Std 1003.1g-2000 (“POSIX.1”)draft specification and documented in RFC 2553, “Basic Socket Interface Extensionsfor IPv6”.

CAVEATS

getnameinfo() can return both numeric and FQDN forms of the address specifiedin sa. There is no return value that indicates whether the string returned in host isa result of binary to numeric-text translation (like inet ntop(3)), or is the result ofa DNS reverse lookup. Because of this, malicious parties could set up a PTR recordas follows:

1.0.0.127.in-addr.arpa. IN PTR 10.1.1.1

and trick the caller of getnameinfo() into believing that sa is 10.1.1.1 when it isactually 127.0.0.1.

To prevent such attacks, the use of NI NAMEREQD is recommended when the resultof getnameinfo() is used for access control purposes:

struct sockaddr *sa;socklen_t salen;

Systems/C C Library 813

Page 832: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

char addr[NI_MAXHOST];struct addrinfo hints, *res;int error;

error = getnameinfo(sa, salen, addr, sizeof(addr),NULL, 0, NI_NAMEREQD);

if (error == 0) {memset(&hints, 0, sizeof(hints));hints.ai_socktype = SOCK_DGRAM; /*dummy*/hints.ai_flags = AI_NUMERICHOST;if (getaddrinfo(addr, "0", &hints, &res) == 0) {/* malicious PTR record */freeaddrinfo(res);printf("bogus PTR record\n");return -1;}/* addr is FQDN as a result of PTR lookup */} else {/* addr is numeric string */error = getnameinfo(sa, salen, addr, sizeof(addr),

NULL, 0, NI_NUMERICHOST);}

814 Systems/C C Library

Page 833: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

GETNETENT(3)

NAME

getnetent, getnetbyaddr, getnetbyname, setnetent, endnetent - get network entry

SYNOPSIS

#include <netdb.h>struct netent *getnetent(void)

struct netent *getnetbyname(const char *name)

struct netent *getnetbyaddr(unsigned long net, int type)

voidsetnetent(int stayopen)

voidendnetent(void)

DESCRIPTION

The getnetent(), getnetbyname(), and getnetbyaddr() functions each returna pointer to an object with the following structure, containing the broken-out fieldsof a line in the network data base.

struct netent {char *n_name; /* official */

/* name of net */char **n_aliases; /* alias list */int n_addrtype; /* net */

/* number type */unsigned long n_net; /* net number */

};

The members of this structure are:

n name The official name of the network.

Systems/C C Library 815

Page 834: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

n aliases A zero terminated list of alternate names for the network.

n addrtype The type of the network number returned; currently onlyAF INET.

n net The network number. Network numbers are return in machine

The getnetent() function reads the next line of the file, opening the file if necessary.

The setnetent() function opens and rewinds the file. If the stayopen flag is non-zero, the net data base will not be closed after each call to getnetbyname() orgetnetbyaddr().

The endnetent() function closes the file.

The getnetbyname() function and getnetbyaddr() sequentially search from thebeginning of the file until a matching net name or net address and type is found, oruntil EOF is encountered. The type must be AF INET. Network numbers are suppliedin host order.

FILES

These functions use the algorithm described in the IBM TCP/IP documentation tolocate the TCPIP.DATA, and ETC.NETWORKS files.

DIAGNOSTICS

A NULL pointer (0) is returned on EOF or error.

SEE ALSO

RFC 1101

ISSUES

The data space used by these functions is static; if future use requires the data, itshould be copied before any subsequent calls to these functions overwrite it. OnlyInternet network numbers are currently understood. Expecting network numbers tofit in no more than 32 bits is probably naive.

816 Systems/C C Library

Page 835: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

GETPROTOENT(3)

NAME

getprotoent, getprotobynumber, getprotobyname, setprotoent, endprotoent - getprotocol entry.

SYNOPSIS

#include <netdb.h>struct protoent *getprotoent(void)

struct protent *getprotobyname(const char *name)

struct protoent *getprotobynumber(int proto)

voidsetprotoent(int stayopen)

voidendprotoent(void)

DESCRIPTION

The getprotoent(), getprotobyname(), and getprotobynumber() functionseach return a pointer to an object with the following structure containing the broken-out fields of a line in the network protocol data base.

struct protoent {char *p_name; /* official name */

/* of protocol */char **p_aliases; /* alias list */int p_proto; /* protocol number */

};

The members of this structure are:

p name The official name of the protocol.

p aliases A zero terminated list of alternate names for the protocol.

Systems/C C Library 817

Page 836: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

p proto The protocol number.

The getprotoent() function reads the next line of the file, opening the file if nec-essary.

The setprotoent() function opens and rewinds the file. If the stayopen flag is non-zero, the net data base will not be closed after each call to getprotobyname() orgetprotobynumber().

The endprotoen() function closes the file.

The getprotobyname(0 function and getprotobynumber(0 function sequentiallysearch from the beginning of the file until a matching protocol name or protocolnumber is found, or until EOF is encountered.

RETURN VALUES

The NULL pointer (0) is returned on EOF or error.

FILES

These functions use the algorithm described in the IBM TCP/IP documentation tolocate the TCPIP.DATA, and ETC.PROTOCOLS files.

ISSUES

These functions use a static data space; if the data is needed for future use, it shouldbe copied before any subsequent calls overwrite it. Only the Internet protocols arecurrently understood.

818 Systems/C C Library

Page 837: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

GETSERVENT(3)

NAME

getservent, getservbyport, getservbyname, setservent, endservent - get service entry.

SYNOPSIS

#include <netdb.h>struct servent *getservent()

struct servent *getservbyname(const char *name, const char *proto)

struct servent *getservbyport(int port, const char *proto)

voidsetservent(int stayopen)

voidendservent(void)

DESCRIPTION

The getservent(), getservbyname(), and getservbyport() functions each re-turn a pointer to an object with the following structure containing the broken-outfields of a line in the network services data base.

struct servent {char *s_name; /* official name */

/* of service */char **s_aliases; /* alias list */int s_port; /* port service */

/* resides at */char *s_proto; /* protocol to use */

};

The members of this structure are:

s name The official name of the service.

Systems/C C Library 819

Page 838: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

s aliases A zero terminated list of alternate names for the service.

s port The port number at which the service resides. Port numbers arereturned in network byte order.

s proto The name of the protocol to use when contacting the service.

The getservent() function reads the next line of the file, opening the file if neces-sary.

The setservent() function opens and rewinds the file. If the stayopen flag is non-zero, the net data base will not be closed after each call to getservbyname() orgetservbyent().

The endservent() function closes the file.

The getservbyname() and getservbyport() functions sequentially search fromthe 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), searchesmust also match the protocol.

FILES

These functions use the algorithm described in the IBM TCP/IP documentation tolocate the TCPIP.DATA, and ETC.SERVICES files. If that file cannot be located, thesefunctions will look for //HFS:/etc/services.

DIAGNOSTICS

The NULL pointer (0) is returned on EOF or error.

SEE ALSO

getprotoent(3)

ISSUES

These functions use static data storage; if the data is needed for future use, it shouldbe copied before any subsequent calls overwrite it. Expecting port numbers to fitin a 32 bit quantity is probably naive.

820 Systems/C C Library

Page 839: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

INET(3)

NAME

inet aton, inet addr, inet network, inet ntoa, inet makeaddr, inet lnaof, inet netof -Internet address manipulation routines.

SYNOPSIS

#include <sys/types.h>#include <sys/socket.h>#include <netinet/in.h>#include <arpa/inet.h>

intinet_aton(const char *cp, struct in_addr *pin)

unsigned longinet_addr(const char *cp)

unsigned longinet_network(const char *cp)

char *inet_ntoa(struct in_addr in)

struct in_addrinet_makeaddr(unsigned long net, unsigned long lna)

unsigned longinet_lnaof(struct in_addr in)

unsigned longinet_netof(struct in_addr in)

DESCRIPTION

The routines inet aton(), inet addr() and inet network() interpret characterstrings representing numbers expressed in the Internet standard ’.’ notation. Theinet aton() routine interprets the specified character string as an Internet ad-dress, placing the address into the structure provided. It returns 1 if the stringwas successfully interpreted, or 0 if the string is invalid. The inet addr(0 andinet network(0 functions return numbers suitable for use an Internet addresses andInternet network numbers, respectively. The routine inet ntoa() takes an Inter-net address and returns a string representing the address in ’.’ notation. The

Systems/C C Library 821

Page 840: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

routine inet makeaddr() takes an Internet network number and a local networkaddress and constructs an Internet address from it. The routines inet netof() andinet lnaof() break apart Internet host addresses, returning the network numberand local network address part, respectively.

All Internet addresses are returned in network order (bytes ordered from left toright.) All network numbers and local address parts are returned as machine formatinteger values.

INTERNET ADDRESSES

Values specified using the ’.’ notation take one of the following forms:

a.b.c.da.b.ca.ba

When four parts are specified, each is interpreted as a byte of data and assigned,from left to right, to the four bytes of an Internet address. Note that when anInternet addresses is viewed as a 32-bit integer quantity appear in host byte order.

When a three part address is specified, the last part is interpreted as a 16-bit quantityand placed in the right-most two bytes of the network address. This makes thethree part address format convenient for specifying Class B network addresses as“128.net.host”.

When a two part address is supplied, the last part is interpreted as a 24-bit quantityand placed in the right most three bytes of the network address. This makes thetwo part address format convenient for specifying Class A network addresses as“net.host”.

When only one part is given, the value is stored directly in the network addresswithout any byte rearrangement.

All numbers supplied as “parts” in a ’.’ notation may be decimal, octal, or hexadec-imal, as specified in the C language (I.e., a leading 0x or 0X implies hexadecimal;otherwise, a leading 0 implies octal; otherwise the number is interpreted as decimal.)

The inet aton() and inet ntoa() functions are semi-deprecated in favor of theaddr2ascii(3) family. However, since those functions are not yet widely implemented,portable programs cannot rely on their presence and will continue to use the inet(3)functions for some time.

822 Systems/C C Library

Page 841: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

DIAGNOSTICS

The constant INADDR NONE is returned by inet addr() and inet network() formalformed requests.

SEE ALSO

addr2ascii(3), gethostbyname(3), getnetent(3)

ISSUES

The value INADDR NONE (0xffffffff) is a valid broadcast address, but inet addr()cannot return that value without indicating failure. The newer inet aton() functiondoes not share this problem. The problem of host byte ordering versus network byteordering is confusing. The string returned by inet ntoa() resides in a static memoryarea.

inet addr() should return a struct in addr .

Systems/C C Library 823

Page 842: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

NS(3)

NAME

ns addr, ns ntoa - Xerox NS address conversion routines

SYNOPSIS

#include <sys/types.h>#include <nets/ns.h>

struct ns_addrns_addr(char *cp)

char *ns_ntoa(struct ns_addr ns)

DESCRIPTION

The routine ns addr() interprets character strings representing XNS addresses,returning binary information suitable for use in system calls. The routine ns ntoa()takes XNS addresses and returns strings representing the address in a notation incommon use in the Xerox Development Environment:

<network number>.<host number>.<port number>

Trailing zero fields are suppressed, and each number is printed in hexadecimal, in aformat suitable for input to ns addr(). Any fields lcaking super-decimal digits willhave a trailing ’H’ appended.

Unfortunately, no universal standard exists for representing XNS addresses. Aneffort has been made to insure that ns addr() be compatible with most formats incommon use. It will first separate an address into 1 to 3 fields using a single delimiterchosen from period ’.’ , colon ’:’ or pound-sign ’#’. Each field is then examinedfor byte separators (colon or period.) If there are byte separators, each subfieldseparated is taken to be a small hexadecimal number, and the entirety is taken as anetwork-byte-ordered quantity to be zero extended in the high-network-order bytes.Next, the field is inspected for hyphens, in which case the field is assumed to be anumber in decimal notation with hyphens separating the millennia. Next, the fieldis assumed to be a number: It is interpreted as hexadecimal if there is a leading ’0x’(as in C), a trailing ’H’ (as in Mesa), or there are any super-decimal digits present.It is interpreted as octal if there is a leading ’0’ and there are no super-octal digits.Otherwise, it is converted as a decimal number.

824 Systems/C C Library

Page 843: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

RETURN VALUES

None. (See ISSUES.)

ISSUES

The string returned by ns ntoa() resides in a static memory area. The functionns addr() should diagnose improperly formed input, and there should be an un-ambiguous way to recognize this.

Systems/C C Library 825

Page 844: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

RESOLVER(3)

NAME

res query, res search, res mkquery, res send, res init, dn comp, dn expand - resolverroutines

SYNOPSIS

#include <sys/types.h>#include <netinet/in.h>#include <arpa/nameser.h>#include <resolv.h>

intres_query(const char *dname, int class, int type,u_char *answer, int anslen)

intres_search(const char *dname, int class, int type,u_char *answer, int anslen)

intres_mkquery(int op, const char *dname, int class,int type, const u_char *data, int datalen,const u_char *newer_in, u_char *buf,int buflen)

intres_send(const u_char *msg, int msglen, u_char *answer,int anslen)

intres_init()

dn_comp(const char *exp_dn, u_char *comp_dn, int length,u_char **dnptrs, u_char **lastdnptr)

intdn_expand(const u_char *msg, const u_char *eomorig,const u_char *comp_dn, char *exp_dn,int length)

826 Systems/C C Library

Page 845: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

DESCRIPTION

These routines are used for making, sending and interpreting query and reply mes-sages with Internet domain name servers.

Global configuration and state information that is used by the resolver routines iskept in the structure res. Most of the values have reasonable defaults and can beignored. Options stored in res.otions are defined in resolv.h and are as follows.Options are stored as a simple bit mask containing the bitwise ‘or’ of the optionsenabled.

RES INIT True if the initial name server address and default domainname are initialized (i.e., res init() has been called.)

RES DEBUG Print debugging messages.

RES AAONLY Accept authoritative answers only. With this option,res send() should continue until it finds an authoritativeanswer or finds an error. Currently this is not implemented.

RES USEVC Use TCP connections for queries instead of UDP datagrams.

RES STAYOPEN Used with RES USEVC to keep the TCP connection open be-tween queries. This is useful only in programs that regularlydo many queries. UDP should be the normal mode used.

RES IGNTC Unused currently (ignore truncation errors, I.e., don’t retrywith TCP.)

RES RECURSE Set the recursion-desired bit in queries. This is the default.(res send() does not do iterative queries and expects thename server to handle recursion.)

RES DEFNAMES If set, res search() will append the default domain name tosingle-component names (those that do not contain a dot.)This option is enabled by default.

RES DNSRCH If this option is set, res search() will search for host namesin the current domain and in parent domains. This is usedby the standard host lookup routine gethostbyname(3). Thisoption is enabled by default.

RES NOALIASES This option turns off the user level aliasing feature con-trolled by the “HOSTALIASES” environment variable. Net-work demons should set this option.

The res init() routine reads the configuration file to get the default domain name,search list and the Internet address of the local name server(s). If no server isconfigured the host running the resolver is tried. The current domain name is defined

Systems/C C Library 827

Page 846: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

by the hostname if not specified in the configuration file; it can be overridden by theenvironment variable LOCALDOMAIN. This environment variable may contain severalblank-separated tokens if you with to override the search list on a per-process basis.This is similar to the search command in the configuration file. Another environmentvariable “RES OPTIONS” can be set to override certain internal resolver options whichare otherwise set by changing fields in the res structure or are inherited fromthe configuration file. Initialization normally occurs on the first call to one of thefollowing routines.

The res query() function provides an interface to the server query mechanism.It constructs a query, sends it to the local server, awaits a response, and makespreliminary checks on the reply. The query requests information of the specified typeand class for the specified fully-qualified domain name dname. The reply messageis left in the answer buffer with length anslen supplied by the caller.

The res search() routine makes a query and awaits a response like res query(),but in addition, it implements the default and search rules controlled by theRES DEFNAMES and RES DNSRCH options. It returns the first successful reply.

The remaining routines are lower-level routines used by res query(). Theres mkquery() function constructs a standard query message and places it inbuf. It returns the size of the query, or -1 if the query is larger than buflen.The query type op is usually QUERY, but can be any of the query types defined in<arpa/nameserv.h>. The domain name for the query is given by dname. Newer inis currently unused but is intended for making update messages.

The res send() routine sends a pre-formatted query and returns an answer. It willcall res init() if RES INIT is not set, send the query to the local name server, andhandle timeouts and retries. The length of the reply message is returned, or -1 ifthere were errors.

The dn comp() function compresses the domain name exp dn and stores it incomp dn. The size of the compressed name is returned or -1 if there were errors.The size of the array pointed to be comp dn is given by length The compression usesan 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 withNULL. The limit to the array is specified by lastdnptr. A side effect of dn comp()is to update the list of pointers for labels inserted into the message as the name iscompressed. If dnptr is NULL, the list of labels is not updated.

The dn expand() entry expands the compressed domain name comp dn to a fulldomain name. The compressed name is contained in a query or reply message; msgis a pointer to the beginning of the message. The uncompressed name is placed inthe buffer indicated by exp dn which is of size length. The size of the compressedname is returned or -1 if there was an error.

828 Systems/C C Library

Page 847: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

FILES

These functions use the algorithm described in the IBM TCP/IP documentation tolocate the TCPIP.DATA, and ETC.RESOLV.CONF files.

SEE ALSO

gethostbyname(3)

RFC1032, RFC1033, RFC1034, RFC1035, RFC974

Thread Library

Systems/C C Library 829

Page 848: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

PTHREAD(3)

NAME

pthread – POSIX thread functions

SYNOPSIS

#include <pthread.h>

DESCRIPTION

POSIX threads are a set of functions that support applications with requirementsfor multiple flows of control, called threads, within a process. Multithreading is usedto improve the performance of a program.

The POSIX thread functions are summarized in this section in the following groups:

o Thread Routines

o Attribute Object Routines

o Mutex Routines

o Condition Variable Routines

o Read/Write Lock Routines

o Per-Thread Context Routines

o Cleanup Routines

Thread Routines

int pthread_create(pthread_t *thread, const pthread_attr_t *attr,void *(*start_routine)(void *), void *arg)

Creates a new thread of execution.

int pthread_cancel(pthread_t thread)

Cancels execution of a thread.

830 Systems/C C Library

Page 849: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

int pthread_detach(pthread_t thread)

Marks a thread for deletion.

int pthread_equal(pthread_t t1, pthread_t t2)

Compares two thread IDs.

void pthread_exit(void *value_ptr)

Terminates the calling thread.

int pthread_join(pthread_t thread, void **value_ptr)

Causes the calling thread to wait for the termination of the specified thread.

int pthread_kill(pthread_t thread, int sig)

Delivers a signal to a specified thread.

int pthread_once(pthread_once_t *once_control, void (*init_routine)(void))

Calls an initialization routine once.

pthread_t pthread_self(void)

Returns the thread ID of the calling thread.

int pthread_setcancelstate(int state, int *oldstate)

Sets the current thread’s cancelability state.

int pthread_setcanceltype(int type, int *oldtype)

Sets the current thread’s cancelability type.

Systems/C C Library 831

Page 850: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

int pthread_set_limit_np(int action, int maxtasks, int maxthreads)

Sets the z/OS maximum number of tasks allowed and/or maximum number ofthreads for the process.

void pthread_testcancel(void)

Creates a cancellation point in the calling thread.

void pthread_yield(void)

Allows the scheduler to run another thread instead of the current one.

Attribute Object Routines

int pthread_attr_destroy(pthread_attr_t *attr)

Destroy a thread attributes object.

int pthread_attr_getinheritsched(const pthread_attr_t *attr,int *inheritsched)

Get the inherit scheduling attribute from a thread attributes object.

int pthread_attr_getschedparam(const pthread_attr_t *attr,struct sched_param *param)

Get the scheduling parameter attribute from a thread attributes object.

int pthread_attr_getschedpolicy(const pthread_attr_t *attr, int *policy)

Get the scheduling policy attribute from a thread attributes object.

int pthread_attr_getscope(const pthread_attr_t *attr, int*contentionscope)

Get the contention scope attribute from a thread attributes object.

832 Systems/C C Library

Page 851: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

int pthread_attr_getstacksize(const pthread_attr_t *attr, size_t*stacksize)

Get the stack size attribute from a thread attributes object.

int pthread_attr_getstackaddr(const pthread_attr_t *attr, void**stackaddr)

Get the stack address attribute from a thread attributes object.

int pthread_attr_getdetachstate(const pthread_attr_t *attr, int*detachstate)

Get the detach state attribute from a thread attributes object.

int pthread_attr_getweight_np(const pthread_attr_t *attr,int *weight);

Get the thread weight.

int pthread_attr_getsynctype_np(const pthread_attr_t *attr, int*synctype);

Get the thread sync type.

int pthread_attr_init(pthread_attr_t *attr)

Initialize a thread attributes object with default values.

int pthread_attr_setinheritsched(pthread_attr_t *attr,int inheritsched)

Set the inherit scheduling attribute in a thread attributes object.

int pthread_attr_setschedparam(pthread_attr_t *attr,const struct sched_param *param)

Set the scheduling parameter attribute in a thread attributes object.

Systems/C C Library 833

Page 852: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

int pthread_attr_setschedpolicy(pthread_attr_t *attr, int policy)

Set the scheduling policy attribute in a thread attributes object.

int pthread_attr_setscope(pthread_attr_t *attr,int contentionscope)

Set the contention scope attribute in a thread attributes object.

int pthread_attr_setstacksize(pthread_attr_t *attr,size_t stacksize)

Set the stack size attribute in a thread attributes object.

int pthread_attr_setstackaddr(pthread_attr_t *attr, void *stackaddr)

Set the stack address attribute in a thread attributes object.

int pthread_attr_setdetachstate(pthread_attr_t *attr, int detachstate)

Set the detach state in a thread attributes object.

int pthread_attr_setweight_np(pthread_attr_t *attr, int weight)

Set the weight in a thread attributes object.

int pthread_attr_setsynctype_np(pthread_attr_t *attr, int type)

Set the synctype in a thread attributes object.

Mutex Routines

int pthread_mutexattr_destroy(pthread_mutexattr_t *attr)

Destroy a mutex attributes object.

834 Systems/C C Library

Page 853: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

int pthread_mutexattr_getprioceiling(pthread_mutexattr_t *attr, int*ceiling)

Obtain priority ceiling attribute of mutex attribute object.

int pthread_mutexattr_getprotocol(pthread_mutexattr_t *attr, int*protocol)

Obtain protocol attribute of mutex attribute object.

int pthread_mutexattr_gettype(pthread_mutexattr_t *attr, int *type)

Obtain the mutex type attribute in the specified mutex attributes object.

int pthread_mutexattr_init(pthread_mutexattr_t *attr)

Initialize a mutex attributes object with default values.

int pthread_mutexattr_setprioceiling(pthread_mutexattr_t *attr, intceiling)

Set priority ceiling attribute of mutex attribute object.

int pthread_mutexattr_setprotocol(pthread_mutexattr_t *attr, intprotocol)

Set protocol attribute of mutex attribute object.

int pthread_mutexattr_settype(pthread_mutexattr_t *attr, int type)

Set the mutex type attribute that is used when a mutex is created.

int pthread_mutex_destroy(pthread_mutex_t *mutex)

Destroy a mutex.

int pthread_mutex_init(pthread_mutex_t *mutex,const pthread_mutexattr_t *attr)

Systems/C C Library 835

Page 854: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

Initialize a mutex with specified attributes.

int pthread_mutex_lock(pthread_mutex_t *mutex)

Lock a mutex and block until it becomes available.

int pthread_mutex_timedlock(pthread_mutex_t *mutex,const struct timespec *abstime)

Lock a mutex and block until it becomes available or until the timeout expires.

int pthread_mutex_trylock(pthread_mutex_t *mutex)

Try to lock a mutex, but do not block if the mutex is locked by another thread,including the current thread.

int pthread_mutex_unlock(pthread_mutex_t *mutex)

Unlock a mutex.

Condition Variable Routines

int pthread_condattr_destroy(pthread_condattr_t *attr)

Destroy a condition variable attributes object.

int pthread_condattr_init(pthread_condattr_t *attr)

Initialize a condition variable attributes object with default values.

int pthread_cond_broadcast(pthread_cond_t *cond)

Unblock all threads currently blocked on the specified condition variable.

int pthread_cond_destroy(pthread_cond_t *cond)

836 Systems/C C Library

Page 855: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

Destroy a condition variable.

int pthread_cond_init(pthread_cond_t *cond, const pthread_condattr_t*attr)

Initialize a condition variable with specified attributes.

int pthread_cond_signal(pthread_cond_t *cond)

Unblock at least one of the threads blocked on the specified condition variable.

int pthread_cond_timedwait(pthread_cond_t *cond, pthread_mutex_t *mutex,const struct timespec *abstime)

Wait no longer than the specified time for a condition and lock the specified mutex.

int pthread_cond_wait(pthread_cond_t *, pthread_mutex_t *mutex)

Wait for a condition and lock the specified mutex.

Read/Write Lock Routines

int pthread_rwlock_destroy(pthread_rwlock_t *lock)

Destroy a read/write lock object.

int pthread_rwlock_init(pthread_rwlock_t *lock,const pthread_rwlockattr_t *attr)

Initialize a read/write lock object.

int pthread_rwlock_rdlock(pthread_rwlock_t *lock)

Lock a read/write lock for reading, blocking until the lock can be acquired.

int pthread_rwlock_tryrdlock(pthread_rwlock_t *lock)

Systems/C C Library 837

Page 856: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

Attempt to lock a read/write lock for reading, without blocking if the lock is un-available.

int pthread_rwlock_trywrlock(pthread_rwlock_t *lock)

Attempt to lock a read/write lock for writing, without blocking if the lock is un-available.

int pthread_rwlock_unlock(pthread_rwlock_t *lock)

Unlock a read/write lock.

int pthread_rwlock_wrlock(pthread_rwlock_t *lock)

Lock a read/write lock for writing, blocking until the lock can be acquired.

int pthread_rwlockattr_destroy(pthread_rwlockattr_t *attr)

Destroy a read/write lock attribute object.

int pthread_rwlockattr_getpshared(const pthread_rwlockattr_t *attr,int *pshared)

Retrieve the process shared setting for the read/write lock attribute object.

int pthread_rwlockattr_init(pthread_rwlockattr_t *attr)

Initialize a read/write lock attribute object.

int pthread_rwlockattr_setpshared(pthread_rwlockattr_t *attr,int pshared)

Set the process shared setting for the read/write lock attribute object.

838 Systems/C C Library

Page 857: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

Per-Thread Context Routines

int pthread_key_create(pthread_key_t *key, void (*routine)(void *))

Create a thread-specific data key.

int pthread_key_delete(pthread_key_t key)

Delete a thread-specific data key.

void * pthread_getspecific(pthread_key_t key)

Get the thread-specific value for the specified key.

int pthread_setspecific(pthread_key_t key, const void *value_ptr)

Set the thread-specific value for the specified key.

Cleanup Routines

int pthread_atfork(void (*prepare)(void), void (*parent)(void),void (*child)(void))

Register fork handlers

void pthread_cleanup_pop(int execute)

Remove the routine at the top of the calling thread’s cancellation cleanup stack andoptionally invoke it.

void pthread_cleanup_push(void (*routine)(void *), void *routine_arg)

Push the specified cancellation cleanup handler onto the calling thread’s cancellationstack.

Systems/C C Library 839

Page 858: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

IMPLEMENTATION

The Dignus POSIX thread implementation depends on z/OS UNIX Systems Ser-vices. Linking a program with the pthread create(3) forces the use of UNIX SystemsServices signal handling. Also, such a program ends with a call to the BPX exit(2)function and not by returning to the caller.

The implementation defaults ”heavy” weight threads, where a single z/OS TASKper thread is used. The weight of a thread can be set before its creation usingpthread attr setweight np(). If the thread is set to ”medium” then a task canexecute the next thread without ending.

IBM recommends that only about 200 tasks be used per process. Thepthread set limit np() function can be used to indicate how many tasks are al-lowed per process. If too many tasks are initiated, there can problems with low-memory usage in the LQSA area, which can cause S422 ABENDs or other MVSinternal errors. If the operating system reports the error, the Dignus runtime willreturn an error code of EMVSERR, otherwise the task or program may simply be ter-minated, with appropriate messages on the console log. This situation should bereported to the system managers and or IBM, as it may indicate a problem withz/OS internal functions.

The z/OS object file format and Dignus runtime does not support Thread LocalStorage (TLS).

SEE ALSO

pthread atfork(3), pthread cleanup pop(3), pthread cleanup push(3),pthread condattr destroy(3), pthread condattr init(3), pthread cond broadcast(3),pthread cond destroy(3), pthread cond init(3), pthread cond signal(3),pthread cond timedwait(3), pthread cond wait(3), pthread create(3),pthread detach(3), pthread equal(3), pthread exit(3), pthread getspecific(3),pthread join(3), pthread key delete(3), pthread kill(3),pthread mutexattr destroy(3), pthread mutexattr getprioceiling(3),pthread mutexattr getprotocol(3), pthread mutexattr gettype(3),pthread mutexattr init(3), pthread mutexattr setprioceiling(3),pthread mutexattr setprotocol(3), pthread mutexattr settype(3),pthread mutex destroy(3), pthread mutex init(3), pthread mutex lock(3),pthread mutex trylock(3), pthread mutex unlock(3), pthread once(3),pthread rwlockattr destroy(3), pthread rwlockattr getpshared(3),pthread rwlockattr init(3), pthread rwlock unlock(3), pthread rwlock wrlock(3),pthread self(3), pthread setcancelstate(3), pthread setcanceltype(3),pthread setspecific(3), pthread testcancel(3) pthread set limit np(3).

840 Systems/C C Library

Page 859: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

STANDARDS

The functions with the pthread prefix and not np suffix or pthread rwlock prefixconform to ISO/IEC 9945-1:1996 (“POSIX.1”).

The functions with the pthread prefix and np suffix are non-portable extensionsto POSIX threads.

The functions with the pthread rwlock prefix are extensions created by The OpenGroup as part of the Version 2 of the Single UNIX Specification (“SUSv2”).

Systems/C C Library 841

Page 860: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

PTHREAD ATFORK(3)

NAME

pthread atfork – register fork handlers

SYNOPSIS

#include <pthread.h>

intpthread_atfork(void (*prepare)(void), void (*parent)(void),

void (*child)(void));

DESCRIPTION

The pthread atfork() function declares handler functions to be called before andafter fork(2), in the context of the thread that called fork(2).

The handler functions registered with pthread atfork() are called at the momentsand contexts described below:

prepare Before fork(2) processing commences in the parent process. If morethan one prepare handler is registered they will be called in theopposite order they were registered.

parent After fork(2) completes in the parent process. If more than oneparent handler is registered they will be called in the same orderthey were registered.

child After fork(2) processing completes in the child process. If more thanone child handler is registered they will be called in the same orderthey were registered.

If no handling is desired at one or more of these three points, a NULL pointer maybe passed as the corresponding fork handler function address.

RETURN VALUES

If successful, the pthread atfork() function will return zero. Otherwise an errornumber will be returned to indicate the error.

842 Systems/C C Library

Page 861: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

ERRORS

The pthread atfork() function will fail if:

[ENOMEM] Insufficient memory space exists to record the fork handler ad-dress(es).

SEE ALSO

fork(2), pthread(3)

STANDARDS

The pthread atfork() function is expected to conform to IEEE Std 1003.1(“POSIX.1”).

Systems/C C Library 843

Page 862: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

PTHREAD ATTR(3)

NAME

pthread attr init, pthread attr destroy, pthread attr setstack,pthread attr getstack, pthread attr setstacksize, pthread attr getstacksize,pthread attr setguardsize, pthread attr getguardsize, pthread attr setstackaddr,pthread attr getstackaddr, pthread attr setdetachstate,pthread attr getdetachstate, pthread attr setinheritsched,pthread attr getinheritsched, pthread attr setschedparam,pthread attr getschedparam, pthread attr setschedpolicy,pthread attr getschedpolicy, pthread attr setscope, pthread attr getscope,pthread attr getsynctype np, pthread attr setsynctype np,pthread attr getweight np, pthread attr setweight np - thread attributeoperations

SYNOPSIS

#include <pthread.h>

intpthread_attr_init(pthread_attr_t *attr);

intpthread_attr_destroy(pthread_attr_t *attr);

intpthread_attr_setstack(pthread_attr_t *attr, void *stackaddr,

size_t stacksize);

intpthread_attr_getstack(const pthread_attr_t * restrict attr,

void ** restrict stackaddr, size_t * restrict stacksize);

intpthread_attr_setstacksize(pthread_attr_t *attr, size_t stacksize);

intpthread_attr_getstacksize(const pthread_attr_t *attr, size_t *stacksize);

intpthread_attr_setguardsize(pthread_attr_t *attr, size_t guardsize);

intpthread_attr_getguardsize(const pthread_attr_t *attr, size_t *guardsize);

844 Systems/C C Library

Page 863: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

intpthread_attr_setstackaddr(pthread_attr_t *attr, void *stackaddr);

intpthread_attr_getstackaddr(const pthread_attr_t *attr, void **stackaddr);

intpthread_attr_setdetachstate(pthread_attr_t *attr, int detachstate);

intpthread_attr_getdetachstate(const pthread_attr_t *attr,

int *detachstate);

intpthread_attr_setinheritsched(pthread_attr_t *attr, int inheritsched);

intpthread_attr_getinheritsched(const pthread_attr_t *attr,

int *inheritsched);

intpthread_attr_setschedparam(pthread_attr_t *attr,

const struct sched_param *param);

intpthread_attr_getschedparam(const pthread_attr_t *attr,

struct sched_param *param);

intpthread_attr_setschedpolicy(pthread_attr_t *attr, int policy);

intpthread_attr_getschedpolicy(const pthread_attr_t *attr, int *policy);

intpthread_attr_setscope(pthread_attr_t *attr, int contentionscope);

intpthread_attr_getscope(const pthread_attr_t *attr, int *contentionscope);

intpthread_attr_setweight_np(pthead_attr_t *attr, int weight);

intpthead_attr_getweight_np(pthread_attr_t *attr, int *weight);

int

Systems/C C Library 845

Page 864: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

pthread_attr_setsynctype_np(pthead_attr_t *attr, int synctype);

intpthead_attr_getsynctype_np(pthread_attr_t *attr, int *synctype);

DESCRIPTION

Thread attributes are used to specify parameters to pthread create(). One at-tribute object can be used in multiple calls to pthread create(), with or withoutmodifications between calls.

The pthread attr init() function initializes attr with all the default thread at-tributes.

The pthread attr destroy() function destroys attr.

The pthread attr set*() functions set the attribute that corresponds to each func-tion name.

The pthread attr get*() functions copy the value of the attribute that corre-sponds to each function name to the location pointed to by the second functionparameter.

The pthread attr setweight np() and pthread attr getweight np() controlthe weight of the thread about to created. The weight is either MEDIUM WEIGHTor HEAVY WEIGHT. A MEDIUM WEIGHT indicates that a thread can be executedon the same task as a previous thread, which can alleviate task creation time. AHEAVY WEIGHT thread executes on its own task and when the thread finishes, the

task ends. In the Dignus implementation threads are HEAVY WEIGHT by default.

The pthread attr setsynctype np() and pthread attr getsynctype np()control the synctype of the thread to be created. The synctype is one of:

PTATSYNCHRONOUS A thread can only be created if a task is available (or the max-imum number of threads, if smaller.)

PTATASYNCHRONOUS Threads can be created up to the maximum number of threads.

PTATASYNCHRONOUS threads will be created up to the maximum number of threads.If there are no available tasks, the thread will be queued for execution when an-other thread ends and a task becomes available. Queued threads can be affectedby other pthread functions, but aren’t executing until a task becomes available;which complicates thread coordination. The default value for the Dignus runtimeis PTATSYNCHRONOUS. The pthread set limit np(3) function can be used to controlthe number of tasks and threads for the process.

846 Systems/C C Library

Page 865: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

RETURN VALUES

If successful, these functions return 0. Otherwise, an error number is returned toindicate the error.

ERRORS

The pthread attr init() function will fail if:

[ENOMEM] Out of memory.

The pthread attr destroy() function will fail if:

[EINVAL] Invalid value for attr.

The pthread attr setstacksize() and pthread attr setstack() functions willfail if:

[EINVAL] stacksize is less than PTHREAD STACK MIN.

The pthread attr setdetachstate() function will fail if:

[EINVAL] Invalid value for detachstate.

The pthread attr setinheritsched() function will fail if:

[EINVAL] Invalid value for attr.

The pthread attr setschedparam() function will fail if:

[EINVAL] Invalid value for attr.

[ENOTSUP] Invalid value for param.

The pthread attr setschedpolicy() function will fail if:

[EINVAL] Invalid value for attr.

[ENOTSUP] Invalid value for policy.

Systems/C C Library 847

Page 866: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

The pthread attr setscope() function will fail if:

[EINVAL] Invalid value for attr.

[ENOTSUP] Invalid or unsupported value for contentionscope.

The pthread attr setweight np() function will fail if:

[EINVAL] Invalid value for attr.

The pthread attr setsynctype np() function will fail if:

[EINVAL] Invalid value for attr.

SEE ALSO

pthread create(3), pthread set limit np(3).

IMPLEMENTATION

This implementation does not support the process-shared attribute, nor does itsupport scheduling scope or scheduling attributes.

STANDARDS

pthread attr init(), pthread attr destroy(), pthread attr setstacksize(),pthread attr getstacksize(), pthread attr setstackaddr(),pthread attr getstackaddr(), pthread attr setdetachstate(), andpthread attr getdetachstate() functions conform to ISO/IEC 9945-1:1996(“POSIX.1”)

The pthread attr setinheritsched(), pthread attr getinheritsched(),pthread attr setschedparam(), pthread attr getschedparam(),pthread attr setschedpolicy(), pthread attr getschedpolicy(),pthread attr setscope(), and pthread attr getscope() functions con-form to Version 2 of the Single UNIX Specification (“SUSv2”)

848 Systems/C C Library

Page 867: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

PTHREAD BARRIER(3)

NAME

pthread barrier destroy, pthread barrier init, pthread barrier wait - destroy, initial-ize or wait on a barrier object

SYNOPSIS

#include <pthread.h>

intpthread_barrier_destroy(pthread_barrier_t *barrier);

intpthread_barrier_init(pthread_barrier_t *barrier,

const pthread_barrierattr_t *attr, unsigned count);

intpthread_barrier_wait(pthread_barrier_t *barrier);

DESCRIPTION

The pthread barrier init() function will initialize barrier with attributes specifiedin attr, or if it is NULL, with default attributes. The number of threads that mustcall pthread barrier wait() before any of the waiting threads can be released isspecified by count. The pthread barrier destroy() function will destroy barrierand release any resources that may have been allocated on its behalf.

The pthread barrier wait() function will synchronize calling threads at bar-rier. The threads will be blocked from making further progress until a sufficientnumber of threads calls this function. The number of threads that must callit before any of them will be released is determined by the count argument topthread barrier init(). Once the threads have been released the barrier will bereset.

RETURN VALUES

If successful, both pthread barrier destroy() and pthread barrier init() willreturn zero. Otherwise, an error number will be returned to indicate the error. If thecall to pthread barrier wait() is successful, all but one of the threads will returnzero. That one thread will return PTHREAD BARRIER SERIAL THREAD. Otherwise, anerror number will be returned to indicate the error.

None of these functions will return EINTR.

Systems/C C Library 849

Page 868: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

ERRORS

The pthread barrier destroy() function will fail if:

[EBUSY] An attempt was made to destroy barrier while it was in use.

The pthread barrier destroy() and pthread barrier wait() functions may failif:

[EINVAL] The value specified by barrier is invalid.

The pthread barrier init() function will fail if:

[EAGAIN] The system lacks resources, other than memory, to initialize barrier.

[EINVAL] The count argument is less than 1.

[ENOMEM] Insufficient memory to initialize barrier.

SEE ALSO

pthread barrierattr(3)

850 Systems/C C Library

Page 869: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

PTHREAD BARRIERATTR(3)

NAME

pthread barrierattr destroy, pthread barrierattr getpshared,pthread barrierattr init, pthread barrierattr setpshared - manipulate a bar-rier attribute object

SYNOPSIS

#include <pthread.h>

intpthread_barrierattr_destroy(pthread_barrierattr_t *attr);

intpthread_barrierattr_getpshared(const pthread_barrierattr_t *attr,

int *pshared);

intpthread_barrierattr_init(pthread_barrierattr_t *attr);

intpthread_barrierattr_setpshared(pthread_barrierattr_t *attr, int pshared);

DESCRIPTION

The pthread barrierattr init() function will initialize attr with default attributes.The pthread barrierattr destroy() function will destroy attr and release anyresources that may have been allocated on its behalf.

The pthread barrierattr getpshared() function will put the value of the process-shared attribute from attr into the memory area pointed to by pshared. Thepthread barrierattr setpshared() function will set the process-shared attributeof attr to the value specified in pshared. The argument pshared may have one of thefollowing values:

[PTHREAD PROCESS PRIVATE] The barrier object it is attached to may only be ac-cessed by threads in the same process as the one that created theobject.

[PTHREAD PROCESS SHARED] The barrier object it is attached to may be accessed bythreads in processes other than the one that created the object.

Systems/C C Library 851

Page 870: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

RETURN VALUES

If successful, all these functions will return zero. Otherwise, an error number willbe returned to indicate the error.

None of these functions will return EINTR.

ERRORS

The pthread barrierattr destroy(), pthread barrierattr getpshared() andpthread barrierattr setpshared() functions may fail if:

[EINVAL] The value specified by attr is invalid.

The pthread barrierattr init() function will fail if:

[ENOMEM] Insufficient memory to initialize the barrier attribute object attr.

The pthread barrierattr setpshared() function will fail if:

[EINVAL] The value specified in pshared is not one of the allowed values.

SEE ALSO

pthread barrier destroy(3), pthread barrier init(3), pthread barrier wait(3)

IMPLEMENTATION

This implementation does not support process-shared barriers.

852 Systems/C C Library

Page 871: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

PTHREAD CANCEL(3)

NAME

pthread cancel – cancel execution of a thread

SYNOPSIS

#include <pthread.h>

intpthread_cancel(pthread_t thread);

DESCRIPTION

The pthread cancel() function requests that thread be canceled. The targetthread’s cancelability state and type determines when the cancellation takes effect.When the cancellation is acted on, the cancellation cleanup handlers for thread arecalled. When the last cancellation cleanup handler returns, the thread-specific datadestructor functions will be called for thread. When the last destructor functionreturns, thread will be terminated.

The cancellation processing in the target thread runs asynchronously with respectto the calling thread returning from pthread cancel().

A status of PTHREAD CANCELED is made available to any threads joining with thetarget. The symbolic constant PTHREAD CANCELED expands to a constant expressionof type (void *), whose value matches no pointer to an object in memory nor thevalue NULL.

RETURN VALUES

If successful, the pthread cancel() functions will return zero. Otherwise an errornumber will be returned to indicate the error.

ERRORS

The pthread cancel() function will fail if:

[ESRCH] No thread could be found corresponding to that specified by thegiven thread ID.

Systems/C C Library 853

Page 872: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

SEE ALSO

pthread cleanup pop(3), pthread cleanup push(3), pthread exit(3), pthread join(3),pthread setcancelstate(3), pthread setcanceltype(3), pthread testcancel(3)

STANDARDS

The pthread cancel() function conforms to ISO/IEC 9945-1:1996 (“POSIX.1”).

854 Systems/C C Library

Page 873: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

PTHREAD CLEANUP POP(3)

NAME

pthread cleanup pop – call the first cleanup routine

SYNOPSIS

#include <pthread.h>

voidpthread_cleanup_pop(int execute);

DESCRIPTION

The pthread cleanup pop() function pops the top cleanup routine off of the cur-rent threads cleanup routine stack, and, if execute is non-zero, it will execute thefunction. If there is no cleanup routine then pthread cleanup pop() does nothing.

The pthread cleanup pop() function is required to be in the lexical scope as itscorresponding pthread cleanup push().

RETURN VALUES

The pthread cleanup pop() function does not return any value.

ERRORS

None

SEE ALSO

pthread cleanup push(3), pthread exit(3)

STANDARDS

The pthread cleanup pop() function conforms to ISO/IEC 9945-1:1996(“POSIX.1”).

Systems/C C Library 855

Page 874: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

PTHREAD CLEANUP PUSH(3)

NAME

pthread cleanup push – add a cleanup function for thread exit

SYNOPSIS

#include <pthread.h>

voidpthread_cleanup_push(void (*cleanup_routine)(void *), void *arg);

DESCRIPTION

The pthread cleanup push() function adds cleanup routine to the top of the stackof cleanup handlers that get called when the current thread exits.

When cleanup routine is called, it is passed arg as its only argument.

The pthread cleanup push() function is required to be used in the same lexicalscope as its corresponding pthread cleanup pop().

RETURN VALUES

The pthread cleanup push() function does not return any value.

ERRORS

None

SEE ALSO

pthread cleanup pop(3), pthread exit(3)

STANDARDS

The pthread cleanup push() function conforms to ISO/IEC 9945-1:1996(“POSIX.1”).

856 Systems/C C Library

Page 875: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

PTHREAD CONDATTR(3)

NAME

pthread condattr init, pthread condattr destroy, pthread condattr getclock,pthread condattr setclock, pthread condattr getpshared,pthread condattr setpshared – condition attribute operations

SYNOPSIS

#include <pthread.h>

intpthread_condattr_init(pthread_condattr_t *attr);

intpthread_condattr_destroy(pthread_condattr_t *attr);

intpthread_condattr_getclock(pthread_condattr_t * restrict attr,

clock_t * restrict clock_id);

intpthread_condattr_setclock(pthread_condattr_t *attr, clock_t clock_id);

intpthread_condattr_getpshared(pthread_condattr_t * restrict attr,

int * restrict pshared);

intpthread_condattr_setpshared(pthread_condattr_t *attr, int pshared);

DESCRIPTION

Condition attribute objects are used to specify parameters to pthread cond init().

The pthread condattr init() function initializes a condition attribute object withthe default attributes.

The pthread condattr destroy() function destroys a condition attribute object.

The pthread condattr getclock() function will put the value of the clockattribute from attr into the memory area pointed to by clock id. Thepthread condattr setclock() function will set the clock attribute of attr to the

Systems/C C Library 857

Page 876: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

value specified in clock id. The clock attribute affects the interpretation of ab-stime in pthread cond timedwait(3) and may be set to CLOCK REALTIME (default) orCLOCK MONOTONIC. (Only CLOCK REALTIME is supported in this hardware.)

The pthread condattr getpshared() function will put the value of the process-shared attribute from attr into the memory area pointed to by pshared. Thepthread condattr setpshared() function will set the process-shared attribute ofattr to the value specified in pshared. The argument pshared may have one of thefollowing values:

PTHREAD PROCESS PRIVATE The condition variable it is attached to may only be ac-cessed by threads in the same process as the one that created theobject.

PTHREAD PROCESS SHARED The condition variable it is attached to may be accessedby threads in processes other than the one that created the object.

This implementation does not support PTHREAD PROCESS SHARED.

RETURN VALUES

If successful, these functions return 0. Otherwise, an error number is returned toindicate the error.

ERRORS

The pthread condattr init() function will fail if:

[ENOMEM] Out of memory.

The pthread condattr destroy() function will fail if:

[EINVAL] Invalid value for attr.

The pthread condattr setclock() function will fail if:

[EINVAL] The value specified in clock id is not one of the allowed values.

The pthread condattr setpshared() function will fail if:

[EINVAL] The value specified in pshared is not one of the allowed values.

858 Systems/C C Library

Page 877: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

SEE ALSO

pthread cond init(3), pthread cond timedwait(3)

STANDARDS

The pthread condattr init() and pthread condattr destroy() functions con-form to ISO/IEC 9945-1:1996 (“POSIX.1”)

Systems/C C Library 859

Page 878: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

PTHREAD COND BROADCAST(3)

NAME

pthread cond broadcast – unblock all threads waiting for a condition variable

SYNOPSIS

#include <pthread.h>

intpthread_cond_broadcast(pthread_cond_t *cond);

DESCRIPTION

The pthread cond broadcast() function unblocks all threads waiting for the con-dition variable cond.

RETURN VALUES

If successful, the pthread cond broadcast() function will return zero, otherwisean error number will be returned to indicate the error.

ERRORS

The pthread cond broadcast() function will fail if:

[EINVAL] The value specified by cond is invalid.

SEE ALSO

pthread cond destroy(3), pthread cond init(3), pthread cond signal(3),pthread cond timedwait(3), pthread cond wait(3)

STANDARDS

The pthread cond broadcast() function conforms to ISO/IEC 9945-1:1996(“POSIX.1”).

860 Systems/C C Library

Page 879: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

PTHREAD COND DESTROY(3)

NAME

pthread cond destroy – destroy a condition variable

SYNOPSIS

#include <pthread.h>

intpthread_cond_destroy(pthread_cond_t *cond);

DESCRIPTION

The pthread cond destroy() function frees the resources allocated by the condi-tion variable cond.

RETURN VALUES

If successful, the pthread cond destroy() function will return zero, otherwise anerror number will be returned to indicate the error.

ERRORS

The pthread cond destroy() function will fail if:

[EINVAL] The value specified by cond is invalid.

[EBUSY] The variable cond is locked by another thread.

SEE ALSO

pthread cond broadcast(3), pthread cond init(3), pthread cond signal(3),pthread cond timedwait(3), pthread cond wait(3)

STANDARDS

The pthread cond destroy() function conforms to ISO/IEC 9945-1:1996(“POSIX.1”).

Systems/C C Library 861

Page 880: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

PTHREAD COND INIT(3)

NAME

pthread cond init – create a condition variable

SYNOPSIS

#include <pthread.h>

intpthread_cond_init(pthread_cond_t *cond, const pthread_condattr_t *attr);

DESCRIPTION

The pthread cond init() function creates a new condition variable, with attributesspecified with attr. If attr is NULL the default attributes are used.

RETURN VALUES

If successful, the pthread cond init() function will return zero and put the newcondition variable id into cond, otherwise an error number will be returned to indi-cate the error.

ERRORS

The pthread cond init() function will fail if:

[EINVAL] The value specified by attr is invalid.

[ENOMEM] The process cannot allocate enough memory to create another con-dition variable.

[EAGAIN] The system temporarily lacks the resources to create another con-dition variable.

SEE ALSO

pthread cond broadcast(3), pthread cond destroy(3), pthread cond signal(3),pthread cond timedwait(3), pthread cond wait(3)

862 Systems/C C Library

Page 881: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

STANDARDS

The pthread cond init() function conforms to ISO/IEC 9945-1:1996(“POSIX.1”).

Systems/C C Library 863

Page 882: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

PTHREAD COND SIGNAL(3)

NAME

pthread cond signal – unblock a thread waiting for a condition variable

SYNOPSIS

#include <pthread.h>

intpthread_cond_signal(pthread_cond_t *cond);

DESCRIPTION

The pthread cond signal() function unblocks one thread waiting for the conditionvariable cond.

RETURN VALUES

If successful, the pthread cond signal() function will return zero, otherwise anerror number will be returned to indicate the error.

ERRORS

The pthread cond signal() function will fail if:

[EINVAL] The value specified by cond is invalid.

SEE ALSO

pthread cond broadcast(3), pthread cond destroy(3), pthread cond init(3),pthread cond timedwait(3), pthread cond wait(3)

STANDARDS

The pthread cond signal() function conforms to ISO/IEC 9945-1:1996(“POSIX.1”).

864 Systems/C C Library

Page 883: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

PTHREAD COND TIMEDWAIT(3)

NAME

pthread cond timedwait – wait on a condition variable for a specific amount of time

SYNOPSIS

#include <pthread.h>

intpthread_cond_timedwait(pthread_cond_t *cond, pthread_mutex_t *mutex,

const struct timespec *abstime);

DESCRIPTION

The pthread cond timedwait() function atomically blocks the current threadwaiting on the condition variable specified by cond, and unblocks the mutex spec-ified by mutex. The waiting thread unblocks only after another thread callspthread cond signal(3), or pthread cond broadcast(3) with the same condition vari-able, or if the system time reaches the time specified in abstime, and the currentthread reacquires the lock on mutex.

RETURN VALUES

If successful, the pthread cond timedwait() function will return zero. Otherwisean error number will be returned to indicate the error.

ERRORS

The pthread cond timedwait() function will fail if:

[EINVAL] The value specified by cond, mutex or abstime is invalid.

[ETIMEDOUT] The system time has reached or exceeded the time specified in ab-stime.

SEE ALSO

pthread cond broadcast(3), pthread cond destroy(3), pthread cond init(3),pthread cond signal(3), pthread cond wait(3)

Systems/C C Library 865

Page 884: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

STANDARDS

The pthread cond timedwait() function conforms to ISO/IEC 9945-1:1996(“POSIX.1”).

866 Systems/C C Library

Page 885: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

PTHREAD COND WAIT(3)

NAME

pthread cond wait – wait on a condition variable

SYNOPSIS

#include <pthread.h>

intpthread_cond_wait(pthread_cond_t *cond, pthread_mutex_t *mutex);

DESCRIPTION

The pthread cond wait() function atomically blocks the current thread waiting onthe condition variable specified by cond, and unblocks the mutex specified by mutex.The waiting thread unblocks only after another thread calls pthread cond signal(3),or pthread cond broadcast(3) with the same condition variable, and the currentthread reacquires the lock on mutex.

RETURN VALUES

If successful, the pthread cond wait() function will return zero. Otherwise anerror number will be returned to indicate the error.

ERRORS

The pthread cond wait() function will fail if:

[EINVAL] The value specified by cond or the value specified by mutex is invalid.

SEE ALSO

pthread cond broadcast(3), pthread cond destroy(3), pthread cond init(3),pthread cond signal(3), pthread cond timedwait(3)

STANDARDS

The pthread cond wait() function conforms to ISO/IEC 9945-1:1996(“POSIX.1”).

Systems/C C Library 867

Page 886: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

PTHREAD CREATE(3)

NAME

pthread create – create a new thread

SYNOPSIS

#include <pthread.h>

intpthread_create(pthread_t *thread, const pthread_attr_t *attr,

void *(*start_routine)(void *), void *arg);

DESCRIPTION

The pthread create() function is used to create a new thread, with attributesspecified by attr, within a process. If attr is NULL, the default attributes are used.If the attributes specified by attr are modified later, the thread’s attributes are notaffected. Upon successful completion pthread create() will store the ID of thecreated thread in the location specified by thread.

The thread is created executing start routine with arg as its sole argument. If thestart routine returns, the effect is as if there was an implicit call to pthread exit()using the return value of start routine as the exit status. Note that the threadin which main() was originally invoked differs from this. When it returns frommain(), the effect is as if there was an implicit call to exit() using the return valueof main() as the exit status.

The signal state of the new thread is initialized as:

o The signal mask is inherited from the creating thread.

o The set of signals pending for the new thread is empty.

RETURN VALUES

If successful, the pthread create() function will return zero. Otherwise an errornumber will be returned to indicate the error.

868 Systems/C C Library

Page 887: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

ERRORS

The pthread create() function will fail if:

[EAGAIN] The system lacked the necessary resources to create another thread,or the system-imposed limit on the total number of threads in aprocess [PTHREAD THREADS MAX] would be exceeded.

[EINVAL] The value specified by attr is invalid.

[EMVSERR] An internal error occurred in the operation system, this should bereported to IBM.

IMPLEMENTATION

The pthread create() function depends on the use of the Unix Systems Services(POSIX) subsystem and POSIX signals. If pthread create() is linked with yourprogram, then POSIX signals are assumed.

Programs that invoke pthread create() become ”threaded”. When such programsend they invoke the POSIX exit(2) function and don’t simply return to the calleras other Systems/C programs do.

Unlike stack space for the main() program, the stack space for a thread is notexpandable. Enough space must be allocated for the thread to use or the programwill suffer a Dignus out-of-stack ABEND. The default stack space for both 31-bitand 64-bit programs is 4096 bytes, which can be quite small for some programs.

SEE ALSO

fork(2), pthread cleanup pop(3), pthread cleanup push(3), pthread exit(3),pthread join(3)

STANDARDS

The pthread create() function conforms to ISO/IEC 9945-1:1996 (“POSIX.1”).

Systems/C C Library 869

Page 888: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

PTHREAD DETACH(3)

NAME

pthread detach – detach a thread

SYNOPSIS

#include <pthread.h>

intpthread_detach(pthread_t thread);

DESCRIPTION

The pthread detach() function is used to indicate to the implementation thatstorage for the thread thread can be reclaimed when the thread terminates. Ifthread has not terminated, pthread detach() will not cause it to terminate. Theeffect of multiple pthread detach() calls on the same target thread is unspecified.

RETURN VALUES

If successful, the pthread detach() function will return zero. Otherwise an errornumber will be returned to indicate the error.

ERRORS

The pthread detach() function will fail if:

[EINVAL] The implementation has detected that the value specified by threaddoes not refer to a joinable thread.

[ESRCH] No thread could be found corresponding to that specified by thegiven thread ID, thread.

SEE ALSO

pthread join(3)

870 Systems/C C Library

Page 889: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

STANDARDS

The pthread detach() function conforms to ISO/IEC 9945-1:1996 (“POSIX.1”).

Systems/C C Library 871

Page 890: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

PTHREAD EQUAL(3)

NAME

pthread equal – compare thread IDs

SYNOPSIS

#include <pthread.h>

intpthread_equal(pthread_t t1, pthread_t t2);

DESCRIPTION

The pthread equal() function compares the thread IDs t1 and t2.

RETURN VALUES

The pthread equal() function will return non-zero if the thread IDs t1 and t2correspond to the same thread, otherwise it will return zero.

ERRORS

None.

SEE ALSO

pthread create(3), pthread exit(3)

STANDARDS

The pthread equal() function conforms to ISO/IEC 9945-1:1996 (“POSIX.1”).

872 Systems/C C Library

Page 891: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

PTHREAD EXIT(3)

NAME

pthread exit – terminate the calling thread

SYNOPSIS

#include <pthread.h>

voidpthread_exit(void *value_ptr);

DESCRIPTION

The pthread exit() function terminates the calling thread and makes the valuevalue ptr available to any successful join with the terminating thread. Any cancel-lation cleanup handlers that have been pushed and are not yet popped are poppedin the reverse order that they were pushed and then executed. Thread terminationdoes not release any application visible process resources, including, but not lim-ited to, mutexes and file descriptors, nor does it perform any process level cleanupactions, including, but not limited to, calling atexit() routines that may exist.

An implicit call to pthread exit() is made when a thread other than the threadin which main() was first invoked returns from the start routine that was used tocreate it. The function’s return value serves as the thread’s exit status.

The behavior of pthread exit() is undefined if called from a cancellation handleror destructor function that was invoked as the result of an implicit or explicit callto pthread exit().

After a thread has terminated, the result of access to local (auto) vari- ables of thethread is undefined. Thus, references to local variables of the exiting thread shouldnot be used for the pthread exit() value ptr parameter value.

The process will exit with an exit status of 0 after the last thread has been termi-nated. The behavior is as if the implementation called exit() with a zero argumentat thread termination time.

RETURN VALUES

The pthread exit() function cannot return to its caller.

Systems/C C Library 873

Page 892: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

ERRORS

None.

SEE ALSO

exit(2), exit(3), pthread create(3), pthread join(3)

STANDARDS

The pthread exit() function conforms to ISO/IEC 9945-1:1996 (“POSIX.1”).

874 Systems/C C Library

Page 893: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

PTHREAD GETSPECIFIC(3)

NAME

pthread getspecific – get a thread-specific data value

SYNOPSIS

#include <pthread.h>

void *pthread_getspecific(pthread_key_t key);

DESCRIPTION

The pthread getspecific() function returns the value currently bound to the spec-ified key on behalf of the calling thread.

The effect of calling pthread getspecific() with a key value not obtained frompthread key create() or after key has been deleted with pthread key delete()is undefined.

The pthread getspecific() function may be called from a thread-specific datadestructor function.

RETURN VALUES

The pthread getspecific() function will return the thread-specific data value as-sociated with the given key. If no thread-specific data value is associated with key,then the value NULL is returned.

ERRORS

None.

SEE ALSO

pthread key create(3), pthread key delete(3), pthread setspecific(3)

Systems/C C Library 875

Page 894: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

STANDARDS

The pthread getspecific() function conforms to ISO/IEC 9945-1:1996(“POSIX.1”).

876 Systems/C C Library

Page 895: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

PTHREAD JOIN(3)

NAME

pthread join – wait for thread termination

SYNOPSIS

#include <pthread.h>

intpthread_join(pthread_t thread, void **value_ptr);

DESCRIPTION

The pthread join() function suspends execution of the calling thread until thetarget thread terminates unless the target thread has already terminated.

On return from a successful pthread join() call with a non-NULL value ptr argu-ment, the value passed to pthread exit() by the terminating thread is stored inthe location referenced by value ptr. When a pthread join() returns successfully,the target thread has been terminated. The results of multiple simultaneous callsto pthread join() specifying the same target thread are undefined. If the threadcalling pthread join() is cancelled, then the target thread is not detached.

A thread that has exited but remains unjoined counts against[ POSIX THREAD THREADS MAX].

RETURN VALUES

If successful, the pthread join() function will return zero. Otherwise an error numberwill be returned to indicate the error.

ERRORS

The pthread join() function will fail if:

[EINVAL] The implementation has detected that the value specified by threaddoes not refer to a joinable thread.

[ESRCH] No thread could be found corresponding to that specified by thegiven thread ID, thread.

[EDEADLK] A deadlock was detected or the value of thread specifies the callingthread.

Systems/C C Library 877

Page 896: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

SEE ALSO

wait(2), pthread create(3)

STANDARDS

The pthread join() function conforms to ISO/IEC 9945-1:1996 (“POSIX.1”).

878 Systems/C C Library

Page 897: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

PTHREAD KEY CREATE(3)

NAME

pthread key create – thread-specific data key creation

SYNOPSIS

#include <pthread.h>

intpthread_key_create(pthread_key_t *key, void (*destructor)(void *));

DESCRIPTION

The pthread key create() function creates a thread-specific data key visible to allthreads in the process. Key values provided by pthread key create() are opaqueobjects used to locate thread-specific data. Although the same key value may beused by different threads, the values bound to the key by pthread setspecific()are maintained on a per-thread basis and persist for the life of the calling thread.

Upon key creation, the value NULL is associated with the new key in all activethreads. Upon thread creation, the value NULL is associated with all defined keys inthe new thread.

An optional destructor function may be associated with each key value. At threadexit, if a key value has a non-NULL destructor pointer, and the thread has a non-NULL value associated with the key, the function pointed to is called with the currentassociated value as its sole argument. The order of destructor calls is unspecified ifmore than one destructor exists for a thread when it exits.

If, after all the destructors have been called for all non-NULL values with associ-ated destructors, there are still some non-NULL values with associated destructors,then the process is repeated. If, after at least [PTHREAD DESTRUCTOR ITERATIONS]iterations of destructor calls for outstanding non-NULL values, there are still somenon-NULL values with associated destructors, the implementation stops calling de-structors.

RETURN VALUES

If successful, the pthread key create() function will store the newly created keyvalue at the location specified by key and returns zero.

Otherwise an error number will be returned to indicate the error.

Systems/C C Library 879

Page 898: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

ERRORS

The pthread key create() function will fail if:

[EAGAIN] The system lacked the necessary resources to create another thread-specific data key, or the system-imposed limit on the total numberof keys per process [PTHREAD KEYS MAX] would be exceeded.

[ENOMEM] Insufficient memory exists to create the key.

SEE ALSO

pthread getspecific(3), pthread key delete(3), pthread setspecific(3)

STANDARDS

The pthread key create() function conforms to ISO/IEC 9945-1:1996(“POSIX.1”).

880 Systems/C C Library

Page 899: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

PTHREAD KEY DELETE(3)

NAME

pthread key delete – delete a thread-specific data key

SYNOPSIS

#include <pthread.h>

intpthread_key_delete(pthread_key_t key);

DESCRIPTION

The pthread key delete() function deletes a thread-specific data key previouslyreturned by pthread key create(). The thread-specific data values associatedwith key need not be NULL at the time that pthread key delete() is called. Itis the responsibility of the application to free any application storage or performany cleanup actions for data structures related to the deleted key or associatedthread-specific data in any threads; this cleanup can be done either before or afterpthread key delete() is called. Any attempt to use key following the call topthread key delete() results in undefined behavior.

The pthread key delete() function is callable from within destructor functions.Destructor functions are not invoked by pthread key delete(). Any destructorfunction that may have been associated with key will no longer be called uponthread exit.

RETURN VALUES

If successful, the pthread key delete() function will return zero. Otherwise anerror number will be returned to indicate the error.

ERRORS

The pthread key delete() function will fail if:

[EINVAL] The key value is invalid.

Systems/C C Library 881

Page 900: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

SEE ALSO

pthread getspecific(3), pthread key create(3), pthread setspecific(3)

STANDARDS

The pthread key delete() function conforms to ISO/IEC 9945-1:1996(“POSIX.1”).

882 Systems/C C Library

Page 901: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

PTHREAD KILL(3)

NAME

pthread kill – send a signal to a specified thread

SYNOPSIS

#include <pthread.h>#include <signal.h>

intpthread_kill(pthread_t thread, int sig);

DESCRIPTION

The pthread kill() function sends a signal, specified by sig, to a thread, specifiedby thread. If sig is 0, error checking is performed, but no signal is actually sent.

RETURN VALUES

If successful, pthread kill() returns 0. Otherwise, an error number is returned.

ERRORS

The pthread kill() function will fail if:

[ESRCH] thread is an invalid thread ID.

[EINVAL] sig is an invalid or unsupported signal number.

SEE ALSO

kill(2), pthread self(3), raise(3)

STANDARDS

The pthread kill() function conforms to ISO/IEC 9945-1:1996 (“POSIX.1”)

Systems/C C Library 883

Page 902: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

PTHREAD MUTEXATTR(3)

NAME

pthread mutexattr init, pthread mutexattr destroy,pthread mutexattr setprioceiling, pthread mutexattr getprioceiling,pthread mutexattr setprotocol, pthread mutexattr getprotocol,pthread mutexattr settype, pthread mutexattr gettype – mutex attributeoperations

SYNOPSIS

#include <pthread.h>

intpthread_mutexattr_init(pthread_mutexattr_t *attr);

intpthread_mutexattr_destroy(pthread_mutexattr_t *attr);

intpthread_mutexattr_setprioceiling(pthread_mutexattr_t *attr,

int prioceiling);

intpthread_mutexattr_getprioceiling(pthread_mutexattr_t *attr,

int *prioceiling);

intpthread_mutexattr_setprotocol(pthread_mutexattr_t *attr, int protocol);

intpthread_mutexattr_getprotocol(pthread_mutexattr_t *attr, int *protocol);

intpthread_mutexattr_settype(pthread_mutexattr_t *attr, int type);

intpthread_mutexattr_gettype(pthread_mutexattr_t *attr, int *type);

DESCRIPTION

Mutex attributes are used to specify parameters to pthread mutex init(). Oneattribute object can be used in multiple calls to pthread mutex init(), with orwithout modifications between calls.

884 Systems/C C Library

Page 903: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

The pthread mutexattr init() function initializes attr with all the default mutexattributes.

The pthread mutexattr destroy() function destroys attr.

The pthread mutexattr set*() functions set the attribute that corresponds toeach function name.

The pthread mutexattr get*() functions copy the value of the attribute thatcorresponds to each function name to the location pointed to by the second functionparameter.

RETURN VALUES

If successful, these functions return 0. Otherwise, an error number is returned toindicate the error.

ERRORS

The pthread mutexattr init() function will fail if:

[ENOMEM] Out of memory.

The pthread mutexattr destroy() function will fail if:

[EINVAL] Invalid value for attr.

The pthread mutexattr setprioceiling() function will fail if:

[EINVAL] Invalid value for attr, or invalid value for prioceiling.

The pthread mutexattr getprioceiling() function will fail if:

[EINVAL] Invalid value for attr.

The pthread mutexattr setprotocol() function will fail if:

[EINVAL] Invalid value for attr, or invalid value for protocol.

The pthread mutexattr getprotocol() function will fail if:

Systems/C C Library 885

Page 904: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

[EINVAL] Invalid value for attr.

The pthread mutexattr settype() function will fail if:

[EINVAL] Invalid value for attr, or invalid value for type.

The pthread mutexattr gettype() function will fail if:

[EINVAL] Invalid value for attr.

IMPLEMENTATION

This implementation does not support scheduling priority settings.

SEE ALSO

pthread mutex init(3)

STANDARDS

The pthread mutexattr init() and pthread mutexattr destroy() functionsconform to ISO/IEC 9945-1:1996 (“POSIX.1”)

The pthread mutexattr setprioceiling(),pthread mutexattr getprioceiling(), pthread mutexattr setprotocol(),pthread mutexattr getprotocol(), pthread mutexattr settype(), andpthread mutexattr gettype() functions conform to Version 2 of the SingleUNIX Specification (“SUSv2”)

886 Systems/C C Library

Page 905: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

PTHREAD MUTEX DESTROY(3)

NAME

pthread mutex destroy – free resources allocated for a mutex

SYNOPSIS

#include <pthread.h>

intpthread_mutex_destroy(pthread_mutex_t *mutex);

DESCRIPTION

The pthread mutex destroy() function frees the resources allocated for mutex.

RETURN VALUES

If successful, pthread mutex destroy() will return zero, otherwise an error num-ber will be returned to indicate the error.

ERRORS

The pthread mutex destroy() function will fail if:

[EINVAL] The value specified by mutex is invalid.

[EBUSY] mutex is locked by another thread.

SEE ALSO

pthread mutex init(3), pthread mutex lock(3), pthread mutex trylock(3),pthread mutex unlock(3)

STANDARDS

The pthread mutex destroy() function conforms to ISO/IEC 9945-1:1996(“POSIX.1”).

Systems/C C Library 887

Page 906: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

PTHREAD MUTEX INIT(3)

NAME

pthread mutex init – create a mutex

SYNOPSIS

#include <pthread.h>

intpthread_mutex_init(pthread_mutex_t *mutex,

const pthread_mutexattr_t *attr);

DESCRIPTION

The pthread mutex init() function creates a new mutex, with attributes specifiedwith attr. If attr is NULL the default attributes are used.

RETURN VALUES

If successful, pthread mutex init() will return zero and put the new mutex idinto mutex, otherwise an error number will be returned to indicate the error.

ERRORS

The pthread mutex init() function will fail if:

[EINVAL] The value specified by attr is invalid.

[ENOMEM] The process cannot allocate enough memory to create another mu-tex.

SEE ALSO

pthread mutex destroy(3), pthread mutex lock(3), pthread mutex trylock(3),pthread mutex unlock(3)

888 Systems/C C Library

Page 907: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

STANDARDS

The pthread mutex init() function conforms to ISO/IEC 9945-1:1996(“POSIX.1”).

Systems/C C Library 889

Page 908: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

PTHREAD MUTEX LOCK(3)

NAME

pthread mutex lock – lock a mutex

SYNOPSIS

#include <pthread.h>

intpthread_mutex_lock(pthread_mutex_t *mutex);

DESCRIPTION

The pthread mutex lock() function locks mutex. If the mutex is already locked,the calling thread will block until the mutex becomes available.

RETURN VALUES

If successful, pthread mutex lock() will return zero, otherwise an error numberwill be returned to indicate the error.

ERRORS

The pthread mutex lock() function will fail if:

[EINVAL] The value specified by mutex is invalid.

[EDEADLK] A deadlock would occur if the thread blocked waiting for mutex.

SEE ALSO

pthread mutex destroy(3), pthread mutex init(3), pthread mutex trylock(3),pthread mutex unlock(3)

STANDARDS

The pthread mutex lock() function conforms to ISO/IEC 9945-1:1996(“POSIX.1”).

890 Systems/C C Library

Page 909: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

PTHREAD MUTEX TRYLOCK(3)

NAME

pthread mutex trylock – attempt to lock a mutex without blocking

SYNOPSIS

#include <pthread.h>

intpthread_mutex_trylock(pthread_mutex_t *mutex);

DESCRIPTION

The pthread mutex trylock() function locks mutex. If the mutex is alreadylocked, pthread mutex trylock() will not block waiting for the mutex, but willreturn an error condition.

RETURN VALUES

If successful, pthread mutex trylock() will return zero, otherwise an error num-ber will be returned to indicate the error.

ERRORS

The pthread mutex trylock() function will fail if:

[EINVAL] The value specified by mutex is invalid.

[EBUSY] mutex is already locked.

SEE ALSO

pthread mutex destroy(3), pthread mutex init(3), pthread mutex lock(3),pthread mutex unlock(3)

STANDARDS

The pthread mutex trylock() function conforms to ISO/IEC 9945-1:1996(“POSIX.1”).

Systems/C C Library 891

Page 910: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

PTHREAD MUTEX UNLOCK(3)

NAME

pthread mutex unlock – unlock a mutex

SYNOPSIS

#include <pthread.h>

intpthread_mutex_unlock(pthread_mutex_t *mutex);

DESCRIPTION

If the current thread holds the lock on mutex, then the pthread mutex unlock()function unlocks mutex.

RETURN VALUES

If successful, pthread mutex unlock() will return zero, otherwise an error numberwill be returned to indicate the error.

ERRORS

The pthread mutex unlock() function will fail if:

[EINVAL] The value specified by mutex is invalid.

[EPERM] The current thread does not hold a lock on mutex.

SEE ALSO

pthread mutex destroy(3), pthread mutex init(3), pthread mutex lock(3),pthread mutex trylock(3)

STANDARDS

The pthread mutex unlock() function conforms to ISO/IEC 9945-1:1996(“POSIX.1”).

892 Systems/C C Library

Page 911: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

PTHREAD ONCE(3)

NAME

pthread once – dynamic package initialization

SYNOPSIS

#include <pthread.h>

pthread_once_t once_control = PTHREAD_ONCE_INIT;

intpthread_once(pthread_once_t *once_control, void (*init_routine)(void));

DESCRIPTION

The first call to pthread once() by any thread in a process, with a givenonce control, will call the init routine() with no arguments. Subsequent calls topthread once() with the same once control will not call the init routine(). On re-turn from pthread once(), it is guaranteed that init routine() has completed. Theonce control parameter is used to determine whether the associated initializationroutine has been called.

The function pthread once() is not a cancellation point. However, if init routine()is a cancellation point and is cancelled, the effect on once control is as ifpthread once() was never called.

The constant PTHREAD ONCE INIT is defined by header <pthread.h>.

The behavior of pthread once() is undefined if once control has automatic storageduration or is not initialized by PTHREAD ONCE INIT.

RETURN VALUES

If successful, the pthread once() function will return zero. Otherwise an errornumber will be returned to indicate the error.

ERRORS

None.

Systems/C C Library 893

Page 912: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

STANDARDS

The pthread once() function conforms to ISO/IEC 9945-1:1996 (“POSIX.1”).

894 Systems/C C Library

Page 913: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

PTHREAD RWLOCKATTR DESTROY(3)

NAME

pthread rwlockattr destroy – destroy a read/write lock

SYNOPSIS

#include <pthread.h>

intpthread_rwlockattr_destroy(pthread_rwlockattr_t *attr);

DESCRIPTION

The pthread rwlockattr destroy() function is used to destroy a read/write lockattribute object previously created with pthread rwlockattr init().

RETURN VALUES

If successful, the pthread rwlockattr destroy() function will return zero. Oth-erwise an error number will be returned to indicate the error.

ERRORS

The pthread rwlockattr destroy() function may fail if:

[EINVAL] The value specified by attr is invalid.

SEE ALSO

pthread rwlockattr init(3)

STANDARDS

The pthread rwlockattr destroy() function is expected to conform to Version 2of the Single UNIX Specification (“SUSv2”).

Systems/C C Library 895

Page 914: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

PTHREAD RWLOCKATTR GETPSHARED(3)

NAME

pthread rwlockattr getpshared – get the process shared attribute

SYNOPSIS

#include <pthread.h>

intpthread_rwlockattr_getpshared(const pthread_rwlockattr_t *attr,

int *pshared);

DESCRIPTION

The pthread rwlockattr getpshared() function is used to get the process sharedsetting of a read/write lock attribute object. The setting is returned via pshared,and may be one of two values:

[PTHREAD PROCESS SHARED] Any thread of any process that has access to the mem-ory where the read/write lock resides can manipulate the lock.

[PTHREAD PROCESS PRIVATE] Only threads created within the same process as thethread that initialized the read/write lock can manipulate the lock.This is the default value.

RETURN VALUES

If successful, the pthread rwlockattr getpshared() function will return zero.Otherwise an error number will be returned to indicate the error.

ERRORS

The pthread rwlockattr getpshared() function may fail if:

[EINVAL] The value specified by attr is invalid.

IMPLEMENTATION

This implementation does not support process shared locks.

896 Systems/C C Library

Page 915: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

SEE ALSO

pthread rwlockattr init(3), pthread rwlockattr setpshared(3),pthread rwlock init(3)

STANDARDS

The pthread rwlockattr getpshared() function is expected to conform to Ver-sion 2 of the Single UNIX Specification (“SUSv2”).

PTHREAD RWLOCKATTR INIT(3)

NAME

pthread rwlockattr init – initialize a read/write lock

SYNOPSIS

#include <pthread.h>

intpthread_rwlockattr_init(pthread_rwlockattr_t *attr);

DESCRIPTION

The pthread rwlockattr init() function is used to initialize a read/write lockattributes object.

RETURN VALUES

If successful, the pthread rwlockattr init() function will return zero. Otherwisean error number will be returned to indicate the error.

ERRORS

The pthread rwlockattr init() function will fail if:

[ENOMEM] Insufficient memory exists to initialize the attribute object.

Systems/C C Library 897

Page 916: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

SEE ALSO

pthread rwlockattr destroy(3), pthread rwlockattr getpshared(3),pthread rwlockattr setpshared(3), pthread rwlock init(3)

STANDARDS

The pthread rwlockattr init() function is expected to conform to Version 2 ofthe Single UNIX Specification (“SUSv2”).

898 Systems/C C Library

Page 917: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

PTHREAD RWLOCKATTR SETPSHARED(3)

NAME

pthread rwlockattr setpshared – set the process shared attribute

SYNOPSIS

#include <pthread.h>

intpthread_rwlockattr_setpshared(pthread_rwlockattr_t *attr, int pshared);

DESCRIPTION

The pthread rwlockattr setpshared() function sets the process shared attributeof attr to the value referenced by pshared. The pshared argument may be one oftwo values:

[PTHREAD PROCESS SHARED] Any thread of any process that has access to the mem-ory where the read/write lock resides can manipulate the lock.

[PTHREAD PROCESS PRIVATE] Only threads created within the same process as thethread that initialized the read/write lock can manipulate the lock.This is the default value.

RETURN VALUES

If successful, the pthread rwlockattr setpshared() function will return zero.Otherwise an error number will be returned to indicate the error.

ERRORS

The pthread rwlockattr setpshared() function will fail if:

[EINVAL] The value specified by attr or pshared is invalid.

IMPLEMENTATION

This implementation does not support process-sharded locks, thePTHREAD PROCESS SHARED attribute is not supported.

Systems/C C Library 899

Page 918: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

SEE ALSO

pthread rwlockattr getpshared(3), pthread rwlockattr init(3),pthread rwlock init(3)

STANDARDS

The pthread rwlockattr setpshared() function is expected to conform to Ver-sion 2 of the Single UNIX Specification (“SUSv2”).

900 Systems/C C Library

Page 919: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

PTHREAD RWLOCK DESTROY(3)

NAME

pthread rwlock destroy – destroy a read/write lock

SYNOPSIS

#include <pthread.h>

intpthread_rwlock_destroy(pthread_rwlock_t *lock);

DESCRIPTION

The pthread rwlock destroy() function is used to destroy a read/write lock pre-viously created with pthread rwlock init().

RETURN VALUES

If successful, the pthread rwlock destroy() function will return zero. Otherwisean error number will be returned to indicate the error.

ERRORS

The pthread rwlock destroy() function will fail if:

[EPERM] The caller does not have the privilege to perform the operation.

The pthread rwlock destroy() function may fail if:

[EBUSY] The system has detected an attempt to destroy the object referencedby lock while it is locked.

[EINVAL] The value specified by lock is invalid.

SEE ALSO

pthread rwlock init(3)

Systems/C C Library 901

Page 920: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

STANDARDS

The pthread rwlock destroy() function is expected to conform to Version 2 ofthe Single UNIX Specification (“SUSv2”).

902 Systems/C C Library

Page 921: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

PTHREAD RWLOCK INIT(3)

NAME

pthread rwlock init – initialize a read/write lock

SYNOPSIS

#include <pthread.h>

intpthread_rwlock_init(pthread_rwlock_t *lock,

const pthread_rwlockattr_t *attr);

DESCRIPTION

The pthread rwlock init() function is used to initialize a read/write lock, withattributes specified by attr. If attr is NULL, the default read/write lock attributesare used.

The results of calling pthread rwlock init() with an already initialized lock areundefined.

RETURN VALUES

If successful, the pthread rwlock init() function will return zero. Otherwise anerror number will be returned to indicate the error.

ERRORS

The pthread rwlock init() function will fail if:

[EAGAIN] The system lacked the necessary resources (other than memory) toinitialize the lock.

[ENOMEM] Insufficient memory exists to initialize the lock.

[EPERM] The caller does not have sufficient privilege to perform the opera-tion.

The pthread rwlock init() function may fail if:

Systems/C C Library 903

Page 922: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

[EBUSY] The system has detected an attempt to re-initialize the objectreferenced by lock, a previously initialized but not yet destroyedread/write lock.

[EINVAL] The value specified by attr is invalid.

IMPLEMENTATION

The PTHREAD PROCESS SHARED attribute is not supported.

SEE ALSO

pthread rwlockattr init(3), pthread rwlockattr setpshared(3),pthread rwlock destroy(3)

STANDARDS

The pthread rwlock init() function is expected to conform to Version 2 of theSingle UNIX Specification (“SUSv2”).

904 Systems/C C Library

Page 923: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

PTHREAD RWLOCK RDLOCK(3)

NAME

pthread rwlock rdlock, pthread rwlock tryrdlock – acquire a read/write lock forreading

SYNOPSIS

#include <pthread.h>

intpthread_rwlock_rdlock(pthread_rwlock_t *lock);

intpthread_rwlock_tryrdlock(pthread_rwlock_t *lock);

DESCRIPTION

The pthread rwlock rdlock() function acquires a read lock on lock provided thatlock is not presently held for writing and no writer threads are presently blocked onthe lock. If the read lock cannot be immediately acquired, the calling thread blocksuntil it can acquire the lock.

The pthread rwlock tryrdlock() function performs the same action, but does notblock if the lock cannot be immediately obtained (i.e., the lock is held for writingor there are waiting writers).

A thread may hold multiple concurrent read locks. If so,pthread rwlock unlock() must be called once for each lock obtained.

The results of acquiring a read lock while the calling thread holds a write lock areundefined.

RETURN VALUES

If successful, the pthread rwlock rdlock() and pthread rwlock tryrdlock()functions will return zero. Otherwise an error number will be returned to indicatethe error.

Systems/C C Library 905

Page 924: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

ERRORS

The pthread rwlock tryrdlock() function will fail if:

[EBUSY] The lock could not be acquired because a writer holds the lock orwas blocked on it.

The pthread rwlock rdlock() and pthread rwlock tryrdlock() functions mayfail if:

[EAGAIN] The lock could not be acquired because the maximum number ofread locks against lock has been exceeded.

[EDEADLK] The current thread already owns lock for writing.

[EINVAL] The value specified by lock is invalid.

[ENOMEM] Insufficient memory exists to initialize the lock (applies to staticallyinitialized locks only).

SEE ALSO

pthread rwlock init(3), pthread rwlock trywrlock(3), pthread rwlock unlock(3),pthread rwlock wrlock(3)

STANDARDS

The pthread rwlock rdlock() and pthread rwlock tryrdlock() functions areexpected to conform to Version 2 of the Single UNIX Specification (“SUSv2”).

906 Systems/C C Library

Page 925: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

PTHREAD RWLOCK UNLOCK(3)

NAME

pthread rwlock unlock – release a read/write lock

SYNOPSIS

#include <pthread.h>

intpthread_rwlock_unlock(pthread_rwlock_t *lock);

DESCRIPTION

The pthread rwlock unlock() function is used to release the read/write lockpreviously obtained by pthread rwlock rdlock(), pthread rwlock wrlock(),pthread rwlock tryrdlock(), or pthread rwlock trywrlock().

RETURN VALUES

If successful, the pthread rwlock unlock() function will return zero. Otherwisean error number will be returned to indicate the error.

The results are undefined if lock is not held by the calling thread.

ERRORS

The pthread rwlock unlock() function may fail if:

[EINVAL] The value specified by lock is invalid.

[EPERM] The current thread does not own the read/write lock.

SEE ALSO

pthread rwlock rdlock(3), pthread rwlock wrlock(3)

STANDARDS

The pthread rwlock unlock() function is expected to conform to Version 2 of theSingle UNIX Specification (“SUSv2”).

Systems/C C Library 907

Page 926: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

PTHREAD RWLOCK WRLOCK(3)

NAME

pthread rwlock wrlock, pthread rwlock trywrlock – acquire a read/write lock forwriting

SYNOPSIS

#include <pthread.h>

intpthread_rwlock_wrlock(pthread_rwlock_t *lock);

intpthread_rwlock_trywrlock(pthread_rwlock_t *lock);

DESCRIPTION

The pthread rwlock wrlock() function blocks until a write lock can be acquiredagainst lock. The pthread rwlock trywrlock() function performs the same ac-tion, but does not block if the lock cannot be immediately obtained.

The results are undefined if the calling thread already holds the lock at the time thecall is made.

RETURN VALUES

If successful, the pthread rwlock wrlock() and pthread rwlock trywrlock()functions will return zero. Otherwise an error number will be returned to indicatethe error.

ERRORS

The pthread rwlock trywrlock() function will fail if:

[EBUSY] The calling thread is not able to acquire the lock without blocking.

The pthread rwlock wrlock() and pthread rwlock trywrlock() functionsmay fail if:

908 Systems/C C Library

Page 927: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

[EDEADLK] The calling thread already owns the read/write lock (for reading orwriting).

[EINVAL] The value specified by lock is invalid.

[ENOMEM] Insufficient memory exists to initialize the lock (applies to staticallyinitialized locks only).

SEE ALSO

pthread rwlock init(3), pthread rwlock rdlock(3), pthread rwlock tryrdlock(3),pthread rwlock unlock(3)

STANDARDS

The pthread rwlock wrlock() and pthread rwlock trywrlock() functions areexpected to conform to Version 2 of the Single UNIX Specification (“SUSv2”).

Systems/C C Library 909

Page 928: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

PTHREAD SELF(3)

NAME

pthread self – get the calling thread’s ID

SYNOPSIS

#include <pthread.h>

pthread_tpthread_self(void);

DESCRIPTION

The pthread self() function returns the thread ID of the calling thread.

RETURN VALUES

The pthread self() function returns the thread ID of the calling thread.

ERRORS

None.

SEE ALSO

pthread create(3), pthread equal(3)

STANDARDS

The pthread self() function conforms to ISO/IEC 9945-1:1996 (“POSIX.1”).

910 Systems/C C Library

Page 929: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

PTHREAD SET LIMIT NP(3)

NAME

pthread set limit np – control number of tasks and/or threads allowed in the process

SYNOPSIS

#include <pthread.h>

intpthread_set_limit_np(int which, int maxtasks, int maskthreads);

DESCRIPTION

The pthread set limit np() function controls the maximum number of tasks andthe maximum number of threads allowed for the current process. These values areunique to the process, however the initial settings are inherited from the defaultsettings defined when z/OS is initialized.

The pthread set limit np() function can set either the number of z/OS tasks,or the number of threads, or both. The which value determines which setting isdesired:

STL MAX TASKS The maximum number of tasks is set to the value of maxtasks.

STL MAX THREADS The maximum number of threads is set to the value of max-threads.

STL SET BOTH The maximum number of tasks is set to the value of maxtasks andthe maximum number of threads is set to the value of maxthreads.

The z/OS operating system requires memory in the private area below the 16Mfor each task and thread. The number of threads and tasks depends on how muchmemory is available in that area. When that area is exhausted, the task or theprogram may be summarily terminated by the operating system, along with appro-priate messages on the system console. IBM recommends that a reasonable limitfor threads and threads is 200 to 400.

The weight attribute of a thread controls the mapping of threads to tasks. Also thesynctype attribute controls if a thread can be created without an available task.

RETURN VALUES

If successful, pthread set limit np() returns 0, otherwise -1 is returned.

Systems/C C Library 911

Page 930: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

NAME

pthread setspecific – set a thread-specific data value

SYNOPSIS

#include <pthread.h>

intpthread_setspecific(pthread_key_t key, const void *value);

DESCRIPTION

The pthread setspecific() function associates a thread-specific value with a keyobtained via a previous call to pthread key create(). Different threads can binddifferent values to the same key. These values are typically pointers to blocks ofdynamically allocated memory that have been reserved for use by the calling thread.

The effect of calling pthread setspecific() with a key value not obtained frompthread key create() or after key has been deleted with pthread key delete()is undefined.

The pthread setspecific() function may be called from a thread-specific data de-structor function, however this may result in lost storage or infinite loops.

RETURN VALUES

If successful, the pthread setspecific() function will return zero. Otherwise anerror number will be returned to indicate the error.

ERRORS

The pthread setspecific() function will fail if:

[ENOMEM] Insufficient memory exists to associate the value with the key.

[EINVAL] The key value is invalid.

SEE ALSO

pthread getspecific(3), pthread key create(3), pthread key delete(3)

912 Systems/C C Library

Page 931: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

STANDARDS

The pthread setspecific() function conforms to ISO/IEC 9945-1:1996(“POSIX.1”).

Systems/C C Library 913

Page 932: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

PTHREAD SIGMASK(3)

NAME

pthread sigmask – examine and/or change a thread’s signal mask

SYNOPSIS

#include <pthread.h>#include <signal.h>

intpthread_sigmask(int how, const sigset_t *set, sigset_t *oset);

DESCRIPTION

The pthread sigmask() function examines and/or changes the calling thread’ssignal mask.

If set is not NULL, it specifies a set of signals to be modified, and how specifies whatto set the signal mask to:

[SIG BLOCK] Union of the current mask and set.

[SIG UNBLOCK] Intersection of the current mask and the complement of set.

[SIG SETMASK] set.

If oset is not NULL, the previous signal mask is stored in the location pointed to byoset.

SIGKILL and SIGSTOP cannot be blocked, and will be silently ignored if included inthe signal mask.

RETURN VALUES

If successful, pthread sigmask() returns 0. Otherwise, an error is returned.

ERRORS

The pthread sigmask() function will fail if:

[EINVAL] how is not one of the defined values.

914 Systems/C C Library

Page 933: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

SEE ALSO

sigaction(2), sigpending(2), sigprocmask(2), sigsuspend(2), sigsetops(3)

STANDARDS

The pthread sigmask() function conforms to ISO/IEC 9945-1:1996 (“POSIX.1”)

Systems/C C Library 915

Page 934: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

PTHREAD SPIN INIT(3)

NAME

pthread spin init, pthread spin destroy – initialize or destroy a spin lock

SYNOPSIS

#include <pthread.h>

intpthread_spin_init(pthread_spinlock_t *lock, int pshared);

intpthread_spin_destroy(pthread_spinlock_t *lock);

DESCRIPTION

The pthread spin init() function will initialize lock to an unlocked stateand allocate any resources necessary to begin using it. If pshared is set toPTHREAD PROCESS SHARED, any thread, whether belonging to the process in whichthe spinlock was created or not, that has access to the memory area where lockresides, can use lock. If it is set to PTHREAD PROCESS PRIVATE, it can only be usedby threads within the same process.

The pthread spin destroy() function will destroy lock and release any resourcesthat may have been allocated on its behalf.

RETURN VALUES

If successful, both pthread spin init() and pthread spin destroy() will returnzero. Otherwise, an error number will be returned to indicate the error.

Neither of these functions will return EINTR.

ERRORS

The pthread spin init() and pthread spin destroy() functions will fail if:

[EBUSY] An attempt to initialize or destroy lock while it is in use.

[EINVAL] The value specified by lock is invalid.

916 Systems/C C Library

Page 935: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

The pthread spin init() function will fail if:

[EAGAIN] Insufficient resources, other than memory, to initialize lock.

[ENOMEM] Insufficient memory to initialize lock.

SEE ALSO

pthread spin lock(3), pthread spin unlock(3)

IMPLEMENTATION

This implementation does not support process-shared locks, if any value other thanPTHREAD PROCESSES PRIVATE is specified, pthread spin init() returns EINVAL.

Systems/C C Library 917

Page 936: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

PTHREAD SPIN LOCK(3)

NAME

pthread spin lock, pthread spin trylock, pthread spin unlock – lock or unlock a spinlock

SYNOPSIS

#include <pthread.h>

intpthread_spin_lock(pthread_spinlock_t *lock);

intpthread_spin_trylock(pthread_spinlock_t *lock);

intpthread_spin_unlock(pthread_spinlock_t *lock);

DESCRIPTION

The pthread spin lock() function will acquire lock if it is not currently owned byanother thread. If the lock cannot be acquired immediately, it will spin attemptingto acquire the lock (it will not sleep) until it becomes available.

The pthread spin trylock() function is the same as pthread spin lock() exceptthat if it cannot acquire lock immediately it will return with an error.

The pthread spin unlock() function will release lock, which must have been pre-viously locked by a call to pthread spin lock() or pthread spin trylock().

RETURN VALUES

If successful, all these functions will return zero. Otherwise, an error number willbe returned to indicate the error.

None of these functions will return EINTR.

ERRORS

The pthread spin lock(), pthread spin trylock() andpthread spin unlock() functions will fail if:

918 Systems/C C Library

Page 937: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

[EINVAL] The value specified by lock is invalid or is not initialized.

The pthread spin lock() function may fail if:

[EDEADLK] The calling thread already owns the lock.

The pthread spin trylock() function will fail if:

[EBUSY] Another thread currently holds lock.

The pthread spin unlock() function may fail if:

[EPERM] The calling thread does not own lock.

SEE ALSO

pthread spin destroy(3), pthread spin init(3)

STANDARDS

The implementation of pthread spin lock(), pthread spin trylock() andpthread spin unlock() is expected to conform to IEEE Std 1003.2 (“POSIX.2”).

Systems/C C Library 919

Page 938: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

PTHREAD TESTCANCEL(3)

NAME

pthread setcancelstate, pthread setcanceltype, pthread testcancel – set cancelabilitystate

SYNOPSIS

#include <pthread.h>

intpthread_setcancelstate(int state, int *oldstate);

intpthread_setcanceltype(int type, int *oldtype);

voidpthread_testcancel(void);

DESCRIPTION

The pthread setcancelstate() function atomically both sets the calling thread’scancelability state to the indicated state and, if oldstate is not NULL, returns theprevious cancelability state at the location referenced by oldstate. Legal values forstate are PTHREAD CANCEL ENABLE and PTHREAD CANCEL DISABLE.

The pthread setcanceltype() function atomically both sets the calling thread’scancelability type to the indicated type and, if oldtype is not NULL, returns theprevious cancelability type at the location referenced by oldtype. Legal values fortype are PTHREAD CANCEL DEFERRED and PTHREAD CANCEL ASYNCHRONOUS.

The cancelability state and type of any newly created threads, including thethread in which main() was first invoked, are PTHREAD CANCEL ENABLE andPTHREAD CANCEL DEFERRED respectively.

The pthread testcancel() function creates a cancellation point in the callingthread. The pthread testcancel() function has no effect if cancelability is dis-abled.

Cancelability States

The cancelability state of a thread determines the action taken upon receipt of acancellation request. The thread may control cancellation in a number of ways.

920 Systems/C C Library

Page 939: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

Each thread maintains its own “cancelability state” which may be encoded in twoflags:

Cancelability Enable When cancelability is PTHREAD CANCEL DISABLE, cancellationrequests against the target thread are held pending.

Cancelability Type When cancelability is enabled and the cancelability type isPTHREAD CANCEL ASYNCHRONOUS, new or pending cancellation requestsmay be acted upon at any time. When cancelability is enabled and thecancelability type is PTHREAD CANCEL DEFERRED, cancellation requestsare held pending until a cancellation point (see below) is reached. Ifcancelability is disabled, the setting of the cancelability type has noimmediate effect as all cancellation requests are held pending; how-ever, once cancelability is enabled again the new type will be in effect.

Cancellation Points

Cancellation points will occur when a thread is executing at least the fol-lowing functions: close(), creat(), fcntl(), fsync(), msync(), open(),pause(), pthread cond timedwait(), pthread cond wait(), pthread join(),pthread testcancel(), read(), sigwaitinfo(), sigsuspend(), sigwait(),sleep(), system(), tcdrain(), wait(), waitpid(), write().

RETURN VALUES

If successful, the pthread setcancelstate() and pthread setcanceltype() func-tions will return zero. Otherwise, an error number shall be returned to indicate theerror.

The pthread setcancelstate() and pthread setcanceltype() functions are usedto control the points at which a thread may be asynchronously canceled. For can-cellation control to be usable in modular fashion, some rules must be followed.

For purposes of this discussion, consider an object to be a generalization of a pro-cedure. It is a set of procedures and global variables written as a unit and called byclients not known by the object. Objects may depend on other objects.

First, cancelability should only be disabled on entry to an object, never explicitlyenabled. On exit from an object, the cancelability state should always be restoredto its value on entry to the object.

This follows from a modularity argument: if the client of an object (or the client ofan object that uses that object) has disabled cancelability, it is because the clientdoes not want to have to worry about how to clean up if the thread is canceledwhile executing some sequence of actions. If an object is called in such a state and

Systems/C C Library 921

Page 940: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

it enables cancelability and a cancellation request is pending for that thread, thenthe thread will be canceled, contrary to the wish of the client that disabled.

Second, the cancelability type may be explicitly set to either deferred or asyn-chronous upon entry to an object. But as with the cancelability state, on exit froman object that cancelability type should always be restored to its value on entry tothe object.

Finally, only functions that are cancel-safe may be called from a thread that isasynchronously cancelable.

ERRORS

The function pthread setcancelstate() may fail with:

[EINVAL] The specified state is not PTHREAD CANCEL ENABLE orPTHREAD CANCEL DISABLE.

The function pthread setcanceltype() may fail with:

[EINVAL] The specified state is not PTHREAD CANCEL DEFERRED orPTHREAD CANCEL ASYNCHRONOUS.

SEE ALSO

pthread cancel(3)

STANDARDS

The pthread testcancel() function conforms to ISO/IEC 9945-1:1996(“POSIX.1”).

922 Systems/C C Library

Page 941: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

PTHREAD YIELD(3)

NAME

pthread yield – yield control of the current thread

SYNOPSIS

#include <pthread.h>

voidpthread_yield(void);

DESCRIPTION

The pthread yield() forces the running thread to relinquish the processor until itagain becomes the head of its thread list.

SEE ALSO

sched yield(2)

STANDARDS

The pthread yield() is a non-portable (but quite common) extension to IEEE Std1003.1-2001 (“POSIX.1”).

Systems/C C Library 923

Page 942: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

THRD CREATE(3)

NAME

call once, cnd broadcast, cnd destroy, cnd init, cnd signal, cnd timedwait,cnd wait, mtx destroy, mtx init, mtx lock, mtx timedlock, mtx trylock, mtx unlock,thrd create, thrd current, thrd detach, thrd equal, thrd exit, thrd join, thrd sleep,thrd yield, tss create, tss delete, tss get, tss set - C11 threads interface

SYNOPSIS

#include <threads.h>

voidcall_once(once_flag *flag, void (*func)(void));

intcnd_broadcast(cnd_t *cond);

voidcnd_destroy(cnd_t *cond);

intcnd_init(cnd_t *cond);

intcnd_signal(cnd_t *cond);

intcnd_timedwait(cnd_t * restrict cond, mtx_t * restrict mtx,

const struct timespec * restrict ts);

intcnd_wait(cnd_t *cond, mtx_t *mtx);

voidmtx_destroy(mtx_t *mtx);

intmtx_init(mtx_t *mtx, int type);

intmtx_lock(mtx_t *mtx);

intmtx_timedlock(mtx_t * restrict mtx, const struct timespec * restrict ts);

924 Systems/C C Library

Page 943: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

intmtx_trylock(mtx_t *mtx);

intmtx_unlock(mtx_t *mtx);

intthrd_create(thrd_t *thr, int (*func)(void *), void *arg);

thrd_tthrd_current(void);

intthrd_detach(thrd_t thr);

intthrd_equal(thrd_t thr0, thrd_t thr1);

_Noreturn voidthrd_exit(int res);

intthrd_join(thrd_t thr, int *res);

intthrd_sleep(const struct timespec *duration, struct timespec *remaining);

voidthrd_yield(void);

inttss_create(tss_t *key, void (*dtor)(void *));

voidtss_delete(tss_t key);

void *tss_get(tss_t key);

inttss_set(tss_t key, void *val);

Systems/C C Library 925

Page 944: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

DESCRIPTION

As of ISO/IEC 9899:2011 (“ISO C11”), the C standard includes an API for writingmultithreaded applications. Since POSIX.1 already includes a threading API thatis used by virtually any multithreaded application, the interface provided by the Cstandard can be considered superfluous.

In this implementation, the threading interface is therefore implemented as a light-weight layer on top of existing interfaces. The functions to which these routines aremapped, are listed in the following table. Please refer to the documentation of thePOSIX equivalent functions for more information.

Function POSIX equivalent

call once() pthread once(3)

cnd broadcast() pthread cond broadcast(3)

cnd destroy() pthread cond destroy(3)

cnd init() pthread cond init(3)

cnd signal() pthread cond signal(3)

cnd timedwait() pthread cond timedwait(3)

cnd wait() pthread cond wait(3)

mtx destroy() pthread mutex destroy(3)

mtx init() pthread mutex init(3)

mtx lock() pthread mutex lock(3)

mtx timedlock() pthread mutex timedlock(3)

mtx trylock() pthread mutex trylock(3)

mtx unlock() pthread mutex unlock(3)

thrd create() pthread create(3)

thrd current() pthread self(3)

thrd detach() pthread detach(3)

thrd equal() pthread equal(3)

thrd exit() pthread exit(3)

thrd join() pthread join(3)

thrd sleep() nanosleep(2)

926 Systems/C C Library

Page 945: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

thrd yield() pthread yield(3)

tss create() pthread key create(3)

tss delete() pthread key delete(3)

tss get() pthread getspecific(3)

tss set() pthread setspecific(3)

DIFFERENCES WITH POSIX EQUIVALENTS

The thrd exit() function returns an integer value to the thread calling thrd join(),whereas the pthread exit() function uses a pointer.

The mutex created by mtx init() can be of type mtx plain or mtx timed to dis-tinguish between a mutex that supports mtx timedlock(). This type can be or’dwith mtx recursive to create a mutex that allows recursive acquisition. Theseproperties are normally set using pthread mutex init()’s attr parameter.

RETURN VALUES

If successful, the cnd broadcast(), cnd init(), cnd signal(), cnd timedwait(),cnd wait(), mtx init(), mtx lock(), mtx timedlock(), mtx trylock(),mtx unlock(), thrd create(), thrd detach(), thrd equal(), thrd join(),thrd sleep(), tss create() and tss set() functions return thrd success. Oth-erwise an error code will be returned to indicate the error.

The thrd current() function returns the thread ID of the calling thread.

The tss get() function returns the thread-specific data value associated with thegiven key. If no thread-specific data value is associated with key, then the valueNULL is returned.

ERRORS

The cnd init() and thrd create() functions will fail if:

thrd nonmem The system has insufficient memory.

The cnd timedwait() and mtx timedlock() functions will fail if:

thrd timedout The system time has reached or exceeded the time specified in tsbefore the operation could be completed.

Systems/C C Library 927

Page 946: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

The mtx trylock() function will fail if:

thrd busy The mutex is already locked.

In all other cases, these functions may fail by returning general error codethrd error.

SEE ALSO

nanosleep(2), pthread(3)

STANDARDS

These functions are expected to conform to ISO/IEC 9899:2011 (“ISO C11”).

928 Systems/C C Library

Page 947: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

CEEPIPI interface

Systems/C C Library 929

Page 948: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

CEEPIPI(3)

NAME

ceepipi - LE Pre-initialization interface services

SYNOPSIS

#include <stdlib.h>#include <machine/ceepipi.h>

int __CEEPIPI_init_main(__CEEPIT *ceexptbl_addr, void *service_rtns,int *token);

int __CEEPIPI_init_main_dp(__CEEPIT *ceexptbl_addr, void *service_rtns,int *token);

int __CEEPIPI_init_sub(__CEEPIT *ceexpttbl_addr, void *service_rtns,char *runtime_opts, int *token);

int __CEEPIPI_init_sub_dp(__CEEPIT *ceexpttbl_addr, void *service_rtns,char *runtime_opts, int *token);

int __CEEPIPI_call_main(int ceexptbl_index, int token,char *runtime_opts, void *parm_list,int *enclave_return_code,int *enclave_reason_code,__CEECTOK *appl_feedback_code);

int __CEEPIPI_call_sub(int ceexptbl_index, int token,void *parm_list,int *sub_ret_code,int *sub_reason_code,__CEECTOK *sub_feedback_code);

int __CEEPIPI_call_sub_addr(void *routine_addr, int token,void *parm_list,int *sub_ret_code,int *sub_reason_code,__CEECTOK *sub_feedback_code);

int __CEEPIPI_end_seq(int token);int __CEEPIPI_start_seq(int token);int __CEEPIPI_term(int token, int *env_return_code);int __CEEPIPI_add_entry( int token, char *routine_name,

void **routine_entry,int *ceexptbl_index);

int __CEEPIPI_delete_entry( int token, int ceexptbl_index);int __CEEPIPI_identify_entry( int token, int ceexptbl_index,

int *prog_language);int __CEEPIPI_identify_environment( int token, int *pipi_environment);int __CEEPIPI_identify_attributes( int token, int ceexptbl_index,

int *program_attributes);

930 Systems/C C Library

Page 949: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

int __CEEPIPI_set_user_word( int token, int value);int __CEEPIPI_get_user_word( int token, int *value);__CEEPIT *__CEEPIPI_alloc_CEEPIT( int flag, int n, ...);

DESCRIPTION

The Systems/C runtime provides an interface to IBM’s LE Pre-initialization facility(CEEPIPI). Using this, Systems/C code can invoke LE functions, pass parametersto them and retrieve return values.

For details on the LE Pre-initialization interface, consult the IBM documentation“z/OS Language Environment Programming Guide” (SA22-7561).

Systems/C C Library 931

Page 950: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

LIST OF FUNCTIONS

Name Appears on Page DescriptionCEEPIPI init main CEEPIPI init main(3) initialize for main

routinesCEEPIPI init main dp CEEPIPI init main dp(3) initialize for main

routines (multipleenvironment)

CEEPIPI init sub CEEPIPI init sub(3) initialize for subrou-tine

CEEPIPI init sub dp CEEPIPI init sub dp(3) initialize for subrou-tine (multiple envi-ronment)

CEEPIPI call main CEEPIPI call main(3) invocation for mainroutine

CEEPIPI call sub CEEPIPI call sub(3) invocation for subrou-tines

CEEPIPI call sub addr CEEPIPI call sub addr(3) invocation for subrou-tines by address

CEEPIPI end seq CEEPIPI end seq(3) end a sequence of callsCEEPIPI start seq CEEPIPI start seq(3) start a sequence of

callsCEEPIPI term CEEPIPI term(3) terminate environ-

mentCEEPIPI add entry CEEPIPI add entry(3) add entry to the

Preinit tableCEEPIPI delete entry CEEPIPI delete entry(3) delete entry from

Preinit tableCEEPIPI identify entry CEEPIPI identify entry(3) identify an entry in

the Preinit tableCEEPIPI identify environment CEEPIPI identify environment(3) identify the environ-

ment in the Preinittable

CEEPIPI identify attributes CEEPIPI identify attributes(3) identify the programattributes in thePreinit table

CEEPIPI set user word CEEPIPI set user word(3) set value to be usedto initialize CAA userword

CEEPIPI get user word CEEPIPI get user word(3) get value to be usedto initialize CAA userword

CEEPIPI alloc CEEPIT CEEPIPI alloc CEEPIT(3) create an populate aPreinit table

932 Systems/C C Library

Page 951: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

EXAMPLE

The following C code uses the CEEPIPI functions to invoke an LE C function named”HLLPIPI”:

#include <stdio.h>#include <string.h>#include <stdlib.h>#include <machine/ceepipi.h>

main(){

int rc;int token;__CEEPIT *cexptbl;int subretc, subrsnc;__CEECTOK subfbc;int env_rc;

int parms[1];

printf("Dignus C caller of LE HLLPIPI function\n");

/** Allocate and populate an LE Preinitialization table* This table has one entry, HLLPIPI*/cexptbl = __CEEPIPI_alloc_CEEPIT(0, 1, "HLLPIPI");if(cexptbl == NULL) {

printf("Out of memory allocating pre-init table");exit(12);

}

/** Initialize an LE preinitialization subroutine environment*/rc = __CEEPIPI_init_sub(cexptbl, NULL, NULL, &token);if(rc != 0) {

printf("CEEPIPI init_sub failed - rc is %d\n", rc);exit(12);

}

/** Call the subroutine HLLPIPI(int parm);* The value being passed is "20"

Systems/C C Library 933

Page 952: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

*/parms[0] = 20;rc = __CEEPIPI_call_sub(0 /* function #0 */,

token, parms, &subretc, &subrsnc, &subfbc);

printf("call_sub() returns %d\n", rc);printf(" subretc=%d, subrsnc=%d\n", subretc, subrsnc);

if(rc != 0) {printf("CEEPIPI_call_sub failed - rc is %d\n", rc);exit(12);

}

/** Terminate the environment*/rc = __CEEPIPI_term(token, &env_rc);if(rc != 0) {

printf("CEEPIPI_term failed - rc is %d\n", rc);exit(12);

}

/* free the pre-init table’s memory */free(cexptbl);

}

The function HLLPIPI is written in C and compiled and linked in LE mode toproduce a loadable LE module:

/** HLLPIPI is called by the C program* using the LE preinitialization program* subroutine call interface.**/

#include <stdio.h>#include <string.h>#pragma linkage(HLLPIPI, fetchable)

intHLLPIPI(int parm){int retval = 100;printf(" Enter HLLPIPI\n");printf(" This is an LE C program invoked from Dignus C!\n");printf(" The parameter passed was: %d\n", parm);

934 Systems/C C Library

Page 953: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

printf(" Exit HLLPIPI - returning %d\n", retval+parm);retval = retval + parm;return retval;

}

Systems/C C Library 935

Page 954: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

CEEPIPI init main(3)

NAME

CEEPIPI init main - initialize for main routines

SYNOPSIS

#include <stdlib.h>#include <machine/ceepipi.h>

int __CEEPIPI_init_main(__CEEPIT *ceexptbl_addr, void *service_rtns,int *token);

DESCRIPTION

The CEEPIPI init main() function creates and ininitializes a LE runtime en-vironment that allows for multiple executions of the main routine.

ceexptbl addr pointers to a PreInit table used during initialization of the environ-ment.

token points to a integer to return a value used to identify the newly created envi-ronment.

service rtns contains a pointer to a service routines vector or NULL.

RETURN VALUES

On success, CEEPIPI init main() returns 0. Otherwise, it returns the returncode specified in the IBM Language Environment Preinitialization Interface docu-mentation.

SEE ALSO

For detailed information about the IBM Preinitialization interface, consult the IBMdocument “z/OS Language Environment Programming Guide”.

936 Systems/C C Library

Page 955: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

CEEPIPI init main dp(3)

NAME

CEEPIPI init main dp - initialize for main routines (multiple environments)

SYNOPSIS

#include <stdlib.h>#include <machine/ceepipi.h>

int __CEEPIPI_init_main_dp(__CEEPIT *ceexptbl_addr, void *service_rtns,int *token);

DESCRIPTION

The CEEPIPI init main dp() function creates and ininitializes a Language En-vironment (LE) runtime environment that allows for multiple executions of the mainroutine. CEEPIPI init main dp() ensures that the environment tolerates theexistence of multiple IBM Language Environment processes or enclaves, thus multi-ple main environments can be establised using CEEPIPI init main dp() whereCEEPIPI init main() can only establish one environment.

ceexptbl addr pointers to a PreInit table used during initialization of the environ-ment.

token points to a integer to return a value used to identify the newly created envi-ronment.

service rtns contains a pointer to a service routines vector or NULL.

RETURN VALUES

On success, CEEPIPI init main dp() returns 0. Otherwise, it returns the re-turn code specified in the IBM Language Environment Preinitialization Interfacedocumentation.

SEE ALSO

For detailed information about the IBM Preinitialization interface, consult the IBMdocument “z/OS Language Environment Programming Guide”.

Systems/C C Library 937

Page 956: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

CEEPIPI init sub(3)

NAME

CEEPIPI init sub - initialize for subroutines

SYNOPSIS

#include <stdlib.h>#include <machine/ceepipi.h>

int __CEEPIPI_init_sub(__CEEPIT *ceexpttbl_addr, void *service_rtns,char *runtime_opts, int *token);

DESCRIPTION

The CEEPIPI init sub() function creates and ininitializes a Language Environ-ment (LE) runtime environment that allows for multiple executions of subroutines.

ceexptbl addr pointers to a PreInit table used during initialization of the environ-ment.

runtime opts is a character string containing the LE runtime options. See the IBM“z/OS Language Environment Programming Reference” documentation for a list ofavailable runtime options.

token points to a integer to return a value used to identify the newly created envi-ronment.

service rtns contains a pointer to a service routines vector or NULL.

RETURN VALUES

On success, CEEPIPI init sub() returns 0. Otherwise, it returns the returncode specified in the IBM Language Environment Preinitialization Interface docu-mentation.

SEE ALSO

For detailed information about the IBM Preinitialization interface, consult the IBMdocument “z/OS Language Environment Programming Guide”.

938 Systems/C C Library

Page 957: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

CEEPIPI init sub dp(3)

NAME

CEEPIPI init sub dp - initialize for subroutine (multiple environment)

SYNOPSIS

#include <stdlib.h>#include <machine/ceepipi.h>

int __CEEPIPI_init_sub_dp(__CEEPIT *ceexpttbl_addr, void *service_rtns,char *runtime_opts, int *token);

DESCRIPTION

The CEEPIPI init sub dp() function creates and ininitializes a LE run-time environment that allows for multiple executions of subroutines. UnlikeCEEPIPI init sub(), CEEPIPI init sub dp() can establish multiple envi-

ronments.

ceexptbl addr pointers to a PreInit table used during initialization of the environ-ment.

runtime opts is a character string containing the LE runtime options. See the IBM“z/OS Language Environment Programming Reference” documentation for a list ofavailable runtime options.

token points to a integer to return a value used to identify the newly created envi-ronment.

service rtns contains a pointer to a service routines vector or NULL.

RETURN VALUES

On success, CEEPIPI init sub dp() returns 0. Otherwise, it returns the re-turn code specified in the IBM Language Environment Preinitialization Interfacedocumentation.

SEE ALSO

For detailed information about the IBM Preinitialization interface, consult the IBMdocument “z/OS Language Environment Programming Guide”.

Systems/C C Library 939

Page 958: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

CEEPIPI call main(3)

NAME

CEEPIPI call main - invocation for main routine

SYNOPSIS

#include <stdlib.h>#include <machine/ceepipi.h>

int __CEEPIPI_call_main(int ceexptbl_index, int token,char *runtime_opts, void *parm_list,int *enclave_return_code,int *enclave_reason_code,__CEECTOK *appl_feedback_code);

DESCRIPTION

The CEEPIPI call main() function invokes the specified main routine indicatedby lvarceexptbl index in the environment specified by token. After the routine re-turns, the environment becomes dormant.

ceexptbl index indicates which entry in the environment’s PreInit table is to be in-voked.

token is the environment’s identifier.

runtime opts is a character string containing the LE runtime options. See the IBM“z/OS Language Environment Programming Reference” documentation for a list ofavailable runtime options.

parm list is either NULL or an array of parameter values passed to the main routine.

enclave return code points to an integer where the return code from the enclave issaved after the main routine completes.

enclave reason code points to an integer where the reason code from the enclave issaved after the main routine completes.

appl feedback code points to 96-bit condition token indicating why the applicationterminated.

940 Systems/C C Library

Page 959: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

RETURN VALUES

On success, CEEPIPI call main() returns 0. Otherwise, it returns the returncode specified in the IBM Language Environment Preinitialization Interface docu-mentation.

SEE ALSO

For detailed information about the IBM Preinitialization interface, consult the IBMdocument “z/OS Language Environment Programming Guide”.

Systems/C C Library 941

Page 960: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

CEEPIPI call sub(3)

NAME

CEEPIPI call sub - invocation for subroutines

SYNOPSIS

#include <stdlib.h>#include <machine/ceepipi.h>

int __CEEPIPI_call_sub(int ceexptbl_index, int token,void *parm_list,int *sub_ret_code,int *sub_reason_code,__CEECTOK *sub_feedback_code);

DESCRIPTION

The CEEPIPI call sub() function invokes the specified sub routine indicatedby lvarceexptbl index in the environment specified by token.

ceexptbl index indicates which entry in the environment’s PreInit table is to be in-voked.

token is the environment’s identifier.

parm list is either NULL or an array of parameter values passed to the sub routine.

sub ret code points to an integer where the return code from the enclave is savedafter the sub routine completes.

sub reason code points to an integer where the reason code from the enclave is savedafter the sub routine completes.

sub feedback code points to 96-bit condition token.

RETURN VALUES

On success, CEEPIPI call sub() returns 0. Otherwise, it returns the returncode specified in the IBM Language Environment Preinitialization Interface docu-mentation.

942 Systems/C C Library

Page 961: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

SEE ALSO

For detailed information about the IBM Preinitialization interface, consult the IBMdocument “z/OS Language Environment Programming Guide”.

Systems/C C Library 943

Page 962: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

CEEPIPI call sub addr(3)

NAME

CEEPIPI call sub addr - invocation for subroutines by address

SYNOPSIS

#include <stdlib.h>#include <machine/ceepipi.h>

int __CEEPIPI_call_sub_addr(void *routine_addr, int token,void *parm_list,int *sub_ret_code,int *sub_reason_code,__CEECTOK *sub_feedback_code);

DESCRIPTION

The CEEPIPI call sub addr() function invokes the specified sub routine indi-cated by lvarroutine addr in the environment specified by token.

routine addr is a pointer to a structure containing two pointers. The first pointerpoints to the function’s entry point. Initially, the second pointer should be NULL.If the environment is XPLINK, the IBM Preinitilization services will provide a newpointer in the second pointer for directly invoking the function on a subsequent call.If the environment is XPLINK and the second pointer is not NULL, then the secondpointer is used to directly invoke the function and avoid some overhead.

token is the environment’s identifier.

parm list is either NULL or an array of parameter values passed to the sub routine.

sub ret code points to an integer where the return code from the enclave is savedafter the sub routine completes.

sub reason code points to an integer where the reason code from the enclave is savedafter the sub routine completes.

sub feedback code points to 96-bit condition token.

RETURN VALUES

On success, CEEPIPI call sub addr() returns 0. Otherwise, it returns thereturn code specified in the IBM Language Environment Preinitialization Interfacedocumentation.

944 Systems/C C Library

Page 963: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

SEE ALSO

For detailed information about the IBM Preinitialization interface, consult the IBMdocument “z/OS Language Environment Programming Guide”.

Systems/C C Library 945

Page 964: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

CEEPIPI end seq(3)

NAME

CEEPIPI end seq - end a sequence of calls

SYNOPSIS

#include <stdlib.h>#include <machine/ceepipi.h>

int __CEEPIPI_end_seq(int token);

DESCRIPTION

The CEEPIPI end seq() indicates the end of a sequence of uniterrupted sub-routine calls for the given environment.

token is the environment’s identifier.

RETURN VALUES

On success, CEEPIPI end seq() returns 0. Otherwise, it returns the returncode specified in the IBM Language Environment Preinitialization Interface docu-mentation.

SEE ALSO

For detailed information about the IBM Preinitialization interface, consult the IBMdocument “z/OS Language Environment Programming Guide”.

946 Systems/C C Library

Page 965: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

CEEPIPI start seq(3)

NAME

CEEPIPI start seq - start a sequence of calls

SYNOPSIS

#include <stdlib.h>#include <machine/ceepipi.h>

int __CEEPIPI_start_seq(int token);

DESCRIPTION

The CEEPIPI start seq() function indicates that the program is to begin asequence of uninterrupted calls into subroutines for the given environment. Thisminimizes overhead between calls.

token is the environment’s identifier.

RETURN VALUES

On success, CEEPIPI start seq() returns 0. Otherwise, it returns the returncode specified in the IBM Language Environment Preinitialization Interface docu-mentation.

SEE ALSO

For detailed information about the IBM Preinitialization interface, consult the IBMdocument “z/OS Language Environment Programming Guide”.

Systems/C C Library 947

Page 966: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

CEEPIPI term(3)

NAME

CEEPIPI term - terminate environment

SYNOPSIS

#include <stdlib.h>#include <machine/ceepipi.h>

int __CEEPIPI_term(int token, int *env_return_code);

DESCRIPTION

The CEEPIPI term() function terminates the environment indicated by token.

token is the environment’s identifier.

RETURN VALUES

On success, CEEPIPI term() returns 0. Otherwise, it returns the return codespecified in the IBM Language Environment Preinitialization Interface documenta-tion.

SEE ALSO

For detailed information about the IBM Preinitialization interface, consult the IBMdocument “z/OS Language Environment Programming Guide”.

948 Systems/C C Library

Page 967: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

CEEPIPI add entry(3)

NAME

CEEPIPI add entry - add an entry to the PreInit table

SYNOPSIS

#include <stdlib.h>#include <machine/ceepipi.h>

int __CEEPIPI_add_entry( int token, char *routine_name,void **routine_entry,int *ceexptbl_index);

DESCRIPTION

The CEEPIPI add entry() adds an entry to the environment indicated by to-ken. If routine entry is NULL, then the routine name given in routine name is used.The index used is returned in ceexptbl index.

CEEPIPI add entry() does not extend the PreInitialization table.

token is the environment’s identifier.

routine name is a left-justified, blank-padded 8-character sequence of characterscontaining the name of the routine. When not used this field should be all blanks.

routine entry is NULL to indicate that routine name should be used; otherwise it isthe address to be added to the table. The high-order bit of this address is usedto indicate the AMODE. If the routine is succesfully added, this will be set to theaddress of the added routine.

On a successful routine, *ceexptl index will contain the index into the PreInitializa-tion table of the added routine.

RETURN VALUES

On success, CEEPIPI add entry() returns 0. Otherwise, it returns the returncode specified in the IBM Language Environment Preinitialization Interface docu-mentation.

Systems/C C Library 949

Page 968: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

SEE ALSO

For detailed information about the IBM Preinitialization interface, consult the IBMdocument “z/OS Language Environment Programming Guide”.

950 Systems/C C Library

Page 969: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

CEEPIPI delete entry(3)

NAME

CEEPIPI delete entry - delete an entry from the PreInit table

SYNOPSIS

#include <stdlib.h>#include <machine/ceepipi.h>

int __CEEPIPI_delete_entry( int token, int ceexptbl_index);

DESCRIPTION

The CEEPIPI delete entry() removes the routine specified by ceexptbl indexfrom the environment indicated by token.

RETURN VALUES

On success, CEEPIPI delete entry() returns 0. Otherwise, it returns the re-turn code specified in the IBM Language Environment Preinitialization Interfacedocumentation.

SEE ALSO

For detailed information about the IBM Preinitialization interface, consult the IBMdocument “z/OS Language Environment Programming Guide”.

Systems/C C Library 951

Page 970: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

CEEPIPI identify entry(3)

NAME

CEEPIPI identify entry - Identify an entry in the PreInit table

SYNOPSIS

#include <stdlib.h>#include <machine/ceepipi.h>

int __CEEPIPI_identify_entry( int token, int ceexptbl_index,int *prog_language);

DESCRIPTION

The CEEPIPI identify entry() indicates the the programming language of thefunction identified by ceexptbl index for the environment indicated by token.

*prog language will contain the possible language codes, defined as:

CEEPIPI C C/C++

CEEPIPI COBOL COBOL

CEEPIPI PLI PL/I

CEEPIPI EPLI Enterprise PL/I for z/OS

CEEPIPI ASM Language Environment-enabled assembler

CEEPIPI PLX PL/X

RETURN VALUES

On success, CEEPIPI identify entry() returns 0. Otherwise, it returns thereturn code specified in the IBM Language Environment Preinitialization Interfacedocumentation.

SEE ALSO

For detailed information about the IBM Preinitialization interface, consult the IBMdocument “z/OS Language Environment Programming Guide”.

952 Systems/C C Library

Page 971: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

CEEPIPI identify environment(3)

NAME

CEEPIPI identify environment - identify the environment in the PreInit table

SYNOPSIS

#include <stdlib.h>#include <machine/ceepipi.h>

int __CEEPIPI_identify_environment( int token, int *pipi_environment);

DESCRIPTION

The CEEPIPI identify environment() indicates the type of environment thatwas preinitialized.

*prog language will contain the possible language codes, defined as:

CEEPIPI ceepipi main PreInit main environment is initialized.

CEEPIPI enclave initialized PreInit enclave is initialized.

CEEPIPI dp environment PreInit sub db environment is intialized.

CEEPIPI seq of calls active PreInit seq call function is active.

CEEPIPI exits established PreInit sub dp exits is set.

CEEPIPI sir unregistered PreInit sir is registered.

CEEPIPI sub environment PreInit sub environment is initialized.

CEEPIPI XPLINK environment PreInit XPLINK environment is initialized.

CEEPIPI init main dp environment PreInit main dp environment is initialized.

RETURN VALUES

On success, CEEPIPI identify environment() returns 0. Otherwise, it re-turns the return code specified in the IBM Language Environment PreinitializationInterface documentation.

Systems/C C Library 953

Page 972: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

ERRORS

SEE ALSO

For detailed information about the IBM Preinitialization interface, consult the IBMdocument “z/OS Language Environment Programming Guide”.

954 Systems/C C Library

Page 973: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

CEEPIPI identify attributes(3)

NAME

CEEPIPI identify attributes - identify the program attributes in the PreInit table

SYNOPSIS

#include <stdlib.h>#include <machine/ceepipi.h>

int __CEEPIPI_identify_attributes( int token, int ceexptbl_index,int *program_attributes);

DESCRIPTION

On success, CEEPIPI identify attributes() function identified the programattributes of the routine specified by ceexptbl index.

*prog language will contain the possible language codes, defined as:

CEEPIPI loaded by pipi The Preinitialization entry was loaded by IBM LanguageEnvironment.

CEEPIPI XPLINK program The loaded Preinitialization entry is an XPLINK pro-gram.

CEEPIPI address not resolved The Preinitialization entry could not be loaded.

RETURN VALUES

On success, CEEPIPI identify attributes() returns 0. Otherwise, it returnsthe return code specified in the IBM Language Environment Preinitialization Inter-face documentation.

SEE ALSO

For detailed information about the IBM Preinitialization interface, consult the IBMdocument “z/OS Language Environment Programming Guide”.

Systems/C C Library 955

Page 974: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

CEEPIPI set user word(3)

NAME

CEEPIPI set user word - set value to be used to initialize CAA user word

SYNOPSIS

#include <stdlib.h>#include <machine/ceepipi.h>

int __CEEPIPI_set_user_word( int token, int value);

DESCRIPTION

The CEEPIPI set user word() saves the given value to be used when the initialCAA thread is created when a main routine or subroutine is invoked.

RETURN VALUES

On success, CEEPIPI set user word() returns 0. Otherwise, it returns thereturn code specified in the IBM Language Environment Preinitialization Interfacedocumentation.

ERRORS

SEE ALSO

For detailed information about the IBM Preinitialization interface, consult the IBMdocument “z/OS Language Environment Programming Guide”.

956 Systems/C C Library

Page 975: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

CEEPIPI get user word(3)

NAME

CEEPIPI get user word - get value to be used to initialize CAA user word

SYNOPSIS

#include <stdlib.h>#include <machine/ceepipi.h>

int __CEEPIPI_get_user_word( int token, int *value);

DESCRIPTION

The CEEPIPI get user word() retrieves the current user-word value for theenvironment indicated by token.

On return, *value will contain the current value used to initialize the CAA user word.

RETURN VALUES

On success, CEEPIPI get user word() returns 0. Otherwise, it returns thereturn code specified in the IBM Language Environment Preinitialization Interfacedocumentation.

SEE ALSO

For detailed information about the IBM Preinitialization interface, consult the IBMdocument “z/OS Language Environment Programming Guide”.

Systems/C C Library 957

Page 976: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

CEEPIPI alloc CEEPIT(3)

NAME

CEEPIPI alloc CEEPIT - allocate and initialize a PreInit table

SYNOPSIS

#include <stdlib.h>#include <machine/ceepipi.h>

__CEEPIT *__CEEPIPI_alloc_CEEPIT( int flag, int n, ...);

DESCRIPTION

CEEPIPI alloc CEEPIT() dynamically allocates a PreInitialization table suf-ficiently large to contain n entries. Following n should be n parameters that areeither NULL or a pointer to a character string for the function name.

For example,

__CEEPIT *ceexptbl;

ceexptbl = __CEEPIPI_alloc_CEEPIT(0, 2, "FUNC", NULL);

allocates a table sufficiently large for 2 entries, the first entry will be initialized withthe function name ”FUNC”.

If there is insufficient available memory, CEEPIPI alloc CEEPIT() returnsNULL.

A non-NULL address returned by CEEPIPI alloc CEEPIT() should be returnedusing the free(3) function.

RETURN VALUES

On success, CEEPIPI alloc CEEPIT() returns a pointer to the allocated mem-ory, or NULL if space was not available.

958 Systems/C C Library

Page 977: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

SEE ALSO

For detailed information about the IBM Preinitialization interface, and the formatof the PreInitialization table, consult the IBM document “z/OS Language Environ-ment Programming Guide”.

Systems/C C Library 959

Page 978: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

Keyed Access (VSAM) I/O

960 Systems/C C Library

Page 979: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

VSAMIO(3)

NAME

vsamio - keyed access (VSAM) input/output library functions

SYNOPSIS

#include <fcntl.h>#include <unistd.h>#include <machine/vsamio.h>

KFILE * kopen (const char *ddn, const char *parms, int mode);int kclose (KFILE *k);int kretrv (void *rec, void *key, int flags, KFILE *k);int ksearch (const void *key, size_t keylen, int flags, KFILE *k);int kinsert (const void *rec, size_t length, void *key, KFILE *k);int kdelete (const void *key, KFILE *k);int kreplace (const void *rec, size_t length, KFILE *k);int kgetpos (KFILE *f, kpos_t *pos);int ksetpos (KFILE *f, const kpos_t *pos);int kdata (KFILE *k, __KFILE_data *d);int kerrinfo (KFILE *k, char *RPLRTNCD, char *RPLCMPON, char *RPLERRCD);

ssize_t kread (KFILE *k, void *buf, size_t nbytes):ssize_t kwrite (KFILE *k, void *buf, size_t nbytes):off_t kseek (KFILE *k, off_t offset, int whence):

DESCRIPTION

The Systems/C runtime supports accessing VSAM files via the VSAMIO functions.

Unlike other mainframe C implementations; this access is not bound with the Stan-dard C input/output functions. The Systems/C runtime supports a more nativeVSAM facility which more closely matches the z/OS VSAM function.

Opening a VSAM file is accomplished with the kopen(3) function, that returns apointer to a KFILE “handle”. A KFILE pointer can then be passed to the otherVSAMIO functions, described here, to read records, search the file, add records,close the file, etc...

Note that VSAMIO is only supported on z/OS, and only for AMODE 31 programs.

For many of the functions described here, the Systems/C runtime library will mapthe VSAM logical errors to errno values as well as the specific errno values providedin the function descriptions:

Systems/C C Library 961

Page 980: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

[ENOSPC] #4 - end of data set

[EEXIST] #8 - duplicate key

[EILSEQ] #12 - an attempt was made to perform sequential or skip-sequentialprocessing against a record whose key/record number does not fol-low the proper ascending/descending sequential order.

[ENOENT] #16 - record not found.

[ENOLCK] #20 - control Interval exclusive use conflict

[ENOLCK] #21, #22 - for RRS, another LUWID holds the lock

[ENXIO] #24 - record lives on volume that connot be mounted

[ENOSPC] #28 - can’t extend dataset because there’s no space.

[ENOENT] #32- XRBA specified does not address any record

[EINVAL] #36 - key ranges were specified for the data set when it was defined,but no range was specified that includes the record to be inserted.

[ENOMEM] #40 - no memory.

[ENOMEM] #44 - work area not large enough for the record.

[EINVAL] #48, #52- invalid options, data set attributes or processing condi-tions.

[EIO] #56 - ACB or LUWID changed underneath the RPL (an RPLreused violation).

[ENOMEM] #64 - no space to add another string.

[EINVAL] #68 - invalid type of processing (i.e. read from OUTPUT)

[EINVAL] #72 - keyed request for ESDS, or GETIX/PUTIX to ESDS orflexed-length RRDS. For RLS - GETIX/PUTIX issued.

[EINVAL] #76 - issued an addressed or CI PUT to add a KSDS or variable-length RRDS, or, issued a constrol interval PUT to a fixed-lengthRRDS.

[EINVAL] #80 - invalid ERASE request.

[EINVAL] #84 - invalid OPTCD=LOC for PUT.

[ESPIPE] #88 - sequential GET request without proper positioning, or, illegalswitch between forward/backward processsing

[EINVAL] #92 - issued PUT for update, or ERASE without previous GET forupdate, or PUTIX without previous GETIX

[EINVAL] #96 - change the primary key will making an update.

962 Systems/C C Library

Page 981: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

[EINVAL] #100 - changed the length of the record while making update.

[EINVAL] #104 - invalid RPL.

[EINVAL] #108 - invalid RECLEN.

[EINVAL] #112 - KEYLEN too large or is zero.

[EINVAL] #116 - initial loading of empty data set not allow UPDATE(OPTCD=UPD) mode.

[EINVAL] #120 - request is operating under wrong TCB.

[ECANCELED] #124 - request was cancelled by user JRNAD exit.

[ELOOP] #128 - a loop was discovered in index.

[EINVAL] #132 - attempt, in locate mode, to retrieve a spanned record.

[EINVAL] #136 - attemped an addressed GET of a spanned record in a KSDS.

[ENOENT] #144 - invalid pointer (no associated base record) in an alternateindex.

[ENOSPC] #148 - maximum number of pointers is alternate index exceeded.

[ENOMEM] #152 - not enough buffers.

[EIO] #156 - invalid control-interval discovred during Keyed processing.

[EBUSY] #160 - buffer multiply marked written.

[EFAULT] #168 - for RLS, the pointer in the RPL is zero.

[EIO] #180 - for RLS, an invalid request for a non-recoverable data set.

[EIO] #184 - for RLS, an ABEND occured during processing.

[ECANCELED] #185 - for RLS, user task cancelled while request was being pro-cessed.

[ENOSPC] #186 - End-of-Volume init failed when attempted to extend.

[EIO] #187 - for RLS, error occured with partial EOV processing.

[EIO] #188 - for RLS, the sphere is in lost locks state.

[EINVAL] #192 - invalid relative record number.

[EINVAL] #196 - addressed request for fixed- or variable-length RRDS.

[EINVAL] #200 - attempted addressed or control-interval access through apath.

[EINVAL] #204 - PUT insert requests (or for RLS, IDALKADD requests) arenot allowed in backward mode.

Systems/C C Library 963

Page 982: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

[EBUSY] #208 - ENDREQ macro isseud against an RPL that has an out-standing WAIT against its associated ECB.

[ENOSPC] #212 - During split processing, an existing condition prevents thesplit - Index or data control interval size may need to be increased.

[EIO] #218 - unrecognized return code.

[EINVAL] #224 - MRKBFR OUT was issued for a buffer with invalid contents.

[EPERM] #228 - cross-memory issues.

[ENOSPC] #229 - record length changed during decompression.

[EIO] #230 - processing environment changed by the user of UPAP exit.

[EPERM] #232 - UPAD error; ECB was not posted by user in cross-memory.

[EINVAL] #236 - validity check of errof re SHAROPTIONS 3 or 4.

[EIO] #237, #238, #239, #241, #242, #243 - reserved.

[EAGAIN] #240 - for shared resources, one of the following is being performed:(1) an attempt is being made to obtain a buffer in exclusived con-tro, (2) a buffer is being invalidated, or (3) the buffer use chain ischaking. For more detailed feedback, reissue the request.

[EFAULT] #244 - register 14 stack size is not large enough.

[EIO] #246 - severe error returned by decompression management.

[EIO] #250 - no valid dictionary token exists for the data set. VSAM isunable to decompress the data record.

[EINVAL] #252 - record mode processing not allowed for LDS.

[EINVAL] #253 - VERIFY is not valid for LDS.

[EBUSY] #254 - I/O activity on the data set not quiesced before WRTBTFTYPE=DS issued.

LINEAR DATA SETS

Unlike other keyed-access files, a Linear Data Set represents a stream of bytes,processed in 4K blocks with no other structure. There is no record format, and nokey (beyond a simple offset value) for accessing particular sections of data. LinearData Sets are often used in data base environments and to implement z/OS USSfile systems.

The kopen(3) function can be used to open a Linear Data Set. In that case, the DataIn Virtual (DIV) macros are used to perform I/O to the file, not the normal VSAM

964 Systems/C C Library

Page 983: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

related system macros. (For more information about DIV see the IBM manual”z/OS Application Development Guide.”)

DIV access to the Linear Data set provides a mechanism to map sections of the fileinto memory via ”windows”. Each window represents bytes from the file beginningat a certain offset for a particular number of bytes. The bufsize and bufmax parmsof the kopen(3) function specify the size and number of DIV windows the systemwill manage to access the Linear Data Set.

The kread(3), kwrite(3) and kseek(3) functions are used with Linear Data Sets, inlieu of the other keyed access functions. These provide mechanisms for reading andwriting a stream of bytes or positioning to a given offset. Besides kopen(3) andkclose(3), these are the only functions that can be used for I/O with Linear DataSets.

When kopen(3) opens a Linear Data set, the system allocates the first window (if nospace can be allocated, then the kopen(3) will fail.) After that, windows of the givensize are allocated until the total count reaches the specified limit, or allocations faildue to unavailable memory. When no more DIV windows can be used, the systemreuses existing windows in a least-recently-used fashion.

The kwrite(3) function does not directly cause output to the Linear Data Set, theactual writing to the file system occurs when the DIV window is released, either onreuse or when the kclose(3) function closes the Linear Data Set.

Systems/C C Library 965

Page 984: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

LIST OF FUNCTIONS

Name Appears on Page Descriptionkclose kclose(3) close a keyed-access, or Linear

Data Set filekdata kdata(3) provide information about an

open keyed-access filekdelete kdelete(3) delete the previously retrieved

recordkgetpos kgetpos(3) return the position of the cur-

rent recordkerrinfo kerrinfo(3) provide information about

last logical errorkinsert kinsert(3) insert a record into a keyed-

access filekopen kopen(3) open a keyed-access or Linear

Data Set filekreplace kreplace(3) replace the previously re-

trieved recordkretrv kretrv(3) retrieve the next recordksearch ksearch(3) search for a record with a

specified keyksetpos ksetpos(3) set the position to a previous

saved value

Name Appears on Page Descriptionkread kread(3) read data from a Linear Data

Set (LDS)kseek kseek(3) position to a particular byte

offset in a Linear Data Set(LDS)

kwrite kwrite(3) write data to a Linear DataSet (LDS)

966 Systems/C C Library

Page 985: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

KCLOSE(3)

NAME

kclose - close a keyed-access or Linear Data Set file.

SYNOPSIS

#include <fcntl.h>#include <machine/vsamio.h>

int kclose (KFILE *k);

DESCRIPTION

The kclose() function closes a previously opened keyed-access or Linear Data Setfile.

RETURN VALUES

If there is an error or an invalid KFILE was specified, kopen() returns -1; otherwisea 0 value is returned, indicating success.

ERRORS

When a failure is returned, errno is set to one of the following values:

[EIO] The VSAM CLOSE macro indicated a non-zero return code.

[EFAULT] The specified KFILE k was an invalid pointer.

[EBADF] The specified KFILE k was not open.

SEE ALSO

kopen(3)

Systems/C C Library 967

Page 986: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

KDATA(3)

NAME

kdata - return information about an open keyed-access file

SYNOPSIS

#include <fcntl.h>#include <machine/vsamio.h>

int kdata (KFILE *k, __KFILE_data *d)

DESCRIPTION

The kdata() function populates the KFILE data structure addressed by d fromthe KFILE pointer k.

The KFILE data structure (shown below) is defined in <machine/vsamio.h>.

typedef struct __KFILEdata {unsigned int access:2;

#define _KFILE_ACCESS_UNKNOWN (0)#define _KFILE_ACCESS_SEQUENTIAL (1)#define _KFILE_ACCESS_DIRECT (2)#define _KFILE_ACCESS_SKIP_SEQUENTIAL (3)

unsigned int vsam_org:5;#define _KFILE_VSAM_ORG_UNKNOWN (0)#define _KFILE_VSAM_ORG_KSDS (1)#define _KFILE_VSAM_ORG_RRDS (2)#define _KFILE_VSAM_ORG_ESDS (3)#define _KFILE_VSAM_ORG_LDS (4)

unsigned int mode:4;#define _KFILE_VSAM_MODE_UNKNOWN (0)#define _KFILE_VSAM_MODE_INPUT (1)#define _KFILE_VSAM_MODE_OUTPUT (2)#define _KFILE_VSAM_MODE_UPDATE (3)

unsigned char *ddname;unsigned int vsam_keylen;unsigned int vsam_keyoff;unsigned int reclen;unsigned int last_read_reclen;

} __KFILE_data;

968 Systems/C C Library

Page 987: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

The fields of the KFILE data structure are:

access How the VSAM file may be accessed. The access field will beset to one of KFILE ACCESS UNKNOWN, KFILE ACCESS SEQUENTIAL,KFILE ACCESS DIRECT, or KFILE ACCESS SKIP SEQUENTIAL,

vsam org VSAM file organization. The vsam org field will be set toone of KFILE VSAM ORG UNKNOWN, KFILE VSAM ORG KSDS,KFILE VSAM ORG RRDS, KFILE VSAM ORG ESDS, orKFILE VSAM ORG LDS.

mode I/O mode. The mode field will be set to one of VSAM MODE UNKNOWN,VSAM MODE INPUT, VSAM MODE OUTPUT or VSAM MODE UPDATE,

ddname Pointer to the DDNAME used to open the file. This space will beoverwritten on subsequent invocations of kdata().

vsam keylen Key length specified at open or 0.

vsam keyoff Offset of key specified at open or 0.

reclen Record length specified at open.

last read reclen Length of the last record read.

RETURN VALUES

On success, kdata() returns 1. If there was an error, kdata() returns 0 and setsthe errno value.

ERRORS

When a failure is returned, errno is set to one of the following values.

[EFAULT] The specified KFILE k or KFILE data d was an invalid pointer.

SEE ALSO

kopen(3)

Systems/C C Library 969

Page 988: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

KDELETE(3)

NAME

kdelete - delete the last record retrieved

SYNOPSIS

#include <fcntl.h>#include <machine/vsamio.h>

int kdelete (const void *key, KFILE *k);

DESCRIPTION

The kdelete() function removes the previously retrieved record from the keyed-access file k.

The previously retrieved record must be accessed with the kretrv(3) function.

The key parameter is currently ignored.

RETURN VALUES

On success, kdelete() returns 0. If there was an error, kdelete() returns -1 andsets the errno value.

ERRORS

When a failure is returned, errno is set to one of the following values, as well as thegeneric mapping of VSAM logical errors to errno values.

[EFAULT] The specified KFILE k was an invalid pointer.

[EBADF] The specified KFILE k was not open.

[EIO] There was no previously retrieved record.

[EIO] The return value from the ERASE macro was greater than 8.

[ENOSYS] The RPL for the VSAM file could not be accessed or modified.

970 Systems/C C Library

Page 989: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

SEE ALSO

kretrv(3), kreplace(3)

Systems/C C Library 971

Page 990: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

KERRINFO(3)

NAME

kerrinfo - provide information about last logical error

SYNOPSIS

#include <fcntl.h>#include <machine/vsamio.h>

int kerrinfo (KFILE *k, char *RPLRTNCD, char *RPLCMPON, char *RPLERRCD);

DESCRIPTION

When a VSAM logical error occurs, the VSAM library executes a VSAM SHOWCBFIELDS=FDBK macro to discern the reasons for the logical error and set the errnovalue appropriately.

The kerrinfo() function returns the values set by that SHOWCB invocation.

If the keyed-access file function returns an error indication, the kerrinfo() functioncan be used to learn more details about the error condition.

These values are set to zero before every VSAM operation, so if the values arezero, there is no more information available, or the error condition was unrelated toVSAM functions.

RETURN VALUES

On success, kerrinfo() returns 1. If there was an error, kerrinfo() returns 0 andsets the errno value.

ERRORS

When a failure is returned, errno is set to one of the following values.

[EFAULT] The specified KFILE k was an invalid pointer.

[EBADF] The specified KFILE k was not open.

[EIO] The internal VSAM error information could not be located.

972 Systems/C C Library

Page 991: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

KGETPOS(3)

NAME

kgetpos - return the position of the current record

SYNOPSIS

#include <fcntl.h>#include <machine/vsamio.h>

int kgetpos (KFILE *k, kpos_t *pos);

DESCRIPTION

The kgetpos() function determines the current record location and places that intothe kpos t pointer pos.

The value in pos can subsequently be used by the ksetpos(3) function to “seek” tothis location.

The kpos t is purposefully defined in an opaque manner to allow flexibility forchanges to the positioning mechanisms in the future. There should be no assumptionabout the type or values of kpos t values.

RETURN VALUES

On success, kgetpos() returns 0. If there was an error, kgetpos() returns -1 andsets the errno value.

ERRORS

When a failure is returned, errno is set to one of the following values, as well as thegeneric mapping of VSAM logical errors to errno values.

[EIO] The VSAM SHOWCB macro failed.

[EFAULT] The specified KFILE k or kpos t pos was an invalid pointer.

[EBADF] The specified KFILE k was not open.

[ENOSYS] The RPL for the VSAM file could not be accessed or modified.

Systems/C C Library 973

Page 992: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

SEE ALSO

ksetpos(3)

974 Systems/C C Library

Page 993: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

KINSERT(3)

NAME

kinsert - Insert a record into a key-access file.

SYNOPSIS

#include <fcntl.h>#include <machine/vsamio.h>

int kinsert (void *rec, size_t length, void *key, KFILE *k);

DESCRIPTION

The kinsert() function inserts a record into the keyed-access file k.

The rec parameter is a pointer to the record to insert, of length bytes. Note that ifthe file is an ESDS or RRDS file, then length must include the 4-byte key prefix.

The key parameter is the key to use for insertion. If key is NULL, then the insertionkey is taken from the given record using the values specified when the file waskopen’d. For ESDS files, key points to the area to provide the new VSAM-assignedkey.

RETURN VALUES

On success, kinsert() returns 0. If there was an error, kinsert() returns -1 andsets the errno value.

ERRORS

When a failure is returned, errno is set to one of the following values, as well as thegeneric mapping of VSAM logical errors to errno values.

[EEXIST] The key is a duplicate and duplicate keys are not allowed.

[EIO] The VSAM PUT or SHOWCB macros failed.

[EFAULT] The specified KFILE k was an invalid pointer.

[EBADF] The specified KFILE k was not open.

Systems/C C Library 975

Page 994: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

[EBADF] The given keylen was not zero and the VSAM organization was notKSDS.

[ENOSYS] The RPL for the VSAM file could not be accessed or modified.

976 Systems/C C Library

Page 995: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

KOPEN(3)

NAME

kopen - open a keyed-access or Linear Data Set file.

SYNOPSIS

#include <fcntl.h>#include <machine/vsamio.h>

KFILE * kopen (const char *ddn, const char *parms, int mode);

DESCRIPTION

The kopen() function opens a keyed-access or Linear Data Set file for input, outputor update.

The file to open is specified via the DD name ddn. The name should be a simpleDD name, with no Systems/C prefix. It must be a name which is associated withthe VSAM file. The parms parameter is a pointer to a string that defines the typeof file to open, and several options that may apply. The mode parameter describesthe direction of the operation; either O RDONLY for read access, O WRONLY for writeaccess or O RDWR for update access.

kopen() is roughly analagous to open(2).

The KFILE pointer returned is a handle which can be passed to other keyed-accessI/O functions.

The parms parameter is a pointer to a constant character string that contains acomma separate list of parameters. Each parameter is of the form NAME=VALUEpairs. The following names and values are current supported:

recfm specifies the record format, values are v, f and u. VSAM RRDSand LDS are RECFM=F, all other VSAM files are RECFM=V.

reclen specifies the record format, values are an integer value indicat-ing the record length, or the special symbol x for RECFM=Vfiles. VSAM LDS is always reclen=4096.

blksize specifies the block size, values are an integer value indicatingthe requested size.

Systems/C C Library 977

Page 996: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

bufsize specifies the size, in bytes, of the windows for a Linear DataSet (LDS). The integer value specified will be rounded up to amultiple of 4K. The default value is 262144 (256K).

bufmax specifies the maximum number of DIV windows for a LinearData Set (LDS) - default is 4.

keyoff specifies the offset of the key embedded in the VSAM record.The value can be zero for non-key files. For ESDS and RRDSfiles, the value must be zero. If the value is not specified forKSDS files, the value found in the system catalogue will beused.

keyoff specifies the offset of the key embedded in the VSAM record.The value can be zero for non-key files. For ESDS and RRDSfiles, the value must be zero. If the value is not specified forKSDS files, the value found in the system catalogue will beused.

keylen specifies the length of the key embedded in the VSAM record.If the value is not specified for KSDS files, the value found inthe system catalogue will be used.

org specifies the VSAM organization. The value is a two characterfield, where “ks” indicates KSDS, “es” indicates ESDS, “rr”indicates RRDS and “ls” indicates LDS.

org specifies the VSAM organization. The value is a two characterfield, where “ks” indicates KSDS, “es” indicates ESDS, “rr”indicates RRDS and “ls” indicates LDS.

access specifies the kind of VSAM access is to be used. The value is athree character field, where “seq” indicates sequential access,“skp” indicates skip access, and “dir” indicates direct access.

unsafeshare indicates that the system should allow sharing kopen() of anLDS file without SHAREOPTIONS(1,3) specified in the file allo-cation.

Other values specified in the parms parameter are silently ignored.

RETURN VALUES

If the kopen() was successful, a pointer to the allocated KFILE handle is returned;otherwise the NULL pointer is returned and errno is set.

978 Systems/C C Library

Page 997: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

ERRORS

Access to the file is denied if:

[EACCESS] The DIV ACCESS macro indicated access was denied when openingan LDS file.

[EBUSY] The DIV ACCESS macro indicated the file is being opened by mul-tiple tasks without SHAREOPTIONS(1,3) being specified in the allo-cation. Use ”unsafeshare” to ignore this error.

[ENOMEM] Insufficient memory was available.

[ENOSYS] A DFSMS macro or facility indicated failure.

[EIO] A DFSMS or DIV macro or facility indicated failure after VSAMfile was successfully opened.

[EFAULT] The given ddn or parms value was NULL.

[EFTYPE] A kopen() of an LDS file with the O RDONLY mode was specified, butthe source file is empty. An empty LDS file must be opened withO RDWR or O WRONLY.

[EINVAL] An invalid ddn, parms or mode paramter was passed. Or, the spec-ified "org=", "keylen=" or "keyoff=" value in the parms did notmatch the information returned by the system Catalog Search In-terface. Or, the mode value was invalid for the specified "access="value.

[EFTYPE] An invalid "org=" value was specified in parms.

[ENOENT] The specified ddn isn’t allocated, or the allocation points to an in-correct DSN that was not found in the system catalog. ENOENT canalso be set if the OPEN system service succeeded with a return codeof 4, in which case the file is closed with the CLOSE system serviceand NULL is returned.

[ENOATTR] The Catalog Search Interface could not locate the information forthe file.

SEE ALSO

kopen(3)

Systems/C C Library 979

Page 998: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

KREAD(3)

NAME

kread - read input from a Linear Data Set

SYNOPSIS

size_tkread(KFILE *k, void *buf, size_t nbytes)

DESCRIPTION

kread() attempts to read nbytes of data from the Linear Data Set referenced bythe KFILE pointer k into the buffer pointed to by buf.

The kread() starts at a position given by the pointer associated with k (seekseek(2)). Upon return from kread(), the pointer is incremented by the number ofbytes actually read.

Upon successful completion, kread() returns the number of bytes actually read andplaced in the buffer.

IMPLEMENTATION NOTES

kread() only does ”binary” reading, no attempt is made to restructure the datainto records.

kread() uses the DIV macro to process ”windows” into the Linear Data Set. Thebufsize and bufmax parms on the associated kopen(3) can adjust the size and numberof those windows which can affect performance. When the number of windows isexhausted, the least recently used window will be re-used.

RETURN VALUES

If successful, the number of bytes actually read is returned. Upon exhausing theinput data (end-of-file), zero is returned. Otherwise, a -1 is returned and the globalvariable errno is set to indicate the error.

980 Systems/C C Library

Page 999: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

ERRORS

kread() will succeed unless:

[EBADF] k is not a valid KFILE pointer open for reading.

[EINVAL] The KFILE pointed to by k is not a Linear Data Set.

[EFAULT] buf points outside the allocated address space.

[EIO] An low-level error occurred while processing DIV windows.

[ENOMEM] Inadequate memory was available to set up various internal datastructures.

SEE ALSO

kopen(3), kseek(3)

Systems/C C Library 981

Page 1000: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

KREPLACE(3)

NAME

kreplace - replace the last record retrieved

SYNOPSIS

#include <fcntl.h>#include <machine/vsamio.h>

int kreplace (void *rec, size_t length, KFILE *k);

DESCRIPTION

The kreplace() function replaces, in place, the previous record retrieved viakretrv(3) with the record specified by rec of length bytes.

If the file is ESDS or RSDS then length includes the 4-byte prefix.

RETURN VALUES

On success, kreplace() returns 0. If there was an error, kreplace() returns -1 andsets the errno value.

ERRORS

When a failure is returned, errno is set to one of the following values, as well as thegeneric mapping of VSAM logical errors to errno values.

[EFAULT] The specified KFILE k was an invalid pointer.

[EBADF] The specified KFILE k was not open.

[EIO] There was no previously retrieved record.

[EIO] The return value from the PUT macro was greater than 8.

[ENOSYS] The RPL for the VSAM file could not be accessed or modified.

SEE ALSO

kretrv(3), kdelete(3)

982 Systems/C C Library

Page 1001: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

KRETRV(3)

NAME

kretrv - Retrieve the next record from the keyed-acccess file.

SYNOPSIS

#include <fcntl.h>#include <machine/vsamio.h>

int kretrv (void *rec, void *key, int flags, KFILE *k);

DESCRIPTION

The kretrv() function returns the next record from the specified KFILE k. Therecord is stored in the area addressed by the rec parameter.

If the key pointer is non-NULL, then kretrv() will save the record’s key in thememory addressed by key.

Note that no length parameters are specified, the program must ensure that thememory addressed by rec and key is sufficient to contain the largest record and keyfrom the file.

The flags value can be one of K backwards indicating the previous record in thefile should be returned, or K noupdate indicating that the program does not intendto alter the records in the file. These values can be logically OR’d together. IfK backwards isn’t specified, then the current record is returned and for sequentialaccess, the position advances to the next record.

RETURN VALUES

The kretrv() function returns the length of the retrieved record. This length in-cludes a 4-byte key prefix for ESDS and RRDS files. If the end-of-file (or beginingif K backwards is specified) is reached, kretrv() returns 0. kretrv() returns -1 onerror.

ERRORS

When a failure is returned, errno is set to one of the following values:

Systems/C C Library 983

Page 1002: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

[EIO] The VSAM GET or SHOWCB macros failed.

[EFAULT] The specified KFILE k was an invalid pointer.

[EBADF] The specified KFILE k was not open.

[ENOSYS] The RPL for the VSAM file could not be accessed or modified.

SEE ALSO

kopen(3), ksearch(3), kdelete(3)

984 Systems/C C Library

Page 1003: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

KSEARCH(3)

NAME

ksearch - search a keyed-access file based on key.

SYNOPSIS

#include <fcntl.h>#include <machine/vsamio.h>

int ksearch (const void *key, size_t keylen, int flags, KFILE *k);

DESCRIPTION

The ksearch() function searches for records in the specified KFILE k, returning 1 ifthe record was found, 0 or -1 otherwise. If the record is found, the file position isset to that record, so it can be retrieved with the kretrv function.

The key parameter is a pointer to the bytes to be used for the search key, up tokeylen bytes in length.

The flags value indicates how the search should proceed. The specified value in flagscan be K exact, K backwards, K noupdate and can be logically OR’d together:

K exact Indicates that the given record must match exactly, up to keylenbytes for a generic search. If K exact is not specified, the firstrecord found with a key that is greater than or equal (less thanor equal for a backwards searches). K exact must be specifiedfor ESDS files.

K backwards The search is performed in descending key order.

K noupdate The program does not intend to replace or delete records, thusa subsequent kretr() is needed.

RETURN VALUES

The ksearch() function returns 1 if a matching record is located, 0 if no record islocated, and -1 if there is an error.

Systems/C C Library 985

Page 1004: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

ERRORS

When a failure is returned, errno is set to one of the following values:

[EIO] The VSAM POINT, SHOWCB macros failed, or the returned value fromVSAM could not be interpreted.

[EINVAL] A keylen was specified by the key pointer is NULL.

[EFAULT] The specified KFILE k was an invalid pointer.

[EBADF] The specified KFILE k was not open.

[EBADF] The given keylen was not zero and the VSAM organization was notKSDS.

[ENOSYS] The RPL for the VSAM file could not be accessed or modified.

SEE ALSO

kopen(3), kretrv(3)

986 Systems/C C Library

Page 1005: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

KSEEK(2)

NAME

kseek - reposition read/write file offset of Linear Data Set

SYNOPSIS

#include <unistd.h>#include <machine/vsamio.h>

off_tkseek(KFILE *k, off_t offset, int whence)

DESCRIPTION

The kseek() function repositions the offset of the Linear Data Set specified in theKFILE pointer k to the argument offset according to the directive whence. Theargument k must be an open KFILE. kseek() repositions the file position pointerassociated with the KFILE pointer k as follows:

• If whence is SEEK SET, the offset is set to offset bytes.

• If whence is SEEK CUR, the offset is set to its current location plus offset bytes.

• If whence is SEEK END, the offset is set to the size of the file plus offset bytes.

If the KFILE was opened for output (O WRONLY) then the kseek() function allowsthe file offset to be set beyond the end of the existing end-of-file of the file. If datais later written at this point, subsequent reads of the data in the gap return bytesof zeros (until data is actually written into the gap).

RETURN VALUES

Upon successful completion, kseek() returns the resulting offset location as mea-sured in bytes from the beginning of the file. Otherwise, a value of -1 is returnedand errno is set to indicate the error.

Systems/C C Library 987

Page 1006: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

ERRORS

kseek() will fail and the file position pointer will remain unchanged if:

[EBADF] k is not an open file KFILE pointer, or k does not specify an LDSfile.

[EINVAL] Whence is not a proper value.

SEE ALSO

dup(2), open(2)

ISSUES

This document’s use of whence is incorrect English, but is maintained for historicalreasons.

There are limitations to the Systems/C lseek() support, due to implementing abyte offset file abstraction in the OS/390 environment. lseek(fd, 0, SEEK CUR) issupported for any file. This returns the internal byte count (the number of bytes reador written.) lseek(fd, n, SEEK CUR) is supported if the corresponding SEEK SETlseek operation is supported. That is, the value of n is added to the current positionto determine a new offset. If lseek with the SEEK SET option on the compute offsetsucceeds, this succeeds. lseek(fd, 0, SEEK SET) succeeds on any OS/390 file forwhich the NOTE and POINT service is valid. lseek(fd, n, SEEK SET) succeeds forany file opened with the O RDONLY mode and for which the OS/390 NOTE and POINTservice is valid. Note that this will not extend the file size as the file is openedread-only. Seeking past the end of file on a read-only file will return -1 and seterrno to EINVAL.

lseek(fd, 0, SEEK END) is supported for O RDONLY files. This is can be an ex-pensive operation because the entire file must be read to determine its length inbytes.

These limitations similarly affect the fseek() function, which uses lseek() in itsimplementation.

STANDARDS

The lseek() function call is expected to conform to IEEE Std1003.1-1990(“POSIX”) as closely as the host operating system allows.

988 Systems/C C Library

Page 1007: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

KSETPOS(3)

NAME

ksetpos - set the position of the keyed-access file

SYNOPSIS

#include <fcntl.h>#include <machine/vsamio.h>

int ksetpos (KFILE *k, const kpos_t *pos);

DESCRIPTION

The ksetpos() function repositions the keyed-access file k to the position addressedby the point pos.

The value specified via pos was previously obtained in a kgetpos(3) function call.

The kpos t is purposefully defined in an opaque manner to allow flexibility forchanges to the positioning mechanisms in the future. There should be no assumptionabout the type or values of kpos t values.

RETURN VALUES

On success, ksetpos() returns 0. If there was an error, ksetpos() returns -1 andsets the errno value.

ERRORS

When a failure is returned, errno is set to one of the following values, as well as thegeneric mapping of VSAM logical errors to errno values.

[EIO] The VSAM POINT macro failed.

[EFAULT] The specified KFILE k or kpos t pos was an invalid pointer.

[EBADF] The specified KFILE k was not open.

[ENOSYS] The RPL for the VSAM file could not be accessed or modified.

Systems/C C Library 989

Page 1008: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

SEE ALSO

kgetpos(3)

990 Systems/C C Library

Page 1009: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

KWRITE(3)

NAME

kwrite - write output to a Linear Data Set

SYNOPSIS

#include <sys/types.h>#include <sys/uio.h>#include <unistd.h>#include <machine/vsamio.h>

size_tkwrite(FILE *k, const void *buf, size_t nbytes)

DESCRIPTION

kwrite() attempts to write nbytes of data to the Linear Data Set referenced by theKFILE pointer k from the buffer pointed to by buf.

kwrite() starts at a position given by the pointer associated with k, see kseek(3).Upon return from kwrite(), the pointer is incremented by the number of byteswhich were written. kwrite() writes the data in ”binary” mode, no attempt ismade to place record boundaries onto the data.

kwrite() may write fewer bytes than requested; the return value must be noted,and the remainder of the operation should be retried when possible.

IMPLEMENTATION NOTES

kwrite() is implemented using the DIV (Data In Virtual) macros. Bytes are copiedto the managed DIV windows which map into offsets of the Linear Data Set. Thebytes are not actually written onto the Linear Data Set until the DIV windowis UNMAP’d. A DIV window will be UNMAP’d when the file is closed with thekclose(3) function, or when the number of available DIV windows has been exhaustedand the window needs to be re-used.

A Linear Data Set is processed in terms of 4K data blocks, so a kwrite() the outputfile will have a size that is a multiple of 4K after the file has been closed via kclose(3),even those less than that number of bytes may have been processed via kwrite().

Systems/C C Library 991

Page 1010: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

RETURN VALUES

Upon successful completion the number of bytes which were written is returned.Otherwise a -1 is returned and the global variable errno is set to indicate the error.

ERRORS

kwrite() will fail and the file pointer will remain unchanged if:

[EBADF] The pointer associated with k was not open for OUTPUT or didnot represent a Linear Data Set.

[EINVAL] The pointer associated with k did not represent a Linear Data Set.

[EIO] An error occurred while saving or mapping a DIV window to thefile system.

SEE ALSO

kopen(3), kseek(2)

992 Systems/C C Library

Page 1011: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

ASCII/EBCDIC TranslationTable

The Systems/C compiler and utilities use the following tables to translate charactersbetween ASCII and EBCDIC. These tables represent the mapping of the IBM CodePage 1047 to ISO LATIN-1.

ASCII to EBCDIC

0 1 2 3 4 5 6 7 8 9 A B C D E F

0 00 01 02 03 37 2D 2E 2F 16 05 15 0B 0C 0D 0E 0F

1 10 11 12 13 3C 3D 32 26 18 19 3F 27 1C 1D 1E 1F

2 40 5A 7F 7B 5B 6C 50 7D 4D 5D 5C 4E 6B 60 4B 61

3 F0 F1 F2 F3 F4 F5 F6 F7 F8 F9 7A 5E 4C 7E 6E 6F

4 7C C1 C2 C3 C4 C5 C6 C7 C8 C9 D1 D2 D3 D4 D5 D6

5 D7 D8 D9 E2 E3 E4 E5 E6 E7 E8 E9 AD E0 BD 5F 6D

6 79 81 82 83 84 85 86 87 88 89 91 92 93 94 95 96

7 97 98 99 A2 A3 A4 A5 A6 A7 A8 A9 C0 4F D0 A1 07

8 20 21 22 23 24 25 06 17 28 29 2A 2B 2C 09 0A 1B

9 30 31 1A 33 34 35 36 08 38 39 3A 3B 04 14 3E FF

A 41 AA 4A B1 9F B2 6A B5 BB B4 9A 8A B0 CA AF BC

B 90 8F EA FA BE A0 B6 B3 9D DA 9B 8B B7 B8 B9 AB

C 64 65 62 66 63 67 9E 68 74 71 72 73 78 75 76 77

D AC 69 ED EE EB EF EC BF 80 FD FE FB FC BA AE 59

E 44 45 42 46 43 47 9C 48 54 51 52 53 58 55 56 57

F 8C 49 CD CE CB CF CC E1 70 DD DE DB DC 8D 8E DF

Systems/C C Library 993

Page 1012: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

EBCDIC to ASCII

0 1 2 3 4 5 6 7 8 9 A B C D E F

0 00 01 02 03 9C 09 86 7F 97 8D 8E 0B 0C 0D 0E 0F

1 10 11 12 13 9D 0A 08 87 18 19 92 8F 1C 1D 1E 1F

2 80 81 82 83 84 85 17 1B 88 89 8A 8B 8C 05 06 07

3 90 91 16 93 94 95 96 04 98 99 9A 9B 14 15 9E 1A

4 20 A0 E2 E4 E0 E1 E3 E5 E7 F1 A2 2E 3C 28 2B 7C

5 26 E9 EA EB E8 ED EE EF EC DF 21 24 2A 29 3B 5E

6 2D 2F C2 C4 C0 C1 C3 C5 C7 D1 A6 2C 25 5F 3E 3F

7 F8 C9 CA CB C8 CD CE CF CC 60 3A 23 40 27 3D 22

8 D8 61 62 63 64 65 66 67 68 69 AB BB F0 FD FE B1

9 B0 6A 6B 6C 6D 6E 6F 70 71 72 AA BA E6 B8 C6 A4

A B5 7E 73 74 75 76 77 78 79 7A A1 BF D0 5B DE AE

B AC A3 A5 B7 A9 A7 B6 BC BD BE DD A8 AF 5D B4 D7

C 7B 41 42 43 44 45 46 47 48 49 AD F4 F6 F2 F3 F5

D 7D 4A 4B 4C 4D 4E 4F 50 51 52 B9 FB FC F9 FA FF

E 5C F7 53 54 55 56 57 58 59 5A B2 D4 D6 D2 D3 D5

F 30 31 32 33 34 35 36 37 38 39 B3 DB DC D9 DA 9F

994 Systems/C C Library

Page 1013: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

SIGABND example to catchABEND 978 (out-of-stack)

The following example demonstrates how to set up a signal handler on an alternatestack to catch an ABEND and report the ABEND and REASON codes, then re-issuethe ABEND to have it go thru normal percolation.

In this example, the SIGABND handler is provided an alternate execution stack, sothat ABEND 978 (out-of-stack) can be handled. If an alternate stack is not provided,then an ABEND 978 will automatically be percolated.

Also note that the SA RESETHAND flag is used when establishing the signal handler(via sigaction(2)) in order to avoid looping into the signal handler when the ABENDis re-issued by the return of the signal handler.

/** Demonstrates "catching" an ABEND, displaying* some information about it, then returning to* re-issue the ABEND and have it percolate.***/#include <signal.h>#include <stdlib.h>#include <stdio.h>

int __bpxsig = 1; /* force the use of BPX signals which *//* enables TRAP(ON) */

/** The abend_handler() will be invoked for the SIGABND* signal. Because SA_RESETHAND is set, it will only* be invoked once. On return from the handler, the library* will restore the processor state at the point of the* ABEND, and the ABEND will be re-issued and will percolate* thru normal ABEND processing.** If SA_RESETHAND is not set (or the signal handler does

Systems/C C Library 995

Page 1014: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

* not set the SIGABND handler to SIG_DFL) then a return* from the signal handler will restore the processor state* to the instruction that issued the ABEND and re-issue the* ABEND, causing the signal handler to be re-invoked in a loop.***/voidabend_handler(int signum, siginfo_t *info, void *ctx){int a = __abendcode();int r = __rsncode();

printf("in abend_handler:\n");printf(" __abendcode() is 0x%08x\n", a);

/* user completion is the last 12 bits */printf(" user completion code is %d\n", a & 0xfff);printf(" __rsncode() is %d\n", __rsncode());fflush(stdout);

/* A SIGABEND can’t return to the point of the interrupt *//* (if the signal handler remains installed, then we *//* return to the point of interrupt, which causes the *//* ABEND to be re-issued which brings us right back here.*//* This is handled by the SA_RESETHAND flag on the *//* sigaction setting. If SA_RESETHAND is on, then the *//* signal handler is set back to SIG_DFL before invoking *//* this routine. Thus, if we return, we redo the ABEND *//* but with the signal being SIG_DFL, normal ABEND *//* processing happens. */

/* So - an ABEND catcher can do a few things: *//* Return to loop forever *//* longjump() or setcontext() to a previous *//* program state *//* exit() the program. */

/* In this example, we are returning to allow *//* normal ABEND processing to take over. */return;

}

int counter;

/* Cause an out-of-stack situation by recursively* consuming memory until we run out. When this* occurs, the C library will issue ABEND 978.*/

996 Systems/C C Library

Page 1015: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

int recurse(){int big_array[4096*16];counter++;return big_array[counter] + recurse();

}

main(){

stack_t sigstk;struct sigaction act;

printf("CATCH ABEND 978 (out-of-stack)\n");

/* Allocate memory for the alternate stack and *//* set it up. */if ((sigstk.ss_sp = malloc(SIGSTKSZ+4096)) == NULL) {fprintf(stderr,"No mem");

/* error return */exit(12);

}

/* Define the alternate signal execution stack */sigstk.ss_size = SIGSTKSZ+4096;sigstk.ss_flags = 0;if (sigaltstack(&sigstk,0) < 0) {

perror("sigaltstack");}

/* Define an ABEND signal handler to use the *//* alternate stack, and to reset the handler *//* back to SIG_DFL at the time signal handler*//* function is invoked. */act.sa_sigaction = abend_handler;act.sa_flags = (SA_SIGINFO|SA_ONSTACK|SA_RESETHAND);sigemptyset(&act.sa_mask);sigaction(SIGABND, &act, NULL);

/* Invoke the function to eventually consume *//* all space for the stack and thus cause a *//* user ABEND 978. */return recurse();

}

Systems/C C Library 997

Page 1016: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

998 Systems/C C Library

Page 1017: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

DCALL example

The following example demonstrates how to use the Direct CALL facility to pack-age together a set of functions and make these available to any 31-bit mainframeenvironment.

The functions here define an initialization function, named INIT(), two supportfunctions, SUP1() and SUP2() and a termination function named END(). The userof this package would first call the INIT() function, then could make use of thesupport functions, and terminate everything with the END() function.

Each of these functions accepts as the first parameter the address of a 4-byte area.This area holds the environment “handle” returned by the dcall env() function.It is set by the INIT() function and retrieved by the

@@FNDENV

assembly code as needed by the other functions.

/** Direct CALL packaging example** This example demonstrates how to use Direct CALL* in the situation where you want to package functions* together to be linked (or dynamically loaded) from* any mainframe environment.** The package provides* 1) An initialization function, name "INIT".* This must be the first function invoked* to initialize the package.** 2) Two support functions "SUP1" and "SUP2".* Which re-use the extent environment and* perform any interesting functions.* These also use the FINDENV DCALL facility

Systems/C C Library 999

Page 1018: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

* to locate the extent environment.** 3) A destruction function, named "END", that* ends the environment.*** Each of these is called with a first parameter* that is a by-reference parm which will contain* the DCALL environment handle. When the "INIT"* function is invoked, the Systems/C direct-call* environment pointer is saved in the first parm.* The other functions retrieve the pointer from* there using the direct-call FINDENV facility.** In C, these functions would be prototyped as:* INIT(void **env);* SUP1(void **env, int p1);* SUP2(void **env, int p1);* END(void **env);** Also note that the functions are upper-case, to* make linking in other environments easier.** When calling these in an IBM C/C++ environment, it* is important to declare the functions with #pragma* OS linkage, as in:* #pragma linkage(INIT, OS)* #pragma linkage(SUP1, OS)* #pragma linkage(SUP2, OS)* #pragma linkage(END, OS)** When pre-linking this package, it is a good idea* to use the PLINK features which obscure the C runtime* by renaming everything. We want to rename everything* except the INIT, SUP1, SUP2 and END functions; so* these PLINK options would be appropriate:

* plink -renameall -prefix=@SX -except=INIT,END,SUP1,SUP2 ...

* This obfuscates all of the external names consistently* and avoids potential clashes with other runtime environments.***/

#include <machine/dcall.h>

/*

1000 Systems/C C Library

Page 1019: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

* allocate function** Sets the void * pointer passed as* a parameter to the direct-call environment* handle. Subsequent calls to the functions* below must pass that same pointer as the* first parameter.**/

#pragma prolkey(INIT,"DCALL=ALLOCATE")voidINIT(void **env)

*env = __dcall_env();

/** supplied function* Retrieves the environment pointer from the 1st parm,* and executes the function.*/#pragma prolkey(SUP1, "DCALL=SUPPLIED,FINDENV=@@FNDENV")voidSUP1(void **env, int parm1)

/** supplied function* Retrieves the environment pointer from the 1st parm,* and executes the function.*/#pragma prolkey(SUP2, "DCALL=SUPPLIED,FINDENV=@@FNDENV")voidSUP2(void **env, int parm1)

/*

Systems/C C Library 1001

Page 1020: Systems/C C Library ManualContents How to use this book 1 Using the Systems/C C library 3 Linking with the Systems/C C run-time library on OS/390 and z/OS . . 3 A note on re-entrant

* end function* Retrieves the environment pointer from the 1st parm,* and destroys the environment.*/#pragma prolkey(END, "DCALL=DESTROY,FINDENV=@@FNDENV")voidEND(void **env)

/** @@FNDENV assembly function** Invoked by the DCALL=SUPPLIED,FINDENV=@@FNDENV* functions above. Loads the first parm and* copies that as the environment pointer into R0.** It’s assumed that R1 points to a parm* block of the form:* +--------------+* R1 -> | ptr to env. | --> +-------------+* +--------------+ | env handle |* ... +-------------+* +--------------+** which would be the typical pass-by-refernce* form from a COBOL module, or a #pragma linkage OS* IBM C/C++ function call.** NB: @@FNDENV will be an externally visible CSECT, and thus* should only be defined in one source file.***/__asm@@FNDENV CSECT@@FNDENV AMODE ANY@@FNDENV RMODE ANY

USING @@FNDENV,15L 2,0(0,1)L 0,0(0,2) Get ENV ptr into R0L 15,=V(CRT9A)BR 15LTORG

1002 Systems/C C Library