Open C Documentation

Open C API Reference
Developer Guides
Alphabetical Indexes
Open C Quick Reference
Acknowledgements

© Nokia 2007

Back to top


Open C API Reference

Overview
API Description
Limitations
Standard C Library - libc
Encryption - libcrypt
Math Library - libm
Dynamic Linking - libdl
Compression - libz
General-Purpose Utility Library - GLib
OpenSSL SSL/TLS Library - libssl
OpenSSL Cryptographic Library - libcrypto
Internationalization - libintl
Posix Thread Library - libpthread

© Nokia 2007

Back to top


$title

S60 Open C
Open C API Specification

Open C API Specification

Table of Contents

Overview

Overview

The standard base libraries provide a vendor-neutral (or Linux/Unix-like) C programming interface to the base functionality provided by such commonly used libraries as glib, openssl, and so on. These libraries:
  • enable a faster application development in Symbian OS via familiar standard interfaces and programming model.
  • reduce the porting effort of existing components to Symbian OS mobile phones.
  • reduce the effort to have a common code base for multiple platforms.
  • enable easier porting of open source software (OSS) components on top of Symbian OS mobile phones.

Give feedback of this article

©Nokia 2006

Back to top

This material, including documentation and any related computer programs, is protected by copyright controlled by Nokia. All rights are reserved. Copying, including reproducing, storing, adapting or translating, any or all of this material requires the prior written consent of Nokia. This material also contains confidential information, which may not be disclosed to others without the prior written consent of Nokia.

Nokia is a registered trademark of Nokia Corporation. S60 and logo is a trademark of Nokia Corporation. Java and all Java-based marks are trademarks or registered trademarks of Sun Microsystems, Inc. Other company and product names mentioned herein may be trademarks or tradenames of their respective owners.


$title

S60 Open C
Open C API Specification

Open C API Specification

Table of Contents

API Description

API Description

Open C provides the following libraries:

Standard C libraries

Library | Description
libc Standard C libraries. There are several 'libraries' or groups of functions included inside libc:
  • Character Type Functions
  • IPC Functions
  • Localization Functions
  • Regular Expressions
  • Socket Interface Functions
  • Standard I/O Functions
  • Standard Library Functions
  • String Functions
  • System Call Functions
  • System Database
  • Time Manipulation Functions
  • Wide Character Functions
libm | Arithmetical and mathematical functions operating according to the standard C.
libpthread | The pthreads API provides an IEEE Std1003.1c (POSIX) standard interface implementing multiple threads of execution within a traditional user process. This implementation is currently user-space only. Pthreads provide functions for thread creation and destruction, an interface to the thread scheduler to establish thread scheduling parameters, and mutex and condition variables to provide mechanisms for the programmer to synchronize access to shared process resources.
libcrypt | Cryptography libraries containing functions for crypting/encrypting datablocks and messages and password hashing.
libdl | Provides the user with the functionality to dynamically load the dynamic link libraries (DLLs).

Middleware libraries:

Library | Description
libz | The 'zlib' compression library provides in-memory compression and decompression functions, including integrity checks of the uncompressed data.
libcrypto | The OpenSSL crypto library implements a wide range of cryptographic algorithms used in various Internet standards. The services provided by this library are used by the OpenSSL implementations of SSL, TLS and S/MIME, and they have also been used to implement SSH, OpenPGP, and other cryptographic standards.
libssl | The OpenSSL ssl library implements the Secure Sockets Layer (SSL v2/v3) and Transport Layer Security (TLS v1) protocols.
libglib | A general-purpose utility library, which provides many useful data types, macros, type conversions, string utilities, file utilities, a main loop abstraction, and so on. It works on many UNIX-like platforms, Windows, OS/2 and BeOS.
libintl | The libintl library provides APIs that internationalize messages.

Give feedback of this article

©Nokia 2006

Back to top

This material, including documentation and any related computer programs, is protected by copyright controlled by Nokia. All rights are reserved. Copying, including reproducing, storing, adapting or translating, any or all of this material requires the prior written consent of Nokia. This material also contains confidential information, which may not be disclosed to others without the prior written consent of Nokia.

Nokia is a registered trademark of Nokia Corporation. S60 and logo is a trademark of Nokia Corporation. Java and all Java-based marks are trademarks or registered trademarks of Sun Microsystems, Inc. Other company and product names mentioned herein may be trademarks or tradenames of their respective owners.


$title

S60 Open C
Open C API Specification

Open C API Specification

Table of Contents

Limitations

Limitations

Some APIs of the standard C Library are not implemented because of the constraints or limitations of Symbian OS:

  • Open C does not support signals, because a Symbian thread cannot be made to spontaneously execute a "signal handler".
  • Because of the difference in the Symbian OS model (when compared to UNIX-like OS),fork and exec functions are not supported.
  • Since fork and exec are not supported, popen is not complete. It will just create a child process and open a pipe between a parent and a child process either in read or write mode. It neither copies the address space to a child nor copies all the open descriptors in the parent process to the child.
  • wait and waitpid behave differently from the standard.
  • int dup2(int oldfd, int newfd); The return value of dup2 can be different from the one the user expected it to be (newfd). So, the user of dup2 has to use the return value of dup2 as the new allocated fd rather than the one which is been passed to dup2 (newfd). According to the standard, newfd and return values are the same if dup2 is successful.
  • Since some Open C APIs assume that a cleanup stack is created and there is a top-level TRAP for the current thread, all the threads created using RThread::Create should create them explicitly.
  • In case of Open C, libc will have its own console object maintained and all threads console I/O will be routed to that. In case of a hybrid application, if the application also creates one more console, then switching between these consoles will be a problem. The developer will not be aware of this problem.
  • In case of an emulator, the developer can configure the window size dynamically. But the console maintained by Open C libc will remain the same. So, if the configuration is changed, data displayed on the console may not be aligned properly.
  • Even though some APIs like open, and fcntl take both 2 or 3 arguments, on Open C these APIs may not behave according to the standard when only 2 arguments are passed.
  • Since Symbian C++ does not support long double, math-related APIs that use long double might not have the desired precision.

libc

  • All threads created using RThread::Create should create a cleanup stack before calling MRT.
  • Libc has its own console object and all threads console I/O will be routed to that. In case of a hybrid application, if the application creates one more console, then switching between these consoles will be a problem.
  • Unable to create a file with write only permission (Symbian OS does not support it).
  • Unable to support creation and access time stamps for file entries.
  • Creating/deleting an entry within the file system does not alter the time stamp of the parent directory.
  • wchar works only with UTF8.
  • Character conversion is not affected by the LC_TYPE category of the current locale.

The following APIs (or functionality) are not supported by libc due to platform limitations:

  • signal
  • fork
  • exec
  • popen (partial support)
  • wait() and waitpid() behave differently from the standard.
  • dup2 will return the duped fd as the return value of dup2 so do not use newfd as a valid one. It may not be the valid fd.
int err = dup2(fd, newfd);
if (err < 0)
{
Perror(“dup2 fails.”);
Return;
}
else
    newfd = err;
  • No concept of user/group.

libm

  • Since there is no long double support in Sybian OS, all long double version APIs invoke the double versions of the APIs. Long double APIs behave similarly to double APIs. In Symbian OS, floating-point operations are carried out with the help of a floating-point emulator. It does not support any hardware for floating point operations. Therefore the accuracy of the result varies from that of the accuracy obtained in an OS with a hardware floating-point unit.
  • Floating-point exceptions are not supported, because there is no hardware floating-point coprocessor support in the current phones.
  • Complex number APIs are not supported in this library.
  • Errno is not set in any of the APIs, since the FreeBSD code does not follow it. FreeBSD man pages do not mention the errno at all.
  • The accuracy level of the APIs is too low, since the floating point operations are carried out by software emulation in Symbian OS.

libpthread

  • pthread_attr_setscope supports only PTHREAD_SCOPE_SYSTEM.
  • pthread_attr_setschedpolicy supports only SCHED_RR.
  • pthread_join: Only one thread can join one specific target thread.
  • pthread_setschedparam supports only SCHED_RR policy.
  • sem_init: Semaphore can be used only within the process. Semaphore across the processes is not supported.

libz

  • Requires huge heap memory (> 100kB) to provide compression and decompression

libdl

  • Cannot support address lookup using names.
  • The limitation is due to the current behavior of the RLibrary API within Symbian

libcrypto

  • Unsupported algorithms due to IPR issues such as Rc5, IDEA, Blowfish, cast, ripemd, md4, mdc2, ecc, ecdh, ecdsa.
  • Certificates should be in .der format Usage of Symbian’s certstore to avoid duplication of certificates.

Click here to view the alphabetical index of non-implemented functions.

Give feedback of this article

©Nokia 2006

Back to top

This material, including documentation and any related computer programs, is protected by copyright controlled by Nokia. All rights are reserved. Copying, including reproducing, storing, adapting or translating, any or all of this material requires the prior written consent of Nokia. This material also contains confidential information, which may not be disclosed to others without the prior written consent of Nokia.

Nokia is a registered trademark of Nokia Corporation. S60 and logo is a trademark of Nokia Corporation. Java and all Java-based marks are trademarks or registered trademarks of Sun Microsystems, Inc. Other company and product names mentioned herein may be trademarks or tradenames of their respective owners.


Standard C Library - libc

Character Type Functions
IPC Functions
Localization Functions
Regular Expressions
Socket Interface
Standard I/O
Standard Library
String Functions
System Calls
System Database
Time Manipulation
Wide character

© Nokia 2007

Back to top


Character Type Functions

Overview
Functions
Limitations
Capabilities

© Nokia 2007

Back to top


$title

S60 Open C
Standard C Library/Character Type Functions

Standard C Library/Character Type Functions

Table of Contents

Overview

Overview

This section lists the different APIs that work with character classification and mapping. Character classification deals with categorizing the character as belonging to the class(es) alpha, alnum, digit, or punct (refer to defns.html for definitions of these classes). They classify the character as an alphabet, alphanumeric character, digit, or a punctuation character, and so on. They also perform a case conversion operation on characters (uppercase to lowercase and vice versa). This section explains the character type handling functionalities. Character sets used in the early days of computing had only six, seven, or eight bits for each character. There was never a case where more than eight bits (one byte) were used to represent a single character. The limitations of this approach became apparent as more people grappled with non-Roman character sets, where not all the characters that make up a language's character set can be represented by 2^8 choices. This section shows the functionality that was added to the C library to support multiple character sets so as to support such languages, by incorporation of wide characters and the related classification and mapping functionalities as well.

Give feedback of this article

©Nokia 2006

Back to top

This material, including documentation and any related computer programs, is protected by copyright controlled by Nokia. All rights are reserved. Copying, including reproducing, storing, adapting or translating, any or all of this material requires the prior written consent of Nokia. This material also contains confidential information, which may not be disclosed to others without the prior written consent of Nokia.

Nokia is a registered trademark of Nokia Corporation. S60 and logo is a trademark of Nokia Corporation. Java and all Java-based marks are trademarks or registered trademarks of Sun Microsystems, Inc. Other company and product names mentioned herein may be trademarks or tradenames of their respective owners.


$title

S60 Open C
Standard C Library/Character Type Functions

Standard C Library/Character Type Functions

Table of Contents

Character Type Functions

Character Type Functions

Function | Description
tolower | Converts letter to lower case
toupper | Converts letter to upper case
toascii | Converts character to ASCII
isascii | Tests if the character is ASCII
iscntrl | Tests for control narrow character
isgraph | Tests for graphic narrow character
islower | Tests for lowercase narrow character
ispunct | Tests for punctuation or symbolic narrow character
isupper | Tests for uppercase narrow character
isxdigit | Tests for hexadecimal digit
isalnum | Tests for alphanumeric narrow character
isalpha | Tests for alphabetic narrow character
isdigit | Tests for decimal digit
isprint | Tests for narrow printable character
isspace | Tests for narrow whitespace character
iswcntrl | Tests for control wide character
iswgraph | Tests for graphic wide character
iswlower | Tests for lowercase wide character
iswpunct | Tests for punctuation or symbolic wide character
iswupper | Tests for uppercase wide character
iswxdigit | Tests for hexadecimal digit
iswalnum | Tests for alphanumeric wide character
iswalpha | Tests for alphabetic wide character
iswdigit | Tests for decimal digit
iswprint | Tests for printable wide character
iswspace | Tests for whitespace wide character
iswblank | Tests for whitespace wide character
iswctype | Wide character classification

Give feedback of this article

©Nokia 2006

Back to top

This material, including documentation and any related computer programs, is protected by copyright controlled by Nokia. All rights are reserved. Copying, including reproducing, storing, adapting or translating, any or all of this material requires the prior written consent of Nokia. This material also contains confidential information, which may not be disclosed to others without the prior written consent of Nokia.

Nokia is a registered trademark of Nokia Corporation. S60 and logo is a trademark of Nokia Corporation. Java and all Java-based marks are trademarks or registered trademarks of Sun Microsystems, Inc. Other company and product names mentioned herein may be trademarks or tradenames of their respective owners.


$title

S60 Open C
Standard C Library/Character Type Functions

Standard C Library/Character Type Functions

Table of Contents

Limitations

Limitations

No known limitations.

Give feedback of this article

©Nokia 2006

Back to top

This material, including documentation and any related computer programs, is protected by copyright controlled by Nokia. All rights are reserved. Copying, including reproducing, storing, adapting or translating, any or all of this material requires the prior written consent of Nokia. This material also contains confidential information, which may not be disclosed to others without the prior written consent of Nokia.

Nokia is a registered trademark of Nokia Corporation. S60 and logo is a trademark of Nokia Corporation. Java and all Java-based marks are trademarks or registered trademarks of Sun Microsystems, Inc. Other company and product names mentioned herein may be trademarks or tradenames of their respective owners.


$title

S60 Open C
Standard C Library/Character Type Functions

Standard C Library/Character Type Functions

Table of Contents

Required Capabilities

Required Capabilities

A 3rd-party application does not need any capabilities in order to use character type functions.

Give feedback of this article

©Nokia 2006

Back to top

This material, including documentation and any related computer programs, is protected by copyright controlled by Nokia. All rights are reserved. Copying, including reproducing, storing, adapting or translating, any or all of this material requires the prior written consent of Nokia. This material also contains confidential information, which may not be disclosed to others without the prior written consent of Nokia.

Nokia is a registered trademark of Nokia Corporation. S60 and logo is a trademark of Nokia Corporation. Java and all Java-based marks are trademarks or registered trademarks of Sun Microsystems, Inc. Other company and product names mentioned herein may be trademarks or tradenames of their respective owners.


IPC Functions

Overview
Functions
Limitations
Capabilities

© Nokia 2007

Back to top


$title

S60 Open C
Standard C Library/IPC Functions

Standard C Library/IPC Functions

Table of Contents

Overview

Overview

Generic functions for IPC functions such as shared memory functions.

Give feedback of this article

©Nokia 2006

Back to top

This material, including documentation and any related computer programs, is protected by copyright controlled by Nokia. All rights are reserved. Copying, including reproducing, storing, adapting or translating, any or all of this material requires the prior written consent of Nokia. This material also contains confidential information, which may not be disclosed to others without the prior written consent of Nokia.

Nokia is a registered trademark of Nokia Corporation. S60 and logo is a trademark of Nokia Corporation. Java and all Java-based marks are trademarks or registered trademarks of Sun Microsystems, Inc. Other company and product names mentioned herein may be trademarks or tradenames of their respective owners.


$title

S60 Open C
Standard C Library/IPC Functions

Standard C Library/IPC Functions

Table of Contents

IPC Functions

IPC Functions

Shared Memory Functions

Function | Description
shmat | Shared memory operations
shmctl | Shared memory control
shmdt | Shared memory operations
shmget | Allocates a shared memory segment
ftok | Converts a path name and a project identifier to a System V IPC key

Semaphores

Function | Description
semop | Semaphore operations
semctl | Semaphore control operations
semget | Gets a semaphore set identifier

Message Operations

Function | Description
msgctl | Message control operations
msgget | Gets a message queue identifier
msgrcv | Receives a message from the message queue
msgsnd | Sends a message to the message queue

Give feedback of this article

©Nokia 2006

Back to top

This material, including documentation and any related computer programs, is protected by copyright controlled by Nokia. All rights are reserved. Copying, including reproducing, storing, adapting or translating, any or all of this material requires the prior written consent of Nokia. This material also contains confidential information, which may not be disclosed to others without the prior written consent of Nokia.

Nokia is a registered trademark of Nokia Corporation. S60 and logo is a trademark of Nokia Corporation. Java and all Java-based marks are trademarks or registered trademarks of Sun Microsystems, Inc. Other company and product names mentioned herein may be trademarks or tradenames of their respective owners.


$title

S60 Open C
Standard C Library/IPC Functions

Standard C Library/IPC Functions

Table of Contents

Limitations

Limitations

This section lists the limitations that the user will encounter when working with IPC functions such as shared memory functions, and semaphores.

  • The maximum number of message queues, shared memory and semaphores in the system is 256.
  • The maximum number of messages in a message queue is 128.
  • The maximum size of a message is 16Kb.
  • The maximum size of a shared memory segment is 512kb.
  • The message queue identifiers cannot be shared across threads.

Give feedback of this article

©Nokia 2006

Back to top

This material, including documentation and any related computer programs, is protected by copyright controlled by Nokia. All rights are reserved. Copying, including reproducing, storing, adapting or translating, any or all of this material requires the prior written consent of Nokia. This material also contains confidential information, which may not be disclosed to others without the prior written consent of Nokia.

Nokia is a registered trademark of Nokia Corporation. S60 and logo is a trademark of Nokia Corporation. Java and all Java-based marks are trademarks or registered trademarks of Sun Microsystems, Inc. Other company and product names mentioned herein may be trademarks or tradenames of their respective owners.


$title

S60 Open C
Standard C Library/IPC Functions

Standard C Library/IPC Functions

Table of Contents

Required Capabilities

Required Capabilities

A 3rd-party application does not need any capabilities in order to use IPC functions.

Give feedback of this article

©Nokia 2006

Back to top

This material, including documentation and any related computer programs, is protected by copyright controlled by Nokia. All rights are reserved. Copying, including reproducing, storing, adapting or translating, any or all of this material requires the prior written consent of Nokia. This material also contains confidential information, which may not be disclosed to others without the prior written consent of Nokia.

Nokia is a registered trademark of Nokia Corporation. S60 and logo is a trademark of Nokia Corporation. Java and all Java-based marks are trademarks or registered trademarks of Sun Microsystems, Inc. Other company and product names mentioned herein may be trademarks or tradenames of their respective owners.


Localization Functions

Overview
Functions
Limitations
Capabilities

© Nokia 2007

Back to top


$title

S60 Open C
Standard C Library/Localization Functions

Standard C Library/Localization Functions

Table of Contents

Overview

Overview

Generic functions for localization functions such as querying language and locale information, getting numeric formatting information, and so on.

Give feedback of this article

©Nokia 2006

Back to top

This material, including documentation and any related computer programs, is protected by copyright controlled by Nokia. All rights are reserved. Copying, including reproducing, storing, adapting or translating, any or all of this material requires the prior written consent of Nokia. This material also contains confidential information, which may not be disclosed to others without the prior written consent of Nokia.

Nokia is a registered trademark of Nokia Corporation. S60 and logo is a trademark of Nokia Corporation. Java and all Java-based marks are trademarks or registered trademarks of Sun Microsystems, Inc. Other company and product names mentioned herein may be trademarks or tradenames of their respective owners.


$title

S60 Open C
Standard C Library/Localization Functions

Standard C Library/Localization Functions

Table of Contents

Localization Functions

Localization Functions

Character Set Conversion Functions

Function | Description
iconv | Convert encoding of given files from one encoding to another
iconv_close | Deallocates descriptor for character set conversion
iconv_open | Allocates descriptor for character set conversion

Locale

Function | Description
nl_langinfo | Queries language and locale information
localeconv | Gets numeric formatting information
setlocale | Sets the current locale

Give feedback of this article

©Nokia 2006

Back to top

This material, including documentation and any related computer programs, is protected by copyright controlled by Nokia. All rights are reserved. Copying, including reproducing, storing, adapting or translating, any or all of this material requires the prior written consent of Nokia. This material also contains confidential information, which may not be disclosed to others without the prior written consent of Nokia.

Nokia is a registered trademark of Nokia Corporation. S60 and logo is a trademark of Nokia Corporation. Java and all Java-based marks are trademarks or registered trademarks of Sun Microsystems, Inc. Other company and product names mentioned herein may be trademarks or tradenames of their respective owners.


$title

S60 Open C
Standard C Library/Localization Functions

Standard C Library/Localization Functions

Table of Contents

Limitations

Limitations

No known limitations.

Give feedback of this article

©Nokia 2006

Back to top

This material, including documentation and any related computer programs, is protected by copyright controlled by Nokia. All rights are reserved. Copying, including reproducing, storing, adapting or translating, any or all of this material requires the prior written consent of Nokia. This material also contains confidential information, which may not be disclosed to others without the prior written consent of Nokia.

Nokia is a registered trademark of Nokia Corporation. S60 and logo is a trademark of Nokia Corporation. Java and all Java-based marks are trademarks or registered trademarks of Sun Microsystems, Inc. Other company and product names mentioned herein may be trademarks or tradenames of their respective owners.


$title

S60 Open C
Standard C Library/Localization Functions

Standard C Library/Localization Functions

Table of Contents

Required Capabilities

Required Capabilities

A 3rd-party application does not need any capabilities in order to use localization functions.

Give feedback of this article

©Nokia 2006

Back to top

This material, including documentation and any related computer programs, is protected by copyright controlled by Nokia. All rights are reserved. Copying, including reproducing, storing, adapting or translating, any or all of this material requires the prior written consent of Nokia. This material also contains confidential information, which may not be disclosed to others without the prior written consent of Nokia.

Nokia is a registered trademark of Nokia Corporation. S60 and logo is a trademark of Nokia Corporation. Java and all Java-based marks are trademarks or registered trademarks of Sun Microsystems, Inc. Other company and product names mentioned herein may be trademarks or tradenames of their respective owners.


Regular Expressions

Overview
Functions
Limitations
Capabilities

© Nokia 2007

Back to top


$title

S60 Open C
Standard C Library/Regular Expressions

Standard C Library/Regular Expressions

Table of Contents

Overview

Overview

Generic functions for regular expressions such as pattern matching facilities for two kinds of patterns: regular expressions and file-name wildcards.

Give feedback of this article

©Nokia 2006

Back to top

This material, including documentation and any related computer programs, is protected by copyright controlled by Nokia. All rights are reserved. Copying, including reproducing, storing, adapting or translating, any or all of this material requires the prior written consent of Nokia. This material also contains confidential information, which may not be disclosed to others without the prior written consent of Nokia.

Nokia is a registered trademark of Nokia Corporation. S60 and logo is a trademark of Nokia Corporation. Java and all Java-based marks are trademarks or registered trademarks of Sun Microsystems, Inc. Other company and product names mentioned herein may be trademarks or tradenames of their respective owners.


$title

S60 Open C
Standard C Library/Regular Expressions

Standard C Library/Regular Expressions

Table of Contents

Regular Expressions

Regular Expressions

Regular Expression Matching

Function | Description
regerror | POSIX regex functions
regcomp | POSIX regex functions
regexec | POSIX regex functions
regfree | POSIX regex functions

Give feedback of this article

©Nokia 2006

Back to top

This material, including documentation and any related computer programs, is protected by copyright controlled by Nokia. All rights are reserved. Copying, including reproducing, storing, adapting or translating, any or all of this material requires the prior written consent of Nokia. This material also contains confidential information, which may not be disclosed to others without the prior written consent of Nokia.

Nokia is a registered trademark of Nokia Corporation. S60 and logo is a trademark of Nokia Corporation. Java and all Java-based marks are trademarks or registered trademarks of Sun Microsystems, Inc. Other company and product names mentioned herein may be trademarks or tradenames of their respective owners.


$title

S60 Open C
Standard C Library/Regular Expressions

Standard C Library/Regular Expressions

Table of Contents

Limitations

Limitations

No known limitations.

Give feedback of this article

©Nokia 2006

Back to top

This material, including documentation and any related computer programs, is protected by copyright controlled by Nokia. All rights are reserved. Copying, including reproducing, storing, adapting or translating, any or all of this material requires the prior written consent of Nokia. This material also contains confidential information, which may not be disclosed to others without the prior written consent of Nokia.

Nokia is a registered trademark of Nokia Corporation. S60 and logo is a trademark of Nokia Corporation. Java and all Java-based marks are trademarks or registered trademarks of Sun Microsystems, Inc. Other company and product names mentioned herein may be trademarks or tradenames of their respective owners.


$title

S60 Open C
Standard C Library/Regular Expressions

Standard C Library/Regular Expressions

Table of Contents

Required Capabilities

Required Capabilities

A 3rd-party application does not need any capabilities in order to use regular expressions functions.

Give feedback of this article

©Nokia 2006

Back to top

This material, including documentation and any related computer programs, is protected by copyright controlled by Nokia. All rights are reserved. Copying, including reproducing, storing, adapting or translating, any or all of this material requires the prior written consent of Nokia. This material also contains confidential information, which may not be disclosed to others without the prior written consent of Nokia.

Nokia is a registered trademark of Nokia Corporation. S60 and logo is a trademark of Nokia Corporation. Java and all Java-based marks are trademarks or registered trademarks of Sun Microsystems, Inc. Other company and product names mentioned herein may be trademarks or tradenames of their respective owners.


Socket Interface

Overview
Functions
Limitations
Capabilities

© Nokia 2007

Back to top


$title

S60 Open C
Standard C Library/Socket Interface Functions

Standard C Library/Socket Interface Functions

Table of Contents

Overview

Overview

Generic functions for socket interface functions such as sending and receiving messages from a socket.

Give feedback of this article

©Nokia 2006

Back to top

This material, including documentation and any related computer programs, is protected by copyright controlled by Nokia. All rights are reserved. Copying, including reproducing, storing, adapting or translating, any or all of this material requires the prior written consent of Nokia. This material also contains confidential information, which may not be disclosed to others without the prior written consent of Nokia.

Nokia is a registered trademark of Nokia Corporation. S60 and logo is a trademark of Nokia Corporation. Java and all Java-based marks are trademarks or registered trademarks of Sun Microsystems, Inc. Other company and product names mentioned herein may be trademarks or tradenames of their respective owners.


$title

S60 Open C
Standard C Library/Socket Interface Functions

Standard C Library/Socket Interface Functions

Table of Contents

Socket Interface Functions

Socket Interface Functions

Socket Handling

Function | Description
connect | Initiates a connection on a socket
getpeername | Gets name of connected peer socket
listen | Listens for connections on a socket
recv | Receives a message from a socket
send | Sends a message from a socket
recvfrom | Receives a message from a socket
sendto | Sends a message from a socket
shutdown | Brings the system down
socket | Creates an endpoint for communication
bind | Bash built-in commands
getsockname | Gets socket name
getsockopt | Gets options on sockets
setsockopt | Sets options on sockets

Namespaces

Function | Description
if_freenameindex | Free memory allocated by if_nameindex
if_indextoname | Maps a network interface index to its corresponding name
if_nameindex | Returns all network interface names and indexes
if_nametoindex | Maps a network interface name to its corresponding index

Give feedback of this article

©Nokia 2006

Back to top

This material, including documentation and any related computer programs, is protected by copyright controlled by Nokia. All rights are reserved. Copying, including reproducing, storing, adapting or translating, any or all of this material requires the prior written consent of Nokia. This material also contains confidential information, which may not be disclosed to others without the prior written consent of Nokia.

Nokia is a registered trademark of Nokia Corporation. S60 and logo is a trademark of Nokia Corporation. Java and all Java-based marks are trademarks or registered trademarks of Sun Microsystems, Inc. Other company and product names mentioned herein may be trademarks or tradenames of their respective owners.


$title

S60 Open C
Standard C Library/Socket Interface Functions

Standard C Library/Socket Interface Functions

Table of Contents

Limitations

Limitations

Symbian C++ supports only the following ioctl() commands:
  • SIOCGIFCONF
  • SIOCGIFACTIVECONF
  • SIOCSIFNAME
  • SIOCGIFINDEX
  • SIOCIFACTIVESTART
  • SIOCIFSTOP
  • SIOCATMARK
  • SIOCGIFADDR:Get interface address.
  • SIOCGIFNUM:Get the number of interfaces.

NOTE : Sockios.h lists ioctl() operations for sockets. UNIX domain sockets are not supported. The user has to connect to some server to get the interface address as it is dynamically assigned.

Give feedback of this article

©Nokia 2006

Back to top

This material, including documentation and any related computer programs, is protected by copyright controlled by Nokia. All rights are reserved. Copying, including reproducing, storing, adapting or translating, any or all of this material requires the prior written consent of Nokia. This material also contains confidential information, which may not be disclosed to others without the prior written consent of Nokia.

Nokia is a registered trademark of Nokia Corporation. S60 and logo is a trademark of Nokia Corporation. Java and all Java-based marks are trademarks or registered trademarks of Sun Microsystems, Inc. Other company and product names mentioned herein may be trademarks or tradenames of their respective owners.


$title

S60 Open C
Standard C Library/Socket Interface Functions

Standard C Library/Socket Interface Functions

Table of Contents

Required Capabilities

Required Capabilities

A 3rd-party application needs the following capabilities in order to use socket interface functions:

Capability | Description
NetworkServices | A user capability that grants access to a remote service without any restriction on its physical location. Typically, such a location is unknown to the phone user, and such services may incur cost for the phone user. Voice calls, SMS, and Internet services are good examples of such network services. They are supported by GSM, CDMA, and all IP transport protocols including Bluetooth profiles over IP.

Give feedback of this article

©Nokia 2006

Back to top

This material, including documentation and any related computer programs, is protected by copyright controlled by Nokia. All rights are reserved. Copying, including reproducing, storing, adapting or translating, any or all of this material requires the prior written consent of Nokia. This material also contains confidential information, which may not be disclosed to others without the prior written consent of Nokia.

Nokia is a registered trademark of Nokia Corporation. S60 and logo is a trademark of Nokia Corporation. Java and all Java-based marks are trademarks or registered trademarks of Sun Microsystems, Inc. Other company and product names mentioned herein may be trademarks or tradenames of their respective owners.


Standard I/O

Overview
Functions
Limitations
Capabilities

© Nokia 2007

Back to top


$title

S60 Open C
Standard C Library/Standard I/O Functions

Standard C Library/Standard I/O Functions

Table of Contents

Overview

Overview

Generic functions for standard I/O functions such as creating streams and performing input and output operations on them. A stream is a fairly abstract, high-level concept representing a communication channel to a file, device, or process.

Give feedback of this article

©Nokia 2006

Back to top

This material, including documentation and any related computer programs, is protected by copyright controlled by Nokia. All rights are reserved. Copying, including reproducing, storing, adapting or translating, any or all of this material requires the prior written consent of Nokia. This material also contains confidential information, which may not be disclosed to others without the prior written consent of Nokia.

Nokia is a registered trademark of Nokia Corporation. S60 and logo is a trademark of Nokia Corporation. Java and all Java-based marks are trademarks or registered trademarks of Sun Microsystems, Inc. Other company and product names mentioned herein may be trademarks or tradenames of their respective owners.


$title

S60 Open C
Standard C Library/Standard I/O Functions

Standard C Library/Standard I/O Functions

Table of Contents

Standard I/O Functions

Standard I/O Functions

Directory Handling

Function | Description
remove | Deletes a name and possibly the file it refers to

File/Streams Handling

Function | Description
fread | Binary stream input/output
fwrite | Binary stream input/output
getc | Input of characters and strings
getw | Input and output of words (ints)
fgetc | Input of characters and strings
getchar | Input of characters and strings
fclose | Closes a stream
ferror | Checks and resets stream status
feof | Tests the end-of-file indicator for the stream pointed to by stream, returning non-zero if it is set. The end-of-file indicator can only be cleared by the function clearer.
fseek | Repositions a stream
rewind | Repositions a stream
ftell | Repositions a stream
fopen | Streams open functions
freopen | Streams open functions
fsetpos | Repositions a stream
fgetpos | Repositions a stream
clearerr | Checks and resets stream status
fflush | Flush a stream
setbuf | Streams buffering operations
setvbuf | Streams buffering operations
flockfile | Locks FILE for stdio
funlockfile | Locks FILE for stdio
ftrylockfile | Locks FILE for stdio
vfscanf | Input format conversion
vscanf | Input format conversion
vsscanf | Input format conversion
fwscanf | Converts formatted wide-character input
swscanf | Converts formatted wide-character input
vfwscanf | Wide-character formatted input of a stdarg argument list
vswscanf | Wide-character formatted input of a stdarg argument list
vwscanf | Wide-character formatted input of a stdarg argument list
wscanf | Converts formatted wide-character input
scanf | Input format conversion
vprintf | Formatted output conversion
fscanf | Input format conversion
sscanf | Input format conversion
printf | Formatted output conversion
vfprintf | Formatted output conversion
vsnprintf | Formatted output conversion
vsprintf | Formatted output conversion
snprintf | Formatted output conversion
sprintf | Formatted output conversion
fprintf | Formatted output conversion
asprintf | Print to allocated string
vasprintf | Print to allocated string
fwprintf | Formatted wide character output conversion
swprintf | Formatted wide character output conversion
vfwprintf | Formatted wide character output conversion
vswprintf | Formatted wide character output conversion
vwprintf | Formatted wide character output conversion
wprintf | Formatted wide character output conversion
fgets | Input of characters and strings
fgetws | Reads a wide character string from a FILE stream
putc | Output of characters and strings
fputs | Output of characters and strings
puts | Output of characters and strings
putw | Input and output of words (ints)
putchar | It is identical to putc with an output stream of stdout.
fputc | Output of characters and strings
fputwc | Writes a wide character to a FILE stream
fputws | Writes a wide character string to a FILE stream
putwc | Writes a wide character to a FILE stream
putwchar | Writes a wide character to standard output
ungetc | Input of characters and strings
ungetwc | Pushes back a wide character onto a FILE stream

Operations on File Descriptors

Function | Description
fileno | Checks and resets stream status
fdopen | Stream open functions

Give feedback of this article

©Nokia 2006

Back to top

This material, including documentation and any related computer programs, is protected by copyright controlled by Nokia. All rights are reserved. Copying, including reproducing, storing, adapting or translating, any or all of this material requires the prior written consent of Nokia. This material also contains confidential information, which may not be disclosed to others without the prior written consent of Nokia.

Nokia is a registered trademark of Nokia Corporation. S60 and logo is a trademark of Nokia Corporation. Java and all Java-based marks are trademarks or registered trademarks of Sun Microsystems, Inc. Other company and product names mentioned herein may be trademarks or tradenames of their respective owners.


$title

S60 Open C
Standard C Library/Standard I/O Functions

Standard C Library/Standard I/O Functions

Table of Contents

Limitations

Limitations

No known limitations.

Give feedback of this article

©Nokia 2006

Back to top

This material, including documentation and any related computer programs, is protected by copyright controlled by Nokia. All rights are reserved. Copying, including reproducing, storing, adapting or translating, any or all of this material requires the prior written consent of Nokia. This material also contains confidential information, which may not be disclosed to others without the prior written consent of Nokia.

Nokia is a registered trademark of Nokia Corporation. S60 and logo is a trademark of Nokia Corporation. Java and all Java-based marks are trademarks or registered trademarks of Sun Microsystems, Inc. Other company and product names mentioned herein may be trademarks or tradenames of their respective owners.


$title

S60 Open C
Standard C Library/Standard I/O Functions

Standard C Library/Standard I/O Functions

Table of Contents

Required Capabilities

Required Capabilities

A 3rd-party application does not need any capabilities in order to use standard I/O functions, for the following exception:

AllFiles AllFiles capability is needed if file operations require read-write access to any directory under \private or read-only access to any directory under \sys.

Give feedback of this article

©Nokia 2006

Back to top

This material, including documentation and any related computer programs, is protected by copyright controlled by Nokia. All rights are reserved. Copying, including reproducing, storing, adapting or translating, any or all of this material requires the prior written consent of Nokia. This material also contains confidential information, which may not be disclosed to others without the prior written consent of Nokia.

Nokia is a registered trademark of Nokia Corporation. S60 and logo is a trademark of Nokia Corporation. Java and all Java-based marks are trademarks or registered trademarks of Sun Microsystems, Inc. Other company and product names mentioned herein may be trademarks or tradenames of their respective owners.


Standard Library

Overview
Functions
Limitations
Capabilities

© Nokia 2007

Back to top


$title

S60 Open C
Standard C Library/Standard Library Functions

Standard C Library/Standard Library Functions

Table of Contents

Overview

Overview

Generic functions for standard library functions like performing basic arithmetic operations, such as splitting a float into its integer and fractional parts, or retrieving the imaginary part of a complex value. These functions are declared in the header files math.h and complex.h.

Give feedback of this article

©Nokia 2006

Back to top

This material, including documentation and any related computer programs, is protected by copyright controlled by Nokia. All rights are reserved. Copying, including reproducing, storing, adapting or translating, any or all of this material requires the prior written consent of Nokia. This material also contains confidential information, which may not be disclosed to others without the prior written consent of Nokia.

Nokia is a registered trademark of Nokia Corporation. S60 and logo is a trademark of Nokia Corporation. Java and all Java-based marks are trademarks or registered trademarks of Sun Microsystems, Inc. Other company and product names mentioned herein may be trademarks or tradenames of their respective owners.


$title

S60 Open C
Standard C Library/Standard Library Functions

Standard C Library/Standard Library Functions

Table of Contents

Standard Library Functions

Standard Library Functions

Arithmetic Functions

Function | Description
abs | Computes the absolute value of the integer
labs, llabs | Computes the absolute value of the integer

Integer Division

Functions | Description
div | Computes quotient and remainder of an integer division
ldiv | Computes quotient and remainder of an integer division
lldiv | Computes quotient and remainder of an integer division

Parsing of Numbers

Functions | Description
atof | Converts a string to a double
atol | Converts a string to an integer ASCII string to long or long long integer
atoll | Converts a string to an integer ASCII string to long or long long integer
atoi | Converts a string to an integer

Pseudo-Random Numbers

Functions | Description
rand | Pseudo-random number generator
srand | Pseudo-random number generator

Directory Handling

Functions | Description
getcwd | Gets current working directory

File Attributes

Functions | Description
realpath | Returns the canonicalized absolute pathname

Temporary Files

Functions | Description
tempnam | Creates a name for a temporary file
mkstemp | Creates a unique temporary file
tmpfile | Creates a temporary file
tmpnam | Creates a name for a temporary file

Non - local control flow

Functions | Description
setjmp | Saves stack context for non-local goto
longjmp | Non-local jump to a saved stack context

Searching and Sorting

Functions | Description
bsearch | Binary search of a sorted array
qsort | Sorts an array

Namespaces

Function | Description
inet_pton | Create a network address structure
inet_addr | Internet address manipulation routines
inet_ntoa | Internet address manipulation routines
htonl | Converts values between host and network byte order
htons | Converts values between host and network byte order
ntohl | Converts values between host and network byte order
ntohs | Converts values between host and network byte order

Path Handling

Function | Description
confstr | Gets configuration dependent string variables

Command Line Parsing

Functions | Description
putenv | Changes or adds an environment variable
getenv | Gets an environment variable
setenv, unsetenv | Changes or adds an environment variable
getopt | Parses command options
getopt_long | Parse command line options

Memory Allocation

Functions | Description
calloc | Allocate and free dynamic memory
free | Allocate and free dynamic memory
malloc | Allocate and free dynamic memory
realloc | Allocate and free dynamic memory

Shell Command Execution

Functions | Description
system | Executes a shell command

Give feedback of this article

©Nokia 2006

Back to top

This material, including documentation and any related computer programs, is protected by copyright controlled by Nokia. All rights are reserved. Copying, including reproducing, storing, adapting or translating, any or all of this material requires the prior written consent of Nokia. This material also contains confidential information, which may not be disclosed to others without the prior written consent of Nokia.

Nokia is a registered trademark of Nokia Corporation. S60 and logo is a trademark of Nokia Corporation. Java and all Java-based marks are trademarks or registered trademarks of Sun Microsystems, Inc. Other company and product names mentioned herein may be trademarks or tradenames of their respective owners.


$title

S60 Open C
Standard C Library/Standard Library Functions

Standard C Library/Standard Library Functions

Table of Contents

Limitations

Limitations

The command in the system() API's argument should include the path of the executable to be launched from the system() API. For example: Say we have an executable sample.exe (executables are put in c:\sys\bin on the hardware). So, the system() command should be system("c:\sys\bin\sample.exe") . Normally, the same code is expected to work on the emulator as well, in which case make a folder bin in \epoc32\release\winscw\c\sys and place the executable at that location before execution.

Give feedback of this article

©Nokia 2006

Back to top

This material, including documentation and any related computer programs, is protected by copyright controlled by Nokia. All rights are reserved. Copying, including reproducing, storing, adapting or translating, any or all of this material requires the prior written consent of Nokia. This material also contains confidential information, which may not be disclosed to others without the prior written consent of Nokia.

Nokia is a registered trademark of Nokia Corporation. S60 and logo is a trademark of Nokia Corporation. Java and all Java-based marks are trademarks or registered trademarks of Sun Microsystems, Inc. Other company and product names mentioned herein may be trademarks or tradenames of their respective owners.


$title

S60 Open C
Standard C Library/Standard Library Functions

Standard C Library/Standard Library Functions

Table of Contents

Required Capabilities

Required Capabilities

A 3rd-party application does not need any capabilities in order to use standard library functions, except for the following capability that is required for the exit() API.

Capability

Description
PowerMgmt Grants the right:
  • to kill any process in the system.
  • to power off unused peripherals.
  • to switch the machine into standby state.
  • to wake the machine up.
  • to power the machine down completely.
Note that this does not control access to anything that might drain battery power.

Note: This capability is required for the exit() API.

Give feedback of this article

©Nokia 2006

Back to top

This material, including documentation and any related computer programs, is protected by copyright controlled by Nokia. All rights are reserved. Copying, including reproducing, storing, adapting or translating, any or all of this material requires the prior written consent of Nokia. This material also contains confidential information, which may not be disclosed to others without the prior written consent of Nokia.

Nokia is a registered trademark of Nokia Corporation. S60 and logo is a trademark of Nokia Corporation. Java and all Java-based marks are trademarks or registered trademarks of Sun Microsystems, Inc. Other company and product names mentioned herein may be trademarks or tradenames of their respective owners.


String Functions

Overview
Functions
Limitations
Capabilities

© Nokia 2007

Back to top


$title

S60 Open C
Standard C Library/String Functions

Standard C Library/String Functions

Table of Contents

Overview

Overview

Generic functions for string functions such as converting a string to another format, or copying, concatenating, and duplicating strings.

Give feedback of this article

©Nokia 2006

Back to top

This material, including documentation and any related computer programs, is protected by copyright controlled by Nokia. All rights are reserved. Copying, including reproducing, storing, adapting or translating, any or all of this material requires the prior written consent of Nokia. This material also contains confidential information, which may not be disclosed to others without the prior written consent of Nokia.

Nokia is a registered trademark of Nokia Corporation. S60 and logo is a trademark of Nokia Corporation. Java and all Java-based marks are trademarks or registered trademarks of Sun Microsystems, Inc. Other company and product names mentioned herein may be trademarks or tradenames of their respective owners.


$title

S60 Open C
Standard C Library/String Functions

Standard C Library/String Functions

Table of Contents

String Functions

String Functions

Arithmetic Functions

Function | Description
strtod | Converts ASCII string to floating point number
strtol | Converts a string to a long integer
strtoul | Converts a string to an unsigned long integer
strtoimax, strtoumax | Converts a string to an integer
strtof | Converts an ASCII string to a floating point number
strtol | Converts a string to a long integer
strtoull | Converts a string to an unsigned long integer
strtoq | Converts a string to a long integer
strtouq | Converts a string to an unsigned long integer
strtold | Converts an ASCII string to a floating point number

Time Functionalities

Function | Description
strptime | Converts a string representation of time to a time tm structure
strftime | Format date and time

Collation Functions

Function | Description
strcoll | Compares two strings using the current locale
strxfrm | String transformation

Error Messages

Function | Description
perror | Describes a system or MySQL error code
strerror_r | Returns string describing error code
strerror | Returns string describing error code

Locale

Function | Description
strfmon | Converts monetary value to a string

Compatibility String Search Functions

Function | Description
index | Locates character in string
rindex | Locates character in string

Copying and Concatenation

Function | Description
memccpy | Copies memory area
bcopy | Copies byte sequence
bzero | Writes zero bytes
memcpy | Copies memory area
memmove | Copies memory area
memset | Fills memory with a constant byte
strcat | Concatenates two strings
strcpy | Copies the string src to dst (including the terminating ‘\0’ character).
strdup, strndup | Duplicates a string
strncat | Concatenates two strings
strncpy | Copies a string
stpcpy | Copies a string returning a pointer to its end

Finding Tokens in a String

Function | Description
strtok_r, strtok | Extracts tokens from strings
strsep | Extracts tokens from strings

Search Functions

Function | Description
strpbrk | Searches a string for any of a set of characters
strspn | Searches a string for a set of characters
memchr | Scans memory for a character
strchr, strrchr | Locates the first occurrence of c (converted to a char ) in the string pointed to by s.
strcspn | Searches a string for a set of characters
strcasestr | Locates the first occurrence of the null-terminated string little in the null-terminated string big, but ignores the case of both strings.
strstr | Locates a substring

String Length

Function | Description
strlen | Calculates the length of a string
strnlen | Determines the length of a fixed-size string

String/Array Comparison

Function | Description
memcmp | Compares memory areas
bcmp | Compares byte sequences
strcmp, strncmp | Compares two strings
strcasecmp, strncasecmp | Compares two strings ignoring case

Give feedback of this article

©Nokia 2006

Back to top

This material, including documentation and any related computer programs, is protected by copyright controlled by Nokia. All rights are reserved. Copying, including reproducing, storing, adapting or translating, any or all of this material requires the prior written consent of Nokia. This material also contains confidential information, which may not be disclosed to others without the prior written consent of Nokia.

Nokia is a registered trademark of Nokia Corporation. S60 and logo is a trademark of Nokia Corporation. Java and all Java-based marks are trademarks or registered trademarks of Sun Microsystems, Inc. Other company and product names mentioned herein may be trademarks or tradenames of their respective owners.


$title

S60 Open C
Standard C Library/String Functions

Standard C Library/String Functions

Table of Contents

Limitations

Limitations

No known limitations except that all the functions specified by the LSB have not been implemented.

Give feedback on this article

©Nokia 2006

Back to top

This material, including documentation and any related computer programs, is protected by copyright controlled by Nokia. All rights are reserved. Copying, including reproducing, storing, adapting or translating, any or all of this material requires the prior written consent of Nokia. This material also contains confidential information, which may not be disclosed to others without the prior written consent of Nokia.

Nokia is a registered trademark of Nokia Corporation. S60 and logo is a trademark of Nokia Corporation. Java and all Java-based marks are trademarks or registered trademarks of Sun Microsystems, Inc. Other company and product names mentioned herein may be trademarks or tradenames of their respective owners.


$title

S60 Open C
Standard C Library/String Functions

Standard C Library/String Functions

Table of Contents

Required Capabilities

Required Capabilities

A 3rd-party application does not need any capabilities in order to use string functions.

Give feedback of this article

©Nokia 2006

Back to top

This material, including documentation and any related computer programs, is protected by copyright controlled by Nokia. All rights are reserved. Copying, including reproducing, storing, adapting or translating, any or all of this material requires the prior written consent of Nokia. This material also contains confidential information, which may not be disclosed to others without the prior written consent of Nokia.

Nokia is a registered trademark of Nokia Corporation. S60 and logo is a trademark of Nokia Corporation. Java and all Java-based marks are trademarks or registered trademarks of Sun Microsystems, Inc. Other company and product names mentioned herein may be trademarks or tradenames of their respective owners.


System Calls

Overview
Functions
Limitations
Capabilities

© Nokia 2007

Back to top


$title

S60 Open C
Standard C Library/System Call Functions

Standard C Library/System Call Functions

Table of Contents

Overview

Overview

Generic functions for system call functions for manipulating files. Unlike the input and output functions, these functions are concerned with operating on the files themselves rather than on their contents. This section describes, for example, functions for examining or modifying directories, functions for renaming and deleting files, and functions for examining and setting file attributes such as access permissions and modification times.

Give feedback of this article

©Nokia 2006

Back to top

This material, including documentation and any related computer programs, is protected by copyright controlled by Nokia. All rights are reserved. Copying, including reproducing, storing, adapting or translating, any or all of this material requires the prior written consent of Nokia. This material also contains confidential information, which may not be disclosed to others without the prior written consent of Nokia.

Nokia is a registered trademark of Nokia Corporation. S60 and logo is a trademark of Nokia Corporation. Java and all Java-based marks are trademarks or registered trademarks of Sun Microsystems, Inc. Other company and product names mentioned herein may be trademarks or tradenames of their respective owners.


$title

S60 Open C
Standard C Library/System Call Functions

Standard C Library/System Call Functions

Table of Contents

System Calls

System Calls

Time Functionalities

Function | Description
gettimeofday | Gets time

Timer Functionalities

Function | Description
clock | Determines processor time
nanosleep | Pauses execution for a specified time
sleep | Delays for a specified amount of time

Directory Handling

Function | Description
seekdir | Sets the position of the next readdir call in the directory stream.
rewinddir | Resets directory stream
telldir | Returns the current location in the directory stream
closedir | Closes a directory
opendir | Opens a directory
readdir | Reads directory entry
mkdir | Makes directories
unlink | Calls the unlink function to remove the specified file
rmdir | Remove empty directories
fchdir | Changes working directory
chdir | Changes working directory

File Attributes

Functions | Description
chmod | Changes file access permissions
fchmod | Changes permissions of a file
ftruncate | Truncates a file to a specified length
utimes | Changes access and/or modification times of an inode
fstat | Gets file status
lstat | Gets file status
utime | Changes access and/or modification times of an inode
rename | Rename files
link | Calls the link function to create a link to a file
readlink | Displays value of a symbolic link
symlink | Makes a new name for a file
sysconf | Gets configuration information at runtime

Operations on File Descriptors

Functions | Description
fcntl | Manipulates file descriptor
dup | Duplicates a file descriptor
dup2 | Duplicates a file descriptor
readv | Reads or writes data into multiple buffers
writev | Reads or writes data into multiple buffers
ioctl | Controls device
creat | Opens and possibly creates a file or device
lseek | Repositions a read/write file offset
sync | Flushes filesystem buffers
fsync | Synchronizes a fileâs complete in-core state with that on disk

Memory-mapped I/O

Functions | Description
mmap | Map or unmap files or devices into memory
mprotect | Controls allowable accesses to a region of memory
msync | Synchronizes a file with a memory map
munmap | Map or unmap files or devices into memory

FIFOs

Functions | Description
mkfifo | Make FIFOs (named pipes)

Pipes

Functions | Description
pipe | Creates a pipe
pclose | Processes I/O
popen | Processes I/O

POSIX spawn

Functions | Description
glob | Generates pathnames matching a pattern.
globfree | Generates pathnames matching a pattern.
posix_spawn | Spawns a process.
posix_spawn_file_actions_addclose | Adds a close action to the file actions object.
posix_spawn_file_actions_addopen | Adds a open action to the file action object.
posix_spawn_file_actions_adddup2 | Add a dup2 action to the spawn file actions object.
posix_spawn_file_actions_destroy | Destroys the spawn file actions object.
posix_spawn_file_actions_init | Initialize the spawn file actions object.
posix_spawnattr_destroy | Destroys the spawn attribute object.
posix_spawnattr_init | Initialize the spawn attribute object.
posix_spawnattr_getflags | Get the value of the spawn-flags attribute.
posix_spawnattr_setflags | Set the value of the spawn-flags attribute.
posix_spawnattr_getpgroup | Get the value of the spawn-pgroup attribute from the attributes object.
posix_spawnattr_setpgroup | Set the spawn-pgroup attribute in an initialized attributes object
posix_spawnattr_getschedparam | Get the value of the spawn-schedparam attribute from the attributes object.
posix_spawnattr_setschedparam | Set the spawn-schedparam attribute in an initialized attributes object.
posix_spawnattr_getschedpolicy | Get the value of the spawn-schedpolicy attribute from the attributes object.
posix_spawnattr_setschedpolicy | Set the spawn-schedpolicy attribute in an initialized attributes object.
posix_spawnattr_getsigdefault | Get the value of the spawn-sigdefault attribute from the attributes object.
posix_spawnattr_setsigdefault | Set the spawn-sigdefault attribute in an initialized attributes object.
posix_spawnattr_getsigmask | Get the value of the spawn-sigmask attribute from the attributes object.
posix_spawnattr_setsigmask | Set the spawn-sigmask attribute in an initialized attributes object.

Process Completion

Functions | Description
wait | Wait for process termination
waitpid | Wait for process termination
wait4 | Wait for process termination, BSD style

Process Identification

Functions | Description
getpid | Get process identification

Program Scheduling Priority

Functions | Description
nice | Run a program with modified scheduling priority
getpriority | Gets program scheduling priority
setpriority | Sets program scheduling priority

Path Handling

Functions | Description
pathconf | Gets configuration values for files

System Names Handling

Functions | Description
uname | Prints system information

Querying Memory Resources

Functions | Description
getpagesize | Gets memory page size

Give feedback of this article

©Nokia 2006

Back to top

This material, including documentation and any related computer programs, is protected by copyright controlled by Nokia. All rights are reserved. Copying, including reproducing, storing, adapting or translating, any or all of this material requires the prior written consent of Nokia. This material also contains confidential information, which may not be disclosed to others without the prior written consent of Nokia.

Nokia is a registered trademark of Nokia Corporation. S60 and logo is a trademark of Nokia Corporation. Java and all Java-based marks are trademarks or registered trademarks of Sun Microsystems, Inc. Other company and product names mentioned herein may be trademarks or tradenames of their respective owners.


$title

S60 Open C
Standard C Library/System Call Functions

Standard C Library/System Call Functions

Table of Contents

Limitations

Limitations

No known limitations.

Give feedback of this article

©Nokia 2006

Back to top

This material, including documentation and any related computer programs, is protected by copyright controlled by Nokia. All rights are reserved. Copying, including reproducing, storing, adapting or translating, any or all of this material requires the prior written consent of Nokia. This material also contains confidential information, which may not be disclosed to others without the prior written consent of Nokia.

Nokia is a registered trademark of Nokia Corporation. S60 and logo is a trademark of Nokia Corporation. Java and all Java-based marks are trademarks or registered trademarks of Sun Microsystems, Inc. Other company and product names mentioned herein may be trademarks or tradenames of their respective owners.


$title

S60 Open C
Standard C Library/System Call Functions

Standard C Library/System Call Functions

Table of Contents

Required Capabilities

Required Capabilities

A 3rd-party application needs the following capabilities in order to use system call functions:

Capability | Description
WriteDeviceData | Grants write access to settings that control the behavior of the device. For example, device lock settings, system time, time zone, alarms, etc.
ReadDeviceData | Grants read access to network operator, phone manufacturer and device confidential settings or data. For example, the PIN lock code and the list of applications that are installed.

Give feedback of this article

©Nokia 2006

Back to top

This material, including documentation and any related computer programs, is protected by copyright controlled by Nokia. All rights are reserved. Copying, including reproducing, storing, adapting or translating, any or all of this material requires the prior written consent of Nokia. This material also contains confidential information, which may not be disclosed to others without the prior written consent of Nokia.

Nokia is a registered trademark of Nokia Corporation. S60 and logo is a trademark of Nokia Corporation. Java and all Java-based marks are trademarks or registered trademarks of Sun Microsystems, Inc. Other company and product names mentioned herein may be trademarks or tradenames of their respective owners.


System Database

Overview
Functions
Limitations
Capabilities

© Nokia 2007

Back to top


$title

S60 Open C
Standard C Library/System Database

Standard C Library/System Database

Table of Contents

Overview

Overview

Generic functions for system database functions.

Give feedback of this article

©Nokia 2006

Back to top

This material, including documentation and any related computer programs, is protected by copyright controlled by Nokia. All rights are reserved. Copying, including reproducing, storing, adapting or translating, any or all of this material requires the prior written consent of Nokia. This material also contains confidential information, which may not be disclosed to others without the prior written consent of Nokia.

Nokia is a registered trademark of Nokia Corporation. S60 and logo is a trademark of Nokia Corporation. Java and all Java-based marks are trademarks or registered trademarks of Sun Microsystems, Inc. Other company and product names mentioned herein may be trademarks or tradenames of their respective owners.


$title

S60 Open C
Standard C Library/System Database

Standard C Library/System Database

Table of Contents

System Database

System Database

Namespaces

Function | Description
gethostbyaddr | Gets network host entry
gethostbyname | Gets network host entry
getprotobyname | Gets protocol entry
getprotobynumber | Gets protocol entry
endservent | Closes the file.
getservbyname | Gets service entry
getservbyport | Gets service entry
getservent | Gets service entry
setservent | Gets service entry

Give feedback of this article

©Nokia 2006

Back to top

This material, including documentation and any related computer programs, is protected by copyright controlled by Nokia. All rights are reserved. Copying, including reproducing, storing, adapting or translating, any or all of this material requires the prior written consent of Nokia. This material also contains confidential information, which may not be disclosed to others without the prior written consent of Nokia.

Nokia is a registered trademark of Nokia Corporation. S60 and logo is a trademark of Nokia Corporation. Java and all Java-based marks are trademarks or registered trademarks of Sun Microsystems, Inc. Other company and product names mentioned herein may be trademarks or tradenames of their respective owners.


$title

S60 Open C
Standard C Library/System Database

Standard C Library/System Database

Table of Contents

Limitations

Limitations

No known limitations.

Give feedback of this article

©Nokia 2006

Back to top

This material, including documentation and any related computer programs, is protected by copyright controlled by Nokia. All rights are reserved. Copying, including reproducing, storing, adapting or translating, any or all of this material requires the prior written consent of Nokia. This material also contains confidential information, which may not be disclosed to others without the prior written consent of Nokia.

Nokia is a registered trademark of Nokia Corporation. S60 and logo is a trademark of Nokia Corporation. Java and all Java-based marks are trademarks or registered trademarks of Sun Microsystems, Inc. Other company and product names mentioned herein may be trademarks or tradenames of their respective owners.


$title

S60 Open C
Standard C Library/System Database

Standard C Library/System Database

Table of Contents

Required Capabilities

Required Capabilities

A 3rd-party application does not need any capabilities in order to use system database functions.

Give feedback of this article

©Nokia 2006

Back to top

This material, including documentation and any related computer programs, is protected by copyright controlled by Nokia. All rights are reserved. Copying, including reproducing, storing, adapting or translating, any or all of this material requires the prior written consent of Nokia. This material also contains confidential information, which may not be disclosed to others without the prior written consent of Nokia.

Nokia is a registered trademark of Nokia Corporation. S60 and logo is a trademark of Nokia Corporation. Java and all Java-based marks are trademarks or registered trademarks of Sun Microsystems, Inc. Other company and product names mentioned herein may be trademarks or tradenames of their respective owners.


Time Manipulation

Overview
Functions
Limitations
Capabilities

© Nokia 2007

Back to top


$title

S60 Open C
Standard C Library/Time Manipulation Functions

Standard C Library/Time Manipulation Functions

Table of Contents

Overview

Overview

Generic functions for time manipulation functions for manipulating dates and times, including functions for determining what time it is and conversion between different time representations. This includes APIs for standard C library with time and date-related functions. This library includes the following functionalities:
  • Date/time-format conversion functions
  • Minimal subset of the Posix realtime library (librt). Limited functionality available through Symbian OS
  • Time-locale related functions

Give feedback of this article

©Nokia 2006

Back to top

This material, including documentation and any related computer programs, is protected by copyright controlled by Nokia. All rights are reserved. Copying, including reproducing, storing, adapting or translating, any or all of this material requires the prior written consent of Nokia. This material also contains confidential information, which may not be disclosed to others without the prior written consent of Nokia.

Nokia is a registered trademark of Nokia Corporation. S60 and logo is a trademark of Nokia Corporation. Java and all Java-based marks are trademarks or registered trademarks of Sun Microsystems, Inc. Other company and product names mentioned herein may be trademarks or tradenames of their respective owners.


$title

S60 Open C
Standard C Library/Time Manipulation Functions

Standard C Library/Time Manipulation Functions

Table of Contents

Time Manipulation Functions

Time Manipulation Functions

Time Functionalities

Function | Description
asctime | Transform date and time to broken-down time or ASCII
asctime_r | Transform date and time to broken-down time or ASCII
gmtime_r | Transform date and time to broken-down time or ASCII
ctime | Transform date and time to broken-down time or ASCII
ctime_r | Transform date and time to broken-down time or ASCII
gmtime | Transform date and time to broken-down time or ASCII
localtime | Transform date and time to broken-down time or ASCII
localtime_r | Transform date and time to broken-down time or ASCII
mktime | Transform date and time to broken-down time or ASCII
tzset | Initialize time conversion information
adjtime | Makes small adjustments to the system time, as returned by gettimeofday, advancing or retarding it by the time specified by the timeval delta.
wcsftime | Converts date and time to a wide-character string
difftime | Calculates time difference

Give feedback of this article

©Nokia 2006

Back to top

This material, including documentation and any related computer programs, is protected by copyright controlled by Nokia. All rights are reserved. Copying, including reproducing, storing, adapting or translating, any or all of this material requires the prior written consent of Nokia. This material also contains confidential information, which may not be disclosed to others without the prior written consent of Nokia.

Nokia is a registered trademark of Nokia Corporation. S60 and logo is a trademark of Nokia Corporation. Java and all Java-based marks are trademarks or registered trademarks of Sun Microsystems, Inc. Other company and product names mentioned herein may be trademarks or tradenames of their respective owners.


$title

S60 Open C
Standard C Library/Time Manipulation Functions

Standard C Library/Time Manipulation Functions

Table of Contents

Limitations

Limitations

No known limitations.

Give feedback of this article

©Nokia 2006

Back to top

This material, including documentation and any related computer programs, is protected by copyright controlled by Nokia. All rights are reserved. Copying, including reproducing, storing, adapting or translating, any or all of this material requires the prior written consent of Nokia. This material also contains confidential information, which may not be disclosed to others without the prior written consent of Nokia.

Nokia is a registered trademark of Nokia Corporation. S60 and logo is a trademark of Nokia Corporation. Java and all Java-based marks are trademarks or registered trademarks of Sun Microsystems, Inc. Other company and product names mentioned herein may be trademarks or tradenames of their respective owners.


$title

S60 Open C
Standard C Library/Time Manipulation Functions

Standard C Library/Time Manipulation Functions

Table of Contents

Required Capabilities

Required Capabilities

A 3rd-party application does not need any capabilities in order to use time manipulation functions.

Give feedback of this article

©Nokia 2006

Back to top

This material, including documentation and any related computer programs, is protected by copyright controlled by Nokia. All rights are reserved. Copying, including reproducing, storing, adapting or translating, any or all of this material requires the prior written consent of Nokia. This material also contains confidential information, which may not be disclosed to others without the prior written consent of Nokia.

Nokia is a registered trademark of Nokia Corporation. S60 and logo is a trademark of Nokia Corporation. Java and all Java-based marks are trademarks or registered trademarks of Sun Microsystems, Inc. Other company and product names mentioned herein may be trademarks or tradenames of their respective owners.


Wide character

Overview
Functions
Limitations
Capabilities

© Nokia 2007

Back to top


$title

S60 Open C
Standard C Library/Wide Character Functions

Standard C Library/Wide Character Functions

Table of Contents

Overview

Overview

Generic functions for wide character functions.

Give feedback of this article

©Nokia 2006

Back to top

This material, including documentation and any related computer programs, is protected by copyright controlled by Nokia. All rights are reserved. Copying, including reproducing, storing, adapting or translating, any or all of this material requires the prior written consent of Nokia. This material also contains confidential information, which may not be disclosed to others without the prior written consent of Nokia.

Nokia is a registered trademark of Nokia Corporation. S60 and logo is a trademark of Nokia Corporation. Java and all Java-based marks are trademarks or registered trademarks of Sun Microsystems, Inc. Other company and product names mentioned herein may be trademarks or tradenames of their respective owners.


$title

S60 Open C
Standard C Library/Wide Character Functions

Standard C Library/Wide Character Functions

Table of Contents

Wide Character Functions

Wide Character Functions

Arithmetic Functions

Functions | Description
wcstod | Converts ASCII string to floating point number
wcstol | Converts a string to a long integer
wcstoul | Converts a string to an unsigned long integer

Character Classification

Functions | Description
wctype | Wide character classification
towctrans | Wide-character transliteration
towlower | Converts a wide character to lowercase
towupper | Converts a wide character to uppercase
wctrans | Wide character translation mapping

Character Set Conversion Functions

Functions | Description
mblen, mbrlen | Determines number of bytes in next multibyte character
mbstowcs, mbsrtowcs | Converts a multibyte string to a wide character string
mbtowc, mbrtowc | Converts a multibyte sequence to a wide character
wcstombs, wcsrtombs | Converts a wide character string to a multibyte string
wctomb, wcrtomb | Converts a wide character to a multibyte sequence
btowc | Converts a single byte to wide character
mbsinit | Tests for initial shift state
wctob | Tries to represent a wide character as a single byte
mbsnrtowcs | Converts a multibyte string to a wide character string
wcsnrtombs | Converts a wide character string to a multibyte string

Collation Functions

Functions | Description
wcscoll | Wide-character string comparison using collating information
wcsxfrm | Wide-character string transformation
wcsicoll | Wide-character string comparison using collating information.
wcsncoll | Wide-character string comparison using collating information.
wcsnicoll | Wide-character string comparison using collating information.

Copying and Concatenation

Function | Description
wmemcpy | Copies an array of wide-characters
wmemmove | Copies an array of wide-characters
wmemset | Fills an array of wide-characters with a constant wide character
wcscat, wcsncat | Concatenates two wide-character strings
wcscpy, wcsncpy | Copies a wide character string
wcpcpy | Copies a wide character string, returning a pointer to its end
wcpncpy | Copies a fixed-size string of wide characters, returning a pointer to its end
wcsdup | Duplicates a wide-character string
wcstok | Splits wide-character string into tokens
wcslcat | Appends a copy of the wide-character string .
wcslcpy | Copies the wide-character string

Directory Handling

Functions | Description
wseekdir | Directory operations
wtelldir | Directory operations
scandir | Scans a directory
wopendir | Opens a directory with wide-character name
wclosedir | Closes the directory stream
wreaddir | Reads a directory with wide-character name
wremove | Deletes a wide character name and possibly the file it refers.
wrewinddir | Resets the position of the directory stream

Error Messages

Functions | Description
wperror | System error messages
wcserror | System error messages

File/Streams Handling

Function | Description
fgetwc | Read a wide character from a FILE stream
getwc | Read a wide character from a FILE stream
getwchar | Read a wide character from standard input
fwide | Sets and determines the orientation of a FILE stream
wchdir | Changes working directory
wchmod | Changes permissions of a file
wfopen | Streams open function
wopen | Creates a file or device
wgetcwd | Gets current working directory
wmkdir | Creates a directory
wrealpath | Returns the canonicalized absolute pathname
wrename | Renames a file
wrmdir | Deletes a directory
wstat | Gets wide-character file status
wsystem | Executes a shell command
wunlink | Deletes a name and possibly the file it refers.
wcreat | Creates a file or device
getws | Reads a wide character string from stdin.
wprintf | Writes output to stdout

Operations on File Descriptors

Functions | Desription
wsetlocale | Sets the current locale

Parsing of Numbers

Functions | Description
wcstoimax, wcstoumax | Converts a wide-character string to an integer
wcstof, wcstold | Converts a wide-character string to a double-precision number
wcstoll | Converts a wide-character string to a long integer
wcstoull | Converts a wide-character string to an unsigned long
wcstoq, wcstouq | Convert a wide-character string to a long integer

Pipes

Functions | Description
wpopen | Opens a process by creating a pipe and invoking the shell.

Pseudo Random Numbers

Functions | Description
random | Random number generator
srandom | Random number generator
setstate | Routine for changing generators
initstate | Routine for changing generators

Search Functions

Function | Description
wcschr | Searches a wide character in a wide-character string
wcscspn | Searches a wide-character string for any of a set of wide characters
wcspbrk | Searches a wide-character string for any of a set of wide characters
wcsrchr | Searches a wide character in a wide-character string
wcsspn | Advances in a wide-character string, skipping any of a set of wide characters
wcsstr | Locates a substring in a wide-character string
wcswcs | Finds a wide substring
wcwidth | Determines columns needed for a wide character
wmemchr | Searches a wide character in a wide-character array
wfindfirst | Provides information about the first instance of a file name that matches the file specified in the filespec argument.
wfindnext | Finds the next name that matches the file specified in the filespec argument.
findclose | Closes the specified search handle and releases the associated resources.

Searching and Sorting Functions

Functions | Description
alphasort | Sorts an array alphabetically.

String Functions

Function | Description
wcslen | Determines the length of a wide-character string
wcsnlen | Determines the length of a fixed-size wide-character string
wcslwr | Converts the wide-character string to lowercase wide-character string.
wcsnset | Sets first n characters of the wide-character string to the specified wide-char.
wcsrev | Reverts the wide-character string.
wcsset | Sets all the characters of the wide-character string to the specified wide-char.
wcsupr | Converts the wide-character string to uppercase wide-character string.

String/Array Comparison

Function | Description
wcscmp | Compares two wide-character strings
wcsncmp | Compares two fixed-size wide-character strings
wmemcmp | Compares two arrays of wide-characters
wcscasecmp | Compares two wide-character strings, ignoring case
wcsncasecmp | Compares two fixed-size wide-character strings, ignoring case
wcsicpm | Compares two wide-character strings, by converting them into lowercase.
wcsnicmp | Compares two wide-character strings, by converting them into lowercase.

System Calls

Functions | Description
waccess | Checks user's permissions for a file.

Temporary File Functions

Functions | Description
wtmpnam | Generates temporary file name.

Time Functionalities

Functions | Description
wasctime | Transforms date and time to a wide char string.
wctime | Transforms date and time to a wide char string.
wstrdate | Gets the system date in wide-character format.
wstrtime | Gets the system time in wide-character format.

Give feedback of this article

©Nokia 2006

Back to top

This material, including documentation and any related computer programs, is protected by copyright controlled by Nokia. All rights are reserved. Copying, including reproducing, storing, adapting or translating, any or all of this material requires the prior written consent of Nokia. This material also contains confidential information, which may not be disclosed to others without the prior written consent of Nokia.

Nokia is a registered trademark of Nokia Corporation. S60 and logo is a trademark of Nokia Corporation. Java and all Java-based marks are trademarks or registered trademarks of Sun Microsystems, Inc. Other company and product names mentioned herein may be trademarks or tradenames of their respective owners.


$title

S60 Open C
Standard C Library/Wide Character Functions

Standard C Library/Wide Character Functions

Table of Contents

Limitations

Limitations

  • Works only with UTF8.
  • Character conversion is not affected by the LC_TYPE category of the current locale.

Give feedback of this article

©Nokia 2006

Back to top

This material, including documentation and any related computer programs, is protected by copyright controlled by Nokia. All rights are reserved. Copying, including reproducing, storing, adapting or translating, any or all of this material requires the prior written consent of Nokia. This material also contains confidential information, which may not be disclosed to others without the prior written consent of Nokia.

Nokia is a registered trademark of Nokia Corporation. S60 and logo is a trademark of Nokia Corporation. Java and all Java-based marks are trademarks or registered trademarks of Sun Microsystems, Inc. Other company and product names mentioned herein may be trademarks or tradenames of their respective owners.


$title

S60 Open C
Standard C Library/Wide Character Functions

Standard C Library/Wide Character Functions

Table of Contents

Required Capabilities

Required Capabilities

A 3rd-party application does not need any capabilities in order to use wide character functions.

Give feedback of this article

©Nokia 2006

Back to top

This material, including documentation and any related computer programs, is protected by copyright controlled by Nokia. All rights are reserved. Copying, including reproducing, storing, adapting or translating, any or all of this material requires the prior written consent of Nokia. This material also contains confidential information, which may not be disclosed to others without the prior written consent of Nokia.

Nokia is a registered trademark of Nokia Corporation. S60 and logo is a trademark of Nokia Corporation. Java and all Java-based marks are trademarks or registered trademarks of Sun Microsystems, Inc. Other company and product names mentioned herein may be trademarks or tradenames of their respective owners.


Encryption - libcrypt

Overview
Functions
Limitations
Capabilities

© Nokia 2007

Back to top


$title

S60 Open C
libcrypt API Specification

libcrypt API Specification

Table of Contents

Overview

Overview

The libcrypt library provides APIs that perform functions such as password encryption (hashing) and encryption/decryption of 64-bit message blocks.

Password encryption: Either the Data Encryption Standard (DES) or the MD5 hash algorithm is used. The user can choose the actual algorithm to be used by specifying an appropriate value to one of the arguments of this API. Also, the API for password encryption implements the feature to thwart the "dictionary attack". This is done by perturbing the underlying algorithm based on the user-supplied parameter.

Encryption/decryption of 64-bit message blocks: The API that performs the encryption/decryption of message blocks uses the Data Encryption Standard (DES) algorithm.

Give feedback of this article

©Nokia 2006

Back to top

This material, including documentation and any related computer programs, is protected by copyright controlled by Nokia. All rights are reserved. Copying, including reproducing, storing, adapting or translating, any or all of this material requires the prior written consent of Nokia. This material also contains confidential information, which may not be disclosed to others without the prior written consent of Nokia.

Nokia is a registered trademark of Nokia Corporation. S60 and logo is a trademark of Nokia Corporation. Java and all Java-based marks are trademarks or registered trademarks of Sun Microsystems, Inc. Other company and product names mentioned herein may be trademarks or tradenames of their respective owners.


$title

S60 Open C
libcrypt API Specification

libcrypt API Specification

Table of Contents

Cryptographic Functions

Cryptographic Functions

Cryptographic Functions

Function | Description
setkey | Encrypts or decrypts the data block.
encrypt | Encrypts and decrypts 64-bit messages
crypt | Performs password hashing with additional code added to deter key search attempts.

Give feedback of this article

©Nokia 2006

Back to top

This material, including documentation and any related computer programs, is protected by copyright controlled by Nokia. All rights are reserved. Copying, including reproducing, storing, adapting or translating, any or all of this material requires the prior written consent of Nokia. This material also contains confidential information, which may not be disclosed to others without the prior written consent of Nokia.

Nokia is a registered trademark of Nokia Corporation. S60 and logo is a trademark of Nokia Corporation. Java and all Java-based marks are trademarks or registered trademarks of Sun Microsystems, Inc. Other company and product names mentioned herein may be trademarks or tradenames of their respective owners.


$title

S60 Open C
libcrypt API Specification

libcrypt API Specification

Table of Contents

Limitations

Limitations

No known limitations.

Give feedback of this article

©Nokia 2006

Back to top

This material, including documentation and any related computer programs, is protected by copyright controlled by Nokia. All rights are reserved. Copying, including reproducing, storing, adapting or translating, any or all of this material requires the prior written consent of Nokia. This material also contains confidential information, which may not be disclosed to others without the prior written consent of Nokia.

Nokia is a registered trademark of Nokia Corporation. S60 and logo is a trademark of Nokia Corporation. Java and all Java-based marks are trademarks or registered trademarks of Sun Microsystems, Inc. Other company and product names mentioned herein may be trademarks or tradenames of their respective owners.


$title

S60 Open C
libcrypt API Specification

libcrypt API Specification

Table of Contents

Required Capabilities

Required Capabilities

A 3rd-party application does not need any capabilities in order to use libcrypt functions.

Give feedback of this article

©Nokia 2006

Back to top

This material, including documentation and any related computer programs, is protected by copyright controlled by Nokia. All rights are reserved. Copying, including reproducing, storing, adapting or translating, any or all of this material requires the prior written consent of Nokia. This material also contains confidential information, which may not be disclosed to others without the prior written consent of Nokia.

Nokia is a registered trademark of Nokia Corporation. S60 and logo is a trademark of Nokia Corporation. Java and all Java-based marks are trademarks or registered trademarks of Sun Microsystems, Inc. Other company and product names mentioned herein may be trademarks or tradenames of their respective owners.


Math Library - libm

Overview
Functions
Limitations
Capabilities

© Nokia 2007

Back to top


$title

S60 Open C
libm API Specification

libm API Specification

Table of Contents

Overview

Overview

The math library provides the traditional UNIX “math library” functions. The functionality of the APIs is compliant with FreeBSD math APIs.

Give feedback of this article

©Nokia 2006

Back to top

This material, including documentation and any related computer programs, is protected by copyright controlled by Nokia. All rights are reserved. Copying, including reproducing, storing, adapting or translating, any or all of this material requires the prior written consent of Nokia. This material also contains confidential information, which may not be disclosed to others without the prior written consent of Nokia.

Nokia is a registered trademark of Nokia Corporation. S60 and logo is a trademark of Nokia Corporation. Java and all Java-based marks are trademarks or registered trademarks of Sun Microsystems, Inc. Other company and product names mentioned herein may be trademarks or tradenames of their respective owners.


$title

S60 Open C
libm API Specification

libm API Specification

Table of Contents

API Description
API Categories
Arithmetic Functions
Mathematical Functions

API Description

This chapter describes the basic Arithmetic and Mathematical functions.

API Categories

Arithmetic Functions

This chapter contains information about functions performing basic arithmetic operations, such as splitting a float into its integer and fractional parts or retrieving the imaginary part of a complex value. These functions are declared in the header files math.h and complex.h.

Normalization Functions

Function | Description
frexp, frexpf, frexpl | Converts floating-point number to fractional and integral components
ldexp, ldexpf, ldexpl | Multiplies a floating-point number by an integral power of 2.
scalb, scalbf, scalbl | Loads exponent of a radix-independent floating-point number
scalbln, scalblnf, scalblnl | Computes exponent using FLT_RADIX
scalbn, scalbnf, scalbnl | Computes exponent using FLT_RADIX
significand, significandf, significandl | Allows users to test conformance to -ieee754.

Remainder Functions

Function | Description
drem, dremf, dreml | Floating-point remainder function
fmod, fmodf, fmodl | Floating-point remainder function
remainder, remainderf, remainderl | Floating-point remainder function

Rounding Functions

Function | Description
floor, floorf, floorl | Largest integral value not greater than argument
llrint, llrintf, llrintl | Round to nearest integer
llround, llroundf, llroundl | Round to nearest integer, away from zero
lrint, lrintf, lrintl | Round to nearest integer
lround, lroundf, lroundl | Round to nearest integer, away from zero
modf, modff, modfl | Extracts signed integral and fractional values from floating-point number
nearbyint, nearbyintf, nearbyintl | Round to nearest integer
rint, rintf, rintl | Round to nearest integer
round, roundf, roundl | Round to nearest integer, away from zero
ceil, ceilf, ceill | Smallest integral value not less than argument
trunc, truncf, truncl | Round to integer, towards zero

Setting and modifying single bits of FP values

Function | Description
copysign, copysignf, copysignl | Copy sign of a number
nextafter, nextafterf, nextafterl | Floating point number manipulation
nexttoward, nexttowardf, nexttowardl | Floating point number manipulation

Examining the FPU status word

Function | Description
feclearexcept | C99 floating point rounding and exception handling
fegetexceptflag | C99 floating point rounding and exception handling
feraiseexcept | C99 floating point rounding and exception handling
fesetexceptflag | C99 floating point rounding and exception handling
fetestexcept | C99 floating point rounding and exception handling

Floating-Point Control Functions

Function | Description
fegetenv | C99 floating point rounding and exception handling
feholdexcept | C99 floating point rounding and exception handling
fesetenv | C99 floating point rounding and exception handling
feupdateenv | C99 floating point rounding and exception handling

Floating-Point Number Classification Functions

Function | Description
finite, finitef, finitel | test for infinity or not-a-number (NaN)

Rounding Modes

Function | Description
fegetround | C99 floating point rounding and exception handling
fesetround | C99 floating point rounding and exception handling

Miscellaneous FP arithmetic functions

Function | Description
fdim, fdimf, fdiml | Positive difference
fma, fmaf, fmal | Floating-point multiply and add
fmax, fmaxf, fmaxl | Find maximum value
fmin, fminf, fminl | Find minimum value

Mathematical Functions

Absolute Value

Function | Description
fabs, fabsf, fabsl | Absolute value of a floating-point number

Exponentiation and Logarithms

Function | Description
cbrt, cbrtf, cbrtl | Cube root function
exp, expf, expl | Base-e exponential function
exp2, exp2f | Base-2 exponential function
expm1, expm1f, expm1l | Exponential minus 1
hypot, hypotf, hypotl | Euclidean distance function
ilogb, ilogbf, ilogbl | Returns an unbiased exponent
log, logf, logl | Natural logarithmic function
log10, log10f, log10l | Base-10 logarithmic function
log1p, log1pf, log1pl | Logarithm of 1 plus argument
logb, logbf, logbl | Radix-independent exponent
pow, powf, powl | Power functions
sqrt, sqrtf, sqrtl | Square root function

Hyperbolic Functions

Function | Description
acosh, acoshf, acoshl | Inverse hyperbolic cosine function
asinh, asinhf, asinhl | Inverse hyperbolic sine function
atanh, atanhf, atanhl | Inverse hyperbolic tangent function
cosh, coshf, coshl | Hyperbolic cosine function
sinh, sinhf, sinhl | Hyperbolic sine function
tanh, tanhf, tanhl | Hyperbolic tangent function

Inverse Trigonometric Functions

Function | Description
acos, acosf, acosl | Arc cosine function
asin, asinf, asinl | Arc sine function
atan, atanf, atanl | Arc tangent function
atan2, atan2f, atan2l | Arc tangent function of two variables

Special Functions

Function | Description
erf, erff, erfl | Error function and complementary error function
erfc, erfcf, erfcl | Error function and complementary error function
gamma, gammaf, gammal | logarithm of the gamma function
j0, j0f, j0l | Bessel functions
j1, j1f, j1l | Bessel functions
jn, jnf, jnl | Bessel functions
ldexp, ldexpf, ldexpl | Multiplies floating-point number by integral power of 2
lgamma, lgammaf, lgammal | Log gamma function
lgamma_r, lgammaf_r, lgammal_r | Log gamma function
tgamma | True gamma function
y0, y0f, y0l | Bessel functions
y1, y1f, y1l | Bessel functions
yn, ynf, ynl | Bessel functions

Trigonometric Functions

Function | Description
cos, cosf, cosl | Cosine function
sin, sinf, sinl | Sine function
tan, tanf, tanl | Tangent function

Give feedback of this article

©Nokia 2006

Back to top

This material, including documentation and any related computer programs, is protected by copyright controlled by Nokia. All rights are reserved. Copying, including reproducing, storing, adapting or translating, any or all of this material requires the prior written consent of Nokia. This material also contains confidential information, which may not be disclosed to others without the prior written consent of Nokia.

Nokia is a registered trademark of Nokia Corporation. S60 and logo is a trademark of Nokia Corporation. Java and all Java-based marks are trademarks or registered trademarks of Sun Microsystems, Inc. Other company and product names mentioned herein may be trademarks or tradenames of their respective owners.


$title

S60 Open C
libm API Specification

libm API Specification

Table of Contents

Limitations

Limitations

  • Since there is no long double support in Symbian OS, all long double version APIs invoke the double versions of the APIs. Long double APIs behave similarly to double APIs. In Symbian OS, the floating-point operations are carried out with the help of a floating-point emulator. It does not support any hardware for floating-point operations. Therefore the accuracy of the result varies from that of the accuracy obtained in an OS with a hardware floating-point unit.
  • Floating-point exceptions are not supported, because there is no hardware floating-point coprocessor support in the current phones.
  • Complex number APIs are not supported in this library.
  • Errno is not set in any of the APIs, since the FreeBSD code does not follow it. FreeBSD man pages do not mention the errno at all.
  • The accuracy level of the APIs is too low, as the floating point operations are carried out by software emulation in Symbian OS.

Give feedback on this article

©Nokia 2006

Back to top

This material, including documentation and any related computer programs, is protected by copyright controlled by Nokia. All rights are reserved. Copying, including reproducing, storing, adapting or translating, any or all of this material requires the prior written consent of Nokia. This material also contains confidential information, which may not be disclosed to others without the prior written consent of Nokia.

Nokia is a registered trademark of Nokia Corporation. S60 and logo is a trademark of Nokia Corporation. Java and all Java-based marks are trademarks or registered trademarks of Sun Microsystems, Inc. Other company and product names mentioned herein may be trademarks or tradenames of their respective owners.


$title

S60 Open C
libm API Specification

libm API Specification

Table of Contents

Required Capabilities

Required Capabilities

A 3rd-party application does not need any capabilities in order to use libm functions.

Give feedback of this article

©Nokia 2006

Back to top

This material, including documentation and any related computer programs, is protected by copyright controlled by Nokia. All rights are reserved. Copying, including reproducing, storing, adapting or translating, any or all of this material requires the prior written consent of Nokia. This material also contains confidential information, which may not be disclosed to others without the prior written consent of Nokia.

Nokia is a registered trademark of Nokia Corporation. S60 and logo is a trademark of Nokia Corporation. Java and all Java-based marks are trademarks or registered trademarks of Sun Microsystems, Inc. Other company and product names mentioned herein may be trademarks or tradenames of their respective owners.


Dynamic Linking - libdl

Overview
Functions
Limitations
Capabilities

© Nokia 2007

Back to top


$title

S60 Open C
libdl API Specification

libdl API Specification

Table of Contents

Overview

Overview

The libdl library comprises the APIs that provide the user with the functionality to dynamically load the dynamic link libraries (DLLs) into the address space of the current process , access the addresses of the symbols defined within the loaded DLLs, unload the DLLs (currently loaded) from the address space, and to retrieve the information about the errors that occurred during any of the previous libdl operations. The library thus allows the users to access the services of the loader through a well-defined interface.

Give feedback of this article

©Nokia 2006

Back to top

This material, including documentation and any related computer programs, is protected by copyright controlled by Nokia. All rights are reserved. Copying, including reproducing, storing, adapting or translating, any or all of this material requires the prior written consent of Nokia. This material also contains confidential information, which may not be disclosed to others without the prior written consent of Nokia.

Nokia is a registered trademark of Nokia Corporation. S60 and logo is a trademark of Nokia Corporation. Java and all Java-based marks are trademarks or registered trademarks of Sun Microsystems, Inc. Other company and product names mentioned herein may be trademarks or tradenames of their respective owners.


$title

S60 Open C
libdl API Specification

libdl API Specification

Table of Contents

Dynamic Link functions

Dynamic Link functions

Functions | Description
dlclose | Deletes a reference to the DLL referenced by handle. If the reference count drops to 0, the DLL is removed from the address space, and handle is rendered invalid.
dlerror | Returns a null-terminated character string describing the last error that occurred during a call to dlopen, dlsym, or dlclose.
dlopen | Returns the handle for the dynamic library loaded into the address space of the current process.
dlsym | Returns the address binding of the symbol associated with the ordinal number.

Give feedback of this article

©Nokia 2006

Back to top

This material, including documentation and any related computer programs, is protected by copyright controlled by Nokia. All rights are reserved. Copying, including reproducing, storing, adapting or translating, any or all of this material requires the prior written consent of Nokia. This material also contains confidential information, which may not be disclosed to others without the prior written consent of Nokia.

Nokia is a registered trademark of Nokia Corporation. S60 and logo is a trademark of Nokia Corporation. Java and all Java-based marks are trademarks or registered trademarks of Sun Microsystems, Inc. Other company and product names mentioned herein may be trademarks or tradenames of their respective owners.


$title

S60 Open C
libdl API Specification

libdl API Specification

Table of Contents

Limitations

Limitations

The limitations are as following:

  • dlopen() limitations: The flags within the mode argument of dlopen() will have the same impact irrespective of their values. This is because the implementation relies on the current behavior of the Symbian OS loader server, which does not support the usage of these flags. POSIX suggests returning a handle to the global symbol object if the first argument to dlopen() is NULL. However, the implementation does not return a handle to the global symbol object: instead, it returns NULL in this scenario. This is due to the non-availability of the global symbol object within the libdl library. Support for the export of routines that use __attribute((constructor)) and __attribute((destructor)) function attributes is not provided. However, invocation of the constructors of the global (static) objects, if any, will be performed prior to returning from dlopen().
  • dlsym limitations: POSIX suggests address lookup through symbol names. However, the implementation uses ordinal numbers instead of symbol names. Ordinal numbers of the exported functions could be obtained from the DEF file of the associated DLL. Special handles to dlsym() are ignored, and the users receive NULL as the return value of dlsym() in this scenario.
  • Cannot support address lookup using names due to the current behavior of the RLibrary API within Symbian OS.

Give feedback of this article

©Nokia 2006

Back to top

This material, including documentation and any related computer programs, is protected by copyright controlled by Nokia. All rights are reserved. Copying, including reproducing, storing, adapting or translating, any or all of this material requires the prior written consent of Nokia. This material also contains confidential information, which may not be disclosed to others without the prior written consent of Nokia.

Nokia is a registered trademark of Nokia Corporation. S60 and logo is a trademark of Nokia Corporation. Java and all Java-based marks are trademarks or registered trademarks of Sun Microsystems, Inc. Other company and product names mentioned herein may be trademarks or tradenames of their respective owners.


$title

S60 Open C
libdl API Specification

libdl API Specification

Table of Contents

Required Capabilities

Required Capabilities

A 3rd-party application does not need any capabilities in order to use libdl functions.

Give feedback of this article

©Nokia 2006

Back to top

This material, including documentation and any related computer programs, is protected by copyright controlled by Nokia. All rights are reserved. Copying, including reproducing, storing, adapting or translating, any or all of this material requires the prior written consent of Nokia. This material also contains confidential information, which may not be disclosed to others without the prior written consent of Nokia.

Nokia is a registered trademark of Nokia Corporation. S60 and logo is a trademark of Nokia Corporation. Java and all Java-based marks are trademarks or registered trademarks of Sun Microsystems, Inc. Other company and product names mentioned herein may be trademarks or tradenames of their respective owners.


Compression - libz

Overview
Functions
Limitations
Capabilities

© Nokia 2007

Back to top


$title

S60 Open C
libz API Specification

libz API Specification

Table of Contents

Overview

Overview

The 'zlib' compression library provides in-memory compression and decompression functions, including integrity checks of the uncompressed data. This version of the library supports only one compression method (deflation) but other algorithms will be added later and will have the same stream interface.

Compression can be done in a single step if the buffers are large enough (for example if an input file is mmap'ed), or can be done by repeated calls of the compression function. In the latter case, the application must provide more input and/or consume the output (providing more output space) before each call.

The library also supports reading and writing files in gzip (.gz) format with an interface similar to that of stdio. The library does not install any signal handler. The decoder checks the consistency of the compressed data, so the library should never crash even in case of corrupted input.

The source reference for original glib pages was taken from www.zlib.net.

Give feedback of this article

©Nokia 2006

Back to top

This material, including documentation and any related computer programs, is protected by copyright controlled by Nokia. All rights are reserved. Copying, including reproducing, storing, adapting or translating, any or all of this material requires the prior written consent of Nokia. This material also contains confidential information, which may not be disclosed to others without the prior written consent of Nokia.

Nokia is a registered trademark of Nokia Corporation. S60 and logo is a trademark of Nokia Corporation. Java and all Java-based marks are trademarks or registered trademarks of Sun Microsystems, Inc. Other company and product names mentioned herein may be trademarks or tradenames of their respective owners.


$title

S60 Open C
libz API Specification

libz API Specification

Table of Contents

API Description
Compression Functions

API Description

This chapter lists information about functions which act as interface functions to Compression Library.

Compression Functions

This section lists functions of compression category.

Interface functions

Function | Description
adler32 | Computes a running Adler-32 checksum.
compress2 | Compresses data at a specified level.
compress | Attempts to compress source Len bytes of data in the buffer source, placing the result in the buffer dest.
compressbound | Estimates the size of buffer required to compress sourceLen bytes of data using the compress() or compress2() functions.
crc32 | Computes a running Cyclic Redundancy Check checksum.
deflate | Attempts to compress data until either the input buffer is empty or the output buffer is full.
deflatebound | Estimates the size of buffer required to compress sourceLen bytes of data.
deflatecopy | Copies the compression state information in source to the uninitialized z_stream structure referenced by dest.
deflateend | Frees all allocated state information referenced by stream.
deflateinit2 | Initializes the compression system.
deflateinit | Initializes the compression system.
deflateparams | Alters the compression parameters for the compression stream object stream.
deflatereset | Resets all state associated with stream.
deflatesetdictionary | Initializes the compression dictionary associated with stream using the dictlen bytes referenced by dictionary.
get-crc-table | Generates tables for a byte-wise 32-bit CRC calculation based on the polynomial.
gzclose | Closes the compressed file stream file.
gzdopen | Attempts to associate the open file referenced by fd with a gzFile object.
gzeof | Tests the compressed file stream file for end of file.
gzerror | Returns a string describing the last error occurred, associated with the open compressed file stream referred to by file.
gzflush | The gzflush() function shall flush pending output to the compressed file stream identified by file, which must be open for writing.
gzgetc | Reads the next single character from the compressed file stream referenced by file.
gzgets | Reads a string from a compressed file.
gzopen | Opens the compressed file named by path.
gzprintf | Formats and compresses the data.
gzputc | Writes character to a compressed file.
gzputs | Writes to a compressed file.
gzread | Reads from a compressed file.
gzrewind | Resets the file-position on a compressed file stream.
gzseek | Sets the file-position indicator for the compressed file stream file.
gzsetparams | Sets the compression level and compression strategy on the compressed file stream referenced by file.
gztell | Returns the starting position for the next read or write operation on compressed file stream file.
gzwrite | Writes data to the compressed file referenced by file, opened in a write mode.
inflate | Attempts to decompress data until either the input buffer is empty or the output buffer is full.
inflateend | Frees all allocated state information referenced by stream.
inflateinit2 | Initializes the decompression system.
inflateinit | Initializes the decompression system.
inflatereset | Resets all state associated with stream.
inflatesetdictionary | Initializes the decompression dictionary.
inflatesync | Advances compression stream to next sync point.
inflatesyncpoint | Tests for synchronization point.
uncompress | Uncompresses the data.
zerror | Translates error number to string.
zlibversion | Locates library version at run time.

Give feedback of this article

©Nokia 2006

Back to top

This material, including documentation and any related computer programs, is protected by copyright controlled by Nokia. All rights are reserved. Copying, including reproducing, storing, adapting or translating, any or all of this material requires the prior written consent of Nokia. This material also contains confidential information, which may not be disclosed to others without the prior written consent of Nokia.

Nokia is a registered trademark of Nokia Corporation. S60 and logo is a trademark of Nokia Corporation. Java and all Java-based marks are trademarks or registered trademarks of Sun Microsystems, Inc. Other company and product names mentioned herein may be trademarks or tradenames of their respective owners.


$title

S60 Open C
libz API Specification

libz API Specification

Table of Contents

Limitations

Limitations

Requires huge heap memory (> 100 kB) to provide compression and decompression.

Give feedback of this article

©Nokia 2006

Back to top

This material, including documentation and any related computer programs, is protected by copyright controlled by Nokia. All rights are reserved. Copying, including reproducing, storing, adapting or translating, any or all of this material requires the prior written consent of Nokia. This material also contains confidential information, which may not be disclosed to others without the prior written consent of Nokia.

Nokia is a registered trademark of Nokia Corporation. S60 and logo is a trademark of Nokia Corporation. Java and all Java-based marks are trademarks or registered trademarks of Sun Microsystems, Inc. Other company and product names mentioned herein may be trademarks or tradenames of their respective owners.


$title

S60 Open C
libz API Specification

libz API Specification

Table of Contents

Required Capabilities

Required Capabilities

A 3rd-party application does not need any capabilities in order to use libz APIs.

Give feedback of this article

©Nokia 2006

Back to top

This material, including documentation and any related computer programs, is protected by copyright controlled by Nokia. All rights are reserved. Copying, including reproducing, storing, adapting or translating, any or all of this material requires the prior written consent of Nokia. This material also contains confidential information, which may not be disclosed to others without the prior written consent of Nokia.

Nokia is a registered trademark of Nokia Corporation. S60 and logo is a trademark of Nokia Corporation. Java and all Java-based marks are trademarks or registered trademarks of Sun Microsystems, Inc. Other company and product names mentioned herein may be trademarks or tradenames of their respective owners.


General-Purpose Utility Library - GLib

Overview
Functions
Limitations
Capabilities
GLib Object System - GObject

© Nokia 2007

Back to top


$title

S60 Open C
glib API Specification

glib API Specification

Table of Contents

Overview

Overview

Glib is a general-purpose utility library, which provides many useful data types, macros, type conversions, string utilities, file utilities, a main loop abstraction, and so on. It works on many UNIX-like platforms, Windows, OS/2, and BeOS. Glib is released under the GNU Library General Public License (GNU LGPL).

The general policy of Glib is that all functions are invisibly thread-safe with the exception of data structure manipulation functions, where, two threads manipulating the same data structure, must use a lock to synchronize their operation.

The source reference for original glib pages was taken from www.gtk.org.

Give feedback of this article

©Nokia 2006

Back to top

This material, including documentation and any related computer programs, is protected by copyright controlled by Nokia. All rights are reserved. Copying, including reproducing, storing, adapting or translating, any or all of this material requires the prior written consent of Nokia. This material also contains confidential information, which may not be disclosed to others without the prior written consent of Nokia.

Nokia is a registered trademark of Nokia Corporation. S60 and logo is a trademark of Nokia Corporation. Java and all Java-based marks are trademarks or registered trademarks of Sun Microsystems, Inc. Other company and product names mentioned herein may be trademarks or tradenames of their respective owners.


$title

S60 Open C
glib API Specification

glib API Specification

Table of Contents

API Description
API Categories
Arrays
Asynchronous Queues
Atomic Operations
Automatic String Completion
Balanced Binary Trees
Basic Types
Byte Arrays
Byte Order Macros
Caches
Character Set Conversion
Commandline option parser
Datasets
Date and Time Functions
Double-ended Queues
Doubly Linked lists
Dynamic Loading of Modules
Error Reporting
File Utilities
Glob-style pattern matching
Hash Tables
Hook Functions
Internationalization
IO Channels
Keyed Data Lists
Key-value file parser
Lexical Scanner
Limits of Basic Type
Memory Allocation
Memory Allocators
Memory Chunks
Memory Slices
Message Logging
Message Output and Debugging
Miscellaneous Macros
Miscellaneous Utility Functions
N-ary Trees
Numerical Definitions
Pointer Arrays
Quarks
Random Numbers
Relations and Tuples
Shell-related Utilities
Simple XML Subset Parser
Singly Linked Lists
Spawning Processes
Standard Macros
Strings
String Chunks
String Utility Functions
The Main Event Loop
Threads
Thread Pools
Timers
Trash Stacks
Type Conversion Macros
Unicode Manipulation
Version Information

API Description

The glib library is arranged into following categories:

  • Arrays
  • Asynchronous Queues
  • Atomic Operations
  • Automatic String Completion
  • Balanced Binary Trees
  • Basic Types
  • Byte Arrays
  • Byte Order Macros
  • Caches
  • Character Set Conversion
  • Commandline option parser
  • Datasets
  • Date and Time Functions
  • Double-ended Queues
  • Doubly Linked lists
  • Dynamic Loading of Modules
  • Error Reporting
  • File Utilities
  • Glob-style pattern matching
  • Hash Tables
  • Hook Functions
  • Internationalization
  • IO Channels
  • Keyed Data Lists
  • Key-value file parser
  • Lexical Scanner
  • Limits of Basic Type
  • Memory Allocation
  • Memory Allocators
  • Memory Chunks
  • Memory Slices
  • Message Logging
  • Message Output and Debugging
  • Miscellaneous Macros
  • Miscellaneous Utility Functions
  • N-ary Trees
  • Numerical Definitions
  • Pointer Arrays
  • Quarks
  • Random Numbers
  • Relations and Tuples
  • Shell-related Utilities
  • Simple XML Subset Parser
  • Singly Linked Lists
  • Spawning Processes
  • Standard Macros
  • Strings
  • String Chunks
  • String Utility Functions
  • The Main Event Loop
  • Threads
  • Thread Pools
  • Timers
  • Trash Stacks
  • Type Conversion Macros
  • Unicode Manipulation
  • Version Information

API Categories

Following is the classification of the functions.

Arrays

This chapter lists arrays of arbitrary elements which grow automatically as elements are added.

Function | Description
GArray | Contains the public fields of an Array.
g_array_new | Creates a new GArray.
g_array_sized_new | Creates a new GArray with reserved_size elements preallocated.
g_array_append_val | Adds the value on to the end of the array.
g_array_append_vals | Adds len elements onto the end of the array.
g_array_prepend_val | Adds the value on to the start of the array.
g_array_prepend_vals | Adds len elements onto the start of the array.
g_array_insert_val | Inserts an element into an array at the given index.
g_array_insert_vals | Inserts len elements into a GArray at the given index.
g_array_remove_index | Removes the element at the given index from a GArray.
g_array_remove_index_fast | Removes the element at the given index from a GArray.
g_array_remove_range | Removes the given number of elements starting at the given index from a GArray.
g_array_sort | Sorts a GArray using compare_func .
g_array_sort_with_data | Sorts a GArray but the comparison function receives a user data argument.
g_array_index | Returns the element of a GArray at the given index.
g_array_set_size | Sets the size of the array.
g_array_free | Frees the memory allocated for the GArray.

Give feedback of this article

Asynchronous Queues

Function | Description
GAsyncQueue | The GAsyncQueue struct is an opaque data structure, which represents an asynchronous queue.
g_async_queue_new | Creates a new asynchronous queue with the initial reference count of 1.
g_async_queue_ref | Increases the reference count of the asynchronous queue by 1.
g_async_queue_unref | Decreases the reference count of the asynchronous queue by 1.
g_async_queue_push | Pushes the data into the queue. data must not be NULL.
g_async_queue_push_sorted | Inserts data into queue using func to determine the new position.
g_async_queue_pop | Pops data from the queue. This function blocks until data become available.
g_async_queue_try_pop | Tries to pop data from the queue. If no data is available, NULL is returned.
g_async_queue_timed_pop | Pops data from the queue. If no data is received before end_time, NULL is returned.
g_async_queue_length | Returns the length of the queue.
g_async_queue_sort | This function will lock queue before it sorts the queue and unlock it when it is finished.
g_async_queue_lock | Acquires the queue's lock.
g_async_queue_unlock | Releases the queue's lock.
g_async_queue_ref_unlocked | Increases the reference count of the asynchronous queue by 1.
g_async_queue_unref_and_unlock | Decreases the reference count of the asynchronous queue by 1 and releases the lock.
g_async_queue_push_unlocked | Pushes the data into the queue. data must not be NULL.
g_async_queue_push_sorted_unlocked | Inserts data into queue using func to determine the new position.
g_async_queue_pop_unlocked | Pops data from the queue. This function blocks until data become available.
g_async_queue_try_pop_unlocked | Tries to pop data from the queue. If no data is available, NULL is returned.
g_async_queue_timed_pop_unlocked | Pops data from the queue.
g_async_queue_length_unlocked | Returns the length of the queue.
g_async_queue_sort_unlocked | Sorts queue using func.

Give feedback of this article

Atomic Operations

Function | Description
g_atomic_int_get | Reads the value of the integer pointed to by atomic.
g_atomic_int_add | Sets the value of the integer pointed to by atomic.
g_atomic_int_exchange_and_add | Atomically adds val to the integer pointed to by atomic.
g_atomic_int_compare_and_exchange | Atomically adds val to the integer pointed to by atomic.
g_atomic_pointer_get | Compares oldval with the integer pointed to by atomic and if they are equal, atomically exchanges *atomic with newval.
g_atomic_pointer_compare_and_exchange | Reads the value of the pointer pointed to by atomic.
g_atomic_int_inc | Sets the value of the pointer pointed to by atomic.
g_atomic_int_dec_and_test | Compares oldval with the pointer pointed to by atomic and if they are equal, atomically exchanges *atomic with newval.

Give feedback of this article

Automatic String Completion

Function | Description
GCompletion | The data structure used for automatic completion.
g_completion_new | Creates a new GCompletion.
GCompletionFunc | Specifies the type of the function passed to g_completion_new().
g_completion_add_items | Adds items to the GCompletion.
g_completion_remove_items | Removes items from a GCompletion.
g_completion_clear_items | Removes all items from the GCompletion.
g_completion_complete | Attempts to complete the string prefix using the GCompletion target items.
g_completion_complete_utf8 | Attempts to complete the string prefix using the GCompletion target items.
g_completion_set_compare | Attempts to complete the string prefix using the GCompletion target items.
GCompletionStrncmpFunc | Specifies the type of the function passed to g_completion_set_compare().
g_completion_free | Frees all memory used by the GCompletion.

Give feedback of this article

Balanced Binary Trees

This chapter lists functions belonging to Balanced Binary Trees, which are sorted collection of key/value pairs optimized for searching and traversing in order.

Function | Description
GTree | The GTree struct is an opaque data structure representing a Balanced Binary Tree.
g_tree_new | Creates a new GTree.
g_tree_new_with_data | Creates a new GTree with a comparison function that accepts user data.
g_tree_new_full | Creates a new GTree and allows to specify functions to free the memory allocated for the key and value that get called when removing the entry from the GTree.
g_tree_insert | Inserts a key/value pair into a GTree.
g_tree_replace | Inserts a new key and value into a GTree.
g_tree_nnodes | Gets the number of nodes in a GTree.
g_tree_height | If the GTree contains no nodes, the height is 0.
g_tree_lookup | Gets the value corresponding to the given key.
g_tree_lookup_extended | Looks up a key in the GTree, returning the original key and the associated value and a gboolean which is TRUE if the key was found.
g_tree_foreach | Calls the given function for each of the key/value pairs in the GTree.
g_tree_traverse | Calls the given function for each node in the GTree.
GTraverseFunc | Specifies the type of function passed to g_tree_traverse().
GTraverseType | Specifies the type of traversal performed by g_tree_traverse(), g_node_traverse() and g_node_find().
g_tree_search | Searches a GTree using search_func.
g_tree_remove | Removes a key/value pair from a GTree.
g_tree_steal | Removes a key and its associated value from a GTree without calling the key and value destroy functions.
g_tree_destroy | Destroys the GTree.

Give feedback of this article

Basic Types

Function | Description
gboolean | A standard boolean type.
gpointer | An untyped pointer.
gconstpointer | An untyped pointer to constant data.
gchar | Corresponds to the standard C char type.
guchar | Corresponds to the standard C unsigned char type.
gint | Corresponds to the standard C int type.
guint | Corresponds to the standard C unsigned int type.
gshort | Corresponds to the standard C short type.
gushort | Corresponds to the standard C unsigned short type.
glong | Corresponds to the standard C long type.
gulong | Corresponds to the standard C unsigned long type.
gint8 | A signed integer guaranteed to be 8 bits on all platforms.
guint8 | An unsigned integer guaranteed to be 8 bits on all platforms.
gint16 | A signed integer guaranteed to be 16 bits on all platforms.
guint16 | An unsigned integer guaranteed to be 16 bits on all platforms.
gint32 | A signed integer guaranteed to be 32 bits on all platforms.
guint32 | An unsigned integer guaranteed to be 32 bits on all platforms.
G_HAVE_GINT64 | This macro is defined if 64-bit signed and unsigned integers are available on the platform.
gint64 | A signed integer guaranteed to be 64 bits on all platforms on which it is available
guint64 | An unsigned integer guaranteed to be 64 bits on all platforms on which it is available
G_GINT64_CONSTANT | This macro is used to insert 64-bit integer literals into the source code.
gfloat | This macro is used to insert 64-bit unsigned integer literals into the source code.
gdouble | Corresponds to the standard C float type.
gsize | An unsigned 32-bit integer intended to represent sizes of data structures.
gssize | A signed 32-bit integer intended to represent sizes of data structures.

Give feedback of this article

Byte Arrays

GByteArray is based on GArray, to provide arrays of bytes which grow automatically as elements are added.
Function | Description
GByteArray | The GByteArray struct allows access to the public fields of a GByteArray.
g_byte_array_new | Creates a new GByteArray with reserved_size bytes preallocated
g_byte_array_sized_new | Adds the given bytes at the end of the GByteArray.
g_byte_array_append | Adds the given bytes at the end of the GByteArray.
g_byte_array_prepend | Adds the given data at the start of the GByteArray.
g_byte_array_remove_index | Removes the byte at the given index from a GByteArray.
g_byte_array_remove_index_fast | Removes the byte at the given index from a GByteArray.
g_byte_array_remove_range | Removes the given number of bytes starting at the given index from a GByteArray.
g_byte_array_sort | Sorts a byte array, using compare_func
g_byte_array_sort_with_data | Sorts a byte array, but the comparison function takes a user data argument.
g_byte_array_set_size | Sets the size of the GByteArray.
g_byte_array_free | Frees the memory allocated by the GByteArray.

Give feedback of this article

Byte Order Macros

Function | Description
G_BYTE_ORDER | The host byte order.
G_LITTLE_ENDIAN | Specifies one of the possible types of byte order.
G_BIG_ENDIAN | Specifies one of the possible types of byte order.
G_PDP_ENDIAN | Specifies one of the possible types of byte order (currently unused).
g_htonl | Converts a 32-bit integer value from host to network byte order.
g_htons | Converts a 16-bit integer value from host to network byte order.
g_ntohl | Converts a 32-bit integer value from network to host byte order.
g_ntohs | Converts a 16-bit integer value from network to host byte order.
GINT_FROM_BE | Converts a gint value from big-endian to host byte order.
GINT_FROM_LE | Converts a gint value from little-endian to host byte order.
GINT_TO_BE | Converts a gint value from host byte order to big-endian.
GINT_TO_LE | Converts a gint value from host byte order to little-endian.
GUINT_FROM_BE | Converts a guint value from big-endian to host byte order.
GUINT_FROM_LE | Converts a guint value from little-endian to host byte order.
GUINT_TO_BE | Converts a guint value from host byte order to big-endian.
GUINT_TO_LE | Converts a guint value from host byte order to little-endian.
GLONG_FROM_BE | Converts a glong value from big-endian to the host byte order.
GLONG_FROM_LE | Converts a glong value from little-endian to host byte order.
GLONG_TO_BE | Converts a glong value from host byte order to big-endian.
GLONG_TO_LE | Converts a glong value from host byte order to little-endian.
GULONG_FROM_BE | Converts a gulong value from big-endian to host byte order.
GULONG_TO_BE | Converts a gulong value from little-endian to host byte order.
GULONG_TO_LE | Converts a gulong value from host byte order to big-endian.
GINT16_FROM_BE | Converts a gulong value from host byte order to little-endian.
GINT16_FROM_LE | Converts a gint16 value from big-endian to host byte order.
GINT16_TO_BE | Converts a gint16 value from little-endian to host byte order.
GINT16_TO_LE | Converts a gint16 value from host byte order to big-endian.
GUINT16_FROM_BE | Converts a gint16 value from host byte order to little-endian.
GUINT16_FROM_LE | Converts a guint16 value from big-endian to host byte order.
GUINT16_TO_BE | Converts a guint16 value from little-endian to host byte order.
GUINT16_TO_LE | Converts a guint16 value from host byte order to big-endian.
GINT32_FROM_BE | Converts a guint16 value from host byte order to little-endian.
GINT32_FROM_LE | Converts a gint32 value from big-endian to host byte order.
GINT32_TO_BE | Converts a gint32 value from little-endian to host byte order.
GINT32_TO_LE | Converts a gint32 value from host byte order to big-endian.
GUINT32_FROM_BE | Converts a gint32 value from host byte order to little-endian.
GUINT32_FROM_LE | Converts a guint32 value from big-endian to host byte order.
GUINT32_TO_BE | Converts a guint32 value from little-endian to host byte order.
GUINT32_TO_LE | Converts a guint32 value from host byte order to big-endian.
GINT64_FROM_BE | Converts a guint32 value from host byte order to little-endian.
GINT64_FROM_LE | Converts a gint64 value from big-endian to host byte order.
GINT64_TO_BE | Converts a gint64 value from little-endian to host byte order.
GINT64_TO_LE | Converts a gint64 value from host byte order to big-endian.
GUINT64_FROM_BE | Converts a gint64 value from host byte order to little-endian.
GUINT64_FROM_LE | Converts a guint64 value from big-endian to host byte order.
GUINT64_TO_BE | Converts a guint64 value from little-endian to host byte order.
GUINT64_TO_LE | Converts a guint64 value from host byte order to big-endian.
GUINT16_SWAP_BE_PDP | Converts a guint16 value between big-endian and pdp-endian byte order.
GUINT16_SWAP_LE_BE | Converts a guint16 value between little-endian and big-endian byte order.
GUINT16_SWAP_LE_PDP | Converts a guint16 value between little-endian and pdp-endian byte order.
GUINT32_SWAP_BE_PDP | Converts a guint32 value between big-endian and pdp-endian byte order.
GUINT32_SWAP_LE_BE | Converts a guint32 value between big-endian and pdp-endian byte order.
GUINT32_SWAP_LE_PDP | Converts a guint32 value between little-endian and pdp-endian byte order.
GUINT64_SWAP_LE_BE | Converts a guint64 value between little-endian and big-endian byte order.

Give feedback of this article

Caches

This chapter lists functions of the category Caches.
Function | Description
GCache | The GCache struct is an opaque data structure containing information about a GCache.
g_cache_new | Creates a new GCache.
g_cache_insert | Gets the value corresponding to the given key, creating it if necessary.
g_cache_remove | Decreases the reference count of the given value.
g_cache_destroy | Frees the memory allocated for the GCache.
g_cache_key_foreach | Calls the given function for each of the keys in the GCache.
g_cache_value_foreach | Calls the given function for each of the values in the GCache.
GCacheDestroyFunc | Specifies the type of the value_destroy_func and key_destroy_func functions passed to g_cache_new().
GCacheDupFunc | Specifies the type of the key_dup_func function passed to g_cache_new().
GCacheNewFunc | Specifies the type of the value_new_func function passed to g_cache_new().

Give feedback of this article

Character Set Conversion

Function | Description
g_convert | Converts a string from one character set to another.
g_convert_with_fallback | Converts a string from one character set to another, possibly including fallback sequences for characters not representable in the output.
GIConv | The GIConv struct wraps an iconv() conversion descriptor. It contains private data and should only be accessed using the following functions.
g_convert_with_iconv | Converts a string from one character set to another.
G_CONVERT_ERROR | Error domain for character set conversions.
g_iconv_open | Same as the standard UNIX routine iconv_open(), but may be implemented via libiconv on UNIX flavors that lack a native implementation.
g_iconv | Same as the standard UNIX routine iconv(), but may be implemented via libiconv on UNIX flavors that lack a native implementation.
g_iconv_close | Same as the standard UNIX routine iconv_close(), but may be implemented via libiconv on UNIX flavors that lack a native implementation.
g_locale_to_utf8 | Converts a string which is in the encoding used for strings by the C runtime (usually the same as that used by the operating system) in the current locale into a UTF-8 string.
g_filename_to_utf8 | Converts a string which is in the encoding used by GLib for filenames into a UTF-8 string. Note that on Windows GLib uses UTF-8 for filenames.
g_filename_from_utf8 | Converts a string from UTF-8 to the encoding GLib uses for filenames. Note that on Windows GLib uses UTF-8 for filenames.
g_filename_from_uri | Converts an escaped ASCII-encoded URI to a local filename in the encoding used for filenames.
g_filename_to_uri | Converts an absolute filename to an escaped ASCII-encoded URI.
g_get_filename_charsets | Determines the preferred character sets used for filenames.
g_filename_display_name | Converts a filename into a valid UTF-8 string.
g_filename_display_basename | Returns the display basename for the particular filename, guaranteed to be valid UTF-8.
g_uri_list_extract_uris | Splits an URI list conforming to the text/uri-list mime type defined in RFC 2483 into individual URIs, discarding any comments.
g_locale_from_utf8 | Converts a string from UTF-8 to the encoding used for strings by the C runtime (usually the same as that used by the operating system) in the current locale.
GConvertError | Error codes returned by character set conversion routines.
g_get_charset | Obtains the character set for the current locale; use this character set as an argument to g_convert(), to convert from the current locale's encoding to some other encoding.

Give feedback of this article

Commandline option parser

Function | Description
GOptionError | Error codes returned by option parsing.
G_OPTION_ERROR | Error domain for option parsing.
GOptionArgFunc | The type of function to be passed as callback for G_OPTION_ARG_CALLBACK options.
GOptionContext | A GOptionContext struct defines which options are accepted by the commandline option parser.
g_option_context_new | Creates a new option context.
g_option_context_free | Frees context and all the groups which have been added to it.
g_option_context_parse | Parses the command line arguments, recognizing options which have been added to context.
g_option_context_set_help_enabled | Enables or disables automatic generation of --help output.
g_option_context_get_help_enabled | Returns whether automatic --help generation is turned on for context.
g_option_context_set_ignore_unknown_options | Sets whether to ignore unknown options or not.
g_option_context_get_ignore_unknown_options | Returns whether unknown options are ignored or not.
GOptionArg | The GOptionArg enum values determine which type of extra argument the options expect to find.
GOptionFlags | Flags which modify individual options.
G_OPTION_REMAINING | If a long option in the main group has this name, it is not treated as a regular option.
GOptionEntry | A GOptionEntry defines a single option.
g_option_context_add_main_entries | A convenience function which creates a main group if it doesn't exist, adds the entries to it and sets the translation domain.
GOptionGroup | A GOptionGroup struct defines the options in a single group. The struct has only private fields and should not be directly accessed.
g_option_context_add_group | Adds a GOptionGroup to the context, so that parsing with context will recognize the options in the group.
g_option_context_set_main_group | Sets a GOptionGroup as main group of the context.
g_option_context_get_main_group | Returns a pointer to the main group of context.
g_option_group_new | Creates a new GOptionGroup.
g_option_group_free | Frees a GOptionGroup. Note: do not free groups which have been added to a GOptionContext.
g_option_group_add_entries | Adds the options specified in entries to group.
GOptionParseFunc | The type of function that can be called before and after parsing.
g_option_group_set_parse_hooks | Associates two functions with group which will be called from g_option_context_parse() before the first option is parsed and after the last option has been parsed, respectively.
GOptionErrorFunc | The type of function to be used as callback when a parse error occurs.
g_option_group_set_error_hook | Associates a function with group which will be called from g_option_context_parse() when an error occurs.
GTranslateFunc | The type of functions which are used to translate user-visible strings, for --help output.
g_option_group_set_translate_func | Sets the function which is used to translate user-visible strings, for --help output.
g_option_group_set_translation_domain | A convenience function to use gettext() for translating user-visible strings.

Give feedback of this article

Datasets

This chapter lists functions of the category Datasets.
Function | Description
g_dataset_id_set_data | Sets the data element associated with the given GQuark id.
g_dataset_id_set_data_full | Sets the data element associated with the given GQuark id, and also the function to call when the data element is destroyed.
GDestroyNotify | Specifies the type of function which is called when a data element is destroyed.
g_dataset_id_get_data | Gets the data element corresponding to a GQuark.
g_dataset_id_remove_data | Removes a data element from a dataset.
g_dataset_id_remove_no_notify | Removes an element, without calling its destroy notification function.
g_dataset_set_data | Sets the data corresponding to the given string identifier.
g_dataset_set_data_full | Sets the data corresponding to the given string identifier, and the function to call when the data element is destroyed.
g_dataset_get_data | Gets the data element corresponding to a string.
g_dataset_remove_data | Removes a data element corresponding to a string.
g_dataset_remove_no_notify | Removes an element, without calling its destroy notifier.
g_dataset_foreach | Calls the given function for each data element which is associated with the given location.
GDataForeachFunc | Specifies the type of function passed to g_dataset_foreach().
g_dataset_destroy | Destroys the dataset, freeing all memory allocated, and calling any destroy functions set for data elements.

Give feedback of this article

Date and Time Functions

Function | Description
G_USEC_PER_SEC | Number of microseconds in one second (1 million). This macro is provided for code readability.
GTimeVal | Represents a precise time, with seconds and microseconds.
g_get_current_time | Equivalent to the UNIX gettimeofday() function, but portable.
g_usleep | Pauses the current thread for the given number of microseconds.
g_time_val_add | Adds the given number of microseconds to time_. microseconds can also be negative to decrease the value of time_.
GDate | Represents a day between January 1, Year 1 and a few thousand years in the future.
GTime | Simply a replacement for time_t. Unrelated to GTimer.
GDateDMY | This enumeration is not used in the API, but may be useful to mark a number as a day, month, or year.
GDateDay | Integer representing a day of the month; between 1 and 31. G_DATE_BAD_DAY represents an invalid day of the month.
GDateMonth | Enumeration representing a month; values are G_DATE_JANUARY, G_DATE_FEBRUARY, etc. G_DATE_BAD_MONTH is the invalid value.
GDateYear | Integer representing a year; G_DATE_BAD_YEAR is the invalid value. The year must be 1 or higher; negative (BC) years are not allowed. The year is represented with four digits.
GDateWeekday | Enumeration representing a day of the week; G_DATE_MONDAY, G_DATE_TUESDAY, etc. G_DATE_BAD_WEEKDAY is an invalid weekday.
G_DATE_BAD_DAY | Represents an invalid GDateDay.
G_DATE_BAD_JULIAN | Represents an invalid Julian day number.
G_DATE_BAD_YEAR | Represents an invalid year.
g_date_new | Allocates a GDate and initializes it to a sane state.
g_date_new_dmy | Like g_date_new(), but also sets the value of the date.
g_date_new_julian | Like g_date_new(), but also sets the value of the date.
g_date_free | Initializes one or more GDate structs to a sane but invalid state.
g_date_clear | Frees a GDate returned from g_date_new().
g_date_set_day | Sets the day of the month for a GDate. If the resulting day-month-year triplet is invalid, the date will be invalid.
g_date_set_month | Sets the month of the year for a GDate. If the resulting day-month-year triplet is invalid, the date will be invalid.
g_date_set_year | Sets the year for a GDate. If the resulting day-month-year triplet is invalid, the date will be invalid.
g_date_set_dmy | Sets the value of a GDate from a day, month, and year.
g_date_set_julian | Sets the value of a GDate from a Julian day number.
g_date_set_time | Sets the value of a date from a GTime value.
g_date_set_parse | Sets the value of a date from a time_t value.
g_date_add_days | Sets the value of a date from a GTimeVal value.
g_date_subtract_days | Parses a user-inputted string str, and try to figure out what date it represents, taking the current locale into account.
g_date_add_months | Increments a date some number of days. To move forward by weeks, add weeks*7 days. The date must be valid.
g_date_subtract_months | Moves a date some number of days into the past. To move by weeks, just move by weeks*7 days. The date must be valid.
g_date_add_years | Increments a date by some number of months.
g_date_subtract_years | Moves a date some number of months into the past.
g_date_days_between | Increments a date by some number of years.
g_date_compare | Moves a date some number of years into the past.
g_date_clamp | Computes the number of days between two dates.
g_date_order | qsort()-style comparsion function for dates. Both dates must be valid.
g_date_get_day | If date is prior to min_date, sets date equal to min_date.
g_date_get_month | Checks if date1 is less than or equal to date2, and swap the values if this is not the case.
g_date_get_year | Returns the day of the month. The date must be valid.
g_date_get_julian | Returns the month of the year. The date must be valid.
g_date_get_julian | Returns the year of a GDate. The date must be valid.
g_date_get_day_of_year | Returns the Julian day or "serial number" of the GDate.
g_date_get_days_in_month | Returns the day of the week for a GDate. The date must be valid.
g_date_is_first_of_month | Returns the day of the year, where Jan 1 is the first day of the year. The date must be valid.
g_date_is_last_of_month | Returns the number of days in a month, taking leap years into account.
g_date_is_leap_year | Returns TRUE if the date is on the first of a month. The date must be valid.
g_date_get_monday_week_of_year | Returns TRUE if the date is the last day of the month. The date must be valid.
g_date_get_monday_weeks_in_year | Returns TRUE if the year is a leap year.
g_date_get_sunday_week_of_year | Returns the week of the year, where weeks are understood to start on Monday
g_date_get_sunday_weeks_in_year | Returns the number of weeks in the year, where weeks are taken to start on Monday.
g_date_get_iso8601_week_of_year | Returns the week of the year during which this date falls, if weeks are understood to being on Sunday.
g_date_strftime | Generates a printed representation of the date, in a locale-specific way.
g_date_to_struct_tm | Fills in the date-related bits of a struct tm using the date value. Initializes the non-date parts with something sane but meaningless.
g_date_valid | Generates a printed representation of the date, in a locale-specific way.Returns TRUE if the GDate represents an existing day.
g_date_valid_day | Returns TRUE if the day of the month is valid (a day is valid if it's between 1 and 31 inclusive).
g_date_valid_month | Returns TRUE if the month value is valid. The 12 GDateMonth enumeration values are the only valid months.
g_date_valid_year | Returns TRUE if the year is valid. Any year greater than 0 is valid, though there is a 16-bit limit to what GDate will understand.
g_date_valid_dmy | Returns TRUE if the day-month-year triplet forms a valid, existing day in the range of days GDate understands (Year 1 or later, no more than a few thousand years in the future).
g_date_valid_julian | Returns TRUE if the Julian day is valid. Anything greater than zero is basically a valid Julian, though there is a 32-bit limit.
g_date_valid_weekday | Returns TRUE if the weekday is valid. The 7 GDateWeekday enumeration values are the only valid weekdays.

Give feedback of this article

Double-ended Queues

This chapter lists GQueue structure and its associated functions, which provide a standard queue data structure.
Function | Description
GQueue | Contains the public fields of a Queue.
g_queue_new | Creates a new GQueue.
g_queue_free | Frees the memory allocated for the GQueue.
g_queue_is_empty | Returns TRUE if the queue is empty.
g_queue_get_length | Returns the number of items in queue.
g_queue_reverse | Reverses the order of the items in queue.
g_queue_copy | Copies a queue.
g_queue_foreach | Calls func for each element in the queue passing user_data to the function.
g_queue_find | Finds the first link in queue which contains data.
g_queue_find_custom | Finds an element in a GQueue, using a supplied function to find the desired element.
g_queue_sort | Sorts queue using compare_func.
g_queue_push_head | Adds a new element at the head of the queue.
g_queue_push_tail | Adds a new element at the tail of the queue
g_queue_push_nth | Inserts a new element into queue at the given position
g_queue_pop_head | Removes the first element of the queue.
g_queue_pop_tail | Removes the last element of the queue.
g_queue_pop_nth | Removes the n'th element of queue.
g_queue_peek_head | Returns the first element of the queue.
g_queue_peek_tail | Returns the last element of the queue.
g_queue_peek_nth | Returns the n'th element of queue.
g_queue_index | Returns the position of link_ in queue.
g_queue_unlink | Unlinks link_ so that it will no longer be part of queue.
g_queue_delete_link | Removes link_ from queue and frees it.

Give feedback of this article

Doubly Linked lists

This section lists functions containing integer values or pointers to data, which have the ability to iterate over the list in both directions.

Character classification

Function | Description
GList | The GList struct is used for each element in a doubly-linked list.
g_list_append | Adds a new element at the end of the list.
g_list_prepend | Adds a new element at the start of the list.
g_list_insert | Inserts a new element at the given point in the list.
g_list_insert_before | Inserts a new element before the given point in the list.
g_list_insert_sorted | Inserts a new element in the list, using the given comparison function to determine its position.
g_list_remove | Removes an element from a GList.
g_list_remove_link | Removes an element from GList, without freeing the element.
g_list_delete_link | Deletes the node link_ from list.
g_list_remove_all | Removes all list nodes with data equal to data.
g_list_free | Frees all of the memory used by a GList.
g_list_alloc | Allocates space for one GList element.
g_list_free_1 | Frees one GList element.
g_list_length | Gets the number of elements in a GList.
g_list_copy | Copies a GList.
g_list_reverse | Reverses a GList.
g_list_sort | Sorts a GList using the given comparison function.
GCompareFunc | Specifies the type of a comparison function used to compare two values.
g_list_sort_with_data | Sorts a GList using the given comparison function and also accepts user data arguments for comparing.
GCompareDataFunc | Specifies the type of a comparison function used to compare two values.
g_list_concat | Adds the second GList to the end of the first GList.
g_list_foreach | Calls a function for each element of a GList.
GFunc | Specifies the type of functions passed to g_list_foreach() and g_slist_foreach().
g_list_first | Gets the first element in a GList.
g_list_last | Gets the last element in a GList.
g_list_previous | A macro used to get the previous element in a GList.
g_list_next | A macro used to get the next element in a GList.
g_list_nth | Gets the element at the given position in a GList.
g_list_nth_data | Gets the data of the element at the given position.
g_list_nth_prev | Gets the element n and places before list.
g_list_find | Finds the element in a GList which contains the given data.
g_list_find_custom | Finds an element in a GList, using a supplied function to find the desired element.
g_list_position | Gets the position of the given element in the GList (starting from 0).
g_list_index | Gets the position of the element containing the given data (starting from 0).
g_list_push_allocator | Sets the allocator to use to allocate GList elements.
g_list_pop_allocator | Restores the previous GAllocator used when allocating GList elements.

Give feedback of this article

Dynamic Loading of Modules

Function | Description
GModule | The GModule struct is an opaque data structure to represent a Dynamically-Loaded Module.
g_module_supported | Checks if modules are supported on the current platform.
g_module_build_path | A portable way to build the filename of a module.
g_module_open | Opens a module.
GModuleFlags | Flags passed to g_module_open().
g_module_symbol | Gets a symbol pointer from a module.
g_module_name | Gets the filename from a GModule.
g_module_make_resident | Ensures that a module will never be unloaded.
g_module_close | Closes a module.
g_module_error | Gets a string describing the last module error.
GModuleCheckInit | Specifies the type of the module initialization function.
GModuleUnload | Specifies the type of the module function called when it is unloaded.
G_MODULE_SUFFIX | Expands to the proper shared library suffix for the current platform without the leading dot.
G_MODULE_EXPORT | Used to declare functions exported by modules.
G_MODULE_IMPORT | Used to declare functions imported from modules.

Give feedback of this article

Error Reporting

Function | Description
GError | The GError structure contains information about an error that has occurred.
g_error_new | Creates a new GError with the given domain and code, and a message formatted with format.
g_error_new_literal | Creates a new GError; unlike g_error_new(), message is not a printf()-style format string.
g_error_free | Frees a GError and associated resources.
g_error_copy | Makes a copy of error.
g_error_matches | Returns TRUE if error matches domain and code, FALSE otherwise.
g_error_matches | Does nothing if err is NULL; if err is non-NULL, then *err must be NULL. A new GError is created and assigned to *err.
g_propagate_error | If dest is NULL, free src; otherwise, moves src into *dest. *dest must be NULL.
g_clear_error | If err is NULL, does nothing. If err is non-NULL, calls g_error_free() on *err and sets *err to NULL.

Give feedback of this article

File Utilities

Function | Description
GFileError | Values corresponding to errno codes returned from file operations on UNIX.
G_FILE_ERROR | Error domain for file operations.
GFileTest | A test to perform on a file using g_file_test().
g_file_error_from_errno | Gets a GFileError constant based on the passed-in errno.
g_file_get_contents | Reads an entire file into allocated memory, with good error checking.
g_file_set_contents | Writes all of contents to a file named filename, with good error checking.
g_file_test | Returns TRUE if any of the tests in the bitfield test are TRUE.
g_mkstemp | Opens a temporary file.
g_file_open_tmp | Opens a file for writing in the preferred directory for temporary files (as returned by g_get_tmp_dir()).
g_file_read_link | Reads the contents of the symbolic link filename like the POSIX readlink() function.
g_mkdir_with_parents | Create a directory if it doesn't already exist.
GDir | An opaque structure representing an opened directory.
g_dir_open | Opens a directory for reading.
g_dir_read_name | Retrieves the name of the next entry in the directory.
g_dir_rewind | Resets the given directory.
g_dir_close | Closes the directory and deallocates all related resources.
GMappedFile | The GMappedFile represents a file mapping created with g_mapped_file_new().
g_mapped_file_new | Maps a file into memory.
g_mapped_file_free | Unmaps the buffer of file and frees it.
g_mapped_file_get_length | Returns the length of the contents of a GMappedFile.
g_mapped_file_get_contents | Returns the contents of a GMappedFile.
g_open | A wrapper for the POSIX open() function.
g_rename | A wrapper for the POSIX rename() function.
g_mkdir | A wrapper for the POSIX mkdir() function.
g_stat | A wrapper for the POSIX stat() function.
g_lstat | A wrapper for the POSIX lstat() function.
g_unlink | A wrapper for the POSIX unlink() function.
g_remove | A wrapper for the POSIX remove() function.
g_rmdir | A wrapper for the POSIX rmdir() function.
g_fopen | A wrapper for the POSIX fopen() function.
g_freopen | A wrapper for the POSIX freopen() function.
g_chmod | A wrapper for the POSIX chmod() function.
g_access | A wrapper for the POSIX access() function.
g_creat | A wrapper for the POSIX creat() function.
g_chdir | A wrapper for the POSIX chdir() function.

Give feedback of this article

Glob-style pattern matching

Function | Description
GPatternSpec | A GPatternSpec is the 'compiled' form of a pattern. This structure is opaque and its fields cannot be accessed directly.
g_pattern_spec_new | Compiles a pattern to a GPatternSpec.
g_pattern_spec_free | Frees the memory allocated for the GPatternSpec.
g_pattern_spec_equal | Compares two compiled pattern specs and returns whether they will match the same set of strings.
g_pattern_match | Matches a string against a compiled pattern. Passing the correct length of the string given is mandatory.
g_pattern_match_string | Matches a string against a compiled pattern.
g_pattern_match_simple | Matches a string against a pattern given as a string.

Give feedback of this article

Hash Tables

This chapter lists functions that provide associations between optimized keys and values, so that given a key, the associated value can be found very quickly.
Function | Description
GHashTable | The GHashTable struct is an opaque data structure to represent a Hash Table.
g_hash_table_new | Creates a new GHashTable.
g_hash_table_new_full | Creates a new GHashTable. and allows to specify functions to free the memory allocated.
GHashFunc | Specifies the type of the hash function which is passed to g_hash_table_new() when a GHashTable is created.
GEqualFunc | Specifies the type of a function used to test two values for equality.
g_hash_table_insert | Inserts a new key and value into a GHashTable.
g_hash_table_replace | Inserts a new key and value into a GHashTable.
g_hash_table_size | Returns the number of elements contained in the GHashTable.
g_hash_table_lookup | Looks up a key in a GHashTable.
g_hash_table_lookup_extended | Looks up a key in the GHashTable.
g_hash_table_foreach | Calls the given function for each of the key/value pairs in the GHashTable.
g_hash_table_find | Calls the given function for key/value pairs in the GHashTable until predicate returns TRUE.
GHFunc | Specifies the type of the function passed to g_hash_table_foreach().
g_hash_table_remove | Removes a key and its associated value from a GHashTable.
g_hash_table_steal | Removes a key and its associated value from a GHashTable without calling the key and value destroy functions.
g_hash_table_foreach_remove | Calls the given function for each key/value pair in the GHashTable.
g_hash_table_foreach_steal | Calls the given function for each key/value pair in the GHashTable.
GHRFunc | Specifies the type of the function passed to g_hash_table_foreach_remove().
g_hash_table_freeze | This function is deprecated and will be removed in the next major release of GLib.
g_hash_table_thaw | This function is deprecated and will be removed in the next major release of GLib. It does nothing.
g_hash_table_destroy | Destroys the GHashTable.
g_direct_equal | Compares two gpointer arguments and returns TRUE if they are equal.
g_direct_hash | Converts a gpointer to a hash value.
g_int_equal | Compares the two gint values being pointed to and returns TRUE if they are equal.
g_int_hash | Converts a pointer to a gint to a hash value.
g_str_equal | Compares two strings and returns TRUE if they are equal.
g_str_hash | Converts a string to a hash value.

Give feedback of this article

Hook Functions

Function | Description
GHookList | The GHookList struct represents a list of hook functions.
GHook | The GHook struct represents a single hook function in a GHookList.
GHookFinalizeFunc | Defines the type of function to be called when a hook in a list of hooks gets finalized.
GHookFunc | Defines the type of a hook function that can be invoked by g_hook_list_invoke().
GHookCheckFunc | Defines the type of a hook function that can be invoked by g_hook_list_invoke_check().
g_hook_list_init | Initializes a GHookList. This must be called before the GHookList is used.
g_hook_list_invoke | Calls all of the GHook functions in a GHookList.
g_hook_list_invoke_check | Calls all of the GHook functions in a GHookList. Any function which returns FALSE is removed from the GHookList.
g_hook_list_marshal | Calls a function on each valid GHook.
GHookMarshaller | Defines the type of function used by g_hook_list_marshal().
g_hook_list_marshal_check | Calls a function on each valid GHook and destroys it if the function returns FALSE.
GHookCheckMarshaller | Defines the type of function used by g_hook_list_marshal_check().
g_hook_list_clear | Removes all the GHook elements from a GHookList.
g_hook_alloc | Allocates space for a GHook and initializes it.
g_hook_append | Appends a GHook onto the end of a GHookList.
g_hook_prepend | Prepends a GHook on the start of a GHookList.
g_hook_insert_before | Inserts a GHook into a GHookList, before a given GHook.
g_hook_insert_sorted | Inserts a GHook into a GHookList, sorted by the given function.
GHookCompareFunc | Defines the type of function used to compare GHook elements in g_hook_insert_sorted().
g_hook_compare_ids | Compares the ids of two GHook elements, returning a negative value if the second id is greater than the first.
g_hook_get | Returns the GHook with the given id, or NULL if it is not found.
g_hook_find | Finds a GHook in a GHookList using the given function to test for a match. .
GHookFindFunc | Defines the type of the function passed to g_hook_find().
g_hook_find_data | Finds a GHook in a GHookList with the given data.
g_hook_find_func | Finds a GHook in a GHookList with the given function.
g_hook_find_func_data | Finds a GHook in a GHookList with the given function and data.
g_hook_first_valid | Returns the first GHook in a GHookList which has not been destroyed.
g_hook_next_valid | Returns the next GHook in a GHookList which has not been destroyed.
GHookFlagMask | Flags used internally in the GHook implementation.
G_HOOK_FLAGS | Returns the flags of a hook.
G_HOOK_FLAG_USER_SHIFT | The position of the first bit which is not reserved for internal use be the GHook implementation, i.e. 1 << G_HOOK_FLAG_USER_SHIFT is the first bit which can be used for application-defined flags.
G_HOOK | Casts a pointer to a GHook*.
G_HOOK_IS_VALID | Returns TRUE if the GHook is valid, i.e. it is in a GHookList, it is active and it has not been destroyed.
G_HOOK_ACTIVE | Returns TRUE if the GHook is active, which is normally TRUE until the GHook is destroyed.
G_HOOK_IN_CALL | Returns TRUE if the GHook function is currently executing.
G_HOOK_IS_UNLINKED | Returns TRUE if the GHook is not in a GHookList.
g_hook_ref | Increments the reference count for a GHook.
g_hook_unref | Decrements the reference count of a GHook. If the reference count falls to 0, the GHook is removed from the GHookList and g_hook_free() is called to free it.
g_hook_free | Calls the GHookList hook_free function if it exists, and frees the memory allocated for the GHook.
g_hook_destroy | Destroys a GHook, given its ID.
g_hook_destroy_link | Removes one GHook from a GHookList, marking it inactive and calling g_hook_unref() on it.

Give feedback of this article

Internationalization

Function | Description
_() | Marks a string for translation, gets replaced with the translated string at runtime.
Q_ | Like _(), but applies g_strip_context() to the translation. This has the advantage that the string can be adorned with a prefix to guarantee uniqueness and provide context to the translator.
N_ | Marks a string for translation, gets replaced with the untranslated string at runtime. This is useful in situations where the translated strings can't be directly used, e.g. in string array initializers.
g_strip_context | An auxiliary function for gettext() support.
g_get_language_names | Computes a list of applicable locale names, which can be used to e.g. construct locale-dependent filenames or search paths. The returned list is sorted from most desirable to least desirable and always contains the default locale "C".

Give feedback of this article

IO Channels

Function | Description
GIOChannel | A data structure representing an IO Channel.
g_io_channel_unix_new | Creates a new GIOChannel given a file descriptor.
g_io_channel_unix_get_fd | Returns the file descriptor of the GIOChannel.
g_io_channel_win32_new_fd | Creates a new GIOChannel given a file descriptor on Windows.
g_io_channel_win32_new_socket | Creates a new GIOChannel given a socket on Windows.
g_io_channel_win32_new_messages | Creates a new GIOChannel given a window handle on Windows.
g_io_channel_init | Initializes a GIOChannel struct.
g_io_channel_new_file | Open a file filename as a GIOChannel using mode mode.
g_io_channel_read_chars | Replacement for g_io_channel_read() with the new API.
g_io_channel_read_unichar | This function cannot be called on a channel with NULL encoding.
g_io_channel_read_line | Reads a line, including the terminating character(s), from a GIOChannel into a newly-allocated string.
g_io_channel_read_line_string | Reads a line from a GIOChannel, using a GString as a buffer.
g_io_channel_read_to_end | Reads all the remaining data from the file.
g_io_channel_write_chars | Replacement for g_io_channel_write() with the new API.
g_io_channel_write_unichar | This function cannot be called on a channel with NULL encoding.
g_io_channel_flush | Flushes the write buffer for the GIOChannel.
g_io_channel_seek_position | Replacement for g_io_channel_seek() with the new API.
GSeekType | An enumeration specifying the base position for a g_io_channel_seek_position() operation.
g_io_channel_shutdown | Close an IO channel.
GIOStatus | Stati returned by most of the GIOFuncs functions.
GIOChannelError | Error codes returned by GIOChannel operations.
G_IO_CHANNEL_ERROR | Error domain for GIOChannel operations.
g_io_channel_error_from_errno | Converts an errno error number to a GIOChannelError.
g_io_channel_ref | Increments the reference count of a GIOChannel.
g_io_channel_unref | Decrements the reference count of a GIOChannel.
g_io_create_watch | Creates a GSource that's dispatched when condition is met for the given channel.
g_io_add_watch | Adds the GIOChannel into the main event loop with the default priority.
g_io_add_watch_full | Adds the GIOChannel into the main event loop with the given priority.
GIOCondition | A bitwise combination representing a condition to watch for on an event source.
GIOFunc | Specifies the type of function passed to g_io_add_watch() or g_io_add_watch_full(), which is called when the requested condition on a GIOChannel is satisfied.
g_io_channel_get_buffer_size | A table of functions used to handle different types of GIOChannel in a generic way.
g_io_channel_set_buffer_size | Gets the buffer size.
g_io_channel_get_buffer_condition | Sets the buffer size.
g_io_channel_get_flags | This function returns a GIOCondition depending on whether there is data to be read/space to write data in the internal buffers in the GIOChannel.
g_io_channel_set_flags | Gets the current flags for a GIOChannel, including read-only flags such as G_IO_FLAG_IS_READABLE.
GIOFlags | Sets the (writeable) flags in channel to (flags & G_IO_CHANNEL_SET_MASK).
g_io_channel_get_line_term | Specifies properties of a GIOChannel.
g_io_channel_set_line_term | This sets the string that GIOChannel uses to determine where in the file a line break occurs.
g_io_channel_get_buffered | Returns whether channel is buffered.
g_io_channel_set_buffered | The buffering state can only be set if the channel's encoding is NULL. For any other encoding, the channel must be buffered.
g_io_channel_get_encoding | Gets the encoding for the input/output of the channel.
g_io_channel_set_encoding | Sets the encoding for the input/output of the channel.
g_io_channel_get_close_on_unref | Returns whether the file/socket/whatever associated with channel will be closed when channel receives its final unref and is destroyed.
g_io_channel_set_close_on_unref | Setting this flag to TRUE for a channel already closed can cause problems.
g_io_channel_read | Reads data from a GIOChannel.
GIOError | GIOError is only used by the deprecated functions g_io_channel_read(), g_io_channel_write(), and g_io_channel_seek().
g_io_channel_write | Writes data to a GIOChannel.
g_io_channel_seek | Sets the current position in the GIOChannel, similar to the standard library function fseek().
g_io_channel_close | Closes an IO channel.

Give feedback of this article

Keyed Data Lists

This chapter lists functions belonging to Keyed Data Lists.
Function | Description
GData | The GData struct is an opaque data structure to represent a Keyed Data List.
g_datalist_init | Resets the datalist to NULL.
g_datalist_id_set_data | Sets the data corresponding to the given GQuark id.
g_datalist_id_set_data_full | Sets the data corresponding to the given GQuark id, and the function to be called when the element is removed from the datalist.
g_datalist_id_get_data | Retrieves the data element corresponding to key_id.
g_datalist_id_remove_data | Removes an element, using its GQuark identifier.
g_datalist_id_remove_no_notify | Removes an element, without calling its destroy notification function.
g_datalist_set_data | Sets the data element corresponding to the given string identifier.
g_datalist_set_data_full | Sets the data element corresponding to the given string identifier, and the function to be called when the data element is removed.
g_datalist_get_data | Gets a data element, using its string identifer.
g_datalist_remove_data | Removes an element using its string identifier.
g_datalist_remove_no_notify | Removes an element, without calling its destroy notifier.
g_datalist_foreach | Calls the given function for each data element of the datalist.
g_datalist_clear | Frees all the data elements of the datalist.
g_datalist_set_flags | Turns on flag values for a data list.
g_datalist_unset_flags | Turns off flag values for a data list.
g_datalist_get_flags | Gets flags values packed in together with the datalist.
G_DATALIST_FLAGS_MASK | A bit-mask that restricts the possible flags passed to g_datalist_set_flags().

Give feedback of this article

Key-value file parser

Function | Description
GKeyFile | The GKeyFile struct contains only private fields and should not be used directly.
G_KEY_FILE_ERROR | Error domain for key file parsing.
GKeyFileError | Error codes returned by key file parsing.
GKeyFileFlags | Flags which influence the parsing.
g_key_file_new | Creates a new empty GKeyFile object.
g_key_file_free | Frees a GKeyFile.
g_key_file_set_list_separator | Sets the character which is used to separate values in lists.
g_key_file_load_from_file | Loads a key file into an empty GKeyFile structure.
g_key_file_load_from_data | Loads a key file from memory into an empty GKeyFile structure.
g_key_file_load_from_data_dirs | This function looks for a key file named file in the paths returned from g_get_user_data_dir() and g_get_system_data_dirs(), loads the file into key_file and returns the file's full path in full_path.
g_key_file_to_data | This function outputs key_file as a string.
g_key_file_get_start_group | Returns the name of the start group of the file.
g_key_file_get_groups | Returns all groups in the key file loaded with key_file. The array of returned groups will be NULL-terminated, so length may optionally be NULL.
g_key_file_get_keys | Returns all keys for the group name group_name.
g_key_file_has_group | Looks whether the key file has the group group_name.
g_key_file_has_key | Looks whether the key file has the key key in the group group_name.
g_key_file_get_value | Returns the value associated with key under group_name.
g_key_file_get_string | Returns the value associated with key under group_name.
g_key_file_get_locale_string | Returns the value associated with key under group_name translated in the given locale if available.
g_key_file_get_boolean | Returns the value associated with key under group_name as a boolean.
g_key_file_get_integer | Returns the value associated with key under group_name as an integer.
g_key_file_get_string_list | Returns the values associated with key under group_name.
g_key_file_get_locale_string_list | Returns the values associated with key under group_name translated in the given locale if available.
g_key_file_get_boolean_list | Returns the values associated with key under group_name as booleans.
g_key_file_get_integer_list | Returns the values associated with key under group_name as integers.
g_key_file_get_comment | Retrieves a comment above key from group_name. group_name.
g_key_file_set_value | Associates a new value with key under group_name.
g_key_file_set_string | Associates a new string value with key under group_name.
g_key_file_set_locale_string | Associates a string value for key and locale under group_name.
g_key_file_set_boolean | Associates a new boolean value with key under group_name.
g_key_file_set_integer | Associates a new integer value with key under group_name.
g_key_file_set_string_list | Associates a list of string values for key under group_name.
g_key_file_set_locale_string_list | Associates a list of string values for key and locale under group_name.
g_key_file_set_boolean_list | Associates a list of boolean values with key under group_name.
g_key_file_set_integer_list | Associates a list of integer values with key under group_name.
g_key_file_set_comment | Places a comment above key from group_name. group_name.
g_key_file_remove_group | Removes the specified group, group_name, from the key file.
g_key_file_remove_key | Removes the specified group, group_name, from the key file.
g_key_file_remove_comment | Removes a comment above key from group_name. group_name.

Give feedback of this article

Lexical Scanner

Function | Description
GScanner | The data structure representing a lexical scanner.
g_scanner_new | Creates a new GScanner.
GScannerConfig | Specifies the GScanner settings.
g_scanner_input_file | Prepares to scan a file.
g_scanner_sync_file_offset | Rewinds the filedescriptor to the current buffer position and blows the file read ahead buffer.
g_scanner_input_text | Prepares to scan a text buffer.
g_scanner_peek_next_token | Gets the next token, without removing it from the input stream.
g_scanner_get_next_token | Gets the next token, removing it from the input stream.
g_scanner_cur_line | Gets the current line in the input stream (counting from 1).
g_scanner_cur_position | Gets the current position in the current line (counting from 0).
g_scanner_cur_token | Gets the current token type.
g_scanner_cur_value | Gets the current token value.
g_scanner_eof | Returns TRUE if the scanner has reached the end of the file or text buffer.
g_scanner_set_scope | Sets the current scope.
g_scanner_scope_add_symbol | Adds a symbol to the given scope.
g_scanner_scope_foreach_symbol | Calls the given function for each of the symbol/value pairs in the given scope of the GScanner.
g_scanner_scope_lookup_symbol | Looks up a symbol in a scope and return its value.
g_scanner_scope_remove_symbol | Removes a symbol from a scope.
g_scanner_freeze_symbol_table | Has been deprecated since version 2.2 and should not be used in newly-written code. This macro does nothing.
g_scanner_thaw_symbol_table | Has been deprecated since version 2.2 and should not be used in newly-written code. This macro does nothing.
g_scanner_lookup_symbol | Looks up a symbol in the current scope and return its value.
g_scanner_warn | Outputs a warning message, via the GScanner message handler.
g_scanner_error | Outputs an error message, via the GScanner message handler.
g_scanner_unexp_token | Outputs a message through the scanner's msg_handler, resulting from an unexpected token in the input stream.
GScannerMsgFunc | Specifies the type of the message handler function.
g_scanner_destroy | Frees all memory used by the GScanner.
GTokenType | The possible types of token returned from each g_scanner_get_next_token() call.
GTokenValue | A union holding the value of the token.
GErrorType | The possible errors, used in the v_error field of GTokenValue, when the token is a G_TOKEN_ERROR.
G_CSET_a_2_z | Used for specifying valid identifier characters in GScannerConfig.
G_CSET_A_2_Z | Used for specifying valid identifier characters in GScannerConfig.
G_CSET_DIGITS | Used for specifying valid identifier characters in GScannerConfig.
G_CSET_LATINC | Used for specifying valid identifier characters in GScannerConfig.
G_CSET_LATINS | Used for specifying valid identifier characters in GScannerConfig.
g_scanner_add_symbol | Adds a symbol to the default scope.
g_scanner_remove_symbol | Removes a symbol from the default scope.
g_scanner_foreach_symbol | Calls a function for each symbol in the default scope.

Give feedback of this article

Limits of Basic Type

Function | Description
G_MININT | The minimum value which can be held in a gint.
G_MAXINT | The maximum value which can be held in a gint.
G_MAXUINT | The maximum value which can be held in a guint.
G_MINSHORT | The minimum value which can be held in a gshort.
G_MAXSHORT | The maximum value which can be held in a gshort.
G_MAXUSHORT | The maximum value which can be held in a gushort.
G_MINLONG | The minimum value which can be held in a glong.
G_MAXLONG | The maximum value which can be held in a glong.
G_MAXULONG | The maximum value which can be held in a gulong.
G_MININT8 | The minimum value which can be held in a gint8.
G_MAXINT8 | The maximum value which can be held in a gint8.
G_MAXUINT8 | The maximum value which can be held in a guint8.
G_MININT16 | The minimum value which can be held in a gint16.
G_MAXINT16 | The maximum value which can be held in a gint16.
G_MAXUINT16 | The maximum value which can be held in a guint16.
G_MININT32 | The minimum value which can be held in a gint32.
G_MAXINT32 | The maximum value which can be held in a gint32.
G_MAXUINT32 | The maximum value which can be held in a guint32.
G_MININT64 | The minimum value which can be held in a gint64.
G_MAXINT64 | The maximum value which can be held in a gint64.
G_MAXUINT64 | The maximum value which can be held in a guint64.
G_MAXSIZE | The maximum value which can be held in a gsize.
G_MINFLOAT | The minimum positive value which can be held in a gfloat.
G_MAXFLOAT | The maximum value which can be held in a gfloat.
G_MINDOUBLE | The minimum positive value which can be held in a gdouble.
G_MAXDOUBLE | The maximum value which can be held in a gdouble.

Give feedback of this article

Memory Allocation

Function | Description
g_new | Allocates n_structs elements of type struct_type.
g_new0 | Allocates n_structs elements of type struct_type, initialized to 0's.
g_renew | Reallocates the memory pointed to by mem, so that it now has space for n_structs elements of type struct_type.
g_try_new | Attempts to allocate n_structs elements of type struct_type, and returns NULL on failure.
g_try_new0 | Attempts to allocate n_structs elements of type struct_type, initialized to 0's, and returns NULL on failure
g_try_renew | Attempts to reallocate the memory pointed to by mem, so that it now has space for n_structs elements of type struct_type, and returns NULL on failure.
g_malloc | Allocates n_bytes bytes of memory.
g_malloc0 | Allocates n_bytes bytes of memory, initialized to 0's.
g_realloc | Reallocates the memory pointed to by mem, so that it now has space for n_bytes bytes of memory.
g_try_malloc | Attempts to allocate n_bytes, and returns NULL on failure.
g_try_malloc0 | Attempts to allocate n_bytes, initialized to 0's, and returns NULL on failure.
g_try_realloc | Attempts to realloc mem to a new size, n_bytes, and returns NULL on failure.
g_free | Frees the memory pointed to by mem. If mem is NULL it simply returns.
g_alloca | Allocates size bytes on the stack; these bytes will be freed when the current stack frame is cleaned up.
g_newa | Wraps g_alloca() in a more typesafe manner.
g_mem_gc_friendly | This variable is TRUE if the G_DEBUG environment variable includes the key gc-friendly.
g_memmove | Copies a block of memory len bytes long, from src to dest.
g_memdup | Allocates byte_size bytes of memory, and copies byte_size bytes into it from mem.
GMemVTable | A set of functions used to perform memory allocation.
g_mem_set_vtable | Sets the GMemVTable to use for memory allocation
g_mem_is_system_malloc | Checks whether the allocator used by g_malloc() is the system's malloc implementation.
glib_mem_profiler_table | A GMemVTable containing profiling variants of the memory allocation functions.
g_mem_profile | Outputs a summary of memory usage.

Give feedback of this article

Memory Allocators

This chapter lists functions of type Memory Allocators, which allocates chunks of memory for GList, GSList and GNode.
Function | Description
GAllocator | The GAllocator struct contains private data.
g_allocator_new | Creates a new GAllocator.
g_allocator_free | Frees all of the memory allocated by the GAllocator.

Give feedback of this article

Memory Chunks

This section lists all the functions belonging to Memory Chunks, which are used to allocate groups of equal-sized chunks of memory.

Function | Description
G_ALLOC_AND_FREE | Specifies the type of a GMemChunk. Used in g_mem_chunk_new() and g_mem_chunk_create() to specify that atoms will be freed individually.
G_ALLOC_ONLY | Specifies the type of a GMemChunk. Used in g_mem_chunk_new() and g_mem_chunk_create() to specify that atoms will never be freed individually.
g_mem_chunk_new | Creates a new GMemChunk.
g_mem_chunk_alloc | Allocates an atom of memory from a GMemChunk.
g_mem_chunk_alloc0 | Allocates an atom of memory from a GMemChunk, setting the memory to 0
g_mem_chunk_free | Frees an atom in a GMemChunk.
g_mem_chunk_destroy | Frees all of the memory allocated for a GMemChunk.
g_mem_chunk_create | A macro for creating a new GMemChunk.
g_chunk_new | A macro to allocate an atom of memory from a GMemChunk.
g_chunk_new0 | A macro to allocate an atom of memory from a GMemChunk. It calls g_mem_chunk_alloc0() and casts the returned atom to a pointer to the given type, avoiding a type cast in the source code.
g_chunk_free | Macro that switches the arguments and calls g_mem_chunk_free().
g_mem_chunk_reset | Resets a GMemChunk to its initial state. It frees all of the currently allocated blocks of memory.
g_mem_chunk_clean | Frees any blocks in a GMemChunk which are no longer being used.
g_blow_chunks | Calls g_mem_chunk_clean() on all GMemChunk objects.
g_mem_chunk_info | Outputs debugging information for all GMemChunk objects currently in use.
g_mem_chunk_print | Outputs the name of the GMemChunk, the number of bytes used, and the number of blocks of memory allocated.

Give feedback of this article

Memory Slices

Function | Description
g_slice_alloc | Allocates a block of memory from the slice allocator.
g_slice_alloc0 | Allocates a block of memory via g_slice_alloc() and initializes the returned memory to 0.
g_slice_free1 | Frees a block of memory.
g_slice_free_chain_with_offset | Frees a linked list of memory blocks of structure type type.
g_slice_new | A convenience macro to allocate a block of memory from the slice allocator.
g_slice_new0 | A convenience macro to allocate a block of memory from the slice allocator and set the memory to 0.
g_slice_free | A convenience macro to free a block of memory that has been allocated from the slice allocator.
g_slice_free_chain | Frees a linked list of memory blocks of structure type type.

Give feedback of this article

Message Logging

Function | Description
G_LOG_DOMAIN | Defines the log domain.
G_LOG_FATAL_MASK | GLib log levels that are considered fatal by default.
G_LOG_LEVEL_USER_SHIFT | Log level shift offset for user defined log levels (0-7 are used by GLib).
GLogFunc | Log level shift offset for user defined log levels (0-7 are used by GLib).
GLogLevelFlags | Flags specifying the level of log messages.
g_log | Logs an error or debugging message.
g_logv | Logs an error or debugging message.
g_message | Logs an error or debugging message.
g_warning | Logs an error or debugging message.
g_critical | Logs a "critical warning" (G_LOG_LEVEL_CRITICAL).
g_error | A convenience function/macro to log an error message.
g_debug | A convenience function/macro to log an error message.
g_log_set_handler | Sets the log handler for a domain and a set of log levels.
g_log_remove_handler | Removes the log handler.
g_log_set_always_fatal | Sets the message levels which are always fatal, in any log domain.
g_log_set_fatal_mask | Sets the log levels which are fatal in the given domain.
g_log_default_handler | The default log handler set up by GLib
g_log_set_default_handler | Installs a default log handler which is used is used if no log handler has been set for the particular log domain and log level combination.

Give feedback of this article

Message Output and Debugging

Function | Description
g_print | Outputs a formatted message via the print handler.
g_set_print_handler | Outputs a formatted message via the print handler.
GPrintFunc | Outputs a formatted message via the print handler.
g_printerr | Outputs a formatted message via the error message handler.
g_set_printerr_handler | Sets the handler for printing error messages.
g_return_if_fail | Returns from the current function if the expression is not true.
g_return_val_if_fail | Returns from the current function if the expression is not true.
g_return_val_if_fail | Returns from the current function if the expression is not true.
g_return_val_if_reached | Returns from the current function if the expression is not true.
g_assert | Debugging macro to terminate the application if the assertion fails.
g_assert_not_reached | Debugging macro to terminate the application if the assertion fails.
g_on_error_query | Debugging macro to terminate the application if the assertion fails.
g_on_error_stack_trace | Invokes gdb, which attaches to the current process and shows a stack trace.
G_BREAKPOINT | Inserts a breakpoint instruction into the code (on x86 machines only).

Give feedback of this article

Miscellaneous Macros

Function | Description
G_INLINE_FUNC | This macro is used to export function prototypes so they can be linked with an external version when no in-lining is performed.
G_STMT_START | Used within multi-statement macros so that they can be used in places where only one statement is expected by the compiler.
G_STMT_END | Used within multi-statement macros so that they can be used in places where only one statement is expected by the compiler.
G_BEGIN_DECLS | Used (along with G_END_DECLS) to bracket header files.
G_END_DECLS | Used (along with G_BEGIN_DECLS) to bracket header files.
G_N_ELEMENTS | Determines the number of elements in an array.
G_VA_COPY | Portable way to copy va_list variables.
G_STRINGIFY | Accepts a macro or a string and converts it into a string.
G_GNUC_EXTENSION | Expands to __extension__ when gcc is used as the compiler.
G_GNUC_CONST | Expands to the GNU C const function attribute if the compiler is gcc.
G_GNUC_PURE | Expands to the GNU C pure function attribute if the compiler is gcc.
G_GNUC_MALLOC | Expands to the GNU C malloc function attribute if the compiler is gcc.
G_GNUC_DEPRECATED | Expands to the GNU C deprecated attribute if the compiler is gcc.
G_GNUC_NORETURN | Expands to the GNU C noreturn function attribute if the compiler is gcc.
G_GNUC_UNUSED | Expands to the GNU C unused function attribute if the compiler is gcc.
G_GNUC_PRINTF | Expands to the GNU C format function attribute if the compiler is gcc.
G_GNUC_SCANF | Expands to the GNU C format function attribute if the compiler is gcc.
G_GNUC_FORMAT | Expands to the GNU C format_arg function attribute if the compiler is gcc.
G_GNUC_NULL_TERMINATED | Expands to the GNU C sentinel function attribute if the compiler is gcc, or "" if it isn't.
G_GNUC_WARN_UNUSED_RESULT | Expands to the GNU C warn_unused_ersult function attribute if the compiler is gcc, or "" if it isn't.
G_GNUC_FUNCTION | Expands to the GNU C __FUNCTION__ variable if the compiler is gcc, or "" if it isn't.
G_GNUC_PRETTY_FUNCTION | Expands to the GNU C __PRETTY_FUNCTION__ variable if the compiler is gcc, or "" if it isn't.
G_GNUC_NO_INSTRUMENT | Expands to the GNU C no_instrument_function function attribute if the compiler is gcc.
G_HAVE_GNUC_VISIBILITY | This macro is defined as 1 if the compiler supports ELF visibility attributes (currently only gcc).
G_GNUC_INTERNAL | Expands to the GNU C visibility(hidden) attribute if the compiler supports it (currently only gcc).
G_LIKELY | Hints the compiler that the expression is likely to evaluate to a true value. The compiler may use this information for optimizations.
G_UNLIKELY | Hints the compiler that the expression is unlikely to evaluate to a true value. The compiler may use this information for optimizations.
G_STRLOC | Expands to a string identifying the current code position.
G_STRFUNC | Expands to a string identifying the current function.
G_GINT16_MODIFIER | The platform dependent length modifier for constructing printf() conversion specifiers for values of type gint16 or guint16.
G_GINT16_FORMAT | This is the platform dependent conversion specifier for scanning and printing values of type gint16.
G_GUINT16_FORMAT | This is the platform dependent conversion specifier for scanning and printing values of type guint16.
G_GINT32_MODIFIER | The platform dependent length modifier for constructing printf() conversion specifiers for values of type gint32 or guint32.
G_GINT32_FORMAT | This is the platform dependent conversion specifier for scanning and printing values of type gint32.
G_GUINT32_FORMAT | This is the platform dependent conversion specifier for scanning and printing values of type guint32.
G_GINT64_MODIFIER | The platform dependent length modifier for constructing printf() conversion specifiers for values of type gint64 or guint64.
G_GINT64_FORMAT | This is the platform dependent conversion specifier for scanning and printing values of type gint64.
G_GUINT64_FORMAT | This is the platform dependent conversion specifier for scanning and printing values of type guint64.
G_GSIZE_MODIFIER | The platform dependent length modifier for constructing printf() conversion specifiers for values of type gsize or gssize.
G_GSIZE_FORMAT | This is the platform dependent conversion specifier for scanning and printing values of type gsize.
G_GSSIZE_FORMAT | This is the platform dependent conversion specifier for scanning and printing values of type gssize.

Give feedback of this article

Miscellaneous Utility Functions

Function | Description
g_get_application_name | Gets a human-readable name for the application, as set by g_set_application_name().
g_set_application_name | Sets a human-readable name for the application. This name should be localized if possible, and is intended for display to the user.
g_get_prgname | Gets the name of the program. This name should not be localized, contrast with g_get_application_name().
g_set_prgname | Sets the name of the program. This name should not be localized, contrast with g_set_application_name().
g_getenv | Returns the value of an environment variable.
g_setenv | Sets an environment variable.
g_unsetenv | Removes an environment variable from the environment.
g_listenv | Gets the names of all variables set in the environment.
g_get_user_name | Gets the user name of the current user.
g_get_real_name | Gets the real name of the user.
g_get_user_cache_dir | Returns a base directory in which to store non-essential, cached data specific to particular user.
g_get_user_data_dir | Returns a base directory in which to access application data such as icons that is customized for a particular user.
g_get_user_config_dir | Returns a base directory in which to store user-specific application configuration information such as user preferences and settings.
g_get_system_data_dirs | Returns an ordered list of base directories in which to access system-wide application data.
g_get_system_config_dirs | Returns an ordered list of base directories in which to access system-wide configuration information.
g_get_host_name | Return a name for the machine.
g_get_home_dir | Gets the current user's home directory.
g_get_tmp_dir | Gets the directory to use for temporary files.
g_get_current_dir | Gets the current directory.
g_basename | Gets the name of the file without any leading directory components. It returns a pointer into the given file name string.
g_dirname | This function is deprecated and will be removed in the next major release of GLib. Use g_path_get_dirname() instead.
g_path_is_absolute | Returns TRUE if the given file_name is an absolute file name, i.e. it contains a full path from the root directory such as "/usr/local" on UNIX or "C:\windows" on Windows systems.
g_path_skip_root | Returns a pointer into file_name after the root component, i.e. after the "/" in UNIX or "C:\" under Windows. If file_name is not an absolute path it returns NULL.
g_path_get_basename | Gets the last component of the filename. If file_name ends with a directory separator it gets the component before the last slash.
g_path_get_dirname | Gets the directory components of a file name. If the file name has no directory components "." is returned. The returned string should be freed when no longer needed.
g_build_filename |
g_build_filenamev | Behaves exactly like g_build_filename(), but takes the path elements as a string array, instead of varargs. This function is mainly meant for language bindings.
g_build_path | Creates a path from a series of elements using separator as the separator between elements.
g_build_pathv | Creates a path from a series of elements using separator as the separator between elements.
g_find_program_in_path | Creates a path from a series of elements using separator as the separator between elements.
g_bit_nth_lsf | Finds the position of the first bit set in mask, searching from (but not including) nth_bit upwards.
g_bit_nth_msf | Find the position of the first bit set in mask, searching from (but not including) nth_bit downwards.
g_bit_storage | Find the position of the first bit set in mask, searching from (but not including) nth_bit downwards.
g_spaced_primes_closest | Gets the smallest prime number from a built-in array of primes which is larger than num.
g_atexit | Gets the smallest prime number from a built-in array of primes which is larger than num.
g_parse_debug_string | Parses a string containing debugging options separated by ':' into a guint containing bit flags.
GDebugKey | Associates a string with a bit flag. Used in g_parse_debug_string().
GVoidFunc | Declares a type of function which takes no arguments and has no return value. It is used to specify the type function passed to g_atexit().
GFreeFunc | This is just like the standard C qsort() function, but the comparison routine accepts a user data argument.
g_qsort_with_data | This is just like the standard C qsort() function, but the comparison routine accepts a user data argument.
g_nullify_pointer | Set the pointer at the specified location to NULL.

Give feedback of this article

N-ary Trees

This chapter lists the functions of N-ary Trees category.
Function | Description
GNode | The GNode struct represents one node in a N-ary Tree.
g_node_new | Creates a new GNode containing the given data. Used to create the first node in a tree.
g_node_copy | Recursively copies a GNode.
GCopyFunc | A function of this signature is used to copy the node data when doing a deep-copy of a tree.
g_node_copy_deep | Recursively copies a GNode and its data.
g_node_insert | Inserts a GNode beneath the parent at the given position.
g_node_insert_before | Inserts a GNode beneath the parent before the given sibling.
g_node_insert_after | Inserts a GNode beneath the parent after the given sibling.
g_node_append | Inserts a GNode as the last child of the given parent.
g_node_prepend | Inserts a GNode as the first child of the given parent.
g_node_insert_data | Inserts a new GNode at the given position.
g_node_insert_data_before | Inserts a new GNode before the given sibling.
g_node_append_data | Inserts a new GNode as the last child of the given parent.
g_node_prepend_data | Inserts a new GNode as the first child of the given parent.
g_node_reverse_children | Reverses the order of the children of a GNode.
g_node_traverse | Traverses a tree starting at the given root GNode.
GTraverseFlags | Specifies which nodes are visited during several of the tree functions
GNodeTraverseFunc | Specifies the type of function passed to g_node_traverse().
g_node_children_foreach | Calls a function for each of the children of a GNode.
GNodeForeachFunc | Specifies the type of function passed to g_node_children_foreach().
g_node_get_root | Gets the root of a tree.
g_node_find | Finds a GNode in a tree.
g_node_find_child | Finds the first child of a GNode with the given data.
g_node_child_index | Gets the position of the first child of a GNode which contains the given data.
g_node_child_position | Gets the position of a GNode with respect to its siblings.
g_node_first_child | Gets the first child of a GNode.
g_node_last_child | Gets the last child of aGNode.
g_node_nth_child | Gets a child of a GNode, using the given index.
g_node_first_sibling | Gets the first sibling of a GNode.
g_node_next_sibling | Gets the next sibling of a GNode.
g_node_prev_sibling | Gets the previous sibling of a GNode.
g_node_last_sibling | Gets the last sibling of a GNode.
G_NODE_IS_LEAF | Returns TRUE if a GNode is a leaf node.
G_NODE_IS_ROOT | Returns TRUE if a GNode is the root of a tree.
g_node_depth | Gets the depth of a GNode.
g_node_n_nodes | Gets the number of nodes in a tree.
g_node_n_children | Gets the number of children of a GNode.
g_node_is_ancestor | Returns TRUE if node is an ancestor of descendant.
g_node_max_height | Gets the maximum height of all branches beneath a GNode.
g_node_unlink | Unlinks a GNode from a tree, resulting in two separate trees.
g_node_destroy | Removes the GNode and its children from the tree, freeing any memory allocated.
g_node_push_allocator | Sets the allocator to use to allocate GNode elements.
g_node_pop_allocator | Restores the previous GAllocator, used when allocating GNode elements.

Give feedback of this article

Numerical Definitions

Function | Description
G_IEEE754_FLOAT_BIAS |
G_IEEE754_DOUBLE_BIAS |
GFloatIEEE754 |
GDoubleIEEE754 | The GFloatIEEE754 and GDoubleIEEE754 unions are used to access the sign, mantissa and exponent of IEEE floats and doubles. These unions are defined as appropriate for a given platform.
G_E | The base of natural logarithms.
G_LN2 | The natural logarithm of 2.
G_LN10 | The natural logarithm of 10.
G_PI | The value of pi (ratio of circle's circumference to its diameter).
G_PI_2 | Pi divided by 2.
G_PI_4 | Pi divided by 4.
G_SQRT2 | The square root of two.
G_LOG_2_BASE_10 | Used for manipulating with float formats

Give feedback of this article

Pointer Arrays

This chapter lists Pointer Arrays, which are similar to Arrays but are used only for storing pointers.
Function | Description
GPtrArray | Contains the public fields of a pointer array.
g_ptr_array_new | Creates a new GPtrArray.
g_ptr_array_sized_new | Creates a new GPtrArray with reserved_size pointers preallocated.
g_ptr_array_add | Adds a pointer to the end of the pointer array.
g_ptr_array_remove | Removes the first occurrence of the given pointer from the pointer array.
g_ptr_array_remove_index | Removes the pointer at the given index from the pointer array.
g_ptr_array_remove_fast | Removes the first occurrence of the given pointer from the pointer array.
g_ptr_array_remove_index_fast | Removes the pointer at the given index from the pointer array.
g_ptr_array_remove_range | Removes the given number of pointers starting at the given index from a GPtrArray.
g_ptr_array_sort | Sorts the array, using compare_func
g_ptr_array_sort_with_data | Sorts the array but the comparison function has a user data argument.
g_ptr_array_set_size | Sets the size of the array
g_ptr_array_index | Returns the pointer at the given index of the pointer array.
g_ptr_array_free | Frees all of the memory allocated for the pointer array.
g_ptr_array_foreach | Calls a function for each element of a GPtrArray.

Give feedback of this article

Quarks

This chapter lists functions belonging to the category Quarks, which is a 2-way association between a string and a unique integer identifier.
Function | Description
GQuark | A GQuark is an integer which uniquely identifies a particular string.
g_quark_from_string | Gets the GQuark identifying the given string.
g_quark_from_static_string | Gets the GQuark identifying the given (static) string.
g_quark_to_string | Gets the string associated with the given GQuark.
g_quark_try_string | Gets the GQuark associated with the given string, or 0 if the string has no associated GQuark.

Give feedback of this article

Random Numbers

Function | Description
GRand | The GRand struct is an opaque data structure. It should only be accessed through the g_rand_* functions.
g_rand_new_with_seed | Creates a new random number generator initialized with seed.
g_rand_new_with_seed_array | Creates a new random number generator initialized with seed.
g_rand_new | Creates a new random number generator initialized with a seed taken either from /dev/urandom (if existing) or from the current time (as a fallback).
g_rand_copy | Copies a GRand into a new one with the same exact state as before.
g_rand_free | Frees the memory allocated for the GRand.
g_rand_set_seed | Sets the seed for the random number generator GRand to seed.
g_rand_set_seed_array | Sets the seed for the random number generator GRand to seed.
g_rand_boolean | Returns a random gboolean from rand_.
g_rand_int | Returns the next random guint32 from rand_ equally distributed over the range [0..2^32-1].
g_rand_int_range | Returns the next random gint32 from rand_ equally distributed over the range [begin..end-1].
g_rand_double | Returns the next random gdouble from rand_ equally distributed over the range [0..1).
g_rand_double_range | Returns the next random gdouble from rand_ equally distributed over the range [begin..end).
g_random_set_seed | Sets the seed for the global random number generator, which is used by the g_random_* functions, to seed.
g_random_boolean | Returns a random gboolean. This corresponds to a unbiased coin toss.
g_random_int | Return a random guint32 equally distributed over the range [0..2^32-1].
g_random_int_range | Returns a random gint32 equally distributed over the range [begin..end-1].
g_random_double | Returns a random gdouble equally distributed over the range [0..1).
g_random_double_range | Returns a random gdouble equally distributed over the range [begin..end).

Give feedback of this article

Relations and Tuples

This chapter lists functions of the type Relations and Tuples.
Function | Description
GRelation | The GRelation struct is an opaque data structure to represent a Relation
g_relation_new | Creates a new GRelation with the given number of fields.
g_relation_index | Creates an index on the given field.
g_relation_insert | Inserts a record into a GRelation.
g_relation_exists | Returns TRUE if a record with the given values exists in a GRelation.
g_relation_count | Returns the number of tuples in a GRelation that have the given value in the given field.
g_relation_select | Returns all of the tuples which have the given key in the given field.
g_relation_delete | Deletes any records from a GRelation that have the given key value in the given field.
g_relation_destroy | Destroys the GRelation, freeing all memory allocated.
g_relation_print | Outputs information about all records in a GRelation, as well as the indexes.
GTuples | Used to return records (or tuples) from the GRelation by g_relation_select().
g_tuples_destroy | Frees the records which were returned by g_relation_select().
g_tuples_index | Gets a field from the records returned by g_relation_select().

Give feedback of this article

Shell-related Utilities

Function | Description
GShellError | Error codes returned by shell functions.
G_SHELL_ERROR | Error domain for shell functions.
g_shell_parse_argv | Parses a command line into an argument vector, in much the same way the shell would, but without many of the expansions the shell would perform (variable expansion, globs, operators, filename expansion, etc. are not supported).
g_shell_quote | Quotes a string so that the shell (/bin/sh) will interpret the quoted string to mean unquoted_string.
g_shell_unquote | Unquotes a string as the shell (/bin/sh) would.

Give feedback of this article

Simple XML Subset Parser

Function | Description
GMarkupError | Error codes returned by markup parsing.
G_MARKUP_ERROR | Error domain for markup parsing.
GMarkupParseFlags | There are no flags right now. Pass "0" for the flags argument to all functions.
GMarkupParseContext | A parse context is used to parse a stream of bytes that are expected to contain marked-up text.
GMarkupParser | Any of the fields in GMarkupParser can be NULL, in which case they will be ignored.
g_markup_escape_text | Escapes text so that the markup parser will parse it verbatim. Less than, greater than, ampersand, etc. are replaced with the corresponding entities.
g_markup_printf_escaped | Formats arguments according to format, escaping all string and character arguments in the fashion of g_markup_escape_text().
g_markup_vprintf_escaped | Formats the data in args according to format, escaping all string and character arguments in the fashion of g_markup_escape_text().
g_markup_parse_context_end_parse | Signals to the GMarkupParseContext that all data has been fed into the parse context with g_markup_parse_context_parse().
g_markup_parse_context_free | Frees a GMarkupParseContext. Can't be called from inside one of the GMarkupParser functions.
g_markup_parse_context_get_position | Retrieves the current line number and the number of the character on that line. Intended for use in error messages
g_markup_parse_context_get_element | Retrieves the name of the currently open element.
g_markup_parse_context_new | Creates a new parse context.
g_markup_parse_context_parse | Feed some data to the GMarkupParseContext.

Give feedback of this article

Singly Linked Lists

This section lists functions containing integer values or pointers to data, limited to iterating over the list in one direction.
Function | Description
GSList | The GSList struct is used for each element in the singly-linked list.
g_slist_alloc | Allocates space for one GSList element.
g_slist_append | Adds a new element at the end of the list.
g_slist_prepend | Adds a new element at the start of the list.
g_slist_insert | Inserts a new element into the list at the given position.
g_slist_insert_before | Inserts a node before sibling containing data. Returns the new head of the list.
g_slist_insert_sorted | Inserts a new element to the list, using the given comparison function to determine its position.
g_slist_remove | Removes an element from a GSList.
g_slist_remove_link | Removes an element from a GSList, without freeing the element.
g_slist_delete_link | Deletes a node of list.
g_slist_remove_all | Removes all list nodes with data equal to data.
g_slist_free | Frees all of the memory used by a GSList.
g_slist_free_1 | Frees one GSList element.
g_slist_length | Gets the number of elements in a GSList.
g_slist_copy | Copies a GSList.
g_slist_reverse | Reverses a GSList.
g_slist_sort | Sorts a GSList using the given comparison function.
g_slist_sort_with_data | Sorts a GSList using the given comparison function but the sort function accepts a user data argument.
g_slist_concat | Adds the second GSList to the end of the first GSList.
g_slist_foreach | Calls a function for each element of a GSList.
g_slist_last | Gets the last element in a GSList.
g_slist_next | A macro used to get the next element in a GSList
g_slist_nth | Gets the element at the given position in a GSList.
g_slist_nth_data | Gets the data of the element at the given position.
g_slist_find | Finds the element in a GSList which contains the given data.
g_slist_find_custom | Finds an element in a GSList, using a supplied function to find the desired element.
g_slist_position | Gets the position of the given element in the GSList (starting from 0).
g_slist_index | Gets the position of the element containing the given data (starting from 0).
g_slist_push_allocator | Sets the allocator to use to allocate GSList elements.
g_slist_pop_allocator | Restores the previous GAllocator used when allocating GSList elements.

Give feedback of this article

Spawning Processes

Function | Description
GSpawnError | Error codes returned by spawning processes.
G_SPAWN_ERROR | Error domain for spawning processes.
GSpawnFlags | Flags passed to g_spawn_sync(), g_spawn_async() and g_spawn_async_with_pipes().
GSpawnChildSetupFunc | Specifies the type of the setup function passed to g_spawn_async(), g_spawn_sync() and g_spawn_async_with_pipes().
g_spawn_async_with_pipes | Executes a child program asynchronously (the program will not block waiting for the child to exit).
g_spawn_async | this function simply calls the g_spawn_async_with_pipes() without any pipes.
g_spawn_sync | Executes a child synchronously (waits for the child to exit before returning).
g_spawn_command_line_async | A simple version of g_spawn_async() that parses a command line with g_shell_parse_argv() and passes it to g_spawn_async().
g_spawn_command_line_sync | A simple version of g_spawn_sync() with little-used parameters removed, taking a command line instead of an argument vector.
g_spawn_close_pid | On some platforms, notably WIN32, the GPid type represents a resource which must be closed to prevent resource leaking.

Give feedback of this article

Standard Macros

Function | Description
G_OS_WIN32 | This macro is defined only on Windows.
G_OS_BEOS | This macro is defined only on BeOS.
G_OS_UNIX | This macro is defined only on UNIX.
G_DIR_SEPARATOR | The directory separator character.
G_DIR_SEPARATOR_S | The directory separator as a string.
G_IS_DIR_SEPARATOR | Checks whether a character is a directory separator.
G_SEARCHPATH_SEPARATOR | The search path separator character.
G_SEARCHPATH_SEPARATOR_S | The search path separator as a string.
TRUE | Defines the TRUE value for the gboolean type.
FALSE | Defines the FALSE value for the gboolean type.
NULL | Defines the standard NULL pointer.
MIN | Calculates the minimum of a and b.
MAX | Calculates the maximum of a and b.
ABS | Calculates the absolute value of a.
CLAMP | Ensures that x is between the limits set by low and high.
G_STRUCT_MEMBER | Returns a member of a structure at a given offset, using the given type.
G_STRUCT_MEMBER_P | Returns an untyped pointer to a given offset of a struct.
G_STRUCT_OFFSET | Returns the offset, in bytes, of a member of a struct.
G_MEM_ALIGN | Indicates the number of bytes to which memory will be aligned on the current platform.
G_CONST_RETURN | If G_DISABLE_CONST_RETURNS is defined, this macro expands to nothing. By default, the macro expands to const.

Give feedback of this article

Strings

This section lists functions of string category which are text buffers that grow automatically as text is added.
Function | Description
GString | The GString struct contains the public fields of a GString.
g_string_new | Creates a new GString, initialized with the given string.
g_string_sized_new | Creates a new GString, with enough space for dfl_size bytes.
g_string_assign | Copies the bytes from a string into a GString, destroying any previous contents.
g_string_sprintf | Writes a formatted string into a GString.
g_string_sprintfa | Appends a formatted string to the end of a GString.
g_string_printf | Writes a formatted string into a GString.
g_string_append_printf | Appends a formatted string to the end of a GString.
g_string_append | Adds a string to the end of a GString.
g_string_append_c | Adds a byte to the end of a GString
g_string_append_unichar | Converts a Unicode character into UTF-8, and appends it to the string
g_string_append_len | Appends len bytes of val to string.
g_string_prepend | Adds a string on to the start of a GString.
g_string_prepend_c | Adds a byte to the start of a GString.
g_string_prepend_unichar | Converts a Unicode character into UTF-8, and prepends it to the string
g_string_prepend_len | Prepends len bytes of val to string.
g_string_insert | Inserts a copy of a string into a GString.
g_string_insert_c | Inserts a byte into a GString.
g_string_insert_unichar | Converts a Unicode character into UTF-8, and insert it into the string at the given position.
g_string_insert_len | Inserts len bytes of val into string at pos.
g_string_erase | Removes len bytes from a GString, starting at position pos.
g_string_truncate | Cuts off the end of the GString, leaving the first len bytes.
g_string_set_size | Sets the length of a GString.
g_string_free | Frees the memory allocated for the GString.
g_string_up | Converts a GString to uppercase.
g_string_down | Converts a GString to lowercase.
g_string_hash | Creates a hash code for str; for use with GHashTable.
g_string_equal | Compares two strings for equality, returning TRUE if they are equal.

Give feedback of this article

String Chunks

This chapter lists functions containing integer values or pointers to data, limited to iterating over the list in one direction.
Function | Description
GStringChunk | An opaque data structure representing String Chunks.
g_string_chunk_new | Creates a new GStringChunk.
g_string_chunk_insert | Adds a copy of string to the GStringChunk.
g_string_chunk_insert_const | Adds a copy of string to the GStringChunk, unless the same string has already been added to the GStringChunk with g_string_chunk_insert_const().
g_string_chunk_insert_len | Adds a copy of the first len bytes of string to the GStringChunk.
g_string_chunk_free | Frees all memory allocated by the GStringChunk.

Give feedback of this article

String Utility Functions

Function | Description
g_strdup | Duplicates a string.
g_strndup | Duplicates the first n characters of a string, returning a newly-allocated buffer n + 1 characters long which will always be null-terminated.
g_strdupv | Copies NULL-terminated array of strings.
g_strnfill | Creates a new string length characters long filled with fill_char.
g_stpcpy | Copies a null-terminated string into the dest buffer, include the trailing null, and return a pointer to the trailing null byte.
g_strstr_len | Searches the string haystack for the first occurrence of the string needle, limiting the length of the search to haystack_len.
g_strrstr | Searches the string haystack for the last occurrence of the string needle.
g_strrstr_len | Searches the string haystack for the last occurrence of the string needle, limiting the length of the search to haystack_len.
g_str_has_prefix | Looks whether the string str begins with prefix.
g_str_has_suffix | Looks whether the string str ends with suffix.
g_strlcpy | Portability wrapper that calls strlcpy() on systems which have it, and emulates strlcpy() otherwise.
g_strlcat | Appends null-terminated src string to dest.
g_strdup_printf | Similar to the standard C sprintf() function but safer, since it calculates the maximum space required and allocates memory to hold the result.
g_strdup_vprintf | Similar to the standard C vsprintf() function but safer, since it calculates the maximum space required and allocates memory to hold the result. The returned string should be freed when no longer needed.
g_printf | Similar to the standard C vsprintf() function but safer, since it calculates the maximum space required and allocates memory to hold the result. The returned string should be freed when no longer needed.
g_vprintf | An implementation of the standard vprintf() function which supports positional parameters, as specified in the Single Unix Specification.
g_fprintf | An implementation of the standard fprintf() function which supports positional parameters, as specified in the Single Unix Specification.
g_vfprintf | An implementation of the standard fprintf() function which supports positional parameters, as specified in the Single Unix Specification.
g_sprintf | An implementation of the standard sprintf() function which supports positional parameters, as specified in the Single Unix Specification.
g_vsprintf | An implementation of the standard vsprintf() function which supports positional parameters, as specified in the Single Unix Specification.
g_snprintf | A safer form of the standard sprintf() function.
g_vsnprintf | A safer form of the standard vsprintf() function.
g_vasprintf | An implementation of the GNU vasprintf() function which supports positional parameters, as specified in the Single Unix Specification.
g_printf_string_upper_bound | Calculates the maximum space needed to store the output of the sprintf() function.
g_ascii_isalnum | Determines whether a character is alphanumeric.
g_ascii_isalpha | Determines whether a character is alphabetic (i.e. a letter).
g_ascii_iscntrl | Determines whether a character is a control character.
g_ascii_isdigit | Determines whether a character is digit (0-9).
g_ascii_isgraph | Determines whether a character is a printing character and not a space.
g_ascii_islower | Determines whether a character is an ASCII lower case letter.
g_ascii_isprint | Determines whether a character is a printing character.
g_ascii_ispunct | Determines whether a character is a punctuation character.
g_ascii_isspace | Determines whether a character is a white-space character.
g_ascii_isupper | Determines whether a character is an ASCII upper case letter.
g_ascii_isupper | Determines whether a character is a hexadecimal-digit character.
g_ascii_digit_value | Determines the numeric value of a character as a decimal digit.
g_ascii_xdigit_value | Determines the numeric value of a character as a hexadecimal digit.
g_ascii_strcasecmp | Compares two strings, ignoring the case of ASCII characters.
g_ascii_strncasecmp | Compare s1 and s2, ignoring the case of ASCII characters and any characters after the first n in each string.
g_ascii_strup | Converts all lower case ASCII letters to upper case ASCII letters.
g_ascii_strdown | Converts all upper case ASCII letters to lower case ASCII letters.
g_ascii_tolower | Convert a character to ASCII lower case.
g_ascii_toupper | Convert a character to ASCII upper case.
g_string_ascii_up | Converts all lower case ASCII letters to upper case ASCII letters.
g_string_ascii_down | Converts all upper case ASCII letters to lower case ASCII letters.
g_strup | Converts a string to upper case.
g_strdown | Converts a string to lower case.
g_strcasecmp | A case-insensitive string comparison, corresponding to the standard strcasecmp() function on platforms which support it.
g_strncasecmp | A case-insensitive string comparison, corresponding to the standard strncasecmp() function on platforms which support it.
g_strreverse | Reverses all of the bytes in a string. For example, g_strreverse ("abcdef") will result in "fedcba".
g_ascii_strtoull | Converts a string to a guint64 value.
G_ASCII_DTOSTR_BUF_SIZE | A good size for a buffer to be passed into g_ascii_dtostr().
g_ascii_strtod | Converts a string to a gdouble value.
g_ascii_dtostr | Converts a gdouble to a string, using the '.' as decimal point.
g_ascii_formatd | Converts a gdouble to a string, using the '.' as decimal point.
g_strtod | Converts a string to a gdouble value. It calls the standard strtod() function to handle the conversion, but if the string is not completely converted it attempts the conversion again with g_ascii_strtod(), and returns the best match.
g_strchug | Removes leading white space from a string, by moving the rest of the characters forward.
g_strchomp | Removes trailing white space from a string.
g_strstrip | Removes leading and trailing white space from a string. See g_strchomp() and g_strchug().
g_strdelimit | Converts any delimiter characters in string to new_delimiter.
G_STR_DELIMITERS | The standard delimiters, used in g_strdelimit().
g_strescape | Escapes the special characters '\b', '\f', '\n', '\r', '\t', '\' and '"' in the string source by inserting a '\' before them.
g_strcompress | Replaces all escaped characters with their one byte equivalent. It does the reverse conversion of g_strescape().
g_strcanon | For each character in string, if the character is not in valid_chars, replaces the character with substitutor.
g_strsplit | Splits a string into a maximum of max_tokens pieces, using the given delimiter.
g_strsplit_set | Splits string into a number of tokens not containing any of the characters in delimiter.
g_strfreev | Frees a NULL-terminated array of strings, and the array itself.
g_strconcat | Concatenates all of the given strings into one long string.
g_strjoin | Joins a number of strings together to form one long string, with the optional separator inserted between each of them.
g_strjoinv | Joins a number of strings together to form one long string, with the optional separator inserted between each of them.
g_strv_length | Returns the length of the given NULL-terminated string array str_array.
g_strerror | Returns a string corresponding to the given error code, e.g. "no such process".
g_strsignal | Returns a string describing the given signal, e.g. "Segmentation fault".

Give feedback of this article

The Main Event Loop

Function | Description
GMainLoop | The GMainLoop struct is an opaque data type representing the main event loop of a GLib or GTK+ application.
g_main_loop_new | Creates a new GMainLoop structure.
g_main_loop_ref | Increases the reference count on a GMainLoop object by one.
g_main_loop_unref | Decreases the reference count on a GMainLoop object by one.
g_main_loop_run | Runs a main loop until g_main_loop_quit() is called on the loop.
g_main_loop_quit | Stops a GMainLoop from running.
g_main_loop_is_running | Checks to see if the main loop is currently being run via g_main_loop_run().
g_main_loop_get_context | Returns the GMainContext of loop.
g_main_new | Creates a new GMainLoop for the default main loop.
g_main_destroy | Frees the memory allocated for the GMainLoop.
g_main_run | Runs a main loop until it stops running.
g_main_quit | Stops the GMainLoop. If g_main_run() was called to run the GMainLoop, it will now return.
g_main_is_running | Checks if the main loop is running.
G_PRIORITY_HIGH | Use this for high priority event sources. It is not used within GLib or GTK+.
G_PRIORITY_DEFAULT | Use this for default priority event sources.
G_PRIORITY_HIGH_IDLE | Use this for high priority idle functions.
G_PRIORITY_DEFAULT_IDLE | Use this for default priority idle functions.
G_PRIORITY_LOW | Use this for very low priority background tasks.
GMainContext | The GMainContext struct is an opaque data type representing a set of sources to be handled in a main loop.
g_main_context_new | Creates a new GMainContext strcuture.
g_main_context_ref | Increases the reference count on a GMainContext object by one.
g_main_context_unref | Decreases the reference count on a GMainContext object by one. If the result is zero, free the context and free all associated memory.
g_main_context_default | Returns the default main context. This is the main context used for main loop functions when a main loop is not explicitly specified.
g_main_context_iteration | Runs a single iteration for the given main loop.
g_main_iteration | Runs a single iteration for the default GMainContext.
g_main_context_pending | Checks if any sources have pending events for the given context.
g_main_pending | Checks if any events are pending for the default GMainContext (i.e. ready to be processed).
g_main_context_find_source_by_id | Finds a GSource given a pair of context and ID.
g_main_context_find_source_by_user_data | Finds a source with the given user data for the callback.
g_main_context_find_source_by_funcs_user_data | Finds a source with the given source functions and user data.
g_main_context_wakeup | If context is currently waiting in a poll(), interrupt the poll(), and continue the iteration process.
g_main_context_acquire | Tries to become the owner of the specified context.
g_main_context_release | Releases ownership of a context previously acquired by this thread with g_main_context_acquire()
g_main_context_is_owner | Determines whether this thread holds the (recursive) ownership of this GMaincontext.
g_main_context_wait | Tries to become the owner of the specified context, as with g_main_context_acquire().
g_main_context_prepare | Prepares to poll sources within a main loop.
g_main_context_query | Determines information necessary to poll this main loop.
g_main_context_check | Passes the results of polling back to the main loop.
g_main_context_dispatch | Dispatches all pending sources.
g_main_context_set_poll_func | Sets the function to use to handle polling of file descriptors.
g_main_context_get_poll_func | Gets the poll function set by g_main_context_set_poll_func().
GPollFunc | Specifies the type of function passed to g_main_context_set_poll_func().
g_main_context_add_poll | Adds a file descriptor to the set of file descriptors polled for this context.
g_main_context_remove_poll | Removes file descriptor from the set of file descriptors to be polled for a particular context.
g_main_depth |
g_main_set_poll_func | Sets the function to use for the handle polling of file descriptors for the default main context.
g_timeout_source_new | Creates a new timeout source.
g_timeout_add | Sets a function to be called at regular intervals, with the default priority, G_PRIORITY_DEFAULT.
g_timeout_add_full | Sets a function to be called at regular intervals, with the given priority.
g_idle_source_new | Creates a new idle source.
g_idle_add | Adds a function to be called whenever there are no higher priority events pending to the default main loop.
g_idle_add_full | Adds a function to be called whenever there are no higher priority events pending.
g_idle_remove_by_data | Removes the idle function with the given data.
GPid | A type which is used to hold a process identification.
GChildWatchFunc | The type of functions to be called when a child exists.
g_child_watch_source_new | Creates a new child_watch source.
g_child_watch_add | Sets a function to be called when the child indicated by pid exits, at a default priority, G_PRIORITY_DEFAULT.
g_child_watch_add_full | Sets a function to be called when the child indicated by pid exits, at a default priority, G_PRIORITY_DEFAULT.
GPollFD | Defines typedef structure.
GSource | The GSource struct is an opaque data type representing an event source.
GSourceDummyMarshal | This is just a placeholder for GClosureMarshal, which cannot be used here for dependency reasons.
GSourceFuncs | The GSourceFuncs struct contains a table of functions used to handle event sources in a generic manner.
GSourceCallbackFuncs | The GSourceCallbackFuncs struct contains functions for managing callback objects.
g_source_new | Creates a new GSource structure.
g_source_ref | Increases the reference count on a source by one.
g_source_unref | Decreases the reference count of a source by one.
g_source_attach | Adds a GSource to a context so that it will be executed within that context.
g_source_destroy | Removes a source from its GMainContext, if any, and mark it as destroyed.
g_source_set_priority | Sets the priority of a source.
g_source_get_priority | Gets the priority of a source.
g_source_set_can_recurse | Sets whether a source can be called recursively.
g_source_get_can_recurse | Checks whether a source is allowed to be called recursively.
g_source_get_id | Returns the numeric ID for a particular source.
g_source_get_context | Gets the GMainContext with which the source is associated.
g_source_set_callback | Sets the callback function for a source.
GSourceFunc | Specifies the type of function passed to g_timeout_add(), g_timeout_add_full(), g_idle_add(), and g_idle_add_full().
g_source_set_callback_indirect | Sets the callback function storing the data as a refcounted callback "object".
g_source_add_poll | Adds a file descriptor to the set of file descriptors polled for this source.
g_source_remove_poll | Removes a file descriptor from the set of file descriptors polled for this source.
g_source_get_current_time | Gets the "current time" to be used when checking this source.
g_source_remove | Removes the source with the given id from the default main context.
g_source_remove_by_funcs_user_data | Removes a source from the default main loop context given the source functions and user data.
g_source_remove_by_user_data | Removes a source from the default main loop context given the user data for the callback.

Give feedback of this article

Threads

Function

Description
G_THREADS_ENABLED | This macro is defined, if GLib was compiled with thread support.
G_THREADS_IMPL_POSIX | This macro is defined, if POSIX style threads are used.
G_THREADS_IMPL_NONE | This macro is defined, if no thread implementation is used.
G_THREAD_ERROR | This macro is defined, if no thread implementation is used
GThreadError | Possible errors of thread related functions.
GThreadFunctions | This function table is used by g_thread_init() to initialize the thread system.
g_thread_init | The use of GLib from more than one thread, must be followed by an initialization to the thread system by calling g_thread_init().
g_thread_supported | This function returns, whether the thread system is initialized or not.
GThreadFunc | Specifies the type of the func functions passed to g_thread_create() or g_thread_create_full().
GThreadPriority | Specifies the priority of a thread.
GThread | The GThread struct represents a running thread.
g_thread_create | This function creates a new thread with the default priority.
g_thread_create_full This function creates a new thread with the priority
priority
.
g_thread_self This function creates a new thread with the priority
priority.
g_thread_join | Waits until thread finishes, i.e. the function func, as given to g_thread_create(), returns or g_thread_exit() is called by thread.
g_thread_set_priority | Waits until thread finishes, i.e. the function func, as given to g_thread_create(), returns or g_thread_exit() is called by thread.
g_thread_yield | Gives way to other threads waiting to be scheduled.
g_thread_exit | Exits the current thread.
g_thread_foreach | Call thread_func on all existing GThread structures.
GMutex | The GMutex struct is an opaque data structure to represent a mutex (mutual exclusion).
g_mutex_new | The GMutex struct is an opaque data structure to represent a mutex (mutual exclusion).
g_mutex_lock | Locks mutex.
g_mutex_trylock | Tries to lock mutex. If mutex is already locked by another thread, it immediately returns FALSE. Otherwise it locks mutex and returns TRUE.
g_mutex_unlock | Unlocks mutex. If another thread is blocked in a g_mutex_lock() call for mutex, it will be woken and can lock mutex itself.
g_mutex_free | Destroys mutex.
GStaticMutex | A GStaticMutex works like a GMutex, but it has one significant advantage. It doesn't need to be created at run-time like a GMutex, but can be defined at compile-time.
G_STATIC_MUTEX_INIT | A GStaticMutex must be initialized with this macro, before it can be used.
g_static_mutex_init | Initializes mutex.
g_static_mutex_lock | Works like g_mutex_lock(), but for a GStaticMutex.
g_static_mutex_trylock | Works like g_mutex_trylock(), but for a GStaticMutex.
g_static_mutex_unlock | Works like g_mutex_unlock(), but for a GStaticMutex.
g_static_mutex_get_mutex | For some operations (like g_cond_wait()) the user must have a GMutex instead of a GStaticMutex.
g_static_mutex_free | Releases all resources allocated to mutex.
G_LOCK_DEFINE | he G_LOCK_* macros provide a convenient interface to GStaticMutex with the advantage that they will expand to nothing in programs compiled against a thread-disabled GLib, saving code and memory.
G_LOCK_DEFINE_STATIC | This works like G_LOCK_DEFINE, but it creates a static object.
G_LOCK_EXTERN | This declares a lock, that is defined with G_LOCK_DEFINE in another module.
G_LOCK | This declares a lock, that is defined with G_LOCK_DEFINE in another module.
G_TRYLOCK | Works like g_mutex_trylock(), but for a lock defined with G_LOCK_DEFINE.
G_UNLOCK | Works like g_mutex_unlock(), but for a lock defined with G_LOCK_DEFINE.
GStaticRecMutex | A GStaticRecMutex works like a GStaticMutex, but it can be locked multiple times by one thread.
G_STATIC_REC_MUTEX_INIT | A GStaticRecMutex must be initialized with this macro, before it can be used.
g_static_rec_mutex_init | A GStaticRecMutex must be initialized with this function, before it can be used.
g_static_rec_mutex_lock | Locks mutex.
g_static_rec_mutex_trylock | Tries to lock mutex.
g_static_rec_mutex_unlock | Unlocks mutex.
g_static_rec_mutex_lock_full () | Works like calling g_static_rec_mutex_lock() for mutex depth times.
g_static_rec_mutex_unlock_full () | Completely unlocks mutex.
g_static_rec_mutex_free () | Releases all resources allocated to a GStaticRecMutex.
GStaticRWLock | The GStaticRWLock struct represents a read-write lock.
G_STATIC_RW_LOCK_INIT | A GStaticRWLock must be initialized with this macro, before it can be used.
g_static_rw_lock_init | A GStaticRWLock must be initialized with this function, before it can be used.
g_static_rw_lock_reader_lock | Locks lock for reading.
g_static_rw_lock_reader_trylock Tries to lock
lock
for reading.
g_static_rw_lock_reader_unlock | Unlocks lock.
g_static_rw_lock_writer_lock | Locks lock for writing.
g_static_rw_lock_writer_trylock () | Tries to lock lock for writing.
g_static_rw_lock_writer_unlock | Unlocks lock.
g_static_rw_lock_free | Releases all resources allocated to lock.
GCond | The GCond struct is an opaque data structure to represent a condition.
g_cond_signal | If threads are waiting for cond, exactly one of them is woken up.
g_cond_new | Creates a new GCond.
g_cond_broadcast | If threads are waiting for cond, all of them are woken up.
g_cond_wait | Waits until this thread is woken up on cond.
g_cond_timed_wait | Waits until this thread is woken up on cond, but not longer than until the time, that is specified by abs_time.
g_cond_free () | Destroys the GCond.
GPrivate | The GPrivate struct is an opaque data structure to represent a thread private data key.
g_private_new | Returns the pointer keyed to private_key for the current thread.
g_private_get | Returns the pointer keyed to private_key for the current thread.
g_private_set | Sets the pointer keyed to private_key for the current thread.
GStaticPrivate | A GStaticPrivate works almost like a GPrivate, but it has one significant advantage. It doesn't need to be created at run-time like a GPrivate, but can be defined at compile-time.
G_STATIC_PRIVATE_INIT | Every GStaticPrivate must be initialized with this macro, before it can be used.
g_static_private_init | Initializes private_key. Alternatively, it can be initialized by G_STATIC_PRIVATE_INIT.
g_static_private_get | Works like g_private_get() only for a GStaticPrivate.
g_static_private_set | The possible stati of a one-time initialization function controlled by a GOnce struct.
g_static_private_free | The possible stati of a one-time initialization function controlled by a GOnce struct.
GOnce | The possible stati of a one-time initialization function controlled by a GOnce struct.
GOnceStatus | The possible stati of a one-time initialization function controlled by a GOnce struct.
G_ONCE_INIT | The first call to this routine by a process with a given GOnce struct calls func with the given argument.
g_once | The first call to this routine by a process with a given GOnce struct calls func with the given argument.

Give feedback of this article

Thread Pools

Function | Description
GThreadPool | The GThreadPool struct represents a thread pool.
g_thread_pool_new | This function creates a new thread pool.
g_thread_pool_push | Inserts data into the list of tasks to be executed by pool.
g_thread_pool_set_max_threads | Sets the maximal allowed number of threads for pool.
g_thread_pool_get_max_threads | Returns the maximal number of threads for pool.
g_thread_pool_get_num_threads | Returns the number of threads currently running in pool.
g_thread_pool_unprocessed | Returns the number of tasks still unprocessed in pool.
g_thread_pool_free | Frees all resources allocated for pool.
g_thread_pool_set_max_unused_threads | Sets the maximal number of unused threads to max_threads.
g_thread_pool_get_max_unused_threads | Returns the maximal allowed number of unused threads.
g_thread_pool_get_num_unused_threads | Returns the number of currently unused threads.
g_thread_pool_stop_unused_threads | Stops all currently unused threads.
g_thread_pool_set_sort_function | Sets the function used to sort the list of tasks
g_thread_pool_set_max_idle_time | This function will set the maximum interval that a thread waiting in the pool for new tasks can be idle for before being stopped.
g_thread_pool_get_max_idle_time | This function will return the maximum interval that a thread will wait in the thread pool for new tasks before being stopped.

Give feedback of this article

Timers

Function | Description
GTimer | Opaque datatype that records a start time.
g_timer_new | Creates a new timer, and starts timing (i.e. g_timer_start() is called implicitly ).
g_timer_start | Marks a start time, so that future calls to g_timer_elapsed() will report the time since g_timer_start() was called.
g_timer_stop | Marks an end time, so calls to g_timer_elapsed() will return the difference between this end time and the start time.
g_timer_continue | Resumes a timer that has previously been stopped with g_timer_stop(). g_timer_stop() must be called before using this function.
g_timer_elapsed | If timer has been started but not stopped, obtains the time since the timer was started.
g_timer_reset | This function is useless; it's fine to call g_timer_start() on an already-started timer to reset the start time, so g_timer_reset() serves no purpose.
g_timer_destroy | Destroys a timer, freeing associated resources.

Give feedback of this article

Trash Stacks

This chapter lists the functions that maintain a stack of unused allocated memory chunks.
Function | Description
GTrashStack | Each piece of memory that is pushed onto the stack is cast to a GTrashStack.
g_trash_stack_push | Pushes a piece of memory onto a GTrashStack.
g_trash_stack_pop | Pops a piece of memory off a GTrashStack.
g_trash_stack_peek | Returns the element at the top of a GTrashStack.
g_trash_stack_height | Returns the height of a GTrashStack.

Give feedback of this article

Type Conversion Macros

Function | Description
GINT_TO_POINTER | Stuffs an integer into a pointer type.
GPOINTER_TO_INT | Extracts an integer from a pointer.
GUINT_TO_POINTER | Stuffs an unsigned integer into a pointer type.
GPOINTER_TO_UINT | Extracts an unsigned integer from a pointer.
GSIZE_TO_POINTER | Stuffs a gsize into a pointer type.
GPOINTER_TO_SIZE | Extracts a gsize from a pointer.

Give feedback of this article

Unicode Manipulation

Function | Description
gunichar | A type which can hold any UCS-4 character code.
gunichar2 | A type which can hold any UTF-16 code point.
g_unichar_validate | Checks whether ch is a valid Unicode character.
g_unichar_isalnum | Determines whether a character is alphanumeric.
g_unichar_isalpha | Determines whether a character is alphabetic (i.e. a letter).
g_unichar_iscntrl | Determines whether a character is a control character.
g_unichar_isdigit | Determines whether a character is numeric (i.e. a digit).
g_unichar_isgraph | Determines whether a character is printable and not a space (returns FALSE for control characters, format characters, and spaces).
g_unichar_islower | Determines whether a character is a lowercase letter.
g_unichar_isprint | Determines whether a character is printable.
g_unichar_ispunct | Determines whether a character is punctuation or a symbol.
g_unichar_isspace | Determines whether a character is a space, tab, or line separator (new line, carriage return, etc.).
g_unichar_isupper | Determines if a character is uppercase.
g_unichar_isxdigit | Determines if a character is a hexadecimal digit.
g_unichar_istitle | Determines if a character is titlecase.
g_unichar_isdefined | Determines if a given character is assigned in the Unicode standard.
g_unichar_iswide | Determines if a character is typically rendered in a double-width cell.
g_unichar_toupper | Converts a character to uppercase.
g_unichar_tolower | Converts a character to lower case.
g_unichar_totitle | Converts a character to the titlecase.
g_unichar_digit_value | Determines the numeric value of a character as a decimal digit.
g_unichar_xdigit_value | Determines the numeric value of a character as a hexadecimal digit.
GUnicodeType | These are the possible character classifications.
g_unichar_type | Classifies a Unicode character by type.
GUnicodeBreakType | These are the possible line break classifications.
g_unichar_break_type | Determines the break type of c. c should be a Unicode character.
g_unicode_canonical_ordering | Determines the break type of c. c should be a Unicode character
g_unicode_canonical_decomposition | Computes the canonical decomposition of a Unicode character.
g_unichar_get_mirror_char | In Unicode, some characters are mirrored. This means that their images are mirrored horizontally in text that is laid out from right to left. For instance, "(" would become its mirror image, ")", in right-to-left text.
g_utf8_next_char | Skips to the next character in a UTF-8 string.
g_utf8_get_char | Converts a sequence of bytes encoded as UTF-8 to a Unicode character.
g_utf8_get_char_validated | Convert a sequence of bytes encoded as UTF-8 to a Unicode character.
g_utf8_offset_to_pointer | Converts from an integer character offset to a pointer to a position within the string.
g_utf8_pointer_to_offset | Converts from a pointer to position within a string to a integer character offset.
g_utf8_prev_char | Finds the previous UTF-8 character in the string before p.
g_utf8_find_next_char | Finds the start of the next UTF-8 character in the string after p.
g_utf8_find_prev_char | Given a position p with a UTF-8 encoded string str, find the start of the previous UTF-8 character starting before p. Returns NULL if no UTF-8 characters are present in str before p .
g_utf8_strlen | Returns the length of the string in characters.
g_utf8_strncpy | Like the standard C strncpy() function, but copies a given number of characters instead of a given number of bytes. The src string must be valid UTF-8 encoded text. (Use g_utf8_validate() on all text before trying to use UTF-8 utility functions with it.)
g_utf8_strchr | Finds the leftmost occurrence of the given Unicode character in a UTF-8 encoded string, while limiting the search to len bytes. If len is -1, allow unbounded search.
g_utf8_strrchr | Find the rightmost occurrence of the given Unicode character in a UTF-8 encoded string, while limiting the search to len bytes. If len is -1, allow unbounded search.
g_utf8_strreverse | Reverses a UTF-8 string. str must be valid UTF-8 encoded text. (Use g_utf8_validate() on all text before trying to use UTF-8 utility functions with it.)
g_utf8_validate | Validates UTF-8 encoded text.
g_utf8_strup | Converts all Unicode characters in the string that have a case to uppercase.
g_utf8_strdown | Converts all Unicode characters in the string that have a case to lowercase.
g_utf8_casefold | Converts a string into a form that is independent of case.
g_utf8_normalize | Converts a string into canonical form, standardizing such issues as whether a character with an accent is represented as a base character and combining accent or as a single pre-composed character.
GNormalizeMode | Defines how a Unicode string is transformed in a canonical form, standardizing such issues as whether a character with an accent is represented as a base character and combining accent or as a single pre-composed character.
g_utf8_collate | Compares two strings for ordering using the linguistically correct rules for the current locale.
g_utf8_collate_key | Converts a string into a collation key that can be compared with other collation keys produced by the same function using strcmp().
g_utf8_collate_key_for_filename | Converts a string into a collation key that can be compared with other collation keys produced by the same function using strcmp().
g_utf8_to_utf16 | Convert a string from UTF-8 to UTF-16. A 0 word will be added to the result after the converted text.
g_utf8_to_ucs4 | Convert a string from UTF-8 to a 32-bit fixed width representation as UCS-4. A trailing 0 will be added to the string after the converted text.
g_utf8_to_ucs4_fast | Convert a string from UTF-8 to a 32-bit fixed width representation as UCS-4, assuming valid UTF-8 input. This function is roughly twice as fast as g_utf8_to_ucs4() but does no error checking on the input.
g_utf16_to_ucs4 | Convert a string from UTF-16 to UCS-4. The result will be terminated with a 0 character.
g_utf16_to_utf8 | Convert a string from UTF-16 to UTF-8. The result will be terminated with a 0 byte.
g_ucs4_to_utf16 | Convert a string from UCS-4 to UTF-16. A 0 character will be added to the result after the converted text.
g_ucs4_to_utf8 | Convert a string from a 32-bit fixed width representation as UCS-4. to UTF-8. The result will be terminated with a 0 byte.
g_unichar_to_utf8 | Converts a single character to UTF-8.

Give feedback of this article

Version Information

This chapter lists functions of type Version Information.

Function | Description
glib_major_version | The major version number of the GLib library.
glib_minor_version | The minor version number of the GLib library.
glib_micro_version | The micro version number of the GLib library.
glib_binary_age | This is the binary age passed to libtool.
glib_interface_age | This is the interface age passed to libtool.
glib_check_version | Checks that the GLib library in use is compatible with the given version.
GLIB_MAJOR_VERSION | The major version number of the GLib library.
GLIB_MINOR_VERSION | The minor version number of the GLib library.
GLIB_MICRO_VERSION | The micro version number of the GLib library.
GLIB_CHECK_VERSION | Checks the version of the GLib library.

Give feedback of this article

©Nokia 2006

Back to top

This material, including documentation and any related computer programs, is protected by copyright controlled by Nokia. All rights are reserved. Copying, including reproducing, storing, adapting or translating, any or all of this material requires the prior written consent of Nokia. This material also contains confidential information, which may not be disclosed to others without the prior written consent of Nokia.

Nokia is a registered trademark of Nokia Corporation. S60 and logo is a trademark of Nokia Corporation. Java and all Java-based marks are trademarks or registered trademarks of Sun Microsystems, Inc. Other company and product names mentioned herein may be trademarks or tradenames of their respective owners.


$title

S60 Open C
glib API Specification

glib API Specification

Table of Contents

Limitations

Limitations

Libglib

  • Process spawning: No parent-child relationship. Some functionalities of g_spawn* APIs are not supported.
  • The API g_alloca() does not allocate memory on stack. Instead, it allocates memory on the heap that must be freed using g_free().

Libgthread

None.

Libgmodule

The g_module_symbol API must pass the ordinal number of the function as string and not the symbol name.

Give feedback of this article

©Nokia 2006

Back to top

This material, including documentation and any related computer programs, is protected by copyright controlled by Nokia. All rights are reserved. Copying, including reproducing, storing, adapting or translating, any or all of this material requires the prior written consent of Nokia. This material also contains confidential information, which may not be disclosed to others without the prior written consent of Nokia.

Nokia is a registered trademark of Nokia Corporation. S60 and logo is a trademark of Nokia Corporation. Java and all Java-based marks are trademarks or registered trademarks of Sun Microsystems, Inc. Other company and product names mentioned herein may be trademarks or tradenames of their respective owners.


$title

S60 Open C
glib API Specification

glib API Specification

Table of Contents

Required Capabilities

Required Capabilities

Libglib

A 3rd-party application does not need any capabilities in order to use the libglib APIs. The following exceptions exist for the GIOChannel APIs:
Capability | Description
NetworkServices | A user capability that grants access to a remote service without any restriction on its physical location. Typically, such a location is unknown to the phone user, and such services may incur cost for the phone user. Voice calls, SMS, and Internet services are good examples of such network services. They are supported by GSM, CDMA, and all IP transport protocols including Bluetooth profiles over IP.
NetworkControl | Grants the right to modify or access network protocol controls. Typically when an action can change the behavior of all existing and future connections, it should be protected by this capability. For example, forcing all existing connections on a specific protocol to be dropped, or changing the priority of a call.
AllFiles | AllFiles capability is needed if file operations require read-write access to any directory under \private or read-only access to any directory under \sys.

Libgthread

Capability

Description
PowerMgmt Grants the right:
  • to kill any process in the system
  • to power off unused peripherals
  • to switch the machine into standby state
  • to wake the machine up
  • to power the machine down completely.
Note that this does not control access to anything that might drain battery power.
ProtServ Grants the right to a server to register with a protected name. Currently, protected names start with a "!" character. The kernel prevents servers without this capability from using such a name, and therefore prevents protected servers from being impersonated.

Libgmodule

A 3rd-arty application does not need any capabilities in order to use libgmodule APIs.

Give feedback of this article

©Nokia 2006

Back to top

This material, including documentation and any related computer programs, is protected by copyright controlled by Nokia. All rights are reserved. Copying, including reproducing, storing, adapting or translating, any or all of this material requires the prior written consent of Nokia. This material also contains confidential information, which may not be disclosed to others without the prior written consent of Nokia.

Nokia is a registered trademark of Nokia Corporation. S60 and logo is a trademark of Nokia Corporation. Java and all Java-based marks are trademarks or registered trademarks of Sun Microsystems, Inc. Other company and product names mentioned herein may be trademarks or tradenames of their respective owners.


GLib Object System - GObject

Overview
Functions
Limitations
Capabilities

© Nokia 2007

Back to top


$title

S60 Open C
gobject API Specification

gobject API Specification

Table of Contents

Overview

Overview

GObject and its lower-level type system, GType, are used by GTK+ and most Gnome libraries to provide:
  • object-oriented C-based APIs.
  • automatic transparent API bindings to other compiled or interpreted languages.

Give feedback of this article

©Nokia 2006

Back to top

This material, including documentation and any related computer programs, is protected by copyright controlled by Nokia. All rights are reserved. Copying, including reproducing, storing, adapting or translating, any or all of this material requires the prior written consent of Nokia. This material also contains confidential information, which may not be disclosed to others without the prior written consent of Nokia.

Nokia is a registered trademark of Nokia Corporation. S60 and logo is a trademark of Nokia Corporation. Java and all Java-based marks are trademarks or registered trademarks of Sun Microsystems, Inc. Other company and product names mentioned herein may be trademarks or tradenames of their respective owners.


$title

S60 Open C
gobject API Specification

gobject API Specification

Table of Contents

API Description
API Categories
GType
GType Plugin
GTypeModule
GObject
Enumeration and Flag
GBoxed
Generic Values
Parameters and Values
Varargs Value Collection
GParamSpec
Signals
Closures
Value arrays

API Description

The functions are categorized as:
  • GType
  • GTypePlugin
  • GTypeModule
  • GObject
  • Enums and Flags
  • GBoxed
  • Generic Values
  • Parameters and Values
  • Varargs Value Collection
  • GParamSpec
  • Signals
  • Closures
  • Value arrays

API Categories

Following is the classification of the functions.

GType

This section lists functions of the GType, which is GLib Runtime type identification and management system.

GType

Function | Description
GType | A numerical value which represents the unique identifier of a registered type.
G_TYPE_FUNDAMENTAL | Returns the fundamental type which is the ancestor of type.
G_TYPE_FUNDAMENTAL_MAX | An integer constant that represents the number of identifiers reserved for types that are assigned at compile-time.
G_TYPE_MAKE_FUNDAMENTAL | Returns the type ID for the fundamental type number x.
G_TYPE_IS_ABSTRACT | Returns TRUE if type is an abstract type.
G_TYPE_IS_DERIVED | Returns TRUE if type is derived from another type.
G_TYPE_IS_FUNDAMENTAL | Returns TRUE if type is a fundamental type.
G_TYPE_IS_VALUE_TYPE | Returns TRUE if type is a value type which can be used for g_value_init().
G_TYPE_HAS_VALUE_TABLE | Returns TRUE if type has a GTypeValueTable.
G_TYPE_IS_CLASSED | Returns TRUE if type is a classed type.
G_TYPE_IS_INSTANTIATABLE | Returns TRUE if type can be instantiated. Instantiation is the process of creating an instance (object) of this type.
G_TYPE_IS_DERIVABLE | Returns TRUE if type is a derivable type.
G_TYPE_IS_DEEP_DERIVABLE | Returns TRUE if type is a deep derivable type.
G_TYPE_IS_INTERFACE | Returns TRUE if type is an interface type.
GTypeInterface | An opaque structure used as the base of all interface types.
GTypeInstance | An opaque structure used as the base of all type instances.
GTypeClass | An opaque structure used as the base of all classes.
GTypeInfo | This structure is used to provide the type system with the information required to initialize and destruct (finalize) a type's class and instances thereof.
GTypeFundamentalInfo | A structure that provides information to the type system which is used specifically for managing fundamental types.
GInterfaceInfo | A structure that provides information to the type system which is used specifically for managing interface types.
GTypeValueTable | The GTypeValueTable provides the functions required by the GValue implementation, to serve as a container for values of a type.
G_TYPE_FROM_INSTANCE | Returns the type identifier from a given instance structure.
G_TYPE_FROM_CLASS | Returns the type identifier from a given class structure.
G_TYPE_FROM_INTERFACE | Returns the type identifier from a given interface structure.
G_TYPE_INSTANCE_GET_CLASS | Returns the class structure of a given instance, casted to a specified anchestor type g_type of the instance.
G_TYPE_INSTANCE_GET_INTERFACE | Returns the interface structure for interface g_type of a given instance.
G_TYPE_INSTANCE_GET_PRIVATE | Gets the private structure for a particular type.
G_TYPE_CHECK_INSTANCE | Returns TRUE if instance is a valid GTypeInstance structure.
G_TYPE_CHECK_INSTANCE_CAST | Checks that instance is an instance of the type identified by g_type and emits a warning if this is not the case.
G_TYPE_CHECK_INSTANCE_TYPE | Returns TRUE if instance is an instance of the type identified by g_type.
G_TYPE_CHECK_CLASS_CAST | Checks that g_class is a class structure of the type identified by g_type and emits a warning if this is not the case.
G_TYPE_CHECK_CLASS_TYPE | Returns TRUE if g_class is a class structure of the type identified by g_type.
G_TYPE_CHECK_VALUE | Returns TRUE if value has been initialized to hold values of a value type.
G_TYPE_CHECK_VALUE_TYPE | Returns TRUE if value has been initialized to hold values of type g_type.
G_TYPE_FLAG_RESERVED_ID_BIT | A bit in the type number that's supposed to be left untouched.
g_type_init | Prior to any use of the type system, g_type_init() has to be called to initialize the type system.
GTypeDebugFlags | The GTypeDebugFlags enumeration values can be passed to g_type_init_with_debug_flags() to trigger debugging messages during runtime.
g_type_init_with_debug_flags | Similar to g_type_init(), but additionally sets debug flags.
g_type_name | Return the corresponding quark of the type IDs name.
g_type_qname | Looksup the type ID from a given type name.
g_type_from_name | Returns the direct parent type of the passed in type.
g_type_parent | Returns the direct parent type of the passed in type.
g_type_depth | Returns the length of the ancestry of the passed in type.
g_type_next_base | Determines the type that is derived directly from root_type .
g_type_is_a | If is_a_type is a derivable type, check whether type is a descendant of is_a_type.
g_type_class_ref | Increments the reference count of the class structure belonging to type.
g_type_class_peek | This function is essentially the same as g_type_class_ref().
g_type_class_peek_static | A more efficient version of g_type_class_peek().
g_type_class_unref | Decrements the reference count of the class structure being passed in.
g_type_class_peek_parent | This function is often needed in class initializers.
g_type_class_add_private | Registers a private structure for a instantiatable type.
g_type_interface_peek | Returns the GTypeInterface structure of an interface to which the passed in class conforms.
g_type_interface_peek_parent | Returns the corresponding GTypeInterface structure of the parent type of the instance type to which g_iface belongs.
g_type_default_interface_ref | Increments the reference count for the interface type g_type, and returns the default interface vtable for the type.
g_type_default_interface_peek | If the interface type g_type is currently in use, returns its default interface vtable.
g_type_default_interface_unref | Decrements the reference count for the type corresponding to the interface default vtable g_iface.
g_type_children | Returns a newly allocated and 0-terminated array of type IDs, listing the child types of type.
g_type_interfaces | Returns a newly allocated and 0-terminated array of type IDs, listing the interface types that type conforms to.
g_type_interface_prerequisites | Returns the prerequisites of an interfaces type.
g_type_set_qdata | Attaches arbitrary data to a type.
g_type_query | Obtains data which has previously been attached to type with g_type_set_qdata().
GTypeQuery | Queries the type system for information about a specific type.
GBaseInitFunc | A structure holding information for a specific type.
GBaseFinalizeFunc | A callback function used by the type system to do base initialization of the class structures of derived types.
GClassInitFunc | A callback function used by the type system to initialize the class of a specific type.
GClassFinalizeFunc | A callback function used by the type system to finalize a class.
GInstanceInitFunc | A callback function used by the type system to initialize a new instance of a type.
GInterfaceInitFunc | A callback function used by the type system to initialize a new interface.
GInterfaceFinalizeFunc | A callback function used by the type system to finalize an interface.
GTypeClassCacheFunc | A callback function which is called when the reference count of a class drops to zero.
GTypeFlags | Bit masks used to check or determine characteristics of a type.
GTypeFundamentalFlags | Bit masks used to check or determine specific characteristics of a fundamental type.
g_type_register_static | Registers type_name as the name of a new static type derived from parent_type.
g_type_register_dynamic | Registers type_name as the name of a new dynamic type derived from parent_type.
g_type_register_fundamental | Registers type_id as the predefined identifier and type_name as the name of a fundamental type.
g_type_add_interface_static | Adds the static interface_type to instantiable_type.
g_type_add_interface_dynamic | Adds the dynamic interface_type to instantiable_type.
g_type_interface_add_prerequisite | Adds prerequisite_type to the list of prerequisites of interface_type.
g_type_get_plugin | Returns the GTypePlugin structure for type or NULL if type does not have a GTypePlugin structure.
g_type_interface_get_plugin | Returns the GTypePlugin structure for the dynamic interface interface_type.
g_type_fundamental_next | Returns the next free fundamental type id which can be used to register a new fundamental type with g_type_register_fundamental().
g_type_fundamental | Internal function, used to extract the fundamental type ID portion.
g_type_create_instance | Creates and initializes an instance of type if type is valid and can be instantiated.
g_type_free_instance | Frees an instance of a type, returning it to the instance pool for the type, if there is one.
g_type_add_class_cache_func | Adds a GTypeClassCacheFunc to be called before the reference count of a class goes from one to zero.
g_type_remove_class_cache_func | Removes a previously installed GTypeClassCacheFunc.
g_type_class_unref_uncached | A variant of g_type_class_unref() for use in GTypeClassCacheFunc implementations.
g_type_add_interface_check | Adds a function to be called after an interface vtable is initialized for any class.
g_type_remove_interface_check | Removes an interface check function added with g_type_add_interface_check().
GTypeInterfaceCheckFunc | A callback called after an interface vtable is initialized.
g_type_value_table_peek | Returns the location of the GTypeValueTable associated with type.
G_DEFINE_TYPE | Macro used for type implementations.
G_DEFINE_TYPE_WITH_CODE | Macro for type implementations. Similar to G_DEFINE_TYPE(), but allows to insert custom code into the *_get_type() function.
G_DEFINE_ABSTRACT_TYPE | A convenience macro for type implementations. Similar to G_DEFINE_TYPE(), but defines an abstract type.
G_DEFINE_ABSTRACT_TYPE_WITH_CODE | A convenience macro for type implementations.
G_IMPLEMENT_INTERFACE | A convenience macro to ease interface addition in the _C_ section of G_DEFINE_TYPE_WITH_CODE() or G_DEFINE_ABSTRACT_TYPE_WITH_CODE().
G_DEFINE_TYPE_EXTENDED | The most general convenience macro for type implementations, on which G_DEFINE_TYPE(), etc are based.
G_TYPE_INVALID | An invalid GType, used as error return value in some functions which return a GType.
G_TYPE_NONE | A fundamental type which is used as a replacement for the C void return type.
G_TYPE_INTERFACE | The fundamental type from which all interfaces are derived.
G_TYPE_CHAR | The fundamental type corresponding to gchar.
G_TYPE_UCHAR | The fundamental type corresponding to guchar.
G_TYPE_BOOLEAN | The fundamental type corresponding to gboolean.
G_TYPE_INT | The fundamental type corresponding to gint.
G_TYPE_UINT | The fundamental type corresponding to guint.
G_TYPE_LONG | The fundamental type corresponding to glong.
G_TYPE_ULONG | The fundamental type corresponding to gulong.
G_TYPE_INT64 | The fundamental type corresponding to gint64.
G_TYPE_UINT64 | The fundamental type corresponding to guint64.
G_TYPE_ENUM | The fundamental type from which all enumeration types are derived.
G_TYPE_FLAGS | The fundamental type from which all flags types are derived.
G_TYPE_FLOAT | The fundamental type corresponding to gfloat.
G_TYPE_DOUBLE | The fundamental type corresponding to gdouble.
G_TYPE_STRING | The fundamental type corresponding to nul-terminated C strings.
G_TYPE_POINTER | The fundamental type corresponding to gpointer.
G_TYPE_BOXED | The fundamental type from which all boxed types are derived.
G_TYPE_PARAM | The fundamental type from which all GParamSpec types are derived.
G_TYPE_OBJECT | The fundamental type for GObject.
G_TYPE_RESERVED_GLIB_FIRST | First fundamental type number to create a new fundamental type id with G_TYPE_MAKE_FUNDAMENTAL() reserved for GLib.
G_TYPE_RESERVED_GLIB_LAST | Last fundamental type number reserved for GLib.
G_TYPE_RESERVED_BSE_FIRST | First fundamental type number to create a new fundamental type id with G_TYPE_MAKE_FUNDAMENTAL() reserved for BSE. .
G_TYPE_RESERVED_BSE_LAST | Last fundamental type number reserved for BSE.
G_TYPE_RESERVED_USER_FIRST | First available fundamental type number to create new fundamental type id with G_TYPE_MAKE_FUNDAMENTAL().

GType Plugin

This section lists functions of GTypePlugin interface, which is used to handle the lifecycle of dynamically loaded types.

GType Plugin

Functions | Description
GTypePlugin | The GTypePlugin typedef is used as a placeholder for objects that implement the GTypePlugin interface.
GTypePluginClass | The GTypePlugin interface is used by the type system in order to handle the lifecycle of dynamically loaded types.
GTypePluginUse | The type of the use_plugin function of GTypePluginClass, which gets called to increase the use count of plugin.
GTypePluginUnuse | The type of the unuse_plugin function of GTypePluginClass.
GTypePluginCompleteTypeInfo | The type of the complete_type_info function of GTypePluginClass.
GTypePluginCompleteInterfaceInfo | The type of the complete_interface_info function of GTypePluginClass.
g_type_plugin_use | Calls the use_plugin function from the GTypePluginClass of plugin.
g_type_plugin_unuse | Calls the unuse_plugin function from the GTypePluginClass of plugin.
g_type_plugin_complete_type_info | Calls the complete_type_info function from the GTypePluginClass of plugin.
g_type_plugin_complete_interface_info | Calls the complete_interface_info function from the GTypePluginClass of plugin.

GTypeModule

This section lists the functions of GTypeModule, which provides a simple implementation of the GTypePlugin interface.

GTypeModule

Functions | Description
GTypeModule | GTypeModule provides a simple implementation of the GTypePlugin interface.
GTypeModuleClass | In order to implement dynamic loading of types based on GTypeModule, the load and unload functions in GTypeModuleClass must be implemented.
g_type_module_use | Increases the use count of aGTypeModule by one.
g_type_module_unuse | Decreases the use count of a GTypeModule by one.
g_type_module_set_name | Sets the name for a GTypeModule.
g_type_module_register_type | Looks up or registers a type that is implemented with a particular type plugin.
g_type_module_add_interface | Registers an additional interface for a type, whose interface lives in the given type plugin.
g_type_module_register_enum | Looks up or registers an enumeration that is implemented with a particular type plugin.
g_type_module_register_flags | Looks up or registers a flags type that is implemented with a particular type plugin.

GObject

This section lists functions of the type GObject.

GObject

Functions | Description
GObject | GObject is the fundamental type providing the common attributes and methods for all object types in GTK+, Pango and other libraries based on GObject.
GObjectClass | The class structure for the GObject type.
GObjectConstructParam | The GObjectConstructParam struct is an auxiliary structure used to hand GParamSpec/GValue pairs to the constructor of a GObjectClass.
GObjectGetPropertyFunc | The type of the get_property function of GObjectClass.
GObjectSetPropertyFunc | The type of the set_property function of GObjectClass.
GObjectFinalizeFunc | The type of the finalize function of GObjectClass.
G_TYPE_IS_OBJECT | Returns a boolean value of FALSE or TRUE indicating whether the passed in type id is a G_TYPE_OBJECT or derived from it.
G_OBJECT | Casts a GObject or derived pointer into a (GObject*) pointer.
G_IS_OBJECT | Checks whether a valid GTypeInstance pointer is of type G_TYPE_OBJECT.
G_OBJECT_CLASS | Casts a derived GObjectClass structure into a GObjectClass structure.
G_IS_OBJECT_CLASS | Checks whether class "is a" valid GObjectClass structure of type G_TYPE_OBJECT or derived.
G_OBJECT_GET_CLASS | Returns the class structure associated to a GObject instance.
G_OBJECT_TYPE | Returns the type id of an object.
G_OBJECT_TYPE_NAME | Returns the name of an object's type.
G_OBJECT_CLASS_TYPE | Returns the type id of a class structure.
G_OBJECT_CLASS_NAME | Returns the name of a class structure's type.
g_object_class_install_property | Installs a new property.
g_object_class_find_property | Looks up the GParamSpec for a property of a class.
g_object_class_list_properties | Returns an array of GParamSpec* for all properties of a class.
g_object_class_override_property | Registers property_id as referring to a property with the name name in a parent class or in an interface implemented by oclass.
g_object_interface_install_property | Adds a property to an interface; this is only useful for interfaces that are added to GObject-derived types.
g_object_interface_find_property | Finds the GParamSpec with the given name for an interface.
g_object_interface_list_properties | Lists the properties of an interface.
g_object_new | Creates a new instance of a GObject subtype and sets its properties.
g_object_newv | Creates a new instance of a GObject subtype and sets its properties.
GParameter | The GParameter struct is an auxiliary structure used to hand parameter name/value pairs to g_object_newv().
g_object_ref | Increases the reference count of object.
g_object_unref | Decreases the reference count if object.
GWeakNotify | A GWeakNotify function can be added to an object as a callback that gets triggered when the object is finalized.
g_object_weak_ref | Adds a weak reference callback to an object.
g_object_weak_unref | Removes a weak reference callback to an object.
g_object_add_weak_pointer | Adds a weak reference from weak_pointer to object to indicate that the pointer located at weak_pointer_location is only valid during the lifetime of object.
g_object_remove_weak_pointer | Removes a weak reference from object that was previously added using g_object_add_weak_pointer().
GToggleNotify | A callback function used for notification when the state of a toggle reference changes.
g_object_add_toggle_ref | Increases the reference count of the object by one and sets a callback to be called when all other references to the object are dropped, or when this is already the last reference to the object and another reference is established.
g_object_remove_toggle_ref | Removes a reference added with g_object_add_toggle_ref().
g_object_connect | Connects multiple signals at once.
g_object_disconnect | Disconnects multiple signals at once.
g_object_set | Sets properties on an object.
g_object_get | Gets properties of an object.
g_object_notify | Emits a "notify" signal for the property property_name on object.
g_object_freeze_notify | Stops emission of "notify" signals on object.
g_object_thaw_notify | Reverts the effect of a previous call to g_object_freeze_notify().
g_object_get_data | Gets a named field from the objects table of associations.
g_object_set_data | Each object carries around a table of associations from strings to pointers.
g_object_set_data_full | Similar to g_object_set_data() except it adds notification for when the association is destroyed
g_object_steal_data | Removes a specified datum from the object's data associations, without invoking the association's destroy handler.
g_object_get_qdata | This function gets back user data pointers stored via g_object_set_qdata().
g_object_set_qdata | This sets an opaque, named pointer on an object.
g_object_set_qdata_full | This function works like g_object_set_qdata(), but in addition, a void (*destroy) (gpointer) function may be specified.
g_object_steal_qdata | This function gets back user data pointers stored via g_object_set_qdata().
g_object_set_property | Sets a property of an object.
g_object_get_property | Gets a property of an object.
g_object_new_valist | Creates a new instance of a GObject subtype and sets its properties.
g_object_set_valist | Sets properties on an object.
g_object_get_valist | Gets properties of an object.
g_object_watch_closure | This function essentially limits the life time of the closure to the life time of the object.
g_object_run_dispose | Releases all references to other objects.
G_OBJECT_WARN_INVALID_PROPERTY_ID | The notify signal is emitted on an object when one of its properties has been changed.

Enumeration and Flag

This section lists the functions of Enumeration and Flag types.

Enumeration and Flag

Functions | Description
GEnumClass | The class of an enumeration type holds information about its possible values.
GFlagsClass | The class of a flags type holds information about its possible values.
G_ENUM_CLASS_TYPE | Returns the type identifier from a given GEnumClass structure.
G_ENUM_CLASS_TYPE_NAME | Returns the static type name from a given GEnumClass structure.
G_TYPE_IS_ENUM | Returns whether type "is a" G_TYPE_ENUM.
G_ENUM_CLASS | Casts a derived GEnumClass structure into a GEnumClass structure.
G_IS_ENUM_CLASS | Checks whether class "is a" valid GEnumClass structure of type G_TYPE_ENUM or derived.
G_TYPE_IS_FLAGS | Returns whether type "is a" G_TYPE_FLAGS.
G_FLAGS_CLASS | Casts a derived GEnumClass structure into a GEnumClass structure.
G_IS_FLAGS_CLASS | Checks whether class "is a" valid GEnumClass structure of type G_TYPE_FLAGS or derived.
G_FLAGS_CLASS_TYPE | Returns the type identifier from a given GEnumClass structure.
G_FLAGS_CLASS_TYPE_NAME | Returns the static type name from a given GEnumClass structure.
GEnumValue | A structure which contains a single enum value, it's name, and it's nickname.
GFlagsValue | A structure which contains a single flags value, it's name, and it's nickname.
g_enum_get_value | Returns the GEnumClass for a value.
g_enum_get_value_by_name | Looks up a GEnumClass by name.
g_enum_get_value_by_nick | Looks up a GEnumClass by nickname.
g_flags_get_first_value | Returns the first GEnumClass which is set in value.
g_flags_get_value_by_name | Looks up a GFlagsValue by name.
g_flags_get_value_by_nick | Looks up a GFlagsValue by nickname.
g_enum_register_static | Registers a new static enumeration type with the name name.
g_flags_register_static | Registers a new static flags type with the name name.
g_enum_complete_type_info | This function is meant to be called from the complete_type_info() function of a GTypePlugin.
g_flags_complete_type_info | This function is meant to be called from the complete_type_info() function of a GTypePlugin.

GBoxed

This section lists functions of the type GBoxed, which is a mechanism to wrap opaque C structures registered by the type system.

GBoxed

Functions | Description
GBoxedCopyFunc | This function is provided by the user and should produce a copy of the passed in boxed structure.
GBoxedFreeFunc | This function is provided by the user and should free the boxed structure passed.
g_boxed_copy | Provide a copy of a boxed structure src_boxed which is of type boxed_type.
g_boxed_free | Free the boxed structure boxed which is of type boxed_type.
g_boxed_type_register_static | This function creates a new G_TYPE_BOXED derived type id for a new boxed type with name name.
g_pointer_type_register_static | Creates a new G_TYPE_POINTER derived type id for a new pointer type with name name.
G_TYPE_DATE | The GType for GDate.
G_TYPE_GSTRING | The GType for GString.
G_TYPE_STRV | The GType for a boxed type holding a NULL-terminated array of strings.
GStrv | C represent-able type name for G_TYPE_STRV.

Generic Values

This section lists functions of the type Generic Values, a polymorphic type that can hold values of any other type.

Generic Values

Functions | Description
G_VALUE_HOLDS | Returns TRUE if value holds (or contains) a value of type.
G_VALUE_TYPE | Returns the type identifier of value.
G_VALUE_TYPE_NAME | Returns the type name of value.
G_TYPE_IS_VALUE | Return whether the passed in type ID can be used for g_value_init().
G_TYPE_IS_VALUE_ABSTRACT | Returns TRUE if type is an abstract value type.
G_IS_VALUE | Returns TRUE if value is a valid and initialized GValue structure.
GValue | An opaque structure used to hold different types of values.
G_TYPE_VALUE | Returns the type ID of the "GValue" type which is a boxed type, used to pass around pointers to GValues.
G_TYPE_VALUE_ARRAY | Returns the type ID of the "GValueArray" type which is a boxed type, used to pass around pointers to GValueArrays.
g_value_init | Initializes value with the default value of type.
g_value_copy | Copies the value of src_value into dest_value.
g_value_reset | Clears the current value in value and resets it to the default value (as if the value had just been initialized).
g_value_unset | Clears the current value in value and "unsets" the type.
g_value_fits_pointer | Determines if value will fit inside the size of a pointer value.
g_value_peek_pointer | Returns the value contents as pointer.
g_value_type_compatible | Returns whether a GValue of type src_type can be copied into a GValue of type dest_type.
g_value_type_transformable | Checks whether g_value_transform() is able to transform values of type src_type into values of type dest_type.
g_value_transform | Tries to cast the contents of src_value into a type appropriate to store in dest_value.
GValueTransform | The type of value transformation functions which can be registered with g_value_register_transform_func().
g_value_register_transform_func | Registers a value transformation function for use in g_value_transform().
g_strdup_value_contents | Return a newly allocated string, which describes the contents of a GValue.

Parameters and Values

This section lists functions of the type Parameters and Values.

Parameters and Values

Functions | Description
G_IS_PARAM_SPEC_BOOLEAN | Returns whether the given GParamSpec is of type G_TYPE_PARAM_BOOLEAN.
G_PARAM_SPEC_BOOLEAN | Casts a GParamSpec instance into a GParamSpecBoolean.
G_VALUE_HOLDS_BOOLEAN | Returns whether the given GValue can hold values of type G_TYPE_BOOLEAN.
G_TYPE_PARAM_BOOLEAN | The GType of GParamSpecBoolean.
GParamSpecBoolean | A GParamSpec derived structure that contains the meta data for boolean properties.
g_param_spec_boolean | Creates a new GParamSpecBoolean instance specifying a G_TYPE_BOOLEAN property.
g_value_set_boolean | Sets the contents of a G_TYPE_BOOLEAN GValue to v_boolean.
g_value_get_boolean | Gets the contents of a G_TYPE_BOOLEAN GValue.
G_IS_PARAM_SPEC_CHAR | Returns whether the given GParamSpec is of type G_TYPE_PARAM_CHAR.
G_PARAM_SPEC_CHAR | Casts a GParamSpec instance into a GParamSpecChar.
G_VALUE_HOLDS_CHAR | Returns whether the given GValue can hold values of type G_TYPE_CHAR.
G_TYPE_PARAM_CHAR | The GType of GParamSpecChar.
GParamSpecChar | A GParamSpec derived structure that contains the meta data for character properties.
g_param_spec_char | Creates a new GParamSpecChar instance specifying a G_TYPE_CHAR property.
g_value_set_char | Sets the contents of a G_TYPE_CHAR GValue to v_char.
g_value_get_char | Gets the contents of a G_TYPE_CHAR GValue.
G_IS_PARAM_SPEC_UCHAR | Returns whether the given GParamSpec is of type G_TYPE_PARAM_UCHAR.
G_PARAM_SPEC_UCHAR | Casts a GParamSpec instance into a GParamSpecUChar.
G_VALUE_HOLDS_UCHAR | Returns whether the given GValue can hold values of type G_TYPE_UCHAR.
G_TYPE_PARAM_UCHAR | The GType of GParamSpecUChar.
GParamSpecUChar | A GParamSpec derived structure that contains the meta data for unsigned character properties.
g_param_spec_uchar | Creates a new GParamSpecUChar instance specifying a G_TYPE_UCHAR property.
g_value_set_uchar | Sets the contents of a G_TYPE_UCHAR GValue to v_uchar.
g_value_get_uchar | Gets the contents of a G_TYPE_UCHAR GValue.
G_IS_PARAM_SPEC_INT | Returns whether the given GParamSpec is of type G_TYPE_PARAM_INT.
G_PARAM_SPEC_INT | Casts a GParamSpec instance into a GParamSpecInt.
G_VALUE_HOLDS_INT | Returns whether the given GValue can hold values of type G_TYPE_INT.
G_TYPE_PARAM_INT | The GType of GParamSpecInt.
GParamSpecInt | A GParamSpec derived structure that contains the meta data for integer properties.
g_param_spec_int | Creates a new GParamSpecInt instance specifying a G_TYPE_INT property.
g_value_set_int | Sets the contents of a G_TYPE_INT GValue to v_int.
g_value_get_int | Gets the contents of a G_TYPE_INT GValue.
G_IS_PARAM_SPEC_UINT | Returns whether the given GParamSpec is of type G_TYPE_PARAM_UINT.
G_PARAM_SPEC_UINT | Casts a GParamSpec instance into a GParamSpecUInt.
G_VALUE_HOLDS_UINT | Returns whether the given GValue can hold values of type G_TYPE_UINT.
G_TYPE_PARAM_UINT | The GType of GParamSpecUInt.
GParamSpecUInt | A GParamSpec derived structure that contains the meta data for unsigned integer properties.
g_param_spec_uint | Creates a new GParamSpecUInt instance specifying a G_TYPE_UINT property.
g_value_set_uint | Sets the contents of a G_TYPE_UINT GValue to v_uint.
g_value_get_uint | Gets the contents of a G_TYPE_UINT GValue.
G_IS_PARAM_SPEC_LONG | Returns whether the given GParamSpec is of type G_TYPE_PARAM_LONG.
G_PARAM_SPEC_LONG | Casts a GParamSpec instance into a GParamSpecLong.
G_VALUE_HOLDS_LONG | Returns whether the given GValue can hold values of type G_TYPE_LONG.
G_TYPE_PARAM_LONG | The GType of GParamSpecLong.
GParamSpecLong | A GParamSpec derived structure that contains the meta data for long integer properties.
g_param_spec_long | Creates a new GParamSpecLong instance specifying a G_TYPE_LONG property.
g_value_set_long | Sets the contents of a G_TYPE_LONG GValue to v_long.
g_value_get_long | Gets the contents of a G_TYPE_LONG GValue.
G_IS_PARAM_SPEC_ULONG | Returns whether the given GParamSpec is of type G_TYPE_PARAM_ULONG.
G_PARAM_SPEC_ULONG | Casts a GParamSpec instance into a GParamSpecULong.
G_VALUE_HOLDS_ULONG | Returns whether the given GValue can hold values of type G_TYPE_ULONG.
G_TYPE_PARAM_ULONG | The GType of GParamSpecULong.
GParamSpecULong | A GParamSpec derived structure that contains the meta data for unsigned long integer properties.
g_param_spec_ulong | Creates a new GParamSpecULong instance specifying a G_TYPE_ULONG property.
g_value_set_ulong | Sets the contents of a G_TYPE_ULONG GValue to v_ulong.
g_value_get_ulong | Gets the contents of a G_TYPE_ULONG GValue.
G_IS_PARAM_SPEC_INT64 | Returns whether the given GParamSpec is of type G_TYPE_PARAM_INT64.
G_PARAM_SPEC_INT64 | Casts a GParamSpec instance into a GParamSpecInt64.
G_VALUE_HOLDS_INT64 | Returns whether the given GValue can hold values of type G_TYPE_INT64.
G_TYPE_PARAM_INT64 | The GType of GParamSpecInt64.
GParamSpecInt64 | A GParamSpec derived structure that contains the meta data for 64bit integer properties.
g_param_spec_int64 | Creates a new GParamSpecInt64 instance specifying a G_TYPE_INT64 property.
g_value_set_int64 | Sets the contents of a G_TYPE_INT64 GValue to v_int64.
g_value_get_int64 | Gets the contents of a G_TYPE_INT64 GValue.
G_IS_PARAM_SPEC_UINT64 | Returns whether the given GParamSpec is of type G_TYPE_PARAM_UINT64.
G_PARAM_SPEC_UINT64 | Casts a GParamSpec instance into a GParamSpecUInt64.
G_VALUE_HOLDS_UINT64 | Returns whether the given GValue can hold values of type G_TYPE_UINT64.
G_TYPE_PARAM_UINT64 | The GType of GParamSpecUInt64.
GParamSpecUInt64 | A GParamSpec derived structure that contains the meta data for unsigned 64bit integer properties.
g_param_spec_uint64 | Creates a new GParamSpecUInt64 instance specifying a G_TYPE_UINT64 property.
g_value_set_uint64 | Sets the contents of a G_TYPE_UINT64 GValue to v_uint64.
g_value_get_uint64 | Gets the contents of a G_TYPE_UINT64 GValue.
G_IS_PARAM_SPEC_FLOAT | Returns whether the given GParamSpec is of type G_TYPE_PARAM_FLOAT.
G_PARAM_SPEC_FLOAT | Casts a GParamSpec instance into a GParamSpecFloat.
G_VALUE_HOLDS_FLOAT | Returns whether the given GValue can hold values of type G_TYPE_FLOAT.
G_TYPE_PARAM_FLOAT | The GType of GParamSpecFloat.
GParamSpecFloat | A GParamSpec derived structure that contains the meta data for float properties.
g_value_set_float | Sets the contents of a G_TYPE_FLOAT GValue to v_float.
g_value_get_float | Gets the contents of a G_TYPE_FLOAT GValue.
G_IS_PARAM_SPEC_DOUBLE | Returns whether the given GParamSpec is of type G_TYPE_PARAM_DOUBLE.
G_PARAM_SPEC_DOUBLE | Casts a GParamSpec instance into a GParamSpecDouble.
G_VALUE_HOLDS_DOUBLE | Returns whether the given GValue can hold values of type G_TYPE_DOUBLE.
G_TYPE_PARAM_DOUBLE | The GType of GParamSpecDouble.
GParamSpecDouble | A GParamSpec derived structure that contains the meta data for double properties.
g_param_spec_double | Creates a new GParamSpecDouble instance specifying a G_TYPE_DOUBLE property.
g_value_set_double | Sets the contents of a G_TYPE_DOUBLE GValue to v_double.
g_value_get_double | Gets the contents of a G_TYPE_DOUBLE GValue.
G_IS_PARAM_SPEC_ENUM | Returns whether the given GParamSpec is of type G_TYPE_PARAM_ENUM.
G_PARAM_SPEC_ENUM | Casts a GParamSpec instance into a GParamSpecEnum.
G_VALUE_HOLDS_ENUM | Returns whether the given GValue can hold values derived from type G_TYPE_ENUM.
G_TYPE_PARAM_ENUM | The GType of GParamSpecEnum.
GParamSpecEnum | A GParamSpec derived structure that contains the meta data for enum properties.
g_param_spec_enum | Creates a new GParamSpecEnum instance specifying a G_TYPE_ENUM property.
g_value_set_enum | Sets the contents of a G_TYPE_ENUM GValue to v_enum.
g_value_get_enum | Gets the contents of a G_TYPE_ENUM GValue.
G_IS_PARAM_SPEC_FLAGS | Returns whether the given GParamSpec is of type G_TYPE_PARAM_FLAGS.
G_PARAM_SPEC_FLAGS | Casts a GParamSpec instance into a GParamSpecFlags.
G_VALUE_HOLDS_FLAGS | Returns whether the given GValue can hold values derived from type G_TYPE_FLAGS.
G_TYPE_PARAM_FLAGS | The GType of GParamSpecFlags.
GParamSpecFlags | A GParamSpec derived structure that contains the meta data for flags properties.
g_param_spec_flags | Creates a new GParamSpecEnum instance specifying a G_TYPE_FLAGS property.
g_value_set_flags | Sets the contents of a G_TYPE_FLAGS GValue to v_flags.
g_value_get_flags | Gets the contents of a G_TYPE_FLAGS GValue.
G_IS_PARAM_SPEC_STRING | Returns whether the given GParamSpec is of type G_TYPE_PARAM_STRING.
G_PARAM_SPEC_STRING | Casts a GParamSpec instance into a GParamSpecString.
G_VALUE_HOLDS_STRING | Returns whether the given GValue can hold values of type G_TYPE_STRING.
G_TYPE_PARAM_STRING | The GType of GParamSpecString.
GParamSpecString | A GParamSpec derived structure that contains the meta data for string properties.
gchararray | C representable type name for G_TYPE_STRING.
g_param_spec_string | Creates a new GParamSpecString instance.
g_value_set_string | Sets the contents of a G_TYPE_STRING GValue to v_string.
g_value_set_static_string | Sets the contents of a G_TYPE_STRING GValue to v_string.
g_value_take_string | Sets the contents of a G_TYPE_STRING GValue to v_string.
g_value_set_string_take_ownership | This is an internal function introduced mainly for C marshallers.
g_value_get_string | Gets the contents of a G_TYPE_STRING GValue.
g_value_dup_string | Gets a copy the contents of a G_TYPE_STRING GValue.

Varargs Value Collection

This section lists functions of the type Varargs Value Collection, which convert varargs to generic values.

Varargs Value Collection

Functions | Description
GTypeCValue | A union holding one collected value.
G_VALUE_COLLECT | Collects a variable argument value from a va_list.
G_VALUE_LCOPY | Collects a value's variable argument locations from a va_list.
G_VALUE_COLLECT_FORMAT_MAX_LENGTH | The maximal number of GTypeCValues which can be collected for a single GValue.

GParamSpec

This section lists functions of the type GParamSpec, which is an object structure that encapsulates the metadata required to specify parameters.

GParamSpec

Functions | Description
G_TYPE_IS_PARAM | Returns whether type "is a" G_TYPE_PARAM.
G_PARAM_SPEC | Casts a derived GParamSpec object into a GParamSpec object.
G_IS_PARAM_SPEC | Checks whether pspec "is a" valid GParamSpec structure of type G_TYPE_PARAM or derived.
G_PARAM_SPEC_CLASS' | Casts a derived GParamSpecClass structure into a GParamSpecClass structure.
G_IS_PARAM_SPEC_CLASS | Checks whether pclass "is a" valid GParamSpecClass structure of type G_TYPE_PARAM or derived.
G_PARAM_SPEC_GET_CLASS | Retrieves the GParamSpecClass of a GParamSpec.
G_PARAM_SPEC_TYPE | Retrieves the GType of this pspec.
G_PARAM_SPEC_TYPE_NAME | Retrieves the GType name of this pspec.
G_PARAM_SPEC_VALUE_TYPE | Retrieves the GType to initialize a GValue for this parameter.
GParamSpec | Metadata for parameter specifications.
GParamSpecClass | The class structure for the GParamSpec type.
GParamFlags | Through the GParamFlags flag values, certain aspects of parameters can be configured.
G_PARAM_READWRITE | GParamFlags value alias for G_PARAM_READABLE | G_PARAM_WRITABLE.
G_PARAM_MASK | Masks containing the bits of GParamSpec flags which are reserved for GLib.
G_PARAM_USER_SHIFT | Minimum shift count to be used for user defined flags, to be stored in GParamSpec flags.
g_param_spec_ref | Increments the reference count of pspec.
g_param_spec_unref | Decrements the reference count of a pspec.
g_param_spec_sink | Convenient function to ref and sink a GParamSpec.
g_param_value_set_default | Sets value to its default value as specified in pspec.
g_param_value_defaults | Checks whether value contains the default value as specified in pspec.
g_param_value_validate | Ensures that the contents of value comply with the specifications set out by pspec.
g_param_value_convert | Transforms src_value into dest_value if possible, and then validates dest_value, in order for it to conform to pspec.
g_param_values_cmp | Compares value1 with value2 according to pspec.
g_param_spec_get_name | Returns the name of a GParamSpec.
g_param_spec_get_nick | Returns the nickname of a GParamSpec.
g_param_spec_get_blurb | Returns the short description of a GParamSpec.
g_param_spec_get_qdata | Sets an opaque, named pointer on a GParamSpec.
g_param_spec_set_qdata | Sets an opaque, named pointer on a GParamSpec.
g_param_spec_set_qdata_full | This function works like g_param_spec_set_qdata().
g_param_spec_steal_qdata | Gets back user data pointers stored via g_param_spec_set_qdata().
g_param_spec_get_redirect_target | If the paramspec redirects operations to another paramspec, returns that paramspec.
g_param_spec_internal | Creates a new GParamSpec instance.
GParamSpecTypeInfo | This structure is used to provide the type system with the information required to initialize and destruct (finalize) a parameter's class and instances thereof.
g_param_type_register_static | Registers name as the name of a new static type derived from G_TYPE_PARAM.
GParamSpecPool | A GParamSpecPool maintains a collection of GParamSpecs which can be quickly accessed by owner and name.
g_param_spec_pool_new | Creates a new GParamSpecPool.
g_param_spec_pool_insert | Inserts a GParamSpec in the pool.
g_param_spec_pool_remove | Removes a GParamSpec from the pool.
g_param_spec_pool_lookup | Looks up a GParamSpec in the pool.
g_param_spec_pool_list | Gets an array of all GParamSpecs owned by owner_type in the pool.
g_param_spec_pool_list_owned | Gets an GList of all GParamSpecs owned by owner_type in the pool.

Signals

This section lists functions of the type Signals, which is a means for customization of object behaviour and a general purpose notification mechanism.

Signals

Functions | Description
GSignalInvocationHint | The GSignalInvocationHint structure is used to pass on additional information to callbacks during a signal emission.
GSignalAccumulator | The signal accumulator is a special callback function that can be used to collect return values of the various callbacks that are called during a signal emission.
GSignalCMarshaller | This is the signature of marshaller functions, required to marshall arrays of parameter values to signal emissions into C language callback invocations.
GSignalEmissionHook | A simple function pointer to get invoked when the signal is emitted.
GSignalFlags | The signal flags are used to specify a signal's behaviour.
GSignalMatchType | The match types specify what g_signal_handlers_block_matched(), g_signal_handlers_unblock_matched() and g_signal_handlers_disconnect_matched() match signals by.
GSignalQuery | A structure holding in-depth information for a specific signal
G_SIGNAL_TYPE_STATIC_SCOPE | This macro flags signal argument types for which the signal system may assume that instances thereof remain persistent across all signal emissions they are used in.
G_SIGNAL_MATCH_MASK | A mask for all GSignalMatchType bits.
G_SIGNAL_FLAGS_MASK | A mask for all GSignalFlags bits.
g_signal_new | Creates a new signal.
g_signal_newv | Creates a new signal.
g_signal_new_valist | Creates a new signal.
g_signal_query | Queries the signal system for in-depth information about a specific signal.
g_signal_lookup | Given the name of the signal and the type of object it connects to, gets the signal's identifying integer.
g_signal_name | Given the signal's identifier, finds its name.
g_signal_list_ids | Lists the signals by id that a certain instance or interface type created.
g_signal_emit | Emits a signal.
g_signal_emit_by_name | Emits a signal.
g_signal_emitv | Emits a signal.
g_signal_emit_valist | Emits a signal.
g_signal_connect | Connects a GCallback function to a signal for a particular object.
g_signal_connect_after | Connects a GCallback function to a signal for a particular object.
g_signal_connect_swapped | This is similar to g_signal_connect_data(), but uses a closure which ensures that the gobject stays alive during the call to c_handler by temporarily adding a reference count to gobject.
g_signal_connect_object | The connection flags are used to specify the behaviour of a signal's connection.
GConnectFlags | Connects a GCallback function to a signal for a particular object.
g_signal_connect_closure | Connects a closure to a signal for a particular object.
g_signal_connect_closure_by_id | Connects a closure to a signal for a particular object.
g_signal_handler_block | Blocks a handler of an instance so it will not be called during any signal emissions unless it is unblocked again.
g_signal_handler_unblock | Undoes the effect of a previous g_signal_handler_block() call.
g_signal_handler_disconnect | Disconnects a handler from an instance so it will not be called during any future or currently ongoing emissions of the signal it has been connected to.
g_signal_handler_find | Finds the first signal handler that matches certain selection criteria.
g_signal_handlers_block_matched | Blocks all handlers on an instance that match a certain selection criteria.
g_signal_handlers_unblock_matched | Unblocks all handlers on an instance that match a certain selection criteria.
g_signal_handlers_disconnect_matched | Disconnects all handlers on an instance that match a certain selection criteria.
g_signal_handler_is_connected | Returns whether handler_id is the id of a handler connected to instance.
g_signal_handlers_block_by_func | Blocks all handlers on an instance that match func and data.
g_signal_handlers_unblock_by_func | Unblocks all handlers on an instance that match func and data.
g_signal_handlers_disconnect_by_func | Disconnects all handlers on an instance that match func and data.
g_signal_has_handler_pending | Returns whether there are any handlers connected to instance for the given signal id and detail.
g_signal_stop_emission | Stops a signal's current emission.
g_signal_stop_emission_by_name | Stops a signal's current emission.
g_signal_override_class_closure | Overrides the class closure.
g_signal_chain_from_overridden | Calls the original class closure of a signal.
g_signal_add_emission_hook | Adds an emission hook for a signal, which will get called for any emission of that signal, independent of the instance.
g_signal_remove_emission_hook | Deletes an emission hook.
g_signal_parse_name | Internal function to parse a signal name into its signal_id and detail quark.
g_signal_get_invocation_hint | Returns the invocation hint of the innermost signal emission of instance.
g_signal_type_cclosure_new | Creates a new closure which invokes the function found at the offset struct_offset in the class structure of the interface or classed type identified by itype.
g_signal_accumulator_true_handled | A predefined GSignalAccumulator for signals that return a boolean values.

Closures

This section lists the functions of the type Closures, which behave as first-class objects.

Closures

Functions | Description
G_CLOSURE_NEEDS_MARSHAL | Returns TRUE if a GClosureMarshal marshaller has not yet been set on closure.
G_CLOSURE_N_NOTIFIERS | Returns the total number of notifiers connected with the closure cl.
G_CCLOSURE_SWAP_DATA | Returns whether the user data of the GCClosure should be passed as the first parameter to the callback.
G_CALLBACK | Casts a function pointer to a GCallback.
GCallback | The type used for callback functions in structure definitions and function signatures.
GClosure | A GClosure represents a callback supplied by the programmer.
G_TYPE_CLOSURE | The GType for GClosure.
GClosureMarshal | The type used for marshaller functions.
GClosureNotify | The type used for the various notification callbacks which can be registered on closures.
g_cclosure_new | Creates a new closure which invokes callback_func with user_data as the last parameter.
g_cclosure_new_swap | Creates a new closure which invokes callback_func with user_data as the first parameter.
g_cclosure_new_object | A variant of g_cclosure_new() which uses object as user_data and calls g_object_watch_closure() on object and the created closure.
g_cclosure_new_object_swap | A variant of g_cclosure_new_swap() which uses object as user_data and calls g_object_watch_closure() on object and the created closure.
g_closure_new_object | A variant of g_closure_new_simple() which stores object in the data field of the closure and calls g_object_watch_closure() on object and the created closure.
g_closure_ref | Increments the reference count on a closure to force it staying alive while the caller holds a pointer to it.
g_closure_sink | Takes over the initial ownership of a closure.
g_closure_unref | Decrements the reference count of a closure after it was previously incremented by the same caller.
g_closure_invoke | Invokes the closure, i.e. executes the callback represented by the closure.
g_closure_invalidate | Sets a flag on the closure to indicate that it's calling environment has become invalid.
g_closure_add_finalize_notifier | Registers a finalization notifier which will be called when the reference count of closure goes down to 0.
g_closure_add_invalidate_notifier | Registers an invalidation notifier which will be called when the closure is invalidated with g_closure_invalidate().
g_closure_remove_finalize_notifier | Removes a finalization notifier. Notifiers are automatically removed after they are run.
g_closure_remove_invalidate_notifier | Removes a invalidation notifier. Notifiers are automatically removed after they are run.
g_closure_new_simple | Allocates a struct of the given size and initializes the initial part as a GClosure.
g_closure_set_marshal | Sets the marshaller of closure. The marshal_data provides a way for a meta marshaller to provide additional information to the marshaller.
g_closure_add_marshal_guards | Adds a pair of notifiers which get invoked before and after the closure callback, respectively.
g_closure_set_meta_marshal | Sets the meta marshaller of closure.
g_source_set_closure | Sets the callback for a source as a GClosure.
G_TYPE_IO_CHANNEL | The GType for GIOChannel.
G_TYPE_IO_CONDITION | The GType for GIOCondition.
g_cclosure_marshal_VOID__VOID | A marshaller for a GCClosure with a callback of type void (*callback) (gpointer instance, gpointer user_data).
g_cclosure_marshal_VOID__BOOLEAN | A marshaller for a GCClosure with a callback of type void (*callback) (gpointer instance, gboolean arg1, gpointer user_data).
g_cclosure_marshal_VOID__CHAR | A marshaller for a GCClosure with a callback of type void (*callback) (gpointer instance, gchar arg1, gpointer user_data).
g_cclosure_marshal_VOID__UCHAR | A marshaller for a GCClosure with a callback of type void (*callback) (gpointer instance, guchar arg1, gpointer user_data).
g_cclosure_marshal_VOID__INT | A marshaller for a GCClosure with a callback of type void (*callback) (gpointer instance, gint arg1, gpointer user_data).
g_cclosure_marshal_VOID__UINT | A marshaller for a GCClosure with a callback of type void (*callback) (gpointer instance, guint arg1, gpointer user_data).
g_cclosure_marshal_VOID__LONG | A marshaller for a GCClosure with a callback of type void (*callback) (gpointer instance, glong arg1, gpointer user_data).
g_cclosure_marshal_VOID__ULONG | A marshaller for a GCClosure with a callback of type void (*callback) (gpointer instance, gulong arg1, gpointer user_data).
g_cclosure_marshal_VOID__ENUM | A marshaller for a GCClosure with a callback of type void (*callback) (gpointer instance, gint arg1, gpointer user_data).
g_cclosure_marshal_VOID__FLAGS | A marshaller for a GCClosure with a callback of type void (*callback) (gpointer instance, gint arg1, gpointer user_data).
g_cclosure_marshal_VOID__FLOAT | A marshaller for a GCClosure with a callback of type void (*callback) (gpointer instance, gfloat arg1, gpointer user_data).
g_cclosure_marshal_VOID__DOUBLE | A marshaller for a GCClosure with a callback of type void (*callback) (gpointer instance, gdouble arg1, gpointer user_data).
g_cclosure_marshal_VOID__STRING | A marshaller for a GCClosure with a callback of type void (*callback) (gpointer instance, const gchar *arg1, gpointer user_data).
g_cclosure_marshal_VOID__PARAM | A marshaller for a GCClosure with a callback of type void (*callback) (gpointer instance, GParamSpec *arg1, gpointer user_data).
g_cclosure_marshal_VOID__BOXED | A marshaller for a GCClosure with a callback of type void (*callback) (gpointer instance, GBoxed *arg1, gpointer user_data).
g_cclosure_marshal_VOID__POINTER | A marshaller for a GCClosure with a callback of type void (*callback) (gpointer instance, gpointer arg1, gpointer user_data).
g_cclosure_marshal_VOID__OBJECT | A marshaller for a GCClosure with a callback of type void (*callback) (gpointer instance, GOBject *arg1, gpointer user_data).
g_cclosure_marshal_STRING__OBJECT_POINTER | A marshaller for a GCClosure with a callback of type void (*callback) (gpointer instance, GObject *arg1, gpointer arg2, gpointer user_data).
g_cclosure_marshal_VOID__UINT_POINTER | A marshaller for a GCClosure with a callback of type void (*callback) (gpointer instance, guint arg1, gpointer arg2, gpointer user_data).
g_cclosure_marshal_BOOLEAN__FLAGS | A marshaller for a GCClosure with a callback of type gboolean (*callback) (gpointer instance, gint arg1, gpointer user_data).
g_cclosure_marshal_BOOL__FLAGS | Another name for g_cclosure_marshal_BOOLEAN__FLAGS()

Value arrays

This section lists functions of the type Value arrays, which are container structure to maintain an array of generic values.

Value arrays

Functions | Description
GValueArray | A GValueArray contains an array of GValue elements.
g_value_array_get_nth | Return a pointer to the value at index_ containd in value_array.
g_value_array_new | Allocates and initializes a new GValueArray, optionally preserves space for n_prealloced elements.
g_value_array_copy | Constructs an exact copy of a GValueArray by duplicating all its contents.
g_value_array_free | Frees a GValueArray including its contents.
g_value_array_append | Inserts a copy of value as last element of value_array.
g_value_array_prepend | Inserts a copy of value as first element of value_array.
g_value_array_insert | Inserts a copy of value at specified position into value_array.
g_value_array_remove | Removes the value at position index_ from value_array.
g_value_array_sort | Sorts value_array using compare_func to compare the elements accoring to the semantics of GCompareFunc.

Give feedback of this article

©Nokia 2006

Back to top

This material, including documentation and any related computer programs, is protected by copyright controlled by Nokia. All rights are reserved. Copying, including reproducing, storing, adapting or translating, any or all of this material requires the prior written consent of Nokia. This material also contains confidential information, which may not be disclosed to others without the prior written consent of Nokia.

Nokia is a registered trademark of Nokia Corporation. S60 and logo is a trademark of Nokia Corporation. Java and all Java-based marks are trademarks or registered trademarks of Sun Microsystems, Inc. Other company and product names mentioned herein may be trademarks or tradenames of their respective owners.


$title

S60 Open C
gobject API Specification

gobject API Specification

Table of Contents

Limitations

Limitations

No known limitations.

Give feedback of this article

©Nokia 2006

Back to top

This material, including documentation and any related computer programs, is protected by copyright controlled by Nokia. All rights are reserved. Copying, including reproducing, storing, adapting or translating, any or all of this material requires the prior written consent of Nokia. This material also contains confidential information, which may not be disclosed to others without the prior written consent of Nokia.

Nokia is a registered trademark of Nokia Corporation. S60 and logo is a trademark of Nokia Corporation. Java and all Java-based marks are trademarks or registered trademarks of Sun Microsystems, Inc. Other company and product names mentioned herein may be trademarks or tradenames of their respective owners.


$title

S60 Open C
gobject API Specification

gobject API Specification

Table of Contents

Required Capabilities

Required Capabilities

A 3rd-party application does not need any capabilities in order to use the libgobject APIs.

Give feedback of this article

©Nokia 2006

Back to top

This material, including documentation and any related computer programs, is protected by copyright controlled by Nokia. All rights are reserved. Copying, including reproducing, storing, adapting or translating, any or all of this material requires the prior written consent of Nokia. This material also contains confidential information, which may not be disclosed to others without the prior written consent of Nokia.

Nokia is a registered trademark of Nokia Corporation. S60 and logo is a trademark of Nokia Corporation. Java and all Java-based marks are trademarks or registered trademarks of Sun Microsystems, Inc. Other company and product names mentioned herein may be trademarks or tradenames of their respective owners.


OpenSSL SSL/TLS Library - libssl

Overview
Functions
Limitations
Capabilities

© Nokia 2007

Back to top


$title

S60 Open C
libssl API Specification

libssl API Specification

Table of Contents

Overview

Overview

The SSL library implements the Secure Sockets Layer (SSL v2/v3), Datagram Transport Layer Security (DTLS v1) and Transport Layer Security (TLS v1) protocols. It provides a rich API which is documented here.

All ssl library APIs are not documented. Further documentation can be found athttp://www.openssl.org/docs/ssl/ssl.html.

Give feedback of this article

©Nokia 2006

Back to top

This material, including documentation and any related computer programs, is protected by copyright controlled by Nokia. All rights are reserved. Copying, including reproducing, storing, adapting or translating, any or all of this material requires the prior written consent of Nokia. This material also contains confidential information, which may not be disclosed to others without the prior written consent of Nokia.

Nokia is a registered trademark of Nokia Corporation. S60 and logo is a trademark of Nokia Corporation. Java and all Java-based marks are trademarks or registered trademarks of Sun Microsystems, Inc. Other company and product names mentioned herein may be trademarks or tradenames of their respective owners.


$title

S60 Open C
libssl API Specification

libssl API Specification

Table of Contents

API Description
API Categories
Dealing with Protocol Methods
Dealing with Ciphers
Dealing with Protocol Contexts
Dealing with Sessions
Dealing with Connections
General Functions

API Description

At first the library must be initialized; see SSL_library_init(). Then an SSL_CTX object is created as a framework to establish TLS/SSL enabled connections (see SSL_CTX_new). Various options regarding certificates, algorithms etc. can be set in this object. When a network connection has been created, it can be assigned to an SSL object. After the SSL object has been created using SSL_new, SSL_set_fd or SSL_set_bio can be used to associate the network connection with the object. Then the TLS/SSL handshake is performed using SSL_accept or SSL_connect respectively. SSL_read and SSL_write are used to read and write data on the TLS/SSL connection. SSL_shutdown can be used to shut down the TLS/SSL connection. The libssl library is arranged into following categories:

  • Dealing with Protocol Methods
  • Dealing with Ciphers
  • Dealing with Protocol Contexts
  • Dealing with Sessions
  • Dealing with Connections
  • General Functions

Note: Some of the SSL functions need more than the default available stack. The recommended stack size is 10K. To set the stack size to 10K add EPOCSTACKSIZE 0x10000 in the MMP file.

API Categories

The application or project that intends to use OPEN SSL must mention the paths as shown below:

SYSTEMINCLUDE   \epoc32\include\stdapis
SYSTEMINCLUDE   \epoc32\include\stdapis\openssl

Currently the ssl library exports 202 API functions. They are documented in the following:

Dealing with Protocol Methods

Here we document the various API functions which deal with the SSL/TLS protocol methods defined in SSL_METHOD structures.

Dealing with Protocol Methods

Function | Description
SSLv2_client_method | Constructor for the SSLv2 SSL_METHOD structure for a dedicated client.
SSLv2_server_method | Constructor for the SSLv2 SSL_METHOD structure for a dedicated server.
SSLv2_method | Constructor for the SSLv2 SSL_METHOD structure for combined client and server.
SSLv3_client_method | Constructor for the SSLv3 SSL_METHOD structure for a dedicated client.
SSLv3_server_method | Constructor for the SSLv3 SSL_METHOD structure for a dedicated server.
SSLv3_method | Constructor for the SSLv3 SSL_METHOD structure for combined client and server.
TLSv1_client_method | Constructor for the TLSv1 SSL_METHOD structure for a dedicated client.
TLSv1_server_method | Constructor for the TLSv1 SSL_METHOD structure for a dedicated server.
TLSv1_method | Constructor for the TLSv1 SSL_METHOD structure for combined client and server.
DTLSv1_method | Constructor for the DTLSv1 SSL_METHOD structure for combined client and server.
DTLSv1_server_method | Constructor for the DTLSv1 SSL_METHOD structure for a dedicated server.
DTLSv1_client_method | Constructor for the DTLSv1 SSL_METHOD structure for a dedicated client.

Dealing with Ciphers

Dealing with Ciphers

Here we document the various API functions which deal with the SSL/TLS ciphers defined in SSL_CIPHER structures.

Function | Description
SSL_CIPHER_description, SSL_CIPHER_get_bits, SSL_CIPHER_get_name, SSL_CIPHER_get_version | Gets SSL_CIPHER properties.

Dealing with Protocol Contexts

Dealing with Protocol Contexts

Here we document the various API functions which deal with the SSL/TLS protocol context defined in the SSL_CTX structure.

Function | Description
SSL_CTX_add_client_CA, SSL_CTX_set_client_CA_list | Sets list of CAs sent to the client when requesting a client certificate.
SSL_CTX_add_extra_chain_cert | Adds certificate to chain.
SSL_CTX_add_session, SSL_CTX_remove_session | Manipulats session cache.
SSL_CTX_check_private_key, SSL_CTX_use_PrivateKey, SSL_CTX_use_PrivateKey_ASN1, SSL_CTX_use_PrivateKey_file, SSL_CTX_use_RSAPrivateKey, SSL_CTX_use_RSAPrivateKey_ASN1, SSL_CTX_use_RSAPrivateKey_file, SSL_CTX_use_certificate, SSL_CTX_use_certificate_ASN1, SSL_CTX_use_certificate_file | Loads certificate and key data.
SSL_CTX_ctrl | Internal handling functions for SSL_CTX and SSL objects.
SSL_CTX_flush_sessions | Removes expired sessions.
SSL_CTX_free | Frees an allocated SSL_CTX object.
SSL_CTX_get_app_data, SSL_CTX_set_app_data |
SSL_CTX_get_cert_store, SSL_CTX_set_cert_store | Manipulates X509 certificate verification storage.
SSL_CTX_get_client_CA_list | Gets list of client CAs.
SSL_CTX_get_client_cert_cb | Handles client certificate callback function.
SSL_CTX_get_ex_data, SSL_CTX_get_ex_new_index, SSL_CTX_set_ex_data | Internal application specific data functions
SSL_CTX_get_info_callback | Handles information callback for SSL connections.
SSL_CTX_get_quiet_shutdown | manipulates shutdown behaviour.
SSL_CTX_get_session_cache_mode | enable/disable session caching.
SSL_CTX_get_timeout, SSL_CTX_set_timeout | Manipulates timeout values for session caching
SSL_CTX_get_verify_callback, SSL_CTX_get_verify_mode | Gets currently set verification parameters.
SSL_CTX_load_verify_locations | Sets default locations for trusted CA certificates.
SSL_CTX_need_tmp_rsa | Handles RSA keys for ephemeral key exchange.
SSL_CTX_new | creates a new SSL_CTX object as framework for TLS/SSL enabled functions
SSL_CTX_sess_accept, SSL_CTX_sess_accept_good, SSL_CTX_sess_accept_renegotiate, SSL_CTX_sess_cache_full, SSL_CTX_sess_cb_hits, SSL_CTX_sess_connect, SSL_CTX_sess_connect_good, SSL_CTX_sess_connect_renegotiate, SSL_CTX_sess_hits, SSL_CTX_sess_misses, SSL_CTX_sess_number, SSL_CTX_sess_timeouts | Obtain session cache statistics.
SSL_CTX_sess_get_cache_size, SSL_CTX_sess_set_cache_size | Manipulates session cache size.
SSL_CTX_sess_get_get_cb, SSL_CTX_sess_get_new_cb, SSL_CTX_sess_get_remove_cb, SSL_CTX_sess_set_get_cb, SSL_CTX_sess_set_new_cb, SSL_CTX_sess_set_remove_cb | provides callback functions for server side external session caching.
SSL_CTX_sessions | access internal session cache.
SSL_CTX_set_cipher_list | chooses list of available SSL_CIPHERs.
SSL_CTX_set_client_cert_cb | Handles client certificate callback function.
SSL_CTX_set_default_passwd_cb | Sets passwd callback for encrypted PEM file handling.
SSL_CTX_set_default_read_ahead |
SSL_CTX_set_default_verify_paths |
SSL_CTX_set_info_callback | Handles information callback for SSL connections.
SSL_CTX_set_msg_callback, SSL_CTX_set_msg_callback_arg | install callback for observing protocol .
SSL_CTX_set_options | Manipulates SSL engine options.
SSL_CTX_set_quiet_shutdown | Manipulates shutdown behaviour.
SSL_CTX_set_session_cache_mode | enable/disable session caching.
SSL_CTX_set_ssl_version | chooses a new TLS/SSL method
SSL_CTX_set_tmp_dh, SSL_CTX_set_tmp_dh_callback | Handles DH keys for ephemeral key exchange.
SSL_CTX_set_tmp_rsa, SSL_CTX_set_tmp_rsa_callback, SSL_set_tmp_rsa_callback | Handles RSA keys for ephemeral key exchange.
SSL_CTX_set_verify | Sets peer certificate verification parameters.
SSL_CTX_callback_ctrl | Internal handling function for SSL_CTX and SSL objects.
SSL_CTXget_verify_depth, SSL_get_verify_depth | Gets currently set verification parameters.
SSL_CTX_set_cert_verify_callback | Sets peer certificate verification procedure.
SSL_CTX_set_default_passwd_cb_userdata | Sets passwd callback for encrypted PEM file handling.
SSL_CTX_set_verify_depth, SSL_set_verify_depth | Sets peer certificate verification parameters.
SSL_CTX_use_certificate_chain_file | Loads certificate and key data.
SSL_CTX_set_session_id_context | Sets context within which session can be reused (server side only).
SSL_CTX_set_generate_session_id | Manipulate generation of SSL session IDs (server only).
SSL_CTX_need_tmp_rsa | Handles RSA keys for ephemeral key exchange.
SSL_CTX_get_options | Manipulates SSL engine options.
SSL_CTX_set_max_cert_list, SSL_CTX_get_max_cert_list | Manipulate allowed for the peer's certificate chain.
SSL_CTX_set_mode, SSL_CTX_get_mode | Manipulate SSL engine mode.

Dealing with Sessions

Dealing with Sessions

Here we document the various API functions which deal with the SSL/TLS sessions defined in the SSL_SESSION structures.

Function | Description
d2i_SSL_SESSION, i2d_SSL_SESSION | Transforms the external ASN1 representation of an SSL/TLS session, stored as binary data at location pp with length length, into an SSL_SESSION object.
SSL_SESSION_cmp |
SSL_SESSION_free | Frees an allocated SSL_SESSION structure.
SSL_SESSION_get_app_data |
SSL_SESSION_get_ex_data, SSL_SESSION_get_ex_new_index, SSL_SESSION_set_ex_data | Internal application specific data functions.
SSL_SESSION_get_time, SSL_SESSION_get_timeout, SSL_SESSION_set_time, SSL_SESSION_set_timeout | Retrieves and manipulates session time and timeout settings.
SSL_SESSION_hash |
SSL_SESSION_new |
SSL_SESSION_print |
SSL_SESSION_print_fp |
SSL_SESSION_set_app_data |

Dealing with Connections

Dealing with Connections

Here we document the various API functions which deal with the SSL/TLS connection defined in the SSL structure.

Function | Description
SSL_accept | Waits for a TLS/SSL client to initiate the TLS/SSL handshake.
SSL_add_dir_cert_subjects_to_stack |
SSL_add_file_cert_subjects_to_stack |
SSL_add_client_CA | Sets list of CAs sent to the client when requesting a client certificate.
SSL_alert_desc_string, SSL_alert_desc_string_long, SSL_alert_type_string, SSL_alert_type_string_long | Gets textual description of alert information.
SSL_check_private_key | Loads certificate and key data.
SSL_clear | Resets ssl to allow another connection.
SSL_clear_num_renegotiations |
SSL_connect | Initiates the TLS/SSL handshake with an TLS/SSL server.
SSL_copy_session_id |
SSL_ctrl | Internal handling functions for SSL_CTX and SSL objects
SSL_do_handshake | Performs a TLS/SSL handshake.
SSL_dup, SSL_dup_CA_list |
SSL_free | Frees an allocated SSL structure.
SSL_get_SSL_CTX | Gets the SSL_CTX from which an SSL is created.
SSL_get_app_data |
SSL_get_certificate |
SSL_get_cipher_list, SSL_get_ciphers | Gets list of available SSL_CIPHERs.
SSL_get_cipher_bits,SSL_get_cipher_name, SSL_get_cipher_version, SSL_get_cipher, SSL_get_current_cipher | Gets SSL_CIPHER of a connection.
SSL_get_client_CA_list | Gets list of client CAs.
SSL_get_default_timeout | Gets default session time-out value.
SSL_get_error | Obtains result code for TLS/SSL I/O operation.
SSL_get_ex_data_X509_STORE_CTX_idx | Gets ex_data index to access SSL structure from X509_STORE_CTX.
SSL_get_ex_new_index, SSL_get_ex_data | internal application specific data functions.
SSL_get_fd | Get file descriptor linked to an SSL object.
SSL_get_info_callback, SSL_set_info_callback | Handles information callback for SSL connections.
SSL_get_peer_cert_chain | Gets the X509 certificate chain of the peer.
SSL_get_peer_certificate | Gets the X509 certificate of the peer.
SSL_get_privatekey |
SSL_get_quiet_shutdown, SSL_set_quiet_shutdown | Manipulates shutdown behaviour.
SSL_get_rbio | Gets BIO linked to an SSL object.
SSL_get_read_ahead |
SSL_get_session | Retrieves TLS/SSL session data.
SSL_get_shared_ciphers |
SSL_get_shutdown, SSL_set_shutdown | Manipulates shutdown state of an SSL connection.
SSL_get_ssl_method | Chooses a new TLS/SSL method.
SSL_get_state |
SSL_get_time, SSL_get_timeout | Retrieves and manipulates session time and timeout settings.
SSL_get_verify_callback, SSL_get_verify_mode | Gets currently set verification parameters.
SSL_get_verify_result | Gets result of peer certificate verification.
SSL_get_version | Gets the protocol version of a connection.
SSL_get_wbio | Gets BIO linked to an SSL object.
SSL_in_accept_init, SSL_in_connect_init, SSL_in_init, SSL_is_init_finished |
SSL_in_before |
SSL_load_client_CA_file | Loads certificate names from file.
SSL_load_error_strings |
SSL_new | Creates a new SSL structure for a connection.
SSL_num_renegotiations, SSL_renegotiate |
SSL_peek |
SSL_pending | Obtain number of readable bytes buffered in an SSL object.
SSL_read | Reads bytes from a TLS/SSL connection.
SSL_rstate_string, SSL_rstate_string_long | Gets textual description of state of an SSL object during read operation.
SSL_session_reused | Queries whether a reused session was negotiated during handshake.
SSL_set_accept_state | Prepares SSL object to work in client or server mode.
SSL_set_app_data |
SSL_set_bio | Connects the SSL object with a BIO.
SSL_set_cipher_list | Chooses list of available SSL_CIPHERs.
SSL_set_client_CA_list | Sets list of CAs sent to the client when requesting a client certificate.
SSL_set_connect_state | Prepares SSL object to work in client or server mode.
SSL_set_ex_data | Internal application specific data functions.
SSL_set_fd | Connects the SSL object with a file descriptor.
SSL_set_msg_callback, SSL_set_msg_callback_arg | Installs callback for observing protocol .
SSL_set_options | Manipulates SSL engine options.
SSL_set_read_ahead |
SSL_set_rfd | Connects the SSL object with a read channel file descriptor.
SSL_set_session | Sets a TLS/SSL session to be used during TLS/SSL connect.
SSL_set_ssl_method | Chooses a new TLS/SSL method.
SSL_set_time, SSL_set_timeout | Retrieve and manipulate session time and timeout settings.
SSL_set_verify | Sets peer certificate verification parameters
SSL_set_verify_result | Overrides result of peer certificate verification.
SSL_set_wfd | Connects the SSL object with a read channel file descriptor.
SSL_shutdown | Shuts down a TLS/SSL connection.
SSL_state |
SSL_state_string, SSL_state_string_long | Gets textual description of state of an SSL object.
SSL_total_renegotiations |
SSL_use_PrivateKey, SSL_use_PrivateKey_ASN1, SSL_use_PrivateKey_file,SSL_use_RSAPrivateKey, SSL_use_RSAPrivateKey_ASN1, SSL_use_RSAPrivateKey_file, SSL_use_certificate, SSL_use_certificate_ASN1, SSL_use_certificate_file | Loads certificate and key data.
SSL_version |
SSL_want,SSL_want_nothing, SSL_want_read, SSL_want_write,SSL_want_x509_lookup | Obtains state information TLS/SSL I/O operation.
SSL_write | Writes num bytes from the buffer buf into the specified ssl connection.
SSL_set_session_id_context | Sets context within which session can be reused (server side only).

General Functions

Function | Description
SSL_COMP_add_compression_method, SSL_add_session, SSL_remove_session | Handles SSL/TLS integrated compression methods.
SSL_callback_ctrl | Internal handling functions for SSL_CTX and SSL objects.
SSL_flush_sessions | Removes expired sessions.
SSL_set_generate_session_id, SSL_has_matching_session_id | Manipulates generation of SSL session IDs (server only.)
SSL_set_max_cert_list,SSL_get_max_cert_list | Manipulates allowed for the peer's certificate chain.
SSL_set_mode, SSL_get_mode | Manipulates SSL engine mode.
SSL_get_msg_callback_arg | Installs callback for observing protocol.
SSL_get_options | Manipulates SSL engine options.
SSL_set_tmp_dh_callback, SSL_set_tmp_dh | Handles DH keys for ephemeral key exchange.
SSL_set_tmp_rsa, SSL_need_tmp_rsa | Handles RSA keys for ephemeral key exchange.
SSL_library_init,OpenSSL_add_ssl_algorithms, SSLeay_add_ssl_algorithms | Initializes SSL library by registering algorithms.

Give feedback of this article

©Nokia 2006

Back to top

This material, including documentation and any related computer programs, is protected by copyright controlled by Nokia. All rights are reserved. Copying, including reproducing, storing, adapting or translating, any or all of this material requires the prior written consent of Nokia. This material also contains confidential information, which may not be disclosed to others without the prior written consent of Nokia.

Nokia is a registered trademark of Nokia Corporation. S60 and logo is a trademark of Nokia Corporation. Java and all Java-based marks are trademarks or registered trademarks of Sun Microsystems, Inc. Other company and product names mentioned herein may be trademarks or tradenames of their respective owners.


$title

S60 Open C
libssl API Specification

libssl API Specification

Table of Contents

Limitations

Limitations

A 3rd-party application does not need any capabilities in order to use the functions of Open SSL/TSL library.

Give feedback of this article

©Nokia 2006

Back to top

This material, including documentation and any related computer programs, is protected by copyright controlled by Nokia. All rights are reserved. Copying, including reproducing, storing, adapting or translating, any or all of this material requires the prior written consent of Nokia. This material also contains confidential information, which may not be disclosed to others without the prior written consent of Nokia.

Nokia is a registered trademark of Nokia Corporation. S60 and logo is a trademark of Nokia Corporation. Java and all Java-based marks are trademarks or registered trademarks of Sun Microsystems, Inc. Other company and product names mentioned herein may be trademarks or tradenames of their respective owners.


$title

S60 Open C
libssl API Specification

libssl API Specification

Table of Contents

Required Capabilities

Required Capabilities

Capability | Description
WriteDeviceData | Grants write access to settings that control the behavior of the device. For example, device lock settings, system time, time zone, alarms, etc.
NetworkServices | A user capability that grants access to a remote service without any restriction on its physical location. Typically, such a location is unknown to the phone user, and such services may incur cost for the phone user. Voice calls, SMS, and Internet services are good examples of such network services. They are supported by GSM, CDMA, and all IP transport protocols including Bluetooth profiles over IP.

Give feedback of this article

©Nokia 2006

Back to top

This material, including documentation and any related computer programs, is protected by copyright controlled by Nokia. All rights are reserved. Copying, including reproducing, storing, adapting or translating, any or all of this material requires the prior written consent of Nokia. This material also contains confidential information, which may not be disclosed to others without the prior written consent of Nokia.

Nokia is a registered trademark of Nokia Corporation. S60 and logo is a trademark of Nokia Corporation. Java and all Java-based marks are trademarks or registered trademarks of Sun Microsystems, Inc. Other company and product names mentioned herein may be trademarks or tradenames of their respective owners.


OpenSSL Cryptographic Library - libcrypto

Overview
Functions
Limitations
Capabilities

© Nokia 2007

Back to top


$title

S60 Open C
libcrypto API Specification

libcrypto API Specification

Table of Contents

Overview

Overview

The crypto library implements a wide range of cryptographic algorithms used in various Internet standards. The services provided by this library are used by the OpenSSL implementations of SSL, TLS, and S/MIME, and they have also been used to implement SSH, OpenPGP, and other cryptographic standards. All cryptographic library APIs are not documented. Further documentation can be found at http://www.openssl.org/docs/crypto/crypto.html

Give feedback of this article

©Nokia 2006

Back to top

This material, including documentation and any related computer programs, is protected by copyright controlled by Nokia. All rights are reserved. Copying, including reproducing, storing, adapting or translating, any or all of this material requires the prior written consent of Nokia. This material also contains confidential information, which may not be disclosed to others without the prior written consent of Nokia.

Nokia is a registered trademark of Nokia Corporation. S60 and logo is a trademark of Nokia Corporation. Java and all Java-based marks are trademarks or registered trademarks of Sun Microsystems, Inc. Other company and product names mentioned herein may be trademarks or tradenames of their respective owners.


$title

S60 Open C
libcrypto API Specification

libcrypto API Specification

Table of Contents

API Description
API Categories
Symmetric Ciphers
Public Key Cryptography and Key Agreement
Certificates
Authentication Codes and Hash Functions
Auxiliary Functions
Input/Output and Data Encoding
Internal Functions
General Functions

API Description

This chapter defines various sub-libraries and its functionalities.

API Categories

libcrypto consists of a number of sub-libraries that implement the individual algorithms. The functionality includes symmetric encryption, public key cryptography and key agreement, certificate handling, cryptographic hash functions and a cryptographic pseudo-random number generator.

The application or project that intends to use Open SSL must mention the paths as shown below:

SYSTEMINCLUDE   \epoc32\include\stdapis
SYSTEMINCLUDE   \epoc32\include\stdapis\openssl

The applications and projects that intend to use the different sub-modules of libcrypto individually, must include crypto.h before the sub-module's corresponding header file.

Note: Some of the libcrypto functions need more than the default available stack. The recommended stack size is 10K. To set the stack size to 10K add EPOCSTACKSIZE 0x10000 in the MMP file.

Symmetric Ciphers

Symmetric Ciphers

Function | Description
DES_random_key, DES_set_key, DES_key_sched, DES_set_key_checked, DES_set_key_unchecked, DES_set_odd_parity, DES_is_weak_key, DES_ecb_encrypt, DES_ecb2_encrypt, DES_ecb3_encrypt, DES_ncbc_encrypt, DES_cfb_encrypt, DES_ofb_encrypt, DES_pcbc_encrypt, DES_cfb64_encrypt, DES_ofb64_encrypt, DES_xcbc_encrypt, DES_ede2_cbc_encrypt, DES_ede2_cfb64_encrypt, DES_ede2_ofb64_encrypt, DES_ede3_cbc_encrypt, DES_ede3_cbcm_encrypt, DES_ede3_cfb64_encrypt, DES_ede3_ofb64_encrypt, DES_cbc_cksum, DES_quad_cksum, DES_string_to_key, DES_string_to_2keys, DES_fcrypt, DES_crypt, DES_enc_read, DES_enc_write | The DES Standard and its variants.
des_read_password, des_read_2passwords, des_read_pw_string, des_read_pw | Compatibility user interface functions.
des_modes | The DES Standard and it variants.
rc4, RC4_set_key | RC4 encryption.
rc2 | RC2 encryption.

Public Key Cryptography and Key Agreement

Public Key Cryptography and Key Agreement

Function | Description
dsa | Implements the Digital Signature Algorithm (DSA).
dh | Implements the Diffie-Hellman key agreement protocol.
DH_generate_key, DH_compute_key | Performs Diffie-Hellman key exchange.
DH_generate_parameters, DH_check | Generates and check Diffie-Hellman parameters.
DH_get_ex_new_index, DH_set_ex_data, DH_get_ex_data | Adds application specific data to DH structures.
DH_new, DH_free | Allocates and frees DH objects.
DH_set_default_method, DH_get_default_method, DH_set_method, DH_new_method DH_OpenSSL | Selects DH method.
DH_size | Gets Diffie-Hellman prime size.
rsa | Implements RSA public key crypto system.
DSA_do_sign,DSA_do_verify | Raw DSA signature operations.
DSA_dup_DH | Creates a DH structure out of DSA structure.
DSA_generate_key | Generates DSA key pair.
DSA_generate_parameters | Generates DSA parameters.
DSA_get_ex_new_index, DSA_set_ex_data, DSA_get_ex_data | Adds application specific data to DSA structures.
DSA_new, DSA_free | Allocates and frees DSA objects.
DSA_set_default_method, DSA_get_default_method, DSA_set_method, DSA_new_method DSA_OpenSSL | Selects DSA method.
DSA_SIG_new, DSA_SIG_free | Allocates and frees DSA signature objects.
DSA_sign, DSA_sign_setup, DSA_verify | DSA signatures.
DSA_size | Gets DSA signature size.
RSA_blinding_on, RSA_blinding_off | Protects the RSA operation from timing attacks.
RSA_check_key | Validates private RSA keys.
RSA_generate_key_ex | Generates RSA key pair.
RSA_get_ex_new_index, RSA_set_ex_data,RSA_get_ex_data | Add application specific data to RSA structures.
RSA_new, RSA_free | Allocate and free RSA objects.
RSA_padding_add_PKCS1_type_1, RSA_padding_check_PKCS1_type_1, RSA_padding_add_PKCS1_type_2, RSA_padding_check_PKCS1_type_2, RSA_padding_add_PKCS1_OAEP, RSA_padding_check_PKCS1_OAEP, RSA_padding_add_SSLv23, RSA_padding_check_SSLv23, RSA_padding_add_none, RSA_padding_check_none | Asymmetric encryption padding.
RSA_print, RSA_print_fp, DSAparams_print, DSAparams_print_fp, DSA_print, DSA_print_fp, DHparams_print, DHparams_print_fp | Print cryptographic parameters.
RSA_private_encrypt, RSA_public_decrypt | Low level signature operations.
RSA_public_encrypt, RSA_private_decrypt | Public key cryptography.
RSA_set_default_method, RSA_get_default_method, RSA_set_method, RSA_get_method, RSA_PKCS1_SSLeay, RSA_null_method, RSA_flags, RSA_new_method | Select RSA method.
RSA_sign, RSA_verify | RSA signatures.
RSA_sign_ASN1_OCTET_STRING, RSA_verify_ASN1_OCTET_STRING | RSA signatures.
RSA_size | Gets RSA modulus size

Certificates

Certificates

Function | Description
x509 | X.509 certificate handling.
x509v3() | X.509 version3 certificate handling.

Authentication Codes and Hash Functions

Authentication Codes and Hash Functions

Function | Description
hmac, HMAC_Init, HMAC_Update, HMAC_Final, HMAC_cleanup | HMAC message authentication code.
MD2, MD5, MD2_Init, MD2_Update, MD2_Final, MD5_Init, MD5_Update, MD5_Final | Cryptographic hash functions with a 128 bit output.
SHA1, SHA1_Init, SHA1_Update, SHA1_Final | SHA-1 (Secure Hash Algorithm) is a cryptographic hash function with a 160 bit output.

Auxiliary Functions

Auxiliary Functions

Function | Description
err | Error codes contain information about where the error occurred, and what went wrong.
ERR_clear_error | Clears the error queue.
ERR_error_string, ERR_error_string_n, ERR_lib_error_string, ERR_func_error_string, ERR_reason_error_string | Obtain human-readable error message.
ERR_get_error, ERR_peek_error, ERR_peek_last_error, ERR_get_error_line, ERR_peek_error_line, ERR_peek_last_error_line, ERR_get_error_line_data, ERR_peek_error_line_data, ERR_peek_last_error_line_data | Obtain error code and data.
ERR_GET_LIB, ERR_GET_FUNC, ERR_GET_REASON | Get library, function and reason code.
ERR_load_crypto_strings, SSL_load_error_strings, ERR_free_strings | Load and free error strings.
ERR_load_strings, ERR_PACK, ERR_get_next_error_library | Load arbitrary error strings.
ERR_print_errors, ERR_print_errors_fp | Print error messages.
ERR_put_error, ERR_add_error_data | Record an error.
ERR_remove_state | Free a thread's error queue.
ERR_set_mark, ERR_pop_to_mark | Set marks and pop errors until mark.
CRYPTO_set_locking_callback, CRYPTO_set_id_callback, CRYPTO_num_locks, CRYPTO_set_dynlock_create_callback, CRYPTO_set_dynlock_lock_callback, CRYPTO_set_dynlock_destroy_callback, CRYPTO_get_new_dynlockid, CRYPTO_destroy_dynlockid, CRYPTO_lock | OpenSSL thread support.
rand | Implements a cryptographically secure pseudo-random number generator (PRNG).
RAND_add, RAND_seed, RAND_status | Add entropy to the PRNG.
RAND_bytes, RAND_pseudo_bytes | Generate random data.
RAND_cleanup | Erases the PRNG state.
RAND_egd | Queries entropy gathering daemon.
RAND_load_file, RAND_write_file, RAND_file_name | PRNG seed file.
RAND_set_rand_method, RAND_get_rand_method, RAND_SSLeay | Select RAND method.
OPENSSL_VERSION_NUMBER, SSLeay,SSLeay_version | Gets OpenSSL version number.

Input/Output and Data Encoding

Input/Output and Data Encoding

Function | Description
ASN1_generate_nconf, ASN1_generate_v3 | ASN1 generation functions.
ASN1_OBJECT_new, ASN1_OBJECT_free | Object allocation functions.
ASN1_STRING_length, ASN1_STRING_dup, ASN1_STRING_cmp, ASN1_STRING_set, ASN1_STRING_length_set, ASN1_STRING_type, ASN1_STRING_data | ASN1_STRING utility functions.
ASN1_STRING_new, ASN1_STRING_type_new, ASN1_STRING_free | ASN1_STRING allocation functions.
ASN1_STRING_print_ex, ASN1_STRING_print_ex_fp | ASN1_STRING output routines.
bio | I/O abstraction, hides many of the underlying I/O details from an application.
BIO_ctrl, BIO_callback_ctrl, BIO_ptr_ctrl, BIO_int_ctrl, BIO_reset, BIO_seek, BIO_tell, BIO_flush, BIO_eof, BIO_set_close, BIO_get_close, BIO_pending, BIO_wpending, BIO_ctrl_pending, BIO_ctrl_wpending, BIO_get_info_callback, BIO_set_info_callback | BIO control operations.s
BIO_f_base64 | Base64 BIO filter.
BIO_f_buffer | Returns the buffering BIO method.
BIO_f_cipher, BIO_set_cipher, BIO_get_cipher_status, BIO_get_cipher_ctx | Returns the cipher BIO method.
BIO_f_md, BIO_set_md, BIO_get_md, BIO_get_md_ctx | Message digest BIO filter.
BIO_f_null | Returns the null filter BIO method. This is a filter BIO that does nothing.
BIO_f_ssl, BIO_set_ssl, BIO_get_ssl, BIO_set_ssl_mode, BIO_set_ssl_renegotiate_bytes, BIO_get_num_renegotiates, BIO_set_ssl_renegotiate_timeout, BIO_new_ssl, BIO_new_ssl_connect, BIO_new_buffer_ssl_connect, BIO_ssl_copy_session_id, BIO_ssl_shutdown | Returns the SSL BIO method.
BIO_find_type, BIO_next | BIO chain traversal.
BIO_new, BIO_set, BIO_free, BIO_vfree BIO_free_all | BIO allocation and freeing functions.
BIO_push, BIO_pop | Adds and removes BIOs from a chain.
BIO_read, BIO_write, BIO_gets,BIO_puts | BIO I/O functions.
BIO_s_accept, BIO_set_accept_port, BIO_get_accept_port, BIO_set_nbio_accept, BIO_set_accept_bios, BIO_set_bind_mode, BIO_get_bind_mode, BIO_do_accept | Returns the accept BIO method.
BIO_s_bio, BIO_make_bio_pair, BIO_destroy_bio_pair, BIO_shutdown_wr, BIO_set_write_buf_size, BIO_get_write_buf_size, BIO_new_bio_pair, BIO_get_write_guarantee, BIO_ctrl_get_write_guarantee, BIO_get_read_request, BIO_ctrl_get_read_request, BIO_ctrl_reset_read_request | Returns the method for a BIO pair.
BIO_s_connect, BIO_set_conn_hostname, BIO_set_conn_port, BIO_set_conn_ip, BIO_set_conn_int_port, BIO_get_conn_hostname, BIO_get_conn_port, BIO_get_conn_ip, BIO_get_conn_int_port, BIO_set_nbio, BIO_do_connect | Returns the connect BIO method.
BIO_s_fd, BIO_set_fd, BIO_get_fd, BIO_new_fd | File descriptor BIO.
BIO_s_file, BIO_new_file, BIO_new_fp, BIO_set_fp, BIO_get_fp, BIO_read_filename, BIO_write_filename, BIO_append_filename, BIO_rw_filename | Returns the BIO file method.
BIO_s_mem, BIO_set_mem_eof_return, BIO_get_mem_data, BIO_set_mem_buf, BIO_get_mem_ptr, BIO_new_mem_buf | Returns the memory BIO method function.
BIO_s_null | Null data sink.
BIO_s_socket, BIO_new_socket | Returns the socket BIO method.
BIO_set_callback, BIO_get_callback,BIO_set_callback_arg, BIO_get_callback_arg, BIO_debug_callback | Sets and retrieves the BIO callback.
BIO_should_retry, BIO_should_read, BIO_should_write, BIO_should_io_special, BIO_retry_type, BIO_get_retry_BIO, BIO_get_retry_reason | BIO retry functions.
evp | Provides a high-level interface to cryptographic functions.
EVP_BytesToKey | Password based encryption routine.
EVP_MD_CTX_init, EVP_MD_CTX_create, EVP_DigestInit_ex, EVP_DigestUpdate, EVP_DigestFinal_ex, EVP_MD_CTX_cleanup,EVP_MD_CTX_destroy, EVP_MAX_MD_SIZE, EVP_MD_CTX_copy_ex EVP_MD_CTX_copy, EVP_MD_type, EVP_MD_pkey_type, EVP_MD_size, EVP_MD_block_size, EVP_MD_CTX_md, EVP_MD_CTX_size, EVP_MD_CTX_block_size, EVP_MD_CTX_type, EVP_md_null, EVP_md2, EVP_md5, EVP_sha, VP_sha1, EVP_dss, EVP_dss1, EVP_get_digestbyname, EVP_get_digestbynid, EVP_get_digestbyobj | EVP digest routines.
EVP_CIPHER_CTX_init, EVP_EncryptInit_ex, EVP_EncryptUpdate, EVP_EncryptFinal_ex, EVP_DecryptInit_ex, EVP_DecryptUpdate, EVP_DecryptFinal_ex, EVP_CipherInit_ex, EVP_CipherUpdate,EVP_CipherFinal_ex, EVP_CIPHER_CTX_set_key_length, EVP_CIPHER_CTX_ctrl, EVP_CIPHER_CTX_cleanup, EVP_EncryptInit, EVP_EncryptFinal, EVP_DecryptInit, EVP_DecryptFinal, EVP_CipherInit, EVP_CipherFinal, EVP_get_cipherbyname, EVP_get_cipherbynid, EVP_get_cipherbyobj,EVP_CIPHER_nid,EVP_CIPHER_block_size, EVP_CIPHER_key_length, EVP_CIPHER_iv_length, EVP_CIPHER_flags, EVP_CIPHER_mode, EVP_CIPHER_type, EVP_CIPHER_CTX_cipher, EVP_CIPHER_CTX_nid, EVP_CIPHER_CTX_block_size, EVP_CIPHER_CTX_key_length, EVP_CIPHER_CTX_iv_length, EVP_CIPHER_CTX_get_app_data, EVP_CIPHER_CTX_set_app_data, EVP_CIPHER_CTX_type, EVP_CIPHER_CTX_flags, EVP_CIPHER_CTX_mode, EVP_CIPHER_param_to_asn1, EVP_CIPHER_asn1_to_param, EVP_CIPHER_CTX_set_padding | EVP cipher routines.
EVP_OpenInit, EVP_OpenUpdate, EVP_OpenFinal | EVP envelope decryption.
EVP_PKEY_new, EVP_PKEY_free | Private key allocation functions.
EVP_PKEY_set1_RSA, EVP_PKEY_set1_DSA, EVP_PKEY_set1_DH, EVP_PKEY_set1_EC_KEY, EVP_PKEY_get1_RSA, EVP_PKEY_get1_DSA, EVP_PKEY_get1_DH, EVP_PKEY_get1_EC_KEY, EVP_PKEY_assign_RSA, EVP_PKEY_assign_DSA, EVP_PKEY_assign_DH, EVP_PKEY_assign_EC_KEY, EVP_PKEY_type | EVP_PKEY assignment functions.
EVP_SealInit, EVP_SealUpdate, EVP_SealFinal | EVP envelope encryption.
EVP_SignInit, EVP_SignUpdate, EVP_SignFinal | EVP signing functions.
EVP_VerifyInit, EVP_VerifyUpdate, EVP_VerifyFinal | EVP signature verification functions.
pem | Reads or writes structures in PEM format.
pkcs7, pkcs12 |
PKCS12_create | Create a PKCS#12 structure.
PKCS12_parse | Parses a PKCS12 structure.
PKCS7_decrypt | Decrypts content from a PKCS#7 enveloped Data structure.
PKCS7_encrypt | Creates and returns a PKCS#7 enveloped Data structure.
PKCS7_sign | creates and returns a PKCS#7 signedData structure.
PKCS7_verify | verifies a PKCS#7 signedData structure.
SMIME_read_PKCS7 | Parses S/MIME message.
SMIME_write_PKCS7 | Converts PKCS#7 structure to S/MIME format.

Internal Functions

Internal Functions

Function | Description
bn | Performs arithmetic operations on integers of arbitrary size.
BN_add, BN_sub,BN_mul, BN_sqr, BN_div,BN_mod, BN_nnmod, BN_mod_add, BN_mod_sub, BN_mod_mul, BN_mod_sqr,BN_exp, BN_mod_exp, BN_gcd | Arithmetic operations on BIGNUMs.
BN_add_word, BN_sub_word, BN_mul_word, BN_div_word, BN_mod_word | Arithmetic functions on BIGNUMs with integers.
BN_BLINDING_new, BN_BLINDING_free, BN_BLINDING_update, BN_BLINDING_convert, BN_BLINDING_invert, BN_BLINDING_convert_ex, BN_BLINDING_invert_ex, BN_BLINDING_get_thread_id, BN_BLINDING_set_thread_id, BN_BLINDING_get_flags, BN_BLINDING_set_flags, BN_BLINDING_create_param | Blinding related BIGNUM functions.
BN_bn2bin, BN_bin2bn, BN_bn2hex, BN_bn2dec, BN_hex2bn, BN_dec2bn, BN_print, BN_print_fp, BN_bn2mpi, BN_mpi2bn | Format conversions.
BN_cmp, BN_ucmp, BN_is_zero, BN_is_one, BN_is_word, BN_is_odd | BIGNUM comparison and test functions.
BN_copy,BN_dup | Copies BIGNUMs.
BN_CTX_new, BN_CTX_init, | Allocates and frees BN_CTX structures.
BN_CTX_start, BN_CTX_get, BN_CTX_end | Uses temporary BIGNUM variables.
BN_generate_prime, BN_is_prime, BN_is_prime_fasttest | Generates primes and test for primality.
bn_mul_words, bn_mul_add_words, bn_sqr_words, bn_div_words, bn_add_words, bn_sub_words, bn_mul_comba4, bn_mul_comba8, bn_sqr_comba4, bn_sqr_comba8, bn_cmp_words, bn_mul_normal, bn_mul_low_normal, bn_mul_recursive, bn_mul_part_recursive, bn_mul_low_recursive, bn_mul_high, bn_sqr_normal, bn_sqr_recursive, bn_expand, bn_wexpand, bn_expand2, bn_fix_top,bn_check_top, bn_print, bn_dump, bn_set_max, bn_set_high, bn_set_low | BIGNUM library internal functions.
BN_mod_inverse | Computes inverse modulo n.
BN_mod_mul_montgomery, BN_MONT_CTX_new, BN_MONT_CTX_init, BN_MONT_CTX_free, BN_MONT_CTX_set, BN_MONT_CTX_copy, BN_from_montgomery, BN_to_montgomery | Montgomery multiplication.
BN_mod_mul_reciprocal, BN_div_recp, BN_RECP_CTX_new, BN_RECP_CTX_init, BN_RECP_CTX_free, BN_RECP_CTX_set | Performs an efficient BN_mod_mul() operation when the operation will be performed repeatedly with the same modulus.
BN_new, BN_init, BN_clear, BN_free, BN_clear_free | Allocates and frees BIGNUMs.
BN_num_bits, BN_num_bytes, BN_num_bits_word | Gets BIGNUM size.
BN_rand, BN_pseudo_rand | Generates pseudo-random number.
BN_set_bit, BN_clear_bit, BN_is_bit_set, BN_mask_bits, BN_lshift, BN_lshift1, BN_rshift, BN_rshift1 | Performs bit operations on BIGNUMs.
BN_swap | Exchanges BIGNUMs.
BN_zero, BN_one, BN_value_one, BN_set_word, BN_get_word | BIGNUM assignment operations.
BUF_MEM_new, BUF_MEM_free, BUF_MEM_grow, BUF_strdup | Handles simple character arrays. .
lh_new, lh_free, lh_insert, lh_delete, lh_retrieve, lh_doall,lh_doall_arg,lh_error | Implements dynamic hash tables.
lh_stats, lh_node_stats, lh_node_usage_stats, lh_stats_bio, lh_node_stats_bio, lh_node_usage_stats_bio | LHASH statistics.
OBJ_nid2obj, OBJ_nid2ln, OBJ_nid2sn, OBJ_obj2nid, OBJ_txt2nid, OBJ_ln2nid, OBJ_sn2nid, OBJ_cmp, OBJ_dup, OBJ_txt2obj, OBJ_obj2txt, OBJ_create, OBJ_cleanup | ASN1 object utility functions.
objects | ASN1 object utility functions.
stack | Generic implementation of stacks.
txt_db | Simple text based in memory database.

General Functions

General Functions

Function | Description
CONF_modules_free, CONF_modules_load, CONF_modules_unload | OpenSSL configuration cleanup functions.
CONF_modules_load_file, CONF_modules_load | OpenSSL configuration functions.
CRYPTO_set_ex_data, CRYPTO_get_ex_data | Internal application specific data functions.
CRYPTO_cleanup_all_ex_data | This function is used to cleanup application specific data and should be called before the application shuts down to avoid memory leaks.
vd2i_ASN1_OBJECT, i2d_ASN1_OBJECT | ASN1 OBJECT IDENTIFIER functions.
d2i_DHparams, i2d_DHparams | PKCS#3 DH parameter functions.
d2i_DSAPublicKey, i2d_DSAPublicKey, d2i_DSAPrivateKey, i2d_DSAPrivateKey, d2i_DSA_PUBKEY, i2d_DSA_PUBKEY, d2i_DSA_SIG, i2d_DSA_SIG | DSA key encoding and parsing functions.
d2i_PKCS8PrivateKey, d2i_PKCS8PrivateKey_fp, i2d_PKCS8PrivateKey_bio, i2d_PKCS8PrivateKey_fp, i2d_PKCS8PrivateKey_nid_bio, i2d_PKCS8PrivateKey_nid_fp | PKCS#8 format private key functions.
d2i_RSAPublicKey, i2d_RSAPublicKey, d2i_RSAPrivateKey, i2d_RSAPrivateKey, d2i_RSA_PUBKEY,i2d_RSA_PUBKEY, i2d_Netscape_RSA, d2i_Netscape_RSA | RSA public and private key encoding functions.
d2i_X509, i2d_X509, d2i_X509_bio,d2i_X509_fp, i2d_X509_bio, i2d_X509_fp | X509 encode and decode functions.
d2i_X509_ALGOR, i2d_X509_ALGOR | Algorithm Identifier functions.
d2i_X509_CRL,i2d_X509_CRL, d2i_X509_CRL_bio, d2i_509_CRL_fp, i2d_X509_CRL_bio, i2d_X509_CRL_fp | PKCS#10 certificate request functions.
d2i_X509_NAME, i2d_X509_NAME | X509_NAME encoding functions.
d2i_X509_REQ, i2d_X509_REQ, d2i_X509_REQ_bio, d2i_X509_REQ_fp, i2d_X509_REQ_bio, i2d_X509_REQ_fp | PKCS#10 certificate request functions.
d2i_X509_SIG, i2d_X509_SIG | DigestInfo functions.
engine | ENGINE cryptographic module support.
OpenSSL_add_all_algorithms, OpenSSL_add_all_ciphers, OpenSSL_add_all_digests | Add algorithms to internal table.
OPENSSL_Applink | Glue between OpenSSL BIO and Win32 compiler run-time.
OPENSSL_config, OPENSSL_no_config | Simple OpenSSL configuration functions.
OPENSSL_ia32cap | Finding the IA-32 processor capabilities.
OPENSSL_load_builtin_modules | Adds all the standard OpenSSL configuration modules to the internal list.
UI_new, UI_new_method, UI_free, UI_add_input_string, UI_dup_input_string, UI_add_verify_string, UI_dup_verify_string, UI_add_input_boolean, UI_dup_input_boolean, UI_add_info_string, UI_dup_info_string, UI_add_error_string, UI_dup_error_string, UI_construct_prompt, UI_add_user_data, UI_get0_user_data, UI_get0_result, UI_process, UI_ctrl, UI_set_default_method, UI_get_default_method, UI_get_method, UI_set_method, UI_OpenSSL, ERR_load_UI_strings | New User Interface functions.
X509_NAME_add_entry_by_txt, X509_NAME_add_entry_by_OBJ, X509_NAME_add_entry_by_NID, X509_NAME_add_entry, X509_NAME_delete_entry | X509_NAME modification functions.
X509_NAME_ENTRY_get_object, X509_NAME_ENTRY_get_data, X509_NAME_ENTRY_set_object, X509_NAME_ENTRY_set_data, X509_NAME_ENTRY_create_by_txt, X509_NAME_ENTRY_create_by_NID, X509_NAME_ENTRY_create_by_OBJ | X509_NAME_ENTRY utility functions.
X509_NAME_get_index_by_NID, X509_NAME_get_index_by_OBJ, X509_NAME_get_entry, X509_NAME_entry_count, X509_NAME_get_text_by_NID, X509_NAME_get_text_by_OBJ | X509_NAME lookup and enumeration functions.
X509_NAME_print_ex, X509_NAME_print_ex_fp, X509_NAME_print, X509_NAME_oneline | X509_NAME printing routines.
X509_new, X509_free | X509 certificate ASN1 allocation functions.

Give feedback of this article

©Nokia 2006

Back to top

This material, including documentation and any related computer programs, is protected by copyright controlled by Nokia. All rights are reserved. Copying, including reproducing, storing, adapting or translating, any or all of this material requires the prior written consent of Nokia. This material also contains confidential information, which may not be disclosed to others without the prior written consent of Nokia.

Nokia is a registered trademark of Nokia Corporation. S60 and logo is a trademark of Nokia Corporation. Java and all Java-based marks are trademarks or registered trademarks of Sun Microsystems, Inc. Other company and product names mentioned herein may be trademarks or tradenames of their respective owners.


$title

S60 Open C
libcrypto API Specification

libcrypto API Specification

Table of Contents

Limitations

Limitations

  • Unsupported algorithms due to IPR issues: Rc5 IDEA, Blowfish, cast, ripemd, md4, mdc2, ecc, ecdh, ecdsa.
  • Certificate usage: Certificates should be in .DER format. Usage of Symbian's certstore to avoid duplication of certificates.

Give feedback of this article

©Nokia 2006

Back to top

This material, including documentation and any related computer programs, is protected by copyright controlled by Nokia. All rights are reserved. Copying, including reproducing, storing, adapting or translating, any or all of this material requires the prior written consent of Nokia. This material also contains confidential information, which may not be disclosed to others without the prior written consent of Nokia.

Nokia is a registered trademark of Nokia Corporation. S60 and logo is a trademark of Nokia Corporation. Java and all Java-based marks are trademarks or registered trademarks of Sun Microsystems, Inc. Other company and product names mentioned herein may be trademarks or tradenames of their respective owners.


$title

S60 Open C
libcrypto API Specification

libcrypto API Specification

Table of Contents

Required Capabilities

Required Capabilities

Capability | Description
WriteDeviceData | Grants write access to settings that control the behavior of the device. For example, device lock settings, system time, time zone, alarms, etc.
NetworkServices | A user capability that grants access to remote services without any restriction on its physical location. Typically, such a location is unknown to the phone user, and such services may incur cost for the phone user. Voice calls, SMS, and Internet services are good examples of such network services. They are supported by GSM, CDMA, and all IP transport protocols including Bluetooth profiles over IP.

Give feedback of this article

©Nokia 2006

Back to top

This material, including documentation and any related computer programs, is protected by copyright controlled by Nokia. All rights are reserved. Copying, including reproducing, storing, adapting or translating, any or all of this material requires the prior written consent of Nokia. This material also contains confidential information, which may not be disclosed to others without the prior written consent of Nokia.

Nokia is a registered trademark of Nokia Corporation. S60 and logo is a trademark of Nokia Corporation. Java and all Java-based marks are trademarks or registered trademarks of Sun Microsystems, Inc. Other company and product names mentioned herein may be trademarks or tradenames of their respective owners.


Internationalization - libintl

Overview
Functions
Limitations
Capabilities

© Nokia 2007

Back to top


$title

S60 Open C
libintl API Specification

libintl API Specification

Table of Contents

Overview

Overview

The libintl library provides APIs that internationalize messages. The GNU gettext is a tool to internationalize messages a software outputs according to locale status of LC_MESSAGES. msgid specifies the message to be translated. Conventionally, it is the English version of the message with non-ASCII characters replaced by ASCII approximations. The translators work with message catalogs, called the PO files, that contain messages in both English and their translated versions. Use the msgfmt utility to install the PO file.

Give feedback of this article

©Nokia 2006

Back to top

This material, including documentation and any related computer programs, is protected by copyright controlled by Nokia. All rights are reserved. Copying, including reproducing, storing, adapting or translating, any or all of this material requires the prior written consent of Nokia. This material also contains confidential information, which may not be disclosed to others without the prior written consent of Nokia.

Nokia is a registered trademark of Nokia Corporation. S60 and logo is a trademark of Nokia Corporation. Java and all Java-based marks are trademarks or registered trademarks of Sun Microsystems, Inc. Other company and product names mentioned herein may be trademarks or tradenames of their respective owners.


$title

S60 Open C
libintl API Specification

libintl API Specification

Table of Contents

API Description
Functions

API Description

Functions

Function | Description
bind_textdomain_codeset | Sets the encoding of message translations.
bindtextdomain | Sets the directory containing message catalogs.
dcgettext | Translates the messages
dcngettext | Translate message and choose the plural form.
dgettext | Translates the messages
dngettext | Translate message and choose the plural form.
gettext | Translates the messages
ngettext | Translate message and choose the plural form.
textdomain | Sets the domain for the gettext() calls that follow.

Give feedback of this article

©Nokia 2006

Back to top

This material, including documentation and any related computer programs, is protected by copyright controlled by Nokia. All rights are reserved. Copying, including reproducing, storing, adapting or translating, any or all of this material requires the prior written consent of Nokia. This material also contains confidential information, which may not be disclosed to others without the prior written consent of Nokia.

Nokia is a registered trademark of Nokia Corporation. S60 and logo is a trademark of Nokia Corporation. Java and all Java-based marks are trademarks or registered trademarks of Sun Microsystems, Inc. Other company and product names mentioned herein may be trademarks or tradenames of their respective owners.


$title

S60 Open C
libintl API Specification

libintl API Specification

Table of Contents

Limitations

Limitations

No known limitations.

Give feedback of this article

©Nokia 2006

Back to top

This material, including documentation and any related computer programs, is protected by copyright controlled by Nokia. All rights are reserved. Copying, including reproducing, storing, adapting or translating, any or all of this material requires the prior written consent of Nokia. This material also contains confidential information, which may not be disclosed to others without the prior written consent of Nokia.

Nokia is a registered trademark of Nokia Corporation. S60 and logo is a trademark of Nokia Corporation. Java and all Java-based marks are trademarks or registered trademarks of Sun Microsystems, Inc. Other company and product names mentioned herein may be trademarks or tradenames of their respective owners.


$title

S60 Open C
libintl API Specification

libintl API Specification

Table of Contents

Required Capabilities

Required Capabilities

A 3rd party application does not need any capabilities in order to use libintl APIs.

Give feedback of this article

©Nokia 2006

Back to top

This material, including documentation and any related computer programs, is protected by copyright controlled by Nokia. All rights are reserved. Copying, including reproducing, storing, adapting or translating, any or all of this material requires the prior written consent of Nokia. This material also contains confidential information, which may not be disclosed to others without the prior written consent of Nokia.

Nokia is a registered trademark of Nokia Corporation. S60 and logo is a trademark of Nokia Corporation. Java and all Java-based marks are trademarks or registered trademarks of Sun Microsystems, Inc. Other company and product names mentioned herein may be trademarks or tradenames of their respective owners.


Posix Thread Library - libpthread

Overview
Functions
Limitations
Capabilities

© Nokia 2007

Back to top


$title

S60 Open C
libpthread API Specification

libpthread API Specification

Table of Contents

Overview

Overview

Thread is a schedulable entity that runs within a process. In other words, a thread is a unit of execution that has its own stack and executes a given piece of code. Unlike a real process, the thread normally shares its memory with other threads (whereas processes usually have a different memory area for each one of them). A thread group is a set of threads all executing inside the same process. They all share the same memory, and thus can access the same global variables, the same heap memory, the same set of file descriptors, and so on. All the threads in a thread group execute in parallel (that is, using time slices, or if the system has several processors, then really in parallel). This implementation is currently user-space only.

The advantage of using a thread group instead of a normal serial program is that several operations may be carried out in parallel, and thus events can be handled immediately as they arrive (for example, if one thread is handling a user interface, and another thread is handling database queries, we can execute a heavy query requested by the user, and still respond to user input while the query is executed).

The advantage of using a thread group over using a process group is that context switching between threads is much faster than context switching between processes. In addition communication between two threads is usually faster and easier to implement than communication between two processes.

On the other hand, because threads in a group all use the same memory space, if one of them corrupts the contents of its memory, other threads might suffer as well. With processes, the operating system normally protects processes from one another, and thus if one corrupts its own memory space, other processes will not suffer.

Each process will have one main thread, and it may also have several more threads which share the address space of the process. Threads do not have a parent-child relationship with each other.

Give feedback of this article

©Nokia 2006

Back to top

This material, including documentation and any related computer programs, is protected by copyright controlled by Nokia. All rights are reserved. Copying, including reproducing, storing, adapting or translating, any or all of this material requires the prior written consent of Nokia. This material also contains confidential information, which may not be disclosed to others without the prior written consent of Nokia.

Nokia is a registered trademark of Nokia Corporation. S60 and logo is a trademark of Nokia Corporation. Java and all Java-based marks are trademarks or registered trademarks of Sun Microsystems, Inc. Other company and product names mentioned herein may be trademarks or tradenames of their respective owners.


$title

S60 Open C
libpthread API Specification

libpthread API Specification

Table of Contents

API Description
API Categories
libpthread Functions
Pseudo Functions

API Description

This page lists the different categories in the libpthread library.

  • libpthread Functions
  • Pseudo Functions

API Categories

libpthread Functions

Basic Thread Operations

Function | Description
pthread_create | Creates a new thread, with attributes specified by attrib, within a process.
pthread_exit | Terminates the calling thread and makes the value retValPtr available to any successful join with the terminating thread.
pthread_join | Suspends execution of the calling thread until the target thrHandle terminates unless the target thrHandle has already terminated.

Condition Variables

Function | Description
pthread_cond_broadcast | Unblocks all threads waiting for the condition variable cond.
pthread_cond_destroy | Frees the resources allocated by the condition variable cond.
pthread_cond_init | Creates a new condition variable.
pthread_cond_signal | Unblocks one thread waiting for the condition variable cond.
pthread_cond_timedwait | Atomically blocks the current thread waiting on the condition variable specified by cond, and unblocks the mutex specified by mutex.
pthread_cond_wait | Atomically blocks the current thread waiting on the condition variable specified by cond, and unblocks the mutex specified by mutex.

Miscellaneous Thread Functions

Function | Description
pthread_equal | Compares the thread IDs t1 and t2.
pthread_detach | Indicates to the implementation, that storage for the thread thrHandle can be reclaimed when the thread terminates.
pthread_once | Calls the init_routine with no arguments
pthread_self | Returns the thread ID of the calling thread.

Mutexes

Function | Description
pthread_mutex_destroy | Frees the resources allocated for mutex.
pthread_mutex_init | Creates a new mutex, with attributes specified with attr.
pthread_mutex_lock | Locks mutex. If the mutex is already locked, the calling thread will block until the mutex becomes available.
pthread_mutex_unlock | Unlocks mutex.
pthread_mutexattr_init | Initializes attr with all the default mutex attributes.

Thread Attributes

Function | Description
pthread_attr_destroy | Destroys attrib.
pthread_attr_init | Initializes attrib with all the default thread attributes.

Thread-Specific Data

Function | Description
pthread_getspecific | Returns the thread-specific data value associated with the given key.
pthread_key_create | Creates a thread-specific data key visible to all threads in the process.
pthread_setspecific | Associates a thread-specific value with a key obtained via a previous call to pthread_key_create.

Pseudo Functions

Functions | Description
pthread_condattr_init | Destroys and initializes the condition variable attributes object
pthread_condattr_destroy | Destroys and initializes the condition variable attributes object
pthread_attr_setscope | Gets and sets the contentionscope attribute
pthread_attr_getscope | Gets and sets the contentionscope attribute
pthread_attr_setschedpolicy | Gets and sets the schedpolicy attribute
pthread_attr_getschedpolicy | Gets and sets the schedpolicy attribute
pthread_setschedparam | Dynamic thread scheduling parameters access
pthread_getschedparam | Dynamic thread scheduling parameters access
pthread_mutexattr_setpshared | Gets and sets the process-shared attribute
pthread_mutexattr_getpshared | Gets and sets the process-shared attribute

Give feedback of this article

©Nokia 2006

Back to top

This material, including documentation and any related computer programs, is protected by copyright controlled by Nokia. All rights are reserved. Copying, including reproducing, storing, adapting or translating, any or all of this material requires the prior written consent of Nokia. This material also contains confidential information, which may not be disclosed to others without the prior written consent of Nokia.

Nokia is a registered trademark of Nokia Corporation. S60 and logo is a trademark of Nokia Corporation. Java and all Java-based marks are trademarks or registered trademarks of Sun Microsystems, Inc. Other company and product names mentioned herein may be trademarks or tradenames of their respective owners.


$title

S60 Open C
libpthread API Specification

libpthread API Specification

Table of Contents

Limitations

Limitations

  • pthread_attr_setscope supports only PTHREAD_SCOPE_SYSTEM.
  • pthread_attr_setschedpolicy supports only SCHED_RR.
  • pthread_join: Only one thread can join one specific target thread.
  • pthread_setschedparam supports only SCHED_RR policy.
  • sem_init: Semaphore can be used only within the process. Semaphore across the processes is not supported.
  • The pthread_mutexattr_setpshared supports only PTHREAD_PROCESS_PRIVATE

Give feedback of this article

©Nokia 2006

Back to top

This material, including documentation and any related computer programs, is protected by copyright controlled by Nokia. All rights are reserved. Copying, including reproducing, storing, adapting or translating, any or all of this material requires the prior written consent of Nokia. This material also contains confidential information, which may not be disclosed to others without the prior written consent of Nokia.

Nokia is a registered trademark of Nokia Corporation. S60 and logo is a trademark of Nokia Corporation. Java and all Java-based marks are trademarks or registered trademarks of Sun Microsystems, Inc. Other company and product names mentioned herein may be trademarks or tradenames of their respective owners.


$title

S60 Open C
libpthread API Specification

libpthread API Specification

Table of Contents

Required Capabilities

Required Capabilities

Some libpthread functions require the additional capabilities listed below:

Capability

Description
PowerMgmt Grants the right:
  • to kill any process in the system
  • to power off unused peripherals
  • to switch the machine into standby state
  • to wake the machine up
  • to power the machine down completely.
  • For thread termination like pthread_exit() and pthread join(), PowerMgmt is required.

    They are calling Rprocess::Terminate() internally.

Note that this does not control access to anything that might drain battery power.

The following functions require PowerMgmt capabilities:
  • pthread_create
  • pthread_detach
  • pthread_exit
  • pthread_getschedparam
  • pthread_getspecific
  • pthread_join
  • pthread_key_create
  • pthread_key_delete
  • pthread_setschedparam
ProtServ Grants the right to a server to register with a protected name. Currently, protected names start with a "!" character. The kernel prevents servers without this capability from using such a name, and therefore prevents protected servers from being impersonated. The thread create case (pthread_create() ) needs ProtServ capability. It uses the User::SetCritical () API.
The following functions require ProtServ capabilities:
  • pthread_cond_broadcast
  • pthread_cond_destroy
  • pthread_cond_init
  • pthread_cond_signal
  • pthread_cond_timedwait
  • pthread_cond_wait
  • pthread_create
  • pthread_detach
  • pthread_exit
  • pthread_getschedparam
  • pthread_getspecific
  • pthread_join
  • pthread_key_create
  • pthread_key_delete
  • pthread_mutex_destroy
  • pthread_mutex_init
  • pthread_mutex_lock
  • pthread_mutex_timedlock
  • pthread_mutex_trylock
  • pthread_mutex_unlock
  • pthread_once
  • pthread_self
  • pthread_setschedparam
  • pthread_setspecific
  • sem_destroy
  • sem_init

Give feedback of this article

©Nokia 2006

Back to top

This material, including documentation and any related computer programs, is protected by copyright controlled by Nokia. All rights are reserved. Copying, including reproducing, storing, adapting or translating, any or all of this material requires the prior written consent of Nokia. This material also contains confidential information, which may not be disclosed to others without the prior written consent of Nokia.

Nokia is a registered trademark of Nokia Corporation. S60 and logo is a trademark of Nokia Corporation. Java and all Java-based marks are trademarks or registered trademarks of Sun Microsystems, Inc. Other company and product names mentioned herein may be trademarks or tradenames of their respective owners.


Developer Guides

Introduction to Open C
Intermixing C and C++
Localization
Porting Guides and Tricks
Networking and Sockets
Threads,Processes, IPC,and Synchronization
Introduction to Glib
Compilers and IDEs

© Nokia 2007

Back to top


Introduction to Open C

Overview
Symbian OS vs. UNIX
Getting started with Open C
Limitations

© Nokia 2007

Back to top


$title

S60 Open C
Introduction to Open C

Introduction to Open C

Table of Contents

Overview

Overview

The standard base libraries provides a vendor-neutral (or Unix/Linux-like) C programming interface to base functionality provided by such commonly used libraries as glib, openssl, and so on. These libraries:
  • enable a faster application development in Symbian OS via familiar standard interfaces and programming model
  • reduce the porting effort of existing components to Symbian OS mobile phones
  • reduce the effort to have a common code base for multiple platforms
Open C provides the following libraries:
  • libc- Standard C libraries. There are several 'libraries' or groups of functions included inside libc: the standard I/O routines, database routines, bit operators, string operators, character tests and character operators, DES encryption routines, storage allocation, time functions, signal handling, and more.
  • libm- Arithmetical and mathematical functions operating according to the standard C.
  • libpthread- The pthreads API provides an IEEE Std1003.1c (POSIX) standard interface for implementing multiple threads of execution within a traditional developer process. This implementation is currently user-space only. pthreads provide functions for the following:
    • thread creation and destruction
    • an interface to the thread scheduler to establish thread scheduling parameters
    • mutex and condition variables to provide mechanisms for the programmer to synchronize access to shared process resources
  • libdl- Loading of dynamic link libraries.
  • libz- The 'zlib' compression library provides in-memory compression and decompression functions, including integrity checks of the uncompressed data.
  • libcrypto- The OpenSSL crypto library implements a wide range of cryptographic algorithms used in various Internet standards. The services provided by this library are used by the OpenSSL implementations of SSL, TLS, and S/MIME, and they have also been used to implement SSH, OpenPGP, and other cryptographic standards.
  • libssl- The OpenSSL ssl library implements the Secure Sockets Layer (SSL v2/v3) and Transport Layer Security (TLS v1) protocols.
  • libcrypt- Cryptography libraries containing functions for encrypting blocks of data, messages, and password hashing.
  • libglib- A general-purpose utility library, which provides many useful data types, macros, type conversions, string utilities, file utilities, a main loop abstraction, and so on. It works on many UNIX-like platforms, Windows, OS/2, and BeOS.

The provided Open C libraries do not provide any UI functionality. In case the component requires a UI, the S60 UI framework has to be used.

Give feedback of this section

©Nokia 2006

Back to top

This material, including documentation and any related computer programs, is protected by copyright controlled by Nokia. All rights are reserved. Copying, including reproducing, storing, adapting or translating, any or all of this material requires the prior written consent of Nokia. This material also contains confidential information, which may not be disclosed to others without the prior written consent of Nokia.

Nokia is a registered trademark of Nokia Corporation. S60 and logo is a trademark of Nokia Corporation. Java and all Java-based marks are trademarks or registered trademarks of Sun Microsystems, Inc. Other company and product names mentioned herein may be trademarks or tradenames of their respective owners.


$title

S60 Open C
Introduction to Open C

Introduction to Open C

Table of Contents

Symbian OS vs. UNIX
Hello World
File I/O
Thread creation

Symbian OS vs. UNIX

The previous section gave an overview of the amount of work that, needs to be done when programming on Symbian and UNIX environments. This section deals with the more general scenario that will be used frequently in a typical operating system.

Hello World

Assuming that the user is new to the UNIX environment, writing a simple program that displays a string on a console does not take more than a day’s effort. Its simply 4-5 lines of code as shown below:

#include <stdio.h>
int main(int argc, char** argv) {
       printf(“Hello world\n”);
       return 0;
   }

The code contains a main() , one printf statement, and one #include< >. By convention UNIX applications will map descriptor 0 with standard input (STDIN), descriptor 1 with standard output (STDOUT), and descriptor 2 with standard error (STDERROR) of the process. So, there is no need to create/open standard input/output/error for a process before using them. Notice also that, main( ) takes two arguments. These arguments will be read from the command prompt before invoking main( ) and will be passed to main. These arguments are not mandatory; they can be ignored. No additional work is needed for having these arguments.

If we attempt to display a string on a console using Symbian OS, a lot of effort goes into collecting the materials, and for coding. The first time the developer may find the code a little complex to understand.

#include <e32std.h>
#include <e32cons.h>

int HelloWorldL()
       {
       CConsoleBase* console = Console::NewL(_L("Hello World"), TSize( KConsFullScreen, KConsFullScreen));
       console->Printf(_L(“Hello World\n”));
       delete console;
       return 0;
       }

TInt E32Main()
       {
       __UHEAP_MARK;
       CTrapCleanup* cleanup = CTrapCleanup::New();
       TInt retVal = KErrNone;
       if (cleanup)
           {
           TRAP(retVal, HelloWorldL());
           __ASSERT_ALWAYS(!retVal, User::Panic(_L("Hello-World PANIC"), retVal));
           //Destroy cleanup stack
           delete cleanup;
           }
       __UHEAP_MARKEND;
       return retVal;
       }

The code above has some header inclusions, two functions, and some complicated codes. In Symbian OS, the entry function for an EXE is E32Main (not main as in UNIX). The following actions are done to print a message on a console:

  1. Mark the heap using __UHEAP_MARK (not mandatory).
  2. Create the cleanup stack.
  3. Have a top-level TRAP for the function HelloWorldL function.
  4. In the HelloWorldL function, create a console object.
  5. Do print on the created console object.
  6. Delete the console.
  7. Delete the cleanup stack.
  8. Unmark the heap (not mandatory if the heap is not marked).

In Symbian OS, a console is not created by default; it has to be created explicitly. Symbian OS does not give a rich set of APIs needed to perform I/O operations on a console. The I/O operations that can be performed on a console in Symbian OS are limited to :

  • printing strings and reading one character at a time
  • getting cursor position

In case we are interested in command line arguments, it takes some more additional works. We have to read explicitly from the command prompt by using the APIs provided by Symbian OS.

File I/O

This section compares the ease of programming in the Open C environment against programming on Symbian OS.

/* File I/O in UNIX environment */
  FILE* fp = fopen(“file.txt”, w);
  if (fp) {
     fprintf(fp, “Write some data”);
     fclose();
  }

//File I/O in Symbian OS
  RFs fSession;
  User::LeaveIfError(fSession.Connect());
  RFile file;
  ret = file.Open(fSession, _L(“file.txt”), EFileWrite);
  if (ret)
     {
     ret = file.Create(fSession, _L(“file.txt”), EFileWrite);
     }
  if (!ret)
     {
     file.Write(_L8(“Write some data”));
     }
  file.Close();
  fSession.Close();

The example above shows the complexity of the code in Symbian OS for doing simple file I/O. In addition to coding complexity, we need to include and link with :

  • efsrv.lib for any file-related operation
  • esock.lib for network-related operation
  • commdb.lib for selecting IAPs
Since most of the resources under Symbian OS are accessed through client/server IPC, we need to connect with the corresponding server before doing any operation and close the session on completion of the operation. For example:
  • connect with the file server before file operations
  • connect with the socket server for socket-related operation
  • connect to the communication server before serial communication operation
Open C eliminates all these operations. Open C allows the user to code, as if it were done for the UNIX or Linux environment and lets the user link the application with Open C.

Thread creation

This section deals with thread creation in the UNIX and Symbian OS environments.

/* Thread creation in UNIX environment*/
   void* ThreadEntryPoint( void* aParam );
   …
   int exitReason = 0;
   int retVal  = 0;
   pthread_t threadID = 0;
   pthread_attr_t threadAttr;
   pthread_attr_init( &threadAttr );
   retVal = pthread_create( &threadID, &threadAttr, ThreadEntryPoint, (void*)NULL );
   if(retVal == 0) {
       retVal = pthread_join(threadID1, (void**)&exitReason );
   }

// Thread creation in Symbian OS
  TInt ThreadEntryPoint( TAny* aData );
  …
  RThread thread;
  thread.Create(_L("MY-THREAD"), ThreadEntryPoint, 4096, NULL, NULL);
  TRequestStatus stat;
  thread.Logon(stat);
  //Start executing the thread.
  thread.Resume();
  //Wait for the thread to die.
  User::WaitForRequest(stat);
  exitReason = thread.ExitReason();
  thread.Close();

In addition the difference in the code for creating threads using pthread_create and RThread::Create, a thread created using RThread::Create also expects the ThreadEntryPoint function to create its own vcleanup stack and a top-level TRAP, if required. Else, the thread may crash or panic. But this does not have to be done for a thread created using pthread_create. pthread_create does that for the developer.

Give feedback of this section

©Nokia 2006

Back to top

This material, including documentation and any related computer programs, is protected by copyright controlled by Nokia. All rights are reserved. Copying, including reproducing, storing, adapting or translating, any or all of this material requires the prior written consent of Nokia. This material also contains confidential information, which may not be disclosed to others without the prior written consent of Nokia.

Nokia is a registered trademark of Nokia Corporation. S60 and logo is a trademark of Nokia Corporation. Java and all Java-based marks are trademarks or registered trademarks of Sun Microsystems, Inc. Other company and product names mentioned herein may be trademarks or tradenames of their respective owners.


$title

S60 Open C
Introduction to Open C

Introduction to Open C

Table of Contents

Getting started with Open C
Changes to the MMP file
Example using E32Main()
Example using main()
Hybrid application with both Symbian C++ and standard C codes and files

Getting started with Open C

Changes to the MMP file

Add needed libraries used by the MMP file structure:

If developers want to use any of the Open C library, they need to link to the corresponding library in the MMP file using theLIBRARY keyword.

If the application has main() as the entry point, the library libcrt0.lib must be specified as the first library otherwise, it will result in some linker errors. We also need to link with Symbian OS EUSER.DLL. This is required since the static library uses some of the services of the Symbian OS such as creating cleanup stack, and having a top level TRAP. All these details are hidden from the developer. So, the developer does not have to worry about them. The developer will write the application as if it were for the UNIX environment.

STATICLIBRARY  libcrt0.lib
LIBRARY        libc.lib
LIBRARY        euser.lib  // Needed in order to use Symbian services
// and whatever Open C libraries are needed…

Thelibcrt0.lib library is required if we are not going to write E32Main within our application (EXE). This static library has an implementation of E32Main within which it calls the library initialization method followed by calling main written by the developer. This static library also gets command-line arguments and passes the same to main.

If the application has E32Main() as an entry point, there is no need to link to libcrt0.lib like in the example below.

LIBRARY         libc.lib
LIBRARY         libm.lib libpthread.lib
LIBRARY         euser.lib

Add needed include paths

SYSTEMINCLUDE   \epoc32\include\stdapis
Note: Some of the SSL/cryptography functions need more than the default available stack. The recommended stack size is 10K. To set the stack size to 10K add
EPOCSTACKSIZE 0x10000
in the MMP file.

Example using E32Main()

A simple example using E32Main() as an entry point is described below. The example writes a text to a file.

  • Modify the MMP file as mentioned earlier.
  • Create a trap handler using CTrapCleanup.
  • Call the method within TRAPD.
  • Delete the trap handler.
#include <stdio.h>
#include <string.h>
#include <e32base.h>

void doExampleL(void)
{
    FILE* fd;
    char* fileName = "C:\\test.txt";
    char *buf = "Hello world from E32Main()";
    fd = fopen(fileName, "w");
    if (fd == NULL)
    {
        printf("Unable to open the file (%s)", fileName);
        return;
    }
    if (fwrite(buf, sizeof(char), strlen(buf), fd) < 0 )
    {
        perror("write fails.");
    }
    fclose(fd);
}

GLDEF_C TInt E32Main()
    {
    CTrapCleanup* cleanup=CTrapCleanup::New();
    TRAPD(error,doExampleL());
    delete cleanup; // destroy cleanup stack
    return 0; // and return
    }

Example using main()

A simple example using main() as an entry point is described below. The example writes a text to a file.

  • Modify the MMP file as mentioned before.
  • Do usual C style coding.
#include <stdio.h>
#include <string.h>

int main(void)
{
    FILE* fd;
    char* fileName = "C:\\test.txt";
    char *buf = "Hello world";
    fd = fopen(fileName, "w");
    if(fd == NULL)
        {
        printf("Unable to open the file (%s)", fileName);
        return -1;
        }
    if (fwrite(buf, sizeof(char), strlen(buf), fd) < 0 )
        {
        perror("write fails.");
        }
    printf("File (%s) is created successfully.", fileName);
    fclose(fd);
    getchar();
    return 0;
    }

Hybrid application with both Symbian C++ and standard C codes and files

If the developers want to use any of the Open C STDLIB while writing some Symbian application, they need to link to the corresponding library. It is same as in the case above, the only difference being that the developer does not have to link with the STATICLIBRARY libcrt0.lib in the MMP file.

There are no additional Open C-specific changes that need to be done in the source file in this case. This is possible, because the developer of Open C does not have to call any library initialization routine before use or cleanup routine after use.

Some of the Open C STDLIBS APIs assume that a cleanup stack is created and there is a top-level TRAP. If the developer does not create either of the two, calling such API’s may lead to application crash.

NOTE! In a hybrid application, we have to make sure that the cleanup stack is created and a top-level TRAP marker is done.

Hybrid application can also contain threads created using both RThread::Create and pthread_create, and can still use Open C APIs in both the threads. In case of RThread::Create the developer has to create cleanup stack and a top level TRAP for this thread in the Thread Entry Function, if it is required; else this thread may crash or panic.

Even though Open C can be used with hybrid applications well , we have to be a bit careful with some of the APIs like popen. This particular API takes an EXE name as the argument. This EXE should be the one that is built using linking with libcrt0.lib. Otherwise the behavior of popen( ) will differ.

We can also have an application that has both C++ and C source codes. In this case if we want to give C linkage to C++ code- that is calling a function defined in a C++ file that may have C++ code, we can use extern “C”. For example:

// File: sample.c
  void OtherFoo();

  void Foo() {
     OtherFoo();
  }

// File: useme.cpp

  extern “C” {
  void OtherFoo() {
     //Can use any C++ code here
     //Can use Symbian C++ code here
  }
  }

Give feedback of this section

©Nokia 2006

Back to top

This material, including documentation and any related computer programs, is protected by copyright controlled by Nokia. All rights are reserved. Copying, including reproducing, storing, adapting or translating, any or all of this material requires the prior written consent of Nokia. This material also contains confidential information, which may not be disclosed to others without the prior written consent of Nokia.

Nokia is a registered trademark of Nokia Corporation. S60 and logo is a trademark of Nokia Corporation. Java and all Java-based marks are trademarks or registered trademarks of Sun Microsystems, Inc. Other company and product names mentioned herein may be trademarks or tradenames of their respective owners.


$title

S60 Open C
Introduction to Open C

Introduction to Open C

Table of Contents

Limitations
Functions not implemented

Limitations

Some APIs of the standard C Library are not implemented because of the constraints or limitations of Symbian OS:

  • Open C does not support signals because a Symbian C++ thread cannot be made to execute a "signal handler" spontaneously.
  • Owing to the difference in the Symbian OS model (when compared to UNIX -like OS), fork( ) and exec( ) functions are not supported.
  • Since fork( ) and exec( ) are not supported, popen( ) is not complete. It will just create a child process and open a pipe between a parent and a child process either in read or write mode. It neither copies the address space to a child nor copies all the open descriptors in the parent process to the child.
  • wait( ) and waitpid( ) behave differently from the standard.
  • int dup2(int oldfd, int newfd); The return value of dup2 can be different from the one the developer expected it to be (newfd). So, the developer of dup2 should use the return value of dup2 as the new allocated fd rather than the one passed to dup2 (newfd). According to the standard, newfd and return values are the same, if dup2 is successful.
  • Some of the APIs of Open C assume that a cleanup stack is created and there is a top-level TRAP for the current thread. All the threads created using RThread::Create should create them explicitly.
  • In case of Open C, libc will have its own console object maintained and all threads console I/O will be routed to the console. In case of a hybrid application, if the application creates one more console, then switching between these consoles will be a problem. The user may not be aware of this problem.
  • In case of an emulator, the developer can configure the window size dynamically. But the console maintained by Open C libc will remain the same. So, if the configuration is changed, data displayed on the console may not be aligned properly.
  • Even though some APIs likeopen( ), and fcntl( ) take both, two or three arguments, on Open C these APIs may not behave according to the standard when only 2 arguments are passed.
  • Since Symbian C++ does not support long double, math-related APIs that use long double might not have the desired precision.

More detailed information about the limitations can be found in the Open C API Reference documentation.

Give feedback of this section

Functions not implemented

To view the alphabetical index of non- implemented functions, click here.

©Nokia 2006

Back to top

This material, including documentation and any related computer programs, is protected by copyright controlled by Nokia. All rights are reserved. Copying, including reproducing, storing, adapting or translating, any or all of this material requires the prior written consent of Nokia. This material also contains confidential information, which may not be disclosed to others without the prior written consent of Nokia.

Nokia is a registered trademark of Nokia Corporation. S60 and logo is a trademark of Nokia Corporation. Java and all Java-based marks are trademarks or registered trademarks of Sun Microsystems, Inc. Other company and product names mentioned herein may be trademarks or tradenames of their respective owners.


Intermixing C and C++

Introduction to intermixing C and C++
extern C and Symbian DEF files

© Nokia 2007

Back to top


$title

S60 Open C
Intermixing C and C++

Intermixing C and C++

Table of Contents

Introduction to Intermixing C and C++
When and why to use C linkage
Syntax of extern C
How to use extern C
Mixing C and C++ features using extern "C"
Extending C codes with C++ Codes

Introduction to Intermixing C and C++

When porting an open source application or any C (or C++) applications on top of Symbian/S60 using Open C as the platform, the developer will come across situations where C and C++ (and Symbian C++ as well) codes will be used together. The open source community implements a vast number of libraries that export C APIs to the user of such libraries.

When and why to use C linkage

While porting such applications, if developers have to intermix C and C++ code, they then have to depend on C++ language features like extern "C" for giving C linkage to some set of APIs. This is required because C and C++ compilers handle function prototype in a different way. C++ compilers use name mangling, (or name decoration) to generate unique names for identifiers in a program. It is because of this technique, in C++, that it is possible to overload any functions (this requires that all the overloaded functions should have a different argument list). The C++ mangled name for any identifier contains all the necessary information that may be needed by the linker, such as linkage type, scope, calling convention, and others.

All identifiers (function names or variable names) declared or defined in C++ source or headers are subject to name mangling. When it comes to C, however, there is nothing called name mangling or overloading. It applies when the developer tries to use C APIs by including corresponding headers. To avoid name mangling, the developer should mention explicitly that those APIs are C APIs, by using the extern "C" keyword.

Syntax of extern C

The syntax of extern "C" is shown below:

extern "C" declaration ;

The declaration (or definition) that immediately follows extern "C" has the C linkage.

extern "C" {
   declaration ;
   declaration ;
   ...
}

Everything between the curly braces has C linkage, unless declared otherwise.

How to use extern C

While writing header files with C functions which will be included by both C and C++ source files, we need to take care of using extern "C" properly. See the example below:

/*File: GoodCHeader.h */
/* Can be used by C/C++ header and source files directly */

#ifdef __cplusplus
extern "C" {
#endif
/* Write C function declarations here */
void Function1(int, int);
char* Function3(char*, int);
int Function2(int);
#ifdef __cplusplus
} /* extern "C" */
#endif

Using ifdef __cplusplus is required since C does not support or recognize the extern keyword. It is C++ that provides the mechanisms for mixing C and C++ codes in the same program. To be precise, C++ supports mixing codes that are compiled by C and C++ compatible compilers in the same program.

If the C header is already defined and it does not have all the APIs defined under extern "C", then while including such a header in C++ source or header files, extern "C" should be used as in the example below:

/*File: PureCHeader.h */
/* If C++ header/source files need to include this header, extern "C" should be used*/
/* Define all C APIs here*/
void Function1(int, int);
char* Function3(char*, int);
int Function2(int);
#endif

//File: CSource.cpp
// C++ source file using PureCHeader.h
extern "C" {
#include "PureCHeader.h"
}
void Foo() {
   // use those C APIs here
   int ret = Function2(10);
}

Mixing C and C++ features using extern "C"

The developer can use all the features of C++ except templates within C by giving those functions extern "C" linkage. See the example below:

#include <iostream>
using namespace std;

extern "C" {

//Can give C linkage to this class!!
class Sample{
public:
   Sample(int a = 10) : iMem(a) { }
   void Display() { cout<<"iMem is : "<<iMemendl; }

private:
   int iMem;
};

/*
//Can not  give C linkage to template!!
//If we uncomment this code, then it will give a compilation error.
template<class DataType> void Foo(DataType data) {
}*/
}

Extending C codes with C++ Codes

Using C linkage, C codes like structures and functions that manipulate those structures can be extended efficiently in a C++ source file as in the example below:

/* File: CHeader.h */

typedef struct{
   char* name;
   int id;
   float price;
} Item;

int Push(Item* item);
int Pop(Item* item);

/* File: CppHeader.h */
//Give external linkage to C structure
extern "C" {
# include "CHeader.h"
}

class MyStack : public Item {
public:
   MyStack(char* aName, int aId, float aPrice) : name(aName), id(aId), price(aPrice) { }
   int PushOnToStack() { return Push(this);}
   int PopFromStack() { return Pop(this); }
};

Give feedback of this section

©Nokia 2006

Back to top

This material, including documentation and any related computer programs, is protected by copyright controlled by Nokia. All rights are reserved. Copying, including reproducing, storing, adapting or translating, any or all of this material requires the prior written consent of Nokia. This material also contains confidential information, which may not be disclosed to others without the prior written consent of Nokia.

Nokia is a registered trademark of Nokia Corporation. S60 and logo is a trademark of Nokia Corporation. Java and all Java-based marks are trademarks or registered trademarks of Sun Microsystems, Inc. Other company and product names mentioned herein may be trademarks or tradenames of their respective owners.


$title

S60 Open C
Intermixing C and C++

Intermixing C and C++

Table of Contents

extern "C" and Symbian DEF files
Rule for using extern "C"
Example code
Building for WINSCW
Building for ARMv5

extern "C" and Symbian DEF files

This article gives a general idea about the Symbian DEF file. Whenever developers write any DLLs that export a set of APIs to the user, there will be an entry for each exported API in the DEF file created. The developer will use:

  • IMPORT_C while declaring exported APIs
  • EXPORT_C while defining such APIs

After building the application for the first time, it will list all the newly exported APIs. After doing a freeze (for which the abld freeze winscw and abld freeze armv5 commands are used), the DEF files will be created under BWINS and EABI folders within the project directory. These DEF files are used to create .lib files for DLLs. In the DEF file, for each exported API, there will be mapping between its prototype and a number will be present.

Let's assume that directory structure used for implementing a library is as shown below:

  • LibraryName\group -- bld.inf and LibraryName.mmp (all build-related files)
  • LibraryName\inc -- All project-specific headers (user include headers)
  • LibraryName\src -- All project-specific source files

If a developer is building the library for the first time, the developer should follow these steps and give the following commands from LibraryName\group:

  1. Create the abld.bat file for the project.
    LibraryName\group>bldmake bldfiles
  2. Builds the project for the default platform (which will be WINSCW and ARMV5).
    LibraryName\group>abld build
  3. Create the DEF file for the default platform (LibraryName\BWINS\LibraryNameu.def and LibraryName\EABI\LibraryNameu.def).
    LibraryName\group>abld freeze
  4. Create .lib files for the DLL using DEF file entries. (LibraryName.lib)
    LibraryName\group> abld build

The final step is required since applications that link with this library (LibraryName.DLL) will link with LibraryName.lib during link time. If the developer fails to perform the final step, the application will get a linker error because there is no LibraryName.lib present.

Rule for using extern "C"

When porting or writing libraries that export C APIs to the user, care should be taken to ensure that extern "C" is used properly if those APIs are implemented in a C++ source file. Otherwise these libraries may either not be built for the target platform (ARMV5) or the user of such library will get a linker error when using exported APIs of such library.

If extern "C" is declared in the header and not defined in the source, then after building the library there will be a similar entry in DEF files. The compiler will not give external linkage to these APIs. This can be observed when trying to use these APIs from some other C source file. To overcome this, extern "C" must be present in both declarations and definitions.

Example code

/*File: SampleDLL.h*/
/*extern "C" is not used for declaration!*/
#ifndef SAMPLEDLL_H
#define SAMPLEDLL_H

typedef int MyInt;
typedef int (*MyFunPtr) ();

IMPORT_C int MyLibLibFun1(MyInt aParam);
IMPORT_C int MyLibLibFun3(MyFunPtr);
IMPORT_C int MyLibLibFun2(int (*MyFun1)());

#endif /*SAMPLEDLL_H*/

//File: SampleDLL.cpp
#include "SampleDLL.h"
// extern "C" is used for definition
extern "C"  {

EXPORT_C int MyLibLibFun1(MyInt aParam)
   {
   return aParam + 10;
   }

EXPORT_C int MyLibLibFun2(int (*MyFun1)())
   {
   return MyFun1();
   }

EXPORT_C int MyLibLibFun3(MyFunPtr aPtr)
   {
   return aPtr();
   }
}

Building for WINSCW

This code will get compiled for WINSCW. The DEF file for WINSCW will have the following entries:

EXPORTS
     ?MyLibLibFun1@@YAHH@Z @ 1 NONAME ; int MyLibLibFun1(int)
     ?MyLibLibFun2@@YAHP6AHXZ@Z @ 2 NONAME ; int MyLibLibFun2(int (*)(void))
     ?MyLibLibFun3@@YAHP6AHXZ@Z @ 3 NONAME ; int MyLibLibFun3(int (*)(void))

Even if we comment extern "C" from the above SampleDLL.cpp file, we will have the same DEF file entries.

Building for ARMv5

If we try the above code without extern "C" in SampleDLL.cpp, the code will get built and the DEF file entry for ARMv5 will be:

EXPORTS
     _Z12MyLibLibFun1i @ 1 NONAME
     _Z12MyLibLibFun2PFivE @ 2 NONAME
     _Z12MyLibLibFun3PFivE @ 3 NONAME

If we keep the extern "C" in SampleDLL.cpp, this code will not get compiled for ARMv5 and will result in the error given below:

"..\src\Sampledll.cpp", line 7: Error:  #337: linkage specification is incompatible with previous "MyLibLibFun1" (declared at line 9 of "..\inc\SampleDLL.h")
   EXPORT_C int MyLibLibFun1(MyInt aParam)
                ^
"..\src\Sampledll.cpp", line 17: Error:  #337: linkage specification is incompatible with previous "MyLibLibFun3" (declared at line 11 of "..\inc\SampleDLL.h")
   EXPORT_C int MyLibLibFun3(MyFunPtr aPtr)
               ^

The reason for the errors is that MyLibLibFun1 and MyLibLibFun3 use typedef datatypes. There is no issue with MyLibLibFun2() since it does not use typedef datatypes. To overcome these errors, we have to keep both the declaration and the definition within extern "C" linkage.

/*File: SampleDLL.h*/
#ifndef SAMPLEDLL_H
#define SAMPLEDLL_H
/*extern "C" is used for declaration also*/

typedef int MyInt;
typedef int (*MyFunPtr) ();

#ifdef __cplusplus
extern "C" {
#endif //__cplusplus

IMPORT_C int MyLibLibFun1(MyInt aParam);
IMPORT_C int MyLibLibFun3(MyFunPtr);
IMPORT_C int MyLibLibFun2(int (*MyFun1)());

#ifdef __cplusplus
}
#endif //__cplusplus

#endif /*SAMPLEDLL_H*/

When everything is within extern "C" (extern "C" in header and implementation), the DEF file for ARMv5 and WINSCW looks as follows:

EXPORTS
    MyLibLibFun1 @ 1 NONAME
    MyLibLibFun2 @ 2 NONAME
    MyLibLibFun3 @ 3 NONAME

So, as one can observe in the above section where different DEF file entries are created with and without extern "C", we should make sure that the rule is followed. extern "C" has to be used in both declaration and definition: otherwise we will either not be able to build it for all the platforms or it will not be possible to use those exported C APIs in other applications.

Give feedback of this section

©Nokia 2006

Back to top

This material, including documentation and any related computer programs, is protected by copyright controlled by Nokia. All rights are reserved. Copying, including reproducing, storing, adapting or translating, any or all of this material requires the prior written consent of Nokia. This material also contains confidential information, which may not be disclosed to others without the prior written consent of Nokia.

Nokia is a registered trademark of Nokia Corporation. S60 and logo is a trademark of Nokia Corporation. Java and all Java-based marks are trademarks or registered trademarks of Sun Microsystems, Inc. Other company and product names mentioned herein may be trademarks or tradenames of their respective owners.


Localization

Locale support in POSIX vs SYMBIAN
Character conversion in Symbian and GNU C compared

© Nokia 2007

Back to top


$title

S60 Open C
Open C Localization

Open C Localization

Table of Contents

Locale support in POSIX vs Symbian
POSIX
Categories supported in POSIX
Implementation in POSIX
Symbian OS

Locale support in POSIX vs Symbian

POSIX

Locale defines the subset of a user's environment that depends on language and cultural conventions. It is made up from one or more categories. Each category is identified by its name and controls specific aspects of the behavior of components of the system's components.

The convention followed in POSIX to identify the locale is as follows:

language_territory.codeset@modifier

  • Language is an ISO 639 language code.
  • Territory is an ISO 3166 country code.
  • Code set is a character set or encoding identifier like ISO-8859-1, ISO-9959-2 and so on.

Example: en_US.ISO-8859-1, where en represents English language, US represents the United States of America, and ISO-8859-1 is the character set.

Categories supported in POSIX

  • LC_CTYPE: For regular expression matching, character classification, conversion, case-sensitive comparison, and wide character functions.
  • LC_COLLATE: For regular expression matching (it determines the meaning of range expressions and equivalence classes) and string collation.
  • LC_MONETARY: For monetary formatting
  • LC_NUMERIC:For number formatting (such as the decimal point and the thousands separator).
  • LC_TIME: For time and date formatting.
  • LC_MESSAGES : For localizable natural-language messages.

NOTE! The Symbian OS implementation supports only the LC_MONETARY, LC_NUMERIC, and LC_TIME categories.

Implementation in POSIX

Character set information is stored as text files in the /usr/share/i18n/charmaps/ directory.

The entry in the file looks as shown below :

<U0030> /x30 DIGIT ZERO, where U0030 is a UNICODE-16 value and x30 is an ISO-8859-1 value, which is followed by the description of the character. Locale information related to a particular country is stored in a locale definition file in the text format in the/usr/share/i18n/locales/ directory.

NOTE! The Symbian OS implementation does not use the above-mentioned mechanisms for character sets or for storing locale information.

Symbian OS

In Symbian OS locale-specific information is built as a DLL. The user can change the locale information related to a specific country by loading the appropriate DLL.

The convention followed in naming the DLL is as follows:

elocl.language_index - The list of languages supported by Symbian OS is enumerated in TLanguage. Each value in the TLanguage enumeration uniquely identifies a language. TLanguage enumeration can be found in the e32Const.h header file.

Examples:

  • ELangEnglish and DLL name is elocl.01.
  • ELangFrench and DLL name is elocl.02.
  • ELangGerman and DLL name is elocl.03.
  • ELangFinnish and DLL name is elocl.09.

Symbian OS provides the TLocale class to set the system-wide locale settings and to retrieve system-wide locale setting. The TLocale class provides methods for setting the following information: calendar settings, country code, currency format, date and time formatting, numeric values, time zone information, and units of distance.

In Symbian OS most applications do not need to change the locale settings; they just use the system setting instead.

The user can load the appropriate locale-specific DLL to fetch the locale data. The function given below is a way to fetch the locale-specific information.

void LoadLanguageDLL()
{
  //Finnish
  _LIT(KDllName, "elocl.09");
  RLoader loader;
  TInt r = loader.Connect();
  if(KErrNone == r)
  {
    //Load the language variant DLL
    TInt size = KNumLocaleExports * sizeof(TLibraryFunction);
    TPtr8 functionListBuf((TUint8*) data, size, size);
    r = loader.SendReceive(ELoadLocale, TIpcArgs(0, KDllName, &functionListBuf ) );
    if(KErrNone == r)
    {
     ((TLibFn)data[FnLocaleData])(&iLocale);
     retVal = (TText*) aLocale.Ptr();
    }
    loader.Close();
  }
}

Setting the locale by writing a program in POSIX is easier compared to the locale settings in Symbian OS. In POSIX the user does not need to be aware of the locale information, whereas in Symbian OS the user should be aware of it.

Example: The code below sets the monetary information of Finland using POSIX:

#include <stdio.h>
#include <locale.h>
int main()
{
  //before fetching the monetray information it is assumed that locale is set to finnish
  struct lconv* localeinfo = localeconv();
  return 0;
}

The lconv structure has the complete monetary information.

The code below sets the monetary information of Finland using Symbian C++:

#include <e32std.h>
void doExampleL()
{
  TLocale locale;
  locale. SetCurrencySymbolPosition(ELocaleAfter);
  locale. SetCurrencySpaceBetween(ETrue);
  locale. SetCurrencyDecimalPlaces(2);
  locale. SetCurrencyTriadsAllowed(ETrue);
  locale. SetNegativeCurrencyFormat(TLocale::ELeadingMinusSign);
  //similarly other monetary information should be set individually.
}

Give feedback of this section

©Nokia 2006

Back to top

This material, including documentation and any related computer programs, is protected by copyright controlled by Nokia. All rights are reserved. Copying, including reproducing, storing, adapting or translating, any or all of this material requires the prior written consent of Nokia. This material also contains confidential information, which may not be disclosed to others without the prior written consent of Nokia.

Nokia is a registered trademark of Nokia Corporation. S60 and logo is a trademark of Nokia Corporation. Java and all Java-based marks are trademarks or registered trademarks of Sun Microsystems, Inc. Other company and product names mentioned herein may be trademarks or tradenames of their respective owners.


$title

S60 Open C
Open C Localization

Open C Localization

Table of Contents

Character conversion in Symbian C++ and GNU C compared

Character conversion in Symbian C++ and GNU C compared

Symbian C++ supports character conversion between Unicode and other native character sets.

GNU C supports character conversion:

  • between Unicode and other native character sets
  • from a native character set to another native character set.

The following example illustrates the steps to be followed to convert from one native character set to another native character set. In GNU C it is straightforward. In Symbian C++ more lines of code are needed to do the same work. The example converts a string from the ISO-8859-1 character set to the ISO-8859-2 character set.

GNU C

#include <iconv.h>
#include <stddef.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>

int main (void)
{
 iconv_t cd;
 const char *inbuf = "abcd";
 char *outbuf = NULL;;
 size_t inbytes,outbytes;
 cd = iconv_open ("ISO-8859-2", "ISO-8859-1");
 if (cd == (iconv_t) -1)
 {
   printf ("iconv_open failed errno = %d\n",errno);
   iconv_close(cd);
   return 1;
 }
 outbuf = (char*) malloc(4);
 inbytes = outbytes = 4 ;
 iconv (cd, &inbuf, &inbytes, &outbuf, &outbytes);
 if (iconv (cd, &inbuf, &inbytes, &outbuf, &outbytes) == (size_t) -1)
     printf(" errno = %d \n",errno);
 else
       printf("Iconv passed\n");
 iconv_close (cd);
 return 1;
}

SYMBIAN C++

  • Specify the non-Unicode character set being converted to Unicode. In this case it is ISO-8859-1.
  • Convert the text from the native character set to Unicode.
  • Specify the non-Unicode character set being converted from Unicode. In this case it is ISO-8859-2
  • Convert the text from Unicode to the native character set
#include <e32base.h>
#include <e32cons.h>
#include <charconv.h>
#include <f32file.h>
#include <string.h>
#include <stdlib.h>
LIT8(KNativeText, "abcd");
LOCAL_C int doExampleL()
{
   char *inbuf = "abcd";
   char *outbuf = NULL;
   int inbytes,outbytes;
   inbytes = outbytes = 4;

   TInt retVal = KErrNone;
   outbuf = (char*) malloc(outbytes);
   RFs fileSession;
   User::LeaveIfError(fileSession.Connect());
   CleanupClosePushL(fileSession);

  //Allocates and constructs a CCnvCharacterSetConverter object
  CnvCharacterSetConverter* conv = CCnvCharacterSetConverter::NewLC() ;
  TPtrC8 remainderOfForeignText((const TText8*) inbuf,inbytes);
  TBuf16<256> UnicodeText;
  TBuf8<256> outputBuffer;
  TInt numberOfUnconvertibleCharacters = 0;
  TInt indexOfFirstByteOfFirstUnconvertibleCharacter = 0;
  //Specifies the character set(ISO-8859-1) to convert to UNICODE
  CCnvCharacterSetConverter::TAvailability  avail = conv->PrepareToConvertToOrFromL (KCharacterSetIdentifierIso88591, fileSession);
 if(CCnvCharacterSetConverter::ENotAvailable == avail)
 {
   CleanupStack::PopAndDestroy(2);  //conv, fileSession
   return KErrGeneral;
 }
 //Convert text encoded in the ISO-8859-1 character set into the Unicode character set (UCS-2).
 retVal = conv->ConvertToUnicode(UnicodeText, remainderOfForeignText, numberOfUnconvertibleCharacters, indexOfFirstByteOfFirstUnconvertibleCharacter);
 if(retVal < 0 && (retVal != CCnvCharacterSetConverter::EErrorIllFormedInput))
 {
  CleanupStack::PopAndDestroy(2);  //conv, fileSession
  return retVal;
 }
 //Specifies the character set(ISO-8859-2) to convert from UNICODE
 avail = conv->PrepareToConvertToOrFromL(KCharacterSetIdentifierIso88592, fileSession);
 if(CCnvCharacterSetConverter::ENotAvailable == avail)
 {
   CleanupStack::PopAndDestroy(2);  //conv, fileSession
   return KErrGeneral;
 }
 //Convert text encoded in the Unicode character set (UCS-2) to  ISO-8859-2
 retVal = conv->ConvertFromUnicode(outputBuffer,UnicodeText, numberOfUnconvertibleCharacters, indexOfFirstByteOfFirstUnconvertibleCharacter);
 if(retVal < 0 && (retVal != CCnvCharacterSetConverter::EErrorIllFormedInput))
 {
   CleanupStack::PopAndDestroy(2);  //conv, fileSession
   return retVal;
 }
 TInt outputbufferLength = outputBuffer.Length();
 strncpy(outbuf, (const char*) outputBuffer.Ptr(),outputbufferLength);
 outbuf = outbuf + outputbufferLength;
 CleanupStack::PopAndDestroy(2); //conv, fileSession
 return retVal;
}

Currently Symbian C++ supports around 50 character sets, while GNU C supports more number of character sets. A list of the character sets supported in Symbian C++ can be found in the charconv.h header file.

Give feedback of this section

©Nokia 2006

Back to top

This material, including documentation and any related computer programs, is protected by copyright controlled by Nokia. All rights are reserved. Copying, including reproducing, storing, adapting or translating, any or all of this material requires the prior written consent of Nokia. This material also contains confidential information, which may not be disclosed to others without the prior written consent of Nokia.

Nokia is a registered trademark of Nokia Corporation. S60 and logo is a trademark of Nokia Corporation. Java and all Java-based marks are trademarks or registered trademarks of Sun Microsystems, Inc. Other company and product names mentioned herein may be trademarks or tradenames of their respective owners.


Porting Guides and Tricks

OSS Porting Using Open C
How to export global data from a DLL
How to initialize a library
String conversions
Mapping standard C library error codes to Symbian error codes
Possibilities of panic and crash
Calling Symbian asynchronous APIs in an Open C application

© Nokia 2007

Back to top


OSS Porting Using Open C

Overview
Analysis of OSS
Preparation of MMP file and bld.inf
Compilation and build process in Symbian OS
Troubleshooting - some tips and tricks

© Nokia 2007

Back to top


$title

S60 Open C
Porting Illustrated: Effective Guide to OSS Porting using Open C

Porting Illustrated: Effective Guide to OSS Porting using Open C

Table of Contents

Overview

Overview

Symbian OS is a typical platform for open source software (OSS) but with the availability of the Open C platform, developing and porting OSS has become easier and quicker. Issues such as size, and licensing are some of the things that the developer must carefully analyze before porting.

Give feedback of this section

©Nokia 2006

Back to top

This material, including documentation and any related computer programs, is protected by copyright controlled by Nokia. All rights are reserved. Copying, including reproducing, storing, adapting or translating, any or all of this material requires the prior written consent of Nokia. This material also contains confidential information, which may not be disclosed to others without the prior written consent of Nokia.

Nokia is a registered trademark of Nokia Corporation. S60 and logo is a trademark of Nokia Corporation. Java and all Java-based marks are trademarks or registered trademarks of Sun Microsystems, Inc. Other company and product names mentioned herein may be trademarks or tradenames of their respective owners.


$title

S60 Open C
Porting Illustrated: Effective Guide to OSS Porting using Open C

Porting Illustrated: Effective Guide to OSS Porting using Open C

Table of Contents

Analysis of OSS
Installing Linux packages in Linux
Directory analysis
Tips and tools

Analysis of OSS

This section explains the tools and tips for effective analysis of Linux OSS.

Installing Linux packages in Linux

  • Get the latest stable release of OSS from the Internet. Usually OSS come a in compressed format like .tar, .gz, or bz2.
  • Run the configure script using the following command: ./configure. It will look for dependency and creates makefiles.
  • Compile the code using make tool.
  • Copy the files to the target path using the command make install.

Directory analysis

OSS creates the following three subdirectories in the installation directory: include, lib, and bin. These directories contain valuable information required for porting, as explained below:

  • include – This directory contains the user include files that need to be exported to the proper export directory in Symbian OS.
  • lib – This directory gives an idea of the size of the library. It contains libraries built as a result of OSS compilation. Each of these requires an individual MMP file.

    NOTE: Symbian OS compilers produce much smaller-sized libraries than what there are in Linux.

    Linux Symbian OS

    .SO extension for dynamic libraries

    .DLL extension for dynamic libraries

    .A extension for static libraries

    .LIB extension for static libraries
  • bin – This directory contains the executable built during the compilation of OSS.
  • man – This directory contains the man pages of OSS.

Tips and tools

Tools like nm, ldd, and dumpbin are useful in OSS porting:

  • ldd – A Linux tool that can be used to find the dependency library list and overall size of the library, obtained by adding the size of all the dependent libraries. In many cases, to build library 'X' another library 'Y' is needed.
  • nm – Another Linux tool that prints the symbol table in alphabetical order from one or more object files.
  • dumpbin – A Windows-based tool that can be used if Windows port is available for OSS. It gets the list of exported symbols.

The following command can be used to install the software in the user directory:

 ./configure --prefix=$HOME/<foo>

The following commands can be used to decompress the file:

tar -xvjf archivefile.tar.bz2
tar -zxvf archivefile.tar.bz2

At the end of installing the OSS in Linux, it is good to update the environment variables PKG_CONFIG_PATH and LD_LIBRARY_PATH. One of the many ways to initialize environment variables is to add them in the .bash_rc file.

Makefile gives subtle information about the project. SOURCES in Makefile gives an idea about the source files of the OSS. These files have to be listed in SOURCE in the MMP file.

-D<Foo> in Makefile gives the list of preprocessor declarations. These preprocessor declarations can be done using MACRO in the MMP file.

Give feedback of this section

©Nokia 2006

Back to top

This material, including documentation and any related computer programs, is protected by copyright controlled by Nokia. All rights are reserved. Copying, including reproducing, storing, adapting or translating, any or all of this material requires the prior written consent of Nokia. This material also contains confidential information, which may not be disclosed to others without the prior written consent of Nokia.

Nokia is a registered trademark of Nokia Corporation. S60 and logo is a trademark of Nokia Corporation. Java and all Java-based marks are trademarks or registered trademarks of Sun Microsystems, Inc. Other company and product names mentioned herein may be trademarks or tradenames of their respective owners.


$title

S60 Open C
Porting Illustrated: Effective Guide to OSS Porting using Open C

Porting Illustrated: Effective Guide to OSS Porting using Open C

Table of Contents

Preparation of the MMP file and bld.inf
MMP file
bld.inf

Preparation of the MMP file and bld.inf

At the end of this phase, Symbian port should have the bld.inf and MMP files.

MMP file

An .mmp project definition file specifies the properties of a project in a platform and compiler-independent way. The MMP file is very similar to ‘Makefile’ of Linux. MMP file exists per .SO, .A, or .EXE .

The contents of a sample MMP file created for libjpeg are shown below:

TARGET	libjpeg.dll
TARGETTYPE	DLL
UID             	0x1000008d 0x0xE0000100
CAPABILITY All -Tcb
EpocAllowDllData

USERINCLUDE	.

SYSTEMINCLUDE	\epoc32\include\stdapis
SYSTEMINCLUDE	\epoc32\include

SOURCEPATH	.
// LIBSOURCES
SOURCE	jcapimin.c jcapistd.c jccoefct.c jccolor.c jcdctmgr.c jchuff.c
SOURCE	jcinit.c jcmainct.c jcmarker.c jcmaster.c jcomapi.c jcparam.c
SOURCE	jcphuff.c jcprepct.c jcsample.c jctrans.c jdapimin.c jdapistd.c
SOURCE	jdatadst.c jdatasrc.c jdcoefct.c jdcolor.c jddctmgr.c jdhuff.c
SOURCE	jdinput.c jdmainct.c jdmarker.c jdmaster.c jdmerge.c jdphuff.c
SOURCE	jdpostct.c jdsample.c jdtrans.c jerror.c jfdctflt.c jfdctfst.c
SOURCE	jfdctint.c jidctflt.c jidctfst.c jidctint.c jidctred.c jquant1.c
SOURCE	jquant2.c jutils.c jmemmgr.c
// SYSDEPSOURCES
SOURCE	jmemansi.c
LIBRARY	euser.lib

LIBRARY	libc.lib
MACRO	HAVE_CONFIG_H
MACRO 	__SYMBIAN32__

The following table gives a brief introduction to the MMP file keywords found in above file. See Symbian OS technical reference for more details.

Keyword | Description
TARGETTYPE | Target type.Can be DLL, EXE, or LIB. Other types are also supported. For more information, seehttp://www.symbian.com/Developer.
TARGET | Name of the target.
UID | Unique identifier of the target. It is recommended to use test UIDs from the range 0xE0000000-0xEFFFFFFF which is targeted for development use only. For production quality code, UIDs must be requested from Symbian(https://www.symbiansigned.com/app/page) before the application can be sent for signing.
CAPABILITY | Capability requirement of the target. NOTE! Even if the example uses All-TCB capabilities, it is strongly recommended to use a more narrow set of capabilities to have the application successfully signed. For more information, see http://www.symbian.com/Developer.
EpocAllowDllData | Allow global static data in the target
USERINCLUDE | Local file include path. The compiler will look in this path for the files included with “ ”. For example#include "config.h"
SYSTEMINCLUDE | System file include path. The compiler will look in this path for the files included with < >. For example #include <stdio.h>
SOURCEPATH | Source path for the source files.s
SOURCE | Source file listing.
LIBRARY | Dependent DLL library file list.
STATICLIBRARY | Dependent static library file list.
MACRO | Preprocessor declarations. Makefile declares these preprocessor declarations using –D flag.

bld.inf

bld.inf is a component definition file, used by bldmake to define the abld.bat and makefiles to be created. bld.inf can be loosely compared to configure script of Linux. There is one bld.inf for entire the OSS. If the project is divided into more than one module, each module can have an individual bld.inf file. Have a look at the contents of the sample MMP file below created for libjpeg.

PRJ_PLATFORMS
default

PRJ_MMPFILES
jpeg.mmp

PRJ_EXPORTS
jpeglib.h   \epoc32\include\jpeg-6b\jpeglib.h
jconfig.h   \epoc32\include\jpeg-6b\jconfig.h
jmorecfg.h  \epoc32\include\jpeg-6b\jmorecfg.h
jerror.h    \epoc32\include\jpeg-6b\jerror.h

The following table gives a brief introduction to the bld.inf keywords.

Keyword | Description
PRJ_PLATFORMS | Platform to which makefiles will be created
PRJ_MMPFILES | MMP file list
PRJ_EXPORTS | List of public header files for target library users. This list can be prepared by looking at the include directory in Linux installation.

Give feedback of this section

©Nokia 2006

Back to top

This material, including documentation and any related computer programs, is protected by copyright controlled by Nokia. All rights are reserved. Copying, including reproducing, storing, adapting or translating, any or all of this material requires the prior written consent of Nokia. This material also contains confidential information, which may not be disclosed to others without the prior written consent of Nokia.

Nokia is a registered trademark of Nokia Corporation. S60 and logo is a trademark of Nokia Corporation. Java and all Java-based marks are trademarks or registered trademarks of Sun Microsystems, Inc. Other company and product names mentioned herein may be trademarks or tradenames of their respective owners.


$title

S60 Open C
Porting Illustrated: Effective Guide to OSS Porting using Open C

Porting Illustrated: Effective Guide to OSS Porting using Open C

Table of Contents

Compilation and build process in Symbian OS
Creating PKG file and Installation file for the Target

Compilation and build process in Symbian OS

This article discusses a few basic things about the compilation and build process in Symbian OS. Refer to the public S60 C++ SDK documentation for more details.

The bldmake tool processes the component description file bld.inf in the current directory and generates the batch file abld.bat and several build batch makefiles (.make) . The makefiles are used by abld to carry out the various stages of building the component.

The basic usage of abld command is:
abld command[options][platform][build][program]
This enables the programmer to build for different platforms with varied specifications. The parameter command specifies which action to perform to the abld tool. The actions can be build, clean, cleanexport, etc. The parameteroptions includes –c, -w etc., these enable the user to check for the presence of releasables etc. The parameter platform specifies the platform for which the project will be built. The platform can be WINSCW, GCCE, GCCXML, EDG, ARMV5, VS6, CW_IDE or VS2003. The parameter build specifies whether to build for debug (udeb) or release (urel) version. Finally the parameter program specifies which project definition file or mmp file to build. If left unspecified, all the MMP files mentioned in the bld.inf file are built.

For more details logon to http://www.symbian.com/Developer

The example below demonstrates the use of bldmake:

bldmake bldfiles

The abld build command compiles and links the target.

abld build

The abld freeze command freezes the project export. This is needed only for DLLs.

abld freeze

Give feedback of this section

Creating PKG file and Installation file for the Target

A package (PKG) file is a text file containing items or statements that define the information required by the installation (SIS) file creation utility makesis. The PKG file format can be broken down into the following items:

  • Languages
  • Language code table
  • Package-header
  • Vendor
  • Logo
  • Package-signature
  • Package-body
  • Dependency
  • Properties

For more information on PKG files seehttp://www.symbian.com/developer/techlib/v9.1docs/doc_source/n10356/installing-ref/pkg_format/index.html.

The makesis utility creates software installation packages (SIS files) based on the information and the file locations on the source PC or target phone, defined in a package (PKG) file.

For example, consider the code snippet given below:
makesis somefile.pkg
The code goes through the PKG file and by default creates somefile.sis in the directory where the PKG file is present.

For more information on the makesis utility seehttp://www.symbian.com/Developer.

After creating the SIS file it, has to be signed using signsisto install it on the phone. Signsis is a Symbian supplied tool to digitally sign software installation (SIS) files using a specified certificate and private key. For example consider the code snippet given below:

signsis somefile.sis somefile.sisx rd.cer rd-key.pem
The parameter somefile.sis gives, the path to the SIS file which is to be signed. The second parameter, somefile.sisx specifies the name of the resultant signed SIS file. The third parameter, rd.cer specifies the path to the certificate file and the last parameter, rd-key.pem specifies the path to the file containing the private key.

For more information on signsis utility seehttp://www.symbian.com/developer/techlib/v9.1docs/doc_source/n10356/installing-ref/signsistoolreference.guide.html.

Give feedback of this section

©Nokia 2006

Back to top

This material, including documentation and any related computer programs, is protected by copyright controlled by Nokia. All rights are reserved. Copying, including reproducing, storing, adapting or translating, any or all of this material requires the prior written consent of Nokia. This material also contains confidential information, which may not be disclosed to others without the prior written consent of Nokia.

Nokia is a registered trademark of Nokia Corporation. S60 and logo is a trademark of Nokia Corporation. Java and all Java-based marks are trademarks or registered trademarks of Sun Microsystems, Inc. Other company and product names mentioned herein may be trademarks or tradenames of their respective owners.


$title

S60 Open C
Porting Illustrated: Effective Guide to OSS Porting using Open C

Porting Illustrated: Effective Guide to OSS Porting using Open C

Table of Contents

Troubleshooting - some tips and tricks
Symbian directory structure
EXPORT_C, DEF file and ordinal numbers
dlsym or g_module_symbol
Problem with a variable list of arguments in macros
Symbian compiler performs strict type checking
Keep changes to OSS to a minimum
Exporting variables from a DLL
Application is not loaded
Dynamic array allocation
Capabilities not known
Environment variables
Assembly code
Glossary

Troubleshooting - some tips and tricks

This section addresses the basic differences in the way things are done in Symbian OS and in Linux.

  • Symbian directory structure
  • EXPORT_C, DEF file, and ordinal numbers
  • dlsym or g_module_symbol
  • Problem with a variable list of arguments in macros
  • Symbian compiler performs strict type checking
  • Keep changes to OSS to a minimum
  • Exporting variables from a DLL
  • Application is not loaded
  • Dynamic array allocation
  • Capabilities not known
  • Environment variables
  • Assembly code
  • Glossary

Symbian directory structure

In Symbian OS, project source files are arranged based on the directory pattern sown below.

Directory | Description
src | Contains all the source files of the project.
inc | Contains all the header files of the project.
group | Contains MMP files, and bld.inf.

The developer can choose whether to follow this strictly.

EXPORT_C, DEF file and ordinal numbers

This applies only for the DLL target type. If a DLL wants to export an API, the code definition should start with the macro EXPORT_C.

// Declaration
#ifdef SYMBIAN
#define GLOBAL(type)		EXPORT_C type
#else
#define GLOBAL(type)		type
#endif // SYMBIAN
 // Definition
 GLOBAL(void)
 jpeg_CreateDecompress (j_decompress_ptr cinfo, int version, size_t structsize)
 {
   int i;

   /* Guard against version mismatches between library and caller. */
   cinfo->mem = NULL;		/* so jpeg_destroy knows mem mgr not called */
   if (version != JPEG_LIB_VERSION)
     ERREXIT2(cinfo, JERR_BAD_LIB_VERSION, JPEG_LIB_VERSION, version);
   if (structsize != SIZEOF(struct jpeg_decompress_struct))
     ERREXIT2(cinfo, JERR_BAD_STRUCT_SIZE,
          (int) SIZEOF(struct jpeg_decompress_struct), (int) structsize);
 ...
 }
Whenever a DLL is built on Symbian OS, it creates three files:
  • <target>.dll is the actual DLL that gets loaded at runtime
  • <target>.lib is the static library which contains wrappers for each DLL exported function that, when run, will locate and execute the real function’s code in the appropriate runtime-loaded DLL.
  • <target>.def gets created when the user executes abld freeze. The .def file contains the list of exported DLL functions along with their ordinal numbers. Symbian OS does not store exported symbol names in DLL; instead, the exported functions are referenced using only their ordinal numbers. Storing the ordinal numbers instead of names reduces the size of the DLL.

The following is a sample .def file created for libjpeg:.

EXPORTS
jcopy_block_row @ 1 NONAME
jcopy_sample_rows @ 2 NONAME
jdiv_round_up @ 3 NONAME
jinit_1pass_quantizer @ 4 NONAME
jinit_2pass_quantizer @ 5 NONAME
jinit_c_coef_controller @ 6 NONAME
jinit_c_main_controller @ 7 NONAME
jinit_c_master_control @ 8 NONAME
jinit_c_prep_controller @ 9 NONAME
jinit_color_converter @ 10 NONAME

The following example shows how to declare and define an exportable function from a DLL and to make it callable from a Symbian C++ application:

In xxx.h

#ifdef __cplusplus
extern "C"
#endif
IMPORT_C int Foo();

In xxx.c

extern "C" EXPORT_C int Foo()
    {
    return something;
    }

dlsym or g_module_symbol

Since DLL entry points are not exported by name, DLL symbol lookup functions do not work in Symbian OS. The functions dlsym from libdl and g_module_symbol from glib are examples of such functions. Look for usage of these functions in the OSS port and change the code. For example:

ret = g_module_symbol (module, "jinit_c_prep_controller", &ptr);

needs to be changed to:

ret = g_module_symbol (module, "9", &ptr);

Problem with a variable list of arguments in macros

This section suggests a way to overcome the problems faced when macros with a variable list of arguments are used.

#define DEBUG(a,...)

The above statement causes a compilation error. One of the solutions to solve this problem is as follows:

#define DEBUG _DEBUG
static inline void _DEBUG (const char *a, ...)
{
}

Symbian compiler performs strict type checking

Type casting is typically required in many places in OSS code. Sometimes preprocessing a particular file and analyzing the preprocessed file gives many hints about the possible errors.

Consider the following code snippet:

char * buf=”hello world”;
 int i= buf;
The code compiles with a warning with GCC compiler on Linux but gives rise to an error with Symbian compiler.

Keep changes to OSS to a minimum

While porting the OSS code, keep the changes to the OSS code as few as possible. The OSS code is already tested and used by a bigger community, and is unlikely to have any compilation errors or major logical errors. In many cases code changes that are necessary brings potential logical flaws to the OSS port. Minimum changes to the OSS code while porting also helps in merging to the new OSS.

Exporting variables from a DLL

Exporting data from a DLL is not allowed in Symbian OS . The following pattern can be used:

  1. Do not export global variables.
  2. Export one method that returns a pointer to that variable.
  3. Define a macro for the user of the DLL. See the example below

1. Do not export global variables.

Within DLL, there is one global variable, for example:

int globalVal;

2. Export one method that returns a pointer to that variable

extern "C" EXPORT_C int* GlbData ()
    {
    return &globalVal
    }

3. Define a macro for the user of the DLL

Within the DLL header (e.g.,xxx.h), define the following:
#ifdef __cplusplus
extern "C"
#endif
IMPORT_C int* GlbData ();
#define globalVal (*GlbData())

Application is not loaded

The absence of the dependent libraries could be one of the reasons for the application not to load in the mobile device. On the target device, Symbian OS looks for libraries in
  • c:\sys\bin or in
  • z:\sys\bin
Do make sure that all the libraries are present in either of the above-mentioned libraries.

Dynamic array allocation

Statements such as int counts[2*size]; are not allowed in Symbian C++. An alternative would be to create counts dynamically and free the memory after its usage.

Capabilities not known

Capabilities are specified in the MMP file. The primary information source is the Open C API reference documentation. If problems with capabilities remain, one known method to find the capability is to analyze the [Debug Messages] window in CodeWarrior IDE (while debugging). During development, CAPABILITY All –Tcb is acceptable, but for release code it is good practice to give a valid capability in the MMP file in order to have the application successfully signed. The following is a sample of a capability error found in the [Debug Messages] window.

*PlatSec* ERROR - Capability check failed - Process hellogst.exe[10015942]0001 was checked by Thread c32exe.exe[101f7989]0001::ESock_IP and was found to be missing the capabilities: NetworkServices.

Environment variables

At the moment, environment variables are not completely supported in Symbian C++. Therefore be wary of using library functions like getenv() which work on environment variables. Make sure the library initialization routine calls setenv() with the proper value of the environment variable. Also, be wary of functions like g_get_home_dir() which may not work as they behave in Linux.

if ((memenv = getenv("JPEGMEM")) != NULL) // will not work properly

Suggested change:

void LibraryInit()
{
   setenv ("JPEGMEM ", "XXXXX", 1);
}

Assembly code

The syntax for inline assembly code is different in Symbian OS. The following is a code snippet of assembly code syntax in Symbian OS.

EXPORT_C __NAKED__ TUint16 TTemplate::Register16(TUint anAddr)
/**
  Read a 16-bit register
  @returns register contents
*/
  {
  asm("ldrh	r0,[r0]");
      __JUMP(,lr);
  }

In common practice the assembly code has the extension .CIA in Symbian OS, whereas in Linux the assembly code has the extension .S.

Glossary

The following table lists terms used in Linux and their approximate equivalents in Symbian OS:

Linux | Symbian
-D of Makefile | MACRO of theMMP file
-I of Makefile | USERINCLUDE of the MMP file
SO | DLL
A | LIB
Makefile | MMP file
SOURCES of Makefile | SOURCE of the MMP file
/usr/include/ | \EPOC32\INCLUDE
/usr/lib/ | \epoc32\data\c\sys\bin on an emulator, \sys\bin on a target device

The following table lists a few important things about the Symbian OS:

ABI_DIR | Platform, e.g., winscw or armv5
BUILD_DIR | UDEB or UREL
c: drive in emulator | \epoc32\data\c and \epoc32\winscw\c
z: drive in emulator | Z:\epoc32\data\z
bld.inf | Lists public header files and their location in \EPOC32\INCLUDE

Give feedback of this section

©Nokia 2006

Back to top

This material, including documentation and any related computer programs, is protected by copyright controlled by Nokia. All rights are reserved. Copying, including reproducing, storing, adapting or translating, any or all of this material requires the prior written consent of Nokia. This material also contains confidential information, which may not be disclosed to others without the prior written consent of Nokia.

Nokia is a registered trademark of Nokia Corporation. S60 and logo is a trademark of Nokia Corporation. Java and all Java-based marks are trademarks or registered trademarks of Sun Microsystems, Inc. Other company and product names mentioned herein may be trademarks or tradenames of their respective owners.


$title

S60 Open C
Open C Tips and Tricks

Open C Tips and Tricks

Table of Contents

How to export global data from a DLL

How to export global data from a DLL

Exporting global data from a DLL to be accessed by either Open C or Symbian C++ applications is one of the typical problems that developers encounter.

NOTE! It is strongly recommended to avoid having global data in DLLs due to following reasons:

  • EKA2 emulator allows only a DLL with WSD to load into a single process.
  • RAM usage for WSD data chunk is atleast one 4K RAM page (the smallest possible RAM allocation), irrespective of how much static data is required.
  • Chunks are a finite resource on ARMv5. Every process loading WSD enabled DLLs uses a chunk to hold the data.
  • There are ARM architecture 4 and 5 specific costs and limitations that apply only to DLLs that link against “fixed processes”
  • There is a limit on the number of DLLs in a process with WSD.

On having understood the above limitations, the following pattern can be used for exporting global data from a DLL:

  1. Do not export global variables.
  2. Export one method that returns a pointer to that variable.
  3. Define a macro for the user of the DLL.

See the example below:

1. Do not export global variables.

Within DLL, say there is one global variable, for example:

int globalVal;

2. Export one method that returns a pointer to that variable

extern "C" EXPORT_C int* GlbData ()
    {
    return &globalVal
    }

3. Define a macro for the user of the DLL

Within the DLL header (e.g., xxx.h), define the following:
#ifdef __cplusplus
extern "C"
#endif
IMPORT_C int* GlbData ();
#define globalVal (*GlbData())

And the usage is like:

#include <xxx.h>   // DLL header
int main()
    {
    int i = 0;
    globalVal = 10;
    globalVal++;
    i = globalVal;
    return 0;
    }

Give feedback of this section

©Nokia 2006

Back to top

This material, including documentation and any related computer programs, is protected by copyright controlled by Nokia. All rights are reserved. Copying, including reproducing, storing, adapting or translating, any or all of this material requires the prior written consent of Nokia. This material also contains confidential information, which may not be disclosed to others without the prior written consent of Nokia.

Nokia is a registered trademark of Nokia Corporation. S60 and logo is a trademark of Nokia Corporation. Java and all Java-based marks are trademarks or registered trademarks of Sun Microsystems, Inc. Other company and product names mentioned herein may be trademarks or tradenames of their respective owners.


$title

S60 Open C
Open C Tips and Tricks

Open C Tips and Tricks

Table of Contents

How to initialize a library
Export functions for initializing and closing the library
Exported functions check whether the library is initialized
Library defines a static object

How to initialize a library

Sometimes, a library needs to be initialized before it can provide any services to client of the library. This can be done in several ways.

Export functions for initializing and closing the library

  • The library can export more than one function for initializing and closing the library.
  • The client of the library calls the initialization function before requesting any services and calls close when the client does not use the library.

Example:

We have a DLL called xxx.dll. Two functions InitXXX() and CloseXXX() are exported from this DLL. The library code can look like the following:

Library header file xxx_init.h:
....
IMPORT_C void InitXXX();
IMPORT_C CloseXXX();
....
Library source file xxx_init.cpp:
static int _InitCount = 0;
EXPORT_C void InitXXX()
{
   if(_InitCount++ <= 0)
   {
   // initialize xxx.dll
   }
}
EXPORT_C CloseXXX()
{
   if(--_InitCount <= 0)
   {
   // free all the resources
   }
}
User code looks like the following:
#include <xxx_init.h>
...
int main()
{
   InitXXX();
   ....
   ....
   CloseXXX();
   return 0;
}

Exported functions check whether the library is initialized

Every exported function can check whether the library has been initialized. The library can export one function (for example,CloseLib()) and this can be called before exiting main( ).

Example:

Library header file xxx.h:
....
IMPORT_C void X_Export_Api1();
IMPORT_C void X_Export_Api2();
....
Library source file xxx.cpp:
static int _InitCount = 0;
#define INIT_LIB if(_InitCount == 0) \
           {\
               _InitCount++; \
               InitXXX(); \
           }
LOCAL_C void InitXXX()
{
   // initialize xxx.dll
}
LOCAL_C CloseXXX()
{
   // free all the resources
}
EXPORT_C void X_Export_Api1()
{
   INIT_LIB;
   ...
   ...
}

User code looks like the following:

#include <xxx.h>
...
int main()
{
   ....
   ....
   X_Export_Api1();
   ....
   ....
   X_Export_Api2();
   ....
   ....
   return 0;
}

Library defines a static object

The library can define static objects and call the initialization code from the constructor of these static objects so that before calling, the application entry point library will be initialized.

Example:

Library header file xxx.h:
....
IMPORT_C void X_Export_Api1();
IMPORT_C void X_Export_Api2();
....
Library source file xxx.cpp:
LOCAL_C void InitXXX()
{
   // initialize xxx.dll
}
LOCAL_C CloseXXX()
{
   // free all the resources
}
class LibInit
{
   LibInit();
   ~LibInit();
};
LibInit::LibInit()
{
   // put all library initialization code here.
   InitXXX();
}
LibInit::~LibInit()
{
   // free all resources
   CloseXXX();
}
static LibInit _libInit;
User code looks like the following:
#include <xxx.h>
...
int main()
{
   ....
   ....
   X_Export_Api1();
   ....
   ....
   X_Export_Api2();
   ....
   ....
   return 0;
}

Give feedback of this section

©Nokia 2006

Back to top

This material, including documentation and any related computer programs, is protected by copyright controlled by Nokia. All rights are reserved. Copying, including reproducing, storing, adapting or translating, any or all of this material requires the prior written consent of Nokia. This material also contains confidential information, which may not be disclosed to others without the prior written consent of Nokia.

Nokia is a registered trademark of Nokia Corporation. S60 and logo is a trademark of Nokia Corporation. Java and all Java-based marks are trademarks or registered trademarks of Sun Microsystems, Inc. Other company and product names mentioned herein may be trademarks or tradenames of their respective owners.


$title

S60 Open C
Open C Tips and Tricks

Open C Tips and Tricks

Table of Contents

String conversions
Symbian descriptors and C strings compared
How to convert TBuf16 to a char buffer
How to convert TBuf8 to wchar_t
How to convert TText16 to char
How to convert a char array and a wide char array
How to declare a wide-char string

String conversions

In case the developer is developing applications where Open C-based functionality is called from a Symbian/S60 application, the need for conversions between Symbian descriptors and different string types provided by Open C is needed.

Symbian descriptors and C strings compared

The main difference between Symbian descriptors and C strings is that the Symbian descriptors know how many characters are in a data array. A C string does not know its length, so when length is needed the NULL character that indicates the end of the string has to be scanned.

Another difference arises with buffers. When C code reserves a buffer from the heap or stack, it has to keep the maximum length somewhere. Many C methods that alter the buffer contents do not respect the maximum size of the buffer and can override the reserved memory, causing unknown behavior. Some methods take the maximum length as a parameter but it is difficult to use those types in functions, since a pointer to an array and maximum length have to be passed separately. Buffer descriptors can tell the maximum length, and all the methods they provide respect the buffer limits.

When using neutral descriptor types there is no need to worry about character widths. In a C program, the programmer has to explicitly specify which method to use, for example strcat or wcscat.

The table below contains a comparison of standard C string functions and Symbian counter parts.:

C function | Symbian | Description
sprintf, swprintf | TDes::Format | Write formatted data to a string.
strcat, wcscat, strncat, wcsncat | TDes::Append | Append a string to another.
strcmp, strncmp, wcsncmp | TDesC::Compare | Compare strings lexicographically.
strcpy, wcscpy strncpy, wcsncpy | TDes::Copy | Copy a string to another.
strchr, wcschr | TDesC::Locate | Find a character in a string.
strrchr, wcsrchr | TDesC:: LocateReverse | Scan the index of the first character from a string that does not exist in the alphabet array.
strspn, wcsspn | None | Scan index of the first character from string that doesn't exist in alphabet array.
strcspn, wcscspn | None | Scan the index of the first occurrence of a character in a string that belongs to the set of characters.
strstr, wcsstr | TDesC::Find | Find a substring.
strtok, wcstok | TLex:: | Find the next token in a string.
strlen, wcslen | TDesC::Length | Get the length of a string.
strcoll, wcscoll | TDesC::CompareC | Compare strings using locale-specific information.
strftime, wcsftime | Using TDes::Format and TTime | Format a time string.

How to convert TBuf16 to a char buffer

A TBuf16 buffer can be converted to a char buffer using the wcstombs API. The example below illustrates how the conversion can be done.

#include <e32base.h>
#include <sys/types.h>
#include <stdio.h>
#include <stdlib.h>
#include <wchar.h>

#define SIZE 20
_LIT(KData,"hello");

int main (void)
{
    TBuf16<SIZE> buf(KData);
    size_t ret;
    char carray[SIZE];

    ret = wcstombs(carray, (const wchar_t *)buf.PtrZ(), SIZE );
    printf("TBuf converted to char buffer : %s\n",carray);
    getchar();
    return (1);
}

How to convert TBuf8 to wchar_t

ATBuf8 buffer can be converted to wchar_t using the mbstowcs API.

 #include <e32base.h>
 #include <sys/types.h>
 #include <stdio.h>
 #include <stdlib.h>
 #include <wchar.h>

 #define SIZE 20

 int main (void)
 {
     TBuf8<SIZE> buf(_L8("hello"));
     size_t ret;
     wchar_t warray[SIZE];

     ret = mbstowcs(warray, (const char *)buf.PtrZ(), SIZE );
     printf("TBuf8 converted to wchar buffer : %ls\n",warray);
     getchar();

     return (1);
 }

How to convert TText16 to char

The wcstombs API can be used to convert a TText16 buffer to a char buffer. This is one of the examples of converting from a Symbian data type to a C data type.

#include <e32def.h>
#include <sys/types.h>
#include <stdio.h>
#include <stdlib.h>
#include <wchar.h>

#define SIZE 32

int main (void)
{
   TText arr[SIZE] = L"abcdef";
   char carray[SIZE];
   size_t ret;

   ret = wcstombs(carray, (const wchar_t *)arr, SIZE);
   printf("TText converted to char buffer : %s",carray);
   getchar();

   return (1);
}

How to convert a char array and a wide char array

When we want to use both char and wide char pointers or array in our program, we have to convert buffers from a char to a wide char and vice versa. Wide character APIs provide methods to:
  • convert a char array to a wide char array
  • convert a wide char array to a char array

Converting a char array to a wide char array

The mbstowcs API can be used to convert a char array to a wide char array.

#include <stdlib.h>
#include <wchar.h>

#define ARRAY_SIZE 32

int main(void)
{
   char *carray = "char array";
   wchar_t warray[ARRAY_SIZE];
   size_t ret;

   ret = mbstowcs(warray, (const char *)carray, ARRAY_SIZE);
   wprintf(L"character array contents : %s\n",carray);
   wprintf(L"wide char array contents : %ls\n",warray);
   getwchar();

   return (1);
}

Converting a wide char array to a char array

The wcstombs API can be used to convert a wide char array to a char array.

#include <stdlib.h>
#include <wchar.h>

#define ARRAY_SIZE 32

int main(void)
{
   wchar_t *warray = L"wide array";
   char carray[ARRAY_SIZE];
   size_t ret;

   ret = wcstombs(carray, (const wchar_t *)warray, ARRAY_SIZE);
   wprintf(L"wide char array contents : %ls\n",warray);
   wprintf(L"character array contents : %s\n",carray);
   getwchar();

   return (1);
}

How to declare a wide-char string

To declare a wide-char string, prefix the string with 'L' [Capital L].

#include <wchar.h>

int main(void)
{
     wchar_t *wptr = L"This is a wide char string";

     wprintf(L"%ls\n",wptr);
     getwchar();
}

Give feedback of this section

©Nokia 2006

Back to top

This material, including documentation and any related computer programs, is protected by copyright controlled by Nokia. All rights are reserved. Copying, including reproducing, storing, adapting or translating, any or all of this material requires the prior written consent of Nokia. This material also contains confidential information, which may not be disclosed to others without the prior written consent of Nokia.

Nokia is a registered trademark of Nokia Corporation. S60 and logo is a trademark of Nokia Corporation. Java and all Java-based marks are trademarks or registered trademarks of Sun Microsystems, Inc. Other company and product names mentioned herein may be trademarks or tradenames of their respective owners.


$title

S60 Open C
Open C Tips and Tricks

Open C Tips and Tricks

Table of Contents

Mapping standard C library error codes to Symbian error codes
errno example
perror example
Mapping between libc error codes and Symbian error codes

Mapping standard C library error codes to Symbian error codes

Whenever an API of the standard C library (libc) fails, the failure will be indicated by a return code, which will typically be a non-zero value or -1 (some APIs will return NULL (0) in case of an error ). In such cases, the developer can refer to errno for getting the last error code, which is defined in the header <errno.h>

libc uses errno for recording the last error that happened when any of the libc's API is invoked in that threads context. If the previous libc API returns successfully, it does not reset the value. So, if the user wants to know the error state of some particular API of libc, the user can set errno to 0, call the API, and then check the errno. Libc's errno is thread-specific; that is, any failure in libc's API in one thread will not change the errno of another thread. Each thread will have its own errno variable. Typically this variable will be part of TLS (Thread Local Storage).

errno example

#include <stdio.h>
#include <errno.h>
#include <fcntl.h>

int main() {
   int fd = 0;
   /* Assuming file name specified does not exist! */
   FILE* fp = fopen("C:\\does_not_exist.txt", "r");
   if(fp) {
      printf("File Opened in Read Mode, error code is %d\n", errno);
      fclose(fp);
   }
   else {
      printf("File Open Failed with %d\n", errno);
      errno = 0;
   }
   /* Try to create the same file in write mode now */
   fd = open("C:\\does_not_exist.txt", O_WRONLY | O_CREAT);

   if(fd == -1) {
      printf("File create in write mode Failed with %d\n", errno);
   }
   else {
      printf("File Created for write, error code : %d\n", errno);
      errno = 0;
   }
   close(fd);
   return 0;
}

The output will be:

File Open Failed with 2
File Created for write, error code : 0

If the code errno = 0 is commented in the example, the second output message will display "error code : 2"

perror example

In addition to errno, the user can also use perror for getting the last error displayed as a string. The signature of perror is as follows:

void perror(const char *s);

perror() will write a message to the standard error output, which describes the last error encountered during a call to the libc function. If the passed argument is not NULL, it will display that message first, followed by a colon and the error message corresponding to the error code.

In the previous sample code, if the following codes were inserted after fopen and open respectively:

perror("fopen Status");
perror("open Status");

the output would look like the following (assuming that the file does not exist):

fopen Status : No such file or directory
File Open Failed with 2
open Status : Unknown error : 0
File Created for write, error code : 0

Mapping between libc error codes and Symbian error codes

The table below lists the standard C library error codes, which are defined in epoc32\include\stdapis\errno.h and mapping error codes in Symbian OS. Whenever the user gets any such error codes, the reason can be any of the mapping Symbian error codes.

Standard C library | Symbian OS
ENOENT | KErrNotFound or KErrPathNotFound
EINTR | KErrCancel
ENOMEM | KErrNoMemory
ENOSYS | KErrNotSupported
EINVAL | KErrArgument or KErrBadDescriptor or KErrBadName
ERANGE | KErrTotalLossOfPrecision
EBADF | KErrBadHandle
ERANGE | KErrOverflow or KErrUnderflow
EEXIST | KErrAlreadyExists
EPIPE | KErrDied or KErrDisconnected or KErrSessionClosed or KErrEof or KErrServerTerminated
EACCES | KErrInUse or KErrPermissionDenied or KErrAccessDenied or KErrLocked
EBUSY | KErrServerBusy
ENODEV | KErrUnknown or KErrHardwareNotAvailable or KErrDisMounted
EIO | KErrWrite
ENOSPC | KErrDiskFull or KErrDirFull
ECOMM | KErrCommsLineFail or KErrCommsFrame or KErrCommsOverrun or KErrCommsParity or KErrCommsBreak
ETIMEDOUT | KErrTimedOut
ECONNREFUSED | KErrCouldNotConnect
EFAUL | KErrTooBig
EDOM | KErrDivideByZero or KErrBadPower

Give feedback of this section

©Nokia 2006

Back to top

This material, including documentation and any related computer programs, is protected by copyright controlled by Nokia. All rights are reserved. Copying, including reproducing, storing, adapting or translating, any or all of this material requires the prior written consent of Nokia. This material also contains confidential information, which may not be disclosed to others without the prior written consent of Nokia.

Nokia is a registered trademark of Nokia Corporation. S60 and logo is a trademark of Nokia Corporation. Java and all Java-based marks are trademarks or registered trademarks of Sun Microsystems, Inc. Other company and product names mentioned herein may be trademarks or tradenames of their respective owners.


$title

S60 Open C
Open C Tips and Tricks

Open C Tips and Tricks

Table of Contents

Possibilities of panic and crash
Library startup panic
Panics due to bad coding practices
User- 42 panic
E32USER-CBase:66/E32USER-CBase:69 panic
KERN-EXEC 3 panic

Possibilities of panic and crash

Since Symbian OS has different mechanisms for handling or trapping errors and exceptions, standard libraries written on top of Symbian as part of Open C, may throw some panics or crash with Symbian-specific errors. This section lists out the possibilities of such a scenario.

Even though such errors can happen, these error cases can be eliminated if the user is aware of them and knows the solution.

Library startup panic

Open C libc will panic during the startup of the application (before callingmain( ) of the application) if any of the following happens:

  • There is not enough memory.
  • The connection to the Symbian file server fails.

In either of the above cases, the application will panic before starting main( ) of the application.

Panics due to bad coding practices

In addition to the above Panics, applications linking with Open C STDLIBS may also panic or crash because of a bug introduced by the programmer.

User- 42 panic

One such common example can be an application panicking or crashing with the User-42 panic code. This may happen with those APIs of libc that use malloc, calloc, free, or realloc. See the code below:

#define ALLOC_DATA	500

int main()
   {
   char* p = (char*) malloc(1);
   /* Suppose to allocate ALLOC_DATA, but 1 byte is allocated, still doing memset
      for ALLOC_DATA length */
   memset(p, 0, ALLOC_DATA);
   /* This will crash now, as heap is corrupted by previous memset */
   char* q = (char*) malloc(ALLOC_DATA);

   free(p);
   free(q);
   }

This code has a bug that will cause the application to panic with User-42. This panic will be raised when the programmer tries to do allocation or reallocation or freeing up of memory from RHeap and if the address passed is not a valid cell (Bad Heap Cell Address).

E32USER-CBase:66/E32USER-CBase:69 panic

In case of hybrid applications, the users may end up with several problems if they are not aware of the limitations that are mentioned in Introduction to Open C.

Some APIs expect a cleanup stack to be created and that a top-level TRAP is present. Using such APIs of libc like select, any pipe-related APIs (pipe, read, write on fd of a pipe), some socket-specific APIs, locale-specific APIs, iconv_open, mmap API, and ipc-related APIs may cause panics like E32USER-CBase:66 or E32USER-CBase:69 depending on whether the application has created a cleanup stack or whether a top-level TRAP/TRAPD exists. One such example can be:

void PipeTestL()
   {
   int fds[2];
   int ret = pipe(fds);
   printf("pipe returned with %d", ret);
   close(fds[0]);
   close(fds[1]);
   }

TInt E32Main()
   {
   __UHEAP_MARK;
   TInt retVal = KErrNone;
   TRAP(retVal, PipeTestL());
   HelloWorldL();
   __ASSERT_ALWAYS(!retVal, User::Panic(_L("Pipe Test PANIC"), retVal));
   __UHEAP_MARKEND;
   return retVal;
   }

The above sample will panic with E32USER-CBase:69 because a cleanup stack is not created. The solution is to create a cleanup stack in E32Main() as in the example below:

TInt E32Main()
   {
   __UHEAP_MARK;
   CTrapCleanup* cleanup = CTrapCleanup::New();
   TInt retVal = KErrNone;
   if (cleanup)
      {
      TRAP(retVal, PipeTestL());
      HelloWorldL();
      __ASSERT_ALWAYS(!retVal, User::Panic(_L("Pipe Test PANIC"), retVal));
      Destroy cleanup stack
      delete cleanup;
      }
   __UHEAP_MARKEND;
   return retVal;
   }

Similarly, for threads created using direct Symbian APIs, the user has to take care of these limitations (cleanup stack and TRAP or TRAPD). The user does not have to create a cleanup stack or trap if the application has main( ) as the entry point and all the threads are created using the pthread_create API. This is because pthread_create will take care of creating the cleanup stack and trap for that thread.

KERN-EXEC 3 panic

In addition to the above, some common coding mistakes such as operating on uninitialized fds or file pointers will cause the application to crash with KERN-EXEC 3. This panic will be raised when an unhandled exception occurs, like de-referencing NULL or executing an invalid instruction. One such example can be:

void FileTest()
{
   FILE* fp = NULL;
   int ret = fprintf(fp, "write me");
   fclose(fp);
}

This sample case will panic with KERN-EXEC 3 since fp is not pointing to a valid file.

Give feedback of this section

©Nokia 2006

Back to top

This material, including documentation and any related computer programs, is protected by copyright controlled by Nokia. All rights are reserved. Copying, including reproducing, storing, adapting or translating, any or all of this material requires the prior written consent of Nokia. This material also contains confidential information, which may not be disclosed to others without the prior written consent of Nokia.

Nokia is a registered trademark of Nokia Corporation. S60 and logo is a trademark of Nokia Corporation. Java and all Java-based marks are trademarks or registered trademarks of Sun Microsystems, Inc. Other company and product names mentioned herein may be trademarks or tradenames of their respective owners.


$title

S60 Open C
Open C Tips and Tricks

Open C Tips and Tricks

Table of Contents

Calling Symbian asynchronous APIs in an Open C application

Calling Symbian asynchronous APIs in an Open C application

When porting an Open C or C++ application on top of Symbian C++ or Open C, the developer may need to make use of Symbian asynchronous APIs. If asynchronous APIs are made use of in an Open C application, the application needs to wait for the completion of the asynchronous API. This can be done in two ways:

  • Wait for the asynchronous request to complete. This can be achieved by making use of User::WaitForRequest(iStatus); where iStatus is the TRequestSemaphore used by the asynchronous API.
  • Call the asynchronous API in an active object, run an active scheduler, and let the active scheduler wait for the asynchronous operation to complete.

The problems with these approaches are:

The open source application would get blocked till the asynchronous operation completes in the first approach. In the second approach, the active scheduler would be running in a wait loop, checking for asynchronous API completion. Even in this case, the Open C application would not be able to perform any other operations outside the active scheduler framework.

The asynchronous APIs could be called in a separate process, and the Open C application could communicate with this process by making use of the client/server framework of Symbian or by making use of other Open C IPC mechanisms. However, making a different process for calling asynchronous APIs might pose a performance hit.

One of the ways to solve these problems is to call the asynchronous APIs in a separate thread.

An example class which implements the same is given below:

class CActiveThread:  public CActive
{
public:

    enum TState
    {
    EInitialized = 0x0,
    EDoFirst = 0x1,
    EDoSecond = 0x2,
    EDoThird = 0x4,
    ECompleted = 0x8
    };

     // thread startup routine
    static int StartMyThread(void* thisptr);
    // leaving variant of the thread startup routine
    static int StartMyThreadL(void* thisptr);
    // Helper function to start the thread
    void StartThread();
    // Do Function
    void DoFunction(TState aState );

    // CActive Functions
    void RunL();
    void DoCancel();

    // Constructors and destructor
    static CActiveThread* NewL();
    CActiveThread ();
    void ConstructL();
    ~ CActiveThread();

private:

    // Active Scheduler
    CActiveSchedulerWait *iWait;
    // Command/State
    TInt iState;
    TRequestStatus iThreadExitWait;
    // my thread handle
    RThread iActiveThread;
    sem_t iSem;
};

The StartThread member function of CActiveThread creates the thread which runs the active scheduler. StartMyThread is the entry point function for the new thread that starts an active scheduler and sets up the clean up stack. To call an asynchronous function, DoFunction needs to be called with the corresponding state. The parent thread signals the child thread using the child thread’s thread request semaphore. When the thread request semaphore is signaled, the child thread wakes up, calls the corresponding asynchronous API in RunL based on the iState and again goes back to the active scheduler wait loop.

To synchronize between the parent thread and the child thread, a semaphore can be used as shown in the following code snippet.

CActiveThread* CActiveThread::NewL()
{
CActiveThread* self = new (ELeave) CActiveThread();
self->ConstructL();
return self;
}

CActiveThread::CActiveThread():CActive(EPriorityStandard),iState(EInitialized)
{
}

void CActiveThread::ConstructL()
{
// semaphore for Synching
sem_init(&iSem,0,0);
}

void CActiveThread::StartThread()
{
//Create Thread
TInt err = iActiveThread.Create( KThreadName(),&CActiveThread::StartMyThread,
     KDefaultStackSize, NULL, (TAny*)this );
iActiveThread.Logon( iThreadExitWait );
iActiveThread.Resume();
sem_wait( &iSem );
}

int CActiveThread::StartMyThread( void* ptr )
{
CActiveScheduler* scheduler = new (ELeave) CActiveScheduler();
CActiveScheduler::Install(scheduler);
CTrapCleanup* pCleanup = CTrapCleanup::New();
TRAPD(err, StartMyThreadL(ptr));
}

int CActiveThread::StartMyThreadL( void* ptr )
{
CActiveThread *thisptr = (CActiveThread*)ptr;
CActiveScheduler::Add(thisptr);
thisptr->iWait = new (ELeave) CActiveSchedulerWait();
thisptr->iState = EInitialized;
thisptr->iStatus = KRequestPending;
thisptr->SetActive();
sem_post( &(thisptr->iSem ));
thisptr->iWait->Start();
}

 void CActiveThread::RunL()
 {
 switch ( iState )
     {
     case  EDoFirst:
     // Call 1st asynchronous function
     break;

     case EDoSecond:
     // Call 2nd asynchronous function
     break;

     case EDoThird:
     // Call 3rd asynchronous function
     break;

     case ECompleted:
     iWait->AsyncStop();
     return;
     }

iStatus = KRequestPending;
SetActive();
// wake up the waiting thread
sem_post( &iSem );
}

void CActiveThread::DoCancel()
{
}

void CActiveThread::DoFunction(TState aState )
{
iState = aState;
TRequestStatus *reqPtr = &iStatus	;
iActiveThread.RequestComplete( reqPtr, KErrNone );
sem_wait(&iSem);
}

CActiveThread::~CActiveThread()
{
if ( iState != EInitialized )
    {
    iState = ECompleted;
    TRequestStatus *reqPtr = &iStatus
    iActiveThread.RequestComplete( reqPtr, KErrNone );
    User::WaitForRequest( iThreadExitWait);
    }
sem_destroy(&iSem);
}

Using CActiveThread:

iMyAsyncIf = CActiveThread::NewL();
iMyAsyncIf->StartThread();
iMyAsyncIf->DoFunction(EDoFirst);

Limitations:

In this approach, only the parent thread communicates with the child thread. There is no way for the child thread to communicate with the parent thread.

Give feedback of this section

©Nokia 2006

Back to top

This material, including documentation and any related computer programs, is protected by copyright controlled by Nokia. All rights are reserved. Copying, including reproducing, storing, adapting or translating, any or all of this material requires the prior written consent of Nokia. This material also contains confidential information, which may not be disclosed to others without the prior written consent of Nokia.

Nokia is a registered trademark of Nokia Corporation. S60 and logo is a trademark of Nokia Corporation. Java and all Java-based marks are trademarks or registered trademarks of Sun Microsystems, Inc. Other company and product names mentioned herein may be trademarks or tradenames of their respective owners.


Networking and Sockets

Multihoming and socket communication
Multihoming and network host entry functions
How to get mobile IP without ioctl()

© Nokia 2007

Back to top


$title

S60 Open C
Open C Networking and Sockets

Open C Networking and Sockets

Table of Contents

Multihoming and socket communication
Classification of APIs
Browsing the AP table
Choosing connection or subconnection for socket communication
Example code to connect to an IP address
Interface functions

Multihoming and socket communication

In desktop OS, multiple connections are managed by having a different IP address for each connection. The application chooses the IP address. In Symbian OS, connections are managed by the RConnection class and access points are stored in an ‘IAP’ table. The IAP table is accessed using the CommDB class. Libc provides simple and easy-to-use C interfaces to access CommDB, RConnection and RSubConnection functionality. This functionality is provided at libc layer through ioctl() and if_<function>().

Please note that RConnection/RSubConnection code cannot be intermixed with ioctls() discussed here.

Classification of APIs

Browsing the AP table

There are two possibilities:the programmer either wants to read access point details or wants to read active access point details. The SIOCGIFCONF and SIOCGIFACTIVECONF APIs can be used here.

void AccessPoints()
    {
    struct ifconf ifc;
    int sockfd;
    int count;
    int ret;

    sockfd = socket(AF_INET,SOCK_DGRAM,IPPROTO_UDP);

    ifc.ifc_len = sizeof(struct ifreq) * 20;
    ifc.ifc_buf = (caddr_t)malloc( ifc.ifc_len );

     // This will fetch the access point list, ifc.ifc_len will contain the size of the buffer
    ret = ioctl(sockfd, SIOCGIFCONF, &ifc);

    // count will contain the number of access points
    count = ifc.ifc_len / sizeof(struct ifreq)

    close(sockfd);
    free(ifc.ifc_buf);
    return;
    }

Choosing connection or subconnection for socket communication

Once the user knows the access point list or connection list, the same can be displayed to the user to select the proper access point. The SIOCSIFNAME API can be used to select the access point. The following code shows how to start a new connection using available access points.

void ChooseInterface(char *ifname)
    {
    ifreq ifr;
    int sockfd;

    // Name of the interface
    strcpy(ifr.ifr_name, ifname);

    sockfd = socket(AF_INET,SOCK_DGRAM,IPPROTO_UDP);
    ioctl(sockfd,SIOCSIFNAME, &ifr);
    ioctl(sockfd, SIOCIFSTART , &ifr);
    ////
    //// recvfrom() and sendto() operations on socket sockfd
    ////
    ioctl(sockfd, SIOCIFSTOP, &ifr);

    close(sockfd);
    return ret;
    }

The following code shows how to start a new subconnection using an existing connection.

void ChooseActiveInterface(char *ifname)
    {
    ifreq ifr;
    int sockfd1, sockfd2;

    // Name of the interface
    strcpy(ifr.ifr_name, ifname);

    sockfd1 = socket(AF_INET,SOCK_DGRAM,IPPROTO_UDP);
    ioctl(sockfd1,SIOCSIFNAME, &ifr);
    ioctl(sockfd1, SIOCIFSTART , &ifr);

    sockfd2 = socket(AF_INET,SOCK_DGRAM,IPPROTO_UDP);
    ioctl(sockfd2,SIOCSIFNAME, &ifr);
      // Start subconnection using a connection created earlier using SIOCSIFNAME
    ioctl(sockfd2, SIOCIFACTIVESTART , &ifr);

    ////
    //// recvfrom() and sendto() operations on socket sockfd2 and sockfd1
    ////

    ioctl(sockfd2, SIOCIFSTOP, &ifr); // Stop the connection
    ioctl(sockfd1, SIOCIFSTOP, &ifr); // Stop the connection
    close(sockfd2);
    close(sockfd1);
    }

SIOCIFSTART and SIOCIFACTIVESTART are actual ioctl( ) calls which would start a connection or subconnection. All the socket communication calls such as connect(), read(), write(), send(), receive(), sendto(), and recvfrom() should come after calling SIOCIFSTART and SIOCIFACTIVESTART. Calls such as getsockopt(), and getsockname() that do not require any connection do not have any dependency on SIOCIFSTART and SIOCIFACTIVESTART.

Example code to connect to an IP address

Please note that the error checking code has been removed deliberately to improve the readability of the code.

int ConnectToIpUsingConnection( char *apname, char *ipaddr , int port)
    {
    ifreq ifr;
    int sockfd;
    struct sockaddr_in destAddr, selfAddr;

    // Name of the interface
    strcpy(ifr.ifr_name, apname);

    sockfd = socket(AF_INET,SOCK_DGRAM,IPPROTO_UDP);
    ioctl(sockfd,SIOCSIFNAME, &ifr);
    ioctl(sockfd, SIOCIFSTART , &ifr);

    selfAddr.sin_family = AF_INET;
    selfAddr.sin_addr.s_addr = INADDR_ANY;
    selfAddr.sin_port = htons(port);

    bind(sockfd,(struct sockaddr*)&selfAddr, sizeof(selfAddr));

    destAddr.sin_family = AF_INET;
    destAddr.sin_addr.s_addr = inet_addr( ipaadr );
    destAddr.sin_port = htons(port);
    connect(sockfd, (struct sockaddr*)&destAddr, sizeof(destAddr));

    ioctl(sockfd, SIOCIFSTOP, &ifr);
    close(sockfd);
    return;
    }

Interface functions

These interface functions are C interface functions provided using ioctl( ). The functions provided in this category are:

  • if_nameindex()
  • if_freenameindex()
  • if_indextoname()
  • if_nametoindex()
Refer to the Open C API reference for a detailed description.

Example code is given below.

if_nameindex()

void TestIfNameIndex()
     {
     struct if_nameindex *ifname;
     ifname = if_nameindex(); 	// ifname will contain the access point information
     if_freenameindex(ifname);
     }

if_indextoname() and if_nametoindex()

void TestIfIndexToName(int index)
     {
     char ifName[255];
         if_indextoname(index , ifName); // ifName would contain the interface name
     // ifindex would contain the interface index. In this case index and ifindex would match
     ifindex = if_nametoindex(ifName);
     }

Give feedback of this section

©Nokia 2006

Back to top

This material, including documentation and any related computer programs, is protected by copyright controlled by Nokia. All rights are reserved. Copying, including reproducing, storing, adapting or translating, any or all of this material requires the prior written consent of Nokia. This material also contains confidential information, which may not be disclosed to others without the prior written consent of Nokia.

Nokia is a registered trademark of Nokia Corporation. S60 and logo is a trademark of Nokia Corporation. Java and all Java-based marks are trademarks or registered trademarks of Sun Microsystems, Inc. Other company and product names mentioned herein may be trademarks or tradenames of their respective owners.


$title

S60 Open C
Open C Networking and Sockets

Open C Networking and Sockets

Table of Contents

Multihoming and network host entry functions
Querying available access points
gethostbyname
gethostbyaddr

Multihoming and network host entry functions

In Linux, network interfaces are identified by different IP addresses. In the mobile world an IP address is not valid at the moment. In most cases, the IP address is allotted dynamically by the service provider or by WLAN. Therefore, Symbian OS, introduces the idea of an interface via access points. Symbian OS stores access point information in system-wide tables. The programmer can choose any access point without prompting the user about the access point. This section shows how to create an access point and use it for network host entry functions such as gethostbyname, and gethostbyaddr.

Querying available access points

For information about this, refer to Multihoming and Socket communication.

gethostbyname

Note in the following example that the error checking code has been removed deliberately to improve the readability of the code. For release quality code, add the error checking statements in lines such as conn.Start(), conn.Open(), and so on.

int gethostbyname_iap (char *name, size_t size, int iap_id)
    {
    RSocketServ ss;
    struct hostent* retval=0;
    RConnection conn;
    TCommDbConnPref pref;
    RHostResolver r;

    ss.Connect();

    // TCommDbConnPref stores the conection preference of the user.
    pref.SetIapId(iap_id);
    pref.SetDialogPreference(ECommDbDialogPrefDoNotPrompt); // Set not to prompt the user

    // RConnection creates a connection.
    conn.Open(ss, KAfInet);
    conn.Start(pref);

    r.Open(ss, KAfInet, KProtocolInetUdp, conn);

    TNameRecord record;
    TNameEntry entry(record);
#ifdef _UNICODE
    TPtrC8 ptr(reinterpret_cast<const TUint8*> (name));
    TBuf<0x40> hostname; // Assuming name is not more than 40 characters
    hostname.Copy(ptr);
#else
    TPtrC8 hostname(reinterpret_cast<const TUint8*> (name));
#endif /* _UNICODE */
    err = r.GetByName(hostname, entry);
    if (err == KErrNone)
        {
        record = entry();
        retval = mapNameRecord(rp, record, sizeof(struct in_addr), AF_INET);
        }
    r.Close();
    conn.Close();
    ss.Close();

    return err;
    }

gethostbyaddr

struct hostent* gethostbyaddr_iap (struct _reent* rp, const char* addr,
                        int length, int format, int iap_id)
    {
    RSocketServ ss;
    struct hostent* retval = NULL;
    RConnection conn;
    TCommDbConnPref pref;
    RHostResolver r;

    ss.Connect();

    // TCommDbConnPref stores the conection preference of the user.
    pref.SetIapId(iap_id);
     // Set not to prompt the user
    pref.SetDialogPreference(ECommDbDialogPrefDoNotPrompt);

    // RConnection creates a connection.
    conn.Open(ss, KAfInet);
    conn.Start(pref);

    r.Open(ss, format, KProtocolInetUdp, conn);
    struct sockaddr buf;
    buf.sa_family = (unsigned short)format;
    memcpy(buf.sa_data, addr, length);
    TUSockAddr addr(&buf, length+4);
    TNameRecord record;
    TNameEntry entry(record);
    err = r.GetByAddress(addr, entry);
    if (err == KErrNone)
           {
           record = entry();
           retval = mapNameRecord(rp, record, length, format);
           }
    r.Close();
    conn.Close();
    ss.Close();
    return retval;
    }

Give feedback of this section

©Nokia 2006

Back to top

This material, including documentation and any related computer programs, is protected by copyright controlled by Nokia. All rights are reserved. Copying, including reproducing, storing, adapting or translating, any or all of this material requires the prior written consent of Nokia. This material also contains confidential information, which may not be disclosed to others without the prior written consent of Nokia.

Nokia is a registered trademark of Nokia Corporation. S60 and logo is a trademark of Nokia Corporation. Java and all Java-based marks are trademarks or registered trademarks of Sun Microsystems, Inc. Other company and product names mentioned herein may be trademarks or tradenames of their respective owners.


$title

S60 Open C
Open C Networking and Sockets

Open C Networking and Sockets

Table of Contents

How to get mobile IP without ioctl()

How to get mobile IP without ioctl()

In Linux, the function ioctl() is used to get the user's own IP address. But on mobile devices, an IP address is not always allotted. It is assigned as and when a connection is established and will be relinquished when the connection is terminated and/or no other connection exists. (GPRS is assumed as bearer connection)

It is important to know that on mobiledevices, ioctl() returns the access point name rather than the IP address. So the alternative way to get the mobile IP is using Symbian RSocket.

The following example illustrates this. The example code tries to connect to www.nokia.com (147.243.3.83). If this server is down, change it to any other server. Look at the output , the "My IP" might change every time this application is executed. To get a constant IP on successive executions, run the browser and connect to some site, for example www.nokia.com and search in the background.

#include <stdio.h>
#include <es_sock.h>
#include <in_sock.h>
#include <unistd.h>

const TUint32 KInetAddrServ = INET_ADDR(147,243,3,83);
const TInt    KServPort     = 80;
int main()
{
   RSocket fd;
   TRequestStatus status = KRequestPending;
   TInetAddr recvAddr;
   TInt retval;
   RSocketServ iRSockServ;
   /* Connecting to the socket server */
   retval = iRSockServ.Connect();
   if(retval != KErrNone)
   {
       printf("Error : Connecting to the socket server !!\n");
       User::Leave(KErrGeneral);
   }
   /* Opening a socket */
   retval = fd.Open(iRSockServ, KAfInet, KSockStream, KProtocolInetTcp);
   if(retval != KErrNone)
   {
       printf("ERROR : Socket not created !!\n");
       User::Leave( KErrGeneral);
   }
   else
   {
       printf("INFO : Socket created... \n");
   }
   /* Connecting a socket */
   TInetAddr servAddr(KInetAddrServ, KServPort);
   fd.Connect(servAddr,status);
   User::WaitForRequest(status);
   printf ("INFO: Socket Connected..\n");
   /* Getting info */
   TInetAddr myaddr, remoteaddr;
   fd.LocalName(myaddr);
   fd.RemoteName(remoteaddr);
   TUint32 myIP = myaddr.Address();
   TUint32 remoteIP = remoteaddr.Address();
   printf("MY IP = %x or %d.%d.%d.%d\n",myIP,
                                       ((myIP >> 24) & 0xff),
                                       ((myIP >> 16) & 0xff),
                                       ((myIP >> 8) & 0xff),
                                       ((myIP >> 0) & 0xff));
   printf("Remote IP = %x or %d.%d.%d.%d\n",remoteIP,
                                           ((remoteIP >> 24) & 0xff),
                                           ((remoteIP >> 16) & 0xff),
                                           ((remoteIP >> 8) & 0xff),
                                           ((remoteIP >> 0) & 0xff));
   printf ("Sleeping for 10 sec...before exit\n");
   sleep(10);
}

Give feedback of this section

©Nokia 2006

Back to top

This material, including documentation and any related computer programs, is protected by copyright controlled by Nokia. All rights are reserved. Copying, including reproducing, storing, adapting or translating, any or all of this material requires the prior written consent of Nokia. This material also contains confidential information, which may not be disclosed to others without the prior written consent of Nokia.

Nokia is a registered trademark of Nokia Corporation. S60 and logo is a trademark of Nokia Corporation. Java and all Java-based marks are trademarks or registered trademarks of Sun Microsystems, Inc. Other company and product names mentioned herein may be trademarks or tradenames of their respective owners.


Threads,Processes, IPC,and Synchronization

How to communicate between two threads or processes
How to synchronize between processes
How to avoid deadlock using POSIX APIs
How TLS differs between Symbian and POSIX
How to invoke thread entry functions in hybrid applications


$title

S60 Open C
Threads, Processes, IPC, and Synchronization

Threads, Processes, IPC, and Synchronization

Table of Contents

How to communicate between two threads or processes
Pipes
Named pipes (mkfifo)
Message queues
Shared memory

How to communicate between two threads or processes

In order to communicate between two threads within a process and also between unrelated processes, use the following mechanisms:

  • Pipes
  • Named pipes
  • Message queues
  • Shared memory

NOTE! It is fully possible to use all these mechanisms from a Symbian application and communicate with a thread or process created using thread or process creation functions provided by Open C.

Pipes

Pipes can be used when a process creates child processes or threads and wants to communicate with them. The following steps are needed:

  • Declare a global variable with array [2] of data type int.
  • Create a pipe.
  • Create a thread.
  • Read data from the pipe from the parent thread.
  • Write data from the child thread.
  • Close the read or write descriptor

Example:

#include <unistd.h>
#include <string.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <pthread.h>

int pipefd[2];
unsigned int threadid;

// thread entry point
void* PipeWriterThread(void* arg)
{
   char ch[32];
   strcpy(ch, "abcd");
   write(pipefd[1], ch, 4);
   return NULL;
}

void CreateThreadL()
{
   pthread_create(&threadid,(pthread_attr_t *)NULL,PipeWriterThread, NULL);
}

int main()
{
   if(0 == pipe(pipefd))
   {
       char ch[128];
       CreateThreadL();
       read(pipefd[0], ch, 10);
       close(pipefd[1]);
       close(pipefd[0]);
   }
   return 0;
}

Named pipes (mkfifo)

Named pipes are used to communicate between threads within a process or between two unrelated processes. The following pattern is used:

  • Create a named pipe using mkfifo.
  • Create a process or thread and open this pipe in write mode.
  • Another process or thread can open the same in read mode.
  • Close the read or write descriptor.

Example:

#include <unistd.h>
#include <string.h>
#include <sys/stat.h>
#include <stdio.h>
#include <fcntl.h>
#include <pthread.h>

const char* fifopath = "C:\\mkfifo.file";
unsigned int threadid;

// thread entry point
void* FifoWriterThread(void* arg)
{
   const char* buf = "somejunk";
   TInt fd = open (fifopath, O_WRONLY);
   if(fd > 0 )
   {
      write(fd, buf, 9);
      close(fd);
   }
   return 0;
}

void CreateThreadL()
{
   pthread_create(&threadid,(pthread_attr_t *)NULL,FifoWriterThread, NULL);
}

void OpenForRead()
{
   int err = mkfifo (fifopath, 0666);
   if(err != 0)
   {
       // probably file already exists, delete the file
       unlink(fifopath);
       // try once more..
       err = mkfifo (fifopath, 0666);
       if(err != 0)
       {
            return;
       }
   }
   CreateThreadL();
   char buf[128];
   TInt fd = open (fifopath, O_RDONLY);
   if ( fd ( 0 )
       {
           return ;
       }
   err = read (fd, buf, 128);
   close(fd);
   unlink(fifopath);
}

int main()
{
   OpenForRead();
   return 0;
}

Message queues

Message queues are used to communicate between threads within a process or two unrelated processes. The following pattern is used:

  • Create a message queue using msgget.
  • Create a process or thread and send some message to this message queue.
  • Read the message from the main thread.
  • Delete the message queue.

Example:

#include <sys/msg.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>

#define MSG_KEY 1000
pthread_t threadid;

void* MsgDSndThread(void* arg)
{
   struct msgbuf *snd = (struct msgbuf*)malloc(16);
   key_t fd;
   snd->mtype = 1;
   strcpy(snd->mtext, "message");
   fd = msgget(MSG_KEY, IPC_CREAT);
   msgsnd(fd, snd, 12, 0);
   free(snd);
   return 0;
}

void CreateThreadL()
   {
   pthread_create(&threadid,(pthread_attr_t *)NULL,MsgDSndThread, NULL);
   }

int main()
{
   struct msgbuf *rcv = (struct msgbuf*)malloc(16);
   key_t fd = msgget(MSG_KEY, IPC_CREAT);
   CreateThreadL();
   msgrcv(fd, rcv, 6, 0, 0);
   msgctl(fd, IPC_RMID, NULL);
   free(rcv);
   return 0;
}

Shared memory

Shared memory is used to communicate between threads within a process or two unrelated processes. The following pattern can be used:

  • Create a shared memory segment using shmget.
  • Create one process or thread and send some message to this message queue.
  • Read the message from the main thread.
  • Delete the message queue.

Example:

#include <sys/shm.h>
#include <string.h>
#include <pthread.h>

pthread_t threadid;
#define SHM_KEY 1000

void* ShmReadThread(void* arg)
{
   int shmid = shmget(SHM_KEY, 1024, IPC_CREAT);
   char* ch = (char*)shmat(shmid, 0, 0);
   char name[10];
   strncpy(name, ch, 3);
   // name contained "abc"
   shmdt(ch);
   return 0;
}

void CreateThreadL()
   {
   pthread_create(&threadid,(pthread_attr_t *)NULL,ShmReadThread, NULL);
   }

int main()
{
   char* ch;
   int shmid = shmget(SHM_KEY, 1024, IPC_CREAT);
   int threadRetVal = 0;
   if( shmid == -1)
       return -1;
   ch = (char*)shmat(shmid, 0, 0);
   if((int)ch == -1)
   {
       shmctl(shmid, IPC_RMID, NULL);
       return -1;
   }
   strcpy(ch, "abc");
   CreateThreadL();

   pthread_join(threadid, (void**)threadRetVal);
   shmdt(ch);
   shmctl(shmid, IPC_RMID, NULL);
   return 0;
}

Give feedback of this section

©Nokia 2006

Back to top

This material, including documentation and any related computer programs, is protected by copyright controlled by Nokia. All rights are reserved. Copying, including reproducing, storing, adapting or translating, any or all of this material requires the prior written consent of Nokia. This material also contains confidential information, which may not be disclosed to others without the prior written consent of Nokia.

Nokia is a registered trademark of Nokia Corporation. S60 and logo is a trademark of Nokia Corporation. Java and all Java-based marks are trademarks or registered trademarks of Sun Microsystems, Inc. Other company and product names mentioned herein may be trademarks or tradenames of their respective owners.


$title

S60 Open C
Threads, Processes, IPC, and Synchronization

Threads, Processes, IPC, and Synchronization

Table of Contents

How to synchronize between processes
Example
Important note

How to synchronize between processes

In order to synchronize the task between processes we need to have some mechanism to communicate the state of the processes. The user can use the following pattern to achieve the same using semaphore:

  • Create a semaphore using semget.
  • When a process wants to synchronize with some other process, the first process can create the semaphore and set the semval with some condition.
  • Once the other process has finished its task, satisfy the condition for which the other process is waiting for.
  • Delete the semaphore.

Example

Process 1:

#include <sys/sem.h>
#define SEM_KEY 1000
int main()
{
   int semid = semget(SEM_KEY, 1, IPC_CREAT);
   int ret = semctl(semid, 0, SETVAL, 1);
   struct sembuf st = {0, 0, 0};
   ret = semop(semid, &st, 1); // process -1 is blocked over here.
   ret = semctl(semid, 1, IPC_RMID);
   return 0;
}

Process 2:

#include <sys/sem.h>
#define SEM_KEY 1000
int main()
{
   int semid = semget(SEM_KEY, 1, IPC_CREAT);
   struct sembuf st = {0, -1, 0};
   TInt ret = semop(semid, &st, 1); // unblocking the process 1
   return 0;

Important note

Use pthread_mutex for synchronization if, pthread_create is used for creating threads.

Symbian C++ also provides the same type of functionality using RSemaphore, RFastLock, RMutex, RCriticalSection, and so on.

Give feedback of this section

©Nokia 2006

Back to top

This material, including documentation and any related computer programs, is protected by copyright controlled by Nokia. All rights are reserved. Copying, including reproducing, storing, adapting or translating, any or all of this material requires the prior written consent of Nokia. This material also contains confidential information, which may not be disclosed to others without the prior written consent of Nokia.

Nokia is a registered trademark of Nokia Corporation. S60 and logo is a trademark of Nokia Corporation. Java and all Java-based marks are trademarks or registered trademarks of Sun Microsystems, Inc. Other company and product names mentioned herein may be trademarks or tradenames of their respective owners.


$title

S60 Open C
Threads, Processes, IPC, and Synchronization

Threads, Processes, IPC, and Synchronization

Table of Contents

How to avoid deadlock using POSIX APIs

How to avoid deadlock using POSIX APIs

Symbian C++ provides, for example the RSemaphore, RMutex, and RFastLock classes for synchronization. These classes have methods like Wait( ) and Signal() to lock and unlock the resource. If the locks are not handled properly, a deadlock may occur. An example of a deadlock is as given below. The example assumes that there are two threads in a process and there are two locks to protect two resources.

Thread 1             Thread 2
========             ========
…                    …
…                    …
Lock A               Lock B
…                    …
…                    …
Lock B               Lock A
…                    …
…                    …
UnLock B             UnLock A
UnLock A             UnLock B
  1. Thread 1 acquires Lock A and a context switch occurs to Thread 2.
  2. Thread 2 acquires Lock B and a context switch occurs back to Thread 1.
  3. Thread 1 tries to acquire Lock B and blocks since Thread 2 has already locked it.
  4. Now a context switch happens to Thread 2, which tries to acquire Lock A and blocks since Thread 1 has already locked it.

Thus both threads will block indefinitely, leading to a deadlock.

There are many ways to avoid the deadlock by using the locks carefully. One of the easiest ways is to check the lock before blocking, and if the lock is open, then lock it; else return back instead of blocking. This operation has to be done atomically. Thus the operating system should provide a suitable API for this. At the moment, Symbian OS does not have any such API.

POSIX defines the following APIs that can be used to avoid such a situation:

  • sem_trywait() returns 0 if it is successful in locking the semaphore. If the semaphore is already locked, then it returns -1 and sets the errno to EAGAIN.
  • pthread_mutex_trylock() returns 0 if it is successful in locking the mutex. If the mutex is already locked, it returns EBUSY. (None of the pthread APIs set the errno.)

With this API, the solution might look as follows:

Thread 1                     Thread 2
=======                      ========
…                            …
…                            …
Lock A                       Lock B
…                            …
…                            …
begin1:                     begin2:
  TryLock B                    TryLock A
  If failed to Lock            If failed to Lock
  then  Unlock A               then  Unlock B
    sleep (10)                   sleep (10)
    Lock A                       Lock B
    Goto begin1:                 Goto begin2:
    …                            …
    …                            …
  UnLock B                    UnLock A
  UnLock A                    UnLock B

Similarly, there are two more useful APIs in POSIX:

  • sem_timedwait() Tries to lock the semaphore. If the lock is open, sem_timedwait() locks it and returns successfully; otherwise it waits until time-out expires.
  • pthread_mutex_timedlock() Tries to lock the mutex. If the lock is open, pthread_mutex_timedlock() locks it and returns successfully; otherwise it waits until time-out expires.

There are no equivalent APIs for the above in Symbian OS.

Give feedback of this section

©Nokia 2006

Back to top

This material, including documentation and any related computer programs, is protected by copyright controlled by Nokia. All rights are reserved. Copying, including reproducing, storing, adapting or translating, any or all of this material requires the prior written consent of Nokia. This material also contains confidential information, which may not be disclosed to others without the prior written consent of Nokia.

Nokia is a registered trademark of Nokia Corporation. S60 and logo is a trademark of Nokia Corporation. Java and all Java-based marks are trademarks or registered trademarks of Sun Microsystems, Inc. Other company and product names mentioned herein may be trademarks or tradenames of their respective owners.


$title

S60 Open C
Threads, Processes, IPC, and Synchronization

Threads, Processes, IPC, and Synchronization

Table of Contents

How TLS differs between Symbian OS and POSIX?
Symbian TLS
POSIX TLS
Example code for using POSIX TLS

How TLS differs between Symbian OS and POSIX?

Thread Local Storage (TLS) is the memory area that is available to every thread and is not accessible to other threads. Each thread can use it for storing its thread-specific information in it. The size of the TLS and the way it is accessed is operating system-dependent. Some times the scope of the TLS also differs from OS to OS. The POSIX standard has defined the way to access TLS and the size of TLS. Symbian OS is not POSIX-compliant and has defined TLS in a different way.

Symbian TLS

Thread local storage is a single machine word (4 bytes) of static writable memory. The scope of this machine word is the thread, which means that there is one word per thread. The word is accessible only to code running in a DLL. Generally, this word is almost always used to hold a pointer to the allocated memory; this makes the allocated memory available to all DLL code running on behalf of the same thread. The following summarizes the main points of TLS:

  • TLS is 4 bytes of space.
  • TLS is available per DLL per thread.
  • It can be read using the Dll::Tls() API.
  • It can be written using the Dll::SetTls() API.
  • There is no need to allocate this space and free it.
  • It is available throughout the life time of the application.

POSIX TLS

TLS or thread-specific data is the memory area that is specific to that thread. Any DLL or executable can use this. As the name indicates, it is data that is specific to the respective thread. TLS is provided in chunks of 4 bytes. Each such 4 bytes of chunk (memory space) is called a key. If a program needs TLS, then it has to create a key. Once a key is created, an ID (handle) is returned. Subsequently this ID should be used to read and write to the key.

Creating a key

The pthread_key_create() API creates a new key and returns the ID (handle). If one thread calls pthread_key_create(), then a key (4 bytes) is created in all the threads. The ID (handle) to access that key in all threads is the same (which is returned by this API). Hence, one thread can create a key and store the handle (ID) in a global variable and all the other threads can use the same handle to access their respective key. When the key is created, it is assigned to NULL in all the threads.

In addition to this, POSIX also defines an associating destructor routine to each key. The associated destructor routine is called when the thread is terminating and the key value is not NULL. Most of the time the key holds a pointer to an allocated memory. This needs to be freed when the thread is terminating. This freeing can be done from the destructor routine. A program can create a maximum of 128 or 256 keys in a process. This value is defined as PTHREAD_KEY_MAX in the pthread.h header file.

Reading from a key

The pthread_getspecific() API can be used to get the value of the key. It takes the handle (ID) of the key as an argument.

Writing to a key

pthread_setspecific() API can be used to set the value to a key. It takes the handle (ID) of the key as argument.

Freeing the key

The pthread_key_delete() API deletes the key in all the threads. Once the key is deleted, no thread should use the old handle to set and get the key value. All the above APIs are part of the libpthread library.

The following summarizes the main points of POSIX TLS :

  • The key is 4 bytes of space.
  • The key created successfully means, that a separate key is available in all the threads. The same handle is used to access in all threads.
  • A maximum of PTHREAD_KEY_MAX keys can be created.
  • The key value can be read using the pthread_getspecific() API
  • The key value can be written using the pthread_setspecific() API.
  • The key can be created when needed and can be destroyed after use.
  • When a key is deleted, it is removed from all the threads.
  • If a thread is created after the key is created, then the key is available in the new thread from the beginning.

It is important to know if the DLL is written on top of the Open C platform, so that both POSIX TLS as well as Symbian TLS techniques can be used. Both of these techniques work without failure.

Example code for using POSIX TLS

#inlcude <pthread.h>
#inlcude <stdio.h>
#inlcude <stdlib.h>
#inlcude <unistd.h>

static pthread_key_t key;
void *thread_func_1(void*)
{
   void* rc2;
   pthread_setspecific(key, (void *)(200));
   printf("Setting Thread_1 key value to %d\n", 200);
   sleep(5);
   rc2 = pthread_getspecific(key);
   printf("Getting Thread_1 key value %d\n", rc2);
   pthread_exit(0);
   return NULL;
}
void *thread_func_2(void*)
{
   void* rc2;
   sleep(1);
   pthread_setspecific(key, (void *)(400));
   printf("Setting Thread_2 key value to %d\n", 400);
   sleep(1);
   rc2 = pthread_getspecific(key);
   printf("Getting Thread_2 key value %d\n", rc2);
   pthread_exit(0);
   return NULL;
}
int main()
{
   pthread_t new_th_1;
   pthread_t new_th_2;
   void* rc1;
   /* Create the key */
   pthread_key_create(&key, NULL);
   /* Set the value for the main thread key */
   pthread_setspecific(key, (void *)(100));
   printf("Setting Main thread key value to %d\n", 100);
   /* Create 2 threads */
   pthread_create(&new_th1_1, NULL, thread_func_1, NULL);
   pthread_create(&new_th1_2, NULL, thread_func_2, NULL);
   /* Wait for thread to end execution */
   pthread_join(new_th_1, NULL);
   pthread_join(new_th_2, NULL);
   /* Get the value associated for the key in the main thread */
   rc1 = pthread_getspecific(key);
   printf("Getting Main thread key value %d\n", rc1);
   sleep(10);
   return 0;
}

The output is:

Setting Main thread key value to 100
Setting Thread_1 key value to 200
Setting Thread_2 key value to 400
Getting Thread_2 key value 400
Getting Thread_1 key value 200
Getting Main thread key value 100

Give feedback of this section

©Nokia 2006

Back to top

This material, including documentation and any related computer programs, is protected by copyright controlled by Nokia. All rights are reserved. Copying, including reproducing, storing, adapting or translating, any or all of this material requires the prior written consent of Nokia. This material also contains confidential information, which may not be disclosed to others without the prior written consent of Nokia.

Nokia is a registered trademark of Nokia Corporation. S60 and logo is a trademark of Nokia Corporation. Java and all Java-based marks are trademarks or registered trademarks of Sun Microsystems, Inc. Other company and product names mentioned herein may be trademarks or tradenames of their respective owners.


$title

S60 Open C
Threads, Processes, IPC, and Synchronization

Threads, Processes, IPC, and Synchronization

Table of Contents

How to invoke thread entry functions in hybrid applications
Solution 1
Solution 2
Solution 3
Solution 4

How to invoke thread entry functions in hybrid applications

Since Open C standard libraries can be used by hybrid applications with standard C, standard C++, and Symbian C++ codes, we can make use of some design patterns for using some of these APIs in such hybrid applications. One such example can be the use of pthread_create within C++ codes with many classes.

A prototype of pthread_create is shown below:

int pthread_create(pthread_t* threadhdl, pthread_attr_t* attrib, thread_begin_routine begin_routine,  void* param);

This function creates a thread, with attributes specified by attrib, within a process. If attrib is NULL, the default attributes will be used. On successful completion, pthread_create() will store the ID of the created thread in the location referenced by threadhdl and will create the thread for which the user-entry point will be begin_routine.

In case of hybrid applications, we can also refer to C++ methods and class members as thread_begin_routine. There are different ways in which we can have a class member function as thread_begin_routine. Let's take a scenario where a user wants to send a member function of a class as the ThreadEntry point:

Assume that the class is as shown below:

class Sample {
    public:
       Sample();
      ~Sample();
      void ThreadEntryFunction(void*);
      ...
      private:
      ...
   };

If the user tries to create a thread with the following code:

Sample sam;
pthread_t thrd;
pthread_attr_t attr;
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
int pId = pthread_create(&thrd, &attr, sam.ThreadEntryFunction, NULL);  // Error Here...

the code will cause a compilation error as we are referring to a class member as the thread entry function. There are different solutions to handle the resulting compilation error.

Solution 1

Change the function to static,

class Sample {
    public:
       Sample();
      ~Sample();
      static void ThreadEntryFunction(void* );
      ...
    private:
      ...
   };

and use it as follows:

int pId = pthread_create(&thrd, &attr, Sample::ThreadEntryFunction, NULL);

This solution does not allow us to access non-static members from a static function. So all the members that are referred to by function ThreadEntryFunction should be made static.

Solution 2

As we need to make all the class data members accessed within the static member function as static, the alternative will be to add one local function, which will act as the thread entry function and an send object to that function. This function will invoke the actual function as the thread entry function. The code below illustrates this:

void* EntryFunction(void* aPtr) {
   Sample* sam = static_castSample*>(aPtr);
   sam->ThreadEntryFunction();
}

And create the pthread using the following code:

Sample sam;
  ....
  int pId = pthread_create(&thrd, &attr, EntryFunction, &sam);

Solution 3

This solution is a variation of solution 2. We can make use of a template function which takes care of calling a predefined member function of any class. The requirement for this solution is that all the classes (object) that we are sending to the template function should have a thread entry function with the same name.

templatetypename <ClassName>
void* EntryFunction(void* aPtr) {
   ClassName* sam = static_cast<ClassName*>(aPtr);
   sam->ThreadEntryFunction();
}

The advantage is that the user can use it for any type of class, but we should make sure that there is a function named void ThreadEntryFunction() (with definition) in that class. We can impose this by having an abstract class with pure virtual method for ThreadEntryFunction(), so that all the derived classes will implement this function. The example below assumes that we have two classes:

class Sample {
public:
   Sample(int aVal = 0) : iVal(aVal) { }
   ~Sample() { }
   //Will be used as thread entry function
   void ThreadEntryFunction() {}
private:
   int iVal;
};

class OtherClass {
   public:
   OtherClass(int aVal = 0) : iVal(aVal) { }
   ~OtherClass() { }
   //Will be used as thread entry function
   void ThreadEntryFunction() {}
private:
   int iVal;
};

Notice that both Sample and OtherClass have a function ThreadEntryFunction(). This solution can be used as shown below:

int main() {
   Sample sam;
   OtherClass obj;
   pthread_t thrd;
   pthread_attr_t attr;
   pthread_attr_init(&attr);
   pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);

   pthread_create(&thrd, &attr, EntryFunction<Sample>,  &sam);
   pthread_create(&thrd, &attr, EntryFunction<OtherClass>,  &obj);
   pthread_attr_destroy(&attr);
   return 0;
}

Solution 4

This is a generic solution that may look a little complex at first, but is efficient to use.

The solution is as shown below:

template<class T, void (T::*EntryFunction)()>
void* MyThreadEntryFun(void* aPtr) {
   T* p = static_cast<T*>(aPtr);
   (p->*EntryFunction)();
   return 0;
}

This template thread entry function will take an object (pointer) and a function pointer that needs to be called. The signature or prototype of the class member function that will be passed should match the one mentioned in the template.

Let's assume that we have two classes as shown below:

class Sample {
public:
   Sample(int aVal = 0) : iVal(aVal) { }
   ~Sample() { }
   //Will be used as thread entry function
   void ThreadEntryFunctionOne() {}
private:
   int iVal;
};

class OtherClass {
public:
   OtherClass(int aVal = 0) : iVal(aVal) { }
   ~OtherClass() { }
   //Will be used as thread entry function
   void ThreadEntryFunctionTwo() {}
private:
   int iVal;
};

Observe the prototype of those two functions within the class. Notice that they have different names. Now, we can have some codes like the following:

int main() {
   Sample sam;
   OtherClass obj;
   pthread_t thrd;
   pthread_attr_t attr;
   pthread_attr_init(&attr);
   pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);

   pthread_create(&thrd, &attr, MyEntryFun<Sample, Sample::ThreadEntryFunctionOne>, &sam);
   pthread_create(&thrd, &attr, MyEntryFun<OtherClass, OtherClass::ThreadEntryFunctionTwo>, &obj);
   pthread_attr_destroy(&attr);
   return 0;
}

The advantage of this solution is that the user can call any function of a class as the thread entry point that has a matching prototype.

Give feedback of this section

©Nokia 2006

Back to top

This material, including documentation and any related computer programs, is protected by copyright controlled by Nokia. All rights are reserved. Copying, including reproducing, storing, adapting or translating, any or all of this material requires the prior written consent of Nokia. This material also contains confidential information, which may not be disclosed to others without the prior written consent of Nokia.

Nokia is a registered trademark of Nokia Corporation. S60 and logo is a trademark of Nokia Corporation. Java and all Java-based marks are trademarks or registered trademarks of Sun Microsystems, Inc. Other company and product names mentioned herein may be trademarks or tradenames of their respective owners.


Introduction to Glib

Getting started with Glib
Differences between OSS and Symbian Glib
Glib event loop
How to get Glib events in Symbian UI applications
An Introduction to libgmodule
Using exported global variables for Glib
An Introduction to Glib low memory handler
UHEAP markers and panics in Glib based applications
Using GThreads
Using GIOChannel
Using GCompletion

© Nokia 2007

Back to top


$title

S60 Open C
Introduction to Glib

Introduction to Glib

Table of Contents

Getting started with Glib

Getting started with Glib

The following files must be added to the MMP file of the project in order to build an application based on Glib:

  • Include Glib headers as system include files:
    SYSTEMINCLUDE \epoc32\include\stdapis\glib-2.0
  • Add libraries libc.lib and libglib.lib. The application will not link in the absence of the libc.lib library.

Give feedback of this section

©Nokia 2006

Back to top

This material, including documentation and any related computer programs, is protected by copyright controlled by Nokia. All rights are reserved. Copying, including reproducing, storing, adapting or translating, any or all of this material requires the prior written consent of Nokia. This material also contains confidential information, which may not be disclosed to others without the prior written consent of Nokia.

Nokia is a registered trademark of Nokia Corporation. S60 and logo is a trademark of Nokia Corporation. Java and all Java-based marks are trademarks or registered trademarks of Sun Microsystems, Inc. Other company and product names mentioned herein may be trademarks or tradenames of their respective owners.


$title

S60 Open C
Introduction to Glib

Introduction to Glib

Table of Contents

Differences between OSS and Symbian Glib
Memory allocation
Spawn APIs
Libgmodule APIs

Differences between OSS and Symbian Glib

The three areas of difference between the way Glib is implemented in Symbian OS and in OSS are as follows:

  • Memory allocation
  • Spawn APIs
  • Libgmodule APIs

Memory allocation

The Symbian Glib implementation does not follow the default OSS behavior. The default OSS behavior is such that in the event of a memory allocation failure the application, using g_malloc() and not g_try_malloc(), will call abort() and thus terminate the application.

The Symbian implementation, on the other hand will return NULL and not terminate the application in the event of a memory allocation failure. Thus, it is the application’s responsibility to check if the memory allocation failed due to the needed tasksl.

Generally, all the application code written using glib does not perform memory allocation failure checks. Hence, for Symbian Glib it is the application programmer's responsibility to check for memory allocation failures.

Spawn APIs

Glib has a set of APIs for process spawning. Since Symbian OS does not support the fork() and exec() APIs, the g_spawn*APIs have limitations in their functionality. The limitations are explained per API in detail below.

g_spawn_async_with_pipes: The signature of this API is

gboolean g_spawn_async_with_pipes (
    const gchar *working_directoy,
    gchar **argv,
    gchar **envp,
    GSpawnFlags flags,
    GSpawnChildSetupFunc child_setup,
    gpointer user_data,
    GPid *child_pid,
    gint  *standard_input,
    gint *standard_output,
    gint *standard_error,
    GError **error);

This API executes the program asynchronously: that is, the caller does not block for the spawned process to complete. The setting of the following parameters does not have any effect in Symbian Glib:

  • working_directory
  • envp

If a value other than NULL is passed for standard_input, standard_ouput, or standard_error, the value at the location is set to -1.

g_spawn_async: The signature of the API is

gboolean g_spawn_async (
    const gchar *working_directory,
    gchar **argv,
    gchar **envp,
    GSpawnFlags flags,
    GSpawnChildSetupFunc child_setup,
    gpointer user_data,
    GPid *child_pid,
    GError **error);

This API calls g_spawn_async_with_pipes without any pipes. The setting of the following parameters does not have any effect in Symbian Glib:

  • working_directory
  • envp

g_spawn_sync: The signature of the API is

gboolean g_spawn_sync(
    const gchar *working_directory,
    gchar **argv,
    gchar **envp,
    GSpawnFlags flags,
    GSpawnChildSetupFunc child_setup,
    gpointer user_data,
    gchar **standard_output,
    gchar **standard_error,
    gint *exit_status,
    GError **error);

This API executes the program synchronously: that is, the calling process waits for the spawned process to complete before returning. The setting of the following parameters does not have any effect on Symbian Glib:

  • working_directory
  • envp

If a value other than NULL is passed for standard_output or standard_error, the value at the location is set to -1.

g_spawn_command_line_sync: The signature of the API is

gboolean g_spawn_command_line_sync(
    const gchar *command_line,
    gchar **standard_output,
    gchar **standard_error,
    gint *exit_status,
    GError **error);

This API is a simple version of g_spawn_sync in which there are fewer number of parameters involved, and it takes a command line instead.

If a value other than NULL is passed for standard_output or standard_error, the value at the location is set to -1.

In many spawn APIs a variable of type GSpawnFlags is passed. The following flags have no effect:

  • G_SPAWN_LEAVE_DESCRIPTORS_OPEN
  • G_SPAWN_STDOUT_TO_DEV_NULL
  • G_SPAWN_STDERR_TO_DEV_NULL
  • G_SPAWN_CHILD_INHERITS_STDIN

Libgmodule APIs

Libgmodule has APIs that provide a portable method for dynamically loading 'plug-ins' or, in other words, DLLs. There are some deviations in the libgmodule APIs on Symbian OS as compared to the OSS behavior. The APIs with their limitations are explained in detail below.

g_module_open: The signature of the API is

GModule *g_module_open (const gchar *file_name, GModuleFlags flags);

This API is used to open a module. The default OSS behavior when file_name is passed as NULL such that it obtains a GModule representing the main program. In Symbian Glib, NULL is returned instead. Of all the GModuleFlags only G_MODULE_BIND_LOCAL is honored. If the user passes any other flags, the module is still opened using the flag G_MODULE_BIND_LOCAL.

g_module_symbol: The signature of the API is

gboolean g_module_symbol (GModule *module, const gchar *symbol_name, gpointer *symbol);

This API gets the symbol from the GModule opened using g_module_open. In OSS, symbol_name is the name of the symbol that needs to be queried from the GModule. In Symbian OS, the ordinal number (passed as a string) of the symbol name must be passed and not the symbol name.

See also Introduction to libgmodule for more details about libgmodule.

Give feedback of this section

©Nokia 2006

Back to top

This material, including documentation and any related computer programs, is protected by copyright controlled by Nokia. All rights are reserved. Copying, including reproducing, storing, adapting or translating, any or all of this material requires the prior written consent of Nokia. This material also contains confidential information, which may not be disclosed to others without the prior written consent of Nokia.

Nokia is a registered trademark of Nokia Corporation. S60 and logo is a trademark of Nokia Corporation. Java and all Java-based marks are trademarks or registered trademarks of Sun Microsystems, Inc. Other company and product names mentioned herein may be trademarks or tradenames of their respective owners.


$title

S60 Open C
Introduction to Glib

Introduction to Glib

Table of Contents

Glib event loop
Creating an event loop
Creating a new source
Customizing the main loop iteration

Glib event loop

The glib event loop manages all the sources of an event available for glib. These events can come from different kinds of sources like file descriptors (plain file descriptors, sockets, or pipes), time-outs, or any kind of source that can be added.

To allow multiple independent sets of events to be handled in different threads, each source is associated with a GMainContext.

Each event source is given a priority. The default priority is G_PRIORITY_DEFAULT and its value is 0. Values less than 0 denote higher priority and values greater than zero denote lower priority. The events from higher priority sources are processed earlier than events from lower priority sources.

The GMainLoop data type represents an event loop. GMainContext is a parameter to GMainLoop. If GMainContext is passed as NULL, then a main loop with the default context is created. After the sources are added to GMainContext and a GMainLoop variable is created, g_main_loop_run() is called. This checks continuously for events from its sources and dispatches them. Finally when all the events have been processed, g_main_loop_quit() must be called to return from g_main_loop_run().

NOTE! sources are associated with GMainContext and not with GMainLoop. Events from sources will be checked and dispatched from all the GMainLoop the GMainContext is associated with.

Creating an event loop

Glib provides ready-made functions for adding the following sources either to the default context or to a custom context:

  • time-outs
  • I/O
  • child watch
  • idle source (events from idle sources are ready if none of the other sources with priority > G_PRIORITY_DEFAULT are ready)

The following example code demonstrates the way to add a time-out source to the default context. The program makes 10 calls to timeout_callback(), which at the 10th call, calls g_main_loop_quit to make the main loop return.

#include <glib.h>

gboolean timeout_callback(gpointer data)
{
    static int i = 0;

    i++;
    g_print("timeout_callback called %d times\n", i);
    if (10 == i)
    {
        g_main_loop_quit( (GMainLoop*)data );
        return FALSE;
    }

    return TRUE;
}

int main()
{
    GMainLoop *loop;

    loop = g_main_loop_new ( NULL , FALSE );

    // add source to default context
    g_timeout_add (100 , timeout_callback , loop);
    g_main_loop_run (loop);
    g_main_loop_unref(loop);

    return 0;
}

The following code demonstrates the method to add the time-out source to a different context than the default context:

#include <glib.h>

gboolean timeout_callback(gpointer data)
{
    static int i = 0;

    i++;
    g_print("timeout_callback called %d times\n",i);

    if(10 == i)
    {
        g_main_loop_quit((GMainLoop*)data);
        return FALSE;
    }

    return TRUE;
}

int main()
{
    GMainLoop *loop = NULL;
    GMainContext *context;
    GSource *source;
    int id;

    //create a new time-out source
    source = g_timeout_source_new(10);

    //create a context
    context = g_main_context_new();

    //attach source to context
    id = g_source_attach(source,context);

    //create a main loop with context
    loop = g_main_loop_new(context,FALSE);

    //set the callback for this source
    g_source_set_callback (source,timeout_callback,loop,NULL);

    g_main_loop_run (loop);

    g_main_loop_unref (loop);

    return 0;
}

The same process can be used for other default sources like child watch, I/O, and idle source since they are glib APIs that allow the creation of a source directly.

Creating a new source

The previous section applies only to four types of sources ( time-outs, I/O, child watch, and idle source ), for which glib provides ready-made functions. The program below demonstrates the creation of a new source.

#include <glib.h>

gboolean callback(gpointer data)
{
    static int i = 0;
    i++;
    g_print ("timeout_callback called %d times\n",i);
    if (10 == i)
    {
        g_main_loop_quit((GMainLoop*)data);
        return FALSE;
    }

    return TRUE;
}

gboolean prepare(GSource *source,gint *timeout_)
{
    *timeout_ = -1;
    return TRUE;
}

gboolean check(GSource *source)
{
    return TRUE;
}

gboolean dispatch(GSource *source,GSourceFunc callback,gpointer user_data)
{
    if (callback(user_data))
        return TRUE;
    else
        return FALSE;
}

int main()
{
    GMainLoop *loop = NULL;
    GMainContext *context;
    GSource *source;
    int id;

    //create a variable of type GSourceFuncs
    GSourceFuncs SourceFuncs =
    {
        prepare,
        check,
        dispatch,
        NULL
    };

    //create a new source
    source = g_source_new (&SourceFuncs , sizeof(GSource));

    //create a context
    context = g_main_context_new ();

    //attach source to context
    id = g_source_attach (source,context);

    //create a main loop with context
    loop = g_main_loop_new (context,FALSE);

    //set the callback for this source
    g_source_set_callback (source,callback,loop,NULL);

    g_main_loop_run (loop);
    g_main_loop_unref (loop);

    return 0;
}

The creation of a new source requires us to define at least 3 functions:

  • prepare Called before all the file descriptors are polled. If the source can determine that it is ready here (without waiting for the results of the poll() call), it should return TRUE. It can also return a time-out value which should be the maximum time-out (in milliseconds) which should be passed to the poll() call. The actual time-out used will be -1 if all sources returned -1, or it will be the minimum of all the timeout_values returned which were >= 0
  • check Called after all the file descriptors are polled. The source should return TRUE if it is ready to be dispatched.

    NOTE! Time may have passed since the previous prepare function was called, so the source should be checked again.

  • dispatch Called to dispatch the event source after it has returned TRUE in either its prepare or check function. The dispatch function is passed in a callback function and data. The callback function may be NULL if the source was never connected to a callback using g_source_set_callback(). The dispatch function should call the callback function with user_data and the additional parameters that are needed for this type of event source.

Customizing the main loop iteration

Single iteration of GMainContext can be run in g_main_context_iteration (). When a more detailed control of how the main loop runs is desired call the component function of g_main_context iteration() directly.

The component functions of g_main_context iteration() are listed below:

  • g_main_context_prepare()
  • g_main_context_query()
  • g_main_context_check()

Give feedback of this section

©Nokia 2006

Back to top

This material, including documentation and any related computer programs, is protected by copyright controlled by Nokia. All rights are reserved. Copying, including reproducing, storing, adapting or translating, any or all of this material requires the prior written consent of Nokia. This material also contains confidential information, which may not be disclosed to others without the prior written consent of Nokia.

Nokia is a registered trademark of Nokia Corporation. S60 and logo is a trademark of Nokia Corporation. Java and all Java-based marks are trademarks or registered trademarks of Sun Microsystems, Inc. Other company and product names mentioned herein may be trademarks or tradenames of their respective owners.


$title

S60 Open C
Introduction to Glib

Introduction to Glib

Table of Contents

How to get Glib events in Symbian UI applications

How to get Glib events in Symbian UI applications

Symbian UI applications run an event loop that is based on CActiveScheduler. The active scheduler is started by the UI framework immediately after the UI has been created (that is., after ConstructL() of CEikAppUi-derived class).

In order to receive events from Glib event sources, an active object can be added to the active scheduler especially for this purpose. The active object runs one iteration of the glib event loop every time it gets scheduled.

NOTE! The scheduling logic in the sample code provided below is based on a simple timer; more complex scheduling logic can be implemented depending on the requirement of the application.

/********* GlibEventHandler.h *********************/

class CGlibEventHandler: public CActive
{
public:
    static CGlibEventHandler* NewL();
    ~CGlibEventHandler();
       void RunL();
       void DoCancel();
       void Start();
       void Stop();
private:
       CGlibEventHandler();
       void ConstructL();
       RTimer iTimer;
};

/********* GlibEventHandler.h *********************/

/********* GlibEventHandler.cpp *******************/

CGlibEventHandler* CGlibEventHandler::NewL()
{
       CGlibEventHandler* self = new(ELeave) CGlibEventHandler();
       CleanupStack::PushL(self);
       self->ConstructL();
       CleanupStack::Pop();
       return self;
}

CGlibEventHandler::CGlibEventHandler():CActive(EPriorityStandard)
{
}

void CGlibEventHandler::ConstructL()
{
    User::LeaveIfError(iTimer.CreateLocal());
    CActiveScheduler::Add(this);
}

CGlibEventHandler::~CGlibEventHandler()
{
    Cancel();
    iTimer.Close();
}

void CGlibEventHandler::Start()
{
    iTimer.After(iStatus, TTimeIntervalMicroSeconds32(1000));
    SetActive();
}

void CGlibEventHandler::Stop()
{
    Cancel();
}

void CGlibEventHandler::RunL()
{
    g_main_context_iteration(NULL, FALSE);
    iTimer.After(iStatus, TTimeIntervalMicroSeconds32(1000));
    SetActive();
}

void CGlibEventHandler::DoCancel()
{
    iTimer.Cancel();
}

/********* GlibEventHandler.cpp *******************/

The following is done in the application:

GMainLoop* mainloop = g_main_loop_new(NULL, FALSE);
CGlibEventHandler* glibeventhandler = NULL;
glibeventhandler = CGlibEventHandler::NewL();
glibeventhandler->Start();

Give feedback of this section

©Nokia 2006

Back to top

This material, including documentation and any related computer programs, is protected by copyright controlled by Nokia. All rights are reserved. Copying, including reproducing, storing, adapting or translating, any or all of this material requires the prior written consent of Nokia. This material also contains confidential information, which may not be disclosed to others without the prior written consent of Nokia.

Nokia is a registered trademark of Nokia Corporation. S60 and logo is a trademark of Nokia Corporation. Java and all Java-based marks are trademarks or registered trademarks of Sun Microsystems, Inc. Other company and product names mentioned herein may be trademarks or tradenames of their respective owners.


$title

S60 Open C
Introduction to Glib

Introduction to Glib

Table of Contents

An Introduction to libgmodule

An Introduction to libgmodule

Libgmodule has APIs that provide a portable method for dynamically loading 'plug-ins' or, in other words, DLLs. Any program that wants to dynamically load modules must be linked to libgmodule.

In order to use the libgmodule APIs, we must check whether dsynamic loading of DLLs is supported by the platform by using the g_module_supported() API which returns TRUE if the dynamic loading of modules is supported. Open C provides the implementation of libdl, where dynamic loading of modules is supported, but to write code which runs across platforms we must do a check before using the libgmodule APIs.

If the dynamic loading of DLLs is supported, we can open the module using g_module_open(). It takes the name of the module as the first argument and the flags as the second argument.

NOTE! G_MODULE_BIND_LOCAL is the only flag currently supported. The other flags are not supported. If the user specifies any other flag, the module is loaded using the flag G_MODULE_BIND_LOCAL and not by the user-specified flag.

GModule * g_module_open(const gchar *file_name, GModuleFlags flags);
  • file_name The name of the file containing the module.
  • flags The flags used for opening the module.

Once the module is opened, the user can find the module symbols (for example,. function names) using the function g_module_symbol().

gboolean g_module_symbol (GModule *module, const gchar *symbol_name, gpointer *symbol);
  • *module This is a pointer returned when a module is opened using g_module_open()
  • symbol_name This is the ordinal number of the symbol that one wants to open. There is a difference between Symbian Glib and OSS Glib; as in Linux the symbol_name is the name of the symbol and not a number. The ordinal number must be passed as a string and not a number.
  • symbol This is the pointer to the symbol value

The GModule can be closed by using the g_module_close()API. This API returns TRUE if it successfully closed the module; else it returns FALSE.

gboolean g_module_close(GModule *module);
  • *module The GModule to close.

The following example code explains the usage of the libgmodule APIs. It opens a module libmoduletestplugin_a.dll and uses its gplugin_a_func1() API which is ordinal number 1. Finally, the module is closed.

#include <gmodule.h>
#include <glib.h>

typedef int (*SimpleFunc) (void);

int main()
{
  GModule *module = NULL;
  gpointer func;
  SimpleFunc f_a;
  int retVal;

  if (!g_module_supported())
  {
        g_print ("Dynamic Opening of modules is not supported");
        return 1;
  }

  /* G_MODULE_BIND_LAZY is overridden and the module is opened with
   * flag G_MODULE_BIND_LOCAL
   */
  module = g_module_open("libmoduletestplugin_a.dll",G_MODULE_BIND_LAZY);

  // 1 is the ordinal number for gplugin_a_func1
  if(module && g_module_symbol(module, "1" ,&func))
  {
        f_a = (SimpleFunc)func;
        retVal = f_a();
        g_print("Function at ordinal number 1 of module libgmodule_a returns %d",retVal);
  }
  else
  {
        g_print("Error quering symbol at ordinal number 1");
        return 1;
  }

  return 0;
}

See alsoLibgmodule APIs section for more details about libgmodule limitations in the Symbian Glib implementation.

Give feedback of this section

©Nokia 2006

Back to top

This material, including documentation and any related computer programs, is protected by copyright controlled by Nokia. All rights are reserved. Copying, including reproducing, storing, adapting or translating, any or all of this material requires the prior written consent of Nokia. This material also contains confidential information, which may not be disclosed to others without the prior written consent of Nokia.

Nokia is a registered trademark of Nokia Corporation. S60 and logo is a trademark of Nokia Corporation. Java and all Java-based marks are trademarks or registered trademarks of Sun Microsystems, Inc. Other company and product names mentioned herein may be trademarks or tradenames of their respective owners.


$title

S60 Open C
Introduction to Glib

Introduction to Glib

Table of Contents

Using exported global variables for Glib

Using exported global variables for Glib

Glib on Linux has many global variables like g_idle_funcs exported from the .so file. Symbian OS does not support exporting global variables from the DLL. Therefore, the global variable of glib cannot be exported and hence used directly.

The users must include the header glib_global.h for libglib global variables and gobject_global.h for libgobject global variables. The other two DLLs - libgmodule and libgthread - do not have any exported global variables.

NOTE! The header must be included only after all the other headers in the file.

The following example code snippet explains the usage. This is a code that prints the version of glib being used.

The variables listed below are libglib global variables:
  • glib_major_version
  • glib_minor_version
  • glib_micro_version
#include <stdio.h>
#include <glib.h>
#include <glib_global.h> // Always include as the last include

int main()
{
    /* glib_major_version,glib_minor_version and
     * glib_micro_version are libglib global variables
     */
    printf("The version of glib that you are using is %d.%d.%d",
            glib_major_version,glib_minor_version,glib_micro_version);
    getchar();
    return 0;
}

Give feedback of this section

©Nokia 2006

Back to top

This material, including documentation and any related computer programs, is protected by copyright controlled by Nokia. All rights are reserved. Copying, including reproducing, storing, adapting or translating, any or all of this material requires the prior written consent of Nokia. This material also contains confidential information, which may not be disclosed to others without the prior written consent of Nokia.

Nokia is a registered trademark of Nokia Corporation. S60 and logo is a trademark of Nokia Corporation. Java and all Java-based marks are trademarks or registered trademarks of Sun Microsystems, Inc. Other company and product names mentioned herein may be trademarks or tradenames of their respective owners.


$title

S60 Open C
Introduction to Glib

Introduction to Glib

Table of Contents

An Introduction to Glib low memory handler
Illustration of the mechanism to handle a memory allocation failure scenario

An Introduction to Glib low memory handler

The default behavior of Glib in Linux is such that in case of a memory allocation failure, the Glib memory allocation API will call abort and hence terminate the application.

Memory allocation failures are more likely on a mobile device and aborting the application in such cases is undesirable. Therefore, the implementation of Glib for Symbian OS has been modified so that the Glib memory allocation APIs return NULL and do not call abort(). This requires the application written using Glib to start handling memory allocation failures which they are currently not doing.

If we, for example, want to change the first character of a string with z and return the string to the caller a Glib code for this can be written as follows

gchar * f1(gchar * x)
{
       gchar *temp;
    temp = g_strdup(x);
    temp[0] = ‘z’;
    return temp;
}

If there is a memory allocation failure in Linux, the call to g_strdup which internally uses g_malloc will cause the application to abort. However, in Symbian OS the g_malloc() function will return NULL, but the implementation of g_strdup() is such that the return value of g_malloc( ) is not checked for NULL. This causes the g_strdup() API to panic or crash the application. Thus, a mechanism to deal with the failures, panics or crash resulting from low memory situations within Symbian OS is needed.

Illustration of the mechanism to handle a memory allocation failure scenario

The user needs to initialize the framework which handles the low memory scenarios using the below-mentioned macros:

  1. SET_LOW_MEMORY_TRAP(failure_value) This macro will set a trap handler for low memory cases. If case there is an allocation failure, the failure value will be returned from the function where the trap handler is set.
  2. SET_LOW_MEMORY_TRAP_VOID() This will do the same as the above except that the function where this is set will just return. This will typically be used by functions which return void. In this case, however, the caller must check the errno value. If it is ENOMEM, then the user must handle things appropriately.
  3. REMOVE_LOW_MEMORY_TRAP() This will remove the trap handler which was set.

The function f1() will now be rewritten as:

#include <glowmem>
gchar * f1(gchar * x)
{
    gchar *temp;
  SET_LOW_MEMORY_TRAP(NULL);
  temp = g_strdup(x);
    temp[0] = ‘z’;
    REMOVE_LOW_MEMORY_TRAP():
    return temp;
}

If there is a memory allocation failure when the above function f1() is called, then f1() will return NULL to its caller. The caller of f1() is expected to check the failure value of f1() instead of ignoring the same.

Some words of caution: The macro SET_LOW_MEMORY_TRAP() defines a variable so it is necessary to make the call after all the local variables declarations in C. REMOVE_LOW_MEMORY_TRAP() must be called just before the return from the function, which means that if there are four return statements in the function then all of them must be preceded with a call to REMOVE_LOW_MEMORY_TRAP().

Give feedback of this section

©Nokia 2006

Back to top

This material, including documentation and any related computer programs, is protected by copyright controlled by Nokia. All rights are reserved. Copying, including reproducing, storing, adapting or translating, any or all of this material requires the prior written consent of Nokia. This material also contains confidential information, which may not be disclosed to others without the prior written consent of Nokia.

Nokia is a registered trademark of Nokia Corporation. S60 and logo is a trademark of Nokia Corporation. Java and all Java-based marks are trademarks or registered trademarks of Sun Microsystems, Inc. Other company and product names mentioned herein may be trademarks or tradenames of their respective owners.


$title

S60 Open C
Introduction to Glib

Introduction to Glib

Table of Contents

UHEAP markers and panics in Glib-based applications

UHEAP markers and panics in Glib-based applications

The 2.10.x version of Glib has introduced a new type of memory allocator called slice allocator. These allocators allocate memory in page sizes even for a small request of something like 20 bytes. Once a huge chunk has been allocated, all the future memory requests are granted using the chunk that was allocated for the first memory request. Once the free pool runs out, another huge chunk is allocated.

Whenever the memory is freed using g_slice_free1(), the memory is not returned to the OS; instead it is maintained by glib as free memory which is used to for future memory requests.

The following example explains the issue. The code given below uses slice allocators to allocate 10 bytes of memory using g_slice_alloc() and subsequently frees it using g_slice_free1(). The code panics at __UHEAP_MARKEND, although the memory that has been allocated has been deallocated. This is because all the allocated memory on the heap has not been deallocated. When the user calls g_slice_free1() to free up, the memory is not freed; instead, glib will keep it as part of the free pool for future allocation.

#include <glib.h>
#include <e32base.h>

int main()
{
  char *x;
  __UHEAP_MARK;
  x = (char *)g_slice_alloc(10);
  g_slice_free1(10,x);
  __UHEAP_MARKEND;
  return 0;
}

To get around this problem, define an environment variable G_SLICE and set it to “always-malloc”.

NOTE! It is necessary that this environment variable is set before any glib call that can cause memory allocation. If the environment variable is set after any g_slice* APIs have been called either from the application code or from glib library code, setting it has not effect.

The code below demonstrates the usage.

#include <glib.h>
#include <e32base.h>
int main()
{
  char *x;
  __UHEAP_MARK;
     g_setenv("G_SLICE","always-malloc",1);
  x = (char *)g_slice_alloc(10);
  g_slice_free1(10,x);
 __UHEAP_MARKEND;
 return 0;
}

NOTE! G_SLICE is just a debugging environment variable. Setting it to “always-malloc” can help in detecting memory leaks in application code. This setting need not and should not be done in the release code since doing it overrides the glib memory allocation mechanism and hence may result in loss of efficiency. The slice allocators are used by other glib APIs like GList, GSList, GNode, and so on. Thus setting the environment variable is necessary if the application makes use of any such APIs that might use slice allocators.

Give feedback of this section

©Nokia 2006

Back to top

This material, including documentation and any related computer programs, is protected by copyright controlled by Nokia. All rights are reserved. Copying, including reproducing, storing, adapting or translating, any or all of this material requires the prior written consent of Nokia. This material also contains confidential information, which may not be disclosed to others without the prior written consent of Nokia.

Nokia is a registered trademark of Nokia Corporation. S60 and logo is a trademark of Nokia Corporation. Java and all Java-based marks are trademarks or registered trademarks of Sun Microsystems, Inc. Other company and product names mentioned herein may be trademarks or tradenames of their respective owners.


$title

S60 Open C
Introduction to Glib

Introduction to Glib

Table of Contents

Using GThreads

Using GThreads

Glib threads provide a portable way of writing multi-threaded applications. There are:

  • primitives for mutexes to protect concurrent accesses to portions of the memory
  • primitives for conditional variables to allow synchronization between threads
  • primitives for thread-private data that every thread has an instance of
  • APIs for creating and managing threads.

To use thread-related APIs the application must link to libgthread.lib. The function g_thread_init() must be called to initialize the thread system before calling any other thread-related functions.

NOTE! The function g_thread_init() must be called only once. The second call to it will abort the application.

The code given below verifies whether the thread system is initialized :

if (!g_thread_supported ())
    g_thread_init (NULL);

g_thread_init() can be called with a non-NULL parameter; however, the user must be sure of what is done since this will override the default thread implementation.

The following example code explains the usage of some of the thread APIs. In the example code we create NTHREADS threads. We wait in the main thread for all the threads to start before proceeding with some other work. Finally we join to all the threads so that the main thread waits for all the other threads to terminate.

#include <glib.h>

/* g_mutex_lock is a macro that uses the dll global variable
 * g_thread_functions_for_glib_use. To use the global variable
 * we must include glib_global.h.
 */
#include <glib_global.h> // Always include as the last include.

#define NTHREADS 5

int no_threads = 0;
GMutex *mutex;
GCond *cond;

void* thread_function(void *data)
{
    /*
    .
    local data declaration
    .
     */

    // lock on the mutex before changing the global variable no_threads
    g_mutex_lock(mutex);
    no_threads++;

    //do a broadcast on the conditional variable once NTHREDS have been created
    if(no_threads == NTHREADS)
        g_cond_broadcast(cond);

    //unlock the mutex
    g_mutex_unlock(mutex);

    /*
    .
    some code
    .
     */

    return NULL;

}

int main ()
{
    int i;
    GThread *thread[NTHREADS];
    /*
     .
     other local data declaration
     .
      */

    if(!g_thread_supported())
        g_thread_init (NULL);

    mutex = g_mutex_new ();
    cond = g_cond_new ();

    for(i=0; i<NTHREADS; i++)
        thread[i] = g_thread_create(thread_function, NULL,TRUE, NULL);

    g_mutex_lock (mutex);

    if (no_threads < NTHREADS)
        g_cond_wait (cond, mutex);

    g_mutex_unlock (mutex);

    /*
    .
    some code
    .
     */

    for(i=0; i<NTHREADS; i++)
        g_thread_join(thread[i]);

    g_mutex_free(mutex);
    g_cond_free(cond);

    /*
    .
    some code
    .
     */

    return 0;
}

Give feedback of this section

©Nokia 2006

Back to top

This material, including documentation and any related computer programs, is protected by copyright controlled by Nokia. All rights are reserved. Copying, including reproducing, storing, adapting or translating, any or all of this material requires the prior written consent of Nokia. This material also contains confidential information, which may not be disclosed to others without the prior written consent of Nokia.

Nokia is a registered trademark of Nokia Corporation. S60 and logo is a trademark of Nokia Corporation. Java and all Java-based marks are trademarks or registered trademarks of Sun Microsystems, Inc. Other company and product names mentioned herein may be trademarks or tradenames of their respective owners.


$title

S60 Open C
Introduction to Glib

Introduction to Glib

Table of Contents

Using GIOChannel
Using GIOChannel in Glib main loops

Using GIOChannel

GIOChannel provides a portable method for using file descriptors, sockets and pipes and integrating them into the Glib main loop.

The g_io_channel_unix_new() API takes a file descriptor as an input parameter and is used to create a new GIOChannel. Alternatively, the g_io_channel_new_file() API can be used to create a channel for a file. Once the channel is created, it can be used in a generic manner.

To read a channel, APIs such as the following can be used:

  • g_io_channel_read_chars()
  • g_io_channel_read_line()
  • g_io_channel_read_to_end()

To write to a channel an API like g_io_channel_write_chars() is used.

To set the position in the current GIOChannel, g_io_channel_seek_position() can be used.

Finally the channel can be closed using g_io_channel_shutdown().

The following is an example code where a file descriptor to a plain file is used to create a GIOChannel, and then the contents of the file are read in chunks of 100 bytes and printed using g_print. Finally the channel is closed.

#include <glib.h>
#include <stdio.h>

int main(int argc, char *argv[])
{
    GIOChannel *channel;
    gchar buf[100];
    gsize bytes_read;
    FILE *fp;

    if(argc != 2)
    {
        g_print("usage:cat <file_name>\n");
        g_print("Press any key to exit\n");
        getchar();
        return 1;
    }

    fp = fopen(argv[1],"r");

    if(!fp)
    {
        g_print("Unable to open the file %s\n",argv[1]);
        return 1;
    }

    channel = g_io_channel_unix_new(fileno(fp));

     do
     {
        g_io_channel_read_chars(channel,buf,100,&bytes_read,NULL);
        g_print("%s",buf);

    }
    while(bytes_read > 0);

    g_io_channel_shutdown(channel,TRUE,NULL);

    fclose(fp);

    return 0;
}

In the example below, a sample code to copy a file is written. In the code, channels are opened using g_io_channel_new_file(). The contents of the file are read using g_io_channel_read_chars(), and the contents are written to a new file using g_io_channel_write_chars().

#include <glib.h>
#include <stdio.h>

int main(int argc, char *argv[])
{
    GIOChannel *in_channel,*out_channel;
    gchar buf[100];
    gsize bytes_read,bytes_written;
    GError *error = NULL;

    if(argc != 3)
    {
        g_print("usage:<cp SOURCE> <DESTINATION>\n");
        g_print("Press any key to exit\n");
        getchar();
        return 1;
    }

    in_channel = g_io_channel_new_file(argv[1],"r",&error);

    if(!in_channel)
    {
        g_print("Unable to open the file %s to read\n",argv[1]);
        g_print("Press any key to exit\n");
        getchar();
        return 1;
    }

    out_channel = g_io_channel_new_file(argv[2],"w",&error);

    if(!out_channel)
    {
        g_print("Unable to open the file %s to write\n",argv[2]);
        g_print("Press any key to exit\n");
        getchar();
        return 1;
    }

    do
    {
        g_io_channel_read_chars(in_channel,buf,100,&bytes_read,&error);
        if(error)
        {
            g_print("Error while reading file %s\n",argv[1]);
            g_print("Press any key to exit\n");
            getchar();
            return 1;
        }

        g_io_channel_write_chars(out_channel,buf,bytes_read,&bytes_written,&error);
        if(error)
        {
            g_print("Error while writing file %s\n",argv[2]);
            g_print("Press any key to exit\n");
            getchar();
            return 1;
        }
    }
    while(bytes_read > 0);

       g_io_channel_shutdown(in_channel,TRUE,&error);
    if(error)
    {
        g_print("Error has occured\n");
        g_print("Press any key to exit\n");
        getchar();
        return 1;
    }

    g_io_channel_shutdown(out_channel,TRUE,&error);
     if(error)
    {
        g_print("Error has occured\n");
        g_print("Press any key to exit\n");
        getchar();
        return 1;
    }

    g_print("File copied successfully...\n");
    getchar();

    return 0;
}

Using GIOChannel in Glib main loops

GIOChannel provides a way to integrate file descriptors to main loops.

The following code demonstrates the usage.

In the code, a pipe is created. A thread is created which writes to the write end of the pipe. The main loop checks if the other end of the pipe is ready to read. If it is, then the callback function is called. The callback calls g_main_loop_quit, and the main loop is terminated and g_main_loop_run() returns.

#include <glib.h>
#include <stdio.h>

int fd[2];

void *thread_function(void *data)
{
    // call sleep so that the main loop source is not ready immediately
    sleep(10);

    write(fd[1],"GIOChannel main loop example",29);
    return NULL;
}

gboolean my_callback(GIOChannel *source,GIOCondition condition,gpointer data)
{
    char buf[100];

    read(fd[0],buf,sizeof(buf));
    g_print("%s",buf);

    getchar();

    g_main_loop_quit((GMainLoop *)data);

    return FALSE;
}

int main()
{
    GMainLoop *loop;
    GIOChannel *channel;

    pipe(fd);

    channel = g_io_channel_unix_new(fd[0]);

    g_thread_init(NULL);
    g_thread_create(thread_function,NULL,TRUE,NULL);

    loop = g_main_loop_new(NULL,FALSE);
    g_io_add_watch(channel,G_IO_IN | G_IO_HUP | G_IO_ERR,(GIOFunc)my_callback,loop);
    g_main_loop_run(loop);

    g_io_channel_shutdown(channel,TRUE,NULL);

    return 0;
}

Give feedback of this section

©Nokia 2006

Back to top

This material, including documentation and any related computer programs, is protected by copyright controlled by Nokia. All rights are reserved. Copying, including reproducing, storing, adapting or translating, any or all of this material requires the prior written consent of Nokia. This material also contains confidential information, which may not be disclosed to others without the prior written consent of Nokia.

Nokia is a registered trademark of Nokia Corporation. S60 and logo is a trademark of Nokia Corporation. Java and all Java-based marks are trademarks or registered trademarks of Sun Microsystems, Inc. Other company and product names mentioned herein may be trademarks or tradenames of their respective owners.


$title

S60 Open C
Introduction to Glib

Introduction to Glib

Table of Contents

Using GCompletion

Using GCompletion

GCompletion provides a method for automatic string completion using a group of target strings. This is typically used for file name completion as is common in many UNIX shells. A possible use of such APIs in a mobile device application is the contacts application. For example, if all the names that begin with a particular prefix, say "abc", are to be displayed, these APIs can be used to get and display all the names that begin with "abc".

A GCompletion is created using g_completion_new(). Target items are added using g_completion_add_items(). This API takes a doubly-linked list item, GList, as a parameter. Items are removed using g_completion_clear_items() and g_completion_remove_items(). A completion attempt is requested using g_completion_complete() or g_completion_complete_utf8(). A GCompletion is freed using g_completion_free().

Generally a GCompletion item is a string. The default function used to compare a string is strncmp(). If a function other than it is desired, then it can be set using the function g_completion_set_compare(). If an arbitrary data structure is to be compared, a GCompletionFunc is to be provided to g_completion_new().

The following code demonstrates the usage of GCompletion APIs.

In the code a GCompletion is created using g_completion_new(). Target strings are added using g_completion_add_items(). The comparison function is changed to g_ascii_strncasecmp() to allow matches without the consideration of case. A completion attempt for the string “aB” and the same is printed using g_print(). Finally the GCompletion is freed using g_completion_free().

#include <glib.h>

int main ()
{
    GCompletion *cmp;
    GList *items;
    gchar *prefix;

    //create a new GCompletion
    cmp = g_completion_new (NULL);

    //create a new GList to create a set of target strings.
    items = NULL;
    items = g_list_append (items, "AbcDEF");
    items = g_list_append (items, "bc");
    items = g_list_append (items, "bd");

    //add the target strings
    g_completion_add_items (cmp, items);

    //change the comparison API to g_ascii_strncasecmp
    g_completion_set_compare(cmp,g_ascii_strncasecmp);

    //find the first match
    items = g_completion_complete (cmp, "aB", &prefix);

    g_print("The match for aB is %s",prefix);
    getchar();

    g_free (prefix);

    g_completion_free(cmp);
    return 0;
}

Give feedback of this section

©Nokia 2006

Back to top

This material, including documentation and any related computer programs, is protected by copyright controlled by Nokia. All rights are reserved. Copying, including reproducing, storing, adapting or translating, any or all of this material requires the prior written consent of Nokia. This material also contains confidential information, which may not be disclosed to others without the prior written consent of Nokia.

Nokia is a registered trademark of Nokia Corporation. S60 and logo is a trademark of Nokia Corporation. Java and all Java-based marks are trademarks or registered trademarks of Sun Microsystems, Inc. Other company and product names mentioned herein may be trademarks or tradenames of their respective owners.


Compilers and IDEs

How to use GCCE and Open C
How to use Carbide.c++ and Open C
How to promote char in comparison with RVCT

© Nokia 2007

Back to top


$title

S60 Open C
Compilers and IDEs Using Open C

Compilers and IDEs Using Open C

Table of Contents

How to use GCCE and Open C

How to use GCCE and Open C

There are some known issues when compiling an Open C application containing the main() entry point and using the GCCE target compiler. A workaround is described in this section:

  1. Patch file \epoc32\tools\compilation_config\gcce.mk file with the following:
    AR=arm-none-symbianelf-ar
ARCHIVER=$(AR)
export ARCHIVER
  2. Include a header called staticlibinit_gcce.h once within the application source code.
  3. Modify the MMP file with the following statements:
    STATICLIBRARY libcrt0.lib
  4. Build the application using the GCCE target like abld build gcce urel.
The user code may look like the following:
#include <stdio.h>

#ifdef __GCCE__
#include <staticlibinit_gcce.h>  // This is needed in one file
#endif

int main(void)
{
   printf("Hello Open C!\n");
   printf("Press a character to exit!");
   getchar();
   return 0;
}

Give feedback of this section

©Nokia 2006

Back to top

This material, including documentation and any related computer programs, is protected by copyright controlled by Nokia. All rights are reserved. Copying, including reproducing, storing, adapting or translating, any or all of this material requires the prior written consent of Nokia. This material also contains confidential information, which may not be disclosed to others without the prior written consent of Nokia.

Nokia is a registered trademark of Nokia Corporation. S60 and logo is a trademark of Nokia Corporation. Java and all Java-based marks are trademarks or registered trademarks of Sun Microsystems, Inc. Other company and product names mentioned herein may be trademarks or tradenames of their respective owners.


$title

S60 Open C
Compilers and IDEs Using Open C

Compilers and IDEs Using Open C

Table of Contents

How to use Carbide.c++ and Open C
Inclusion of libc.lib in the MMP file
Order of the SYSTEMINCLUDE in the MMP file
Suppressing "illegal implicit conversion error"

How to use Carbide.c++ and Open C

To be able to use Open C and the Carbide.c++ provided by Nokia efficiently, the user must perform the following steps:

  • Define the system include files required by Open C. This is done in the System Options view in the project properties window.
  • Specify the needed Open C libraries:
    • libc.lib must always be specified.
    • Libraries must be specified for all build configurations.

NOTE! The include paths for Open C headers must be specified as well as the used Open C libraries.

NOTE! This must be done for all possible build configurations.

Give feedback of this section

Inclusion of libc.lib in the MMP file

libc.lib must be included in the MMP file for both the WINSCW as well as the target. The code will compile and link for WINSCW even if libc.lib is not mentioned in the MMP file, but will fail during execution. If libc.lib is not mentioned in the MMP file for the target, the code will compile but will fail during linking.

Order of the SYSTEMINCLUDE in the MMP file

Carbide.c++ 1.1 does not take into account the header file inclusion order as mentioned in the MMP file. This is a typical scenario when we need the headers from both open C and libc [symbian libc]. Eventhough the order of the SYSTEMINCLUDE in the MMP file is:
epoc32\include\stdapis
epoc32\include\libc
epoc32\include\libc will be included first followed by epoc32\include\stdapis .(It might be included on the basis of alphabetical order).

This issue can be resolved by manually changing the project properties in carbide.c++ IDE. In order to change the project properties in Carbide.c++ IDE :

  1. Go to Project
  2. Click on Property
  3. Click on C \C++ Build and choose the ToolSettings Tab

Suppressing "illegal implicit conversion error"

The code that makes use of implicit pointer casts will not compile with the WINSCW compiler. The compilation breaks with "illegal implicit conversion error". However, the same code will compile with gcc compiler. A work around for this problem without changing the code is to define a pragma.

©Nokia 2006

Back to top

This material, including documentation and any related computer programs, is protected by copyright controlled by Nokia. All rights are reserved. Copying, including reproducing, storing, adapting or translating, any or all of this material requires the prior written consent of Nokia. This material also contains confidential information, which may not be disclosed to others without the prior written consent of Nokia.

Nokia is a registered trademark of Nokia Corporation. S60 and logo is a trademark of Nokia Corporation. Java and all Java-based marks are trademarks or registered trademarks of Sun Microsystems, Inc. Other company and product names mentioned herein may be trademarks or tradenames of their respective owners.


$title

S60 Open C
Compilers and IDEs Using Open C

Compilers and IDEs Using Open C

Table of Contents

How to promote char in comparison with RVCT

How to promote char in comparison with RVCT

The default char will be promoted to int on WINSCW and unsigned on the RVCT compiler. Due to this promotion, comparison c != EOF will not become true on hardware and it will loop infinite.

RVCT treats plain char type as unsigned by default. There is a command line option "--signed_chars" that forces RVCT to treat plain char type as a signed char. Using this option, the example will compile and run the way it is expected to. But this option must be applied with care, since using the switch universally may have other ramifications elsewhere in the source base.

The MMP file can be modified as:

OPTION armcc  --signed_chars

Example:

#include <stdio.h>
int main()
{
  FILE *fp;
  char c;
  fp=fopen("test.txt","w");
  fprintf(fp,"%s","ab");
  fclose(fp);
  fp=fopen("test.txt","r");
  c=getc(fp);
  while(c != EOF)
  {
     c = getc(fp);
  }
  printf("\nOut of loop");
  fclose(fp);
  getchar();
}

Give feedback of this section

©Nokia 2006

Back to top

This material, including documentation and any related computer programs, is protected by copyright controlled by Nokia. All rights are reserved. Copying, including reproducing, storing, adapting or translating, any or all of this material requires the prior written consent of Nokia. This material also contains confidential information, which may not be disclosed to others without the prior written consent of Nokia.

Nokia is a registered trademark of Nokia Corporation. S60 and logo is a trademark of Nokia Corporation. Java and all Java-based marks are trademarks or registered trademarks of Sun Microsystems, Inc. Other company and product names mentioned herein may be trademarks or tradenames of their respective owners.


Alphabetical Indexes

glib
gobject
libc
libcrypt
libcrypto
libdl
libintl
libm
libpthread
libssl
libz

© Nokia 2007

Back to top


Alphabetical Index for glib

Index - glib

A

ABS()

C

CLAMP()

E

enum GConvertError

enum GDateDMY

enum GDateMonth

enum GDateWeekday

enum GErrorType

enum GFileError

enum GFileTest

enum GIOChannelError

enum GIOCondition

enum GIOError

enum GIOFlags

enum GHookFlagMask

enum GIOStatus

enum GKeyFileError

enum GKeyFileFlags

enum GLogLevelFlags

enum GMarkupError

enum GMarkupParseFlags

enum GModuleFlags

enum GNormalizeMode

enum GOnceStatus

enum GOptionArg

enum GOptionError

enum GOptionFlags

enum GSeekType

enum GShellError

enum GSpawnError

enum GSpawnFlags

enum GThreadError

enum GThreadPriority

enum GTokenType

enum GTraverseFlags

enum GTraverseType

enum GUnicodeBreakType

enum GUnicodeType

F

FALSE

G

g_scanner_cur_position ()
g_stpcpy ()
g_access ()
G_ALLOC_AND_FREE
G_ALLOC_ONLY
g_alloca()
g_allocator_free ()
g_allocator_new ()
g_array_append_val()
g_array_append_vals ()
g_array_free ()
g_array_index()
g_array_insert_val()
g_array_insert_vals ()
g_array_new ()
g_array_prepend_val()
g_array_prepend_vals ()
g_array_remove_index ()
g_array_remove_index_fast ()
g_array_remove_range ()
g_array_set_size ()
g_array_sized_new ()
g_array_sort ()
g_array_sort_with_data ()
g_ascii_digit_value ()
g_ascii_dtostr ()
G_ASCII_DTOSTR_BUF_SIZE
g_ascii_formatd ()
g_ascii_isalnum ()
g_ascii_isalpha ()
g_ascii_iscntrl ()
g_ascii_isdigit ()
g_ascii_isgraph ()
g_ascii_islower ()
g_ascii_isprint ()
g_ascii_ispunct ()
g_ascii_isspace ()
g_ascii_isxdigit ()
g_ascii_strcasecmp ()
g_ascii_strdown ()
g_ascii_strncasecmp ()
g_ascii_strtod ()
g_ascii_strtoull ()
g_ascii_strup ()
g_ascii_tolower ()
g_ascii_toupper ()
g_ascii_xdigit_value ()
g_assert()
g_assert_not_reached()
g_async_queue_length ()
g_async_queue_length_unlocked ()
g_async_queue_lock ()
g_async_queue_new ()
g_async_queue_pop ()
g_async_queue_pop_unlocked ()
g_async_queue_push ()
g_async_queue_push_unlocked ()
g_async_queue_ref ()
g_async_queue_ref_unlocked ()
g_async_queue_timed_pop ()
g_async_queue_timed_pop_unlocked ()
g_async_queue_try_pop ()
g_async_queue_try_pop_unlocked ()
g_async_queue_unlock ()
g_async_queue_unref ()
g_async_queue_unref_and_unlock ()
g_atexit ()
g_atomic_int_add ()
g_atomic_int_compare_and_exchange
()
g_atomic_int_dec_and_test ()
g_atomic_int_exchange_and_add ()
g_atomic_int_get ()
g_atomic_pointer_compare_and
_exchange ()
g_atomic_pointer_get ()
g_basename ()
G_BEGIN_DECLS
G_BIG_ENDIAN
g_bit_nth_lsf ()
g_bit_nth_msf ()
g_bit_storage ()
g_blow_chunks ()
G_BREAKPOINT()
g_build_filename ()
g_build_filenamev ()
g_build_path ()
g_build_pathv ()
g_byte_array_append ()
g_byte_array_free ()
g_byte_array_new ()
g_byte_array_prepend ()
g_byte_array_remove_index ()
g_byte_array_remove_index_fast ()
g_byte_array_remove_range ()
g_byte_array_set_size ()
g_byte_array_sized_new ()
g_byte_array_sort ()
g_byte_array_sort_with_data ()
G_BYTE_ORDER
g_cache_destroy ()
g_cache_insert ()
g_cache_key_foreach ()
g_cache_new ()
g_cache_remove ()
g_cache_value_foreach ()
g_chdir ()
g_child_watch_add ()
g_child_watch_add_full ()
g_child_watch_source_new ()
g_chmod ()
g_chunk_free()
g_chunk_new()
g_chunk_new0()
g_clear_error ()
g_completion_add_items ()
g_completion_clear_items ()
g_completion_complete ()
g_completion_complete_utf8 ()
g_completion_free ()
g_completion_new ()
g_completion_remove_items ()
g_completion_set_compare ()
g_cond_broadcast ()
g_cond_free ()
g_cond_new ()
g_cond_signal ()
g_cond_timed_wait ()
g_cond_wait ()
G_CONST_RETURN
g_convert ()
G_CONVERT_ERROR
g_convert_with_fallback ()
g_convert_with_iconv ()
g_creat ()
g_critical()
G_CSET_a_2_z
G_CSET_A_2_Z
G_CSET_DIGITS
G_CSET_LATINC
G_CSET_LATINS
g_datalist_clear ()
G_DATALIST_FLAGS_MASK
g_datalist_foreach ()
g_datalist_get_data()
g_datalist_get_flags ()
g_datalist_id_get_data ()
g_datalist_id_remove_data()
g_datalist_id_remove_no_notify ()
g_datalist_id_set_data()
g_datalist_id_set_data_full ()
g_datalist_init ()
g_datalist_remove_data()
g_datalist_remove_no_notify()
g_datalist_set_data()
g_datalist_set_data_full()
g_datalist_set_flags ()
g_datalist_unset_flags ()
g_dataset_destroy ()
g_dataset_foreach ()
g_dataset_get_data()
g_dataset_id_get_data ()
g_dataset_id_remove_data()
g_dataset_id_remove_no_notify ()
g_dataset_id_set_data()
g_dataset_id_set_data_full ()
g_dataset_remove_data()
g_dataset_remove_no_notify()
g_dataset_set_data()
g_dataset_set_data_full()
g_date_add_days ()
g_date_add_months ()
g_date_add_years ()
G_DATE_BAD_DAY
G_DATE_BAD_JULIAN
G_DATE_BAD_YEAR
g_date_clamp ()
g_date_clear ()
g_date_compare ()
g_date_days_between ()
g_date_free ()
g_date_get_day ()
g_date_get_day_of_year ()
g_date_get_days_in_month ()
g_date_get_iso8601_week_of_year ()
g_date_get_julian ()
g_date_get_monday_week_of_year ()
g_date_get_monday_weeks_in_year ()
g_date_get_month ()
g_date_get_sunday_week_of_year ()
g_date_get_sunday_weeks_in_year ()
g_date_get_weekday ()
g_date_get_year ()
g_date_is_first_of_month ()
g_date_is_last_of_month ()
g_date_is_leap_year ()
g_date_new ()
g_date_new_dmy ()
g_date_new_julian ()
g_date_order ()
g_date_set_day ()
g_date_set_dmy ()
g_date_set_julian ()
g_date_set_month ()
g_date_set_parse ()
g_date_set_year ()
g_date_strftime ()
g_date_subtract_days ()
g_date_subtract_months ()
g_date_subtract_years ()
g_date_to_struct_tm ()
g_date_valid ()
g_date_valid_day ()
g_date_valid_dmy ()
g_date_valid_julian ()
g_date_valid_month ()
g_date_valid_weekday ()
g_date_valid_year ()
g_debug()
g_dir_close ()
g_dir_open ()
g_dir_read_name ()
g_dir_rewind ()
G_DIR_SEPARATOR
G_DIR_SEPARATOR_S
g_direct_equal ()
g_direct_hash ()
g_dirname
G_E
G_END_DECLS
g_error()
g_error_copy ()
g_error_free ()
g_error_matches ()
g_error_new ()
g_error_new_literal ()
G_FILE_ERROR
g_file_error_from_errno ()
g_file_get_contents ()
g_file_open_tmp ()
g_file_read_link ()
g_file_set_contents ()
g_file_test ()
g_filename_display_basename ()
g_filename_display_name ()
g_filename_from_uri ()
g_filename_from_utf8 ()
g_filename_to_uri ()
g_filename_to_utf8 ()
g_find_program_in_path ()
g_fopen ()
g_fprintf ()
g_free ()
g_freopen ()
g_get_application_name ()
g_get_charset ()
g_get_current_dir ()
g_get_current_time ()
g_get_filename_charsets ()
g_get_home_dir ()
g_get_host_name ()
g_get_language_names ()
g_get_system_config_dirs ()
g_get_system_data_dirs ()
g_get_tmp_dir ()
g_get_user_cache_dir ()
g_get_user_config_dir ()
g_get_user_data_dir ()
g_get_user_name ()
g_getenv ()
G_GINT16_FORMAT
G_GINT16_MODIFIER
G_GINT32_FORMAT
G_GINT32_MODIFIER
G_GINT64_CONSTANT()
G_GINT64_FORMAT
G_GINT64_MODIFIER
G_GNUC_CONST
G_GNUC_DEPRECATED
G_GNUC_EXTENSION
G_GNUC_FORMAT()
G_GNUC_FUNCTION
G_GNUC_INTERNAL
G_GNUC_MALLOC
G_GNUC_NO_INSTRUMENT
G_GNUC_NULL_TERMINATED
G_GNUC_PRETTY_FUNCTION
G_GNUC_PRINTF()
G_GNUC_PURE
G_GNUC_SCANF()
G_GNUC_UNUSED
G_GSIZE_MODIFIER
G_GSSIZE_FORMAT
G_GUINT16_FORMAT
G_GUINT32_FORMAT
G_GUINT64_FORMAT
g_ascii_isupper ()

g_hash_table_destroy ()
g_hash_table_find ()
g_hash_table_foreach ()
g_hash_table_foreach_remove ()
g_hash_table_foreach_steal ()
g_hash_table_freeze()
g_hash_table_insert ()
g_hash_table_lookup ()
g_hash_table_lookup_extended ()
g_hash_table_new ()
g_hash_table_new_full ()
g_hash_table_remove ()
g_hash_table_replace ()
g_hash_table_size ()
g_hash_table_steal ()
g_hash_table_thaw()
G_HAVE_GINT64
G_HAVE_GNUC_VISIBILITY
G_HOOK()
G_HOOK_ACTIVE()
g_hook_alloc ()
g_hook_append()
g_hook_compare_ids ()
g_hook_destroy ()
g_hook_destroy_link ()
g_hook_find ()
g_hook_find_data ()
g_hook_find_func ()
g_hook_find_func_data ()
g_hook_first_valid ()
G_HOOK_FLAG_USER_SHIFT
G_HOOK_FLAGS()
g_hook_free ()
g_hook_get ()
G_HOOK_IN_CALL()
g_atomic_int_inc ()

g_date_set_time ()

g_get_prgname ()

g_get_real_name ()

g_hook_insert_before ()

g_hook_insert_sorted ()

G_HOOK_IS_UNLINKED()

G_HOOK_IS_VALID()

g_hook_list_clear ()

g_hook_list_init ()g_hook_list_init ()

g_hook_list_invoke ()

g_hook_list_invoke_check ()

g_hook_list_marshal ()

g_hook_list_marshal_check ()

g_hook_next_valid () g_hook_prepend ()

g_hook_ref ()

g_hook_unref ()

g_htonl()

g_htons()

g_iconv ()

g_iconv_close ()

g_iconv_open ()

g_idle_add ()

g_idle_add_full ()

g_idle_remove_by_data ()

g_idle_source_new ()

G_IEEE754_DOUBLE_BIAS

G_IEEE754_FLOAT_BIAS

g_int_equal ()

g_int_hash ()

g_io_add_watch () g_io_add_watch_full ()

g_io_channel_close ()

G_IO_CHANNEL_ERROR

g_io_channel_error_from_errno ()

g_io_channel_flush ()

g_io_channel_get_buffer_condition ()

g_io_channel_get_buffer_size ()

g_io_channel_get_buffered ()

g_io_channel_get_close_on_unref ()

g_io_channel_get_encoding ()

g_io_channel_get_flags ()

g_io_channel_get_line_term ()

g_io_channel_init ()

g_io_channel_new_file ()

g_io_channel_read ()

g_io_channel_read_chars ()

g_io_channel_read_line ()

g_io_channel_read_line_string ()

g_io_channel_read_to_end ()

g_io_channel_read_unichar ()

g_io_channel_ref ()

g_io_channel_seek ()

g_io_channel_seek_position ()

g_io_channel_set_buffer_size ()

g_io_channel_set_buffered ()

g_io_channel_set_close_on_unref ()

g_io_channel_set_encoding ()

g_io_channel_set_flags ()

g_io_channel_set_line_term ()

g_io_channel_shutdown ()

g_io_channel_unix_get_fd ()

g_io_channel_unix_new ()

g_io_channel_unref ()

g_io_channel_write ()

g_io_channel_write_chars ()

g_io_channel_write_unichar ()

g_io_create_watch ()

G_IS_DIR_SEPARATOR()

G_KEY_FILE_ERROR

g_key_file_free ()

g_key_file_get_boolean ()

g_key_file_get_boolean_list ()

g_key_file_get_comment ()

g_key_file_get_groups ()

g_key_file_get_integer ()

g_key_file_get_integer_list ()

g_key_file_get_keys ()

g_key_file_get_locale_string ()

g_key_file_get_locale_string_list ()

g_key_file_get_start_group ()

g_key_file_get_string ()

g_key_file_get_string_list ()

g_key_file_get_value ()

g_key_file_has_group ()

g_key_file_has_key ()

g_key_file_load_from_data ()

g_key_file_load_from_data_dirs ()

g_key_file_load_from_file ()

g_key_file_new ()

g_key_file_remove_comment ()

g_key_file_remove_group ()

g_key_file_remove_key ()

g_key_file_set_boolean ()

g_key_file_set_boolean_list ()

g_key_file_set_comment ()

g_key_file_set_integer ()

g_key_file_set_integer_list ()

g_key_file_set_list_separator ()

g_key_file_set_locale_string ()

g_key_file_set_locale_string_list ()

g_key_file_set_string ()

g_key_file_set_string_list ()

g_key_file_set_value ()

g_key_file_to_data ()

G_LIKELY()

g_list_alloc ()

g_list_append ()

g_list_concat ()

g_list_copy ()

g_list_delete_link ()

g_list_find ()

g_list_find_custom ()

g_list_first ()

g_list_foreach ()

g_list_free ()

g_list_free_1 ()

g_list_index ()

g_list_insert ()

g_list_insert_before ()

g_list_insert_sorted ()

g_list_last ()

g_list_length ()

g_list_next()

g_list_nth ()

g_list_nth_data ()

g_list_nth_prev ()

g_list_pop_allocator ()

g_list_position ()

g_list_prepend ()

g_list_previous()

g_list_push_allocator ()

g_list_remove ()

g_list_remove_all ()

g_list_remove_link ()

g_list_reverse ()

g_list_sort ()

g_list_sort_with_data ()

g_listenv ()

G_LITTLE_ENDIAN

G_LN10

G_LN2

g_locale_from_utf8 ()

g_locale_to_utf8 ()

G_LOCK()

G_LOCK_DEFINE()

G_LOCK_DEFINE_STATIC()

G_LOCK_EXTERN()

g_log ()

G_LOG_2_BASE_10

g_log_default_handler ()

G_LOG_DOMAIN

G_LOG_FATAL_MASK

G_LOG_LEVEL_USER_SHIFT

g_log_remove_handler ()

g_log_set_always_fatal ()

g_log_set_default_handler ()

g_log_set_fatal_mask ()

g_log_set_handler ()

g_logv ()

g_lstat ()

g_main_context_acquire ()

g_main_context_add_poll ()

g_main_context_check ()

g_main_context_default ()

g_main_context_dispatch ()

g_main_context_find_source_by_funcs

_user_data ()

g_main_context_find_source_by_id ()

g_main_context_find_source_by_user_data()

g_main_context_get_poll_func ()

g_main_context_iteration ()

g_main_context_new ()

g_main_context_pending ()

g_main_context_prepare ()

g_main_context_query ()

g_main_context_ref ()

g_main_context_release ()

g_main_context_remove_poll ()

g_main_context_set_poll_func ()

g_main_context_unref ()

g_main_context_wait ()

g_main_context_wakeup ()

g_main_depth ()

g_main_destroy()

g_main_is_running()

g_main_iteration()

g_main_loop_get_context ()

g_main_loop_is_running ()

g_main_loop_new ()

g_main_loop_quit ()

g_main_loop_ref ()

g_main_loop_run ()

g_main_loop_unref ()

g_main_new()

g_main_pending()

g_main_quit()

g_main_run()

g_main_set_poll_func()

g_malloc ()

g_malloc0 ()

g_mapped_file_free ()

g_mapped_file_get_contents ()

g_mapped_file_get_length ()

g_mapped_file_new ()

G_MARKUP_ERROR

g_markup_escape_text ()

g_markup_parse_context_end_parse ()

g_markup_parse_context_free ()

g_markup_parse_context_get_element ()

g_markup_parse_context_get_position ()

g_markup_parse_context_new ()

g_markup_parse_context_parse ()

g_markup_printf_escaped ()

g_markup_vprintf_escaped ()

G_MAXDOUBLE

G_MAXFLOAT

G_MAXINT

G_MAXINT16

G_MAXINT32

G_MAXINT64

G_MAXINT8

G_MAXLONG

G_MAXSHORT

G_MAXSIZE

G_MAXUINT

G_MAXUINT16

G_MAXUINT32

G_MAXUINT64

G_MAXUINT8

G_MAXULONG

G_MAXUSHORT

G_MEM_ALIGN

g_mem_chunk_alloc ()

g_mem_chunk_alloc0 ()

g_mem_chunk_clean ()

g_mem_chunk_create()

g_mem_chunk_destroy ()

g_mem_chunk_free ()

g_mem_chunk_info ()

g_mem_chunk_new ()

g_mem_chunk_print ()

g_mem_chunk_reset ()

g_mem_is_system_malloc ()

g_mem_profile ()

g_mem_set_vtable ()

g_memdup ()

g_memmove()

g_message()

G_MINDOUBLE

G_MINFLOAT

G_MININT

G_MININT16

G_MININT32

G_MININT64

G_MININT8

G_MINLONG

G_MINSHORT

g_mkdir ()

g_mkdir_with_parents ()

g_mkstemp ()

g_module_build_path ()

g_module_close ()

g_module_error ()

G_MODULE_EXPORT

G_MODULE_IMPORT

g_module_make_resident ()

g_module_name ()

g_module_open ()

G_MODULE_SUFFIX

g_module_supported ()

g_module_symbol ()

g_mutex_free ()

g_mutex_lock ()

g_mutex_new ()

g_mutex_trylock ()

g_mutex_unlock ()

G_N_ELEMENTS()

g_new()

g_new0()

g_newa()

g_node_append()

g_node_append_data()

g_node_child_index ()

g_node_child_position ()

g_node_children_foreach ()

g_node_copy ()

g_node_copy_deep ()

g_node_depth ()

g_node_destroy ()

g_node_find ()

g_node_find_child ()

g_node_first_child()

g_node_first_sibling ()

g_node_get_root ()

g_node_insert ()

g_node_insert_after ()

g_node_insert_before ()

g_node_insert_data()

g_node_insert_data_before()

g_node_is_ancestor ()

G_NODE_IS_LEAF()

G_NODE_IS_ROOT()

g_node_last_child ()

g_node_last_sibling ()

g_node_max_height ()

g_node_n_children ()

g_node_n_nodes ()

g_node_new ()

g_node_next_sibling()

g_node_nth_child ()

g_node_pop_allocator ()

g_node_prepend ()

g_node_prepend_data()

g_node_prev_sibling()

g_node_push_allocator ()

g_node_reverse_children ()

g_node_traverse ()

g_node_unlink ()

g_ntohl()

g_ntohs()

g_nullify_pointer ()

g_on_error_query ()

g_on_error_stack_trace ()

g_once()

G_ONCE_INIT

g_open ()

g_option_context_add_group ()

g_option_context_add_main_entries ()

g_option_context_free ()

g_option_context_get_help_enabled ()

g_option_context_get_ignore_unknown_options ()

g_option_context_get_main_group ()

g_option_context_new ()

g_option_context_parse ()

g_option_context_set_help_enabled ()

g_option_context_set_ignore_unknown_options ()

g_option_context_set_main_group ()

G_OPTION_ERROR

g_option_group_add_entries ()

g_option_group_free ()

g_option_group_new ()

g_option_group_set_error_hook ()

g_option_group_set_parse_hooks ()

g_option_group_set_translate_func ()

g_option_group_set_translation_domain ()

G_OPTION_REMAINING

G_OS_BEOS

G_OS_UNIX

G_OS_WIN32

g_parse_debug_string ()

g_path_get_basename ()

g_path_get_dirname ()

g_path_is_absolute ()

g_path_skip_root ()

g_pattern_match ()

g_pattern_match_simple ()

g_pattern_match_string ()

g_pattern_spec_equal ()

g_pattern_spec_free ()

g_pattern_spec_new ()

G_PDP_ENDIAN

G_PI

G_PI_2

G_PI_4

g_print ()

g_printerr ()

g_printf ()

g_printf_string_upper_bound ()

G_PRIORITY_DEFAULT|

G_PRIORITY_DEFAULT_IDLE

G_PRIORITY_HIGH

G_PRIORITY_HIGH_IDLE

G_PRIORITY_LOW

g_private_get ()

g_private_new ()

g_private_set ()

g_propagate_error ()

g_ptr_array_add ()

g_ptr_array_foreach ()

g_ptr_array_free ()

g_ptr_array_index()

g_ptr_array_new ()

g_ptr_array_remove ()

g_ptr_array_remove_fast ()

g_ptr_array_remove_index ()

g_ptr_array_remove_index_fast ()

g_ptr_array_remove_range ()

g_ptr_array_set_size ()

g_ptr_array_sized_new ()

g_ptr_array_sort ()

g_ptr_array_sort_with_data ()

g_qsort_with_data ()

g_quark_from_static_string ()

g_quark_from_string ()

g_quark_to_string ()

g_quark_try_string ()

g_queue_copy ()

g_queue_delete_link ()

g_queue_find ()

g_queue_find_custom ()

g_queue_foreach ()

g_queue_free ()

g_queue_get_length ()

g_queue_index ()

g_queue_insert_after ()

g_queue_insert_before ()

g_queue_insert_sorted ()

g_queue_is_empty ()

g_queue_link_index ()

g_queue_new ()

g_queue_peek_head ()

g_queue_peek_head_link ()

g_queue_peek_nth ()

g_queue_peek_nth_link ()

g_queue_peek_tail ()

g_queue_peek_tail_link ()

g_queue_pop_head ()

g_queue_pop_head_link ()

g_queue_pop_nth ()

g_queue_pop_nth_link ()

g_queue_pop_tail ()

g_queue_pop_tail_link ()

g_queue_push_head ()

g_queue_push_head_link ()

g_queue_push_nth ()

g_queue_push_nth_link ()

g_queue_push_tail ()

g_queue_push_tail_link ()

g_queue_remove ()

g_queue_remove_all ()

g_queue_reverse ()

g_queue_sort ()

g_queue_unlink ()

g_rand_boolean()

g_rand_copy ()

g_rand_double ()

g_rand_double_range ()

g_rand_free ()

g_rand_int ()

g_rand_int_range ()

g_rand_new ()

g_rand_new_with_seed ()

g_rand_new_with_seed_array ()

g_rand_set_seed ()

g_rand_set_seed_array ()

g_random_boolean()

g_random_double ()

g_random_double_range ()

g_random_int ()

g_random_int_range ()

g_random_set_seed ()

g_realloc ()

g_relation_count ()

g_relation_delete ()

g_relation_destroy ()

g_relation_exists ()

g_relation_index ()

g_relation_insert ()

g_relation_new ()

g_relation_print ()

g_relation_select ()

g_remove ()

g_rename ()

g_renew()

g_return_if_fail()

g_return_if_reached()

g_return_val_if_fail()

g_return_val_if_reached()

g_rmdir ()

g_scanner_add_symbol()

g_scanner_cur_line ()

g_scanner_cur_token ()

g_scanner_cur_value ()

g_scanner_destroy ()

g_scanner_eof ()

g_scanner_error ()

g_scanner_foreach_symbol()

g_scanner_freeze_symbol_table()

g_scanner_get_next_token ()

g_scanner_input_file ()

g_scanner_input_text ()

g_scanner_lookup_symbol ()

g_scanner_new ()

g_scanner_peek_next_token ()

g_scanner_remove_symbol()

g_scanner_scope_add_symbol ()

g_scanner_scope_foreach_symbol ()

g_scanner_scope_lookup_symbol ()

g_scanner_scope_remove_symbol ()

g_scanner_set_scope ()

g_scanner_sync_file_offset ()

g_scanner_thaw_symbol_table()

g_scanner_unexp_token ()

g_scanner_warn ()

G_SEARCHPATH_SEPARATOR

G_SEARCHPATH_SEPARATOR_S

g_set_application_name ()

g_set_error ()

g_set_prgname ()

g_set_print_handler ()

g_set_printerr_handler ()

g_setenv ()

G_SHELL_ERROR

g_shell_parse_argv ()

g_shell_quote ()

g_shell_unquote ()

g_slist_alloc ()

g_slist_append ()

g_slist_concat ()

g_slist_copy ()

g_slist_delete_link ()

g_slist_find ()

g_slist_find_custom ()

g_slist_foreach ()

g_slist_free ()

g_slist_free_1 ()

g_slist_index ()

g_slist_insert ()

g_slist_insert_before ()

g_slist_insert_sorted ()

g_slist_last ()

g_slist_length ()

g_slist_next()

g_slist_nth ()

g_slist_nth_data ()

g_slist_pop_allocator ()

g_slist_position ()

g_slist_prepend ()

g_slist_push_allocator ()

g_slist_remove ()

g_slist_remove_all ()

g_slist_remove_link ()

g_slist_reverse ()

g_slist_sort ()

g_slist_sort_with_data ()

g_snprintf ()

g_source_add_poll ()

g_source_attach ()

g_source_destroy ()

g_source_get_can_recurse ()

g_source_get_context ()

g_source_get_current_time ()

g_source_get_id ()

g_source_get_priority ()

g_source_new ()

g_source_ref ()

g_source_remove ()

g_source_remove_by_funcs_user_data ()

g_source_remove_by_user_data ()

g_source_remove_poll ()

g_source_set_callback ()

g_source_set_callback_indirect ()

g_source_set_can_recurse ()

g_source_set_priority ()

g_source_unref ()

g_spaced_primes_closest ()

g_spawn_async ()

g_spawn_async_with_pipes ()

g_spawn_close_pid ()

g_spawn_command_line_async ()

g_spawn_command_line_sync ()

G_SPAWN_ERROR

g_spawn_sync ()

g_sprintf ()

G_SQRT2

g_stat ()

g_static_mutex_free ()

g_static_mutex_get_mutex ()

G_STATIC_MUTEX_INIT

g_static_mutex_init ()

g_static_mutex_lock ()

g_static_mutex_trylock ()

g_static_mutex_unlock ()

g_static_private_free ()

g_static_private_get ()

G_STATIC_PRIVATE_INIT

g_static_private_init ()

g_static_private_set ()

g_static_rec_mutex_free ()

G_STATIC_REC_MUTEX_INIT

g_static_rec_mutex_init ()

g_static_rec_mutex_lock ()

g_static_rec_mutex_lock_full ()

g_static_rec_mutex_trylock ()

g_static_rec_mutex_unlock ()

g_static_rec_mutex_unlock_full ()

g_static_rw_lock_free ()

G_STATIC_RW_LOCK_INIT

g_static_rw_lock_init ()

g_static_rw_lock_reader_lock ()

g_static_rw_lock_reader_trylock ()

g_static_rw_lock_reader_unlock ()

g_static_rw_lock_writer_lock ()

g_static_rw_lock_writer_trylock ()

g_static_rw_lock_writer_unlock ()

G_STMT_END

G_STMT_START

G_STR_DELIMITERS

g_str_equal ()

g_str_has_prefix ()

g_str_has_suffix ()

g_str_hash ()

g_strcanon ()

g_strcasecmp ()

g_strchomp ()

g_strchug ()

g_strcompress ()

g_strconcat ()

g_strdelimit ()

g_strdown ()

g_strdup ()

g_strdup_printf ()

g_strdup_vprintf ()

g_strdupv ()

g_strerror ()

g_strescape ()

g_strfreev ()

G_STRFUNC

g_string_append ()

g_string_append_c ()

g_string_append_len ()

g_string_append_printf ()

g_string_append_unichar ()

g_string_ascii_down ()

g_string_ascii_up ()

g_string_assign ()

g_string_chunk_free ()

g_string_chunk_insert ()

g_string_chunk_insert_const ()

g_string_chunk_insert_len ()

g_string_chunk_new ()

g_string_down ()

g_string_equal ()

g_string_erase ()

g_string_free ()

g_string_hash ()

g_string_insert ()

g_string_insert_c ()

g_string_insert_len ()

g_string_insert_unichar ()

g_string_new ()

g_string_new_len ()

g_string_prepend ()

g_string_prepend_c ()

g_string_prepend_len ()

g_string_prepend_unichar ()

g_string_printf ()

g_string_set_size ()

g_string_sized_new ()

g_string_sprintf

g_string_sprintfa

g_string_truncate ()

g_string_up ()

G_STRINGIFY()

g_strip_context ()

g_strjoin ()

g_strjoinv ()
g_strlcat ()

g_strlcpy ()

G_STRLOC

g_strncasecmp ()

g_strndup ()

g_strnfill ()

g_strreverse ()

g_strrstr ()

g_strrstr_len ()

g_strsignal ()

g_strsplit ()

g_strsplit_set ()

g_strstr_len ()

g_strstrip()

g_strtod ()

G_STRUCT_MEMBER()

G_STRUCT_MEMBER_P()

G_STRUCT_OFFSET()

g_strup ()

g_strv_length ()

g_thread_create ()

g_thread_create_full ()

G_THREAD_ERROR

g_thread_exit ()

g_thread_init ()

g_thread_join ()

g_thread_pool_free ()

g_thread_pool_get_max_threads ()

g_thread_pool_get_max_unused_threads ()

g_thread_pool_get_num_threads ()

g_thread_pool_get_num_unused_threads ()

g_thread_pool_new ()

g_thread_pool_push ()

g_thread_pool_set_max_threads ()

g_thread_pool_set_max_unused_threads ()

g_thread_pool_stop_unused_threads ()

g_thread_pool_unprocessed ()

g_thread_self ()

g_thread_set_priority ()

g_thread_supported ()

g_thread_yield ()

G_THREADS_ENABLED

G_THREADS_IMPL_NONE

G_THREADS_IMPL_POSIX

G_THREADS_IMPL_SOLARIS

g_time_val_add ()

g_timeout_add ()

g_timeout_add_full ()

g_timeout_source_new ()

g_timer_continue ()

g_timer_destroy ()

g_timer_elapsed ()

g_timer_new ()

g_timer_reset ()

g_timer_start ()

g_timer_stop ()

g_trash_stack_height ()

g_trash_stack_peek ()

g_trash_stack_pop ()

g_trash_stack_push ()

g_tree_destroy ()

g_tree_foreach ()

g_tree_height ()

g_tree_insert ()

g_tree_lookup ()

g_tree_lookup_extended ()

g_tree_new ()

g_tree_new_full ()

g_tree_new_with_data ()

g_tree_nnodes ()

g_tree_remove ()

g_tree_replace ()

g_tree_search ()

g_tree_steal ()

g_tree_traverse ()

g_try_malloc ()

g_try_malloc0 ()

g_try_new()

g_try_new0()

g_try_realloc ()

g_try_renew()

G_TRYLOCK()

g_tuples_destroy ()

g_tuples_index ()

g_ucs4_to_utf16 ()

g_ucs4_to_utf8 ()

g_unichar_break_type ()

g_unichar_digit_value ()

g_unichar_get_mirror_char ()

g_unichar_isalnum ()

g_unichar_isalpha ()

g_unichar_iscntrl ()

g_unichar_isdefined ()

g_unichar_isdigit ()

g_unichar_isgraph ()

g_unichar_islower ()

g_unichar_isprint ()

g_unichar_ispunct ()

g_unichar_isspace ()

g_unichar_istitle ()

g_unichar_isupper ()

g_unichar_iswide ()

g_unichar_isxdigit ()

g_unichar_to_utf8 ()

g_unichar_tolower ()

g_unichar_totitle ()

g_unichar_toupper ()

g_unichar_type ()

g_unichar_validate ()

g_unichar_xdigit_value ()

g_unicode_canonical_decomposition ()

g_unicode_canonical_ordering ()

G_UNLIKELY()

g_unlink ()

G_UNLOCK()

g_unsetenv ()

g_uri_list_extract_uris ()

G_USEC_PER_SEC

g_usleep ()

g_utf16_to_ucs4 ()

g_utf16_to_utf8 ()

g_utf8_casefold ()

g_utf8_collate ()

g_utf8_collate_key ()

g_utf8_collate_key_for_filename ()

g_utf8_find_next_char ()

g_utf8_find_prev_char ()

g_utf8_get_char ()

g_utf8_get_char_validated ()

g_utf8_next_char()

g_utf8_normalize ()

g_utf8_offset_to_pointer ()

g_utf8_pointer_to_offset ()

g_utf8_prev_char ()

g_utf8_strchr ()

g_utf8_strdown ()

g_utf8_strlen ()

g_utf8_strncpy ()

g_utf8_strrchr ()

g_utf8_strreverse ()

g_utf8_strup ()

g_utf8_to_ucs4 ()

g_utf8_to_ucs4_fast ()

g_utf8_to_utf16 ()

g_utf8_validate ()

G_VA_COPY()

g_vasprintf ()

g_vfprintf ()

g_vprintf ()

g_vsnprintf ()

g_vsprintf ()

g_warning()

G_WIN32_DLLMAIN_FOR_DLL_NAME()

g_win32_error_message ()

g_win32_get_package_installation_directory ()

g_win32_get_package_installation_subdirectory ()

g_win32_get_windows_version ()

g_win32_getlocale ()

G_WIN32_HAVE_WIDECHAR_API()

G_WIN32_IS_NT_BASED()

g_win32_locale_filename_from_utf8 ()

GAllocator

GArray

GAsyncQueue

gboolean

GByteArray

GCache

GCacheDestroyFunc ()

GCacheDupFunc ()

GCacheNewFunc ()

gchar

GChildWatchFunc ()

GCompareDataFunc ()

GCompareFunc ()

GCompletion

GCompletionFunc ()

GCompletionStrncmpFunc ()

GCond

gconstpointer

GCopyFunc ()

GData

GDataForeachFunc ()

GDate

GDateDay

GDateYear

GDebugKey

GDestroyNotify ()

GDir

gdouble

GEqualFunc ()

GError

gfloat

GFreeFunc ()

GFunc ()

GHashFunc ()

GHashTable

GHFunc ()

GHook

GHookCheckFunc ()

GHookCheckMarshaller ()

GHookCompareFunc ()

GHookFinalizeFunc ()

GHookFindFunc ()

GHookFunc ()

GHookList

GHookMarshaller ()

GHRFunc ()

GIConv

gint

GINT_FROM_BE()

GINT_FROM_LE()

GINT_TO_BE()

GINT_TO_LE()

GINT_TO_POINTER()

gint16

GINT16_FROM_BE()

GINT16_FROM_LE()

GINT16_TO_BE()

GINT16_TO_LE()

gint32

GINT32_FROM_BE()

GINT32_FROM_LE()

GINT32_TO_BE()

GINT32_TO_LE()

gint64

GINT64_FROM_BE()

GINT64_FROM_LE()

GINT64_TO_BE()

GINT64_TO_LE()

gint8

GIOChannel

GIOFunc ()

GIOFuncs

GKeyFile

glib_binary_age

glib_check_version ()

GLIB_CHECK_VERSION()

glib_interface_age

glib_major_version

GLIB_MAJOR_VERSION

glib_mem_profiler_table

glib_micro_version

GLIB_MICRO_VERSION

glib_minor_version

GLIB_MINOR_VERSION

GList

GLogFunc ()

glong

GLONG_FROM_BE()

GLONG_FROM_LE()

GLONG_TO_BE()

GLONG_TO_LE()

GMainContext

GMainLoop

GMappedFile

GMarkupParseContext

GMarkupParser

GMemChunk

GMemVTable

GModule

GModuleCheckInit ()

GModuleUnload ()

GMutex

GNode

GNodeForeachFunc ()

GOptionContext

GOptionEntry

GOptionParseFunc ()

GPatternSpec

GPid

gpointer

GPOINTER_TO_INT()

GPOINTER_TO_SIZE()

 GPOINTER_TO_UINT()

GPollFD

GPollFunc ()

GPrintFunc ()

GPrivate

GPtrArray

GQuark

GQueue

GRand

GRelation

GScanner

GScannerConfig

GScannerMsgFunc ()

gshort

 gsize

GSIZE_FORMAT

GSIZE_TO_POINTER()

GSList

GSource

GSourceCallbackFuncs

GSourceDummyMarshal ()

GSourceFunc ()

GSourceFuncs

GSpawnChildSetupFunc ()

gssize

GStaticMutex

GStaticPrivate

GStaticRecMutex

GStaticRWLock

GString

GStringChunk

GThread

GThreadFunc ()

 GThreadFunctions

 GThreadPool

GTime

GTimer

GTimeVal

GTranslateFunc ()

GTrashStack

GTraverseFunc ()

GTree

GTuples

 guchar

guint

GUINT_FROM_BE()

GUINT_FROM_LE()

GUINT_TO_BE()

GUINT_TO_LE()

 GUINT_TO_POINTER()

guint16

GUINT16_FROM_BE()

GUINT16_FROM_LE()

GUINT16_SWAP_BE_PDP()

GUINT16_SWAP_LE_BE()

GUINT16_SWAP_LE_PDP()

GUINT16_TO_BE()

 GUINT16_TO_LE()

guint32

GUINT32_FROM_BE()

GUINT32_FROM_LE()

GUINT32_SWAP_BE_PDP()

GUINT32_SWAP_LE_BE()

GUINT32_SWAP_LE_PDP()

GUINT32_TO_BE()

GUINT32_TO_LE()

guint64

GUINT64_FROM_BE()

GUINT64_FROM_LE()

GUINT64_SWAP_LE_BE()

GUINT64_TO_BE()

GUINT64_TO_LE()

guint8

gulong

GULONG_FROM_BE()

GULONG_FROM_LE()

GULONG_TO_BE()

GULONG_TO_LE()

gunichar

gunichar2

 gushort

 GVoidFunc ()

M

MAX()

MAXPATHLEN

MIN()

N

NULL

N_()

P

pipe()

Q

Q_()

T

TRUE

U

union GDoubleIEEE754

union GFloatIEEE754

union GTokenValue

See Also

Libraries Supported in Open Environment

© 2005-2006 Nokia

Top


Alphabetical Index for gobject

Index - gobject

E

enum GConnectFlags
enum GParamFlags
enum GSignalFlags
enum GSignalMatchType
enum GTypeDebugFlags
enum GTypeFlags
enum GTypeFundamentalFlags

G

g_type_default_interface_unref ()
g_boxed_copy ()
g_boxed_free ()
g_boxed_type_register_static ()
G_CALLBACK()
g_cclosure_marshal_BOOL__FLAGS
g_cclosure_marshal_BOOLEAN__FLAGS ()
g_cclosure_marshal_STRING__OBJECT_
POINTER ()
g_cclosure_marshal_VOID__BOOLEAN ()
g_cclosure_marshal_VOID__BOXED ()
g_cclosure_marshal_VOID__CHAR ()
g_cclosure_marshal_VOID__DOUBLE ()
g_cclosure_marshal_VOID__ENUM ()
g_cclosure_marshal_VOID__FLAGS ()
g_cclosure_marshal_VOID__FLOAT ()
g_cclosure_marshal_VOID__INT ()
g_cclosure_marshal_VOID__LONG ()
g_cclosure_marshal_VOID__OBJECT ()
g_cclosure_marshal_VOID__PARAM ()
g_cclosure_marshal_VOID__POINTER ()
g_cclosure_marshal_VOID__STRING ()
g_cclosure_marshal_VOID__UCHAR ()
g_cclosure_marshal_VOID__UINT ()
g_cclosure_marshal_VOID__UINT_POINTER ()
g_cclosure_marshal_VOID__ULONG ()
g_cclosure_marshal_VOID__VOID ()
g_cclosure_new ()
g_cclosure_new_object ()
g_cclosure_new_object_swap ()
g_cclosure_new_swap ()
G_CCLOSURE_SWAP_DATA()
g_closure_add_finalize_notifier ()
g_closure_add_invalidate_notifier ()
g_closure_add_marshal_guards ()
g_closure_invalidate ()
g_closure_invoke ()
G_CLOSURE_N_NOTIFIERS()
G_CLOSURE_NEEDS_MARSHAL()
g_closure_new_object ()
g_closure_new_simple ()
g_closure_ref ()
g_closure_remove_finalize_notifier ()
g_closure_remove_invalidate_notifier ()
g_closure_set_marshal ()
g_closure_set_meta_marshal ()
g_closure_sink ()
g_closure_unref ()
G_DEFINE_ABSTRACT_TYPE()
G_DEFINE_ABSTRACT_TYPE_WITH_CODE()
G_DEFINE_TYPE()
G_DEFINE_TYPE_EXTENDED()
G_DEFINE_TYPE_WITH_CODE()
G_ENUM_CLASS()
G_ENUM_CLASS_TYPE()
G_ENUM_CLASS_TYPE_NAME()
g_enum_complete_type_info ()
g_enum_get_value ()
g_enum_get_value_by_name ()
g_enum_get_value_by_nick ()
g_enum_register_static ()
G_FLAGS_CLASS()
G_FLAGS_CLASS_TYPE()
G_FLAGS_CLASS_TYPE_NAME()
g_flags_complete_type_info ()
g_flags_get_first_value ()
g_flags_get_value_by_name ()
g_flags_get_value_by_nick ()
g_flags_register_static ()
G_IMPLEMENT_INTERFACE()
G_IS_ENUM_CLASS()
G_IS_FLAGS_CLASS()
G_IS_OBJECT()
G_IS_OBJECT_CLASS()
G_IS_PARAM_SPEC()
G_IS_PARAM_SPEC_BOOLEAN()
G_IS_PARAM_SPEC_BOXED()
G_IS_PARAM_SPEC_CHAR()
G_IS_PARAM_SPEC_CLASS()
G_IS_PARAM_SPEC_DOUBLE()
G_IS_PARAM_SPEC_ENUM()
G_IS_PARAM_SPEC_FLAGS()
G_IS_PARAM_SPEC_FLOAT()
G_IS_PARAM_SPEC_INT()
G_IS_PARAM_SPEC_INT64()
G_IS_PARAM_SPEC_LONG()
G_IS_PARAM_SPEC_OBJECT()
G_IS_PARAM_SPEC_OVERRIDE()
G_IS_PARAM_SPEC_PARAM()
G_IS_PARAM_SPEC_POINTER()
G_IS_PARAM_SPEC_STRING()
G_IS_PARAM_SPEC_UCHAR()
G_IS_PARAM_SPEC_UINT()
G_IS_PARAM_SPEC_UINT64()
G_IS_PARAM_SPEC_ULONG()
G_IS_PARAM_SPEC_UNICHAR()
G_IS_PARAM_SPEC_VALUE_ARRAY()
G_IS_VALUE()
G_OBJECT()
g_object_add_toggle_ref ()
g_object_add_weak_pointer ()
G_OBJECT_CLASS()
g_object_class_find_property ()
g_object_class_install_property ()
g_object_class_list_properties ()
G_OBJECT_CLASS_NAME()
g_object_class_override_property ()
G_OBJECT_CLASS_TYPE()
g_object_connect ()
g_object_disconnect ()
g_object_freeze_notify ()
g_object_get ()
G_OBJECT_GET_CLASS()
g_object_get_data ()
g_object_get_property ()
g_object_get_qdata ()
g_object_get_valist ()
g_object_interface_find_property ()
g_object_interface_install_property ()
g_object_interface_list_properties ()
g_object_new ()
g_object_new_valist ()
g_object_newv ()
g_object_notify ()
g_object_ref ()
g_object_remove_toggle_ref ()
g_object_remove_weak_pointer ()
g_object_run_dispose ()
g_object_set ()
g_object_set_data ()
g_object_set_data_full ()
g_object_set_property ()
g_object_set_qdata ()
g_object_set_qdata_full ()
g_object_set_valist ()
g_object_steal_data ()
g_object_steal_qdata ()
g_object_thaw_notify ()
G_OBJECT_TYPE()
G_OBJECT_TYPE_NAME()

g_object_unref ()
G_OBJECT_WARN_INVALID_PROPERTY_ID()
g_object_watch_closure ()
g_object_weak_ref ()
g_object_weak_unref ()
G_PARAM_MASK
G_PARAM_READWRITE
G_PARAM_SPEC()
g_param_spec_boolean ()
G_PARAM_SPEC_BOOLEAN()
g_param_spec_boxed ()
G_PARAM_SPEC_BOXED()
g_param_spec_char ()
G_PARAM_SPEC_CHAR()
G_PARAM_SPEC_CLASS()
g_param_spec_double ()
G_PARAM_SPEC_DOUBLE()
g_param_spec_enum ()
G_PARAM_SPEC_ENUM()
g_param_spec_flags ()
G_PARAM_SPEC_FLAGS()
g_param_spec_float ()
G_PARAM_SPEC_FLOAT()
g_param_spec_get_blurb ()
G_PARAM_SPEC_GET_CLASS()
g_param_spec_get_name ()
g_param_spec_get_nick ()
g_param_spec_get_qdata ()
g_param_spec_get_redirect_target ()
g_param_spec_int ()
G_PARAM_SPEC_INT()
g_param_spec_int64 ()
G_PARAM_SPEC_INT64()
g_param_spec_internal ()
g_param_spec_long ()
G_PARAM_SPEC_LONG()
g_param_spec_object ()
G_PARAM_SPEC_OBJECT()
g_param_spec_override ()
G_PARAM_SPEC_OVERRIDE()
g_param_spec_param ()
G_PARAM_SPEC_PARAM()
g_param_spec_pointer ()
G_PARAM_SPEC_POINTER()
g_param_spec_pool_insert ()
g_param_spec_pool_list ()
g_param_spec_pool_list_owned ()
g_param_spec_pool_lookup ()
g_param_spec_pool_new ()
g_param_spec_pool_remove ()
g_param_spec_ref ()
g_param_spec_set_qdata ()
g_param_spec_set_qdata_full ()
g_param_spec_sink ()
g_param_spec_steal_qdata ()
g_param_spec_string ()
G_PARAM_SPEC_STRING()
G_PARAM_SPEC_TYPE()
G_PARAM_SPEC_TYPE_NAME()
g_param_spec_uchar ()
G_PARAM_SPEC_UCHAR()
g_param_spec_uint ()
G_PARAM_SPEC_UINT()
g_param_spec_uint64 ()
G_PARAM_SPEC_UINT64()
g_param_spec_ulong ()
G_PARAM_SPEC_ULONG()
g_param_spec_unichar ()
G_PARAM_SPEC_UNICHAR()
g_param_spec_unref ()
g_param_spec_value_array ()
G_PARAM_SPEC_VALUE_ARRAY()
G_PARAM_SPEC_VALUE_TYPE()
g_param_type_register_static ()
G_PARAM_USER_SHIFT
g_param_value_convert ()
g_param_value_defaults ()
g_param_value_set_default ()
g_param_value_validate ()
g_param_values_cmp ()
g_pointer_type_register_static ()
g_signal_accumulator_true_handled ()
g_signal_add_emission_hook ()
g_signal_chain_from_overridden ()
g_signal_connect()
g_signal_connect_after()
g_signal_connect_closure ()
g_signal_connect_closure_by_id ()
g_signal_connect_data ()
g_signal_connect_object ()
g_signal_connect_swapped()
g_signal_emit ()
g_signal_emit_by_name ()
g_signal_emit_valist ()
g_signal_emitv ()
G_SIGNAL_FLAGS_MASK
g_signal_get_invocation_hint ()
g_signal_handler_block ()
g_signal_handler_disconnect ()
g_signal_handler_find ()
g_signal_handler_is_connected ()
g_signal_handler_unblock ()
g_signal_handlers_block_by_func()
g_signal_handlers_block_matched ()
g_signal_handlers_disconnect_by_func()
g_signal_handlers_disconnect_matched ()
g_signal_handlers_unblock_by_func()
g_signal_handlers_unblock_matched ()
g_signal_has_handler_pending ()
g_signal_list_ids ()
g_signal_lookup ()
G_SIGNAL_MATCH_MASK
g_signal_name ()
g_signal_new ()
g_signal_new_valist ()
g_signal_newv ()
g_signal_override_class_closure ()
g_signal_parse_name ()
g_signal_query ()
g_signal_remove_emission_hook ()
g_signal_stop_emission ()
g_signal_stop_emission_by_name ()
g_signal_type_cclosure_new ()
G_SIGNAL_TYPE_STATIC_SCOPE
g_source_set_closure ()
g_strdup_value_contents ()
g_type_add_class_cache_func ()
g_type_add_interface_dynamic ()
g_type_add_interface_static ()
G_TYPE_BOOLEAN
G_TYPE_BOXED
G_TYPE_CHAR
G_TYPE_CHECK_CLASS_CAST()
G_TYPE_CHECK_CLASS_TYPE()
G_TYPE_CHECK_INSTANCE()
G_TYPE_CHECK_INSTANCE_CAST()
G_TYPE_CHECK_INSTANCE_TYPE()
G_TYPE_CHECK_VALUE()
G_TYPE_CHECK_VALUE_TYPE()
g_type_children ()
g_type_class_add_private ()
g_type_class_peek ()
g_type_class_peek_parent ()
g_type_class_peek_static ()
g_type_class_ref ()
g_type_class_unref ()
g_type_class_unref_uncached ()
G_TYPE_CLOSURE
g_type_create_instance ()
G_TYPE_DATE
g_type_default_interface_peek ()
g_type_default_interface_ref ()
g_type_add_interface_check ()
g_type_depth ()
G_TYPE_DOUBLE
G_TYPE_ENUM
G_TYPE_FLAG_RESERVED_ID_BIT
G_TYPE_FLAGS
G_TYPE_FLOAT
g_type_free_instance ()
G_TYPE_FROM_CLASS()
G_TYPE_FROM_INSTANCE()
G_TYPE_FROM_INTERFACE()
g_type_from_name ()
g_type_fundamental ()
G_TYPE_FUNDAMENTAL()
G_TYPE_FUNDAMENTAL_MAX
g_type_fundamental_next ()
g_type_get_plugin ()
g_type_get_qdata ()
G_TYPE_GSTRING
G_TYPE_HAS_VALUE_TABLE()
g_type_init ()
g_type_init_with_debug_flags ()
G_TYPE_INSTANCE_GET_CLASS()
G_TYPE_INSTANCE_GET_INTERFACE()
G_TYPE_INSTANCE_GET_PRIVATE()
G_TYPE_INT
G_TYPE_INT64
G_TYPE_INTERFACE
g_type_interface_add_prerequisite ()
g_type_interface_get_plugin ()
g_type_interface_peek ()
g_type_interface_peek_parent ()
g_type_interface_prerequisites ()
g_type_interfaces ()
G_TYPE_INVALID
G_TYPE_IO_CHANNEL
G_TYPE_IO_CONDITION
g_type_is_a ()
G_TYPE_IS_ABSTRACT()
G_TYPE_IS_CLASSED()
G_TYPE_IS_DEEP_DERIVABLE()
G_TYPE_IS_DERIVABLE()
G_TYPE_IS_DERIVED()
G_TYPE_IS_ENUM()
G_TYPE_IS_FLAGS()
G_TYPE_IS_FUNDAMENTAL()
G_TYPE_IS_INSTANTIATABLE()
G_TYPE_IS_INTERFACE()
G_TYPE_IS_OBJECT()
G_TYPE_IS_PARAM()
G_TYPE_IS_VALUE()
G_TYPE_IS_VALUE_ABSTRACT()
G_TYPE_IS_VALUE_TYPE()
G_TYPE_LONG
G_TYPE_MAKE_FUNDAMENTAL()
g_type_module_add_interface ()
g_type_module_register_enum ()
g_type_module_register_flags ()
g_type_module_register_type ()
g_type_module_set_name ()
g_type_module_unuse ()
g_type_module_use ()
g_type_name ()
g_type_next_base ()
G_TYPE_NONE
G_TYPE_OBJECT
G_TYPE_PARAM
G_TYPE_PARAM_BOOLEAN
G_TYPE_PARAM_BOXED
G_TYPE_PARAM_CHAR
G_TYPE_PARAM_DOUBLE
G_TYPE_PARAM_ENUM
G_TYPE_PARAM_FLAGS
G_TYPE_PARAM_FLOAT
G_TYPE_PARAM_INT
G_TYPE_PARAM_INT64
G_TYPE_PARAM_LONG
G_TYPE_PARAM_OBJECT
G_TYPE_PARAM_OVERRIDE
G_TYPE_PARAM_PARAM
G_TYPE_PARAM_POINTER
G_TYPE_PARAM_STRING
G_TYPE_PARAM_UCHAR
G_TYPE_PARAM_UINT
G_TYPE_PARAM_UINT64
G_TYPE_PARAM_ULONG
G_TYPE_PARAM_UNICHAR
G_TYPE_PARAM_VALUE_ARRAY
g_type_parent ()
g_type_plugin_complete_interface_info ()
g_type_plugin_complete_type_info ()
g_type_plugin_unuse ()
g_type_plugin_use ()
G_TYPE_POINTER
g_type_qname ()
g_type_query ()
g_type_register_dynamic ()
g_type_register_fundamental ()
g_type_register_static ()
g_type_remove_class_cache_func ()
g_type_remove_interface_check ()
G_TYPE_RESERVED_BSE_FIRST
G_TYPE_RESERVED_BSE_LAST
G_TYPE_RESERVED_GLIB_FIRST
G_TYPE_RESERVED_GLIB_LAST
G_TYPE_RESERVED_USER_FIRST
g_type_set_qdata ()
G_TYPE_STRING
G_TYPE_STRV
G_TYPE_UCHAR
G_TYPE_UINT
G_TYPE_UINT64
G_TYPE_ULONG
G_TYPE_VALUE
G_TYPE_VALUE_ARRAY
g_value_array_append ()
g_value_array_copy ()
g_value_array_free ()
g_value_array_get_nth ()
g_value_array_insert ()
g_value_array_new ()
g_value_array_prepend ()
g_value_array_remove ()
g_value_array_sort ()
g_value_array_sort_with_data ()
G_VALUE_COLLECT()
G_VALUE_COLLECT_FORMAT_MAX_LENGTH
g_value_copy ()
g_value_dup_boxed ()
g_value_dup_object ()
g_value_dup_param ()
g_value_dup_string ()
g_value_fits_pointer ()
g_value_get_boolean ()
g_value_get_boxed ()
g_value_get_char ()
g_value_get_double ()
g_value_get_enum ()
g_value_get_flags ()
g_value_get_float ()
g_value_get_int ()
g_value_get_int64 ()
g_value_get_long ()
g_value_get_object ()
g_value_get_param ()
g_value_get_pointer ()
g_value_get_string ()
g_value_get_uchar ()
g_value_get_uint ()
g_value_get_uint64 ()
g_value_get_ulong ()
G_VALUE_HOLDS()
G_VALUE_HOLDS_BOOLEAN()
G_VALUE_HOLDS_BOXED()
G_VALUE_HOLDS_CHAR()
G_VALUE_HOLDS_DOUBLE()
G_VALUE_HOLDS_ENUM()
g_type_value_table_peek ()
G_VALUE_HOLDS_FLAGS()
G_VALUE_HOLDS_FLOAT()
G_VALUE_HOLDS_INT()
G_VALUE_HOLDS_INT64()
G_VALUE_HOLDS_LONG()
G_VALUE_HOLDS_OBJECT()
G_VALUE_HOLDS_PARAM()
G_VALUE_HOLDS_POINTER()
G_VALUE_HOLDS_STRING()
G_VALUE_HOLDS_UCHAR()
G_VALUE_HOLDS_UINT()
G_VALUE_HOLDS_UINT64()
G_VALUE_HOLDS_ULONG()
g_value_init ()
G_VALUE_LCOPY()
g_value_peek_pointer ()
g_value_register_transform_func ()
g_value_reset ()
g_value_set_boolean ()
g_value_set_boxed ()
g_value_set_boxed_take_ownership ()
g_value_set_char ()
g_value_set_double ()
g_value_set_enum ()
g_value_set_flags ()
g_value_set_float ()
g_value_set_int ()
g_value_set_int64 ()
g_value_set_long ()
g_value_set_object ()
g_value_set_object_take_ownership ()
g_value_set_param ()
g_value_set_param_take_ownership ()
g_value_set_pointer ()
g_value_set_static_boxed ()
g_value_set_static_string ()
g_value_set_string ()
g_value_set_string_take_ownership ()
g_value_set_uchar ()
g_value_set_uint ()
g_value_set_uint64 ()
g_value_set_ulong ()
g_value_take_boxed ()
g_value_take_object ()
g_value_take_param ()
g_value_take_string ()
g_value_transform ()
G_VALUE_TYPE()
g_value_type_compatible ()
G_VALUE_TYPE_NAME()
g_value_type_transformable ()
g_value_unset ()
GBaseFinalizeFunc ()
GBaseInitFunc ()
GBoxedCopyFunc ()
GBoxedFreeFunc ()
GCallback ()
GCClosure
gchararray
GClassFinalizeFunc ()
GClassInitFunc ()
GClosure
GClosureMarshal ()
GClosureNotify ()
GEnumClass
GEnumValue
GFlagsClass
GFlagsValue
GInstanceInitFunc ()
GInterfaceFinalizeFunc ()
GInterfaceInfo
GInterfaceInitFunc ()
GObject
GObjectClass
GObjectConstructParam
GObjectFinalizeFunc ()
GObjectGetPropertyFunc ()
GObjectSetPropertyFunc ()
GParameter
GParamSpec
GParamSpecBoolean
GParamSpecBoxed
GParamSpecChar
GParamSpecClass
GParamSpecDouble
GParamSpecEnum
GParamSpecFlags
GParamSpecFloat
GParamSpecInt
GParamSpecInt64
GParamSpecLong
GParamSpecObject
GParamSpecOverride
GParamSpecParam
GParamSpecPointer
GParamSpecPool
GParamSpecString
GParamSpecTypeInfo
GParamSpecUChar
GParamSpecUInt
GParamSpecUInt64
GParamSpecULong
GParamSpecUnichar
GParamSpecValueArray
GSignalAccumulator ()
GSignalCMarshaller
GSignalEmissionHook ()
GSignalInvocationHint
GSignalQuery
GStrv
GToggleNotify ()
GType
GTypeClass
GTypeClassCacheFunc ()
GTypeFundamentalInfo
GTypeInfo
GTypeInstance
GTypeInterface
GTypeInterfaceCheckFunc ()
GTypeModule
GTypeModuleClass
GTypePlugin
GTypePluginClass
GTypePluginCompleteInterfaceInfo()
GTypePluginCompleteTypeInfo ()
GTypePluginUnuse ()
GTypePluginUse ()
GTypeQuery
GTypeValueTable
GValue
GValueArray
GValueTransform ()
GWeakNotify ()

U

union GTypeCValue

See Also

Libraries Supported in Open Environment


Alphabetical Index for libc

Index - libc

A

 getopt_long ntohl
         strtof
write

getopt_long_only

 ntohs strtoimax writev
alphasort

abort
 getpagesize
strtok wscanf

wsetlocale
abs
 getpeername

O

 strtok_r
wstrdate
accept
 getpgid
strtol wstrtime
access
 getpgrp open strtold wrename
adjtime
 getpid opendir strtoll wsystem
asctime
 getppid
strtoq wunlink
asctime_r
 getpriority

P

 strtoul wcslcat
asprintf
 getprotobyname
strtoull
atof
 getprotobynumber pathconf
strtoumax wcslcpy
atoi
 getpwent pclose strtouq wseekdir
atol
 getpwnam perror strxfrm wtelldir
atoll
 getpwnam_r
pipe swab wfindfirst

getpwuid

 popen swprintf wfindnext

B

 getpwuid_r printf swscanf wcreat

getservbyname

 putc symlink waccess
bcmp
 getservbyport putchar sync wpopen
bcopy
 getservent putenv sysconf wopendir
bind
 getsockname puts

T
bindresvport
 getsockopt putw towlower
brk
 gettimeofday putwc tzset
bsearch
 getuid putwchar towupper
btowc
 getw
tempnam

bzero
 getwc

Q

 telldir

getwchar
time

C

 gmtime
 qsort tmpfile

gmtime_r
tmpnam
calloc

R

 toascii
chdir

H
tolower
chmod
rand

random 		toupper
clearerr
 htonl read towctrans
clock
 htons readdir

U
clock_getcpulockid
readlink
unlink
clock_getres

I

 readv unsetenv
clock_gettime
realloc usleep
clock_settime
 iconv
realpath utime
close
 iconv_close recv utimes
closedir
 iconv_open recvfrom umask
confstr
 if_freenameindex recvmsg uname
connect
 if_indextoname regcomp ungetc
creat
 if_nameindex regerror ungetwc
ctime
 if_nametoindex regexec

V
ctime_r
 index regfree vsnprintf

inet_addr remove vwscanf

D

 inet_ntoa rename vwprintf

vswscanf
difftime
         inet_pton rewind vswprintf
div
 initgroups

initstate 		rewinddir vsscanf
dup
 ioctl
rindex vsprintf
dup2
 isalnum rmdir vasprintf

isalpha

S

 vfprintf

E

 isascii
 setkey
         vfscanf

isatty
 system vfwprintf
endgrent

         iscntrl scanf

scandir 		vfwscanf
endpwent
 isdigit sched_getpriority_max vprintf
endservent
 isgraph sched_getpriority_min vscanf
exit
 islower sched_yield

W
_Exit
         isprint
 seekdir wait

F

 ispunct select wait4
findclose isspace

         semctl waitpid

wasctime
fchdir
         isupper semget wrmdir
fchmod
 iswalnum semop wstat
fclose
 iswalpha send wchdir
fcntl
 iswblank sendmsg wchmod

wcserror
fdopen
 iswcntrl sendto wctime

wfopen
feof
 iswctype setbuf wgetcwd
ferror
 iswdigit setegid wmkdir
fflush
 iswgraph setenv wopen

wperror
ffs
 iswlower seteuid wrealpath
fgetc
 iswprint setgid wcpcpy
fgetpos
 iswpunct setgrent wcpncpy
fgets
 iswspace sethostname wcrtomb
fgetwc
 iswupper setjmp
wcscasecmp
fgetws
 iswxdigit
setlocale wcscat
fileno
         isxdigit setpgid wcschr
flockfile
setpgrp wcscmp
fopen

L

 setpriority wcscoll
fpathconf
setpwent wcscpy
fprintf
 labs
setregid wcscspn
fputc
 ldiv setreuid wcsdup
fputs
 link setservent wcsftime
fputwc
 listen setsid wcsicmp

wcsicoll
fputws
 llabs setsockopt

setstate 		wcslen
fread
 lldiv setuid
wcslwr
free
 localeconv setvbuf wcsncasecmp
freeaddrinfo
 localtime shmat wcsncat
freopen
 localtime_r shmctl wcsncmp

wcsncoll
fscanf
 longjmp shmdt wcsncpy
fseek
         lseek shmget wcsnlen

wcsnicoll
fsetpos
 lstat shutdown wcsnicmp

wcsnset
fstat
sleep wcsnrtombs
fsync

M

 snprintf wcspbrk
ftell
sockatmark wcsrchr
ftok
 malloc
socket wcserv
at
 mblen sprint wcsrtombs
ftrylockfile
 mbrlen srand wcsset
funlockfile
 mbrtowc sscanf

srandom 		wcsspn
fwide
 mbsinit stat wcsstr

wcsrev
fwprintf
 mbsnrtowcs stpcpy wcstmpnam

wcstod
fwrite
 mbsrtowcs strcasecmp wcstof
fwscanf
 mbstowcs strcasestr wcstoimax

mbtowc strcat
         wcstok

memccpy strchr wcstol

memchr
 strcmp wcstold

G

 memcmp strcoll wcstoll

memcpy
         strcpy wcstombs
gai_strerror
 memmove strcspn wcstoq
getaddrinfo
 memset strdup wcstoul
getc
 mkdir strerror wcstoull
getchar
 mkfifo strerror_r wcstoumax
getcwd
 mkstemp strfmon wcstouq
getdirentries
 mktime strftime wcsupr
getdtablesize
 mmap strlen wcswcs
getegid
 mprotect strncasecmp wcswidth
getenv
 msgctl strncat
wcsxfrm
geteuid
 msgget strncmp wctob
getgid msgrcv strncpy wctomb
getgrent
 msgsnd strndup wctrans
getgrgid
 msync strnlen wctype
getgrgid_r
 munmap strpbrk wcwidth

wfdopen

wfreopen
getgrnam
strptime wmemchr
getgrnam_r
 strrchr wmemcmp
getgroups
strsep wmemcpy
gethostbyaddr
 nanosleep
strspn wmemmove
getnameinfo
 nice strstr wmemset
getopt
 nl_langinfo strtod wprintf

See Also

Libraries Supported in Open Environment


Alphabetical Index for libcrypt

Index - libcrypt

C

crypt

E

encrypt

S

setkey

See Also

Libraries Supported in Open Environment


Alphabetical Index for libcrypto

Index - libcrypto

A

ASN1_generate_nconf

ASN1_generate_v3

ASN1_OBJECT_new

ASN1_OBJECT_free

ASN1_STRING_cmp

ASN1_STRING_dup

ASN1_STRING_data

ASN1_STRING_length

ASN1_STRING_length_set

ASN1_STRING_set

ASN1_STRING_type

ASN1_STRING_new

ASN1_STRING_print_ex

B

bio

BIO_ctrl

BIO_callback_ctrl

BIO_ptr_ctrl

BIO_int_ctrl

BIO_reset

BIO_seek

BIO_tell

BIO_flush

BIO_eof

BIO_set_close

BIO_get_close

BIO_pending

BIO_wpending

BIO_ctrl_pending

BIO_ctrl_wpending

BIO_get_info_callback

BIO_set_info_callback

BIO_f_base64

BIO_f_buffer

BIO_f_cipher

BIO_set_cipher

BIO_get_cipher_status

BIO_get_cipher_ctx

BIO_f_md

BIO_set_md

BIO_get_md

BIO_get_md_ctx

BIO_f_null

BIO_f_ssl

BIO_set_ssl

BIO_get_ssl

BIO_set_ssl_mode

BIO_set_ssl_renegotiate_bytes

BIO_get_num_renegotiates

BIO_set_ssl_renegotiate_timeout

BIO_new_ssl

BIO_new_ssl_connect

BIO_new_buffer_ssl_connect

BIO_ssl_copy_session_id

BIO_ssl_shutdown

BIO_find_type

BIO_next

BIO_new

BIO_set

BIO_free

BIO_vfree

BIO_free_all

BIO_push

BIO_pop

BIO_read

BIO_write

BIO_gets

BIO_puts

BIO_s_accept

BIO_set_accept_port

BIO_get_accept_port

BIO_set_nbio_accept

BIO_set_accept_bios

BIO_set_bind_mode

BIO_get_bind_mode

BIO_do_accept

BIO_s_bio

BIO_make_bio_pair

BIO_destroy_bio_pair

BIO_shutdown_wr

BIO_set_write_buf_size

BIO_get_write_buf_size

BIO_new_bio_pair

BIO_get_write_guarantee

BIO_ctrl_get_write_guarantee

BIO_get_read_request

BIO_ctrl_get_read_request

BIO_ctrl_reset_read_request

BIO_s_connect

BIO_set_conn_hostname

BIO_set_conn_port

BIO_set_conn_ip

BIO_set_conn_int_port

BIO_get_conn_hostname

BIO_get_conn_port

BIO_get_conn_ip

BIO_get_conn_int_port

BIO_set_nbio

BIO_do_connect

BIO_s_fd

BIO_set_fd

BIO_get_fd

BIO_new_fd

BIO_s_file

BIO_new_file

BIO_new_fp

BIO_set_fp

BIO_get_fp

BIO_read_filename

BIO_write_filename

BIO_append_filename

BIO_rw_filename

BIO_s_mem

BIO_set_mem_eof_return

BIO_get_mem_data

BIO_set_mem_buf

BIO_get_mem_ptr

BIO_new_mem_buf

BIO_s_null

BIO_s_socket

BIO_new_socket

BIO_get_callback

BIO_set_callback_arg

BIO_get_callback_arg

BIO_debug_callback

BIO_set_callback

BIO_should_retry

BIO_should_read

BIO_should_write

BIO_should_io_special

BIO_retry_type

BIO_get_retry_BIO

BIO_get_retry_reason

bn

BN_add

BN_sub

BN_mul

BN_sqr

BN_div

BN_mod

BN_nnmod

BN_mod_add

BN_mod_sub

BN_mod_mul

BN_mod_sqr

BN_exp

BN_mod_exp

BN_gcd

BN_add_word

BN_sub_word

BN_mul_word

BN_div_word

BN_mod_word

BN_BLINDING_new

BN_BLINDING_free

BN_BLINDING_update

BN_BLINDING_convert

BN_BLINDING_invert

BN_BLINDING_convert_ex

BN_BLINDING_invert_ex

BN_BLINDING_get_thread_id

BN_BLINDING_set_thread_id

BN_BLINDING_get_flags

BN_BLINDING_set_flags

BN_BLINDING_create_param

BN_bn2bin

BN_bin2bn

BN_bn2hex

BN_bn2dec

BN_hex2bn

BN_dec2bn

BN_print

BN_print_fp

BN_bn2mpi

BN_mpi2bn

BN_cmp

BN_ucmp

BN_is_zero

BN_is_one

BN_is_word

BN_is_odd

BN_copy

BN_dup

BN_CTX_new

BN_CTX_init

BN_CTX_free

BN_CTX_start

BN_CTX_get

BN_CTX_end

BN_generate_prime

BN_is_prime

BN_is_prime_fasttest

bn_mul_words

bn_mul_add_words

bn_sqr_words

bn_div_words

bn_add_words

bn_sub_words

bn_mul_comba4

bn_mul_comba8

bn_sqr_comba4

bn_sqr_comba8

bn_cmp_words

bn_mul_normal

bn_mul_low_normal

bn_mul_recursive

bn_mul_part_recursive

bn_mul_low_recursive

bn_mul_high

bn_sqr_normal

bn_sqr_recursive

bn_expand

bn_wexpand

bn_expand2

bn_fix_top

bn_check_top

bn_print

bn_dump

bn_set_max

bn_set_high

bn_set_low

BN_mod_inverse

BN_mod_mul_montgomery

BN_MONT_CTX_new

BN_MONT_CTX_init

BN_MONT_CTX_free

BN_MONT_CTX_set

BN_MONT_CTX_copy

BN_from_montgomery

BN_to_montgomery

BN_mod_mul_reciprocal

BN_div_recp

BN_RECP_CTX_new

BN_RECP_CTX_init

BN_RECP_CTX_free

BN_RECP_CTX_set

BN_new

BN_init

BN_clear

BN_free

BN_clear_free

BN_num_bytes

BN_num_bits

BN_num_bits_word

BN_rand

BN_pseudo_rand

BN_set_bit

BN_clear_bit

BN_is_bit_set

BN_mask_bits

BN_lshift

BN_lshift1

BN_rshift

BN_rshift1

BN_swap

BN_one

BN_value_one

BN_set_word

BN_get_word

BN_zero

BUF_MEM_new

BUF_MEM_free

BUF_MEM_grow

BUF_strdup

C

CONF_modules_load
CONF_modules_load_file
CONF_modules_unload

CRYPTO_cleanup_all_ex_data
CRYPTO_destroy_dynlockid
CRYPTO_get_new_dynlockid
CRYPTO_lock
CRYPTO_num_locks
CRYPTO_set_dynlock_create_callback
CRYPTO_set_dynlock_destroy_callback
CRYPTO_set_dynlock_lock_callback
CRYPTO_set_ex_data
CRYPTO_set_id_callback
CRYPTO_set_locking_callback
CONF_modules_free

D

d2i_ASN1_OBJECT

i2d_ASN1_OBJECT

d2i_DHparams

i2d_DHparams

d2i_DSAPublicKey

i2d_DSAPublicKey

d2i_DSAPrivateKey

i2d_DSAPrivateKey

d2i_DSA_PUBKEY

i2d_DSA_PUBKEY

d2i_DSA_SIG

i2d_DSA_SIG

d2i_PKCS8PrivateKey

d2i_PKCS8PrivateKey_fp

i2d_PKCS8PrivateKey_bio

i2d_PKCS8PrivateKey_fp

i2d_PKCS8PrivateKey_nid_bio

i2d_PKCS8PrivateKey_nid_fp

d2i_RSAPublicKey

i2d_RSAPublicKey

d2i_RSAPrivateKey

i2d_RSAPrivateKey

d2i_RSA_PUBKEY

i2d_RSA_PUBKEY

i2d_Netscape_RSA

d2i_Netscape_RSA

d2i_X509

i2d_X509

d2i_X509_bio

d2i_X509_fp

i2d_X509_bio

i2d_X509_fp

d2i_X509_ALGOR

i2d_X509_ALGOR

d2i_X509_CRL

i2d_X509_CRL

d2i_X509_CRL_bio

d2i_509_CRL_fp

i2d_X509_CRL_bio

i2d_X509_CRL_fp

d2i_X509_NAME

i2d_X509_NAME

d2i_X509_REQ

i2d_X509_REQ

d2i_X509_REQ_bio

d2i_X509_REQ_fp

i2d_X509_REQ_bio

i2d_X509_REQ_fp

d2i_X509_SIG

i2d_X509_SIG

DES_random_key

DES_set_key

DES_key_sched

DES_set_key_checked

DES_set_key_unchecked

DES_set_odd_parity

DES_is_weak_key

DES_ecb_encrypt

DES_ecb2_encrypt

DES_ecb3_encrypt

DES_ncbc_encrypt

DES_cfb_encrypt

DES_ofb_encrypt

DES_pcbc_encrypt

DES_cfb64_encrypt

DES_ofb64_encrypt

DES_xcbc_encrypt

DES_ede2_cbc_encrypt

DES_ede2_cfb64_encrypt

DES_ede2_ofb64_encrypt

DES_ede3_cbc_encrypt

DES_ede3_cbcm_encrypt

DES_ede3_cfb64_encrypt

DES_ede3_ofb64_encrypt

DES_cbc_cksum

DES_quad_cksum

DES_string_to_key

DES_string_to_2keys

DES_fcrypt

DES_crypt

DES_enc_read

DES_enc_write

des_modes

des_read_password

des_read_2passwords

des_read_pw_string

des_read_pw

dh

DH_compute_key

DH_generate_key

DH_check

DH_generate_parameters

DH_get_ex_new_index

DH_set_ex_data

DH_get_ex_data

DH_new

DH_free

DH_set_method

DH_set_default_method

DH_get_default_method

DH_new_method

DH_OpenSSL

DH_size

dsa

DSA_do_sign

DSA_do_verify

DSA_dup_DH

DSA_generate_key

DSA_generate_parameters

DSA_get_ex_new_index

DSA_set_ex_data

DSA_get_ex_data

DSA_new

DSA_free

DSA_set_method

DSA_set_default_method

DSA_get_default_method

DSA_new_method

DSA_OpenSSL

DSA_SIG_new

DSA_SIG_free

DSA_sign

DSA_sign_setup

DSA_verify

DSA_size

E

engine

err

ERR_clear_error

ERR_error_string

ERR_error_string_n

ERR_lib_error_string

ERR_func_error_string

ERR_reason_error_string

ERR_get_error

ERR_peek_error

ERR_peek_last_error

ERR_get_error_line

ERR_peek_error_line

ERR_peek_last_error_line

ERR_get_error_line_data

ERR_peek_error_line_data

ERR_peek_last_error_line_data

ERR_GET_LIB

ERR_GET_FUNC

ERR_GET_REASON

ERR_load_crypto_strings

ERR_free_strings

ERR_load_strings

ERR_PACK

ERR_get_next_error_library

ERR_print_errors

ERR_print_errors_fp

ERR_put_error

ERR_add_error_data

ERR_remove_state

ERR_set_mark

ERR_pop_to_mark

ERR_load_UI_strings

evp

EVP_BytesToKey

EVP_MD_CTX_init

EVP_MD_CTX_create

EVP_DigestInit_ex

EVP_DigestUpdate

EVP_DigestFinal_ex

EVP_MD_CTX_cleanup

EVP_MD_CTX_destroy

EVP_MAX_MD_SIZE

EVP_MD_CTX_copy_ex

EVP_MD_CTX_copy

EVP_MD_type

EVP_MD_pkey_type

EVP_MD_size

EVP_MD_block_size

EVP_MD_CTX_md

EVP_MD_CTX_size

EVP_MD_CTX_block_size

EVP_MD_CTX_type

EVP_md_null

EVP_md2

EVP_md5

EVP_sha

VP_sha1

EVP_dss

EVP_dss1

EVP_get_digestbyname

EVP_get_digestbynid

EVP_get_digestbyobj

EVP_CIPHER_CTX_init

EVP_EncryptInit_ex

EVP_EncryptUpdate

EVP_EncryptFinal_ex

EVP_DecryptInit_ex

EVP_DecryptUpdate

EVP_DecryptFinal_ex

EVP_CipherInit_ex

EVP_CipherUpdate

EVP_CipherFinal_ex

EVP_CIPHER_CTX_set_key_length

EVP_CIPHER_CTX_ctrl

EVP_CIPHER_CTX_cleanup

EVP_EncryptInit

EVP_EncryptFinal

EVP_DecryptInit

EVP_DecryptFinal

EVP_CipherInit

EVP_CipherFinal

EVP_get_cipherbyname

EVP_get_cipherbynid

EVP_get_cipherbyobj

EVP_CIPHER_nid

EVP_CIPHER_block_size

EVP_CIPHER_key_length

EVP_CIPHER_iv_length

EVP_CIPHER_flags

EVP_CIPHER_mode

EVP_CIPHER_type

EVP_CIPHER_CTX_cipher

EVP_CIPHER_CTX_nid

EVP_CIPHER_CTX_block_size

EVP_CIPHER_CTX_key_length

EVP_CIPHER_CTX_iv_length

EVP_CIPHER_CTX_get_app_data

EVP_CIPHER_CTX_set_app_data

EVP_CIPHER_CTX_type

EVP_CIPHER_CTX_flags

EVP_CIPHER_CTX_mode

EVP_CIPHER_param_to_asn1

EVP_CIPHER_asn1_to_param

EVP_CIPHER_CTX_set_padding

EVP_OpenInit

EVP_OpenUpdate

EVP_OpenFinal

EVP_PKEY_new

EVP_PKEY_free

EVP_PKEY_set1_RSA

EVP_PKEY_set1_DSA

EVP_PKEY_set1_DH

EVP_PKEY_set1_EC_KEY

EVP_PKEY_get1_RSA

EVP_PKEY_get1_DSA

EVP_PKEY_get1_DH

EVP_PKEY_get1_EC_KEY

EVP_PKEY_assign_RSA

EVP_PKEY_assign_DSA

EVP_PKEY_assign_DH

EVP_PKEY_assign_EC_KEY

EVP_PKEY_type

EVP_SealInit

EVP_SealUpdate

EVP_SealFinal

EVP_SignInit

EVP_SignUpdate

EVP_SignFinal

EVP_VerifyInit

EVP_VerifyUpdate

EVP_VerifyFinal

H

hmac

HMAC_Init

HMAC_Update

HMAC_Final

HMAC_cleanup

L

lh_stats

lh_node_stats

lh_node_usage_stats

lh_stats_bio

lh_node_stats_bio

lh_node_usage_stats_bio

lh_new

lh_free

lh_insert

lh_delete

lh_retrieve

lh_doal

lh_doall_arg

lh_error

M

MD2

MD2_Init

MD2_Update

MD2_Final

md5

MD5_Init

MD5_Update

MD5_Final

O

OBJ_nid2obj

OBJ_nid2ln

OBJ_nid2sn

OBJ_obj2nid

OBJ_txt2nid

OBJ_ln2nid

OBJ_sn2nid

OBJ_cmp

OBJ_dup

OBJ_txt2obj

OBJ_obj2txt

OBJ_create

OBJ_cleanup

OpenSSL_add_all_algorithms

OpenSSL_add_all_ciphers

OpenSSL_add_all_digests

OPENSSL_Applink

OPENSSL_config

OPENSSL_no_config

OPENSSL_ia32cap

OPENSSL_load_builtin_modules

OPENSSL_VERSION_NUMBER

P

pem

PKCS12_create

PKCS12_parse

PKCS7_decrypt

PKCS7_encrypt

PKCS7_sign

PKCS7_verify

R

rand

RAND_add

RAND_seed

RAND_status

RAND_bytes

RAND_pseudo_bytes

RAND_cleanup

RAND_egd

RAND_load_file

RAND_write_file

RAND_file_name

RAND_set_rand_method

RAND_get_rand_method

RAND_SSLeay

rc4

RC4_set_key

rsa

RSA_blinding_on

RSA_blinding_off

RSA_check_key

RSA_generate_key_ex

RSA_get_ex_new_index

RSA_set_ex_data

RSA_get_ex_data

RSA_new

RSA_padding_add_PKCS1_type_1

RSA_padding_check_PKCS1_type_1

RSA_padding_add_PKCS1_type_2

RSA_padding_check_PKCS1_type_2

RSA_padding_add_PKCS1_OAEP

RSA_padding_check_PKCS1_OAEP

RSA_padding_add_SSLv23

RSA_padding_check_SSLv23

RSA_padding_add_none

RSA_padding_check_none

RSA_print

RSA_print_fp

DSAparams_print

DSAparams_print_fp

DSA_print

DSA_print_fp

DHparams_print

DHparams_print_fp

RSA_private_encrypt

RSA_public_decrypt

RSA_public_encrypt

RSA_set_method

RSA_sign

RSA_sign_ASN1_OCTET_STRING

RSA_size

S

SHA1

SHA1_Init

SHA1_Update

SHA1_Final

SMIME_read_PKCS7

SMIME_write_PKCS7

SSLeay

SSL_load_error_strings

SSLeay_version

U

ui

UI_new

UI_new_method

UI_free

UI_add_input_string

UI_dup_input_string

UI_add_verify_string

UI_dup_verify_string

UI_add_input_boolean

UI_dup_input_boolean

UI_add_info_string

UI_dup_info_string

UI_add_error_string

UI_dup_error_string

UI_construct_prompt

UI_add_user_data

UI_get0_user_data

UI_get0_result

UI_process

UI_ctrl

UI_set_default_method

UI_get_default_method

UI_get_method

UI_set_method

UI_OpenSSL

X

x509

X509_NAME_add_entry_by_txt

X509_NAME_add_entry_by_OBJ

X509_NAME_add_entry_by_NID

X509_NAME_add_entry

X509_NAME_delete_entry

X509_NAME_ENTRY_get_object

X509_NAME_get_index_by_NID

X509_NAME_get_index_by_OBJ

X509_NAME_get_entry

X509_NAME_entry_count

X509_NAME_get_text_by_NID

X509_NAME_get_text_by_OBJ

X509_NAME_print_ex

X509_NAME_print_ex_fp

X509_NAME_print, X509_NAME_oneline

X509_free

X509_new

See Also

Libraries Supported in Open Environment


Alphabetical Index for libdl

Index - libdl

D

dlclose

dlerror

dlopen

dlsym

See Also

Libraries Supported in Open Environment


Alphabetical Index for libintl

Index - libintl

B

bind_textdomain_codeset

bindtextdomain

D

dcgettext

dcngettext

dgettext

dngettext

G

gettext

N

ngettext

T

textdomain

See Also

Libraries Supported in Open Environment

© 2006-2007 Nokia


Alphabetical Index for libm

Index - libm

A

 fabsf
jnf
remainderl
acos
         fabsl jnl remquo
acosf
         fdim
remquof
acosh
         fdimf

L

 remquol
acoshf
         fdiml
rint
acoshl
         feclearexcept ldexp rintf
acosl
         fegetenv ldexpf rintl
asin
         fegetexceptflag ldexpl round
asinf
         fegetround lgamma roundf
asinh
         feholdexcept lgamma_r roundl
asinhf
         feraiseexcept lgammaf
asinhl
         fesetenv lgammaf_r

S
asinl
         fesetexceptflag lgammal
atan
         fesetround lgammal_r scalb
atan2
         fetestexcept llrint scalbf
atan2f
         feupdateenv llrintf scalbl
atan2l
         finite
llrintl scalbln
atanf
         finitef llround scalblnf
atanh
         finitel llroundf scalblnl
atanhf
         floor llroundl scalbn
atanhl
         floorf log
scalbnf
atanl
         floorl log10 scalbnl

fma log10f significand

C

 fmaf log10l significandf

fmal log1p significandl
cbrt
         fmax log1pf sin
cbrtf
         fmaxf log1pl sinf
cbrtl
         fmaxl logb sinh
ceil
         fmin
logbf sinhf
ceilf
         fminf logbl sinhl
ceill
         fminl logf sinl
copysign
         fmod logl sqrt
copysignf
         fmodf lrint sqrtf
copysignl
         fmodl lrintf sqrtl
cos
         fpclassify lrintl
cosf
         frexp lround

T
cosh
         frexpf lroundf tan
coshf
         frexpl lroundl tanf
coshl

tanh
cosl

G

M

 tanhf

tanhl

D

 gamma modf
tanl

gammaf modff tgamma
drem
         gammal modfl trunc
dremf

truncf
dreml

H

 truncl

E

 hypot nearbyint

Y

hypotf nearbyintf
erf
         hypotl nearbyintl y0
erfc
nextafter y0f
erfcf

I

 nextafterf y0l
erfcl
nextafterl y1
erff
         ilogb nexttoward y1f
erfl
         ilogbf nexttowardf y1l
exp
         ilogbl nexttowardl yn
exp2
         ieee
ynf
exp2f

P

 ynl
expf

J

expl
pow

expm1
         j0
powf
expm1f
         j0f powl
expm1l
         j0l

j1

R

F

 j1f

j1l remainder

fabs
         jn remainderf

See Also

Libraries Supported in Open Environment


Alphabetical Index for libpthread

Index - libpthread

P

 pthread_cond_destroy pthread_key_delete
pthread_setspecific

pthread_cond_init
         pthread_mutex_destroy
pthread_attr_destroy

pthread_cond_signal pthread_mutex_init

S
pthread_attr_getdetachstate pthread_cond_timedwait pthread_mutex_lock
pthread_attr_getschedparam
pthread_cond_wait pthread_mutex_trylock sem_destroy
pthread_attr_getschedpolicy
pthread_condattr_destroy pthread_mutex_unlock sem_getvalue
pthread_attr_getscope
pthread_condattr_init pthread_mutexattr_destroy sem_init
pthread_attr_getstacksize
pthread_create pthread_mutexattr_gettype sem_post
pthread_attr_init
pthread_detach pthread_mutexattr_getpshared sem_timedwait
pthread_attr_setdetachstate
pthread_equal pthread_mutexattr_init sem_trywait
pthread_attr_setschedparam
pthread_exit pthread_mutexattr_settype sem_wait
pthread_attr_setschedpolicy
pthread_getschedparam pthread_mutexattr_setpshared
pthread_attr_setscope
pthread_getspecific
pthread_once
pthread_attr_setstacksize
pthread_join pthread_self
pthread_cond_broadcast
pthread_key_create pthread_setschedparam

See Also

Libraries Supported in Open Environment


Alphabetical Index for libssl

Index - libssl

D

d2i_SSL_SESSION

I

i2d_SSL_SESSION

S

SSL_accept

SSL_alert_type_string

SSL_alert_type_string_long

SSL_alert_desc_string

SSL_alert_desc_string_long

SSL_CIPHER_get_name

SSL_CIPHER_get_bits

SSL_CIPHER_get_version

SSL_CIPHER_description

SSL_clear

SSL_COMP_add_compression_method

SSL_connect

SSL_CTX_add_extra_chain_cert

SSL_CTX_add_session

SSL_add_session

SSL_CTX_remove_session

SSL_remove_session

SSL_CTX_ctrl

SSL_CTX_callback_ctrl

SSL_ctrl

SSL_callback_ctrl

SSL_CTX_flush_sessions

SSL_flush_sessions

SSL_CTX_free

SSL_CTX_get_ex_new_index

SSL_CTX_set_ex_data

SSL_CTX_get_ex_data

SSL_CTX_get_verify_mode

SSL_get_verify_mode

SSL_CTX_get_verify_depth

SSL_get_verify_depth

SSL_get_verify_callback

SSL_CTX_get_verify_callback

SSL_CTX_load_verify_locations

SSL_CTX_new

SSL_CTX_sess_number

SSL_CTX_sess_set_cache_size

SSL_CTX_sess_get_cache_size

SSL_CTX_sess_set_get_cb

SSL_CTX_sess_set_new_cb

SSL_CTX_sess_set_remove_cb

SSL_CTX_sess_set_get_cb

SSL_CTX_sess_get_new_cb

SSL_CTX_sess_get_remove_cb

SSL_CTX_sessions

SSL_CTX_set_cert_store

SSL_CTX_get_cert_store

SSL_CTX_set_cert_verify_callback

SSL_CTX_set_cipher_list

SSL_set_cipher_list

SSL_CTX_set_client_CA_list

SSL_set_client_CA_list

SSL_CTX_add_client_CA

SSL_add_client_CA

SSL_CTX_set_client_cert_cb

SSL_CTX_get_client_cert_cb

SSL_CTX_set_default_passwd_cb

SSL_CTX_set_default_passwd_cb_userdata

SSL_CTX_set_generate_session_id

SSL_set_generate_session_id

SSL_has_matching_session_id

SSL_CTX_set_info_callback

SSL_CTX_get_info_callback

SSL_set_info_callback

SSL_get_info_callback

SSL_CTX_set_max_cert_list

SSL_CTX_get_max_cert_list

SSL_set_max_cert_list

SSL_get_max_cert_list

SSL_CTX_set_mode

SSL_set_mode

SSL_CTX_get_mode

SSL_get_mode

SSL_CTX_set_msg_callback

SSL_CTX_set_msg_callback_arg

SSL_set_msg_callback

SSL_get_msg_callback_arg

SSL_CTX_set_options

SSL_set_options

SSL_CTX_get_options

SSL_get_options

SSL_CTX_set_quiet_shutdown

SSL_CTX_get_quiet_shutdown

SSL_set_quiet_shutdown

SSL_get_quiet_shutdown

SSL_CTX_set_session_cache_mode

SSL_CTX_get_session_cache_mode

SSL_CTX_set_session_id_context

SSL_set_session_id_context

SSL_CTX_set_ssl_version

SSL_set_ssl_method

SSL_get_ssl_method

SSL_CTX_set_timeout

SSL_CTX_get_timeout

SSL_CTX_set_tmp_dh_callback

SSL_CTX_set_tmp_dh

SSL_set_tmp_dh_callback

SSL_set_tmp_dh

SSL_CTX_set_tmp_rsa_callback

SSL_CTX_set_tmp_rsa

SSL_CTX_need_tmp_rsa

SSL_set_tmp_rsa_callback

SSL_set_tmp_rsa

SSL_need_tmp_rsa

SSL_CTX_set_verify

SSL_set_verify

SSL_CTX_set_verify_depth

SSL_set_verify_depth

SSL_CTX_use_certificate

SSL_CTX_use_certificate_ASN1

SSL_CTX_use_certificate_file

SSL_use_certificate

SSL_use_certificate_ASN1

SSL_use_certificate_file

SSL_CTX_use_certificate_chain_file

SSL_CTX_use_PrivateKey

SSL_CTX_use_PrivateKey_ASN1

SSL_CTX_use_PrivateKey_file

SSL_CTX_use_RSAPrivateKey

SSL_CTX_use_RSAPrivateKey_ASN1

SSL_CTX_use_RSAPrivateKey_file

SSL_use_PrivateKey_file

SSL_use_PrivateKey_ASN1

SSL_use_PrivateKey

SSL_use_RSAPrivateKey

SSL_use_RSAPrivateKey_ASN1

SSL_use_RSAPrivateKey_file

SSL_CTX_check_private_key

SSL_check_private_key

SSL_do_handshake

SSL_free

SSL_get_ciphers

SSL_get_cipher_list

SSL_get_client_CA_list

SSL_CTX_get_client_CA_list

SSL_get_current_cipher

SSL_get_cipher

SSL_get_cipher_name

SSL_get_cipher_bits

SSL_get_cipher_version

SSL_get_default_timeout

SSL_get_error

SSL_get_ex_data_X509_STORE_CTX_idx

SSL_get_ex_new_index

         SSL_SESSION_set_ex_data

SSL_SESSION_get_ex_data

SSL_get_fd

SSL_get_peer_cert_chain

SSL_get_peer_certificate

SSL_get_rbio

SSL_get_session

SSL_get_SSL_CTX

SSL_get_verify_result

SSL_get_version

SSL_library_init

OpenSSL_add_ssl_algorithms

SSLeay_add_ssl_algorithms

SSL_load_client_CA_file

SSL_new

SSL_pending

SSL_read

SSL_rstate_string

SSL_rstate_string_long

SSL_SESSION_free

SSL_SESSION_get_ex_new_index

SSL_SESSION_set_ex_data

SSL_SESSION_get_ex_data

SSL_SESSION_get_time

SSL_SESSION_set_time

SSL_SESSION_get_timeout

SSL_SESSION_set_timeout

SSL_session_reused

SSL_set_bio

SSL_set_connect_state

SSL_get_accept_state

SSL_set_fd

SSL_set_session

SSL_set_shutdown

SSL_get_shutdown

SSL_set_verify_result

SSL_shutdown

SSL_state_string

SSL_state_string_long

SSL_want

SSL_want_nothing

SSL_want_read

SSL_want_write

SSL_want_x509_lookup

SSL_write

See Also

Libraries Supported in Open Environment


Alphabetical Index for libz

Index - libz

A

adler32

C

compress2

compress

compressbound

 crc32

D

deflate

deflatebound

deflatecopy

deflateend

deflateinit2

deflateinit

 deflateparams

deflatereset

deflatesetdictionary

G

get-crc-table

gzclose

gzdopen

gzeof

gzerror

 gzflush

gzgetc

gzgets

gzopen

 gzprintf

gzputc

gzputs

gzread

gzrewind

 gzseek
         gzsetparams

gztell

gzwrite

I

inflate

inflateend

inflateinit2

inflateinit

inflatereset

inflatesetdictionary

inflatesync

inflatesyncpoint

Z

zerror

zlibversion

U

uncompress

See Also

Libraries Supported in Open Environment


$title

S60 Open C
S60: Open C Quick Reference

S60: Open C Quick Reference

Table of Contents

Quick Reference

Quick Reference

Function | Description | Header | Library
System Calls API | APIs those define all basic operations using which other library api's can be defined. These APIs issue a system call (SWI) on UNIX\Linux platform. | unistd.h fcntl.h stdio.h paths.h stdlib.h sys\types.h sys\stat.h sys\ioctl.h sys\select.h sys\wait.h sys\limits.h sys\mman.h sys\time.h sys\resource.h | libc.dll
Standard I/O API | API for doing buffered/non-buffered Input/Output operation on all the fds. Fd's can represent file, socket, pipe, console. | stdio.h dirent.h | libc.dll
Math Operations API | This API gives set of APIs for math operations. | math.h float.h fenv.h stdlib.h | libm.dll
String Functions API | This API gives set of APIs for operating/manipulating string and memory. | string.h strings.h monetary.h stdlib.h | libc.dll
Regular Expressions API | This API gives set of APIs for operating/manipulating Regular expressions. | regex.h sys\types.h | libc.dll
Character Type Functions API | Character classification, conversion API's. | ctype.h wctype.h | libc.dll
Localization Function API | System-wide locale settings API. | iconv.h langinfo.h locale.h | libc.dll
Standard Library API | System related APIs like network byte conversion, environment, error string, creating temporary file and more. | stdio.h stdlib.h setjmp.h unistd.h netinet\in.h errno.h | libc.dll
Time Manipulation API | APIs for setting/getting/displaying system time. | sys\time.h time.h | libc.dll
Posix Thread API | Set of APIs for creating/manipulating threads and thread synchronization APIs. | pthread.h semaphore.h | libpthread.dll
IPC Functions API | Inter process communication related APIs. | unistd.h sys\ipc.h sys\stat.h sys\msg.h sys\sem.h sys\shm.h sys\mman.h sys\types.h | libc.dll
Socket Interface API | Set of APIs for supporting socket programming. | unistd.h sys\types.h arpa\inet.h sys\socket.h | libc.dll
System Database Interface API | Set of APIs for accessing system database specific to the Process. | pwd.h grp.h netdb.h sys\types.h | libc.dll
Wide Characters API | APIs that work on wide character. This covers I/O related and character conversion. | wchar.h wctype.h | libc.dll
Signal Handling API | Signal related APIs. | signal.h | libc.dll
Cryptography Related API | APIs used for encrypting and decrypting data. | md5.h sys\md5.h crypt.h | libcrypt.dll
Loading DLL related API | APIs used for loading, closing and calling a particular function with in a DLL. | dlfcn.h | libcrypt.dll
Backend API | Set of APIs exported by backend.dll those are used by all the libraries as system calls for getting any type of the Symbian Services like, File I/O, Socket I/O, Console I/O, or memory related operation. | sysif.h | backend.dll
Glib Version Information | Variables and functions to check the GLib version. | glib.h | libglib.dll
Glib Basic Types | Standard GLib types, defined for ease-of-use and portability. | glib.h | libglib.dll
Glib Limits of Basic Types | Portable method of determining the limits of the standard types. | glib.h | libglib.dll
Glib Standard Macros | Commonly-used macros. | glib.h | libglib.dll
Glib Type Conversion Macros | Portably storing integers in pointer variables. | glib.h | libglib.dll
Glib Byte Order Macros | Portable way to convert between different byte orders | glib.h | libglib.dll
Glib Numerical Definitions | mathematical constants, and floating point decomposition. | glib.h | libglib.dll
Glib Miscellaneous Macros | Specialized macros which are not used often. | glib.h | libglib.dll
Glib Atomic Operations | Basic atomic integer and pointer operations | glib.h | libglib.dll
Glib Main Event Loop | Manages all available sources of events. | glib.h | libglib.dll
Glib Threads | Thread abstraction; including threads, different mutexes, conditions and thread private data. | glib.h | libglib.dll libgthread.dll
Glib Thread Pools | Pools of threads to execute work concurrently. | glib.h | libglib.dll libgthread.dll
Glib Asynchronous Queues | Asynchronous communication between threads. | glib.h | libglib.dll
Glib Dynamic Loading of Modules | Portable method for dynamically loading 'plug-ins'. | gmodule.h | libgmodue.dll
Glib Memory Allocation | general memory-handling. | glib.h | libglib.dll
Glib IO Channels | Portable support for using files, pipes and sockets. | glib.h | libglib.dll
Glib Error Reporting | System for reporting errors. | glib.h | libglib.dll
Glib Message Output and Debugging Functions | Functions to output messages and help debug applications. | glib.h | libglib.dll
Glib Message Logging | Versatile support for logging messages with different levels of importance. | glib.h | libglib.dll
Glib String Utility Functions | Various string-related functions. | glib.h glib\gprintf.h | libglib.dll
Glib Character Set Conversion | Convert strings between different character sets using iconv(). | glib.h | libglib.dll
Glib Unicode Manipulation | Functions operating on Unicode characters and UTF-8 strings. | glib.h | libglib.dll
Glib Internationalization | Gettext support macros. | glib.h glib\gi18.h | libglib.dll
Glib Date and Time Functions | Calendrical calculations and miscellaneous time stuff. | glib.h | libglib.dll
Glib Random Numbers | Pseudo-random number generator. | glib.h | libglib.dll
Glib Hook Functions | Support for manipulating lists of hook functions. | glib.h | libglib.dll
Glib Miscellaneous Utility Functions | Selection of portable utility functions. | glib.h | libglib.dll
Glib Lexical Scanner | General purpose lexical scanner. | glib.h | libglib.dll
Glib Automatic String Completion | Support for automatic completion using a group of target strings. | glib.h | libglib.dll
Glib Timers | Keep track of elapsed time. | glib.h | libglib.dll
Glib Spawning Processes | Process launching. | glib.h | libglib.dll
Glib File Utilities | Various file-related functions. | glib.h glib\gstdio.h | libglib.dll
Glib Shell-related Utilities | Shell-like commandline handling. | glib.h | libglib.dll
Glib Commandline option parser | parses commandline options | glib.h | libglib.dll
Glib Glob-style pattern matching | Matches strings against patterns containing '*' (wildcard) and '?' (joker). | glib.h | libglib.dll
Glib Simple XML Subset Parser | Parses a subset of XML. | glib.h | libglib.dll
Glib Key-value file parser | Parses .ini-like config files | glib.h | libglib.dll
Glib Memory Slices | Efficient way to allocate groups of equal-sized chunks of memory. | glib.h | libglib.dll
Glib Memory Chunks | Deprecated way to allocate groups of equal-sized chunks of memory. | glib.h | libglib.dll
Glib Doubly-Linked Lists | Linked lists containing integer values or pointers to data, with the ability to iterate over the list in both directions. | glib.h | libglib.dll
Glib Singly-Linked Lists | Linked lists containing integer values or pointers to data, limited to iterating over the list in one direction. | glib.h | libglib.dll
Glib Double-ended Queues | Double-ended queue data structure. | glib.h | libglib.dll
Glib Trash Stacks | Maintain a stack of unused allocated memory chunks. | glib.h | libglib.dll
Glib Hash Tables | Associations between keys and values so that given a key the value can be found quickly. | glib.h | libglib.dll
Glib Strings | Text buffers which grow automatically as text is added. | glib.h | libglib.dll
Glib String Chunks | Efficient storage of groups of strings. | glib.h | libglib.dll
Glib Arrays | Arrays of arbitrary elements which grow automatically as elements are added. | glib.h | libglib.dll
Glib Pointer Arrays | Arrays of pointers to any type of data, which grow automatically as new elements are added. | glib.h | libglib.dll
Glib Byte Arrays | Arrays of bytes, which grow automatically as elements are added. | glib.h | libglib.dll
Glib Balanced Binary Trees | Sorted collection of key/value pairs optimized for searching and traversing in order. | glib.h | libglib.dll
Glib N-ary Trees | Trees of data with any number of branches. | glib.h | libglib.dll
Glib Quarks | a 2-way association between a string and a unique integer identifier. | glib.h | libglib.dll
Glib Keyed Data Lists | Lists of data elements which are accessible by a string or GQuark identifier. | glib.h | libglib.dll
Glib Datasets | Aassociate groups of data elements with particular memory locations. | glib.h | libglib.dll
Glib Relations and Tuples | LIsts of data which can be indexed on any number of fields. | glib.h | libglib.dll
Glib Caches | Caches allow sharing of complex data structures to save resources. | glib.h | libglib.dll
Glib Memory Allocators | deprecated way to allocate chunks of memory for GLIst, Gslist, Gnode | glib.h | libglib.dll
GType | The GLib Runtime type identification and management system | glib-gobject.h | libgobject.dll
GTypePlugin | An interface for dynamically load-able types. | glib-gobject.h | libgobject.dll
GTypeModule | Type loading modules. | glib-gobject.h | libgobject.dll
GObject | The base object type. | glib-gobject.h | libgobject.dll
Glib Enums and Flags | Enumeration and flags types. | glib-gobject.h | libgobject.dll
GBoxed | A mechanism to wrap opaque C structures registered by the type system. | glib-gobject.h | libgobject.dll
Glib Generic Values | A polymorphic type that can hold values of any other type. | glib-gobject.h | libgobject.dll
Glib Parameters and Values | Standard Parameter and Value Types. | glib-gobject.h | libgobject.dll
Glib Varargs Value Collection | Converting varargs to generic values. | glib-gobject.h | libgobject.dll
GParamSpec | Metadata for parameter specifications. | glib-gobject.h | libgobject.dll
Glib Signals | A means for customization of object behaviour and a general purpose notification mechanism | glib-gobject.h | libgobject.dll
Glib Closures | Functions as first-class objects. | glib-gobject.h | libgobject.dll
Glib Value arrays | A container structure to maintain an array of generic values. | glib-gobject.h | libgobject.dll
SSL Protocol Methods API | API functions which deal with the SSL/TLS protocol methods defined in SSL_METHOD structures. | ssl.h | libssl.dll
SSL Ciphers API | API functions which deal with the SSL/TLS ciphers defined in SSL_CIPHER structures. | ssl.h | libssl.dll
SSL Contexts API | API functions which deal with the SSL/TLS protocol context defined in the SSL_CTX structure. | ssl.h | libssl.dll
SSL Sessions API | API functions which deal with the SSL/TLS sessions defined in the SSL_SESSION structures. | ssl.h | libssl.dll
SSL Connections API | API functions which deal with the SSL/TLS connection defined in the SSL structure. | ssl.h | libssl.dll
SSL General API | Generic SSL/TLS API functions which are not very specific to any particular category. | ssl.h | libssl.dll
Crypto Symmetric Ciphers API | APIs related to Symmetric cryptography | des.h des_old.h rc2.h rc4.h aes.h | libcrypto.dll
Crypto Public Key Cryptography and Key Agreement API | APIs related to Asymmetric cryptography (Public key cryptography). | dsa.h dh.h rsa.h | libcrypto.dll
Crypto Certificates API | X.509 and x509 version 3 certificate handling | x509.h x509v3.h x509_vfy.h | libcrypto.dll
Crypto Authentication Codes and Hash Functions API | APIs related to hash algorithms: md2, hmac, md5, sha(sha0) and sha1. | hmac.h md2.h md5.h sha.h | libcrypto.dll
Crypto Auxillary Functions API | APIs related to random numbers generation and error handling. | err.h rand.h | libcrypto.dll
Crypto Input/Output and Data Encoding API | APIs related to ASN1 generation, object allocation, BIO control operations and high-level interface to cryptographic functions (pkcs7, pkcs12) . | asn1.h asn1_mac.h asn1t.h bio.h evp.h pem.h pem2.h pkcs7.h pkcs12.h crypto.h | libcrypto.dll
Crypto Utility Functions API | APIs related to BIGNUMs, buffer operations, generic implementation of stack, queue, LHASH statistics, utility functions, text based in memory database and engines. | bn.h buffer.h lhash.h objects.h obj_mac.h stack.h safestack.h txt_db.h comp.h conf_api.h conf.h dso.h engine.h e_os2.h ocsp.h opensslconf.h opensslv.h ossl_typ.h pq_compat.h pqueue.h store.h symhacks.h tmpdiff.h ui.h ui_compat.h | libcrypto.dll

Give feedback of this article

©Nokia 2006

Back to top

This material, including documentation and any related computer programs, is protected by copyright controlled by Nokia. All rights are reserved. Copying, including reproducing, storing, adapting or translating, any or all of this material requires the prior written consent of Nokia. This material also contains confidential information, which may not be disclosed to others without the prior written consent of Nokia.

Nokia is a registered trademark of Nokia Corporation. S60 and logo is a trademark of Nokia Corporation. Java and all Java-based marks are trademarks or registered trademarks of Sun Microsystems, Inc. Other company and product names mentioned herein may be trademarks or tradenames of their respective owners.


$title

S60 Open C
Standard Libraries Acknowledgements

Standard Libraries Acknowledgements

Table of Contents

Acknowledgements
Free BSD
Open SSL
Zlib
Glib

Acknowledgements

Free BSD

*Copyright (c)  1980,1982,1983,1985,1986,1987,1988,1989,1990, 1991,1992,1993, 1994

    2: "The Regents of the University of California.  All rights reserved.
    3:
    4: *Redistribution and use in source and binary forms, with or without
    5: * modification, are permitted provided that the following conditions
    6: are met:
    7:  1. Redistributions of source code must retain the above copyright
    8:     notice, this list of conditions and the following disclaimer.
    9:  2. Redistributions in binary form must reproduce the above copyright
   10:     notice, this list of conditions and the following disclaimer in the
   11:     documentation and/or other materials provided with the distribution.
   12:  3. All advertising materials mentioning features or use of this software
   13:     must display the following acknowledgement:
   14:     This product includes software developed by the University of
   15:     California, Berkeley and its contributors.
   16:  4. Neither the name of the University nor the names of its contributors
   17:     may be used to endorse or promote products derived from this software
   18:     without specific prior written permission.
   19:
   20:* THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
   21:* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
   22:* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
   23:* ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
   24:* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
   25:* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
   26:* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
   27:* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
   28:* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
   29:* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
   30:* SUCH DAMAGE.

4: /*-
    5:  * Copyright (c) 2000 The NetBSD Foundation, Inc.
    6:  * All rights reserved.
    7:  *
    8:  * This code is derived from software contributed to The NetBSD Foundation
    9:  * by Dieter Baron and Thomas Klausner.
   10:  *
   11:  * Redistribution and use in source and binary forms, with or without
   12:  * modification, are permitted provided that the following conditions
   13:  * are met:
   14:  * 1. Redistributions of source code must retain the above copyright
   15:  *    notice, this list of conditions and the following disclaimer.
   16:  * 2. Redistributions in binary form must reproduce the above copyright
   17:  *    notice, this list of conditions and the following disclaimer in the
   18:  *    documentation and/or other materials provided with the distribution.
   19:  * 3. All advertising materials mentioning features or use of this software
   20:  *    must display the following acknowledgement:
   21:  *        This product includes software developed by the NetBSD
   22:  *        Foundation, Inc. and its contributors.
   23:  * 4. Neither the name of The NetBSD Foundation nor the names of its
   24:  *    contributors may be used to endorse or promote products derived
   25:  *    from this software without specific prior written permission.
   26:  *
   27:  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
   28:  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
   29:  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
   30:  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
   31:  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
   32:  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
   33:  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
   34:  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
   35:  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
   36:  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
   37:  * POSSIBILITY OF SUCH DAMAGE.
   38:  */

    1: /*-
    2:  * Copyright (c) 2001 Mike Barcroft (mike@FreeBSD.org)
    3:  * All rights reserved.
    4:  *
    5:  * Redistribution and use in source and binary forms, with or without
    6:  * modification, are permitted provided that the following conditions
    7:  * are met:
    8:  * 1. Redistributions of source code must retain the above copyright
    9:  *    notice, this list of conditions and the following disclaimer.
   10:  * 2. Redistributions in binary form must reproduce the above copyright
   11:  *    notice, this list of conditions and the following disclaimer in the
   12:  *    documentation and/or other materials provided with the distribution.
   13:  *
   14:  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
   15:  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
   16:  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
   17:  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
   18:  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
   19:  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
   20:  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
   21:  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
   22:  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
   23:  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
   24:  * SUCH DAMAGE.
   25:  *
   26:  * $FreeBSD: src/sys/sys/stdint.h,v 1.4 2002/08/21 16:20:01 mike Exp $
   27:  */

1: /*-
    2:  * Copyright (c) 2002 Thomas Moestl (tmm@FreeBSD.org)
3:  * All rights reserved.
    4:  *
    5:  * Redistribution and use in source and binary forms, with or without
    6:  * modification, are permitted provided that the following conditions
    7:  * are met:
    8:  * 1. Redistributions of source code must retain the above copyright
    9:  *    notice, this list of conditions and the following disclaimer.
   10:  * 2. Redistributions in binary form must reproduce the above copyright
   11:  *    notice, this list of conditions and the following disclaimer in the
   12:  *    documentation and/or other materials provided with the distribution.
   13:  *
   14:  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
   15:  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
   16:  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
   17:  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
   18:  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
   19:  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
   20:  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
   21:  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
   22:  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
   23:  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
   24:  * SUCH DAMAGE.
   25:  *
   26:  * $FreeBSD: src/sys/sys/endian.h,v 1.6 2003/10/15 20:05:57 obrien Exp $
   27:  */
   28:

1: /*-
    2:  * Copyright (c) 1999,2000,2001 Jonathan Lemon (jlemon@FreeBSD.org)
3:  * All rights reserved.
    4:  *
    5:  * Redistribution and use in source and binary forms, with or without
    6:  * modification, are permitted provided that the following conditions
    7:  * are met:
    8:  * 1. Redistributions of source code must retain the above copyright
    9:  *    notice, this list of conditions and the following disclaimer.
   10:  * 2. Redistributions in binary form must reproduce the above copyright
   11:  *    notice, this list of conditions and the following disclaimer in the
   12:  *    documentation and/or other materials provided with the distribution.
   13:  *
   14:  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
   15:  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
   16:  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
   17:  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
   18:  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
   19:  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
   20:  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
   21:  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
   22:  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
   23:  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
   24:  * SUCH DAMAGE.
   25:  *
   26:  * $FreeBSD: src/sys/sys/event.h,v 1.32 2005/07/01 16:28:32 ssouhlal Exp $
   27:  */

1: /*-
    2:  * Copyright (c) 1997 Peter Wemm (peter@freebsd.org)
3:  * All rights reserved.
    4:  *
    5:  * Redistribution and use in source and binary forms, with or without
    6:  * modification, are permitted provided that the following conditions
    7:  * are met:
    8:  * 1. Redistributions of source code must retain the above copyright
    9:  *    notice, this list of conditions and the following disclaimer.
   10:  * 2. Redistributions in binary form must reproduce the above copyright
   11:  *    notice, this list of conditions and the following disclaimer in the
   12:  *    documentation and/or other materials provided with the distribution.
   13:  * 3. The name of the author may not be used to endorse or promote products
   14:  *    derived from this software without specific prior written permission.
   15:  *
   16:  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
   17:  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
   18:  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
   19:  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
   20:  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
   21:  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
   22:  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
   23:  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
   24:  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
   25:  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
   26:  * SUCH DAMAGE.
   27:  *
   28:  * $FreeBSD: src/sys/sys/poll.h,v 1.13 2002/07/10 04:47:25 mike Exp $
   29:  */

1: .\" Copyright (c) 2002 Tim J. Robbins
    2: .\" All rights reserved.
    3: .\"
    4: .\" Redistribution and use in source and binary forms, with or without
    5: .\" modification, are permitted provided that the following conditions
    6: .\" are met:
    7: .\" 1. Redistributions of source code must retain the above copyright
    8: .\"    notice, this list of conditions and the following disclaimer.
    9: .\" 2. Redistributions in binary form must reproduce the above copyright
   10: .\"    notice, this list of conditions and the following disclaimer in the
   11: .\"    documentation and/or other materials provided with the distribution.
   12: .\"
   13: .\" THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
   14: .\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
   15: .\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
   16: .\" ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
   17: .\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
   18: .\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
   19: .\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
   20: .\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
   21: .\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
   22: .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
   23: .\" SUCH DAMAGE.

1: .\" Copyright (c) 1994 SigmaSoft, Th. Lockert (tholo@sigmasoft.com)
2: .\" All rights reserved.
    3: .\"
    4: .\" Redistribution and use in source and binary forms, with or without
    5: .\" modification, are permitted provided that the following conditions
    6: .\" are met:
    7: .\" 1. Redistributions of source code must retain the above copyright
    8: .\"    notice, this list of conditions and the following disclaimer.
    9: .\" 2. Redistributions in binary form must reproduce the above copyright
   10: .\"    notice, this list of conditions and the following disclaimer in the
   11: .\"    documentation and/or other materials provided with the distribution.
   12: .\" 3. The name of the author may not be used to endorse or promote products
   13: .\"    derived from this software without specific prior written permission.
   14: .\"
   15: .\" THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
   16: .\" IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
   17: .\" OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
   18: .\" IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
   19: .\" SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
   20: .\" PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
   21: .\" OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
   22: .\" WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
   23: .\" OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
   24: .\" ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

   2: .\" Copyright (c) 1998 HD Associates, Inc.
    3: .\" All rights reserved.
    4: .\"
    5: .\" Redistribution and use in source and binary forms, with or without
    6: .\" modification, are permitted provided that the following conditions
    7: .\" are met:
    8: .\" 1. Redistributions of source code must retain the above copyright
    9: .\"    notice, this list of conditions and the following disclaimer.
   10: .\" 2. Redistributions in binary form must reproduce the above copyright
   11: .\"    notice, this list of conditions and the following disclaimer in the
   12: .\"    documentation and/or other materials provided with the distribution.
   13: .\"
   14: .\" THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
   15: .\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
   16: .\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
   17: .\" ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
   18: .\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
   19: .\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
   20: .\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
   21: .\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
   22: .\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
   23: .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
   24: .\" SUCH DAMAGE.
   25: .\"

    1: .\" Copyright (c) 2002 William C. Fenner.  All rights reserved.
    2: .\"
    3: .\" Redistribution and use in source and binary forms, with or without
    4: .\" modification, are permitted provided that the following conditions
    5: .\" are met:
    6: .\" 1. Redistributions of source code must retain the above copyright
    7: .\"    notice, this list of conditions and the following disclaimer.
    8: .\" 2. Redistributions in binary form must reproduce the above copyright
    9: .\"    notice, this list of conditions and the following disclaimer in the
   10: .\"    documentation and/or other materials provided with the distribution.
   11: .\"
   12: .\" THIS SOFTWARE IS PROVIDED BY THE CONTRIBUTORS ``AS IS'' AND
   13: .\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
   14: .\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
   15: .\" ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
   16: .\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
   17: .\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
   18: .\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
   19: .\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
   20: .\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
   21: .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
   22: .\" SUCH DAMAGE.

    1: .\" Copyright (c) 2001 Jeroen Ruigrok van der Werven (asmodai@FreeBSD.org)
    2: .\" All rights reserved.
    3: .\"
    4: .\" Redistribution and use in source and binary forms, with or without
    5: .\" modification, are permitted provided that the following conditions
    6: .\" are met:
    7: .\" 1. Redistributions of source code must retain the above copyright
    8: .\"    notice, this list of conditions and the following disclaimer.
    9: .\" 2. Redistributions in binary form must reproduce the above copyright
   10: .\"    notice, this list of conditions and the following disclaimer in the
   11: .\"    documentation and/or other materials provided with the distribution.
   12: .\"
   13: .\" THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
   14: .\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
   15: .\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
   16: .\" ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
   17: .\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
   18: .\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
   19: .\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
   20: .\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
   21: .\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
   22: .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
   23: .\" SUCH DAMAGE.

     3: .\" Copyright (c) 1998 Todd C. Miller (Todd.Miller@courtesan.com)
    4: .\" All rights reserved.
    5: .\"
    6: .\" Redistribution and use in source and binary forms, with or without
    7: .\" modification, are permitted provided that the following conditions
    8: .\" are met:
    9: .\" 1. Redistributions of source code must retain the above copyright
   10: .\"    notice, this list of conditions and the following disclaimer.
   11: .\" 2. Redistributions in binary form must reproduce the above copyright
   12: .\"    notice, this list of conditions and the following disclaimer in the
   13: .\"    documentation and/or other materials provided with the distribution.
   14: .\" 3. The name of the author may not be used to endorse or promote products
   15: .\"    derived from this software without specific prior written permission.
   16: .\"
   17: .\" THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
   18: .\" INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
   19: .\" AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL
   20: .\" THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
   21: .\" EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
   22: .\" PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
   23: .\" OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
   24: .\" WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
   25: .\" OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
   26: .\" ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

    1: .\"
    2: .\" Copyright (c) 1997 Joerg Wunsch
    3: .\"
    4: .\" All rights reserved.
    5: .\"
    6: .\" Redistribution and use in source and binary forms, with or without
    7: .\" modification, are permitted provided that the following conditions
    8: .\" are met:
    9: .\" 1. Redistributions of source code must retain the above copyright
   10: .\"    notice, this list of conditions and the following disclaimer.
   11: .\" 2. Redistributions in binary form must reproduce the above copyright
   12: .\"    notice, this list of conditions and the following disclaimer in the
   13: .\"    documentation and/or other materials provided with the distribution.
   14: .\"
   15: .\" THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY EXPRESS OR
   16: .\" IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
   17: .\" OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
   18: .\" IN NO EVENT SHALL THE DEVELOPERS BE LIABLE FOR ANY DIRECT, INDIRECT,
   19: .\" INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
   20: .\" NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
   21: .\" DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
   22: .\" THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
   23: .\" (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
   24: .\" THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

    1: /*-
    2:  * Copyright (c) 2003 Networks Associates Technology, Inc.
    3:  * All rights reserved.
    4:  *
    5:  * This software was developed for the FreeBSD Project by
    6:  * Jacques A. Vidrine, Safeport Network Services, and Network
    7:  * Associates Laboratories, the Security Research Division of Network
    8:  * Associates, Inc. under DARPA/SPAWAR contract N66001-01-C-8035
    9:  * ("CBOSS"), as part of the DARPA CHATS research program.
   10:  *
   11:  * Redistribution and use in source and binary forms, with or without
   12:  * modification, are permitted provided that the following conditions
   13:  * are met:
   14:  * 1. Redistributions of source code must retain the above copyright
   15:  *    notice, this list of conditions and the following disclaimer.
   16:  * 2. Redistributions in binary form must reproduce the above copyright
   17:  *    notice, this list of conditions and the following disclaimer in the
   18:  *    documentation and/or other materials provided with the distribution.
   19:  *
   20:  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
   21:  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
   22:  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
   23:  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
   24:  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
   25:  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
   26:  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
   27:  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
   28:  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
   29:  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
   30:  * SUCH DAMAGE.

    1: /*
    2:  * Copyright (c) 1998 John Birrell (jb@cimlogic.com.au).
    3:  * All rights reserved.
    4:  *
    5:  * Redistribution and use in source and binary forms, with or without
    6:  * modification, are permitted provided that the following conditions
    7:  * are met:
    8:  * 1. Redistributions of source code must retain the above copyright
    9:  *    notice, this list of conditions and the following disclaimer.
   10:  * 2. Redistributions in binary form must reproduce the above copyright
   11:  *    notice, this list of conditions and the following disclaimer in the
   12:  *    documentation and/or other materials provided with the distribution.
   13:  * 3. All advertising materials mentioning features or use of this software
   14:  *    must display the following acknowledgement:
   15:  *This product includes software developed by John Birrell.
   16:  * 4. Neither the name of the author nor the names of any co-contributors
   17:  *    may be used to endorse or promote products derived from this software
   18:  *    without specific prior written permission.
   19:  *
   20:  * THIS SOFTWARE IS PROVIDED BY JOHN BIRRELL AND CONTRIBUTORS ``AS IS'' AND
   21:  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
   22:  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
   23:  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
   24:  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
   25:  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
   26:  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
   27:  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
   28:  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
   29:  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
   30:  * SUCH DAMAGE.

1: /*
    2:  * Copyright (c) 1993, 1994 by Chris Provenzano, proven@mit.edu
    3:  * Copyright (c) 1995-1998 by John Birrell (jb@cimlogic.com.au)
    4:  * All rights reserved.
    5:  *
    6:  * Redistribution and use in source and binary forms, with or without
    7:  * modification, are permitted provided that the following conditions
    8:  * are met:
    9:  * 1. Redistributions of source code must retain the above copyright
   10:  *    notice, this list of conditions and the following disclaimer.
   11:  * 2. Redistributions in binary form must reproduce the above copyright
   12:  *    notice, this list of conditions and the following disclaimer in the
   13:  *    documentation and/or other materials provided with the distribution.
   14:  * 3. All advertising materials mentioning features or use of this software
   15:  *    must display the following acknowledgement:
   16:  *  This product includes software developed by Chris Provenzano.
   17:  * 4. The name of Chris Provenzano may not be used to endorse or promote
   18:  *  products derived from this software without specific prior written
   19:  *  permission.
   20:  *
   21:  * THIS SOFTWARE IS PROVIDED BY CHRIS PROVENZANO ``AS IS'' AND
   22:  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
   23:  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
   24:  * ARE DISCLAIMED.  IN NO EVENT SHALL CHRIS PROVENZANO BE LIABLE FOR ANY
   25:  * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
   26:  * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
   27:  * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
   28:  * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
   29:  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
   30:  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
   31:  * SUCH DAMAGE.

    1: /*-
    2:  * Copyright (c) 1995 Alex Tatmanjants (alex@elvisti.kiev.ua)
    3:  *at Electronni Visti IA, Kiev, Ukraine.
    4:  *All rights reserved.
    5:  *
    6:  * Redistribution and use in source and binary forms, with or without
    7:  * modification, are permitted provided that the following conditions
    8:  * are met:
    9:  * 1. Redistributions of source code must retain the above copyright
   10:  *    notice, this list of conditions and the following disclaimer.
   11:  * 2. Redistributions in binary form must reproduce the above copyright
   12:  *    notice, this list of conditions and the following disclaimer in the
   13:  *    documentation and/or other materials provided with the distribution.
   14:  *
   15:  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND
   16:  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
   17:  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
   18:  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR BE LIABLE
   19:  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
   20:  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
   21:  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
   22:  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
   23:  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
   24:  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
   25:  * SUCH DAMAGE.
   26:  *
   27:  * $FreeBSD: src/lib/libc/locale/collate.h,v 1.15 2005/02/27 20:31:13 ru Exp $
   28:  */

    1: .\"$KAME: setkey.8,v 1.89 2003/09/07 22:17:41 itojun Exp $
    2: .\"
    3: .\" Copyright (C) 1995, 1996, 1997, 1998, and 1999 WIDE Project.
    4: .\" All rights reserved.
    5: .\"
    6: .\" Redistribution and use in source and binary forms, with or without
    7: .\" modification, are permitted provided that the following conditions
    8: .\" are met:
    9: .\" 1. Redistributions of source code must retain the above copyright
   10: .\"    notice, this list of conditions and the following disclaimer.
   11: .\" 2. Redistributions in binary form must reproduce the above copyright
   12: .\"    notice, this list of conditions and the following disclaimer in the
   13: .\"    documentation and/or other materials provided with the distribution.
   14: .\" 3. Neither the name of the project nor the names of its contributors
   15: .\"    may be used to endorse or promote products derived from this software
   16: .\"    without specific prior written permission.
   17: .\"
   18: .\" THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
   19: .\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
   20: .\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
   21: .\" ARE DISCLAIMED.  IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
   22: .\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
   23: .\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
   24: .\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
   25: .\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
   26: .\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
   27: .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
   28: .\" SUCH DAMAGE.

    1: .\" Copyright (c) 2003, Steven G. Kargl
    2: .\" All rights reserved.
    3: .\"
    4: .\" Redistribution and use in source and binary forms, with or without
    5: .\" modification, are permitted provided that the following conditions
    6: .\" are met:
    7: .\" 1. Redistributions of source code must retain the above copyright
    8: .\"    notice, this list of conditions and the following disclaimer.
    9: .\" 2. Redistributions in binary form must reproduce the above copyright
   10: .\"    notice, this list of conditions and the following disclaimer in the
   11: .\"    documentation and/or other materials provided with the distribution.
   12: .\"
   13: .\" THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
   14: .\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
   15: .\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
   16: .\" ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
   17: .\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
   18: .\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
   19: .\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
   20: .\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
   21: .\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
   22: .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
   23: .\" SUCH DAMAGE.

    1: .\" Copyright (c) 1997 Brian Cully (shmit@kublai.com)
    2: .\" All rights reserved.
    3: .\"
    4: .\" Redistribution and use in source and binary forms, with or without
    5: .\" modification, are permitted provided that the following conditions
    6: .\" are met:
    7: .\" 1. Redistributions of source code must retain the above copyright
    8: .\"    notice, this list of conditions and the following disclaimer.
    9: .\" 2. Redistributions in binary form must reproduce the above copyright
   10: .\"    notice, this list of conditions and the following disclaimer in the
   11: .\"    documentation and/or other materials provided with the distribution.
   12: .\" 3. Neither the name of the author nor the names of any co-contributors
   13: .\"    may be used to endorse or promote products derived from this software
   14: .\"    without specific prior written permission.
   15: .\"
   16: .\" THIS SOFTWARE IS PROVIDED BY JOHN BIRRELL AND CONTRIBUTORS ``AS IS'' AND
   17: .\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
   18: .\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
   19: .\" ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
   20: .\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
   21: .\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
   22: .\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
   23: .\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
   24: .\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
   25: .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
   26: .\" SUCH DAMAGE.

    1: .\" Copyright (c) 2003 Michael Telahun Makonnen
    2: .\" All rights reserved.
    3: .\"
    4: .\" Redistribution and use in source and binary forms, with or without
    5: .\" modification, are permitted provided that the following conditions
    6: .\" are met:
    7: .\" 1. Redistributions of source code must retain the above copyright
    8: .\"    notice, this list of conditions and the following disclaimer.
    9: .\" 2. Redistributions in binary form must reproduce the above copyright
   10: .\"    notice, this list of conditions and the following disclaimer in the
   11: .\"    documentation and/or other materials provided with the distribution.
   12: .\"
   13: .\" THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
   14: .\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
   15: .\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
   16: .\" ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
   17: .\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
   18: .\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
   19: .\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
   20: .\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
   21: .\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
   22: .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
   23: .\" SUCH DAMAGE.
   24: .\"

  3: .\" Copyright (c)2001 Citrus Project,
    4: .\" All rights reserved.
    5: .\"
    6: .\" Redistribution and use in source and binary forms, with or without
    7: .\" modification, are permitted provided that the following conditions
    8: .\" are met:
    9: .\" 1. Redistributions of source code must retain the above copyright
   10: .\"    notice, this list of conditions and the following disclaimer.
   11: .\" 2. Redistributions in binary form must reproduce the above copyright
   12: .\"    notice, this list of conditions and the following disclaimer in the
   13: .\"    documentation and/or other materials provided with the distribution.
   14: .\"
   15: .\" THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
   16: .\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
   17: .\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
   18: .\" ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
   19: .\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
   20: .\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
   21: .\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
   22: .\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
   23: .\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
   24: .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
   25: .\" SUCH DAMAGE.

    1: /*-
    2:  * © Portions copyright (c) 2006 Nokia Corporation.  All rights reserved.
    3:  *
    4:  * Copyright (c) 2001, 2003 Alexey Zelkin (phantom@FreeBSD.org)
    5:  * All rights reserved.
    6:  *
    7:  * Redistribution and use in source and binary forms, with or without
    8:  * modification, are permitted provided that the following conditions
    9:  * are met:
   10:  * 1. Redistributions of source code must retain the above copyright
   11:  *    notice, this list of conditions and the following disclaimer.
   12:  * 2. Redistributions in binary form must reproduce the above copyright
   13:  *    notice, this list of conditions and the following disclaimer in the
   14:  *    documentation and/or other materials provided with the distribution.
   15:  *
   16:  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
   17:  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
   18:  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
   19:  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
   20:  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
   21:  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
   22:  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
   23:  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
   24:  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
   25:  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
   26:  * SUCH DAMAGE.
   27:  */

    1: /*-
    2:  * © Portions copyright (c) 2006 Nokia Corporation.  All rights reserved.
    3:  *
    4:  * Copyright (c) 2000, 2001 Alexey Zelkin (phantom@FreeBSD.org)
    5:  * All rights reserved.
    6:  *
    7:  * Redistribution and use in source and binary forms, with or without
    8:  * modification, are permitted provided that the following conditions
    9:  * are met:
   10:  * 1. Redistributions of source code must retain the above copyright
   11:  *    notice, this list of conditions and the following disclaimer.
   12:  * 2. Redistributions in binary form must reproduce the above copyright
   13:  *    notice, this list of conditions and the following disclaimer in the
   14:  *    documentation and/or other materials provided with the distribution.
   15:  *
   16:  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
   17:  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
   18:  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
   19:  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
   20:  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
   21:  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
   22:  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
   23:  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
   24:  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
   25:  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
   26:  * SUCH DAMAGE.
   27:  *

   1: /*-
    2:  * Copyright (c) 2003 Mike Barcroft (mike@FreeBSD.org)
    3:  * Copyright (c) 2002 David Schultz (das@FreeBSD.ORG)
    4:  * All rights reserved.
    5:  *
    6:  * Redistribution and use in source and binary forms, with or without
    7:  * modification, are permitted provided that the following conditions
    8:  * are met:
    9:  * 1. Redistributions of source code must retain the above copyright
   10:  *    notice, this list of conditions and the following disclaimer.
   11:  * 2. Redistributions in binary form must reproduce the above copyright
   12:  *    notice, this list of conditions and the following disclaimer in the
   13:  *    documentation and/or other materials provided with the distribution.
   14:  *
   15:  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
   16:  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
   17:  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
   18:  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
   19:  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
   20:  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
   21:  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
   22:  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
   23:  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
   24:  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
   25:  * SUCH DAMAGE.

   1: /*-
    2:  * Copyright (c) 2002, 2003 David Schultz (das@FreeBSD.ORG)
    3:  * All rights reserved.
    4:  *
    5:  * Redistribution and use in source and binary forms, with or without
    6:  * modification, are permitted provided that the following conditions
    7:  * are met:
    8:  * 1. Redistributions of source code must retain the above copyright
    9:  *    notice, this list of conditions and the following disclaimer.
   10:  * 2. Redistributions in binary form must reproduce the above copyright
   11:  *    notice, this list of conditions and the following disclaimer in the
   12:  *    documentation and/or other materials provided with the distribution.
   13:  *
   14:  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
   15:  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
   16:  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
   17:  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
   18:  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
   19:  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
   20:  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
   21:  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
   22:  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
   23:  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
   24:  * SUCH DAMAGE.

    5: /*-
    6:  * Copyright (c) 2004-2005 David Schultz (das@FreeBSD.ORG)
    7:  * All rights reserved.
    8:  *
    9:  * Redistribution and use in source and binary forms, with or without
   10:  * modification, are permitted provided that the following conditions
   11:  * are met:
   12:  * 1. Redistributions of source code must retain the above copyright
   13:  *    notice, this list of conditions and the following disclaimer.
   14:  * 2. Redistributions in binary form must reproduce the above copyright
   15:  *    notice, this list of conditions and the following disclaimer in the
   16:  *    documentation and/or other materials provided with the distribution.
   17:  *
   18:  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
   19:  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
   20:  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
   21:  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
   22:  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
   23:  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
   24:  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
   25:  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
   26:  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
   27:  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
   28:  * SUCH DAMAGE.

    1: /*-
    2:  * Copyright (c)1999 Citrus Project,
    3:  * All rights reserved.
    4:  *
    5:  * Redistribution and use in source and binary forms, with or without
    6:  * modification, are permitted provided that the following conditions
    7:  * are met:
    8:  * 1. Redistributions of source code must retain the above copyright
    9:  *    notice, this list of conditions and the following disclaimer.
   10:  * 2. Redistributions in binary form must reproduce the above copyright
   11:  *    notice, this list of conditions and the following disclaimer in the
   12:  *    documentation and/or other materials provided with the distribution.
   13:  *
   14:  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
   15:  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
   16:  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
   17:  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
   18:  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
   19:  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
   20:  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
   21:  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
   22:  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
   23:  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
   24:  * SUCH DAMAGE.

1: /*-
    2:  * Copyright (c) 1997 Berkeley Software Design, Inc. All rights reserved.
    3:  *
    4:  * Redistribution and use in source and binary forms, with or without
    5:  * modification, are permitted provided that the following conditions
    6:  * are met:
    7:  * 1. Redistributions of source code must retain the above copyright
    8:  *    notice, this list of conditions and the following disclaimer.
    9:  * 2. Redistributions in binary form must reproduce the above copyright
   10:  *    notice, this list of conditions and the following disclaimer in the
   11:  *    documentation and/or other materials provided with the distribution.
   12:  * 3. Berkeley Software Design Inc's name may not be used to endorse or
   13:  *    promote products derived from this software without specific prior
   14:  *    written permission.
   15:  *
   16:  * THIS SOFTWARE IS PROVIDED BY BERKELEY SOFTWARE DESIGN INC ``AS IS'' AND
   17:  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
   18:  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
   19:  * ARE DISCLAIMED.  IN NO EVENT SHALL BERKELEY SOFTWARE DESIGN INC BE LIABLE
   20:  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
   21:  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
   22:  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
   23:  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
   24:  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
   25:  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
   26:  * SUCH DAMAGE.

    1: /*-
    2:  * Copyright (c) 2001, 2002 Mike Barcroft (mike@FreeBSD.org)
    3:  * Copyright (c) 2001 The NetBSD Foundation, Inc.
    4:  * All rights reserved.
    5:  *
    6:  * This code is derived from software contributed to The NetBSD Foundation
    7:  * by Klaus Klein.
    8:  *
    9:  * Redistribution and use in source and binary forms, with or without
   10:  * modification, are permitted provided that the following conditions
   11:  * are met:
   12:  * 1. Redistributions of source code must retain the above copyright
   13:  *    notice, this list of conditions and the following disclaimer.
   14:  * 2. Redistributions in binary form must reproduce the above copyright
   15:  *    notice, this list of conditions and the following disclaimer in the
   16:  *    documentation and/or other materials provided with the distribution.
   17:  * 3. All advertising materials mentioning features or use of this software
   18:  *    must display the following acknowledgement:
   19:  *        This product includes software developed by the NetBSD
   20:  *        Foundation, Inc. and its contributors.
   21:  * 4. Neither the name of The NetBSD Foundation nor the names of its
   22:  *    contributors may be used to endorse or promote products derived
   23:  *    from this software without specific prior written permission.
   24:  *
   25:  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
   26:  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
   27:  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
   28:  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
   29:  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
   30:  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
   31:  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
   32:  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
   33:  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
   34:  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
   35:  * POSSIBILITY OF SUCH DAMAGE.
   36:  *
    1: /*-
    2:  * © Portions copyright (c) 2006 Nokia Corporation.  All rights reserved.
    3:  *
    4:  * Copyright (c) 2001 Alexey Zelkin (phantom@FreeBSD.org)
    5:  * All rights reserved.
    6:  *
    7:  * Redistribution and use in source and binary forms, with or without
    8:  * modification, are permitted provided that the following conditions
    9:  * are met:
   10:  * 1. Redistributions of source code must retain the above copyright
   11:  *    notice, this list of conditions and the following disclaimer.
   12:  * 2. Redistributions in binary form must reproduce the above copyright
   13:  *    notice, this list of conditions and the following disclaimer in the
   14:  *    documentation and/or other materials provided with the distribution.
   15:  *
   16:  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
   17:  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
   18:  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
   19:  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
   20:  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
   21:  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
   22:  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
   23:  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
   24:  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
   25:  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
   26:  * SUCH DAMAGE.

    4:  * Copyright (c) 2000, 2001 Alexey Zelkin (phantom@FreeBSD.org)
    5:  * All rights reserved.
    6:  *
    7:  * Redistribution and use in source and binary forms, with or without
    8:  * modification, are permitted provided that the following conditions
    9:  * are met:
   10:  * 1. Redistributions of source code must retain the above copyright
   11:  *    notice, this list of conditions and the following disclaimer.
   12:  * 2. Redistributions in binary form must reproduce the above copyright
   13:  *    notice, this list of conditions and the following disclaimer in the
   14:  *    documentation and/or other materials provided with the distribution.
   15:  *
   16:  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
   17:  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
   18:  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
   19:  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
   20:  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
   21:  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
   22:  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
   23:  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
   24:  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
   25:  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
   26:  * SUCH DAMAGE.

    1: .\" Copyright (C) 2000 Jason Evans (jasone@FreeBSD.org)
    2: .\" All rights reserved.
    3: .\"
    4: .\" Redistribution and use in source and binary forms, with or without
    5: .\" modification, are permitted provided that the following conditions
    6: .\" are met:
    7: .\" 1. Redistributions of source code must retain the above copyright
    8: .\"    notice(s), this list of conditions and the following disclaimer as
    9: .\"    the first lines of this file unmodified other than the possible
   10: .\"    addition of one or more copyright notices.
   11: .\" 2. Redistributions in binary form must reproduce the above copyright
   12: .\"    notice(s), this list of conditions and the following disclaimer in
   13: .\"    the documentation and/or other materials provided with the
   14: .\"    distribution.
   15: .\"
   16: .\" THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER(S) ``AS IS'' AND ANY
   17: .\" EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
   18: .\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
   19: .\" PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT HOLDER(S) BE
   20: .\" LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
   21: .\" CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
   22: .\" SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
   23: .\" BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
   24: .\" WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
   25: .\" OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
   26: .\" EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

3: .\" Copyright (c) 1995 Frank van der Linden
    4: .\" All rights reserved.
    5: .\"
    6: .\" Redistribution and use in source and binary forms, with or without
    7: .\" modification, are permitted provided that the following conditions
    8: .\" are met:
    9: .\" 1. Redistributions of source code must retain the above copyright
   10: .\"    notice, this list of conditions and the following disclaimer.
   11: .\" 2. Redistributions in binary form must reproduce the above copyright
   12: .\"    notice, this list of conditions and the following disclaimer in the
   13: .\"    documentation and/or other materials provided with the distribution.
   14: .\" 3. All advertising materials mentioning features or use of this software
   15: .\"    must display the following acknowledgement:
   16: .\"      This product includes software developed for the NetBSD Project
   17: .\"      by Frank van der Linden
   18: .\" 4. The name of the author may not be used to endorse or promote products
   19: .\"    derived from this software without specific prior written permission
   20: .\"
   21: .\" THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
   22: .\" IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
   23: .\" OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
   24: .\" IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
   25: .\" INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
   26: .\" NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
   27: .\" DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
   28: .\" THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
   29: .\" (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
   30: .\" THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

\" Copyright (c) 1992, 1993, 1994 Henry Spencer.
     2: .\" Copyright (c) 1992, 1993, 1994
     3: .\"The Regents of the University of California.  All rights reserved.
      4: .\"
     5: .\" This code is derived from software contributed to Berkeley by
     6: .\" Henry Spencer.
     7: .\"
     8: .\" Redistribution and use in source and binary forms, with or without
     9: .\" modification, are permitted provided that the following conditions
     10: .\" are met:
    11: .\" 1. Redistributions of source code must retain the above copyright
     12: .\"    notice, this list of conditions and the following disclaimer.
     13: .\" 2. Redistributions in binary form must reproduce the above copyright
    14: .\"    notice, this list of conditions and the following disclaimer in the
    15: .\"    documentation and/or other materials provided with the distribution.
    16: .\" 3. All advertising materials mentioning features or use of this software
    17: .\"    must display the following acknowledgement:
     18: .\"This product includes software developed by the University of
    19: .\"California, Berkeley and its contributors.
     20: .\" 4. Neither the name of the University nor the names of its contributors
     21: .\"    may be used to endorse or promote products derived from this software
     22: .\"    without specific prior written permission.
     23: .\"
    24: .\" THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
    25: .\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     26: .\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
    27: .\" ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
     28: .\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
    29: .\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
    30: .\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
    31: .\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     32: .\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
    33: .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
    34: .\" SUCH DAMAGE.
    35: .\"

    1: /*-
    2:  * Copyright (c) 1996, 1997 HD Associates, Inc.
    3:  *All rights reserved.
    4:  *
    5:  * Redistribution and use in source and binary forms, with or without
    6:  * modification, are permitted provided that the following conditions
    7:  * are met:
    8:  * 1. Redistributions of source code must retain the above copyright
    9:  *    notice, this list of conditions and the following disclaimer.
   10:  * 2. Redistributions in binary form must reproduce the above copyright
   11:  *    notice, this list of conditions and the following disclaimer in the
   12:  *    documentation and/or other materials provided with the distribution.
   13:  * 3. All advertising materials mentioning features or use of this software
   14:  *    must display the following acknowledgement:
   15:  *This product includes software developed by HD Associates, Inc
   16:  *and Jukka Antero Ukkonen.
   17:  * 4. Neither the name of the author nor the names of any co-contributors
   18:  *    may be used to endorse or promote products derived from this software
   19:  *    without specific prior written permission.
   20:  *
   21:  * THIS SOFTWARE IS PROVIDED BY HD ASSOCIATES AND CONTRIBUTORS ``AS IS'' AND
   22:  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
   23:  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
   24:  * ARE DISCLAIMED.  IN NO EVENT SHALL HD ASSOCIATES OR CONTRIBUTORS BE LIABLE
   25:  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
   26:  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
   27:  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
   28:  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
   29:  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
   30:  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
   31:  * SUCH DAMAGE.

    1: .\"
    2: .\" Copyright (c) 1995 David Hovemeyer (daveho@infocom.com)
    3: .\"
    4: .\" All rights reserved.
    5: .\"
    6: .\" Redistribution and use in source and binary forms, with or without
    7: .\" modification, are permitted provided that the following conditions
    8: .\" are met:
    9: .\" 1. Redistributions of source code must retain the above copyright
   10: .\"    notice, this list of conditions and the following disclaimer.
   11: .\" 2. Redistributions in binary form must reproduce the above copyright
   12: .\"    notice, this list of conditions and the following disclaimer in the
   13: .\"    documentation and/or other materials provided with the distribution.
   14: .\"
   15: .\" THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY EXPRESS OR
   16: .\" IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
   17: .\" OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
   18: .\" IN NO EVENT SHALL THE DEVELOPERS BE LIABLE FOR ANY DIRECT, INDIRECT,
   19: .\" INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
   20: .\" NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
   21: .\" DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
   22: .\" THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
   23: .\" (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
   24: .\" THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

1: /*
    2:  * © Portions copyright (c) 2005 Nokia Corporation.  All rights reserved.
    3:  * Copyright (c) 2000 Jeroen Ruigrok van der Werven (asmodai@FreeBSD.org)
    4:  * All rights reserved.
    5:  *
    6:  * Redistribution and use in source and binary forms, with or without
    7:  * modification, are permitted provided that the following conditions
    8:  * are met:
    9:  * 1. Redistributions of source code must retain the above copyright
   10:  *    notice, this list of conditions and the following disclaimer.
   11:  * 2. Redistributions in binary form must reproduce the above copyright
   12:  *    notice, this list of conditions and the following disclaimer in the
   13:  *    documentation and/or other materials provided with the distribution.
   14:  *
   15:  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
   16:  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
   17:  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
   18:  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
   19:  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
   20:  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
   21:  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
   22:  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
   23:  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
   24:  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
   25:  * SUCH DAMAGE.

3: /*
    4:  * Copyright (c) 1997 Todd C. Miller (Todd.Miller@courtesan.com)
    5:  * All rights reserved.
    6:  *
    7:  * Redistribution and use in source and binary forms, with or without
    8:  * modification, are permitted provided that the following conditions
    9:  * are met:
   10:  * 1. Redistributions of source code must retain the above copyright
   11:  *    notice, this list of conditions and the following disclaimer.
   12:  * 2. Redistributions in binary form must reproduce the above copyright
   13:  *    notice, this list of conditions and the following disclaimer in the
   14:  *    documentation and/or other materials provided with the distribution.
   15:  * 3. The name of the author may not be used to endorse or promote products
   16:  *    derived from this software without specific prior written permission.
   17:  *
   18:  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
   19:  * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
   20:  * AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL
   21:  * THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
   22:  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
   23:  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
   24:  * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
   25:  * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
   26:  * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
   27:  * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
   28:  * © Portions copyright (c) 2005-2006  Nokia Corporation.  All rights reserved.
   29:  */

1: /*
    2:  * Copyright (c) 2002 Bob Beck (beck@openbsd.org)
    3:  * Copyright (c) 2002 Theo de Raadt
    4:  * Copyright (c) 2002 Markus Friedl
    5:  * All rights reserved.
    6:  *
    7:  * Redistribution and use in source and binary forms, with or without
    8:  * modification, are permitted provided that the following conditions
    9:  * are met:
   10:  * 1. Redistributions of source code must retain the above copyright
   11:  *    notice, this list of conditions and the following disclaimer.
   12:  * 2. Redistributions in binary form must reproduce the above copyright
   13:  *    notice, this list of conditions and the following disclaimer in the
   14:  *    documentation and/or other materials provided with the distribution.
   15:  *
   16:  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND ANY
   17:  * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
   18:  * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
   19:  * DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ANY
   20:  * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
   21:  * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
   22:  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
   23:  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
   24:  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
   25:  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
   26:  *
   27:  */

    4: /*-
    5:  * Copyright (c) 1997, 1998, 1999 The NetBSD Foundation, Inc.
    6:  * All rights reserved.
    7:  *
    8:  * This code is derived from software contributed to The NetBSD Foundation
    9:  * by Luke Mewburn.
   10:  *
   11:  * Redistribution and use in source and binary forms, with or without
   12:  * modification, are permitted provided that the following conditions
   13:  * are met:
   14:  * 1. Redistributions of source code must retain the above copyright
   15:  *    notice, this list of conditions and the following disclaimer.
   16:  * 2. Redistributions in binary form must reproduce the above copyright
   17:  *    notice, this list of conditions and the following disclaimer in the
   18:  *    documentation and/or other materials provided with the distribution.
   19:  * 3. All advertising materials mentioning features or use of this software
   20:  *    must display the following acknowledgement:
   21:  *        This product includes software developed by the NetBSD
   22:  *        Foundation, Inc. and its contributors.
   23:  * 4. Neither the name of The NetBSD Foundation nor the names of its
   24:  *    contributors may be used to endorse or promote products derived
   25:  *    from this software without specific prior written permission.
   26:  *
   27:  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
   28:  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
   29:  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
   30:  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
   31:  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
   32:  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
   33:  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
   34:  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
   35:  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
   36:  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
   37:  * POSSIBILITY OF SUCH DAMAGE.
   38:  */

   31: /*-
   32:  * Copyright (c) 1999, 2000 The NetBSD Foundation, Inc.
   33:  * All rights reserved.
   34:  *
   35:  * This code is derived from software contributed to The NetBSD Foundation
   36:  * by Julian Coleman.
   37:  *
   38:  * Redistribution and use in source and binary forms, with or without
   39:  * modification, are permitted provided that the following conditions
   40:  * are met:
   41:  * 1. Redistributions of source code must retain the above copyright
   42:  *    notice, this list of conditions and the following disclaimer.
   43:  * 2. Redistributions in binary form must reproduce the above copyright
   44:  *    notice, this list of conditions and the following disclaimer in the
   45:  *    documentation and/or other materials provided with the distribution.
   46:  * 3. All advertising materials mentioning features or use of this software
   47:  *    must display the following acknowledgement:
   48:  *        This product includes software developed by the NetBSD
   49:  *        Foundation, Inc. and its contributors.
   50:  * 4. Neither the name of The NetBSD Foundation nor the names of its
   51:  *    contributors may be used to endorse or promote products derived
   52:  *    from this software without specific prior written permission.
   53:  *
   54:  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
   55:  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
   56:  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
   57:  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
   58:  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
   59:  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
   60:  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
   61:  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
   62:  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
   63:  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
   64:  * POSSIBILITY OF SUCH DAMAGE.

    1: /*-
    2:  * Copyright (c) 1997,98 The NetBSD Foundation, Inc.
    3:  * All rights reserved.
    4:  *
    5:  * This code is derived from software contributed to The NetBSD Foundation
    6:  * by J.T. Conklin.
    7:  *
    8:  * Redistribution and use in source and binary forms, with or without
    9:  * modification, are permitted provided that the following conditions
   10:  * are met:
   11:  * 1. Redistributions of source code must retain the above copyright
   12:  *    notice, this list of conditions and the following disclaimer.
   13:  * 2. Redistributions in binary form must reproduce the above copyright
   14:  *    notice, this list of conditions and the following disclaimer in the
   15:  *    documentation and/or other materials provided with the distribution.
   16:  * 3. All advertising materials mentioning features or use of this software
   17:  *    must display the following acknowledgement:
   18:  *        This product includes software developed by the NetBSD
   19:  *        Foundation, Inc. and its contributors.
   20:  * 4. Neither the name of The NetBSD Foundation nor the names of its
   21:  *    contributors may be used to endorse or promote products derived
   22:  *    from this software without specific prior written permission.
   23:  *
   24:  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
   25:  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
   26:  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
   27:  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
   28:  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
   29:  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
   30:  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
   31:  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
   32:  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
   33:  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
   34:  * POSSIBILITY OF SUCH DAMAGE.

    1: /*-
    2:  * Copyright (c) 2003 Marcel Moolenaar
    3:  * All rights reserved.
    4:  *
    5:  * Redistribution and use in source and binary forms, with or without
    6:  * modification, are permitted provided that the following conditions
    7:  * are met:
    8:  *
    9:  * 1. Redistributions of source code must retain the above copyright
   10:  *    notice, this list of conditions and the following disclaimer.
   11:  * 2. Redistributions in binary form must reproduce the above copyright
   12:  *    notice, this list of conditions and the following disclaimer in the
   13:  *    documentation and/or other materials provided with the distribution.
   14:  *
   15:  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
   16:  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
   17:  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
   18:  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
   19:  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
   20:  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
   21:  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
   22:  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
   23:  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
   24:  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
   25:  *
   26:  * $FreeBSD: src/sys/sys/_null.h,v 1.7 2005/01/07 02:29:23 imp Exp $
   27:  */

1: /*-
    2:  * Copyright (c) 2004 Poul-Henning Kamp
    3:  * All rights reserved.
    4:  *
    5:  * Redistribution and use in source and binary forms, with or without
    6:  * modification, are permitted provided that the following conditions
    7:  * are met:
    8:  * 1. Redistributions of source code must retain the above copyright
    9:  *    notice, this list of conditions and the following disclaimer.
   10:  * 2. Redistributions in binary form must reproduce the above copyright
   11:  *    notice, this list of conditions and the following disclaimer in the
   12:  *    documentation and/or other materials provided with the distribution.
   13:  *
   14:  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
   15:  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
   16:  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
   17:  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
   18:  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
   19:  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
   20:  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
   21:  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
   22:  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
   23:  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
   24:  * SUCH DAMAGE.
   25:  *
   26:  * This file contains definitions which pertain to serial ports as such,
   27:  * (both async and sync), but which do not necessarily have anything to
   28:  * do with tty processing.
   29:  *
   30:  * $FreeBSD: src/sys/sys/serial.h,v 1.2 2004/06/25 10:56:43 phk Exp $
   31:  */

1: /*-
    2:  * © Portions copyright (c) 2005-2006 Nokia Corporation.
    3:  * All rights reserved.
    4:  *
    5:  * Copyright (c) 2003 Poul-Henning Kamp
    6:  * All rights reserved.
    7:  *
    8:  * Redistribution and use in source and binary forms, with or without
    9:  * modification, are permitted provided that the following conditions
   10:  * are met:
   11:  * 1. Redistributions of source code must retain the above copyright
   12:  *    notice, this list of conditions and the following disclaimer.
   13:  * 2. Redistributions in binary form must reproduce the above copyright
   14:  *    notice, this list of conditions and the following disclaimer in the
   15:  *    documentation and/or other materials provided with the distribution.
   16:  *
   17:  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
   18:  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
   19:  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
   20:  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
   21:  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
   22:  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
   23:  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
   24:  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
   25:  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
   26:  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
   27:  * SUCH DAMAGE.
   28:  */

   1: /*
    2:  * Copyright (c) 2001 Daniel Eischen (deischen@FreeBSD.org).
    3:  * All rights reserved.
    4:  * © Portions copyright (c) 2006 Symbian Software Ltd. All rights reserved.
    5:  *
    6:  * Redistribution and use in source and binary forms, with or without
    7:  * modification, are permitted provided that the following conditions
    8:  * are met:
    9:  * 1. Redistributions of source code must retain the above copyright
   10:  *    notice, this list of conditions and the following disclaimer.
   11:  * 2. Redistributions in binary form must reproduce the above copyright
   12:  *    notice, this list of conditions and the following disclaimer in the
   13:  *    documentation and/or other materials provided with the distribution.
   14:  *
   15:  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
   16:  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
   17:  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
   18:  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
   19:  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
   20:  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
   21:  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
   22:  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
   23:  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
   24:  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
   25:  * SUCH DAMAGE.

    1: /*-
    2:  * Copyright (C) 2005 The FreeBSD Project.  All rights reserved.
    3:  *
    4:  * Redistribution and use in source and binary forms, with or without
    5:  * modification, are permitted provided that the following conditions
    6:  * are met:
    7:  * 1. Redistributions of source code must retain the above copyright
    8:  *    notice, this list of conditions and the following disclaimer.
    9:  * 2. Redistributions in binary form must reproduce the above copyright
   10:  *    notice, this list of conditions and the following disclaimer in the
   11:  *    documentation and/or other materials provided with the distribution.
   12:  *
   13:  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
   14:  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
   15:  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
   16:  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
   17:  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
   18:  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
   19:  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
   20:  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
   21:  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
   22:  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
   23:  * SUCH DAMAGE.
   24:  *
   25:  * $FreeBSD: src/lib/libc/net/netdb_private.h,v 1.9 2005/05/15 20:15:15 ume Exp $
   26:  */

Open SSL

2: /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
    3:  * All rights reserved.
    4:  *
    5:  * This package is an SSL implementation written
    6:  * by Eric Young (eay@cryptsoft.com).
    7:  * The implementation was written so as to conform with Netscapes SSL.
    8:  *
    9:  * This library is free for commercial and non-commercial use as long as
   10:  * the following conditions are aheared to.  The following conditions
   11:  * apply to all code found in this distribution, be it the RC4, RSA,
   12:  * lhash, DES, etc., code; not just the SSL code.  The SSL documentation
   13:  * included with this distribution is covered by the same copyright terms
   14:  * except that the holder is Tim Hudson (tjh@cryptsoft.com).
   15:  *
   16:  * Copyright remains Eric Young's, and as such any Copyright notices in
   17:  * the code are not to be removed.
   18:  * If this package is used in a product, Eric Young should be given attribution
   19:  * as the author of the parts of the library used.
   20:  * This can be in the form of a textual message at program startup or
   21:  * in documentation (online or textual) provided with the package.
   22:  *
   23:  * Redistribution and use in source and binary forms, with or without
   24:  * modification, are permitted provided that the following conditions
   25:  * are met:
   26:  * 1. Redistributions of source code must retain the copyright
   27:  *    notice, this list of conditions and the following disclaimer.
   28:  * 2. Redistributions in binary form must reproduce the above copyright
   29:  *    notice, this list of conditions and the following disclaimer in the
   30:  *    documentation and/or other materials provided with the distribution.
   31:  * 3. All advertising materials mentioning features or use of this software
   32:  *    must display the following acknowledgement:
   33:  *    "This product includes cryptographic software written by
   34:  *     Eric Young (eay@cryptsoft.com)"
   35:  *    The word 'cryptographic' can be left out if the rouines from the library
   36:  *    being used are not cryptographic related :-).
   37:  * 4. If you include any Windows specific code (or a derivative thereof) from
   38:  *    the apps directory (application code) you must include an acknowledgement:
   39:  *    "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
   40:  *
   41:  * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
   42:  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
   43:  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
   44:  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
   45:  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
   46:  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
   47:  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
   48:  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
   49:  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
   50:  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
   51:  * SUCH DAMAGE.
   52:  *
   53:  * The licence and distribution terms for any publically available version or
   54:  * derivative of this code cannot be changed.  i.e. this code cannot simply be
   55:  * copied and put under another distribution licence
   56:  * [including the GNU Public Licence.]
   57:  */

    2: /* Copyright (C) 1995-1997 Eric Young (eay@cryptsoft.com)
    3:  * All rights reserved.
    4:  *
    5:  * This package is an SSL implementation written
    6:  * by Eric Young (eay@cryptsoft.com).
    7:  * The implementation was written so as to conform with Netscapes SSL.
    8:  *
    9:  * This library is free for commercial and non-commercial use as long as
   10:  * the following conditions are aheared to.  The following conditions
   11:  * apply to all code found in this distribution, be it the RC4, RSA,
   12:  * lhash, DES, etc., code; not just the SSL code.  The SSL documentation
   13:  * included with this distribution is covered by the same copyright terms
   14:  * except that the holder is Tim Hudson (tjh@cryptsoft.com).
   15:  *
   16:  * Copyright remains Eric Young's, and as such any Copyright notices in
   17:  * the code are not to be removed.
   18:  * If this package is used in a product, Eric Young should be given attribution
   19:  * as the author of the parts of the library used.
   20:  * This can be in the form of a textual message at program startup or
   21:  * in documentation (online or textual) provided with the package.
   22:  *
   23:  * Redistribution and use in source and binary forms, with or without
   24:  * modification, are permitted provided that the following conditions
   25:  * are met:
   26:  * 1. Redistributions of source code must retain the copyright
   27:  *    notice, this list of conditions and the following disclaimer.
   28:  * 2. Redistributions in binary form must reproduce the above copyright
   29:  *    notice, this list of conditions and the following disclaimer in the
   30:  *    documentation and/or other materials provided with the distribution.
   31:  * 3. All advertising materials mentioning features or use of this software
   32:  *    must display the following acknowledgement:
   33:  *    "This product includes cryptographic software written by
   34:  *     Eric Young (eay@cryptsoft.com)"
   35:  *    The word 'cryptographic' can be left out if the rouines from the library
   36:  *    being used are not cryptographic related :-).
   37:  * 4. If you include any Windows specific code (or a derivative thereof) from
   38:  *    the apps directory (application code) you must include an acknowledgement:
   39:  *    "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
   40:  *
   41:  * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
   42:  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
   43:  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
   44:  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
   45:  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
   46:  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
   47:  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
   48:  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
   49:  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
   50:  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
   51:  * SUCH DAMAGE.
   52:  *
   53:  * The licence and distribution terms for any publically available version or
   54:  * derivative of this code cannot be changed.  i.e. this code cannot simply be
   55:  * copied and put under another distribution licence
   56:  * [including the GNU Public Licence.]
   57:  */

1: /* $LP: LPlib/source/LPdir_unix.c,v 1.11 2004/09/23 22:07:22 _cvs_levitte Exp $ */
     2: /*
     3:  * Copyright (c) 2004, Richard Levitte (richard@levitte.org)
     4:  * All rights reserved.
     5:  *
     6:  * Redistribution and use in source and binary forms, with or without
     7:  * modification, are permitted provided that the following conditions
     8:  * are met:
     9:  * 1. Redistributions of source code must retain the above copyright
     10:  *    notice, this list of conditions and the following disclaimer.
     11:  * 2. Redistributions in binary form must reproduce the above copyright
     12:  *    notice, this list of conditions and the following disclaimer in the
     13:  *    documentation and/or other materials provided with the distribution.
     14:  *
     15:  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
     16:  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
     17:  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
     18:  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
     19:  * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
     20:  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
     21:  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
     22:  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
     23:  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
     24:  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
     25:  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
     26:  */
     27:  /*

2: /* ====================================================================
    3:  * Copyright (c) 1998-2002 The OpenSSL Project.  All rights reserved.
    4:  *
    5:  * Redistribution and use in source and binary forms, with or without
    6:  * modification, are permitted provided that the following conditions
    7:  * are met:
    8:  *
    9:  * 1. Redistributions of source code must retain the above copyright
   10:  *    notice, this list of conditions and the following disclaimer.
   11:  *
   12:  * 2. Redistributions in binary form must reproduce the above copyright
   13:  *    notice, this list of conditions and the following disclaimer in
   14:  *    the documentation and/or other materials provided with the
   15:  *    distribution.
   16:  *
   17:  * 3. All advertising materials mentioning features or use of this
   18:  *    software must display the following acknowledgment:
   19:  *    "This product includes software developed by the OpenSSL Project
   20:  *    for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
   21:  *
   22:  * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
   23:  *    endorse or promote products derived from this software without
   24:  *    prior written permission. For written permission, please contact
   25:  *    openssl-core@openssl.org.
   26:  *
   27:  * 5. Products derived from this software may not be called "OpenSSL"
   28:  *    nor may "OpenSSL" appear in their names without prior written
   29:  *    permission of the OpenSSL Project.
   30:  *
   31:  * 6. Redistributions of any form whatsoever must retain the following
   32:  *    acknowledgment:
   33:  *    "This product includes software developed by the OpenSSL Project
   34:  *    for use in the OpenSSL Toolkit (http://www.openssl.org/)"
   35:  *
   36:  * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
   37:  * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
   38:  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
   39:  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenSSL PROJECT OR
   40:  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
   41:  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
   42:  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
   43:  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
   44:  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
   45:  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
   46:  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
   47:  * OF THE POSSIBILITY OF SUCH DAMAGE.
   48:  * ====================================================================

    5: /* ====================================================================
    6:  * Copyright (c) 2000 The OpenSSL Project.  All rights reserved.
    7:  *
    8:  * Redistribution and use in source and binary forms, with or without
    9:  * modification, are permitted provided that the following conditions
   10:  * are met:
   11:  *
   12:  * 1. Redistributions of source code must retain the above copyright
   13:  *    notice, this list of conditions and the following disclaimer.
   14:  *
   15:  * 2. Redistributions in binary form must reproduce the above copyright
   16:  *    notice, this list of conditions and the following disclaimer in
   17:  *    the documentation and/or other materials provided with the
   18:  *    distribution.
   19:  *
   20:  * 3. All advertising materials mentioning features or use of this
   21:  *    software must display the following acknowledgment:
   22:  *    "This product includes software developed by the OpenSSL Project
   23:  *    for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)"
   24:  *
   25:  * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
   26:  *    endorse or promote products derived from this software without
   27:  *    prior written permission. For written permission, please contact
   28:  *    licensing@OpenSSL.org.
   29:  *
   30:  * 5. Products derived from this software may not be called "OpenSSL"
   31:  *    nor may "OpenSSL" appear in their names without prior written
   32:  *    permission of the OpenSSL Project.
   33:  *
   34:  * 6. Redistributions of any form whatsoever must retain the following
   35:  *    acknowledgment:
   36:  *    "This product includes software developed by the OpenSSL Project
   37:  *    for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)"
   38:  *
   39:  * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
   40:  * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
   41:  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
   42:  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenSSL PROJECT OR
   43:  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
   44:  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
   45:  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
   46:  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
   47:  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
   48:  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
   49:  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
   50:  * OF THE POSSIBILITY OF SUCH DAMAGE.
   51:  * ====================================================================

    2: /* ====================================================================
    3:  * Copyright (c) 1998-2003 The OpenSSL Project.  All rights reserved.
    4:  *
    5:  * Redistribution and use in source and binary forms, with or without
    6:  * modification, are permitted provided that the following conditions
    7:  * are met:
    8:  *
    9:  * 1. Redistributions of source code must retain the above copyright
   10:  *    notice, this list of conditions and the following disclaimer.
   11:  *
   12:  * 2. Redistributions in binary form must reproduce the above copyright
   13:  *    notice, this list of conditions and the following disclaimer in
   14:  *    the documentation and/or other materials provided with the
   15:  *    distribution.
   16:  *
   17:  * 3. All advertising materials mentioning features or use of this
   18:  *    software must display the following acknowledgment:
   19:  *    "This product includes software developed by the OpenSSL Project
   20:  *    for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
   21:  *
   22:  * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
   23:  *    endorse or promote products derived from this software without
   24:  *    prior written permission. For written permission, please contact
   25:  *    openssl-core@openssl.org.
   26:  *
   27:  * 5. Products derived from this software may not be called "OpenSSL"
   28:  *    nor may "OpenSSL" appear in their names without prior written
   29:  *    permission of the OpenSSL Project.
   30:  *
   31:  * 6. Redistributions of any form whatsoever must retain the following
   32:  *    acknowledgment:
   33:  *    "This product includes software developed by the OpenSSL Project
   34:  *    for use in the OpenSSL Toolkit (http://www.openssl.org/)"
   35:  *
   36:  * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
   37:  * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
   38:  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
   39:  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenSSL PROJECT OR
   40:  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
   41:  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
   42:  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
   43:  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
   44:  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
   45:  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
   46:  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
   47:  * OF THE POSSIBILITY OF SUCH DAMAGE.
   48:  * ====================================================================

    5: /* ====================================================================
    6:  * Copyright (c) 1999-2004 The OpenSSL Project.  All rights reserved.
    7:  *
    8:  * Redistribution and use in source and binary forms, with or without
    9:  * modification, are permitted provided that the following conditions
   10:  * are met:
   11:  *
   12:  * 1. Redistributions of source code must retain the above copyright
   13:  *    notice, this list of conditions and the following disclaimer.
   14:  *
   15:  * 2. Redistributions in binary form must reproduce the above copyright
   16:  *    notice, this list of conditions and the following disclaimer in
   17:  *    the documentation and/or other materials provided with the
   18:  *    distribution.
   19:  *
   20:  * 3. All advertising materials mentioning features or use of this
   21:  *    software must display the following acknowledgment:
   22:  *    "This product includes software developed by the OpenSSL Project
   23:  *    for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)"
   24:  *
   25:  * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
   26:  *    endorse or promote products derived from this software without
   27:  *    prior written permission. For written permission, please contact
   28:  *    licensing@OpenSSL.org.
   29:  *
   30:  * 5. Products derived from this software may not be called "OpenSSL"
   31:  *    nor may "OpenSSL" appear in their names without prior written
   32:  *    permission of the OpenSSL Project.
   33:  *
   34:  * 6. Redistributions of any form whatsoever must retain the following
   35:  *    acknowledgment:
   36:  *    "This product includes software developed by the OpenSSL Project
   37:  *    for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)"
   38:  *
   39:  * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
   40:  * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
   41:  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
   42:  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenSSL PROJECT OR
   43:  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
   44:  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
   45:  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
   46:  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
   47:  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
   48:  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
   49:  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
   50:  * OF THE POSSIBILITY OF SUCH DAMAGE.

    5: /* ====================================================================
    6:  * Copyright (c) 2000 The OpenSSL Project.  All rights reserved.
    7:  *
    8:  * Redistribution and use in source and binary forms, with or without
    9:  * modification, are permitted provided that the following conditions
   10:  * are met:
   11:  *
   12:  * 1. Redistributions of source code must retain the above copyright
   13:  *    notice, this list of conditions and the following disclaimer.
   14:  *
   15:  * 2. Redistributions in binary form must reproduce the above copyright
   16:  *    notice, this list of conditions and the following disclaimer in
   17:  *    the documentation and/or other materials provided with the
   18:  *    distribution.
   19:  *
   20:  * 3. All advertising materials mentioning features or use of this
   21:  *    software must display the following acknowledgment:
   22:  *    "This product includes software developed by the OpenSSL Project
   23:  *    for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)"
   24:  *
   25:  * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
   26:  *    endorse or promote products derived from this software without
   27:  *    prior written permission. For written permission, please contact
   28:  *    licensing@OpenSSL.org.
   29:  *
   30:  * 5. Products derived from this software may not be called "OpenSSL"
   31:  *    nor may "OpenSSL" appear in their names without prior written
   32:  *    permission of the OpenSSL Project.
   33:  *
   34:  * 6. Redistributions of any form whatsoever must retain the following
   35:  *    acknowledgment:
   36:  *    "This product includes software developed by the OpenSSL Project
   37:  *    for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)"
   38:  *
   39:  * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
   40:  * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
   41:  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
   42:  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenSSL PROJECT OR
   43:  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
   44:  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
   45:  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
   46:  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
   47:  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
   48:  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
   49:  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
   50:  * OF THE POSSIBILITY OF SUCH DAMAGE.

    1: /* ====================================================================
    2:  * Copyright (c) 1998-2001 The OpenSSL Project.  All rights reserved.
    3:  *
    4:  * Redistribution and use in source and binary forms, with or without
    5:  * modification, are permitted provided that the following conditions
    6:  * are met:
    7:  *
    8:  * 1. Redistributions of source code must retain the above copyright
    9:  *    notice, this list of conditions and the following disclaimer.
   10:  *
   11:  * 2. Redistributions in binary form must reproduce the above copyright
   12:  *    notice, this list of conditions and the following disclaimer in
   13:  *    the documentation and/or other materials provided with the
   14:  *    distribution.
   15:  *
   16:  * 3. All advertising materials mentioning features or use of this
   17:  *    software must display the following acknowledgment:
   18:  *    "This product includes software developed by the OpenSSL Project
   19:  *    for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
   20:  *
   21:  * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
   22:  *    endorse or promote products derived from this software without
   23:  *    prior written permission. For written permission, please contact
   24:  *    openssl-core@openssl.org.
   25:  *
   26:  * 5. Products derived from this software may not be called "OpenSSL"
   27:  *    nor may "OpenSSL" appear in their names without prior written
   28:  *    permission of the OpenSSL Project.
   29:  *
   30:  * 6. Redistributions of any form whatsoever must retain the following
   31:  *    acknowledgment:
   32:  *    "This product includes software developed by the OpenSSL Project
   33:  *    for use in the OpenSSL Toolkit (http://www.openssl.org/)"
   34:  *
   35:  * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
   36:  * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
   37:  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
   38:  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenSSL PROJECT OR
   39:  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
   40:  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
   41:  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
   42:  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
   43:  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
   44:  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
   45:  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
   46:  * OF THE POSSIBILITY OF SUCH DAMAGE.

    5: /* ====================================================================
    6:  * Copyright (c) 1999 The OpenSSL Project.  All rights reserved.
    7:  *
    8:  * Redistribution and use in source and binary forms, with or without
    9:  * modification, are permitted provided that the following conditions
   10:  * are met:
   11:  *
   12:  * 1. Redistributions of source code must retain the above copyright
   13:  *    notice, this list of conditions and the following disclaimer.
   14:  *
   15:  * 2. Redistributions in binary form must reproduce the above copyright
   16:  *    notice, this list of conditions and the following disclaimer in
   17:  *    the documentation and/or other materials provided with the
   18:  *    distribution.
   19:  *
   20:  * 3. All advertising materials mentioning features or use of this
   21:  *    software must display the following acknowledgment:
   22:  *    "This product includes software developed by the OpenSSL Project
   23:  *    for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)"
   24:  *
   25:  * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
   26:  *    endorse or promote products derived from this software without
   27:  *    prior written permission. For written permission, please contact
   28:  *    licensing@OpenSSL.org.
   29:  *
   30:  * 5. Products derived from this software may not be called "OpenSSL"
   31:  *    nor may "OpenSSL" appear in their names without prior written
   32:  *    permission of the OpenSSL Project.
   33:  *
   34:  * 6. Redistributions of any form whatsoever must retain the following
   35:  *    acknowledgment:
   36:  *    "This product includes software developed by the OpenSSL Project
   37:  *    for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)"
   38:  *
   39:  * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
   40:  * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
   41:  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
   42:  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenSSL PROJECT OR
   43:  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
   44:  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
   45:  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
   46:  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
   47:  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
   48:  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
   49:  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
   50:  * OF THE POSSIBILITY OF SUCH DAMAGE.
   51:  * ====================================================================

    5:  */
    6: /* ====================================================================
    7:  * Copyright (c) 1999-2005 The OpenSSL Project.  All rights reserved.
    8:  *
    9:  * Redistribution and use in source and binary forms, with or without
   10:  * modification, are permitted provided that the following conditions
   11:  * are met:
   12:  *
   13:  * 1. Redistributions of source code must retain the above copyright
   14:  *    notice, this list of conditions and the following disclaimer.
   15:  *
   16:  * 2. Redistributions in binary form must reproduce the above copyright
   17:  *    notice, this list of conditions and the following disclaimer in
   18:  *    the documentation and/or other materials provided with the
   19:  *    distribution.
   20:  *
   21:  * 3. All advertising materials mentioning features or use of this
   22:  *    software must display the following acknowledgment:
   23:  *    "This product includes software developed by the OpenSSL Project
   24:  *    for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)"
   25:  *
   26:  * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
   27:  *    endorse or promote products derived from this software without
   28:  *    prior written permission. For written permission, please contact
   29:  *    openssl-core@OpenSSL.org.
   30:  *
   31:  * 5. Products derived from this software may not be called "OpenSSL"
   32:  *    nor may "OpenSSL" appear in their names without prior written
   33:  *    permission of the OpenSSL Project.
   34:  *
   35:  * 6. Redistributions of any form whatsoever must retain the following
   36:  *    acknowledgment:
   37:  *    "This product includes software developed by the OpenSSL Project
   38:  *    for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)"
   39:  *
   40:  * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
   41:  * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
   42:  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
   43:  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenSSL PROJECT OR
   44:  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
   45:  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
   46:  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
   47:  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
   48:  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
   49:  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
   50:  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
   51:  * OF THE POSSIBILITY OF SUCH DAMAGE.

Zlib

    1: /*--------------------------------------------------------------------
    2:    (c) Portions copyright (c) 2005-2006 Nokia Corporation.  All rights reserved.
    3:  *--------------------------------------------------------------------*/
    4: /* zlib.h -- interface of the 'zlib' general purpose compression library
    5:   version 1.2.3, July 18th, 2005
    6:
    7:   Copyright (C) 1995-2005 Jean-loup Gailly and Mark Adler
    8:
    9:   This software is provided 'as-is', without any express or implied
   10:   warranty.  In no event will the authors be held liable for any damages
   11:   arising from the use of this software.
   12:
   13:   Permission is granted to anyone to use this software for any purpose,
   14:   including commercial applications, and to alter it and redistribute it
   15:   freely, subject to the following restrictions:
   16:
   17:   1. The origin of this software must not be misrepresented; you must not
   18:      claim that you wrote the original software. If you use this software
   19:      in a product, an acknowledgment in the product documentation would be
   20:      appreciated but is not required.
   21:   2. Altered source versions must be plainly marked as such, and must not be
   22:      misrepresented as being the original software.
   23:   3. This notice may not be removed or altered from any source distribution.
   24:
   25:   Jean-loup Gailly        Mark Adler
   26:   jloup@gzip.org          madler@alumni.caltech.edu

Glib

    1: /* GBSearchArray - Binary Searchable Array implementation
    2:  * Copyright (C) 2000-2003 Tim Janik
    3:  *
    4:  * This software is provided "as is"; redistribution and modification
    5:  * is permitted, provided that the following disclaimer is retained.
    6:  *
    7:  * This software is distributed in the hope that it will be useful,
    8:  * but WITHOUT ANY WARRANTY; without even the implied warranty of
    9:  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
   10:  * In no event shall the authors or contributors be liable for any
   11:  * direct, indirect, incidental, special, exemplary, or consequential
   12:  * damages (including, but not limited to, procurement of substitute
   13:  * goods or services; loss of use, data, or profits; or business
   14:  * interruption) however caused and on any theory of liability, whether
   15:  * in contract, strict liability, or tort (including negligence or
   16:  * otherwise) arising in any way out of the use of this software, even
   17:  * if advised of the possibility of such damage.
   18:  */

©

Back to top

This material, including documentation and any related computer programs, is protected by copyright controlled by Nokia. All rights are reserved. Copying, including reproducing, storing, adapting or translating, any or all of this material requires the prior written consent of Nokia. This material also contains confidential information, which may not be disclosed to others without the prior written consent of Nokia.

Nokia is a registered trademark of Nokia Corporation. S60 and logo is a trademark of Nokia Corporation. Java and all Java-based marks are trademarks or registered trademarks of Sun Microsystems, Inc. Other company and product names mentioned herein may be trademarks or tradenames of their respective owners.


_exit

Name

_exit - terminate the curent process

Library

 libc.lib

Synopsis
#include <unistd.h>
void _exit (int status);

Return values

 The _exit system call can never return.

Detailed description

 The _exit system call terminates a process with the following consequences:
  • All of the descriptors open in the calling process are closed. This may entail delays, for example, waiting for output to drain; a process in this state may not be killed, as it is already dying.
  • If the parent process of the calling process has an outstanding wait call, it is notified of the calling process’s termination and the status is set as defined by wait.
  • The parent process-ID of all of the calling process’s existing child processes are set to 1; the initialization process inherits each of these processes

As the function _exit terminates the calling process instantly, the value status is returned as the process’ exit status to it’s parent process. Most C programs call the library routine exit, which flushes buffers, closes streams, unlinks temporary files, etc., before calling _exit.

Examples

#include <unistd.h>

int main( void )
{
   _exit( 1 );
   return 0;
}

Errors

 No errors are defined.

Limitations

 The signal related functionalities are not applicable to the symbian implementation as there is no support for signals from symbian.

See also

 wait, exit

Feedback

For additional information or queries on this page send feedback


abort

Name

abort - causes abnormal program termination

Library

 libc.lib

Synopsis
#include <stdlib.h>
void abort (void);

Return values

 The abort function never returns.

Detailed description

 The abort function causes abnormal program termination to occur, unless the signal SIGABRT is being caught and the signal handler does not return.

Any open streams are flushed and closed.

Examples

#include  <stdio.h>
#include  <stdlib.h>

int main( void )
{
   FILE *stream;

   if( (stream = fopen( "notexist.file", "r" )) == NULL )
   {
      perror( "Error occurred while opening file" );
      abort();
   }
   else
      fclose( stream );
   return 0;
}

Output

Error occurred while opening file: No such file or directory

Implementation notes

 The abort function is thread-safe. It is unknown if it is async-cancel-safe.

Errors

 No errors are defined.

Limitations

 The signal related functionalities are not applicable to the symbian implementation as there is no support for signals from symbian.

See also

 exit

Feedback

For additional information or queries on this page send feedback


abs

Name

abs - computes the absolute value of an integer

Library

 libc.lib

Synopsis
#include <stdlib.h>
int abs (int j);

Return values

 The abs function returns the absolute value.

Detailed description

 The abs function computes the absolute value of the integer j.

Examples

#include  <stdio.h>
#include  <stdlib.h>

int main( void )
{
   int    ix = -4, iy;
   long   lx = -41567L, ly;
   long long llx = -5343546758, lly;

   iy = abs( ix );
   printf( "The absolute value of %d is %d\n", ix, iy);

   ly = labs( lx );
   printf( "The absolute value of %ld is %ld\n", lx, ly);

   lly = llabs( llx );
   printf( "The absolute value of %lld is %lld\n", llx, lly );

   return 0;
}

Output

The absolute value of -4 is 4
The absolute value of -41567 is 41567
The absolute value of -5343546758 is 5343546758

Errors

 No errors are defined.

See also

 fabs, floor, hypot, labs, llabs, math

Feedback

For additional information or queries on this page send feedback


accept

Name

accept - accepts a connection on a socket

Library

 libc.lib

Synopsis
#include <sys/types.h>
#include <sys/socket.h>
int accept (int s, struct sockaddr * restrict addr, socklen_t * restrict addrlen);

Detailed description

 The argument s is a socket that has been created with socket bound to an address with bind and is listening for connections after a listen The accept system call extracts the first connection request on the queue of pending connections, creates a new socket, and allocates a new file descriptor for the socket which inherits the state of the O_NONBLOCK property from the original socket s.

If no pending connections are present on the queue, and the original socket is not marked as non-blocking, accept blocks the caller until a connection is present. If the original socket is marked non-blocking and no pending connections are present on the queue, accept returns an error as described below. The accepted socket may not be used to accept more connections. The original socket s remains open.

The argument addr is a result argument that is filled-in with the address of the connecting entity, as known to the communications layer. The exact format of the addr argument is determined by the domain in which the communication is occurring. A null pointer may be specified for addr if the address information is not desired; in this case, addrlen is not used and should also be null. Otherwise, the addrlen argument is a value-result argument; it should initially contain the amount of space pointed to by addr; on return it will contain the actual length (in bytes) of the address returned. This call is used with connection-based socket types, currently with SOCK_STREAM.

It is possible to select a socket for the purposes of doing an accept by selecting it for read.

For certain protocols which require an explicit confirmation, such as ISO or DATAKIT, accept can be thought of as merely dequeueing the next connection request and not implying confirmation. Confirmation can be implied by a normal read or write on the new file descriptor, and rejection can be implied by closing the new socket.

Examples

#include <sys/socket.h>
#include <netinet/in.h>
#include <unistd.h>
void GetSockName()
{
   int sock_fd;
   int newsock_fd;
   struct sockaddr_in addr;
   struct sockaddr_in ss;
   struct sockaddr_in new_socket;
   unsigned int len;
   unsigned int addr_len;

   sock_fd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);

   addr.sin_family = AF_INET;
   addr.sin_addr.s_addr = htonl(INADDR_ANY);
   addr.sin_port = htons(5000);
   bind(sock_fd,(sockaddr*)&addr,sizeof(addr));
   listen(sock_fd,1);
   newsock_fd = accept(sock_fd,(sockaddr*)&new_socket,&addr_len); // Code blocks here
   if (newsock_fd <= 0)
   {
                perror("accept:");
   }
   close(newsock_fd);
   close(sock_fd);
}

Return values

 The call returns -1 on error. If it succeeds, it returns a non-negative integer that is a descriptor for the accepted socket.

Errors

 The accept system call 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 has not been called on the socket descriptor. The addrlen argument is invalid.
[EWOULDBLOCK]
 | The socket is marked non-blocking and no connections are present to be accepted.
[ECONNABORTED]
 | A connection arrived, but it was closed while waiting on the listen queue.

See also

 bind, connect, getpeername, listen, select, socket
The accept system call appeared in BSD 4.2 .

Feedback

For additional information or queries on this page send feedback


access

Name

access - checks user's permissions for a file

Library

 libc.lib

Synopsis
#include <unistd.h>
int access (const char *path, int mode);

Return values

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

Detailed description

 The access system calls check the accessibility of the file named by the path argument for the access permissions indicated by the mode argument. The value of mode is either the bitwise-inclusive OR of the access permissions to be checked (R_OK for read permission, W_OK for write permission, and X_OK for execute/search permission), or the existence test (F_OK.)

For additional information, see the File Access Permission section of intro . X_OK, the file may not actually have execute permission bits set. Likewise for R_OK and W_OK.

Note that as execute-bit for file is not supported hence access system call for X_OK is undefined.

Examples

/**
 * Detailed description: This sample code checks read-ok accessibility of file Example.c
 *
 * Precondtions: Example.txt file should be present in working directory.
**/
#include <unistd.h>
int main()
{
  if(access("Example.c" ,R_OK)  < 0)
  {
    printf("Read operation on the file is not permitted \n") ;
    return -1 ;
  }
  printf("Read operation permitted on Example.c file \n") ;
  return 0 ;
}

Output

Read operation permitted on Example.c file

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 entire path name exceeded 1023 characters (Not supported).
[ENOENT]
 | The named file does not exist.
[ELOOP]
 | Too many symbolic links were encountered in translating the pathname (Not supported).
[EROFS]
 | Write access is requested for a file on a read-only file system (Not supported).
[ETXTBSY]
 | Write access is requested for a pure procedure (shared text) file presently being executed(Not supported).
[EACCES]
 | Permission bits of the file mode do not permit the requested access, or search permission is denied on a component of the path prefix.
[EFAULT]
 | The path argument points outside the process’s allocated address space (Not supported)
[EIO] |
An I/O error occurred while reading from or writing to the file system(Not supported)

See also

 chmod, stat

Feedback

For additional information or queries on this page send feedback


acos

Name

acos, acosf, acosl
- arc cosine function

Library

 libm.lib

Synopsis
#include <math.h>
double acos (double x);
float acosf (float x);
long double acosl (long double x);

Return values

 The acos, acosf, and acosl functions return the arc cosine in the range [0, pi] radians. If:

| x | > 1,

acos (x);
returns an NaN.

Detailed description

The acos, acosf, and acosl functions compute the principal value of the arc cosine of x.

Examples

#include <math.h>
int main( )
{
   double x = -1;
   double y = acos( x );
   printf( "acos(%f) = %f\n", x, y );
   y = acosf( x );
   printf( "acosf(%f) = %f\n", x, y );
   y = acosl( x );
   printf( "acosl(%f) = %f\n", x, y );
}

Output

acos( -1.000000 ) = 3.14159
acosf(-1.000000 ) = 3.14159
acosl(-1.000000 ) = 3.14159

See also

 asin, atan, atan2, cos, cosh, math, sin, sinh, tan, tanh

Feedback

For additional information or queries on this page send feedback


. acosh

Name

acosh, acoshf, acoshl
- inverse hyperbolic cosine function

Library

 libm.lib

Synopsis
#include <math.h>
double acosh (double x);
float acoshf (float x);
long double acoshl (long double x);

Return values

 The acosh, acoshf, and acoshl functions return the inverse hyperbolic cosine of x. If the argument is less than 1, acosh returns an NaN.

Detailed description

 The acosh and acoshf functions compute the inverse hyperbolic cosine of the real argument x. The function acoshl is an alias to the function acosh.

Examples

#include <math.h>
int main( )
{
   double x = 1;
   double y = acosh( x );
   printf( "acosh(%f) = %f\n", x, y );
   y = acoshf( x );
   printf( "acoshf(%f) = %f\n", x, y );
   y = acoshl( x );
   printf( "acoshl(%f) = %f\n", x, y );
}

Output

acosh( 1.000000 ) = 0.0
acoshf(1.000000 ) = 0.0
acoshl(1.000000 ) = 0.0

See also

 asinh, atanh, exp, math

Feedback

For additional information or queries on this page send feedback


adjtime

Name

adjtime - correct the time to allow synchronization of the system clock

Library

 libc.lib

Synopsis
#include <sys/time.h>
int adjtime (const struct timeval *delta, struct timeval *olddelta);

Return values

 A successful call will return 0 while a failure will return -1

Detailed description

 The adjtime system call makes small adjustments to the system time, as returned by gettimeofday advancing it by the time specified by the timeval delta. If delta is negative, the clock is still incremented by the positive of delta until the correction is complete. Thus, the time is always a monotonically increasing function. A time correction from an earlier call to adjtime may not be finished when adjtime is called again. If olddelta is not a null pointer, the structure pointed to will contain, upon return, the number of microseconds still to be corrected from the earlier call.In case of success we always set the values to 0

This call may be used by time servers that synchronize the clock.

Examples

#include <sys/time.h>
#include <stdio.h>
int main()
{
        //Fill the input struct with 100 microseconds
        const struct timeval delta = {0, 100};
        struct timeval  olddelta;
        int retval;
        retval = adjtime (&delta, &olddelta); //Call adjtime
        printf("adjtime returned %d",retval);
        return 0;
}

Output

adjtime returned 0

Errors

 The adjtime system call will fail if:
[EFAULT]
The *delta or *olddelta argument was an invalid address

See also

 gettimeofday

Feedback

For additional information or queries on this page send feedback


adler32

Name

adler32 — computes a running Adler-32 checksum.

Library

Libz.lib

Synopsis

#include <zlib.h>

uLong adler32(uLong adler, const Bytef * buf, uInt len);

Return Value

The adler32() function returns the new checksum value.

Detailed Description

The adler32() function computes a running Adler-32 checksum. On entry, adler is the previous value of the checksum, and buf points to an array of len bytes of data, to be added to this checksum. The adler32() function will return the new checksum.

If buf is NULL (or Z_NULL), adler32() returns the initial checksum.

Examples

To compute Adler-32 checksum of 1234:

#include <stdio.h>
#include <zlib.h>

void Adler( )
{
    unsigned char  buffer[5]="1234";
    unsigned int i=4;
    unsigned long j=0L;
    long adler_init = adler32(j,0, 0);
    long adler = adler32(adler_init, &buffer[0], i);
    printf("adler checksum value is %x",adler);
}

Output

adler checksum value is 01f800cb.

Errors

None defined.

Feedback

For additional information or queries on this page send feedback

© 2005-2006 Nokia

back to top


Alphabetical Index for non-implemented APIs

Index for non-implemented APIs

libc - Character Type Functions | environ | setitimer | csinf
 | erand48 | setrlimit | csinh
__ctype_b_loc | err | setrlimit64 | csinhf
__ctype_get_mb_cur_max | error | statvfs | csinhl
__ctype_tolower_loc | errx | stime | csinl
__ctype_toupper_loc | fcvt | sync | csqrt
_tolower | fmtmsg | times | csqrtf
_toupper | fnmatch | ulimit | csqrtl
isascii | ftw | vfork | ctan
toascii | gcvt | wait4 | ctanf
 | getdate |  | ctanh
libc - Language Support | getdate_err | libc - System Database Interface | ctanhf
 | getlogin |  | ctanhl
__libc_start_main | getlogin_r | endprotoent | ctanl
__register_atfork | getopt_long_only | endutent | dreml
 | getsubopt | endutxent | erfcl
libc - Large File Support | glob | getgrouplist | erfl
 | glob64 | getprotoent | expl
__fxstat64 | globfree | getutent | expm1l
__lxstat64 | globfree64 | getutent_r | feclearexcept
__xstat64 | grantpt | getutxent | fegetenv
creat64 | hcreate | getutxid | fegetexceptflag
fgetpos64 | hdestroy | getutxline | fegetround
fopen64 | hsearch | pututxline | feholdexcept
freopen64 | imaxabs | setprotoent | feraiseexcept
fseeko64 | imaxdiv | setutent | fesetenv
fsetpos64 | inet_addr | setutxent | fesetexceptflag
fstatvfs64 | inet_ntoa | utmpname | fesetround
ftello64 | inet_ntop |  | fetestexcept
ftruncate64 | inet_pton | libc - Terminal Interface Functions | feupdateenv
ftw64 | insque |  | finitel
getrlimit64 | isblank | cfgetispeed | floorl
lockf64 | jrand48 | cfgetospeed | fmal
mkstemp64 | l64a | cfmakeraw | fminl
mmap64 | lcong48 | cfsetispeed | fmodl
nftw64 | lfind | cfsetospeed | frexpl
readdir64 | lrand48 | cfsetspeed | gammal
statvfs64 | lsearch | tcdrain | hypotl
tmpfile64 | makecontext | tcflow | j0l
truncate64 | memmem | tcflush | j1l
 | mktemp | tcgetattr | jnl
libc - Localization Functions | mrand48 | tcgetpgrp | ldexpf
 | nftw | tcgetsid | ldexpl
bind_textdomain_codeset | nrand48 | tcsendbreak | lgammal
bindtextdomain | ntohl | tcsetattr | lgammal_r
catclose | ntohs | tcsetpgrp | llrintl
catgets | openlog |  | llroundl
catopen | optarg | libc - Time Manipulation | log10l
dcgettext | opterr |  | log1pl
dcngettext | optind | __daylight | log2
dgettext | optopt | __timezone | log2f
dngettext | posix_memalign | __tzname | log2l
duplocale | posix_openpt | daylight | logbl
freelocale | ptsname | timezone | logl
gettext | rand_r | ualarm | lrintl
newlocale | remque |  | lroundl
gettext | seed48 | libc - Wide Characters | matherr
textdomain | sethostname | __wcstod_internal | modfl
uselocale | setlogmask | __wcstof_internal | nanl
_nl_msg_cat_cntr | srand48 | __wcstol_internal | nearbyintl
 | swapcontext | __wcstold_internal | nextafterl
libc - Signal Handling | syslog | __wcstoul_internal | nexttoward
 | tdelete |  | nexttowardl
__libc_current_sigrtmax | tfind | libdl | pow10
__libc_current_sigrtmin | tsearch |  | pow10f
__sigsetjmp | ttyname | diladdr | pow10l
__sysv_signal | ttyname_r |  | powl
bsd_signal | twalk | libm | remainderl
psignal | unlockpt |  | remquol
raise | verrx | __finite | rintl
sigaddset | vfscanf | __finitel | roundl
sigaltstack | vsyslog | __fpclassify | scalbl
sigandset | warn | acoshl | scalbnl
sigdelset | warnx | asinhl | significandl
sigfillset | wordexp | asinl | sincos
sighold | wordfree | atan2l | sincosf
sigignore |  | atanhl | sincosl
siginterrupt | libc - String Functions | atanl | sinhl
sigisemptyset | __mempcpy | cabs | sinl
sigismember | __rawmemchr | cabsf | sqrtl
siglongjmp | __stpcpy | cabsl | tanhl
signal | __strdup | cacos | tanl
sigpause | __strtod_internal | cacosf | tgamma
sigorset | __strtof_internal | cacosh | tgammaf
sigpending | __strtok_r | cacoshf | tgammal
sigprocmask | __strtol_internal | cacoshl | trunc
sigqueue | __strtold_internal | cacosl | y0l
sigrelse | __strtoll_internal | carg | y1l
sigreturn | __strtoul_internal | cargf | ynl
sigset | __strtoull_internal | cargl |
sigsuspend | memrchr | casin | libpthread
sigtimedwait | stpncpy | casinf |
sigwait | strsignal | casinh | pthread_attr_getinheritsched
sigwaitinfo |  | casinhf | pthread_attr_setinheritsched
_sys_siglist | libc - System Calls | casinhl | pthread_setschedprio
 |  | casinl | _pthread_cleanup_push
 | __fxstat | catan | pthread_attr_getstack
 | __getpgid | catanf | pthread_attr_getstackaddr
libc - Socket Interface | __xmknod | catanh | pthread_attr_setguardsize
 | acct | catanhf | pthread_attr_setstack
gethostid | alarm | catanhl | pthread_attr_setstackaddr
socketpair | chroot | catanl | pthread_cancel
 | execl | cbrtl | pthread_cond_broadcast
libc - Standard I/O | execle | ccos | pthread_condattr_getpshared
 | execlp | ccosf | pthread_condattr_setpshared
_IO_feof | execv | ccosh | pthread_getconcurrency
_IO_getc | execve | ccoshf | pthread_getspecific
_IO_putc | execvp | ccoshl | pthread_kill
_IO_puts | fchown | ccosl | pthread_rwlock_d
ctermid | flock | ceill | pthread_rwlock_i
fflush_unlocked | fork | cexp | pthread_rwlock_r
fseeko | fstatvfs | cexpf | pthread_rwlock_timedrdlock
ftello | ftime | cexpl | pthread_rwlock_timedwrlock
vdprintf | getitimer | cimag | pthread_rwlock_tryrdlock
stderr | getloadavg | cimagf | pthread_rwlock_trywrlock
stdin | getrlimit | cimagl | pthread_rwlock_unlock
stdout | getrusage | clog | pthread_rwlock_wrlock
 | getsid | clog10 | pthread_rwlockattr_destroy
libc - Standard Library | getuid | clog10f | pthread_rwlockattr_getpshared
 | getwd | clog10l | pthread_rwlockattr_init
__assert_fail | kill | clogf | pthread_rwlockattr_setpshared
__cxa_atexit | killpg | clogl | pthread_setcancelstate
__errno_location | lockf | conj | pthread_setcanceltype
__fpending | mlock | conjf | pthread_setconcurrency
__getpagesize | mlockall | conjl | pthread_sigmask
__sysconf | munlock | coshl | pthread_testcancel
_environ | munlockall | cosl | lseek64
_longjmp | pause | cpow | open64
_setjmp | poll | cpowf | pread
_sys_errlist | readdir_r | cpowl | pread64
basename | sbrk | cproj | pwrite
closelog | sched_getparam | cprojf | pwrite64
cuserid | sched_getscheduler | cprojl | thread_cancel
daemon | sched_rr_get_interval | creal | thread_cleanup_pop
dirname | sched_setparam | crealf | thread_cleanup_push
drand48 | sched_setscheduler | creall | thread_setcanceltype
ecvt | setcontext | csin | thread_setcancelstate
 |  |  | thread_testcancel

See Also

Libraries Supported in Open Environment


alphasort

Name

scandir, alphasort
- scan a directory

Library

 libc.lib

Synopsis
#include <sys/types.h>
#include <dirent.h>
int scandir (const char *dirname, struct dirent ***namelist, int \*(lp*select\*(rp\*(lpstruct dirent *\*(rp, int \*(lp*compar\*(rp\*(lpconst void *, const void *\*(rp);
int alphasort (const void *d1, const void *d2);

Detailed description

 The scandir function reads the directory dirname and builds an array of pointers to directory entries using malloc It returns the number of entries in the array. A pointer to the array of directory entries is stored in the location referenced by namelist.

The select argument is a pointer to a user supplied subroutine which is called by scandir to select which entries are to be included in the array. The select routine is passed a pointer to a directory entry and should return a non-zero value if the directory entry is to be included in the array. If select is null, then all the directory entries will be included.

The compar argument is a pointer to a user supplied subroutine which is passed to qsort to sort the completed array. If this pointer is null, the array is not sorted.

The alphasort function is a routine which can be used for the compar argument to sort the array alphabetically.

The memory allocated for the array can be deallocated with free, by freeing each pointer in the array and then the array itself.

Diagnostics

 Returns -1 if the directory cannot be opened for reading or if malloc cannot allocate enough memory to hold all the data structures.

See also

 directory, malloc, qsort, dir
The scandir and alphasort functions appeared in BSD 4.2.

Feedback

For additional information or queries on this page send feedback


asin

Name

asin, asinf, asinl
- arc sine function

Library

 libm.lib

Synopsis
#include <math.h>
double asin (double x);
float asinf (float x);
long double asinl (long double x);

Return values

 The asin, asinf, and asinl functions return the arc sine in the range -words [-pi/2, +pi/2] radians. If:

| x | > 1

asin (x);
returns an NaN.

Detailed description

 The asin and asinf functions compute the principal value of the arc sine of x. The function asinl is an alias to the function asin. A domain error occurs for arguments not in the range [-1, +1].

Examples

#include <math.h>
int main( )
{
   double x = 0.5;
   double y = asin( x );
   printf( "asin(%f) = %f\n", x, y );
   y = asinf( x );
   printf( "asinf(%f) = %f\n", x, y );
   y = asinl( x );
   printf( "asinl(%f) = %f\n", x, y );
}

Output

asin( 0.500000 ) = 0.523599
asinf(0.500000 ) = 0.523599
asinl(0.500000 ) = 0.523599

See also

 acos, atan, atan2, cos, cosh, math, sin, sinh, tan, tanh

Feedback

For additional information or queries on this page send feedback


asinh

Name

asinh, asinhf, asinhl
- inverse hyperbolic sine functions

Library

 libm.lib

Synopsis
#include <math.h>
double asinh (double x);
float asinhf (float x);
long double asinh (long double x);

Return values

 The asinh, asinhf, and asinhl functions return the inverse hyperbolic sine of x.

Detailed description

 The asinh, asinhf, and asinhl functions compute the inverse hyperbolic sine of the real argument x. The function asinhl is an alias to the function asinh.

Examples

#include <math.h>
int main( )
{
   double x = 0.75;
   double y = asinh( x );
   printf( "asinh(%f) = %f\n", x, y );
   y = asinhf( x );
   printf( "asinhf(%f) = %f\n", x, y );
   y = asinhl( x );
   printf( "asinhl(%f) = %f\n", x, y );
}

Output

asinh( 0.750000 ) = 0.6931471
asinhf(0.750000 ) = 0.6931471
asinhl(0.750000 ) = 0.6931471

See also

 acosh, atanh, exp, math

Feedback

For additional information or queries on this page send feedback


ASN1_generate_v3 - ASN1 generation functions

Name

ASN1_generate_nconf, ASN1_generate_v3 — ASN1 generation functions

Library

libcrypto.lib

Synopsis

ASN1_TYPE *ASN1_generate_nconf(char *str, CONF *nconf);
ASN1_TYPE *ASN1_generate_v3(char *str, X509V3_CTX *cnf);

Detailed Description

These functions generate the ASN1 encoding of a string in an ASN1_TYPE structure.

str contains the string to encode nconf or cnf contains the optional configuration information where additional strings will be read from. nconf will typically come from a config file whereas cnf is obtained from an X509V3_CTX structure which will typically be used by X509 v3 certificate extension functions. cnf or nconf can be set to NULL if no additional configuration will be used.

Examples

A simple IA5String:
 IA5STRING:Hello World

An IA5String explicitly tagged:

 EXPLICIT:0,IA5STRING:Hello World

An IA5String explicitly tagged using APPLICATION tagging:

 EXPLICIT:0A,IA5STRING:Hello World

A more complex example using a config file to produce a SEQUENCE consisting of a BOOL an OID and a UTF8String:

asn1 = SEQUENCE:seq_section

[seq_section]

field1 = BOOLEAN:TRUE
field2 = OID:commonName
field3 = UTF8:Third field

This example produces an RSAPrivateKey structure, this is the key contained in the file client.pem in all OpenSSL distributions (note: the field names such as 'coeff' are ignored and are present just for clarity):

 asn1=SEQUENCE:private_key
 [private_key]
 version=INTEGER:0
 n=INTEGER:0xBB6FE79432CC6EA2D8F970675A5A87BFBE1AFF0BE63E879F2AFFB93644\
 D4D2C6D000430DEC66ABF47829E74B8C5108623A1C0EE8BE217B3AD8D36D5EB4FCA1D9
 e=INTEGER:0x010001
 d=INTEGER:0x6F05EAD2F27FFAEC84BEC360C4B928FD5F3A9865D0FCAAD291E2A52F4A\
 F810DC6373278C006A0ABBA27DC8C63BF97F7E666E27C5284D7D3B1FFFE16B7A87B51D
 p=INTEGER:0xF3929B9435608F8A22C208D86795271D54EBDFB09DDEF539AB083DA912\
 D4BD57
 q=INTEGER:0xC50016F89DFF2561347ED1186A46E150E28BF2D0F539A1594BBD7FE467\
 46EC4F
 exp1=INTEGER:0x9E7D4326C924AFC1DEA40B45650134966D6F9DFA3A7F9D698CD4ABEA\
 9C0A39B9
 exp2=INTEGER:0xBA84003BB95355AFB7C50DF140C60513D0BA51D637272E355E397779\
 E7B2458F
 coeff=INTEGER:0x30B9E4F2AFA5AC679F920FC83F1F2DF1BAF1779CF989447FABC2F5\
 628657053A

This example is the corresponding public key in a SubjectPublicKeyInfo structure:

 # Start with a SEQUENCE
 asn1=SEQUENCE:pubkeyinfo
 # pubkeyinfo contains an algorithm identifier and the public key wrapped
 # in a BIT STRING
 [pubkeyinfo]
 algorithm=SEQUENCE:rsa_alg
 pubkey=BITWRAP,SEQUENCE:rsapubkey
 # algorithm ID for RSA is just an OID and a NULL
 [rsa_alg]
 algorithm=OID:rsaEncryption
 parameter=NULL
 # Actual public key: modulus and exponent
 [rsapubkey]
 n=INTEGER:0xBB6FE79432CC6EA2D8F970675A5A87BFBE1AFF0BE63E879F2AFFB93644\
 D4D2C6D000430DEC66ABF47829E74B8C5108623A1C0EE8BE217B3AD8D36D5EB4FCA1D9
 e=INTEGER:0x010001

Generation String Format

The actual data encoded is determined by the string str and the configuration information. The general format of the string is:

 B<[modifier,]type[:value]>

That is zero or more comma separated modifiers followed by a type followed by an optional colon and a value. The formats of type, value and modifier are explained below.

Supported Types

The supported types are listed below. Unless otherwise specified only the ASCII format is permissible.

BOOLEAN, BOOL
This encodes a boolean type. The value string is mandatory and should be TRUE or FALSE. Additionally TRUE, true, Y, y, YES, yes, FALSE, false, N, n, NO and no are acceptable.

NULL
Encode the NULL type, the value string must not be present.

INTEGER, INT
Encodes an ASN1 INTEGER type. The value string represents the value of the integer, it can be preceded by a minus sign and is normally interpreted as a decimal value unless the prefix 0x is included.

ENUMERATED, ENUM
Encodes the ASN1 ENUMERATED type, it is otherwise identical to INTEGER.

OBJECT, OID
Encodes an ASN1 OBJECT IDENTIFIER, the value string can be a short name, a long name or numerical format.

UTCTIME, UTC
Encodes an ASN1 UTCTime structure, the value should be in the format YYMMDDHHMMSSZ.

GENERALIZEDTIME, GENTIME
Encodes an ASN1 GeneralizedTime structure, the value should be in the format YYYYMMDDHHMMSSZ.

OCTETSTRING, OCT
Encodes an ASN1 OCTET STRING. value represents the contents of this structure, the format strings ASCII and HEX can be used to specify the format of value.

BITSRING, BITSTR
Encodes an ASN1 BIT STRING. value represents the contents of this structure, the format strings ASCII, HEX and BITLIST can be used to specify the format of value.

If the format is anything other than BITLIST the number of unused bits is set to zero.

UNIVERSALSTRING, UNIV, IA5, IA5STRING, UTF8, UTF8String, BMP, BMPSTRING, VISIBLESTRING, VISIBLE, PRINTABLESTRING, PRINTABLE, T61, T61STRING, TELETEXSTRING, GeneralString
These encode the corresponding string types. value represents the contents of this structure. The format can be ASCII or UTF8.

SEQUENCE, SEQ, SET
Formats the result as an ASN1 SEQUENCE or SET type. value should be a section name which will contain the contents. The field names in the section are ignored and the values are in the generated string format. If value is absent then an empty SEQUENCE will be encoded.

Modifiers

Modifiers affect the following structure, they can be used to add EXPLICIT or IMPLICIT tagging, add wrappers or to change the string format of the final type and value. The supported formats are documented below.

EXPLICIT, EXP
Add an explicit tag to the following structure. This string should be followed by a colon and the tag value to use as a decimal value.

By following the number with U, A, P or C UNIVERSAL, APPLICATION, PRIVATE or CONTEXT SPECIFIC tagging can be used, the default is CONTEXT SPECIFIC.

IMPLICIT, IMP
This is the same as EXPLICIT except IMPLICIT tagging is used instead.

OCTWRAP, SEQWRAP, SETWRAP, BITWRAP
The following structure is surrounded by an OCTET STRING, a SEQUENCE, a SET or a BIT STRING respectively. For a BIT STRING the number of unused bits is set to zero.

FORMAT
This specifies the format of the ultimate value. It should be followed by a colon and one of the strings ASCII, UTF8, HEX or BITLIST.

If no format specifier is included then ASCII is used. If UTF8 is specified then the value string must be a valid UTF8 string. For HEX the output must be a set of hex digits. BITLIST (which is only valid for a BIT STRING) is a comma separated list of set bits.

Return Values

ASN1_generate_nconf() and ASN1_generate_v3() return the encoded data as an ASN1_TYPE structure or NULL if an error occurred.

The error codes that can be obtained by ERR_get_error().

See Also

ERR_get_error()

History

ASN1_generate_nconf() and ASN1_generate_v3() were added to OpenSSL 0.9.8

Feedback

For additional information or queries on this page send feedback


ASN1_OBJECT_free, - object allocation functions

Name

ASN1_OBJECT_new, ASN1_OBJECT_free — object allocation functions

Library

libcrypto.lib

Synopsis

ASN1_OBJECT *ASN1_OBJECT_new(void);
void ASN1_OBJECT_free(ASN1_OBJECT *a);

Detailed Description

The ASN1_OBJECT allocation routines, allocate and free an ASN1_OBJECT structure, which represents an ASN1 OBJECT IDENTIFIER.

ASN1_OBJECT_new() allocates and initializes a ASN1_OBJECT structure.

ASN1_OBJECT_free() frees up the ASN1_OBJECT structure a.

Notes

Although ASN1_OBJECT_new() allocates a new ASN1_OBJECT structure it is almost never used in applications. The ASN1 object utility functions such as OBJ_nid2obj() are used instead.

Return Values

If the allocation fails, ASN1_OBJECT_new() returns NULL and sets an error code that can be obtained by ERR_get_error(). Otherwise it returns a pointer to the newly allocated structure.

ASN1_OBJECT_free() returns no value.

See Also

ERR_get_error(), d2i_ASN1_OBJECT()

History

ASN1_OBJECT_new() and ASN1_OBJECT_free() are available in all versions of SSLeay and OpenSSL.

Feedback

For additional information or queries on this page send feedback


ASN1_STRING_data - ASN1_STRING utility functions

Name

ASN1_STRING_dup, ASN1_STRING_cmp
ASN1_STRING_set, ASN1_STRING_length
ASN1_STRING_length_set, ASN1_STRING_type
ASN1_STRING_data

ASN1_STRING utility functions

Library

libcrypto.lib

Synopsis

int ASN1_STRING_length(ASN1_STRING *x);
unsigned char * ASN1_STRING_data(ASN1_STRING *x);
ASN1_STRING * ASN1_STRING_dup(ASN1_STRING *a);
int ASN1_STRING_cmp(ASN1_STRING *a, ASN1_STRING *b);
int ASN1_STRING_set(ASN1_STRING *str, const void *data, int len);
int ASN1_STRING_type(ASN1_STRING *x);
int ASN1_STRING_to_UTF8(unsigned char **out, ASN1_STRING *in);

Detailed Description

These functions allow an ASN1_STRING structure to be manipulated.

ASN1_STRING_length() returns the length of the content of x.

ASN1_STRING_data() returns an internal pointer to the data of x. Since this is an internal pointer it should not be freed or modified in any way.

ASN1_STRING_dup() returns a copy of the structure a.

ASN1_STRING_cmp() compares a and b returning 0 if the two are identical. The string types and content are compared.

ASN1_STRING_set() sets the data of string str to the buffer data or length len. The supplied data is copied. If len is -1 then the length is determined by strlen(data).

ASN1_STRING_type() returns the type of x, using standard constants such as V_ASN1_OCTET_STRING.

ASN1_STRING_to_UTF8() converts the string in to UTF8 format, the converted data is allocated in a buffer in *out. The length of out is returned or a negative error code. The buffer *out should be free using OPENSSL_free().

Notes

Almost all ASN1 types in OpenSSL are represented as an ASN1_STRING structure. Other types such as ASN1_OCTET_STRING are simply typedefed to ASN1_STRING and the functions call the ASN1_STRING equivalents. ASN1_STRING is also used for some CHOICE types which consist entirely of primitive string types such as DirectoryString and Time.

These functions should not be used to examine or modify ASN1_INTEGER or ASN1_ENUMERATED types: the relevant INTEGER or ENUMERATED utility functions should be used instead.

In general it cannot be assumed that the data returned by ASN1_STRING_data() is null terminated or does not contain embedded nulls. The actual format of the data will depend on the actual string type itself: for example for and IA5String the data will be ASCII, for a BMPString two bytes per character in big endian format, UTF8String will be in UTF8 format.

Similar care should be take to ensure the data is in the correct format when calling ASN1_STRING_set().

Return Values

See Also

ERR_get_error()

History

Feedback

For additional information or queries on this page send feedback


ASN1_STRING_free - ASN1_STRING allocation functions

Name

ASN1_STRING_new, ASN1_STRING_type_new
ASN1_STRING_free

ASN1_STRING allocation functions

Library

libcrypto.lib

Synopsis

ASN1_STRING * ASN1_STRING_new(void);
ASN1_STRING * ASN1_STRING_type_new(int type);
void ASN1_STRING_free(ASN1_STRING *a);

Detailed Description

ASN1_STRING_new() returns an allocated ASN1_STRING structure. Its type is undefined.

ASN1_STRING_type_new() returns an allocated ASN1_STRING structure of type type.

ASN1_STRING_free() frees up a.

Notes

Other string types call the ASN1_STRING functions. For example ASN1_OCTET_STRING_new() calls ASN1_STRING_type(V_ASN1_OCTET_STRING).

Return Values

ASN1_STRING_new() and ASN1_STRING_type_new() return a valid ASN1_STRING structure or NULL if an error occurred.

ASN1_STRING_free() does not return a value.

See Also

ERR_get_error()

History

TBA

Feedback

For additional information or queries on this page send feedback


ASN1_STRING_print_ex_fp - ASN1_STRING output routines.

Name

ASN1_STRING_print_ex, ASN1_STRING_print_ex_fp — ASN1_STRING output routines

Library

libcrypto.lib

Synopsis

#include <openssl/asn1.h>
int ASN1_STRING_print_ex(BIO *out, ASN1_STRING *str, unsigned long flags);
int ASN1_STRING_print_ex_fp(FILE *fp, ASN1_STRING *str, unsigned long flags);
int ASN1_STRING_print(BIO *out, ASN1_STRING *str);

Detailed Description

These functions output an ASN1_STRING structure. ASN1_STRING is used to represent all the ASN1 string types.

ASN1_STRING_print_ex() outputs str to out, the format is determined by the options flags. ASN1_STRING_print_ex_fp() is identical except it outputs to fp instead.

ASN1_STRING_print() prints str to out but using a different format to ASN1_STRING_print_ex(). It replaces unprintable characters (other than CR, LF) with '.'.

Notes

ASN1_STRING_print() is a legacy function which should be avoided in new applications.

Although there are a large number of options frequently ASN1_STRFLGS_RFC2253 is suitable, or on UTF8 terminals ASN1_STRFLGS_RFC2253 & ~ASN1_STRFLGS_ESC_MSB.

The complete set of supported options for flags is listed below.

Various characters can be escaped. If ASN1_STRFLGS_ESC_2253 is set the characters determined by RFC2253 are escaped. If ASN1_STRFLGS_ESC_CTRL is set control characters are escaped. If ASN1_STRFLGS_ESC_MSB is set characters with the MSB set are escaped: this option should not be used if the terminal correctly interprets UTF8 sequences.

Escaping takes several forms.

If the character being escaped is a 16 bit character then the form ``\WXXXX'' is used using exactly four characters for the hex representation. If it is 32 bits then ``\UXXXXXXXX'' is used using eight characters of its hex representation. These forms will only be used if UTF8 conversion is not set (see below).

Printable characters are normally escaped using the backslash '\' character. If ASN1_STRFLGS_ESC_QUOTE is set then the whole string is instead surrounded by double quote characters: this is arguably more readable than the backslash notation. Other characters use the ``\XX'' using exactly two characters of the hex representation.

If ASN1_STRFLGS_UTF8_CONVERT is set then characters are converted to UTF8 format first. If the terminal supports the display of UTF8 sequences then this option will correctly display multi byte characters.

If ASN1_STRFLGS_IGNORE_TYPE is set then the string type is not interpreted at all: everything is assumed to be one byte per character. This is primarily for debugging purposes and can result in confusing output in multi character strings.

If ASN1_STRFLGS_SHOW_TYPE is set then the string type itself is printed out before its value (for example ``BMPSTRING''), this actually uses ASN1_tag2str().

The content of a string instead of being interpreted can be ``dumped'': this just outputs the value of the string using the form #XXXX using hex format for each octet.

If ASN1_STRFLGS_DUMP_ALL is set then any type is dumped.

Normally non character string types (such as OCTET STRING) are assumed to be one byte per character, if ASN1_STRFLGS_DUMP_UNKNOWN is set then they will be dumped instead.

When a type is dumped normally just the content octets are printed, if ASN1_STRFLGS_DUMP_DER is set then the complete encoding is dumped instead (including tag and length octets).

ASN1_STRFLGS_RFC2253 includes all the flags required by RFC2253. It is equivalent to: ASN1_STRFLGS_ESC_2253 | ASN1_STRFLGS_ESC_CTRL | ASN1_STRFLGS_ESC_MSB | ASN1_STRFLGS_UTF8_CONVERT | ASN1_STRFLGS_DUMP_UNKNOWN ASN1_STRFLGS_DUMP_DER

See Also

X509_NAME_print_ex(), ASN1_tag2str()

History

TBA

Feedback

For additional information or queries on this page send feedback


atan

Name

atan, atanf, atanl
- arc tangent function

Library

 libm.lib

Synopsis
#include <math.h>
double atan (double x);
float atanf (float x);
long double atan (long double x);
Sh RETURN VALUES The atan, atanf, and the atanl functions return the arc tangent in the range -words [-pi/2, +pi/2]
radians.

Detailed description

 The atan and atanf functions compute the principal value of the arc tangent of x. The function atanl is just an alias to the function atan.

Examples

#include <math.h>
int main( )
{
   double x = 1;
   double y = atan( x );
   printf( "atan(%f) = %f\n", x, y );
   y = atanf( x );
   printf( "atanf(%f) = %f\n", x, y );
   y = atanl( x );
   printf( "atanl(%f) = %f\n", x, y );
}

Output

atan ( 1.000000 ) = 0.7853981
atanf (1.000000 ) = 0.7853981
atanl(1.000000 ) = 0.7853981

See also

 acos, asin, atan2, cos, cosh, math, sin, sinh, tan, tanh

Feedback

For additional information or queries on this page send feedback


atan2

Name

atan2, atan2f, atan2l
- arc tangent function of two variables

Library

 libm.lib

Synopsis
#include <math.h>
double atan2 (double y, double x);
float atan2f (float y, float x);
long double atan2 (long double y, long double x);

Return values

 The atan2, atan2f, and atan2l functions, if successful, return the arc tangent of y/ x in the range -words [- pi, + pi] radians. Here are some of the special cases: atan2 (y, x, No, :=, Ta);
 | atan (y/x, Ta); if x > 0,
sign( y )*(pi - | atan (\*(Bay/x\*(Ba, ), Ta); if x < 0,
 | 0 if x = y = 0, or
 | sign( y )*\*(Pi/2 if x = 0 != y.

Detailed description

 The atan2 and atan2f functions compute the principal value of the arc tangent of y/ x, using the signs of both arguments to determine the quadrant of the return value. The function atan2l is an alias to the function atan2.

Examples

#include <math.h>
int main( void )
{
   double x1 = -862.42, x2 = 78.5149, y;
   y = atan2( x1, x2 );
   printf( "atan2(%f , %f) = %f\n", x1, x2, y );
   y = atan2f( x1, x2 );
   printf( "atan2f(%f , %f) = %f\n", x1, x2, y );
   y = atan2l( x1, x2 );
   printf( "atan2l(%f , %f) = %f\n", x1, x2, y );
}

Output

atan2( -862.42, 78.5149 ) = -1.480006
atan2f( -862.42, 78.5149 ) = -1.480006
atan2l( -862.42, 78.5149 ) = -1.480006

Notes

 The function atan2 defines "if x > 0," atan2 (0, 0);
= 0 despite that previously atan2 (0, 0);
may have generated an error message. The reasons for assigning a value to atan2 (0, 0);
are these:
  1. Programs that test arguments to avoid computing atan2 (0, 0);
    must be indifferent to its value. Programs that require it to be invalid are vulnerable to diverse reactions to that invalidity on diverse computer systems.
  2. The atan2 function is used mostly to convert from rectangular (x,y) to polar (r,theta) (r,th) coordinates that must satisfy x = r*cos theta r*costh and y = r*sin theta. r*sinth. These equations are satisfied when (x=0,y=0) is mapped to (r=0,theta=0).

    (r=0,th=0). In general, conversions to polar coordinates should be computed thus:

r       := hypot(x,y);  ... := sqrt(x*x+y*y)
theta   := atan2(y,x).

r       := hypot(x,y);  ... := v/(x20+y20)
th      := atan2(y,x).

  3. The foregoing formulas need not be altered to cope in a reasonable way with signed zeros and infinities on a machine that conforms to IEEE 754; the versions of hypot and atan2 provided for such a machine are designed to handle all cases. That is why atan2 (±0, -0);
    = ±pi for instance. In general the formulas above are equivalent to these:

r := sqrt(x*x+y*y); if r = 0 then x := copysign(1,x);
r := v/(x*x+y*y);  if r = 0 then x := copysign(1,x);

See also

 acos, asin, atan, cos, cosh, math, sin, sinh, tan, tanh
The atan2 function conforms to -isoC.

Feedback

For additional information or queries on this page send feedback


atanh

Name

atanh, atanhf, atanhl
- inverse hyperbolic tangent function

Library

 libm.lib

Synopsis
#include <math.h>
double atanh (double x);
float atanhf (float x);
long double atanh (long double x);

Return values

 The atanh, atanhf, and atanhl functions return the inverse hyperbolic tangent of x if successful. If the argument has absolute value 1, an infinity is returned. If |x| > 1,an NaN is returned.

Detailed description

 The atanh and atanhf functions compute the inverse hyperbolic tangent of the real argument x. The function atanhl is an alias to the function atanh.

Examples

#include <math.h>
int main( )
{
   double x = 1;
   double y = atanh( x );
   printf( "atanh(%f) = %f\n", x, y );
   y = atanhf( x );
   printf( "atanhf(%f) = %f\n", x, y );
   y = atanhl( x );
   printf( "atanhl(%f) = %f\n", x, y );
}

Output

atanh  ( 1.000000 ) = Inf
atanhf ( 1.000000 ) = Inf
atanhl ( 1.000000 ) = Inf

See also

 acosh, asinh, exp, math

Feedback

For additional information or queries on this page send feedback


atexit

Name

atexit - registers a function to be called at normal program termination

Library

 libc.lib

Synopsis
#include <stdlib.h>
int atexit (void (*function)(void));

Return values

 The atexit function returns the value 0 if successful; otherwise the value -1 is returned and the global variable errno is set to indicate the error.

Detailed description

 The atexit function registers the given function to be called at program exit, whether via exit or via return from the program’s main. Functions so registered are called in reverse order; no arguments are passed.

These functions must not call exit; if it should be necessary to terminate the process while in such a function, the _exit function should be used. (Alternatively, the function may cause abnormal process termination, for example by calling abort

At least 32 functions can always be registered, and more are allowed as long as sufficient memory can be allocated.

Examples

#include <stdlib.h>
#include <stdio.h>

void fun1( void ), fun2( void ), fun3( void ), fun4( void );

int main( void )
{
   atexit( fun1 );
   atexit( fun2 );
   atexit( fun3 );
   atexit( fun4 );
   printf( "Before exiting....\n" );
}

void fun1()
{
   printf( " fun1\n " );
}

void fun2()
{
   printf( " fun2\n " );
}

void fun3()
{
   printf( " fun3\n " );
}

void fun4()
{
   printf( " fun4\n " );
}

Output

Before exiting...
fun4
fun3
fun2
fun1

Errors
[ENOMEM]
No memory was available to add the function to the list. The existing list of functions is not modified.

See also

 exit

Feedback

For additional information or queries on this page send feedback


atof

Name

atof - convert a string to a double

Library

 libc.lib

Synopsis
#include <stdlib.h>
double atof (const char *nptr);

Return values

 The atof function returns the converted value if the value can be represented.

Detailed description

 The atof function converts the initial portion of the string pointed to by nptr to double representation.

It is equivalent to:

strtod(nptr, (char **)NULL);

The decimal point character is defined in the program’s locale (category LC_NUMERIC).

Examples

#include <stdlib.h>
#include <stdio.h>

void main( void )
{
 /* Test of atof */
 double d = atof("  86778E-2");

 printf( "result of atof: %f\n", d );
}

Output

result of atof: 867.78

Implementation notes

 The atof function is not thread-safe and also not async-cancel-safe.

The atof function has been deprecated by strtod and its use is not preferred.

Errors

 No errors are defined.

See also

 atoi, atol, strtod, strtol, strtoul

Feedback

For additional information or queries on this page send feedback


atoi

Name

atoi - converts a string to an integer

Library

 libc.lib

Synopsis
#include <stdlib.h>
int atoi (const char *nptr);

Return values

 The atoi function returns the converted value if the value can be represented.

Detailed description

 The atoi function converts the initial portion of the string pointed to by nptr to int representation.

It is equivalent to:

(int)strtol(nptr, (char **)NULL, 10);

Examples

#include <stdlib.h>
#include <stdio.h>

void main( void )
{
  /* call to atoi */
  char *str = "  -56957jdhfjk";
  int i = atoi( str );
  printf( "result of atoi: %d\n", i );
}

Output

result of atoi: -56957

Implementation notes

 The atoi function is not thread-safe and also not async-cancel safe.

The atoi function has been deprecated by strtol and its use is not preferred.

Errors

 No errors are defined.

See also

 atof, atol, strtod, strtol, strtoul

Feedback

For additional information or queries on this page send feedback


atol

Name

atol, atoll
- convert a string to an integer ASCII string to long or long long integer

Library

 libc.lib

Synopsis
#include <stdlib.h>
long atol (const char *nptr);
long long atoll (const char *nptr);

Return values

 The atol and atoll functions return the converted value if the value can be represented.

Detailed description

 The atol function converts the initial portion of the string pointed to by nptr to long 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 to long long integer representation. It is equivalent to:
     strtoll(nptr, (char **)NULL, 10);

Examples

#include <stdlib.h>
#include <stdio.h>

void main( void )
{
 /* call to atol */
 long l = atol( "-000002344" );

 printf( "result of atol: %ld\n", l );
}

Output

result of atol: -2344

#include <stdlib.h>
#include <stdio.h>

void main( void )
{
 /* call to atoll */
 long long l = atoll("454756356bs");

 printf( "result of atoll: %ld\n", l );
}

Output

result of atoll: 454756356

Errors

 No errors are defined.

See also

 atof, atoi, strtod, strtol, strtoul

Feedback

For additional information or queries on this page send feedback


bcmp

Name

bcmp - compares byte sequences

Library

 libc.lib

Synopsis
#include <strings.h>
int bcmp (const void *b1, const void *b2, size_t len);

Return values

bcmp function returns 0 if the byte sequences are equal, otherwise a non-zero result is returned.

Detailed description

 The bcmp function compares byte string b1 against byte string b2, returning zero if they are identical, non-zero otherwise. Both strings are assumed to be len bytes long. Zero-length strings are always identical.

The strings may overlap.

Examples

#include <string.h>
#include <stdio.h>
int main()
{
   int ret = 0;
   ret = bcmp("a","a",1);
   printf("bcmp(\"a\",\"a\",1) is %d",ret);
   ret = bcmp("abcd","abce",4);
   printf("\nbcmp(\"abcd\",\"abce\",1) is %d",ret);
   ret = bcmp("abc","xyz",0);
   printf("\nbcmp(\"abc\",\"xyz\",0) is %d",ret);
   return 0;
}

Output

bcmp("a","a",1) is 0
bcmp("abcd","abce",1) is -1
bcmp("abc","xyz",0) is 0

See also

 memcmp, strcasecmp, strcmp, strcoll, strxfrm

Feedback

For additional information or queries on this page send feedback


bcopy

Name

bcopy - copies byte sequence

Library

 libc.lib

Synopsis
#include <strings.h>
void bcopy (const void *src, void *dst, size_t len);

Detailed description

 The bcopy function copies len bytes from string src to string dst. The two strings may overlap. If len is zero, no bytes are copied.

Examples

#include <string.h>
#include <stdio.h>
int main()
{
    char dst[50];
    bcopy("Hello World",dst,12);
    printf("Destination string after bcopy = %s\n",dst);
    return 0;
}

Output

Destination string after bcopy = Hello World

See also

 memccpy, memcpy, memmove, strcpy

Feedback

For additional information or queries on this page send feedback


bind

Name

bind - binds a name to a socket

Library

 libc.lib

Synopsis
#include <sys/types.h>
#include <sys/socket.h>
int bind (int s, const struct sockaddr *addr, socklen_t addrlen);

Detailed description

 The bind system call assigns the local protocol address to a socket. When a socket is created with socket it exists in an address family space but has no protocol address assigned. The bind system call requests that addr be assigned to the socket.

Examples

#include <sys/socket.h>
#include <netinet/in.h>
#include <unistd.h>
TInt GetSockName()
{
   int sock_fd;
   struct sockaddr_in addr,ss;
   unsigned int len;

   sock_fd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);

   addr.sin_family = AF_INET;
   addr.sin_addr.s_addr = htonl(INADDR_ANY);
   addr.sin_port = htons(5000);
   bind(sock_fd,(struct sockaddr*)&addr,sizeof(addr));
   close(sock_fd);
}

Notes

For maximum portability, always zero the socket address structure before populating it and passing it to bind.

Return values

 The bind() 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 bind system call will fail if:
[EAGAIN]
 | Kernel resources to complete the request are temporarily unavailable.
[EBADF]
 | The s argument is not a valid descriptor.
[ENOTSOCK]
 | The s argument 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 inadequate permission to access it.
[EFAULT]
 | The addr argument is not in a valid part of the user address space.
[EINVAL]
 | The addrlen argument is not in a valid.

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 entire path name exceeded 1023 characters.
[ENOENT] | A prefix component of the path name does not exist.
[ELOOP] | Too many symbolic links were encountered in translating the pathname.
[EIO] | An I/O error occurred while making the directory entry or allocating the inode.
[EROFS] | The name would reside on a read-only file system.
[EISDIR] | An empty pathname was specified.

See also

 connect, getsockname, listen, socket
The bind system call appeared in BSD 4.2 .

Feedback

For additional information or queries on this page send feedback


bind_textdomain_codeset

Name

bind_textdomain_codeset: Sets the encoding of message translations.

Library

libintl.lib

Synopsis

#include <libintl.h>

char * bind_textdomain_codeset(const char *domainname, const char *codeset);

Return values

On success, bind_textdomain_codeset returns the current codeset for the domain domainname after changing the codeset. Do not modify or free the returned string for the same domainname as it is valid till the next call to bind_textdomain_codeset.
On failure, returns NULL and sets the errno to indicate the error.

Detailed description

The bind_textdomain_codeset funtion sets the output codeset for the message catalogs for the message domain domainname.

If the argument codeset is not NULL, the function sets the output codeset for the message catalogs of the domain specified by the argument domainname to the codeset specified by the argument codeset. Internally, the function copies the string arguments as needed.

If the argument codeset is NULL, the function returns the previously set codeset for the message domain specified, by the argument domainname.

Errors

The following error can occur:

ENOMEM Memory available is insufficient.

Feedback

For additional information or queries on this page send feedback

© 2006-2007 Nokia


bindresvport

Name

bindresvport - binds a socket to a privileged IP port

Library

 libc.lib

Synopsis
#include <sys/types.h>
int bindresvport (int sd, struct sockaddr_in *sin);

Detailed description

 The bindresvport function used to bind a socket descriptor to a privileged IP port, that is, a port number in the range 0-1023.

If sin is a pointer to a
struct sockaddr_in then the appropriate fields in the structure should be defined. Note that sin->sin_family must be initialized to the address family of the socket, passed by sd. If sin->sin_port is '0' then an anonymous port (in the range 600-1023) will be chosen, and if bind is successful, the sin->sin_port will be updated to contain the allocated port.

If sin is the NULL pointer, an anonymous port will be allocated (as above). However, there is no way for bindresvport to return the allocated port in this case.

Function prototype of bindresvport is biased to AF_INET socket.

Examples

#include <sys/socket.h>
#include <netinet/in.h>
#include <unistd.h>
void BindResvPort()
{
   int sockfd;
   sockaddr_in selfAddr;
   sockfd = socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);

   selfAddr.sin_family = AF_INET;
   selfAddr.sin_addr.s_addr = INADDR_ANY;
   selfAddr.sin_port = htons(100);
   bindresvport(sockfd, &selfAddr);
   close(sockfd);
}

Return values

 The bindresvport() 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
[EPFNOSUPPORT]
If second argument was supplied, and address family did not match between arguments.

The bindresvport function may also fail and set errno for any of the errors specified for the calls bind, getsockopt, or setsockopt.

See also

 bind, getsockopt, setsockopt,

Feedback

For additional information or queries on this page send feedback


bindtextdomain

Name

bindtextdomain - Sets the directory containing message catalogs.

Library

libintl.lib

Synopsis

#include <libintl.h>

char * bindtextdomain(const char *domainname, const char *dirname);

Return values

On success, the bindtextdomain function returns the current base directory for domain domainname, after changing it. Do not return or free the resulting string as it is valid till the next call to bindtextdomain for the same domainname.
On failure, it returns NULL and sets the errno to indicate the error.

Detailed description

The bindtextdomain function sets the base directory of the hierarchy containing message catalogs for a given message domain.

If the argument dirname is not NULL, set the base directory for the message catalogs belonging to the domain specified by the argument domainname to the directory specified by the argument dirname. Internally, the function copies the string arguments as needed.

If the argument dirname is NULL, the function returns the previously set base directory for the domain specified by the argument domainname.

Errors

The following error can occur:

ENOMEM

 Memory available is insufficient

Feedback

For additional information or queries on this page send feedback

© 2006-2007 Nokia


bio - I/O abstraction

Name

bio — I/O abstraction

Library

libcrypto.lib

Synopsis

#include <openssl/bio.h>

TBA

Detailed Description

A BIO is an I/O abstraction, it hides many of the underlying I/O details from an application. If an application uses a BIO for its I/O it can transparently handle SSL connections, unencrypted network connections and file I/O.

There are two type of BIO, a source/sink BIO and a filter BIO.

As its name implies a source/sink BIO is a source and/or sink of data, examples include a socket BIO and a file BIO.

A filter BIO takes data from one BIO and passes it through to another, or the application. The data may be left unmodified (for example a message digest BIO) or translated (for example an encryption BIO). The effect of a filter BIO may change according to the I/O operation it is performing: for example an encryption BIO will encrypt data if it is being written to and decrypt data if it is being read from.

BIOs can be joined together to form a chain (a single BIO is a chain with one component). A chain normally consist of one source/sink BIO and one or more filter BIOs. Data read from or written to the first BIO then traverses the chain to the end (normally a source/sink BIO).

See Also

BIO_ctrl(),
BIO_f_base64(),
BIO_f_buffer(),
BIO_f_cipher(),
BIO_f_md(),
BIO_f_null(),
BIO_f_ssl(),
BIO_find_type(),
BIO_new(),
BIO_new_bio_pair(),
BIO_push(), BIO_read(),
BIO_s_accept(),
BIO_s_bio(),
BIO_s_connect(),
BIO_s_fd(),
BIO_s_file(),
BIO_s_mem(),
BIO_s_null(),
BIO_s_socket(),
BIO_set_callback(),
BIO_should_retry()

Feedback

For additional information or queries on this page send feedback


BIO_set_info_callback - BIO control operations

Name

BIO_ctrl, BIO_callback_ctrl, BIO_ptr_ctrl
BIO_int_ctrl, BIO_reset, BIO_seek
BIO_tell, BIO_flush, BIO_eof
BIO_set_close, BIO_get_close
BIO_pending, BIO_wpending
BIO_ctrl_pending, BIO_ctrl_wpending
BIO_get_info_callback, BIO_set_info_callback

BIO control operations.

Library

libcrypto.lib

Synopsis

#include <openssl/bio.h>
long BIO_ctrl(BIO *bp,int cmd,long larg,void *parg);
long BIO_callback_ctrl(BIO *b, int cmd, void (*fp)(struct bio_st *, int, const char *, int, long, long));
char * BIO_ptr_ctrl(BIO *bp,int cmd,long larg);
long BIO_int_ctrl(BIO *bp,int cmd,long larg,int iarg);
int BIO_reset(BIO *b);
int BIO_seek(BIO *b, int ofs);
int BIO_tell(BIO *b);
int BIO_flush(BIO *b);
int BIO_eof(BIO *b);
int BIO_set_close(BIO *b,long flag);
int BIO_get_close(BIO *b);
int BIO_pending(BIO *b);
int BIO_wpending(BIO *b);
size_t BIO_ctrl_pending(BIO *b);
size_t BIO_ctrl_wpending(BIO *b);
int BIO_get_info_callback(BIO *b,bio_info_cb **cbp);
int BIO_set_info_callback(BIO *b,bio_info_cb *cb);
typedef void bio_info_cb(BIO *b, int oper, const char *ptr, int arg1, long arg2, long arg3);

Detailed Description

BIO_ctrl(), BIO_callback_ctrl(), BIO_ptr_ctrl() and BIO_int_ctrl() are BIO "control'' operations taking arguments of various types. These functions are not normally called directly, various macros are used instead. The standard macros are described below, macros specific to a particular type of BIO are described in the specific BIOs manual page as well as any special features of the standard calls.

BIO_reset() typically resets a BIO to some initial state, in the case of file related BIOs for example it rewinds the file pointer to the start of the file.

BIO_seek() resets a file related BIO's (that is file descriptor and FILE BIOs) file position pointer to ofs bytes from start of file.

BIO_tell() returns the current file position of a file related BIO.

BIO_flush() normally writes out any internally buffered data, in some cases it is used to signal EOF and that no more data will be written.

BIO_eof() returns 1 if the BIO has read EOF, the precise meaning of ``EOF'' varies according to the BIO type.

BIO_set_close() sets the BIO b close flag to flag. flag can take the value BIO_CLOSE or BIO_NOCLOSE. Typically BIO_CLOSE is used in a source/sink BIO to indicate that the underlying I/O stream should be closed when the BIO is freed.

BIO_get_close() returns the BIOs close flag.

BIO_pending(), BIO_ctrl_pending(), BIO_wpending() and BIO_ctrl_wpending() return the number of pending characters in the BIOs read and write buffers. Not all BIOs support these calls. BIO_ctrl_pending() and BIO_ctrl_wpending() return a size_t type and are functions, BIO_pending() and BIO_wpending() are macros which call BIO_ctrl().

Return Values

BIO_reset() normally returns 1 for success and 0 or -1 for failure. File BIOs are an exception, they return 0 for success and -1 for failure.

BIO_seek() and BIO_tell() both return the current file position on success and -1 for failure, except file BIOs which for BIO_seek() always return 0 for success and -1 for failure.

BIO_flush() returns 1 for success and 0 or -1 for failure.

BIO_eof() returns 1 if EOF has been reached 0 otherwise.

BIO_set_close() always returns 1.

BIO_get_close() returns the close flag value: BIO_CLOSE or BIO_NOCLOSE.

BIO_pending(), BIO_ctrl_pending(),
BIO_wpending() and
BIO_ctrl_wpending()
return the amount of pending data.

Notes

BIO_flush(), because it can write data may return 0 or -1 indicating that the call should be retried later in a similar manner to BIO_write(). The BIO_should_retry() call should be used and appropriate action taken is the call fails.

The return values of BIO_pending() and BIO_wpending() may not reliably determine the amount of pending data in all cases. For example in the case of a file BIO some data may be available in the FILE structures internal buffers but it is not possible to determine this in a portably way. For other types of BIO they may not be supported.

Filter BIOs if they do not internally handle a particular BIO_ctrl() operation usually pass the operation to the next BIO in the chain. This often means there is no need to locate the required BIO for a particular operation, it can be called on a chain and it will be automatically passed to the relevant BIO. However this can cause unexpected results: for example no current filter BIOs implement BIO_seek(), but this may still succeed if the chain ends in a FILE or file descriptor BIO.

Source/sink BIOs return an 0 if they do not recognize the BIO_ctrl() operation.

Bugs

Some of the return values are ambiguous and care should be taken. In particular a return value of 0 can be returned if an operation is not supported, if an error occurred, if EOF has not been reached and in the case of BIO_seek() on a file BIO for a successful operation.

See Also

TBA

Feedback

For additional information or queries on this page send feedback


BIO_f_base64 - base64 BIO filter

Name

BIO_f_base64 — base64 BIO filter

Library

libcrypto.lib

Synopsis

#include <openssl/bio.h>
#include <openssl/evp.h>
BIO_METHOD *   BIO_f_base64(void);

Detailed Description

BIO_f_base64() returns the base64 BIO method. This is a filter BIO that base64 encodes any data written through it and decodes any data read through it.

Base64 BIOs do not support BIO_gets() or BIO_puts().

BIO_flush() on a base64 BIO that is being written through is used to signal that no more data is to be encoded: this is used to flush the final block through the BIO.

The flag BIO_FLAGS_BASE64_NO_NL can be set with BIO_set_flags() to encode the data all on one line or expect the data to be all on one line.

Examples

Base64 encode the string ``Hello World\n'' and write the result to standard output:
 BIO *bio, *b64;
 char message[] = "Hello World \n";
 b64 = BIO_new(BIO_f_base64());
 bio = BIO_new_fp(stdout, BIO_NOCLOSE);
 bio = BIO_push(b64, bio);
 BIO_write(bio, message, strlen(message));
 BIO_flush(bio);
 BIO_free_all(bio);

Read Base64 encoded data from standard input and write the decoded data to standard output:

 BIO *bio, *b64, *bio_out;
 char inbuf[512];
 int inlen;
 b64 = BIO_new(BIO_f_base64());
 bio = BIO_new_fp(stdin, BIO_NOCLOSE);
 bio_out = BIO_new_fp(stdout, BIO_NOCLOSE);
 bio = BIO_push(b64, bio);
 while((inlen = BIO_read(bio, inbuf, 512) > 0)
        BIO_write(bio_out, inbuf, inlen);
 BIO_free_all(bio);

Notes

Because of the format of base64 encoding the end of the encoded block cannot always be reliably determined.

Return Values

BIO_f_base64() returns the base64 BIO method.

Bugs

The ambiguity of EOF in base64 encoded data can cause additional data following the base64 encoded block to be misinterpreted.

There should be some way of specifying a test that the BIO can perform to reliably determine EOF (for example a MIME boundary).

See Also

TBA

Feedback

For additional information or queries on this page send feedback


BIO_f_buffer - buffering BIO

Name

BIO_f_buffer — Returns the buffering BIO method

Library

libcrypto.lib

Synopsis

#include <openssl/bio.h>
BIO_METHOD * BIO_f_buffer(void);
#define BIO_get_buffer_num_lines(b)         BIO_ctrl(b,BIO_C_GET_BUFF_NUM_LINES,0,NULL)
#define BIO_set_read_buffer_size(b,size)    BIO_int_ctrl(b,BIO_C_SET_BUFF_SIZE,size,0)
#define BIO_set_write_buffer_size(b,size)   BIO_int_ctrl(b,BIO_C_SET_BUFF_SIZE,size,1)
#define BIO_set_buffer_size(b,size)         BIO_ctrl(b,BIO_C_SET_BUFF_SIZE,size,NULL)
#define BIO_set_buffer_read_data(b,buf,num) BIO_ctrl(b,BIO_C_SET_BUFF_READ_DATA,num,buf)

Detailed Description

BIO_f_buffer() returns the buffering BIO method.

Data written to a buffering BIO is buffered and periodically written to the next BIO in the chain. Data read from a buffering BIO comes from an internal buffer which is filled from the next BIO in the chain. Both BIO_gets() and BIO_puts() are supported.

Calling BIO_reset() on a buffering BIO clears any buffered data.

BIO_get_buffer_num_lines() returns the number of lines currently buffered.

BIO_set_read_buffer_size(), BIO_set_write_buffer_size() and BIO_set_buffer_size() set the read, write or both read and write buffer sizes to size. The initial buffer size is DEFAULT_BUFFER_SIZE, currently 1024. Any attempt to reduce the buffer size below DEFAULT_BUFFER_SIZE is ignored. Any buffered data is cleared when the buffer is resized.

BIO_set_buffer_read_data() clears the read buffer and fills it with num bytes of buf. If num is larger than the current buffer size the buffer is expanded.

Notes

Buffering BIOs implement BIO_gets() by using BIO_read() operations on the next BIO in the chain. By prepending a buffering BIO to a chain it is therefore possible to provide BIO_gets() functionality if the following BIOs do not support it (for example SSL BIOs).

Data is only written to the next BIO in the chain when the write buffer fills or when BIO_flush() is called. It is therefore important to call BIO_flush() whenever any pending data should be written such as when removing a buffering BIO using BIO_pop(). BIO_flush() may need to be retried if the ultimate source/sink BIO is non blocking.

Return Values

BIO_f_buffer() returns the buffering BIO method.

BIO_get_buffer_num_lines() returns the number of lines buffered (may be 0).

BIO_set_read_buffer_size(),
BIO_set_write_buffer_size() and
 BIO_set_buffer_size()
return 1 if the buffer was successfully resized or 0 for failure.

BIO_set_buffer_read_data() returns 1 if the data was set correctly or 0 if there was an error.

See Also

TBA

Feedback

For additional information or queries on this page send feedback


BIO_get_cipher_ctx - cipher BIO filter

Name

BIO_f_cipher, BIO_set_cipher
BIO_get_cipher_status, BIO_get_cipher_ctx

Returns the cipher BIO method

Library

libcrypto.lib

Synopsis

#include <openssl/bio.h>
#include <openssl/evp.h>
BIO_METHOD *   BIO_f_cipher(void);
void BIO_set_cipher(BIO *b,const EVP_CIPHER *cipher, unsigned char *key, unsigned char *iv, int enc);
int BIO_get_cipher_status(BIO *b)
int BIO_get_cipher_ctx(BIO *b, EVP_CIPHER_CTX **pctx)

Detailed Description

BIO_f_cipher() returns the cipher BIO method. This is a filter BIO that encrypts any data written through it, and decrypts any data read from it. It is a BIO wrapper for the cipher routines EVP_CipherInit(), EVP_CipherUpdate() and EVP_CipherFinal().

Cipher BIOs do not support BIO_gets() or BIO_puts().

BIO_flush() on an encryption BIO that is being written through is used to signal that no more data is to be encrypted: this is used to flush and possibly pad the final block through the BIO.

BIO_set_cipher() sets the cipher of BIO b to cipher using key key and IV iv. enc should be set to 1 for encryption and zero for decryption.

When reading from an encryption BIO the final block is automatically decrypted and checked when EOF is detected. BIO_get_cipher_status() is a BIO_ctrl() macro which can be called to determine whether the decryption operation was successful.

BIO_get_cipher_ctx() is a BIO_ctrl() macro which retrieves the internal BIO cipher context. The retrieved context can be used in conjunction with the standard cipher routines to set it up. This is useful when BIO_set_cipher() is not flexible enough for the applications needs.

Notes

When encrypting BIO_flush() must be called to flush the final block through the BIO. If it is not then the final block will fail a subsequent decrypt.

When decrypting an error on the final block is signaled by a zero return value from the read operation. A successful decrypt followed by EOF will also return zero for the final read. BIO_get_cipher_status() should be called to determine if the decrypt was successful.

As always, if BIO_gets() or BIO_puts() support is needed then it can be achieved by preceding the cipher BIO with a buffering BIO.

Return Values

BIO_f_cipher() returns the cipher BIO method.

BIO_set_cipher() does not return a value.

BIO_get_cipher_status() returns 1 for a successful decrypt and 0 for failure.

BIO_get_cipher_ctx() currently always returns 1.

Examples

TBA

See Also

TBA

Feedback

For additional information or queries on this page send feedback


BIO_get_md_ctx - message digest BIO filter

Name

BIO_f_md, BIO_set_md
BIO_get_md, BIO_get_md_ctx

message digest BIO filter

Library-

libcrypto.lib

Synopsis

#include <openssl/bio.h>
#include <openssl/evp.h>
BIO_METHOD *   BIO_f_md(void);
int BIO_set_md(BIO *b,EVP_MD *md);
int BIO_get_md(BIO *b,EVP_MD **mdp);
int BIO_get_md_ctx(BIO *b,EVP_MD_CTX **mdcp);

Detailed Description

BIO_f_md() returns the message digest BIO method. This is a filter BIO that digests any data passed through it, it is a BIO wrapper for the digest routines EVP_DigestInit(), EVP_DigestUpdate() and EVP_DigestFinal().

Any data written or read through a digest BIO using BIO_read() and BIO_write() is digested.

BIO_gets(), if its size parameter is large enough finishes the digest calculation and returns the digest value. BIO_puts() is not supported.

BIO_reset() reinitializes a digest BIO.

BIO_set_md() sets the message digest of BIO b to md: this must be called to initialize a digest BIO before any data is passed through it. It is a BIO_ctrl() macro.

BIO_get_md() places the a pointer to the digest BIOs digest method in mdp, it is a BIO_ctrl() macro.

BIO_get_md_ctx() returns the digest BIOs context into mdcp.

Examples

The following example creates a BIO chain containing an SHA1 and MD5 digest BIO and passes the string ``Hello World'' through it. Error checking has been omitted for clarity.
 BIO *bio, *mdtmp;
 char message[] = "Hello World";
 bio = BIO_new(BIO_s_null());
 mdtmp = BIO_new(BIO_f_md());
 BIO_set_md(mdtmp, EVP_sha1());
 /* For BIO_push() we want to append the sink BIO and keep a note of
  * the start of the chain.
  */
 bio = BIO_push(mdtmp, bio);
 mdtmp = BIO_new(BIO_f_md());
 BIO_set_md(mdtmp, EVP_md5());
 bio = BIO_push(mdtmp, bio);
 /* Note: mdtmp can now be discarded */
 BIO_write(bio, message, strlen(message));

The next example digests data by reading through a chain instead:

 BIO *bio, *mdtmp;
 char buf[1024];
 int rdlen;
 bio = BIO_new_file(file, "rb");
 mdtmp = BIO_new(BIO_f_md());
 BIO_set_md(mdtmp, EVP_sha1());
 bio = BIO_push(mdtmp, bio);
 mdtmp = BIO_new(BIO_f_md());
 BIO_set_md(mdtmp, EVP_md5());
 bio = BIO_push(mdtmp, bio);
 do {
        rdlen = BIO_read(bio, buf, sizeof(buf));
        /* Might want to do something with the data here */
 } while(rdlen > 0);

This next example retrieves the message digests from a BIO chain and outputs them. This could be used with the examples above.

 BIO *mdtmp;
 unsigned char mdbuf[EVP_MAX_MD_SIZE];
 int mdlen;
 int i;
 mdtmp = bio;   /* Assume bio has previously been set up */
 do {
        EVP_MD *md;
        mdtmp = BIO_find_type(mdtmp, BIO_TYPE_MD);
        if(!mdtmp) break;
        BIO_get_md(mdtmp, &md);
        printf("%s digest", OBJ_nid2sn(EVP_MD_type(md)));
        mdlen = BIO_gets(mdtmp, mdbuf, EVP_MAX_MD_SIZE);
        for(i = 0; i < mdlen; i++) printf(":%02X", mdbuf[i]);
        printf("\n");
        mdtmp = BIO_next(mdtmp);
 } while(mdtmp);
 BIO_free_all(bio);

Notes

The context returned by BIO_get_md_ctx() can be used in calls to EVP_DigestFinal() and also the signature routines EVP_SignFinal() and EVP_VerifyFinal().

The context returned by BIO_get_md_ctx() is an internal context structure. Changes made to this context will affect the digest BIO itself and the context pointer will become invalid when the digest BIO is freed.

After the digest has been retrieved from a digest BIO it must be reinitialized by calling BIO_reset(), or BIO_set_md() before any more data is passed through it.

If an application needs to call BIO_gets() or BIO_puts() through a chain containing digest BIOs then this can be done by prepending a buffering BIO.

Return Values

BIO_f_md() returns the digest BIO method.

BIO_set_md(), BIO_get_md() and BIO_md_ctx() return 1 for success and 0 for failure.

Bugs

The lack of support for BIO_puts() and the non standard behaviour of BIO_gets() could be regarded as anomalous. It could be argued that BIO_gets() and BIO_puts() should be passed to the next BIO in the chain and digest the data passed through and that digests should be retrieved using a separate BIO_ctrl() call.

See Also

TBA

Feedback

For additional information or queries on this page send feedback


BIO_f_null - null filter

Name

BIO_f_null — null filter

Library

libcrypto.lib

Synopsis

#include <openssl/bio.h>
BIO_METHOD *   BIO_f_null(void);

Detailed Description

BIO_f_null() returns the null filter BIO method. This is a filter BIO that does nothing.

All requests to a null filter BIO are passed through to the next BIO in the chain: this means that a BIO chain containing a null filter BIO behaves just as though the BIO was not there.

Notes

As may be apparent a null filter BIO is not particularly useful.

Return Values

BIO_f_null() returns the null filter BIO method.

See Also

TBA

Feedback

For additional information or queries on this page send feedback


BIO_ssl_shutdown - SSL BIO

Name

BIO_f_ssl, BIO_set_ssl, BIO_get_ssl
BIO_set_ssl_mode, BIO_set_ssl_renegotiate_bytes
BIO_get_num_renegotiates, BIO_set_ssl_renegotiate_timeout
BIO_new_ssl, BIO_new_ssl_connect,
BIO_new_buffer_ssl_connect, BIO_ssl_copy_session_id,
BIO_ssl_shutdown

SSL BIO method

Library

libcrypto.lib

Synopsis

#include <openssl/bio.h>
#include <openssl/ssl.h>
BIO_METHOD *BIO_f_ssl(void);
#define BIO_set_ssl(b,ssl,c)   BIO_ctrl(b,BIO_C_SET_SSL,c,(char *)ssl)
#define BIO_get_ssl(b,sslp)    BIO_ctrl(b,BIO_C_GET_SSL,0,(char *)sslp)
#define BIO_set_ssl_mode(b,client)  BIO_ctrl(b,BIO_C_SSL_MODE,client,NULL)
#define BIO_set_ssl_renegotiate_bytes(b,num) \ BIO_ctrl(b,BIO_C_SET_SSL_RENEGOTIATE_BYTES,num,NULL);
#define BIO_set_ssl_renegotiate_timeout(b,seconds) \ BIO_ctrl(b,BIO_C_SET_SSL_RENEGOTIATE_TIMEOUT,seconds,NULL);
#define BIO_get_num_renegotiates(b) \ BIO_ctrl(b,BIO_C_SET_SSL_NUM_RENEGOTIATES,0,NULL);
BIO *BIO_new_ssl(SSL_CTX *ctx,int client);
BIO *BIO_new_ssl_connect(SSL_CTX *ctx);
BIO *BIO_new_buffer_ssl_connect(SSL_CTX *ctx);
int BIO_ssl_copy_session_id(BIO *to,BIO *from);
void BIO_ssl_shutdown(BIO *bio);
#define BIO_do_handshake(b)   BIO_ctrl(b,BIO_C_DO_STATE_MACHINE,0,NULL)

Detailed Description

BIO_f_ssl() returns the SSL BIO method. This is a filter BIO which is a wrapper round the OpenSSL SSL routines adding a BIO ``flavour'' to SSL I/O.

I/O performed on an SSL BIO communicates using the SSL protocol with the Ssl's read and write BIOs. If an SSL connection is not established then an attempt is made to establish one on the first I/O call.

If a BIO is appended to an SSL BIO using BIO_push() it is automatically used as the SSL BIOs read and write BIOs.

Calling BIO_reset() on an SSL BIO closes down any current SSL connection by calling SSL_shutdown(). BIO_reset() is then sent to the next BIO in the chain: this will typically disconnect the underlying transport. The SSL BIO is then reset to the initial accept or connect state.

If the close flag is set when an SSL BIO is freed then the internal SSL structure is also freed using SSL_free().

BIO_set_ssl() sets the internal SSL pointer of BIO b to ssl using the close flag c.

BIO_get_ssl() retrieves the SSL pointer of BIO b, it can then be manipulated using the standard SSL library functions.

BIO_set_ssl_mode() sets the SSL BIO mode to client. If client is 1 client mode is set. If client is 0 server mode is set.

BIO_set_ssl_renegotiate_bytes() sets the renegotiate byte count to num. When set after every num bytes of I/O (read and write) the SSL session is automatically renegotiated. num must be at least 512 bytes.

BIO_set_ssl_renegotiate_timeout() sets the renegotiate timeout to seconds. When the renegotiate timeout elapses the session is automatically renegotiated.

BIO_get_num_renegotiates() returns the total number of session renegotiations due to I/O or timeout.

BIO_new_ssl() allocates an SSL BIO using SSL_CTX ctx and using client mode if client is non zero.

BIO_new_ssl_connect() creates a new BIO chain consisting of an SSL BIO (using ctx) followed by a connect BIO.

BIO_new_buffer_ssl_connect() creates a new BIO chain consisting of a buffering BIO, an SSL BIO (using ctx) and a connect BIO.

BIO_ssl_copy_session_id() copies an SSL session id between BIO chains from and to. It does this by locating the SSL BIOs in each chain and calling SSL_copy_session_id() on the internal SSL pointer.

BIO_ssl_shutdown() closes down an SSL connection on BIO chain bio. It does this by locating the SSL BIO in the chain and calling SSL_shutdown() on its internal SSL pointer.

BIO_do_handshake() attempts to complete an SSL handshake on the supplied BIO and establish the SSL connection. It returns 1 if the connection was established successfully. A zero or negative value is returned if the connection could not be established, the call BIO_should_retry() should be used for non blocking connect BIOs to determine if the call should be retried. If an SSL connection has already been established this call has no effect.

Examples

This SSL/TLS client example, attempts to retrieve a page from an SSL/TLS web server. The I/O routines are identical to those of the unencrypted example in BIO_s_connect(3).
 BIO *sbio, *out;
 int len;
 char tmpbuf[1024];
 SSL_CTX *ctx;
 SSL *ssl;
 ERR_load_crypto_strings();
 ERR_load_SSL_strings();
 OpenSSL_add_all_algorithms();
 /* We would seed the PRNG here if the platform didn't
  * do it automatically
  */
 ctx = SSL_CTX_new(SSLv23_client_method());
 /* We'd normally set some stuff like the verify paths and
  * mode here because as things stand this will connect to
  * any server whose certificate is signed by any CA.
  */
 sbio = BIO_new_ssl_connect(ctx);
 BIO_get_ssl(sbio, &ssl);
 if(!ssl) {
   fprintf(stderr, "Can't locate SSL pointer\n");
   /* whatever ... */
 }
 /* Don't want any retries */
 SSL_set_mode(ssl, SSL_MODE_AUTO_RETRY);
 /* We might want to do other things with ssl here */
 BIO_set_conn_hostname(sbio, "localhost:https");
 out = BIO_new_fp(stdout, BIO_NOCLOSE);
 if(BIO_do_connect(sbio) <= 0) {
        fprintf(stderr, "Error connecting to server\n");
        ERR_print_errors_fp(stderr);
        /* whatever ... */
 }
 if(BIO_do_handshake(sbio) <= 0) {
        fprintf(stderr, "Error establishing SSL connection\n");
        ERR_print_errors_fp(stderr);
        /* whatever ... */
 }
 /* Could examine ssl here to get connection info */
 BIO_puts(sbio, "GET / HTTP/1.0\n\n");
 for(;;) {
        len = BIO_read(sbio, tmpbuf, 1024);
        if(len <= 0) break;
        BIO_write(out, tmpbuf, len);
 }
 BIO_free_all(sbio);
 BIO_free(out);

Here is a simple server example. It makes use of a buffering BIO to allow lines to be read from the SSL BIO using BIO_gets. It creates a pseudo web page containing the actual request from a client and also echoes the request to standard output.

 BIO *sbio, *bbio, *acpt, *out;
 int len;
 char tmpbuf[1024];
 SSL_CTX *ctx;
 SSL *ssl;
 ERR_load_crypto_strings();
 ERR_load_SSL_strings();
 OpenSSL_add_all_algorithms();
 /* Might seed PRNG here */
 ctx = SSL_CTX_new(SSLv23_server_method());
 if (!SSL_CTX_use_certificate_file(ctx,"server.pem",SSL_FILETYPE_PEM)
        || !SSL_CTX_use_PrivateKey_file(ctx,"server.pem",SSL_FILETYPE_PEM)
        || !SSL_CTX_check_private_key(ctx)) {
        fprintf(stderr, "Error setting up SSL_CTX\n");
        ERR_print_errors_fp(stderr);
        return 0;
 }
 /* Might do other things here like setting verify locations and
  * DH and/or RSA temporary key callbacks
  */
 /* New SSL BIO setup as server */
 sbio=BIO_new_ssl(ctx,0);
 BIO_get_ssl(sbio, &ssl);
 if(!ssl) {
   fprintf(stderr, "Can't locate SSL pointer\n");
   /* whatever ... */
 }
 /* Don't want any retries */
 SSL_set_mode(ssl, SSL_MODE_AUTO_RETRY);
 /* Create the buffering BIO */
 bbio = BIO_new(BIO_f_buffer());
 /* Add to chain */
 sbio = BIO_push(bbio, sbio);
 acpt=BIO_new_accept("4433");
 /* By doing this when a new connection is established
  * we automatically have sbio inserted into it. The
  * BIO chain is now 'swallowed' by the accept BIO and
  * will be freed when the accept BIO is freed.
  */

 BIO_set_accept_bios(acpt,sbio);
 out = BIO_new_fp(stdout, BIO_NOCLOSE);
 /* Setup accept BIO */
 if(BIO_do_accept(acpt) <= 0) {
        fprintf(stderr, "Error setting up accept BIO\n");
        ERR_print_errors_fp(stderr);
        return 0;
 }
 /* Now wait for incoming connection */
 if(BIO_do_accept(acpt) <= 0) {
        fprintf(stderr, "Error in connection\n");
        ERR_print_errors_fp(stderr);
        return 0;
 }
 /* We only want one connection so remove and free
  * accept BIO
  */
 sbio = BIO_pop(acpt);
 BIO_free_all(acpt);
 if(BIO_do_handshake(sbio) <= 0) {
        fprintf(stderr, "Error in SSL handshake\n");
        ERR_print_errors_fp(stderr);
        return 0;
 }
 BIO_puts(sbio, "HTTP/1.0 200 OK\r\nContent-type: text/plain\r\n\r\n");
 BIO_puts(sbio, "\r\nConnection Established\r\nRequest headers:\r\n");
 BIO_puts(sbio, "--------------------------------------------------\r\n");
 for(;;) {
        len = BIO_gets(sbio, tmpbuf, 1024);
        if(len <= 0) break;
        BIO_write(sbio, tmpbuf, len);
        BIO_write(out, tmpbuf, len);
        /* Look for blank line signifying end of headers*/
        if((tmpbuf[0] == '\r') || (tmpbuf[0] == '\n')) break;
 }
 BIO_puts(sbio, "--------------------------------------------------\r\n");
 BIO_puts(sbio, "\r\n");
 /* Since there is a buffering BIO present we had better flush it */
 BIO_flush(sbio);
 BIO_free_all(sbio);

Notes

SSL BIOs are exceptional in that if the underlying transport is non blocking they can still request a retry in exceptional circumstances. Specifically this will happen if a session renegotiation takes place during a BIO_read() operation, one case where this happens is when SGC or step up occurs.

In OpenSSL 0.9.6 and later the SSL flag SSL_AUTO_RETRY can be set to disable this behaviour. That is when this flag is set an SSL BIO using a blocking transport will never request a retry.

Since unknown BIO_ctrl() operations are sent through filter BIOs the servers name and port can be set using BIO_set_host() on the BIO returned by BIO_new_ssl_connect() without having to locate the connect BIO first.

Applications do not have to call BIO_do_handshake() but may wish to do so to separate the handshake process from other I/O processing.

Return Values

TBA

See Also

TBA

Feedback

For additional information or queries on this page send feedback


BIO_next - BIO chain traversal

Name

BIO_find_type, BIO_next — BIO chain traversal

Library

libcrypto.lib

Synopsis

#include <openssl/bio.h>
BIO *  BIO_find_type(BIO *b,int bio_type);
BIO *  BIO_next(BIO *b);
#define BIO_method_type(b)     ((b)->method->type)
#define BIO_TYPE_NONE          0
#define BIO_TYPE_MEM           (1|0x0400)
#define BIO_TYPE_FILE          (2|0x0400)
#define BIO_TYPE_FD            (4|0x0400|0x0100)
#define BIO_TYPE_SOCKET        (5|0x0400|0x0100)
#define BIO_TYPE_NULL          (6|0x0400)
#define BIO_TYPE_SSL           (7|0x0200)
#define BIO_TYPE_MD            (8|0x0200)
#define BIO_TYPE_BUFFER        (9|0x0200)
#define BIO_TYPE_CIPHER        (10|0x0200)
#define BIO_TYPE_BASE64        (11|0x0200)
#define BIO_TYPE_CONNECT       (12|0x0400|0x0100)
#define BIO_TYPE_ACCEPT        (13|0x0400|0x0100)
#define BIO_TYPE_PROXY_CLIENT  (14|0x0200)
#define BIO_TYPE_PROXY_SERVER  (15|0x0200)
#define BIO_TYPE_NBIO_TEST     (16|0x0200)
#define BIO_TYPE_NULL_FILTER   (17|0x0200)
#define BIO_TYPE_BER           (18|0x0200)
#define BIO_TYPE_BIO           (19|0x0400)
#define BIO_TYPE_DESCRIPTOR    0x0100
#define BIO_TYPE_FILTER        0x0200
#define BIO_TYPE_SOURCE_SINK   0x0400

Detailed Description

The BIO_find_type() searches for a BIO of a given type in a chain, starting at BIO b. If type is a specific type (such as BIO_TYPE_MEM) then a search is made for a BIO of that type. If type is a general type (such as BIO_TYPE_SOURCE_SINK) then the next matching BIO of the given general type is searched for. BIO_find_type() returns the next matching BIO or NULL if none is found.

Note: not all the BIO_TYPE_* types above have corresponding BIO implementations.

BIO_next() returns the next BIO in a chain. It can be used to traverse all BIOs in a chain or used in conjunction with BIO_find_type() to find all BIOs of a certain type.

BIO_method_type() returns the type of a BIO.

Examples

Traverse a chain looking for digest BIOs:
 BIO *btmp;
 btmp = in_bio; /* in_bio is chain to search through */
 do {
        btmp = BIO_find_type(btmp, BIO_TYPE_MD);
        if(btmp == NULL) break; /* Not found */
        /* btmp is a digest BIO, do something with it ...*/
        ...
        btmp = BIO_next(btmp);
 } while(btmp);

Return Values

BIO_find_type() returns a matching BIO or NULL for no match.

BIO_next() returns the next BIO in a chain.

BIO_method_type() returns the type of the BIO b.

Notes

BIO_next() was added to OpenSSL 0.9.6 to provide a 'clean' way to traverse a BIO chain or find multiple matches using BIO_find_type(). Previous versions had to use:

next = bio->next_bio;

Bugs

BIO_find_type() in OpenSSL 0.9.5a and earlier could not be safely passed a NULL pointer for the b argument.

See Also

TBA

Feedback

For additional information or queries on this page send feedback


BIO_free_all - BIO allocation and freeing functions

Name

BIO_new, BIO_set, BIO_free
BIO_vfree, BIO_free_all

BIO allocation and freeing functions

Library

libcrypto.lib

Synopsis

#include <openssl/bio.h>
BIO *  BIO_new(BIO_METHOD *type);
int    BIO_set(BIO *a,BIO_METHOD *type);
int    BIO_free(BIO *a);
void   BIO_vfree(BIO *a);
void   BIO_free_all(BIO *a);

Detailed Description

The BIO_new() function returns a new BIO using method type.

BIO_set() sets the method of an already existing BIO.

BIO_free() frees up a single BIO, BIO_vfree() also frees up a single BIO but it does not return a value. Calling BIO_free() may also have some effect on the underlying I/O structure, for example it may close the file being referred to under certain circumstances. For more details see the individual BIO_METHOD descriptions.

BIO_free_all() frees up an entire BIO chain, it does not halt if an error occurs freeing up an individual BIO in the chain.

Examples

Create a memory BIO:
 BIO *mem = BIO_new(BIO_s_mem());

Return Values

BIO_new() returns a newly created BIO or NULL if the call fails.

BIO_set(), BIO_free() return 1 for success and 0 for failure.

BIO_free_all() and BIO_vfree() do not return values.

Notes

Some BIOs (such as memory BIOs) can be used immediately after calling BIO_new(). Others (such as file BIOs) need some additional initialization, and frequently a utility function exists to create and initialize such BIOs.

If BIO_free() is called on a BIO chain it will only free one BIO resulting in a memory leak.

Calling BIO_free_all() a single BIO has the same effect as calling BIO_free() on it other than the discarded return value.

Normally the type argument is supplied by a function which returns a pointer to a BIO_METHOD. There is a naming convention for such functions: a source/sink BIO is normally called BIO_s_*() and a filter BIO BIO_f_*().

See Also

TBA

Feedback

For additional information or queries on this page send feedback


BIO_pop - add and remove BIOs from a chain.

Name

BIO_push, BIO_pop — adds and removes BIOs from a chain

Library

libcrypto.lib

Synopsis

#include <openssl/bio.h>
BIO *  BIO_push(BIO *b,BIO *append);
BIO *  BIO_pop(BIO *b);

Detailed Description

The BIO_push() function appends the BIO append to b, it returns b.

BIO_pop() removes the BIO b from a chain and returns the next BIO in the chain, or NULL if there is no next BIO. The removed BIO then becomes a single BIO with no association with the original chain, it can thus be freed or attached to a different chain.

Examples

For these examples suppose md1 and md2 are digest BIOs, b64 is a base64 BIO and f is a file BIO.

If the call:

 BIO_push(b64, f);

is made then the new chain will be b64-chain. After making the calls

 BIO_push(md2, b64);
 BIO_push(md1, md2);

the new chain is md1-md2-b64-f. Data written to md1 will be digested by md1 and md2, base64 encoded and written to f.

It should be noted that reading causes data to pass in the reverse direction, that is data is read from f, base64 decoded and digested by md1 and md2. If the call:

 BIO_pop(md2);

The call will return b64 and the new chain will be md1-b64-f data can be written to md1 as before.

Notes

The names of these functions are perhaps a little misleading. BIO_push() joins two BIO chains whereas BIO_pop() deletes a single BIO from a chain, the deleted BIO does not need to be at the end of a chain.

The process of calling BIO_push() and BIO_pop() on a BIO may have additional consequences (a control call is made to the affected BIOs) any effects will be noted in the descriptions of individual BIOs.

Return Values

BIO_push() returns the end of the chain, b.

BIO_pop() returns the next BIO in the chain, or NULL if there is no next BIO.

See Also

TBA

Feedback

For additional information or queries on this page send feedback


BIO_puts - BIO I/O functions

Name

BIO_read, BIO_write
BIO_gets, BIO_puts

BIO I/O functions

Library

libcrypto.lib

Synopsis

#include <openssl/bio.h>
int    BIO_read(BIO *b, void *buf, int len);
int    BIO_gets(BIO *b,char *buf, int size);
int    BIO_write(BIO *b, const void *buf, int len);
int    BIO_puts(BIO *b,const char *buf);

Detailed Description

BIO_read() attempts to read len bytes from BIO b and places the data in buf.

BIO_gets() performs the BIOs ``gets'' operation and places the data in buf. Usually this operation will attempt to read a line of data from the BIO of maximum length len. There are exceptions to this however, for example BIO_gets() on a digest BIO will calculate and return the digest and other BIOs may not support BIO_gets() at all.

BIO_write() attempts to write len bytes from buf to BIO b.

BIO_puts() attempts to write a null terminated string buf to BIO b

Return Values

All these functions return either the amount of data successfully read or written (if the return value is positive) or that no data was successfully read or written if the result is 0 or -1. If the return value is -2 then the operation is not implemented in the specific BIO type.

Notes

A 0 or -1 return is not necessarily an indication of an error. In particular when the source/sink is non-blocking or of a certain type it may merely be an indication that no data is currently available and that the application should retry the operation later.

One technique sometimes used with blocking sockets is to use a system call (such as select(), poll() or equivalent) to determine when data is available and then call read() to read the data. The equivalent with BIOs (that is call select() on the underlying I/O structure and then call BIO_read() to read the data) should not be used because a single call to BIO_read() can cause several reads (and writes in the case of SSL BIOs) on the underlying I/O structure and may block as a result. Instead select() (or equivalent) should be combined with non blocking I/O so successive reads will request a retry instead of blocking.

See BIO_should_retry() for details of how to determine the cause of a retry and other I/O issues.

If the BIO_gets() function is not supported by a BIO then it possible to work around this by adding a buffering BIO BIO_f_buffer() to the chain.

See Also

BIO_should_retry(), TBA

Feedback

For additional information or queries on this page send feedback


BIO_do_accept - accept BIO

Name

BIO_s_accept, BIO_set_accept_port
BIO_get_accept_port, BIO_set_nbio_accept
BIO_set_accept_bios, BIO_set_bind_mode
BIO_get_bind_mode, BIO_do_accept

accept BIO

Library

libcrypto.lib

Synopsis

#include <openssl/bio.h>
BIO_METHOD *BIO_s_accept(void);
long BIO_set_accept_port(BIO *b, char *name);
char *BIO_get_accept_port(BIO *b);
BIO *BIO_new_accept(char *host_port);
long BIO_set_nbio_accept(BIO *b, int n);
long BIO_set_accept_bios(BIO *b, char *bio);
long BIO_set_bind_mode(BIO *b, long mode);
long BIO_get_bind_mode(BIO *b, long dummy);
#define BIO_BIND_NORMAL                0
#define BIO_BIND_REUSEADDR_IF_UNUSED   1
#define BIO_BIND_REUSEADDR             2
int BIO_do_accept(BIO *b);

Detailed Description

BIO_s_accept() returns the accept BIO method. This is a wrapper round the platform's TCP/IP socket accept routines.

Using accept BIOs, TCP/IP connections can be accepted and data transferred using only BIO routines. In this way any platform specific operations are hidden by the BIO abstraction.

Read and write operations on an accept BIO will perform I/O on the underlying connection. If no connection is established and the port (see below) is set up properly then the BIO waits for an incoming connection.

Accept BIOs support BIO_puts() but not BIO_gets().

If the close flag is set on an accept BIO then any active connection on that chain is shutdown and the socket closed when the BIO is freed.

Calling BIO_reset() on a accept BIO will close any active connection and reset the BIO into a state where it awaits another incoming connection.

BIO_get_fd() and BIO_set_fd() can be called to retrieve or set the accept socket. See BIO_s_fd()

BIO_set_accept_port() uses the string name to set the accept port. The port is represented as a string of the form ``host:port'', where ``host'' is the interface to use and ``port'' is the port. Either or both values can be ``*'' which is interpreted as meaning any interface or port respectively. ``port'' has the same syntax as the port specified in BIO_set_conn_port() for connect BIOs, that is it can be a numerical port string or a string to lookup using getservbyname() and a string table.

BIO_new_accept()
combines BIO_new() and
BIO_set_accept_port() into
a single call: that is it creates a new accept BIO with port
host_port.

BIO_set_nbio_accept() sets the accept socket to blocking mode (the default) if n is 0 or non blocking mode if n is 1.

BIO_set_accept_bios() can be used to set a chain of BIOs which will be duplicated and prepended to the chain when an incoming connection is received. This is useful if, for example, a buffering or SSL BIO is required for each connection. The chain of BIOs must not be freed after this call, they will be automatically freed when the accept BIO is freed.

BIO_set_bind_mode() and BIO_get_bind_mode() set and retrieve the current bind mode. If BIO_BIND_NORMAL (the default) is set then another socket cannot be bound to the same port. If BIO_BIND_REUSEADDR is set then other sockets can bind to the same port. If BIO_BIND_REUSEADDR_IF_UNUSED is set then and attempt is first made to use BIO_BIN_NORMAL, if this fails and the port is not in use then a second attempt is made using BIO_BIND_REUSEADDR.

BIO_do_accept() serves two functions. When it is first called, after the accept BIO has been setup, it will attempt to create the accept socket and bind an address to it. Second and subsequent calls to BIO_do_accept() will await an incoming connection, or request a retry in non blocking mode.

Examples

This example accepts two connections on port 4444, sends messages down each and finally closes both down.
 BIO *abio, *cbio, *cbio2;
 ERR_load_crypto_strings();
 abio = BIO_new_accept("4444");
 /* First call to BIO_accept() sets up accept BIO */
 if(BIO_do_accept(abio) <= 0) {
        fprintf(stderr, "Error setting up accept\n");
        ERR_print_errors_fp(stderr);
        exit(0);
 }
 /* Wait for incoming connection */
 if(BIO_do_accept(abio) <= 0) {
        fprintf(stderr, "Error accepting connection\n");
        ERR_print_errors_fp(stderr);
        exit(0);
 }
 fprintf(stderr, "Connection 1 established\n");
 /* Retrieve BIO for connection */
 cbio = BIO_pop(abio);
 BIO_puts(cbio, "Connection 1: Sending out Data on initial connection\n");
 fprintf(stderr, "Sent out data on connection 1\n");
 /* Wait for another connection */
 if(BIO_do_accept(abio) <= 0) {
        fprintf(stderr, "Error accepting connection\n");
        ERR_print_errors_fp(stderr);
        exit(0);
 }
 fprintf(stderr, "Connection 2 established\n");
 /* Close accept BIO to refuse further connections */
 cbio2 = BIO_pop(abio);
 BIO_free(abio);
 BIO_puts(cbio2, "Connection 2: Sending out Data on second\n");
 fprintf(stderr, "Sent out data on connection 2\n");
 BIO_puts(cbio, "Connection 1: Second connection established\n");
 /* Close the two established connections */
 BIO_free(cbio);
 BIO_free(cbio2);

Notes

When an accept BIO is at the end of a chain it will await an incoming connection before processing I/O calls. When an accept BIO is not at then end of a chain it passes I/O calls to the next BIO in the chain.

When a connection is established a new socket BIO is created for the connection and appended to the chain. That is the chain is now accept->socket. This effectively means that attempting I/O on an initial accept socket will await an incoming connection then perform I/O on it.

If any additional BIOs have been set using BIO_set_accept_bios() then they are placed between the socket and the accept BIO, that is the chain will be accept->otherbios->socket.

If a server wishes to process multiple connections (as is normally the case) then the accept BIO must be made available for further incoming connections. This can be done by waiting for a connection and then calling:

 connection = BIO_pop(accept);

After this call connection will contain a BIO for the recently established connection and accept will now be a single BIO again which can be used to await further incoming connections. If no further connections will be accepted the accept can be freed using BIO_free().

If only a single connection will be processed it is possible to perform I/O using the accept BIO itself. This is often undesirable however because the accept BIO will still accept additional incoming connections. This can be resolved by using BIO_pop() (see above) and freeing up the accept BIO after the initial connection.

If the underlying accept socket is non-blocking and BIO_do_accept() is called to await an incoming connection it is possible for BIO_should_io_special() with the reason BIO_RR_ACCEPT. If this happens then it is an indication that an accept attempt would block: the application should take appropriate action to wait until the underlying socket has accepted a connection and retry the call.

BIO_set_accept_port(), BIO_get_accept_port(), BIO_set_nbio_accept(), BIO_set_accept_bios(), BIO_set_bind_mode(), BIO_get_bind_mode() and BIO_do_accept() are macros.

Return Values

TBA

See Also

TBA

Feedback

For additional information or queries on this page send feedback


BIO_ctrl_reset_read_request - BIO pair BIO

Name

BIO_s_bio, BIO_make_bio_pair
BIO_destroy_bio_pair, BIO_shutdown_wr
BIO_set_write_buf_size, BIO_get_write_buf_size,
BIO_new_bio_pair, BIO_get_write_guarantee,
BIO_ctrl_get_write_guarantee, BIO_get_read_request,
BIO_ctrl_get_read_request, BIO_ctrl_reset_read_request

BIO pair BIO

Library

libcrypto.lib

Synopsis

#include <openssl/bio.h>
BIO_METHOD *BIO_s_bio(void);
#define BIO_make_bio_pair(b1,b2)   (int)BIO_ctrl(b1,BIO_C_MAKE_BIO_PAIR,0,b2)
#define BIO_destroy_bio_pair(b)    (int)BIO_ctrl(b,BIO_C_DESTROY_BIO_PAIR,0,NULL)
#define BIO_shutdown_wr(b) (int)BIO_ctrl(b, BIO_C_SHUTDOWN_WR, 0, NULL)
#define BIO_set_write_buf_size(b,size) (int)BIO_ctrl(b,BIO_C_SET_WRITE_BUF_SIZE,size,NULL)
#define BIO_get_write_buf_size(b,size) (size_t)BIO_ctrl(b,BIO_C_GET_WRITE_BUF_SIZE,size,NULL)
int BIO_new_bio_pair(BIO **bio1, size_t writebuf1, BIO **bio2, size_t writebuf2);
#define BIO_get_write_guarantee(b) (int)BIO_ctrl(b,BIO_C_GET_WRITE_GUARANTEE,0,NULL)
size_t BIO_ctrl_get_write_guarantee(BIO *b);
#define BIO_get_read_request(b)    (int)BIO_ctrl(b,BIO_C_GET_READ_REQUEST,0,NULL)
size_t BIO_ctrl_get_read_request(BIO *b);
int BIO_ctrl_reset_read_request(BIO *b);

Detailed Description

BIO_s_bio() returns the method for a BIO pair. A BIO pair is a pair of source/sink BIOs where data written to either half of the pair is buffered and can be read from the other half. Both halves must usually by handled by the same application thread since no locking is done on the internal data structures.

Since BIO chains typically end in a source/sink BIO it is possible to make this one half of a BIO pair and have all the data processed by the chain under application control.

One typical use of BIO pairs is to place TLS/SSL I/O under application control, this can be used when the application wishes to use a non standard transport for TLS/SSL or the normal socket routines are inappropriate.

Calls to BIO_read() will read data from the buffer or request a retry if no data is available.

Calls to BIO_write() will place data in the buffer or request a retry if the buffer is full.

The standard calls BIO_ctrl_pending() and BIO_ctrl_wpending() can be used to determine the amount of pending data in the read or write buffer.

BIO_reset() clears any data in the write buffer.

BIO_make_bio_pair() joins two separate BIOs into a connected pair.

BIO_destroy_pair() destroys the association between two connected BIOs. Freeing up any half of the pair will automatically destroy the association.

BIO_shutdown_wr() is used to close down a BIO b. After this call no further writes on BIO b are allowed (they will return an error). Reads on the other half of the pair will return any pending data or EOF when all pending data has been read.

BIO_set_write_buf_size() sets the write buffer size of BIO b to size. If the size is not initialized a default value is used. This is currently 17K, sufficient for a maximum size TLS record.

BIO_get_write_buf_size() returns the size of the write buffer.

BIO_new_bio_pair() combines the calls to BIO_new(), BIO_make_bio_pair() and BIO_set_write_buf_size() to create a connected pair of BIOs bio1, bio2 with write buffer sizes writebuf1 and writebuf2. If either size is zero then the default size is used. BIO_new_bio_pair() does not check whether bio1 or bio2 do point to some other BIO, the values are overwritten, BIO_free() is not called.

BIO_get_write_guarantee() and BIO_ctrl_get_write_guarantee() return the maximum length of data that can be currently written to the BIO. Writes larger than this value will return a value from BIO_write() less than the amount requested or if the buffer is full request a retry. BIO_ctrl_get_write_guarantee() is a function whereas BIO_get_write_guarantee() is a macro.

BIO_get_read_request() and BIO_ctrl_get_read_request() return the amount of data requested, or the buffer size if it is less, if the last read attempt at the other half of the BIO pair failed due to an empty buffer. This can be used to determine how much data should be written to the BIO so the next read will succeed: this is most useful in TLS/SSL applications where the amount of data read is usually meaningful rather than just a buffer size. After a successful read this call will return zero. It also will return zero once new data has been written satisfying the read request or part of it. Note that BIO_get_read_request() never returns an amount larger than that returned by BIO_get_write_guarantee().

BIO_ctrl_reset_read_request() can also be used to reset the value returned by BIO_get_read_request() to zero.

Examples

The BIO pair can be used to have full control over the network access of an application. The application can call select() on the socket as required without having to go through the SSL-interface.
 BIO *internal_bio, *network_bio;
 ...
 BIO_new_bio_pair(internal_bio, 0, network_bio, 0);
 SSL_set_bio(ssl, internal_bio, internal_bio);
 SSL_operations();
 ...
 application |   TLS-engine
    |        |
    +----------> SSL_operations()
             |     /\    ||
             |     ||    \/
             |   BIO-pair (internal_bio)
    +----------< BIO-pair (network_bio)
    |        |
  socket     |
  ...
  SSL_free(ssl);                /* implicitly frees internal_bio */
  BIO_free(network_bio);
  ...

As the BIO pair will only buffer the data and never directly access the connection, it behaves non-blocking and will return as soon as the write buffer is full or the read buffer is drained. Then the application has to flush the write buffer and/or fill the read buffer.

Use the BIO_ctrl_pending(), to find out whether data is buffered in the BIO and must be transferred to the network. Use BIO_ctrl_get_read_request() to find out, how many bytes must be written into the buffer before the SSL_operation() can successfully be continued.

Notes

Both halves of a BIO pair should be freed. That is even if one half is implicit freed due to a BIO_free_all() or SSL_free() call the other half needs to be freed.

When used in bidirectional applications (such as TLS/SSL) care should be taken to flush any data in the write buffer. This can be done by calling BIO_pending() on the other half of the pair and, if any data is pending, reading it and sending it to the underlying transport. This must be done before any normal processing (such as calling select() ) due to a request and BIO_should_read() being true.

To see why this is important consider a case where a request is sent using BIO_write() and a response read with BIO_read(), this can occur during an TLS/SSL handshake for example. BIO_write() will succeed and place data in the write buffer. BIO_read() will initially fail and BIO_should_read() will be true. If the application then waits for data to be available on the underlying transport before flushing the write buffer it will never succeed because the request was never sent.

Return Values

BIO_new_bio_pair() returns 1 on success, with the new BIOs available in bio1 and bio2, or 0 on failure, with NULL pointers stored into the locations for bio1 and bio2. Check the error stack for more information.

[XXXXX: More return values need to be added here]

Warnings

As the data is buffered, SSL_operation() may return with a ERROR_SSL_WANT_READ condition, but there is still data in the write buffer. An application must not rely on the error value of SSL_operation() but must assure that the write buffer is always flushed first. Otherwise a deadlock may occur as the peer might be waiting for the data before being able to continue.

See Also

SSL_set_bio(),
ssl(),
bio(),
BIO_should_retry(),
BIO_read()

Feedback

For additional information or queries on this page send feedback


BIO_do_connect - connect BIO

Name

BIO_s_connect, BIO_set_conn_hostname
BIO_set_conn_port, BIO_set_conn_ip
BIO_set_conn_int_port, BIO_get_conn_hostname
BIO_get_conn_port, BIO_get_conn_ip
BIO_get_conn_int_port, BIO_set_nbio
BIO_do_connect

connect BIO

Library

libcrypto.lib

Synopsis

#include <openssl/bio.h>
BIO_METHOD * BIO_s_connect(void);
BIO *BIO_new_connect(char *name);
long BIO_set_conn_hostname(BIO *b, char *name);
long BIO_set_conn_port(BIO *b, char *port);
long BIO_set_conn_ip(BIO *b, char *ip);
long BIO_set_conn_int_port(BIO *b, char *port);
char *BIO_get_conn_hostname(BIO *b);
char *BIO_get_conn_port(BIO *b);
char *BIO_get_conn_ip(BIO *b, dummy);
long BIO_get_conn_int_port(BIO *b, int port);
long BIO_set_nbio(BIO *b, long n);
int BIO_do_connect(BIO *b);

Detailed Description

BIO_s_connect() returns the connect BIO method. This is a wrapper round the platform's TCP/IP socket connection routines.

Using connect BIOs, TCP/IP connections can be made and data transferred using only BIO routines. In this way any platform specific operations are hidden by the BIO abstraction.

Read and write operations on a connect BIO will perform I/O on the underlying connection. If no connection is established and the port and hostname (see below) is set up properly then a connection is established first.

Connect BIOs support BIO_puts() but not BIO_gets().

If the close flag is set on a connect BIO then any active connection is shutdown and the socket closed when the BIO is freed.

Calling BIO_reset() on a connect BIO will close any active connection and reset the BIO into a state where it can connect to the same host again.

BIO_get_fd() places the underlying socket in c if it is not NULL, it also returns the socket . If c is not NULL it should be of type (int *).

BIO_set_conn_hostname() uses the string name to set the hostname. The hostname can be an IP address. The hostname can also include the port in the form hostname:port . It is also acceptable to use the form ``hostname/any/other/path'' or ``hostname:port/any/other/path''.

BIO_set_conn_port() sets the port to port. port can be the numerical form or a string such as ``http''. A string will be looked up first using getservbyname() on the host platform but if that fails a standard table of port names will be used. Currently the list is http, telnet, socks, https, ssl, ftp, gopher and wais.

BIO_set_conn_ip() sets the IP address to ip using binary form, that is four bytes specifying the IP address in big-endian form.

BIO_set_conn_int_port() sets the port using port. port should be of type (int *).

BIO_get_conn_hostname() returns the hostname of the connect BIO or NULL if the BIO is initialized but no hostname is set. This return value is an internal pointer which should not be modified.

BIO_get_conn_port() returns the port as a string.

BIO_get_conn_ip() returns the IP address in binary form.

BIO_get_conn_int_port() returns the port as an int.

BIO_set_nbio() sets the non blocking I/O flag to n. If n is zero then blocking I/O is set. If n is 1 then non blocking I/O is set. Blocking I/O is the default. The call to BIO_set_nbio() should be made before the connection is established because non blocking I/O is set during the connect process.

BIO_new_connect()
combines BIO_new()
and BIO_set_conn_hostname()
into
a single call: that is it creates a new connect BIO with name.

BIO_do_connect() attempts to connect the supplied BIO. It returns 1 if the connection was established successfully. A zero or negative value is returned if the connection could not be established, the call BIO_should_retry() should be used for non blocking connect BIOs to determine if the call should be retried.

Examples

This is example connects to a web server on the local host and attempts to retrieve a page and copy the result to standard output.
 BIO *cbio, *out;
 int len;
 char tmpbuf[1024];
 ERR_load_crypto_strings();
 cbio = BIO_new_connect("localhost:http");
 out = BIO_new_fp(stdout, BIO_NOCLOSE);
 if(BIO_do_connect(cbio) <= 0) {
        fprintf(stderr, "Error connecting to server\n");
        ERR_print_errors_fp(stderr);
        /* whatever ... */
        }
 BIO_puts(cbio, "GET / HTTP/1.0\n\n");
 for(;;) {
        len = BIO_read(cbio, tmpbuf, 1024);
        if(len <= 0) break;
        BIO_write(out, tmpbuf, len);
 }
 BIO_free(cbio);
 BIO_free(out);

Notes

If blocking I/O is set then a non positive return value from any I/O call is caused by an error condition, although a zero return will normally mean that the connection was closed.

If the port name is supplied as part of the host name then this will override any value set with BIO_set_conn_port(). This may be undesirable if the application does not wish to allow connection to arbitrary ports. This can be avoided by checking for the presence of the ':' character in the passed hostname and either indicating an error or truncating the string at that point.

The values returned by BIO_get_conn_hostname(), BIO_get_conn_port(),
BIO_get_conn_ip() and
BIO_get_conn_int_port() are updated when a
connection attempt is made. Before any connection attempt the values
returned are those set by the application itself.

Applications do not have to call BIO_do_connect() but may wish to do so to separate the connection process from other I/O processing.

If non blocking I/O is set then retries will be requested as appropriate.

It addition to BIO_should_read() and BIO_should_write() it is also possible for BIO_should_io_special() to be true during the initial connection process with the reason BIO_RR_CONNECT. If this is returned then this is an indication that a connection attempt would block, the application should then take appropriate action to wait until the underlying socket has connected and retry the call.

BIO_set_conn_hostname(), BIO_set_conn_port(), BIO_set_conn_ip(),
BIO_set_conn_int_port(), BIO_get_conn_hostname(), BIO_get_conn_port(),
BIO_get_conn_ip(), BIO_get_conn_int_port(), BIO_set_nbio()and
BIO_do_connect() are macros.

Return Values

BIO_s_connect() returns the connect BIO method.

BIO_get_fd() returns the socket or -1 if the BIO has not been initialized.

BIO_set_conn_hostname(), BIO_set_conn_port(),
BIO_set_conn_ip() and
BIO_set_conn_int_port()
always return 1.

BIO_get_conn_hostname() returns the connected hostname or NULL is none was set.

BIO_get_conn_port() returns a string representing the connected port or NULL if not set.

BIO_get_conn_ip() returns a pointer to the connected IP address in binary form or all zeros if not set.

BIO_get_conn_int_port() returns the connected port or 0 if none was set.

BIO_set_nbio() always returns 1.

BIO_do_connect() returns 1 if the connection was successfully established and 0 or -1 if the connection failed.

See Also

TBA

Feedback

For additional information or queries on this page send feedback


BIO_new_fd - file descriptor BIO

Name

BIO_s_fd, BIO_set_fd
BIO_get_fd, BIO_new_fd

file descriptor BIO

Library

libcrypto.lib

Synopsis

#include <openssl/bio.h>
BIO_METHOD *   BIO_s_fd(void);
#define BIO_set_fd(b,fd,c)     BIO_int_ctrl(b,BIO_C_SET_FD,c,fd)
#define BIO_get_fd(b,c)        BIO_ctrl(b,BIO_C_GET_FD,0,(char *)c)
BIO *BIO_new_fd(int fd, int close_flag);

Detailed Description

BIO_s_fd() returns the file descriptor BIO method. This is a wrapper round the platforms file descriptor routines such as read() and write().

BIO_read() and BIO_write() read or write the underlying descriptor. BIO_puts() is supported but BIO_gets() is not.

If the close flag is set then then close() is called on the underlying file descriptor when the BIO is freed.

BIO_reset() attempts to change the file pointer to the start of file using lseek(fd, 0, 0).

BIO_seek() sets the file pointer to position ofs from start of file using lseek(fd, ofs, 0).

BIO_tell() returns the current file position by calling lseek(fd, 0, 1).

BIO_set_fd() sets the file descriptor of BIO b to fd and the close flag to c.

BIO_get_fd() places the file descriptor in c if it is not NULL, it also returns the file descriptor. If c is not NULL it should be of type (int *).

BIO_new_fd() returns a file descriptor BIO using fd and close_flag.

Examples

This is a file descriptor BIO version of ``Hello World'':
 BIO *out;
 out = BIO_new_fd(fileno(stdout), BIO_NOCLOSE);
 BIO_printf(out, "Hello World\n");
 BIO_free(out);

Notes

The behaviour of BIO_read() and BIO_write() depends on the behavior of the platforms read() and write() calls on the descriptor. If the underlying file descriptor is in a non blocking mode then the BIO will behave in the manner described in the BIO_read() and BIO_should_retry() manual pages.

File descriptor BIOs should not be used for socket I/O. Use socket BIOs instead.

Return Values

BIO_s_fd() returns the file descriptor BIO method.

BIO_reset() returns zero for success and -1 if an error occurred. BIO_seek() and BIO_tell() return the current file position or -1 is an error occurred. These values reflect the underlying lseek() behaviour.

BIO_set_fd() always returns 1.

BIO_get_fd() returns the file descriptor or -1 if the BIO has not been initialized.

BIO_new_fd() returns the newly allocated BIO or NULL is an error occurred.

See Also

BIO_seek(), BIO_tell(),
BIO_reset(), BIO_read(),
BIO_write(), BIO_puts(),
BIO_gets(), BIO_printf(),
BIO_set_close(), BIO_get_close()

Feedback

For additional information or queries on this page send feedback


BIO_rw_filename - FILE bio

Name

BIO_s_file, BIO_new_file
BIO_new_fp, BIO_set_fp
BIO_get_fp, BIO_read_filename
BIO_write_filename, BIO_append_filename
BIO_rw_filename

FILE bio

Library

libcrypto.lib

Synopsis

#include <openssl/bio.h>
BIO_METHOD *   BIO_s_file(void);
BIO *BIO_new_file(const char *filename, const char *mode);
BIO *BIO_new_fp(FILE *stream, int flags);
BIO_set_fp(BIO *b,FILE *fp, int flags);
BIO_get_fp(BIO *b,FILE **fpp);
int BIO_read_filename(BIO *b, char *name)
int BIO_write_filename(BIO *b, char *name)
int BIO_append_filename(BIO *b, char *name)
int BIO_rw_filename(BIO *b, char *name)

Detailed Description

BIO_s_file() returns the BIO file method. As its name implies it is a wrapper round the stdio FILE structure and it is a source/sink BIO.

Calls to BIO_read() and BIO_write() read and write data to the underlying stream. BIO_gets() and BIO_puts() are supported on file BIOs.

BIO_flush() on a file BIO calls the fflush() function on the wrapped stream.

BIO_reset() attempts to change the file pointer to the start of file using fseek(stream, 0, 0).

BIO_seek() sets the file pointer to position ofs from start of file using fseek(stream, ofs, 0).

BIO_eof() calls feof().

Setting the BIO_CLOSE flag calls fclose() on the stream when the BIO is freed.

BIO_new_file() creates a new file BIO with mode mode the meaning of mode is the same as the stdio function fopen(). The BIO_CLOSE flag is set on the returned BIO.

BIO_new_fp() creates a file BIO wrapping stream. Flags can be: BIO_CLOSE, BIO_NOCLOSE (the close flag) BIO_FP_TEXT (sets the underlying stream to text mode, default is binary: this only has any effect under Win32).

BIO_set_fp() set the fp of a file BIO to fp. flags has the same meaning as in BIO_new_fp(), it is a macro.

BIO_get_fp() retrieves the fp of a file BIO, it is a macro.

BIO_seek() is a macro that sets the position pointer to offset bytes from the start of file.

BIO_tell() returns the value of the position pointer.

BIO_read_filename(), BIO_write_filename(), BIO_append_filename() and BIO_rw_filename() set the file BIO b to use file name for reading, writing, append or read write respectively.

Examples

File BIO ``hello world'':
 BIO *bio_out;
 bio_out = BIO_new_fp(stdout, BIO_NOCLOSE);
 BIO_printf(bio_out, "Hello World\n");

Alternative technique:

 BIO *bio_out;
 bio_out = BIO_new(BIO_s_file());
 if(bio_out == NULL) /* Error ... */
 if(!BIO_set_fp(bio_out, stdout, BIO_NOCLOSE)) /* Error ... */
 BIO_printf(bio_out, "Hello World\n");

Write to a file:

 BIO *out;
 out = BIO_new_file("filename.txt", "w");
 if(!out) /* Error occurred */
 BIO_printf(out, "Hello World\n");
 BIO_free(out);

Alternative technique:

 BIO *out;
 out = BIO_new(BIO_s_file());
 if(out == NULL) /* Error ... */
 if(!BIO_write_filename(out, "filename.txt")) /* Error ... */
 BIO_printf(out, "Hello World\n");
 BIO_free(out);

Notes

When wrapping stdout, stdin or stderr the underlying stream should not normally be closed so the BIO_NOCLOSE flag should be set.

Because the file BIO calls the underlying stdio functions any quirks in stdio behaviour will be mirrored by the corresponding BIO.

Return Values

BIO_s_file() returns the file BIO method.

BIO_new_file() and BIO_new_fp() return a file BIO or NULL if an error occurred.

BIO_set_fp() and BIO_get_fp() return 1 for success or 0 for failure (although the current implementation never return 0).

BIO_seek() returns the same value as the underlying fseek() function: 0 for success or -1 for failure.

BIO_tell() returns the current file position.

BIO_read_filename(), BIO_write_filename(), BIO_append_filename() and BIO_rw_filename() return 1 for success or 0 for failure.

Bugs

BIO_reset() and BIO_seek() are implemented using fseek() on the underlying stream. The return value for fseek() is 0 for success or -1 if an error occurred this differs from other types of BIO which will typically return 1 for success and a non positive value if an error occurred.

See Also

BIO_seek(), BIO_tell(),
BIO_reset(), BIO_flush(),
BIO_read(),
BIO_write(), BIO_puts(),
BIO_gets(), BIO_printf(),
BIO_set_close(), BIO_get_close()

Feedback

For additional information or queries on this page send feedback


BIO_new_mem_buf - memory BIO

Name

BIO_s_mem, BIO_set_mem_eof_return
BIO_get_mem_data, BIO_set_mem_buf
BIO_get_mem_ptr, BIO_new_mem_buf

memory BIO

Library

libcrypto.lib

Synopsis

#include <openssl/bio.h>
BIO_METHOD *   BIO_s_mem(void);
BIO_set_mem_eof_return(BIO *b,int v)
long BIO_get_mem_data(BIO *b, char **pp)
BIO_set_mem_buf(BIO *b,BUF_MEM *bm,int c)
BIO_get_mem_ptr(BIO *b,BUF_MEM **pp)
BIO *BIO_new_mem_buf(void *buf, int len);

Detailed Description

BIO_s_mem() return the memory BIO method function.

A memory BIO is a source/sink BIO which uses memory for its I/O. Data written to a memory BIO is stored in a BUF_MEM structure which is extended as appropriate to accommodate the stored data.

Any data written to a memory BIO can be recalled by reading from it. Unless the memory BIO is read only any data read from it is deleted from the BIO.

Memory BIOs support BIO_gets()and BIO_puts().

If the BIO_CLOSE flag is set when a memory BIO is freed then the underlying BUF_MEM structure is also freed.

Calling BIO_reset() on a read write memory BIO clears any data in it. On a read only BIO it restores the BIO to its original state and the read only data can be read again.

BIO_eof() is true if no data is in the BIO.

BIO_ctrl_pending() returns the number of bytes currently stored.

BIO_set_mem_eof_return() sets the behaviour of memory BIO b when it is empty. If the v is zero then an empty memory BIO will return EOF (that is it will return zero and BIO_should_retry(b) will be false. If v is non zero then it will return v when it is empty and it will set the read retry flag (that is BIO_read_retry(b) is true). To avoid ambiguity with a normal positive return value v should be set to a negative value, typically -1.

BIO_get_mem_data() sets pp to a pointer to the start of the memory BIOs data and returns the total amount of data available. It is implemented as a macro.

BIO_set_mem_buf() sets the internal BUF_MEM structure to bm and sets the close flag to c, that is c should be either BIO_CLOSE or BIO_NOCLOSE. It is a macro.

BIO_get_mem_ptr() places the underlying BUF_MEM structure in pp. It is a macro.

BIO_new_mem_buf() creates a memory BIO using len bytes of data at buf, if len is -1 then the buf is assumed to be null terminated and its length is determined by strlen. The BIO is set to a read only state and as a result cannot be written to. This is useful when some data needs to be made available from a static area of memory in the form of a BIO. The supplied data is read directly from the supplied buffer: it is not copied first, so the supplied area of memory must be unchanged until the BIO is freed.

Examples

Create a memory BIO and write some data to it:
 BIO *mem = BIO_new(BIO_s_mem());
 BIO_puts(mem, "Hello World\n");

Create a read only memory BIO:

 char data[] = "Hello World";
 BIO *mem;
 mem = BIO_new_mem_buf(data, -1);

Extract the BUF_MEM structure from a memory BIO and then free up the BIO:

 BUF_MEM *bptr;
 BIO_get_mem_ptr(mem, &bptr);
 BIO_set_close(mem, BIO_NOCLOSE); /* So BIO_free() leaves BUF_MEM alone */
 BIO_free(mem);

Notes

Writes to memory BIOs will always succeed if memory is available: that is their size can grow indefinitely.

Every read from a read write memory BIO will remove the data just read with an internal copy operation, if a BIO contains a lots of data and it is read in small chunks the operation can be very slow. The use of a read only memory BIO avoids this problem. If the BIO must be read write then adding a buffering BIO to the chain will speed up the process.

Bugs

There should be an option to set the maximum size of a memory BIO.

There should be a way to "rewind'' a read write BIO without destroying its contents.

The copying operation should not occur after every small read of a large BIO to improve efficiency.

See Also

TBA

Feedback

For additional information or queries on this page send feedback


BIO_s_null - null data sink

Name

BIO_s_null — null data sink

Library

libcrypto.lib

Synopsis

#include <openssl/bio.h>
BIO_METHOD *  BIO_s_null(void);

Detailed Description

BIO_s_null() returns the null sink BIO method. Data written to the null sink is discarded, reads return EOF.

Notes

A null sink BIO behaves in a similar manner to the Unix /dev/null device.

A null bio can be placed on the end of a chain to discard any data passed through it.

A null sink is useful if, for example, an application wishes to digest some data by writing through a digest bio but not send the digested data anywhere. Since a BIO chain must normally include a source/sink BIO this can be achieved by adding a null sink BIO to the end of the chain.

Return Values

BIO_s_null() returns the null sink BIO method.

See Also

TBA

Feedback

For additional information or queries on this page send feedback


BIO_new_socket - socket BIO

Name

BIO_s_socket, BIO_new_socket — socket BIO

Library

libcrypto.lib

Synopsis

#include <openssl/bio.h>
BIO_METHOD *BIO_s_socket(void);
long BIO_set_fd(BIO *b, int fd, long close_flag);
long BIO_get_fd(BIO *b, int *c);
BIO *BIO_new_socket(int sock, int close_flag);

Detailed Description

BIO_s_socket() returns the socket BIO method. This is a wrapper round the platform's socket routines.

BIO_read() and BIO_write() read or write the underlying socket. BIO_puts() is supported but BIO_gets() is not.

If the close flag is set then the socket is shut down and closed when the BIO is freed.

BIO_set_fd() sets the socket of BIO b to fd and the close flag to close_flag.

BIO_get_fd() places the socket in c if it is not NULL, it also returns the socket. If c is not NULL it should be of type (int *).

BIO_new_socket() returns a socket BIO using sock and close_flag.

Notes

Socket BIOs also support any relevant functionality of file descriptor BIOs.

The reason for having separate file descriptor and socket BIOs is that on some platforms sockets are not file descriptors and use distinct I/O routines, Windows is one such platform. Any code mixing the two will not work on all platforms.

BIO_set_fd() and BIO_get_fd() are macros.

Return Values

BIO_s_socket() returns the socket BIO method.

BIO_set_fd() always returns 1.

BIO_get_fd() returns the socket or -1 if the BIO has not been initialized.

BIO_new_socket() returns the newly allocated BIO or NULL is an error occurred.

See Also

TBA

Feedback

For additional information or queries on this page send feedback


BIO_debug_callback - BIO callback functions

Name

BIO_set_callback, BIO_get_callback
BIO_set_callback_arg, BIO_get_callback_arg
BIO_debug_callback

BIO callback functions

Library

libcrypto.lib

Synopsis

#include <openssl/bio.h>
#define BIO_set_callback(b,cb)         ((b)->callback=(cb))
#define BIO_get_callback(b)            ((b)->callback)
#define BIO_set_callback_arg(b,arg)    ((b)->cb_arg=(char *)(arg))
#define BIO_get_callback_arg(b)        ((b)->cb_arg)
long BIO_debug_callback(BIO *bio,int cmd,const char *argp,int argi, long argl,long ret);
typedef long callback(BIO *b, int oper, const char *argp, int argi, long argl, long retvalue);

Detailed Description

BIO_set_callback() and BIO_get_callback() set and retrieve the BIO callback, they are both macros. The callback is called during most high level BIO operations. It can be used for debugging purposes to trace operations on a BIO or to modify its operation.

BIO_set_callback_arg() and BIO_get_callback_arg() are macros which can be used to set and retrieve an argument for use in the callback.

BIO_debug_callback() is a standard debugging callback which prints out information relating to each BIO operation. If the callback argument is set if is interpreted as a BIO to send the information to, otherwise stderr is used.

callback() is the callback function itself. The meaning of each argument is described below.

The BIO the callback is attached to is passed in b.

oper is set to the operation being performed. For some operations the callback is called twice, once before and once after the actual operation, the latter case has oper or'ed with BIO_CB_RETURN.

The meaning of the arguments argp, argi and argl depends on the value of oper, that is the operation being performed.

retvalue is the return value that would be returned to the application if no callback were present. The actual value returned is the return value of the callback itself. In the case of callbacks called before the actual BIO operation 1 is placed in retvalue, if the return value is not positive it will be immediately returned to the application and the BIO operation will not be performed.

The callback should normally simply return retvalue when it has finished processing, unless if specifically wishes to modify the value returned to the application.

Examples

The BIO_debug_callback() function is a good example, its source is in crypto/bio/bio_cb.c

Callback Operations

BIO_free(b)
callback(b, BIO_CB_FREE, NULL, 0L, 0L, 1L) is called before the free operation.

BIO_read(b, out, outl)
callback(b, BIO_CB_READ, out, outl, 0L, 1L) is called before the read and callback(b, BIO_CB_READ|BIO_CB_RETURN, out, outl, 0L, retvalue) after.

BIO_write(b, in, inl)
callback(b, BIO_CB_WRITE, in, inl, 0L, 1L) is called before the write and callback(b, BIO_CB_WRITE|BIO_CB_RETURN, in, inl, 0L, retvalue) after.

BIO_gets(b, out, outl)
callback(b, BIO_CB_GETS, out, outl, 0L, 1L) is called before the operation and callback(b, BIO_CB_GETS|BIO_CB_RETURN, out, outl, 0L, retvalue) after.

BIO_puts(b, in)
callback(b, BIO_CB_WRITE, in, 0, 0L, 1L) is called before the operation and callback(b, BIO_CB_WRITE|BIO_CB_RETURN, in, 0, 0L, retvalue) after.

BIO_ctrl(BIO *b, int cmd, long larg, void *parg)
callback(b,BIO_CB_CTRL,parg,cmd,larg,1L) is called before the call and callback(b,BIO_CB_CTRL|BIO_CB_RETURN,parg,cmd, larg,ret) after.

See Also

TBA

Feedback

For additional information or queries on this page send feedback


BIO_get_retry_reason - BIO retry functions

Name

BIO_should_retry, BIO_should_read
BIO_should_write, BIO_should_io_special
BIO_retry_type, BIO_get_retry_BIO
BIO_get_retry_reason

BIO retry functions

Library

libcrypto.lib

Synopsis

#include <openssl/bio.h>
#define BIO_should_read(a)             ((a)->flags & BIO_FLAGS_READ)
#define BIO_should_write(a)            ((a)->flags & BIO_FLAGS_WRITE)
#define BIO_should_io_special(a)       ((a)->flags & BIO_FLAGS_IO_SPECIAL)
#define BIO_retry_type(a)              ((a)->flags & BIO_FLAGS_RWS)
#define BIO_should_retry(a)            ((a)->flags & BIO_FLAGS_SHOULD_RETRY)
#define BIO_FLAGS_READ         0x01
#define BIO_FLAGS_WRITE        0x02
#define BIO_FLAGS_IO_SPECIAL   0x04
#define BIO_FLAGS_RWS (BIO_FLAGS_READ|BIO_FLAGS_WRITE|BIO_FLAGS_IO_SPECIAL)
#define BIO_FLAGS_SHOULD_RETRY 0x08
BIO *  BIO_get_retry_BIO(BIO *bio, int *reason);
int    BIO_get_retry_reason(BIO *bio);

Detailed Description

These functions determine why a BIO is not able to read or write data. They will typically be called after a failed BIO_read() or BIO_write() call.

BIO_should_retry() is true if the call that produced this condition should then be retried at a later time.

If BIO_should_retry() is false then the cause is an error condition.

BIO_should_read() is true if the cause of the condition is that a BIO needs to read data.

BIO_should_write() is true if the cause of the condition is that a BIO needs to read data.

BIO_should_io_special() is true if some ``special'' condition, that is a reason other than reading or writing is the cause of the condition.

BIO_get_retry_reason() returns a mask of the cause of a retry condition consisting of the values BIO_FLAGS_READ, BIO_FLAGS_WRITE, BIO_FLAGS_IO_SPECIAL though current BIO types will only set one of these.

BIO_get_retry_BIO() determines the precise reason for the special condition, it returns the BIO that caused this condition and if reason is not NULL it contains the reason code. The meaning of the reason code and the action that should be taken depends on the type of BIO that resulted in this condition.

BIO_get_retry_reason() returns the reason for a special condition if passed the relevant BIO, for example as returned by BIO_get_retry_BIO().

Notes

If BIO_should_retry() returns false then the precise ``error condition'' depends on the BIO type that caused it and the return code of the BIO operation. For example if a call to BIO_read() on a socket BIO returns 0 and BIO_should_retry() is false then the cause will be that the connection closed. A similar condition on a file BIO will mean that it has reached EOF. Some BIO types may place additional information on the error queue. For more details see the individual BIO type manual pages.

If the underlying I/O structure is in a blocking mode almost all current BIO types will not request a retry, because the underlying I/O calls will not. If the application knows that the BIO type will never signal a retry then it need not call BIO_should_retry() after a failed BIO I/O call. This is typically done with file BIOs.

SSL BIOs are the only current exception to this rule: they can request a retry even if the underlying I/O structure is blocking, if a handshake occurs during a call to BIO_read(). An application can retry the failed call immediately or avoid this situation by setting SSL_MODE_AUTO_RETRY on the underlying SSL structure.

While an application may retry a failed non blocking call immediately this is likely to be very inefficient because the call will fail repeatedly until data can be processed or is available. An application will normally wait until the necessary condition is satisfied. How this is done depends on the underlying I/O structure.

For example if the cause is ultimately a socket and BIO_should_read() is true then a call to select() may be made to wait until data is available and then retry the BIO operation. By combining the retry conditions of several non blocking BIOs in a single select() call it is possible to service several BIOs in a single thread, though the performance may be poor if SSL BIOs are present because long delays can occur during the initial handshake process.

It is possible for a BIO to block indefinitely if the underlying I/O structure cannot process or return any data. This depends on the behaviour of the platforms I/O functions. This is often not desirable: one solution is to use non blocking I/O and use a timeout on the select() (or equivalent) call.

Bugs

The OpenSSL ASN1 functions cannot gracefully deal with non blocking I/O: that is they cannot retry after a partial read or write. This is usually worked around by only passing the relevant data to ASN1 functions when the entire structure can be read or written.

See Also

TBA

Feedback

For additional information or queries on this page send feedback


bn - multiprecision integer arithmetics

Name

bn — multi-precision integer arithmetic functions

Library

libcrypto.lib

Synopsis

#include <openssl/bn.h>
BIGNUM *BN_new(void);
void BN_free(BIGNUM *a);
void BN_init(BIGNUM *);
void BN_clear(BIGNUM *a);
void BN_clear_free(BIGNUM *a);
BN_CTX *BN_CTX_new(void);
void BN_CTX_init(BN_CTX *c);
void BN_CTX_free(BN_CTX *c);
BIGNUM *BN_copy(BIGNUM *a, const BIGNUM *b);
BIGNUM *BN_dup(const BIGNUM *a);
BIGNUM *BN_swap(BIGNUM *a, BIGNUM *b);
int BN_num_bytes(const BIGNUM *a);
int BN_num_bits(const BIGNUM *a);
int BN_num_bits_word(BN_ULONG w);
void BN_set_negative(BIGNUM *a, int n);
int  BN_is_negative(const BIGNUM *a);
int BN_add(BIGNUM *r, const BIGNUM *a, const BIGNUM *b);
int BN_sub(BIGNUM *r, const BIGNUM *a, const BIGNUM *b);
int BN_mul(BIGNUM *r, BIGNUM *a, BIGNUM *b, BN_CTX *ctx);
int BN_sqr(BIGNUM *r, BIGNUM *a, BN_CTX *ctx);
int BN_div(BIGNUM *dv, BIGNUM *rem, const BIGNUM *a, const BIGNUM *d, BN_CTX *ctx);
int BN_mod(BIGNUM *rem, const BIGNUM *a, const BIGNUM *m, BN_CTX *ctx);
int BN_nnmod(BIGNUM *rem, const BIGNUM *a, const BIGNUM *m, BN_CTX *ctx);
int BN_mod_add(BIGNUM *ret, BIGNUM *a, BIGNUM *b, const BIGNUM *m, BN_CTX *ctx);
int BN_mod_sub(BIGNUM *ret, BIGNUM *a, BIGNUM *b, const BIGNUM *m, BN_CTX *ctx);
int BN_mod_mul(BIGNUM *ret, BIGNUM *a, BIGNUM *b, const BIGNUM *m, BN_CTX *ctx);
int BN_mod_sqr(BIGNUM *ret, BIGNUM *a, const BIGNUM *m, BN_CTX *ctx);
int BN_exp(BIGNUM *r, BIGNUM *a, BIGNUM *p, BN_CTX *ctx);
int BN_mod_exp(BIGNUM *r, BIGNUM *a, const BIGNUM *p, const BIGNUM *m, BN_CTX *ctx);
int BN_gcd(BIGNUM *r, BIGNUM *a, BIGNUM *b, BN_CTX *ctx);
int BN_add_word(BIGNUM *a, BN_ULONG w);
int BN_sub_word(BIGNUM *a, BN_ULONG w);
int BN_mul_word(BIGNUM *a, BN_ULONG w);
BN_ULONG BN_div_word(BIGNUM *a, BN_ULONG w);
BN_ULONG BN_mod_word(const BIGNUM *a, BN_ULONG w);
int BN_cmp(BIGNUM *a, BIGNUM *b);
int BN_ucmp(BIGNUM *a, BIGNUM *b);
int BN_is_zero(BIGNUM *a);
int BN_is_one(BIGNUM *a);
int BN_is_word(BIGNUM *a, BN_ULONG w);
int BN_is_odd(BIGNUM *a);
int BN_zero(BIGNUM *a);
int BN_one(BIGNUM *a);
const BIGNUM *BN_value_one(void);
int BN_set_word(BIGNUM *a, unsigned long w);
unsigned long BN_get_word(BIGNUM *a);
int BN_rand(BIGNUM *rnd, int bits, int top, int bottom);
int BN_pseudo_rand(BIGNUM *rnd, int bits, int top, int bottom);
int BN_rand_range(BIGNUM *rnd, BIGNUM *range);
int BN_pseudo_rand_range(BIGNUM *rnd, BIGNUM *range);
BIGNUM *BN_generate_prime(BIGNUM *ret, int bits,int safe, BIGNUM *add, BIGNUM *rem, void (*callback)(int, int, void *), void *cb_arg);
int BN_is_prime(const BIGNUM *p, int nchecks, void (*callback)(int, int, void *), BN_CTX *ctx, void *cb_arg);
int BN_set_bit(BIGNUM *a, int n);
int BN_clear_bit(BIGNUM *a, int n);
int BN_is_bit_set(const BIGNUM *a, int n);
int BN_mask_bits(BIGNUM *a, int n);
int BN_lshift(BIGNUM *r, const BIGNUM *a, int n);
int BN_lshift1(BIGNUM *r, BIGNUM *a);
int BN_rshift(BIGNUM *r, BIGNUM *a, int n);
int BN_rshift1(BIGNUM *r, BIGNUM *a);
int BN_bn2bin(const BIGNUM *a, unsigned char *to);
BIGNUM *BN_bin2bn(const unsigned char *s, int len, BIGNUM *ret);
char *BN_bn2hex(const BIGNUM *a);
char *BN_bn2dec(const BIGNUM *a);
int BN_hex2bn(BIGNUM **a, const char *str);
int BN_dec2bn(BIGNUM **a, const char *str);
int BN_print(BIO *fp, const BIGNUM *a);
int BN_print_fp(FILE *fp, const BIGNUM *a);
int BN_bn2mpi(const BIGNUM *a, unsigned char *to);
BIGNUM *BN_mpi2bn(unsigned char *s, int len, BIGNUM *ret);
BIGNUM *BN_mod_inverse(BIGNUM *r, BIGNUM *a, const BIGNUM *n, BN_CTX *ctx);
BN_RECP_CTX *BN_RECP_CTX_new(void);
void BN_RECP_CTX_init(BN_RECP_CTX *recp);
void BN_RECP_CTX_free(BN_RECP_CTX *recp);
int BN_RECP_CTX_set(BN_RECP_CTX *recp, const BIGNUM *m, BN_CTX *ctx);
int BN_mod_mul_reciprocal(BIGNUM *r, BIGNUM *a, BIGNUM *b, BN_RECP_CTX *recp, BN_CTX *ctx);
BN_MONT_CTX *BN_MONT_CTX_new(void);
void BN_MONT_CTX_init(BN_MONT_CTX *ctx);
void BN_MONT_CTX_free(BN_MONT_CTX *mont);
int BN_MONT_CTX_set(BN_MONT_CTX *mont, const BIGNUM *m, BN_CTX *ctx);
BN_MONT_CTX *BN_MONT_CTX_copy(BN_MONT_CTX *to, BN_MONT_CTX *from);
int BN_mod_mul_montgomery(BIGNUM *r, BIGNUM *a, BIGNUM *b, BN_MONT_CTX *mont, BN_CTX *ctx);
int BN_from_montgomery(BIGNUM *r, BIGNUM *a, BN_MONT_CTX *mont, BN_CTX *ctx);
int BN_to_montgomery(BIGNUM *r, BIGNUM *a, BN_MONT_CTX *mont, BN_CTX *ctx);
BN_BLINDING *BN_BLINDING_new(const BIGNUM *A, const BIGNUM *Ai, BIGNUM *mod);
void BN_BLINDING_free(BN_BLINDING *b);
int BN_BLINDING_update(BN_BLINDING *b,BN_CTX *ctx);
int BN_BLINDING_convert(BIGNUM *n, BN_BLINDING *b, BN_CTX *ctx);
int BN_BLINDING_invert(BIGNUM *n, BN_BLINDING *b, BN_CTX *ctx);
int BN_BLINDING_convert_ex(BIGNUM *n, BIGNUM *r, BN_BLINDING *b, BN_CTX *ctx);
int BN_BLINDING_invert_ex(BIGNUM *n,const BIGNUM *r,BN_BLINDING *b, BN_CTX *ctx);
unsigned long BN_BLINDING_get_thread_id(const BN_BLINDING *);
void BN_BLINDING_set_thread_id(BN_BLINDING *, unsigned long);
unsigned long BN_BLINDING_get_flags(const BN_BLINDING *);
void BN_BLINDING_set_flags(BN_BLINDING *, unsigned long);
BN_BLINDING *BN_BLINDING_create_param(BN_BLINDING *b, const BIGNUM *e, BIGNUM *m, BN_CTX *ctx,
int (*bn_mod_exp)(BIGNUM *r, const BIGNUM *a, const BIGNUM *p, const BIGNUM *m, BN_CTX *ctx, BN_MONT_CTX *m_ctx),
BN_MONT_CTX *m_ctx);

Detailed Description

This library performs arithmetic operations on integers of arbitrary size. It was written for use in public key cryptography, such as RSA and Diffie-Hellman.

It uses dynamic memory allocation for storing its data structures. That means that there is no limit on the size of the numbers manipulated by these functions, but return values must always be checked in case a memory allocation error has occurred.

The basic object in this library is a BIGNUM. It is used to hold a single large integer. This type should be considered opaque and fields should not be modified or accessed directly.

The creation of BIGNUM objects is described in BN_new(); BN_add() describes most of the arithmetic operations. Comparison is described in BN_cmp(); BN_zero() describes certain assignments, BN_rand() the generation of random numbers, BN_generate_prime() deals with prime numbers and BN_set_bit() with bit operations. The conversion of BIGNUMs to external formats is described in BN_bn2bin().

See Also

bn_internal(),
dh(), err(),
rand(), rsa(),
BN_new(), BN_CTX_new(),
BN_copy(), BN_swap(),
BN_num_bytes(),
BN_add(), BN_add_word(),
BN_cmp(), BN_zero(),
BN_rand(),
BN_generate_prime(),
BN_set_bit(),
BN_bn2bin(),
BN_mod_inverse(),
BN_mod_mul_reciprocal(),
BN_mod_mul_montgomery(),
BN_BLINDING_new()

Feedback

For additional information or queries on this page send feedback


BN_gcd - arithmetic operations on BIGNUMs

Name

BN_add, BN_sub, BN_mul
BN_sqr, BN_div, BN_mod
BN_nnmod, BN_mod_add
BN_mod_sub, BN_mod_mul
BN_mod_sqr, BN_exp
BN_mod_exp, BN_gcd

arithmetic operations on BIGNUMs

Library

libcrypto.lib

Synopsis

#include <openssl/bn.h>
int BN_add(BIGNUM *r, const BIGNUM *a, const BIGNUM *b);
int BN_sub(BIGNUM *r, const BIGNUM *a, const BIGNUM *b);
int BN_mul(BIGNUM *r, BIGNUM *a, BIGNUM *b, BN_CTX *ctx);
int BN_sqr(BIGNUM *r, BIGNUM *a, BN_CTX *ctx);
int BN_div(BIGNUM *dv, BIGNUM *rem, const BIGNUM *a, const BIGNUM *d, BN_CTX *ctx);
int BN_mod(BIGNUM *rem, const BIGNUM *a, const BIGNUM *m, BN_CTX *ctx);
int BN_nnmod(BIGNUM *r, const BIGNUM *a, const BIGNUM *m, BN_CTX *ctx);
int BN_mod_add(BIGNUM *r, BIGNUM *a, BIGNUM *b, const BIGNUM *m, BN_CTX *ctx);
int BN_mod_sub(BIGNUM *r, BIGNUM *a, BIGNUM *b, const BIGNUM *m, BN_CTX *ctx);
int BN_mod_mul(BIGNUM *r, BIGNUM *a, BIGNUM *b, const BIGNUM *m, BN_CTX *ctx);
int BN_mod_sqr(BIGNUM *r, BIGNUM *a, const BIGNUM *m, BN_CTX *ctx);
int BN_exp(BIGNUM *r, BIGNUM *a, BIGNUM *p, BN_CTX *ctx);
int BN_mod_exp(BIGNUM *r, BIGNUM *a, const BIGNUM *p, const BIGNUM *m, BN_CTX *ctx);
int BN_gcd(BIGNUM *r, BIGNUM *a, BIGNUM *b, BN_CTX *ctx);

Detailed Description

BN_add() adds a and b and places the result in r (r=a+b). r may be the same BIGNUM as a or b.

BN_sub() subtracts b from a and places the result in r (r=a-b).

BN_mul() multiplies a and b and places the result in r (r=a*b). r may be the same BIGNUM as a or b. For multiplication by powers of 2, use BN_lshift().

BN_sqr() takes the square of a and places the result in r (r=a^2). r and a may be the same BIGNUM. This function is faster than BN_mul(r,a,a).

BN_div() divides a by d and places the result in dv and the remainder in rem (dv=a/d, rem=a%d). Either of dv and rem may be NULL, in which case the respective value is not returned. The result is rounded towards zero; thus if a is negative, the remainder will be zero or negative. For division by powers of 2, use BN_rshift().

BN_mod() corresponds to BN_div() with dv set to NULL.

BN_nnmod() reduces a modulo m and places the non-negative remainder in r.

BN_mod_add() adds a to b modulo m and places the non-negative result in r.

BN_mod_sub() subtracts b from a modulo m and places the non-negative result in r.

BN_mod_mul() multiplies a by b and finds the non-negative remainder respective to modulus m (r=(a*b) mod m). r may be the same BIGNUM as a or b. For more efficient algorithms for repeated computations using the same modulus, see BN_mod_mul_montgomery() and BN_mod_mul_reciprocal().

BN_mod_sqr() takes the square of a modulo m and places the result in r.

BN_exp() raises a to the p-th power and places the result in r (r=a^p). This function is faster than repeated applications of BN_mul().

BN_mod_exp() computes a to the p-th power modulo m (r=a^p % m). This function uses less time and space than BN_exp().

BN_gcd() computes the greatest common divisor of a and b and places the result in r. r may be the same BIGNUM as a or b.

For all functions, ctx is a previously allocated BN_CTX used for temporary variables; see BN_CTX_new().

Unless noted otherwise, the result BIGNUM must be different from the arguments.

Return Values

For all functions, 1 is returned for success, 0 on error. The return value should always be checked (e.g., if (!BN_add(r,a,b)) goto err;). The error codes can be obtained by ERR_get_error().

See Also

bn(),
ERR_get_error(),
BN_CTX_new(),
BN_add_word(),
BN_set_bit()

History

BN_add(), BN_sub(), BN_sqr(), BN_div(), BN_mod(), BN_mod_mul(), BN_mod_exp() and BN_gcd() are available in all versions of SSLeay and OpenSSL. The ctx argument to BN_mul() was added in SSLeay 0.9.1b. BN_exp() appeared in SSLeay 0.9.0. BN_nnmod(), BN_mod_add(), BN_mod_sub(), and BN_mod_sqr() were added in OpenSSL 0.9.7.

Feedback

For additional information or queries on this page send feedback


BN_mod_word - arithmetic functions on BIGNUMs with integers

Name

BN_add_word, BN_sub_word
BN_mul_word, BN_div_word
BN_mod_word

arithmetic functions on BIGNUMs with integers

Library

libcrypto.lib

Synopsis

#include <openssl/bn.h>
int BN_add_word(BIGNUM *a, BN_ULONG w);
int BN_sub_word(BIGNUM *a, BN_ULONG w);
int BN_mul_word(BIGNUM *a, BN_ULONG w);
BN_ULONG BN_div_word(BIGNUM *a, BN_ULONG w);
BN_ULONG BN_mod_word(const BIGNUM *a, BN_ULONG w);

Detailed Description

These functions perform arithmetic operations on BIGNUMs with unsigned integers. They are much more efficient than the normal BIGNUM arithmetic operations.

BN_add_word() adds w to a (a+=w).

BN_sub_word() subtracts w from a (a-=w).

BN_mul_word() multiplies a and w (a*=w).

BN_div_word() divides a by w (a/=w) and returns the remainder.

BN_mod_word() returns the remainder of a divided by w (a%w).

For BN_div_word() and BN_mod_word(), w must not be 0.

Return Values

BN_add_word(), BN_sub_word() and BN_mul_word() return 1 for success, 0 on error. The error codes can be obtained by ERR_get_error().

BN_mod_word() and BN_div_word() return a%w on success and (BN_ULONG)-1 if an error occurred.

See Also

bn(),
ERR_get_error(),
BN_add()

History

BN_add_word() and BN_mod_word() are available in all versions of SSLeay and OpenSSL. BN_div_word() was added in SSLeay 0.8, and BN_sub_word() and BN_mul_word() in SSLeay 0.9.0.

Before 0.9.8a the return value for BN_div_word() and BN_mod_word() in case of an error was 0.

Feedback

For additional information or queries on this page send feedback


BN_BLINDING_create_param - blinding related BIGNUM functions.

Name

BN_BLINDING_new, BN_BLINDING_free
BN_BLINDING_update, BN_BLINDING_convert
BN_BLINDING_invert, BN_BLINDING_convert_ex
BN_BLINDING_invert_ex, BN_BLINDING_get_thread_id
BN_BLINDING_set_thread_id, BN_BLINDING_get_flags
BN_BLINDING_set_flags, BN_BLINDING_create_param

blinding related BIGNUM functions

Library

libcrypto.lib

Synopsis

#include <openssl/bn.h>
BN_BLINDING *BN_BLINDING_new(const BIGNUM *A, const BIGNUM *Ai, BIGNUM *mod);
void BN_BLINDING_free(BN_BLINDING *b);
int BN_BLINDING_update(BN_BLINDING *b,BN_CTX *ctx);
int BN_BLINDING_convert(BIGNUM *n, BN_BLINDING *b, BN_CTX *ctx);
int BN_BLINDING_invert(BIGNUM *n, BN_BLINDING *b, BN_CTX *ctx);
int BN_BLINDING_convert_ex(BIGNUM *n, BIGNUM *r, BN_BLINDING *b, BN_CTX *ctx);
int BN_BLINDING_invert_ex(BIGNUM *n, const BIGNUM *r, BN_BLINDING *b, BN_CTX *ctx);
unsigned long BN_BLINDING_get_thread_id(const BN_BLINDING *);
void BN_BLINDING_set_thread_id(BN_BLINDING *, unsigned long);
unsigned long BN_BLINDING_get_flags(const BN_BLINDING *);
void BN_BLINDING_set_flags(BN_BLINDING *, unsigned long);
BN_BLINDING *BN_BLINDING_create_param(BN_BLINDING *b, const BIGNUM *e, BIGNUM *m, BN_CTX *ctx,
int (*bn_mod_exp)(BIGNUM *r, const BIGNUM *a, const BIGNUM *p, const BIGNUM *m, BN_CTX *ctx, BN_MONT_CTX *m_ctx),
     BN_MONT_CTX *m_ctx);

Detailed Description

BN_BLINDING_new() allocates a new BN_BLINDING structure and copies the A and Ai values into the newly created BN_BLINDING object.

BN_BLINDING_free() frees the BN_BLINDING structure.

BN_BLINDING_update() updates the BN_BLINDING parameters by squaring the A and Ai or, after specific number of uses and if the necessary parameters are set, by re-creating the blinding parameters.

BN_BLINDING_convert_ex() multiplies n with the blinding factor A. If r is not NULL a copy the inverse blinding factor Ai will be returned in r (this is useful if a RSA object is shared among several threads). BN_BLINDING_invert_ex() multiplies n with the inverse blinding factor Ai. If r is not NULL it will be used as the inverse blinding.

BN_BLINDING_convert() and
 BN_BLINDING_invert() are wrapper
functions for  BN_BLINDING_convert_ex() and
 BN_BLINDING_invert_ex()
with r set to NULL.

BN_BLINDING_set_thread_id() and BN_BLINDING_get_thread_id() set and get the ``thread id'' value of the BN_BLINDING structure, a field provided to users of BN_BLINDING structure to help them provide proper locking if needed for multi-threaded use. The ``thread id'' of a newly allocated BN_BLINDING structure is zero.

BN_BLINDING_get_flags() returns the BN_BLINDING flags. Currently there are two supported flags: BN_BLINDING_NO_UPDATE and BN_BLINDING_NO_RECREATE. BN_BLINDING_NO_UPDATE inhibits the automatic update of the BN_BLINDING parameters after each use and BN_BLINDING_NO_RECREATE inhibits the automatic re-creation of the BN_BLINDING parameters after a fixed number of uses (currently 32). In newly allocated BN_BLINDING objects no flags are set. BN_BLINDING_set_flags() sets the BN_BLINDING parameters flags.

BN_BLINDING_create_param() creates new BN_BLINDING parameters using the exponent e and the modulus m. bn_mod_exp and m_ctx can be used to pass special functions for exponentiation (normally BN_mod_exp_mont() and BN_MONT_CTX).

Return Values

BN_BLINDING_new() returns the newly allocated BN_BLINDING structure or NULL in case of an error.

BN_BLINDING_update(), BN_BLINDING_convert(), BN_BLINDING_invert(),
BN_BLINDING_convert_ex() and
 BN_BLINDING_invert_ex() return 1 on
success and 0 if an error occurred.

BN_BLINDING_get_thread_id() returns the thread id (a unsigned long value) or 0 if not set.

BN_BLINDING_get_flags() returns the currently set BN_BLINDING flags (a unsigned long value).

BN_BLINDING_create_param() returns the newly created BN_BLINDING parameters or NULL on error.

See Also

bn()

History

BN_BLINDING_convert_ex, BN_BLINDIND_invert_ex, BN_BLINDING_get_thread_id, BN_BLINDING_set_thread_id, BN_BLINDING_set_flags, BN_BLINDING_get_flags and BN_BLINDING_create_param were first introduced in OpenSSL 0.9.8

Author

Nils Larsch for the OpenSSL project (http://www.openssl.org).

Feedback

For additional information or queries on this page send feedback


BN_mpi2bn - format conversions

Name

BN_bn2bin, BN_bin2bn
BN_bn2hex, BN_bn2dec
BN_hex2bn, BN_dec2bn
BN_print, BN_print_fp
BN_bn2mpi, BN_mpi2bn

format conversions

Library

libcrypto.lib

Synopsis

#include <openssl/bn.h>
int BN_bn2bin(const BIGNUM *a, unsigned char *to);
BIGNUM *BN_bin2bn(const unsigned char *s, int len, BIGNUM *ret);
char *BN_bn2hex(const BIGNUM *a);
char *BN_bn2dec(const BIGNUM *a);
int BN_hex2bn(BIGNUM **a, const char *str);
int BN_dec2bn(BIGNUM **a, const char *str);
int BN_print(BIO *fp, const BIGNUM *a);
int BN_print_fp(FILE *fp, const BIGNUM *a);
int BN_bn2mpi(const BIGNUM *a, unsigned char *to);
BIGNUM *BN_mpi2bn(unsigned char *s, int len, BIGNUM *ret);

Detailed Description

BN_bn2bin() converts the absolute value of a into big-endian form and stores it at to. to must point to BN_num_bytes(a) bytes of memory.

BN_bin2bn() converts the positive integer in big-endian form of length len at s into a BIGNUM and places it in ret. If ret is NULL, a new BIGNUM is created.

BN_bn2hex() and BN_bn2dec() return printable strings containing the hexadecimal and decimal encoding of a respectively. For negative numbers, the string is prefaced with a leading '-'. The string must be freed later using OPENSSL_free().

BN_hex2bn() converts the string str containing a hexadecimal number to a BIGNUM and stores it in **bn. If *bn is NULL, a new BIGNUM is created. If bn is NULL, it only computes the number's length in hexadecimal digits. If the string starts with '-', the number is negative. BN_dec2bn() is the same using the decimal system.

BN_print() and BN_print_fp() write the hexadecimal encoding of a, with a leading '-' for negative numbers, to the BIO or FILE fp.

BN_bn2mpi() and BN_mpi2bn() convert BIGNUMs from and to a format that consists of the number's length in bytes represented as a 4-byte big-endian number, and the number itself in big-endian format, where the most significant bit signals a negative number (the representation of numbers with the MSB set is prefixed with null byte).

BN_bn2mpi() stores the representation of a at to, where to must be large enough to hold the result. The size can be determined by calling BN_bn2mpi(a, NULL).

BN_mpi2bn() converts the len bytes long representation at s to a BIGNUM and stores it at ret, or in a newly allocated BIGNUM if ret is NULL.

Return Values

BN_bn2bin() returns the length of the big-endian number placed at to. BN_bin2bn() returns the BIGNUM, NULL on error.

BN_bn2hex() and BN_bn2dec() return a null-terminated string, or NULL on error. BN_hex2bn() and BN_dec2bn() return the number's length in hexadecimal or decimal digits, and 0 on error.

BN_print_fp() and BN_print() return 1 on success, 0 on write errors.

BN_bn2mpi() returns the length of the representation. BN_mpi2bn() returns the BIGNUM, and NULL on error.

The error codes can be obtained by ERR_get_error().

See Also

bn(),
ERR_get_error(),
BN_zero(),
ASN1_INTEGER_to_BN(),
BN_num_bytes()

History

BN_bn2bin(), BN_bin2bn(),
BN_print_fp() and
BN_print() are available
in all versions of SSLeay and OpenSSL.

BN_bn2hex(), BN_bn2dec(), BN_hex2bn(), BN_dec2bn(),
 BN_bn2mpi() and

BN_mpi2bn() were added in SSLeay 0.9.0.

Feedback

For additional information or queries on this page send feedback


BN_is_odd - BIGNUM comparison and test functions

Name

BN_cmp, BN_ucmp
BN_is_zero, BN_is_one
BN_is_word, BN_is_odd

BIGNUM comparison and test functions

Library

libcrypto.lib

Synopsis

#include <openssl/bn.h>
int BN_cmp(BIGNUM *a, BIGNUM *b);
int BN_ucmp(BIGNUM *a, BIGNUM *b);
int BN_is_zero(BIGNUM *a);
int BN_is_one(BIGNUM *a);
int BN_is_word(BIGNUM *a, BN_ULONG w);
int BN_is_odd(BIGNUM *a);

Detailed Description

BN_cmp() compares the numbers a and b. BN_ucmp() compares their absolute values.

BN_is_zero(), BN_is_one() and BN_is_word() test if a equals 0, 1, or w respectively. BN_is_odd() tests if a is odd.

BN_is_zero(), BN_is_one(), BN_is_word() and BN_is_odd() are macros.

Return Values

BN_cmp() returns -1 if a < b, 0 if a == b and 1 if a > b. BN_ucmp() is the same using the absolute values of a and b.

BN_is_zero(), BN_is_one() BN_is_word() and BN_is_odd() return 1 if the condition is true, 0 otherwise.

See Also

bn()

History

BN_cmp(), BN_ucmp(), BN_is_zero(), BN_is_one() and BN_is_word() are available in all versions of SSLeay and OpenSSL. BN_is_odd() was added in SSLeay 0.8.

Feedback

For additional information or queries on this page send feedback


BN_dup - copy BIGNUMs

Name

BN_copy, BN_dup — copies BIGNUMs

Library

libcrypto.lib

Synopsis

#include <openssl/bn.h>
BIGNUM *BN_copy(BIGNUM *to, const BIGNUM *from);
BIGNUM *BN_dup(const BIGNUM *from);

Detailed Description

BN_copy() copies from to to. BN_dup() creates a new BIGNUM containing the value from.

Return Values

BN_copy() returns to on success, NULL on error. BN_dup() returns the new BIGNUM, and NULL on error. The error codes can be obtained by ERR_get_error().

See Also

bn(), ERR_get_error()

History

BN_copy() and BN_dup() are available in all versions of SSLeay and OpenSSL.

Feedback

For additional information or queries on this page send feedback


BN_CTX_free - allocate and free BN_CTX structures

Name

BN_CTX_new, BN_CTX_init
BN_CTX_free

allocate and free BN_CTX structures

Library

libcrypto.lib

Synopsis

#include <openssl/bn.h>
BN_CTX *BN_CTX_new(void);
void BN_CTX_init(BN_CTX *c);
void BN_CTX_free(BN_CTX *c);

Detailed Description

A BN_CTX is a structure that holds BIGNUM temporary variables used by library functions. Since dynamic memory allocation to create BIGNUMs is rather expensive when used in conjunction with repeated subroutine calls, the BN_CTX structure is used.

BN_CTX_new() allocates and initializes a BN_CTX structure. BN_CTX_init() initializes an existing uninitialized BN_CTX.

BN_CTX_free() frees the components of the BN_CTX, and if it was created by BN_CTX_new(), also the structure itself. If BN_CTX_start() has been used on the BN_CTX, BN_CTX_end() must be called before the BN_CTX may be freed by BN_CTX_free().

Return Values

BN_CTX_new() returns a pointer to the BN_CTX. If the allocation fails, it returns NULL and sets an error code that can be obtained by ERR_get_error().

BN_CTX_init() and BN_CTX_free() have no return values.

See Also

bn(),
ERR_get_error(),
BN_add(),
BN_CTX_start()

History

BN_CTX_new() and BN_CTX_free() are available in all versions on SSLeay and OpenSSL. BN_CTX_init() was added in SSLeay 0.9.1b.

Feedback

For additional information or queries on this page send feedback


BN_CTX_end - use temporary BIGNUM variables

Name

BN_CTX_start, BN_CTX_get
BN_CTX_end

Uses temporary BIGNUM variables

Library

libcrypto.lib

Synopsis

#include <openssl/bn.h>
void BN_CTX_start(BN_CTX *ctx);
BIGNUM *BN_CTX_get(BN_CTX *ctx);
void BN_CTX_end(BN_CTX *ctx);

Detailed Description

These functions are used to obtain temporary BIGNUM variables from a BN_CTX (which can been created by using BN_CTX_new() in order to save the overhead of repeatedly creating and freeing BIGNUMs in functions that are called from inside a loop.

A function must call BN_CTX_start() first. Then, BN_CTX_get() may be called repeatedly to obtain temporary BIGNUMs. All BN_CTX_get() calls must be made before calling any other functions that use the ctx as an argument.

Finally, BN_CTX_end() must be called before returning from the function. When BN_CTX_end() is called, the BIGNUM pointers obtained from BN_CTX_get() become invalid.

Return Values

BN_CTX_start() and BN_CTX_end() return no values.

BN_CTX_get() returns a pointer to the BIGNUM, or NULL on error. Once BN_CTX_get() has failed, the subsequent calls will return NULL as well, so it is sufficient to check the return value of the last BN_CTX_get() call. In case of an error, an error code is set, which can be obtained by ERR_get_error().

See Also

BN_CTX_new()

History

BN_CTX_start(), BN_CTX_get() and BN_CTX_end() were added in OpenSSL 0.9.5.

Feedback

For additional information or queries on this page send feedback


BN_is_prime_fasttest - generate primes and test for primality

Name

BN_generate_prime, BN_is_prime
BN_is_prime_fasttest

generate primes and test for primality

Library

libcrypto.lib

Synopsis

#include <openssl/bn.h>
BIGNUM *BN_generate_prime(BIGNUM *ret, int num, int safe, BIGNUM *add,
                          BIGNUM *rem, void (*callback)(int, int, void *), void *cb_arg);
int BN_is_prime(const BIGNUM *a, int checks, void (*callback)(int, int, void *), BN_CTX *ctx, void *cb_arg);
int BN_is_prime_fasttest(const BIGNUM *a, int checks, void (*callback)(int, int, void *), BN_CTX *ctx, void *cb_arg,
int do_trial_division);

Detailed Description

BN_generate_prime() generates a pseudo-random prime number of num bits. If ret is not NULL, it will be used to store the number.

If callback is not NULL, it is called as follows:

    • callback(0, i, cb_arg) is called after generating the i-th potential prime number.

    • While the number is being tested for primality, callback(1, j, cb_arg) is called as described below.

    • When a prime has been found, callback(2, i, cb_arg) is called.

The prime may have to fulfill additional requirements for use in Diffie-Hellman key exchange:

If add is not NULL, the prime will fulfill the condition p % add == rem (p % add == 1 if rem == NULL) in order to suit a given generator.

If safe is true, it will be a safe prime (i.e. a prime p so that (p-1)/2 is also prime).

The PRNG must be seeded prior to calling BN_generate_prime(). The prime number generation has a negligible error probability.

BN_is_prime() and BN_is_prime_fasttest() test if the number a is prime. The following tests are performed until one of them shows that a is composite; if a passes all these tests, it is considered prime.

BN_is_prime_fasttest(), when called with do_trial_division == 1, first attempts trial division by a number of small primes; if no divisors are found by this test and callback is not NULL, callback(1, -1, cb_arg) is called. If do_trial_division == 0, this test is skipped.

Both BN_is_prime() and BN_is_prime_fasttest() perform a Miller-Rabin probabilistic primality test with checks iterations. If checks == BN_prime_checks, a number of iterations is used that yields a false positive rate of at most 2^-80 for random input.

If callback is not NULL, callback(1, j, cb_arg) is called after the j-th iteration (j = 0, 1, ...). ctx is a pre-allocated BN_CTX (to save the overhead of allocating and freeing the structure in a loop), or NULL.

Return Values

BN_generate_prime() returns the prime number on success, NULL otherwise.

BN_is_prime() returns 0 if the number is composite, 1 if it is prime with an error probability of less than 0.25^checks, and -1 on error.

The error codes can be obtained by ERR_get_error().

See Also

bn(),
ERR_get_error(),
rand()

History

The cb_arg arguments to BN_generate_prime() and to BN_is_prime() were added in SSLeay 0.9.0. The ret argument to BN_generate_prime() was added in SSLeay 0.9.1. BN_is_prime_fasttest() was added in OpenSSL 0.9.5.

Feedback

For additional information or queries on this page send feedback


bn_set_low - BIGNUM library internal functions

Name

bn_mul_words, bn_mul_add_words, bn_sqr_words
bn_div_words, bn_add_words, bn_sub_words
bn_mul_comba4, bn_mul_comba8, bn_sqr_comba4
bn_sqr_comba8, bn_cmp_words, bn_mul_normal
bn_mul_low_normal, bn_mul_recursive
bn_mul_part_recursive, bn_mul_low_recursive
bn_mul_high, bn_sqr_normal, bn_sqr_recursive
bn_expand, bn_wexpand, bn_expand2
bn_fix_top, bn_check_top, bn_print
bn_dump, bn_set_max, bn_set_high,
bn_set_low

BIGNUM library internal functions

Library

libcrypto.lib

Synopsis

BN_ULONG bn_mul_words(BN_ULONG *rp, BN_ULONG *ap, int num, BN_ULONG w);
BN_ULONG bn_mul_add_words(BN_ULONG *rp, BN_ULONG *ap, int num, BN_ULONG w);
void     bn_sqr_words(BN_ULONG *rp, BN_ULONG *ap, int num);
BN_ULONG bn_div_words(BN_ULONG h, BN_ULONG l, BN_ULONG d);
BN_ULONG bn_add_words(BN_ULONG *rp, BN_ULONG *ap, BN_ULONG *bp, int num);
BN_ULONG bn_sub_words(BN_ULONG *rp, BN_ULONG *ap, BN_ULONG *bp, int num);
void bn_mul_comba4(BN_ULONG *r, BN_ULONG *a, BN_ULONG *b);
void bn_mul_comba8(BN_ULONG *r, BN_ULONG *a, BN_ULONG *b);
void bn_sqr_comba4(BN_ULONG *r, BN_ULONG *a);
void bn_sqr_comba8(BN_ULONG *r, BN_ULONG *a);
int bn_cmp_words(BN_ULONG *a, BN_ULONG *b, int n);
void bn_mul_normal(BN_ULONG *r, BN_ULONG *a, int na, BN_ULONG *b, int nb);
void bn_mul_low_normal(BN_ULONG *r, BN_ULONG *a, BN_ULONG *b, int n);
void bn_mul_recursive(BN_ULONG *r, BN_ULONG *a, BN_ULONG *b, int n2, int dna,int dnb,BN_ULONG *tmp);
void bn_mul_part_recursive(BN_ULONG *r, BN_ULONG *a, BN_ULONG *b, int n, int tna,int tnb, BN_ULONG *tmp);
void bn_mul_low_recursive(BN_ULONG *r, BN_ULONG *a, BN_ULONG *b, int n2, BN_ULONG *tmp);
void bn_mul_high(BN_ULONG *r, BN_ULONG *a, BN_ULONG *b, BN_ULONG *l, int n2, BN_ULONG *tmp);
void bn_sqr_normal(BN_ULONG *r, BN_ULONG *a, int n, BN_ULONG *tmp);
void bn_sqr_recursive(BN_ULONG *r, BN_ULONG *a, int n2, BN_ULONG *tmp);
void mul(BN_ULONG r, BN_ULONG a, BN_ULONG w, BN_ULONG c);
void mul_add(BN_ULONG r, BN_ULONG a, BN_ULONG w, BN_ULONG c);
void sqr(BN_ULONG r0, BN_ULONG r1, BN_ULONG a);
BIGNUM *bn_expand(BIGNUM *a, int bits);
BIGNUM *bn_wexpand(BIGNUM *a, int n);
BIGNUM *bn_expand2(BIGNUM *a, int n);
void bn_fix_top(BIGNUM *a);
void bn_check_top(BIGNUM *a);
void bn_print(BIGNUM *a);
void bn_dump(BN_ULONG *d, int n);
void bn_set_max(BIGNUM *a);
void bn_set_high(BIGNUM *r, BIGNUM *a, int n);
void bn_set_low(BIGNUM *r, BIGNUM *a, int n);

Detailed Description

This page documents the internal functions used by the OpenSSL BIGNUM implementation. They are described here to facilitate debugging and extending the library. They are not to be used by applications.

The BIGNUM structure

typedef struct bignum_st
        {
        int top;      /* number of words used in d */
        BN_ULONG *d;  /* pointer to an array containing the integer value */
        int max;      /* size of the d array */
        int neg;      /* sign */
        } BIGNUM;

The integer value is stored in d, a malloc()ed array of words (BN_ULONG), least significant word first. A BN_ULONG can be either 16, 32 or 64 bits in size, depending on the 'number of bits' (BITS2) specified in openssl/bn.h.

max is the size of the d array that has been allocated. top is the number of words being used, so for a value of 4, bn.d[0]=4 and bn.top=1. neg is 1 if the number is negative. When a BIGNUM is 0, the d field can be NULL and top == 0.

Various routines in this library require the use of temporary BIGNUM variables during their execution. Since dynamic memory allocation to create BIGNUMs is rather expensive when used in conjunction with repeated subroutine calls, the BN_CTX structure is used. This structure contains BN_CTX_NUM BIGNUMs,
see BN_CTX_start().

Low-level arithmetic operations

These functions are implemented in C and for several platforms in assembly language:

bn_mul_words(rp, ap, num, w) operates on the num word arrays rp and ap. It computes ap * w, places the result in rp, and returns the high word (carry).

bn_mul_add_words(rp, ap, num, w) operates on the num word arrays rp and ap. It computes ap * w + rp, places the result in rp, and returns the high word (carry).

bn_sqr_words(rp, ap, n) operates on the num word array ap and the 2*num word array ap. It computes ap * ap word-wise, and places the low and high bytes of the result in rp.

bn_div_words(h, l, d) divides the two word number (h,l) by d and returns the result.

bn_add_words(rp, ap, bp, num) operates on the num word arrays ap, bp and rp. It computes ap + bp, places the result in rp, and returns the high word (carry).

bn_sub_words(rp, ap, bp, num) operates on the num word arrays ap, bp and rp. It computes ap - bp, places the result in rp, and returns the carry (1 if bp > ap, 0 otherwise).

bn_mul_comba4(r, a, b) operates on the 4 word arrays a and b and the 8 word array r. It computes a*b and places the result in r.

bn_mul_comba8(r, a, b) operates on the 8 word arrays a and b and the 16 word array r. It computes a*b and places the result in r.

bn_sqr_comba4(r, a, b) operates on the 4 word arrays a and b and the 8 word array r.

bn_sqr_comba8(r, a, b) operates on the 8 word arrays a and b and the 16 word array r.

The following functions are implemented in C:

bn_cmp_words(a, b, n) operates on the n word arrays a and b. It returns 1, 0 and -1 if a is greater than, equal and less than b.

bn_mul_normal(r, a, na, b, nb) operates on the na word array a, the nb word array b and the na+nb word array r. It computes a*b and places the result in r.

bn_mul_low_normal(r, a, b, n) operates on the n word arrays r, a and b. It computes the n low words of a*b and places the result in r.

bn_mul_recursive(r, a, b, n2, dna, dnb, t) operates on the word arrays a and b of length n2+dna and n2+dnb (dna and dnb are currently allowed to be 0 or negative) and the 2*n2 word arrays r and t. n2 must be a power of 2. It computes a*b and places the result in r.

bn_mul_part_recursive(r, a, b, n, tna, tnb, tmp) operates on the word arrays a and b of length n+tna and n+tnb and the 4*n word arrays r and tmp.

bn_mul_low_recursive(r, a, b, n2, tmp) operates on the n2 word arrays r and tmp and the n2/2 word arrays a and b.

bn_mul_high(r, a, b, l, n2, tmp) operates on the n2 word arrays r, a, b and l (?) and the 3*n2 word array tmp.

BN_mul() calls bn_mul_normal(), or an optimized implementation if the factors have the same size: bn_mul_comba8() is used if they are 8 words long, bn_mul_recursive() if they are larger than BN_MULL_SIZE_NORMAL and the size is an exact multiple of the word size, and bn_mul_part_recursive() for others that are larger than BN_MULL_SIZE_NORMAL.

bn_sqr_normal(r, a, n, tmp) operates on the n word array a and the 2*n word arrays tmp and r.

The implementations use the following macros which, depending on the architecture, may use ``long long'' C operations or inline assembler. They are defined in bn_lcl.h.

mul(r, a, w, c) computes w*a+c and places the low word of the result in r and the high word in c.

mul_add(r, a, w, c) computes w*a+r+c and places the low word of the result in r and the high word in c.

sqr(r0, r1, a) computes a*a and places the low word of the result in r0 and the high word in r1.

Size changes

bn_expand() ensures that b has enough space for a bits bit number. bn_wexpand() ensures that b has enough space for an n word number. If the number has to be expanded, both macros call bn_expand2(), which allocates a new d array and copies the data. They return NULL on error, b otherwise.

The bn_fix_top() macro reduces a->top to point to the most significant non-zero word plus one when a has shrunk.

Debugging

bn_check_top() verifies that ((a)->top >= 0 && (a)->top E<lt>= (a)-E<gt>max). A violation will cause the program to abort.

bn_print() prints a to stderr. bn_dump() prints n words at d (in reverse order, i.e. most significant word first) to stderr.

bn_set_max() makes a a static number with a max of its current size. This is used by bn_set_low() and bn_set_high() to make r a read-only BIGNUM that contains the n low or high words of a.

If BN_DEBUG is not defined, bn_check_top(), bn_print(), bn_dump() and bn_set_max() are defined as empty macros.

See Also

bn()

Feedback

For additional information or queries on this page send feedback


BN_mod_inverse - compute inverse modulo n

Name

BN_mod_inverse — computes inverse modulo n

Library

libcrypto.lib

Synopsis

#include <openssl/bn.h>
BIGNUM *BN_mod_inverse(BIGNUM *r, BIGNUM *a, const BIGNUM *n, BN_CTX *ctx);

Detailed Description

BN_mod_inverse() computes the inverse of a modulo n places the result in r ((a*r)%n==1). If r is NULL, a new BIGNUM is created.

ctx is a previously allocated BN_CTX used for temporary variables. r may be the same BIGNUM as a or n.

Return Values

BN_mod_inverse() returns the BIGNUM containing the inverse, and NULL on error. The error codes can be obtained by ERR_get_error().

See Also

bn(),
ERR_get_error(),
BN_add()

History

BN_mod_inverse() is available in all versions of SSLeay and OpenSSL.

Feedback

For additional information or queries on this page send feedback


BN_to_montgomery - Montgomery multiplication

Name

BN_mod_mul_montgomery, BN_MONT_CTX_new
BN_MONT_CTX_init, BN_MONT_CTX_free
BN_MONT_CTX_set, BN_MONT_CTX_copy
BN_from_montgomery, BN_to_montgomery

Montgomery multiplication

Library

libcrypto.lib

Synopsis

#include <openssl/bn.h>
BN_MONT_CTX *BN_MONT_CTX_new(void);
void BN_MONT_CTX_init(BN_MONT_CTX *ctx);
void BN_MONT_CTX_free(BN_MONT_CTX *mont);
int BN_MONT_CTX_set(BN_MONT_CTX *mont, const BIGNUM *m, BN_CTX *ctx);
BN_MONT_CTX *BN_MONT_CTX_copy(BN_MONT_CTX *to, BN_MONT_CTX *from);
int BN_mod_mul_montgomery(BIGNUM *r, BIGNUM *a, BIGNUM *b, BN_MONT_CTX *mont, BN_CTX *ctx);
int BN_from_montgomery(BIGNUM *r, BIGNUM *a, BN_MONT_CTX *mont, BN_CTX *ctx);
int BN_to_montgomery(BIGNUM *r, BIGNUM *a, BN_MONT_CTX *mont, BN_CTX *ctx);

Detailed Description

These functions implement Montgomery multiplication. They are used automatically when BN_mod_exp() is called with suitable input, but they may be useful when several operations are to be performed using the same modulus.

BN_MONT_CTX_new() allocates and initializes a BN_MONT_CTX structure. BN_MONT_CTX_init() initializes an existing uninitialized BN_MONT_CTX.

BN_MONT_CTX_set() sets up the mont structure from the modulus m by precomputing its inverse and a value R.

BN_MONT_CTX_copy() copies the BN_MONT_CTX from to to.

BN_MONT_CTX_free() frees the components of the BN_MONT_CTX, and, if it was created by BN_MONT_CTX_new(), also the structure itself.

BN_mod_mul_montgomery() computes Mont(a,b):=a*b*R^-1 and places the result in r.

BN_from_montgomery() performs the Montgomery reduction r = a*R^-1.

BN_to_montgomery() computes Mont(a,R^2), i.e. a*R. Note that a must be non-negative and smaller than the modulus.

For all functions, ctx is a previously allocated BN_CTX used for temporary variables.

The BN_MONT_CTX structure is defined as follows:

 typedef struct bn_mont_ctx_st
        {
        int ri;         /* number of bits in R */
        BIGNUM RR;      /* R^2 (used to convert to Montgomery form) */
        BIGNUM N;       /* The modulus */
        BIGNUM Ni;      /* R*(1/R mod N) - N*Ni = 1
                         * (Ni is only stored for bignum algorithm) */
        BN_ULONG n0;    /* least significant word of Ni */
        int flags;
        } BN_MONT_CTX;

BN_to_montgomery() is a macro.

Return Values

BN_MONT_CTX_new() returns the newly allocated BN_MONT_CTX, and NULL on error.

BN_MONT_CTX_init() and BN_MONT_CTX_free() have no return values.

For the other functions, 1 is returned for success, 0 on error. The error codes can be obtained by ERR_get_error().

Warnings

The inputs must be reduced modulo m, otherwise the result will be outside the expected range.

See Also

bn(),
ERR_get_error(),
BN_add(),
BN_CTX_new()

History

BN_MONT_CTX_new(), BN_MONT_CTX_free(), BN_MONT_CTX_set(),
BN_mod_mul_montgomery(),  BN_from_montgomery() and
BN_to_montgomery()
are available in all versions of SSLeay and OpenSSL.

BN_MONT_CTX_init() and BN_MONT_CTX_copy() were added in SSLeay 0.9.1b.

Feedback

For additional information or queries on this page send feedback


BN_RECP_CTX_set - modular multiplication using reciprocal

Name

BN_mod_mul_reciprocal, BN_div_recp
BN_RECP_CTX_new, BN_RECP_CTX_init
BN_RECP_CTX_free, BN_RECP_CTX_set

modular multiplication using reciprocal

Library

libcrypto.lib

Synopsis

#include <openssl/bn.h>
BN_RECP_CTX *BN_RECP_CTX_new(void);
void BN_RECP_CTX_init(BN_RECP_CTX *recp);
void BN_RECP_CTX_free(BN_RECP_CTX *recp);
int BN_RECP_CTX_set(BN_RECP_CTX *recp, const BIGNUM *m, BN_CTX *ctx);
int BN_div_recp(BIGNUM *dv, BIGNUM *rem, BIGNUM *a, BN_RECP_CTX *recp, BN_CTX *ctx);
int BN_mod_mul_reciprocal(BIGNUM *r, BIGNUM *a, BIGNUM *b, BN_RECP_CTX *recp, BN_CTX *ctx);

Detailed Description

BN_mod_mul_reciprocal() can be used to perform an efficient BN_mod_mul() operation when the operation will be performed repeatedly with the same modulus. It computes r=(a*b)%m using recp=1/m, which is set as described below. ctx is a previously allocated BN_CTX used for temporary variables.

BN_RECP_CTX_new() allocates and initializes a BN_RECP structure. BN_RECP_CTX_init() initializes an existing uninitialized BN_RECP.

BN_RECP_CTX_free() frees the components of the BN_RECP, and, if it was created by BN_RECP_CTX_new(), also the structure itself.

BN_RECP_CTX_set() stores m in recp and sets it up for computing 1/m and shifting it left by BN_num_bits(m)+1 to make it an integer. The result and the number of bits it was shifted left will later be stored in recp.

BN_div_recp() divides a by m using recp. It places the quotient in dv and the remainder in rem.

The BN_RECP_CTX structure is defined as follows:

 typedef struct bn_recp_ctx_st
        {
        BIGNUM N;       /* the divisor */
        BIGNUM Nr;      /* the reciprocal */
        int num_bits;
        int shift;
        int flags;
        } BN_RECP_CTX;

It cannot be shared between threads.

Return Values

BN_RECP_CTX_new() returns the newly allocated BN_RECP_CTX, and NULL on error.

BN_RECP_CTX_init() and BN_RECP_CTX_free() have no return values.

For the other functions, 1 is returned for success, 0 on error. The error codes can be obtained by ERR_get_error().

See Also

bn(),
ERR_get_error(),
BN_add(),
BN_CTX_new()

History

BN_RECP_CTX was added in SSLeay 0.9.0. Before that, the function BN_reciprocal() was used instead, and the BN_mod_mul_reciprocal() arguments were different.

Feedback

For additional information or queries on this page send feedback


BN_clear_free - allocate and free BIGNUMs

Name

BN_new, BN_init, BN_clear
BN_free, BN_clear_free

Allocates and frees BIGNUMs

Library

libcrypto.lib

Synopsis

#include <openssl/bn.h>
BIGNUM *BN_new(void);
void BN_init(BIGNUM *);
void BN_clear(BIGNUM *a);
void BN_free(BIGNUM *a);
void BN_clear_free(BIGNUM *a);

Detailed Description

BN_new() allocates and initializes a BIGNUM structure. BN_init() initializes an existing uninitialized BIGNUM.

BN_clear() is used to destroy sensitive data such as keys when they are no longer needed. It erases the memory used by a and sets it to the value 0.

BN_free() frees the components of the BIGNUM, and if it was created by BN_new(), also the structure itself. BN_clear_free() additionally overwrites the data before the memory is returned to the system.

Return Values

BN_new() returns a pointer to the BIGNUM. If the allocation fails, it returns NULL and sets an error code that can be obtained by ERR_get_error().

BN_init(), BN_clear(),
BN_free() and
BN_clear_free() have no return
values.

See Also

bn(), ERR_get_error()

History

BN_new(), BN_clear(), BN_free() and BN_clear_free() are available in all versions on SSLeay and OpenSSL. BN_init() was added in SSLeay 0.9.1b.

Feedback

For additional information or queries on this page send feedback


BN_num_bits_word - get BIGNUM size

Name

BN_num_bits, BN_num_bytes
BN_num_bits_word

gets BIGNUM size

Library

libcrypto.lib

Synopsis

#include <openssl/bn.h>
int BN_num_bytes(const BIGNUM *a);
int BN_num_bits(const BIGNUM *a);
int BN_num_bits_word(BN_ULONG w);

Detailed Description

BN_num_bytes() returns the size of a BIGNUM in bytes.

BN_num_bits_word() returns the number of significant bits in a word. If we take 0x00000432 as an example, it returns 11, not 16, not 32. Basically, except for a zero, it returns floor(log2(w))+1.

BN_num_bits() returns the number of significant bits in a BIGNUM, following the same principle as BN_num_bits_word().

BN_num_bytes() is a macro.

Return Values

The size.

Notes

Some have tried using BN_num_bits() on individual numbers in RSA keys, DH keys and DSA keys, and found that they do not always come up with the number of bits they expected (something like 512, 1024, 2048, ...). This is because generating a number with some specific number of bits does not always set the highest bits, thereby making the number of significant bits a little lower. To know the ``key size'' of such a key, either use functions like RSA_size(), DH_size() and DSA_size(), or use BN_num_bytes() and multiply with 8 (although there's no real guarantee that will match the ``key size'', just a lot more probability).

See Also

bn(),
DH_size(), DSA_size(),
RSA_size()

History

BN_num_bytes(), BN_num_bits() and BN_num_bits_word() are available in all versions of SSLeay and OpenSSL.

Feedback

For additional information or queries on this page send feedback


BN_pseudo_rand - generate pseudo-random number

Name

BN_rand, BN_pseudo_rand — generates pseudo-random number

Library

libcrypto.lib

Synopsis

#include <openssl/bn.h>
int BN_rand(BIGNUM *rnd, int bits, int top, int bottom);
int BN_pseudo_rand(BIGNUM *rnd, int bits, int top, int bottom);
int BN_rand_range(BIGNUM *rnd, BIGNUM *range);
int BN_pseudo_rand_range(BIGNUM *rnd, BIGNUM *range);

Detailed Description

BN_rand() generates a cryptographically strong pseudo-random number of bits bits in length and stores it in rnd. If top is -1, the most significant bit of the random number can be zero. If top is 0, it is set to 1, and if top is 1, the two most significant bits of the number will be set to 1, so that the product of two such random numbers will always have 2*bits length. If bottom is true, the number will be odd.

BN_pseudo_rand() does the same, but pseudo-random numbers generated by this function are not necessarily unpredictable. They can be used for non-cryptographic purposes and for certain purposes in cryptographic protocols, but usually not for key generation etc.

BN_rand_range() generates a cryptographically strong pseudo-random number rnd in the range 0 <lt>= rnd < range. BN_pseudo_rand_range() does the same, but is based on BN_pseudo_rand(), and hence numbers generated by it are not necessarily unpredictable.

The PRNG must be seeded prior to calling BN_rand() or BN_rand_range().

Return Values

The functions return 1 on success, 0 on error. The error codes can be obtained by ERR_get_error().

See Also

bn(),
ERR_get_error(),
rand(),
RAND_add(), RAND_bytes()

History

BN_rand() is available in all versions of SSLeay and OpenSSL. BN_pseudo_rand() was added in OpenSSL 0.9.5. The top == -1 case and the function BN_rand_range() were added in OpenSSL 0.9.6a. BN_pseudo_rand_range() was added in OpenSSL 0.9.6c.

Feedback

For additional information or queries on this page send feedback


BN_rshift1 - bit operations on BIGNUMs

Name

BN_set_bit, BN_clear_bit
BN_is_bit_set, BN_mask_bits
BN_lshift, BN_lshift1
BN_rshift, BN_rshift1

bit operations on BIGNUMs

Library

libcrypto.lib

Synopsis

#include <openssl/bn.h>
int BN_set_bit(BIGNUM *a, int n);
int BN_clear_bit(BIGNUM *a, int n);
int BN_is_bit_set(const BIGNUM *a, int n);
int BN_mask_bits(BIGNUM *a, int n);
int BN_lshift(BIGNUM *r, const BIGNUM *a, int n);
int BN_lshift1(BIGNUM *r, BIGNUM *a);
int BN_rshift(BIGNUM *r, BIGNUM *a, int n);
int BN_rshift1(BIGNUM *r, BIGNUM *a);

Detailed Description

BN_set_bit() sets bit n in a to 1 (a|=(1<<n)). The number is expanded if necessary.

BN_clear_bit() sets bit n in a to 0 (a&=~(1<<n)). An error occurs if a is shorter than n bits.

BN_is_bit_set() tests if bit n in a is set.

BN_mask_bits() truncates a to an n bit number (a&=~((~0)>>n)). An error occurs if a already is shorter than n bits.

BN_lshift() shifts a left by n bits and places the result in r (r=a*2^n). BN_lshift1() shifts a left by one and places the result in r (r=2*a).

BN_rshift() shifts a right by n bits and places the result in r (r=a/2^n). BN_rshift1() shifts a right by one and places the result in r (r=a/2).

For the shift functions, r and a may be the same variable.

Return Values

BN_is_bit_set() returns 1 if the bit is set, 0 otherwise.

All other functions return 1 for success, 0 on error. The error codes can be obtained by ERR_get_error().

See Also

bn(),
BN_num_bytes(),
BN_add()

History

BN_set_bit(), BN_clear_bit(), BN_is_bit_set(), BN_mask_bits(), BN_lshift(), BN_lshift1(), BN_rshift(), and BN_rshift1() are available in all versions of SSLeay and OpenSSL.

Feedback

For additional information or queries on this page send feedback


BN_swap - exchange BIGNUMs

Name

BN_swap — exchanges BIGNUMs

Library

libcrypto.lib

Synopsis

#include <openssl/bn.h>
void BN_swap(BIGNUM *a, BIGNUM *b);

Detailed Description

BN_swap() exchanges the values of a and b.

See Also

bn()

History

BN_swap was added in OpenSSL 0.9.7.

Feedback

For additional information or queries on this page send feedback


BN_get_word - BIGNUM assignment operations

Name

BN_zero, BN_one, BN_value_one,
BN_set_word, BN_get_word

BIGNUM assignment operations

Library

libcrypto.lib

Synopsis

#include <openssl/bn.h>
int BN_zero(BIGNUM *a);
int BN_one(BIGNUM *a);
const BIGNUM *BN_value_one(void);
int BN_set_word(BIGNUM *a, unsigned long w);
unsigned long BN_get_word(BIGNUM *a);

Detailed Description

BN_zero(), BN_one() and BN_set_word() set a to the values 0, 1 and w respectively. BN_zero() and BN_one() are macros.

BN_value_one() returns a BIGNUM constant of value 1. This constant is useful for use in comparisons and assignment.

BN_get_word() returns a, if it can be represented as an unsigned long.

Return Values

BN_get_word() returns the value a, and 0xffffffffL if a cannot be represented as an unsigned long.

BN_zero(), BN_one() and BN_set_word() return 1 on success, 0 otherwise. BN_value_one() returns the constant.

Bugs

Someone might change the constant.

If a BIGNUM is equal to 0xffffffffL it can be represented as an unsigned long but this value is also returned on error.

See Also

bn(), BN_bn2bin()

History

BN_zero(), BN_one() and BN_set_word() are available in all versions of SSLeay and OpenSSL. BN_value_one() and BN_get_word() were added in SSLeay 0.8.

BN_value_one() was changed to return a true const BIGNUM * in OpenSSL 0.9.7.

Feedback

For additional information or queries on this page send feedback


brk

Name

brk
- change data segment size

Library

 libc.lib

Synopsis
#include <sys/types.h>
#include <unistd.h>
int brk (const void *addr);

Return values

 Function always returns 0.

Detailed description

 The brk function is used to change the amount of memory allocated in a process’s data segment. It does this by moving the location of the "break". This functionality is not supported by the symbian platform and hence is only build supported.

See also

 mmap, free, malloc

Feedback

For additional information or queries on this page send feedback


bsearch

Name

bsearch - binary search of a sorted array

Library

 libc.lib

Synopsis
#include <stdlib.h>
void * bsearch (const void *key, const void *base, size_t nmemb, size_t size, int (*compar) (const void *, const void *));

Return values

 The bsearch function returns a pointer to a matching member of the array, or a null pointer if no match is found. If two members compare as equal, which member is matched is unspecified.

Detailed description

 The bsearch function searches an array of nmemb objects, the initial member of which is pointed to by base, for a member that matches the object pointed to by key. 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 the comparison function referenced by compar. The compar routine is expected to have two arguments which point to the key object and to an array member, in that order, and should return an integer less than, equal to, or greater than zero if the key object is found, respectively, to be less than, to match, or be greater than the array member.

Examples

#include<stdlib.h>
#include<stdio.h>

int search_function(const void* a,const void* b)
{
    return(*(int *)a - *(int *)b);
}

int main()
{
int arr[] = {3,5,7,8,10};
int key = 7;
int i = 5;

int *ele;

ele  = ( int* ) bsearch(&key, (void *)arr, i, sizeof(arr[0]), search_function);

if (ele != NULL)
        printf("\nelement found: %d", *ele);
else
        printf("\nelement not found");
return 0;
}

Output

element found: 7

See also

 qsort

Feedback

For additional information or queries on this page send feedback


btowc

Name

btowc, wctob
- convert single byte to wide character

Library

 libc.lib

Synopsis
#include <wchar.h>
wint_t btowc (int c);
int wctob (wint_t c);

Return values

btowc function returns the wide character converted from the single byte c
.If c is EOF or not a valid multibyte sequence of length 1, it returns WEOF.

Detailed description

 The btowc function converts a single-byte character into a corresponding wide character. 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 single-byte character. If the wide character is WEOF or not able to be represented as a single byte in the initial shift state, wctob returns WEOF.

The behavior of the btowc and wctob is affected by LC_CTYPE category of the current locale.

Examples

#include <wchar.h>
/* Illustrates how to use btowc API */
wint_t example_btowc(int c)
{
 wint_t wc;
 /* converting single byte to wide-character */
 wc = btowc(c);
 /* return the character that was converted */
return (wc);
}

#include <wchar.h>
/* Illustrates how to use wctob API */
int example_wctob(void)
{
 wint_t wc = L’a’;
 int c;

 /* represent a wide-char in a single byte*/
 c = wctob(wc);
 /* return the single byte */
 return(c);
}

Limitations

 The current implementation of btowc and wctob is not affected by the LC_CTYPE category of the current locale. It works only for UTF8 character set.

See also

 mbrtowc, wcrtomb
The btowc and wctob functions conform to -p1003.1-2001.
The btowc and wctob functions first appeared in 5.0.

Feedback

For additional information or queries on this page send feedback


BUF_strdup - simple character arrays structure

Name

BUF_MEM_new
BUF_MEM_free
BUF_MEM_grow
BUF_strdup

simple character arrays structure

Library

libcrypto.lib

Synopsis

#include <openssl/buffer.h>
BUF_MEM *BUF_MEM_new(void);
void   BUF_MEM_free(BUF_MEM *a);
int    BUF_MEM_grow(BUF_MEM *str, int len);
char * BUF_strdup(const char *str);

Detailed Description

The buffer library handles simple character arrays. Buffers are used for various purposes in the library, most notably memory BIOs.

The library uses the BUF_MEM structure defined in buffer.h:

 typedef struct buf_mem_st
 {
        int length;     /* current number of bytes */
        char *data;
        int max;        /* size of buffer */
 } BUF_MEM;

length is the current size of the buffer in bytes, max is the amount of memory allocated to the buffer. There are three functions which handle these and one ``miscellaneous'' function.

BUF_MEM_new() allocates a new buffer of zero size.

BUF_MEM_free() frees up an already existing buffer. The data is zeroed before freeing up in case the buffer contains sensitive data.

BUF_MEM_grow() changes the size of an already existing buffer to len. Any data already in the buffer is preserved if it increases in size.

BUF_strdup() copies a null terminated string into a block of allocated memory and returns a pointer to the allocated block. Unlike the standard C library strdup() this function uses OPENSSL_malloc() and so should be used in preference to the standard library strdup() because it can be used for memory leak checking or replacing the malloc() function.

The memory allocated from BUF_strdup() should be freed up using the OPENSSL_free() function.

Return Values

BUF_MEM_new() returns the buffer or NULL on error.

BUF_MEM_free() has no return value.

BUF_MEM_grow() returns zero on error or the new size (i.e. len).

See Also

bio()

History

BUF_MEM_new(),  BUF_MEM_free() and
BUF_MEM_grow() are available in all
versions of SSLeay and OpenSSL. BUF_strdup()
was added in SSLeay 0.8.

Feedback

For additional information or queries on this page send feedback


bzero

Name

bzero - write zero bytes

Library

 libc.lib

Synopsis
#include <strings.h>
void bzero (void *b, size_t len);

Detailed description

 The bzero function writes len zero bytes to the string b. If len is zero, bzero does nothing.

Examples

#include <string.h>
#include <stdio.h>
int main()
{
    char dst[50] = "abcdef";
    bzero(dst + 2, 2);
    if(!strcmp(dst, "ab")) printf("dst =  %s\n",dst);
    if(!strcmp(dst+3, "")) printf("zeros added to dst string\n");
    if(!strcmp(dst + 4, "ef")) printf("dst + 4 = %s\n",dst);
    return 0;
}

Output

dst =  ab
zeros added to dst string
dst + 4 = ab

See also

 memset, swab

Feedback

For additional information or queries on this page send feedback


ceil

Name

ceil, ceilf, ceill
- ceiling function: smallest integral value not less than argument

Library

 libm.lib

Synopsis
#include <math.h>
double ceil (double x);
float ceilf (float x);
long double ceill (long double x);

Return values

x is integral or infinite, x itself is returned.

Detailed description

 The ceil, ceilf, and ceill functions return the smallest integral value greater than or equal to x, expressed as a floating-point number.

Examples

#include <math.h>
int main( void )
{
   double y;
   y = ceil( 2.8 );
   printf( "The ceil of 2.8 is %f\n", y );
   y = ceil( -2.8 );
   printf( "The ceil of -2.8 is %f\n", y );
   y = ceilf( 2.8 );
   printf( "The ceilf of 2.8 is %f\n", y );
   y = ceilf( -2.8 );
   printf( "The ceilf of -2.8 is %f\n", y );
   y = ceill( 2.8 );
   printf( "The ceill of 2.8 is %f\n", y );
   y = ceill( -2.8 );
   printf( "The ceill of -2.8 is %f\n", y );
}

Output

The ceil of 2.8 is 3.000000
The ceil of -2.8 is -2.000000
The ceilf of 2.8 is 3.000000
The ceilf of -2.8 is -2.000000
The ceill of 2.8 is 3.000000
The ceill of -2.8 is -2.000000

See also

 abs, fabs, floor, ieee, math, rint, round, and trunc

Feedback

For additional information or queries on this page send feedback


Index

Background

Overview

GObject, and its lower-level type system, GType, are used by GTK+ and most Gnome libraries to provide:

  • object-oriented C-based APIs and

  • automatic transparent API bindings to other compiled or interpreted languages.

A lot of programmers are used to work with compiled-only or dynamically interpreted-only languages and do not understand the challenges associated with cross-language interoperability. This introduction tries to provide an insight into these challenges. describes briefly the solution chosen by GLib.

The following chapters go into greater detail into how GType and GObject work and how you can use them as a C programmer. It is useful to keep in mind that allowing access to C objects from other interpreted languages was one of the major design goals: this can often explain the sometimes rather convoluted APIs and features present in this library.

Data types and programming

One could say (I have seen such definitions used in some textbooks on programming language theory) that a programming language is merely a way to create data types and manipulate them. Most languages provide a number of language-native types and a few primitives to create more complex types based on these primitive types.

In C, the language provides types such as char, long, pointer. During compilation of C code, the compiler maps these language types to the compiler's target architecture machine types. If you are using a C interpreter (I have never seen one myself but it is possible :), the interpreter (the program which interprets the source code and executes it) maps the language types to the machine types of the target machine at runtime, during the program execution (or just before execution if it uses a Just In Time compiler engine).

Perl and Python which are interpreted languages do not really provide type definitions similar to those used by C. Perl and Python programmers manipulate variables and the type of the variables is decided only upon the first assignment or upon the first use which forces a type on the variable. The interpreter also often provides a lot of automatic conversions from one type to the other. For example, in Perl, a variable which holds an integer can be automatically converted to a string given the required context:

my $tmp = 10;
print "this is an integer converted to a string:" . $tmp . "\n";

Of course, it is also often possible to explicitly specify conversions when the default conversions provided by the language are not intuitive.


NGI SDK 1.0 - API Reference Guide: ngi::Index

The Glib Dynamic Type System

A type, as manipulated by the Glib type system, is much more generic than what is usually understood as an Object type. It is best explained by looking at the structure and the functions used to register new types in the type system.

typedef struct _GTypeInfo      GTypeInfo;
struct _GTypeInfo
{
  /* interface types, classed types, instantiated types */
  guint16                class_size;
  GBaseInitFunc          base_init;
  GBaseFinalizeFunc      base_finalize;
  /* classed types, instantiated types */
  GClassInitFunc         class_init;
  GClassFinalizeFunc     class_finalize;
  gconstpointer          class_data;
  /* instantiated types */
  guint16                instance_size;
  guint16                n_preallocs;
  GInstanceInitFunc      instance_init;

  /* value handling */
  const GTypeValueTable *value_table;
};
GType g_type_register_static (GType  parent_type, const gchar  *type_name, const GTypeInfo  *info, GTypeFlags  flags);
GType g_type_register_fundamental (GType  type_id, const gchar *type_name, const GTypeInfo  *info,
                                   const GTypeFundamentalInfo *finfo, GTypeFlags flags);

g_type_register_static and g_type_register_fundamental are the C functions, defined in gtype.h and implemented in gtype.c which you should use to register a new GType in the program's type system. It is not likely you will ever need to use g_type_register_fundamental but in case you want to, the last chapter explains how to create new fundamental types. [2]

Fundamental types are top-level types which do not derive from any other type while other non-fundamental types derive from other types. Upon initialization by g_type_init, the type system not only initializes its internal data structures but it also registers a number of core types: some of these are fundamental types. Others are types derived from these fundamental types.

Fundamental and non-Fundamental types are defined by:

  • class size: the class_size field in GTypeInfo.

  • class initialization functions (C++ constructor): the base_init and class_init fields in GTypeInfo.

  • class destruction functions (C++ destructor): the base_finalize and class_finalize fields in GTypeInfo.

  • instance size (C++ parameter to new): the instance_size field in GTypeInfo.

  • instanciation policy (C++ type of new operator): the n_preallocs field in GTypeInfo.

  • copy functions (C++ copy operators): the value_table field in GTypeInfo.

  • type characteristic flags: GTypeFlags.

Fundamental types are also defined by a set of GTypeFundamentalFlags which are stored in a GTypeFundamentalInfo. Non-Fundamental types are furthermore defined by the type of their parent which is passed as the parent_type parameter to g_type_register_static and g_type_register_dynamic.

Copy functions

The major common point between all glib types (fundamental and non-fundamental, classed and non-classed, instantiable and non-instantiable) is that they can all be manipulated through a single API to copy/assign them.

The GValue structure is used as an abstract container for all of these types. Its simplistic API (defined in gobject/gvalue.h) can be used to invoke the value_table functions registered during type registration: for example g_value_copy copies the content of a GValue to another GValue. This is similar to a C++ assignment which invokes the C++ copy operator to modify the default bit-by-bit copy semantics of C++/C structures/classes.

The following code shows how you can copy around a 64 bit integer, as well as a GObject instance pointer (sample code for this is located in the source tarball for this document in sample/gtype/test.c):

static void test_int (void)
{
  GValue a_value = {0, };
  GValue b_value = {0, };
  guint64 a, b;

  a = 0xdeadbeaf;

  g_value_init (&a_value, G_TYPE_UINT64);
  g_value_set_uint64 (&a_value, a);

  g_value_init (&b_value, G_TYPE_UINT64);
  g_value_copy (&a_value, &b_value);

  b = g_value_get_uint64 (&b_value);

  if (a == b) {
    g_print ("Yay !! 10 lines of code to copy around a uint64.\n");
  } else {
    g_print ("Are you sure this is not a Z80 ?\n");
  }
}

static void test_object (void)
{
  GObject *obj;
  GValue obj_vala = {0, };
  GValue obj_valb = {0, };
  obj = g_object_new (MAMAN_BAR_TYPE, NULL);

  g_value_init (&obj_vala, MAMAN_BAR_TYPE);
  g_value_set_object (&obj_vala, obj);

  g_value_init (&obj_valb, G_TYPE_OBJECT);

  /* g_value_copy's semantics for G_TYPE_OBJECT types is to copy the reference.
     This function thus calls g_object_ref.
     It is interesting to note that the assignment works here because
     MAMAN_BAR_TYPE is a G_TYPE_OBJECT.
   */
  g_value_copy (&obj_vala, &obj_valb);

  g_object_unref (G_OBJECT (obj));
  g_object_unref (G_OBJECT (obj));
}

The important point about the above code is that the exact semantic of the copy calls is undefined since they depend on the implementation of the copy function. Certain copy functions might decide to allocate a new chunk of memory and then to copy the data from the source to the destination. Others might want to simply increment the reference count of the instance and copy the reference to the new GValue.

The value_table used to specify these assignment functions is defined in gtype.h and is thoroughly described in the API documentation provided with GObject (for once ;-) which is why we will not detail its exact semantics.

typedef struct _GTypeValueTable         GTypeValueTable;
struct _GTypeValueTable
{
  void     (*value_init)         (GValue  *value);
  void     (*value_free)         (GValue  *value);
  void     (*value_copy)         (const GValue *src_value, GValue       *dest_value);
  /* varargs functionality (optional) */
  gpointer (*value_peek_pointer) (const GValue *value);
  gchar	    *collect_format;
  gchar*   (*collect_value)      (GValue   *value, guint  n_collect_values, GTypeCValue  *collect_values,
                  guint	 collect_flags);
  gchar	    *lcopy_format;
  gchar*   (*lcopy_value)        (const GValue *value, guint n_collect_values, GTypeCValue  *collect_values,
                                  guint collect_flags);
};

Interestingly, it is also very unlikely you will ever need to specify a value_table during type registration because these value_tables are inherited from the parent types for non-fundamental types which means that unless you want to write a fundamental type (not a great idea !), you will not need to provide a new value_table since you will inherit the value_table structure from your parent type.

[2]Please, note that there exist another registration function: the g_type_register_dynamic. We will not discuss this function here since its use is very similar to the _static version.


The GObject base class

The two previous chapters discussed the details of Glib's Dynamic Type System and its signal control system. The GObject library also contains an implementation for a base fundamental type named GObject.

GObject is a fundamental classed Instantiable type. It implements:

  • Memory management with reference counting

  • Construction/Destruction of instances

  • Generic per-object properties with set/get function pairs

  • Easy use of signals

All the GTK+ objects and all of the objects in Gnome libraries which use the GLib type system inherit from GObject which is why it is important to understand the details of how it works.

Object instantiation

The g_object_new family of functions can be used to instantiate any GType which inherits from the GObject base type. All these functions make sure the class and instance structures have been correctly initialized by glib's type system and then invoke at one point or another the constructor class method which is used to:

  • Allocate and clear memory through g_type_create_instance,

  • Initialize the object' instance with the construction properties.

Although one can expect all class and instance members (except the fields pointing to the parents) to be set to zero, some consider it good practice to explicitly set them.

Objects which inherit from GObject are allowed to override this constructor class method: they should however chain to their parent constructor method before doing so:

  GObject*   (*constructor)     (GType type, guint n_construct_properties, GObjectConstructParam *construct_properties);

The example below shows how MamanBar overrides the parent's constructor:

#define MAMAN_TYPE_BAR		  (maman_bar_get_type ())
#define MAMAN_BAR(obj)		  (G_TYPE_CHECK_INSTANCE_CAST ((obj), MAMAN_TYPE_BAR, MamanBar))
#define MAMAN_BAR_CLASS(klass)	  (G_TYPE_CHECK_CLASS_CAST ((klass), MAMAN_TYPE_BAR, MamanBarClass))
#define MAMAN_IS_BAR(obj)	  (G_TYPE_CHECK_INSTANCE_TYPE ((obj), MAMAN_TYPE_BAR))
#define MAMAN_IS_BAR_CLASS(klass) (G_TYPE_CHECK_CLASS_TYPE ((klass), MAMAN_TYPE_BAR))
#define MAMAN_BAR_GET_CLASS(obj)  (G_TYPE_INSTANCE_GET_CLASS ((obj), MAMAN_TYPE_BAR, MamanBarClass))

typedef struct _MamanBar MamanBar;
typedef struct _MamanBarClass MamanBarClass;

struct _MamanBar {
  GObject parent;
  /* instance members */
};

struct _MamanBarClass {
  GObjectClass parent;

  /* class members */
};

/* used by MAMAN_TYPE_BAR */
GType maman_bar_get_type (void);

static GObject *
maman_bar_constructor (GType type, guint  n_construct_properties, GObjectConstructParam *construct_properties)
{
  GObject *obj;

  {
    /* Invoke parent constructor. */
    MamanBarClass *klass;
    GObjectClass *parent_class;
    klass = MAMAN_BAR_CLASS (g_type_class_peek (MAMAN_TYPE_BAR));
    parent_class = G_OBJECT_CLASS (g_type_class_peek_parent (klass));
    obj = parent_class->constructor (type, n_construct_properties, construct_properties);
  }

  /* do stuff. */

  return obj;
}

static void
maman_bar_instance_init (GTypeInstance  *instance, gpointer g_class)
{
  MamanBar *self = (MamanBar *)instance;
  /* do stuff */
}

static void
maman_bar_class_init (gpointer g_class, gpointer g_class_data)
{
  GObjectClass *gobject_class = G_OBJECT_CLASS (g_class);
  MamanBarClass *klass = MAMAN_BAR_CLASS (g_class);

  gobject_class->constructor = maman_bar_constructor;
}

GType maman_bar_get_type (void)
{
  static GType type = 0;
  if (type == 0) {
    static const GTypeInfo info = {
      sizeof (MamanBarClass),
      NULL,   /* base_init */
      NULL,   /* base_finalize */
      maman_bar_class_init,   /* class_init */
      NULL,   /* class_finalize */
      NULL,   /* class_data */
      sizeof (MamanBar),
      0,      /* n_preallocs */
      maman_bar_instance_init    /* instance_init */
    };
    type = g_type_register_static (G_TYPE_OBJECT, "MamanBarType", &info, 0);
  }
  return type;
}

If the user instantiates an object MamanBar with:

MamanBar *bar = g_object_new (MAMAN_TYPE_BAR, NULL);

If this is the first instantiation of such an object, the maman_b_class_init function will be invoked after any maman_b_base_class_init function. This will make sure the class structure of this new object is correctly initialized. Here, maman_bar_class_init is expected to override the object's class methods and setup the class' own methods. In the example above, the constructor method is the only overridden method: it is set to maman_bar_constructor.

Once g_object_new has obtained a reference to an initialized class structure, it invokes its constructor method to create an instance of the new object. Since it has just been overridden by maman_bar_class_init to maman_bar_constructor, the latter is called and, because it was implemented correctly, it chains up to its parent's constructor. The problem here is how we can find the parent constructor. An approach (used in GTK+ source code) would be to save the original constructor in a static variable from maman_bar_class_init and then to re-use it from maman_bar_constructor. This is clearly possible and very simple but I was told it was not nice and the prefered way is to use the g_type_class_peek and g_type_class_peek_parent functions.

Finally, at one point or another, g_object_constructor is invoked by the last constructor in the chain. This function allocates the object's instance' buffer through g_type_create_instance which means that the instance_init function is invoked at this point if one was registered. After instance_init returns, the object is fully initialized and should be ready to answer any user-request. When g_type_create_instance returns, g_object_constructor sets the construction properties (ie: the properties which were given to g_object_new) and returns to the user's constructor which is then allowed to do useful instance initialization...

The process described above might seem a bit complicated (it is actually overly complicated in my opinion..) but it can be summarized easily by the table below which lists the functions invoked by g_object_new and their order of invocation.

The array below lists the functions invoked by g_object_new and their order of invocation:

Table 1. g_object_new

Invocation time | Function Invoked | Function's parameters | Remark
First call to g_object_new for target type | target type's base_init function | On the inheritance tree of classes from fundamental type to target type. base_init is invoked once for each class structure. | I have no real idea on how this can be used. If you have a good real-life example of how a class' base_init can be used, please, let me know.
First call to g_object_new for target type | target type's class_init function | On target type's class structure | Here, you should make sure to initialize or override class methods (that is, assign to each class' method its function pointer) and create the signals and the properties associated to your object.
First call to g_object_new for target type | interface' base_init function | On interface' vtable |
First call to g_object_new for target type | interface' interface_init function | On interface' vtable |
Each call to g_object_new for target type | target type's class constructor method: GObjectClass->constructor | On object's instance | If you need to complete the object initialization after all the construction properties are set, override the constructor method and make sure to chain up to the object's parent class before doing your own initialization. In doubt, do not override the constructor method.
Each call to g_object_new for target type | type's instance_init function | On the inheritance tree of classes from fundamental type to target type. the instance_init provided for each type is invoked once for each instance structure. | Provide an instance_init function to initialize your object before its construction properties are set. This is the preferred way to initialize a GObject instance. This function is equivalent to C++ constructors.

Readers should feel concerned about one little twist in the order in which functions are invoked: while, technically, the class' constructor method is called before the GType's instance_init function (since g_type_create_instance which calls instance_init is called by g_object_constructor which is the top-level class constructor method and to which users are expected to chain to), the user's code which runs in a user-provided constructor will always run after GType's instance_init function since the user-provided constructor must (you've been warned) chain up before doing anything useful.

©2005-2006 Nokia


NGI SDK 1.0 - API Reference Guide: ngi::Index

The GObject messaging system

Closures

Closures are central to the concept of asynchronous signal delivery which is widely used throughout GTK+ and Gnome applications. A Closure is an abstraction, a generic representation of a callback. It is a small structure which contains three objects:

  • a function pointer (the callback itself) whose prototype looks like:

    return_type function_callback (... , gpointer user_data);

  • the user_data pointer which is passed to the callback upon invocation of the closure

  • a function pointer which represents the destructor of the closure: whenever the closure's refcount reaches zero, this function will be called before the closure structure is freed.

The GClosure structure represents the common functionality of all closure implementations: there exists a different Closure implementation for each separate runtime which wants to use the GObject type system. [7] The GObject library provides a simple GCClosure type which is a specific implementation of closures to be used with C/C++ callbacks.

A GClosure provides simple services:

  • Invocation (g_closure_invoke): this is what closures were created for: they hide the details of callback invocation from the callback invocator.

  • Notification: the closure notifies listeners of certain events such as closure invocation, closure invalidation and closure finalization. Listeners can be registered with g_closure_add_finalize_notifier (finalization notification), g_closure_add_invalidate_notifier (invalidation notification) and g_closure_add_marshal_guards (invocation notification). There exist symmetric de-registration functions for finalization and invalidation events (g_closure_remove_finalize_notifier and g_closure_remove_invalidate_notifier) but not for the invocation process. [8]

C Closures

If you are using C or C++ to connect a callback to a given event, you will either use the simple GCClosures which have a pretty minimal API or the even simpler g_signal_connect functions (which will be presented a bit later :).

GClosure* g_cclosure_new (GCallback  callback_func, gpointer  user_data, GClosureNotify   destroy_data);
GClosure* g_cclosure_new_swap (GCallback  callback_func, gpointer  user_data, GClosureNotify   destroy_data);
GClosure* g_signal_type_cclosure_new (GType  itype, guint  struct_offset);

g_cclosure_new will create a new closure which can invoke the user-provided callback_func with the user-provided user_data as last parameter. When the closure is finalized (second stage of the destruction process), it will invoke the destroy_data function if the user has supplied one.

g_cclosure_new_swap will create a new closure which can invoke the user-provided callback_func with the user-provided user_data as first parameter (instead of being the last parameter as with g_cclosure_new). When the closure is finalized (second stage of the destruction process), it will invoke the destroy_data function if the user has supplied one.

non-C closures

As was explained above, Closures hide the details of callback invocation. In C, callback invocation is just like function invocation: it is a matter of creating the correct stack frame for the called function and executing a call assembly instruction.

C closure marshallers transform the array of GValues which represent the parameters to the target function into a C-style function parameter list, invoke the user-supplied C function with this new parameter list, get the return value of the function, transform it into a GValue and return this GValue to the marshaller caller.

The following code implements a simple marshaller in C for a C function which takes an integer as first parameter and returns void.

g_cclosure_marshal_VOID__INT (GClosure *closure, GValue  *return_value, guint n_param_values,
                              const GValue *param_values, gpointer invocation_hint, gpointer marshal_data)
{
  typedef void (*GMarshalFunc_VOID__INT) (gpointer  data1, gint  arg_1, gpointer data2);
  register GMarshalFunc_VOID__INT callback;
  register GCClosure *cc = (GCClosure*) closure;
  register gpointer data1, data2;

  g_return_if_fail (n_param_values == 2);
  data1 = g_value_peek_pointer (param_values + 0);
  data2 = closure->data;
  callback = (GMarshalFunc_VOID__INT) (marshal_data ? marshal_data : cc->callback);
  callback (data1, g_marshal_value_peek_int (param_values + 1), data2);
}

Of course, there exist other kinds of marshallers. For example, James Henstridge wrote a generic Python marshaller which is used by all python Closures (a python closure is used to have python-based callback be invoked by the closure invocation process). This python marshaller transforms the input GValue list representing the function parameters into a Python tupple which is the equivalent structure in python (you can look in pyg_closure_marshal in pygtype.c in the pygtk module in Gnome cvs server).

[7] In Practice, Closures sit at the boundary of language runtimes: if you are writing python code and one of your Python callback receives a signal from one of GTK+ widgets, the C code in GTK+ needs to execute your Python code. The Closure invoked by the GTK+ object invokes the Python callback: it behaves as a normal C object for GTK+ and as a normal Python object for python code.

[8] Closures are refcounted and notify listeners of their destruction in a two-stage process: the invalidation notifiers are invoked before the finalization notifiers.


chdir

Name

chdir, fchdir
- change working directory

Library

 libc.lib

Synopsis
#include <unistd.h>
int chdir (const char *path);
int fchdir (int fd);

Return values

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

Detailed description

 The path argument points to the pathname of a directory. The chdir system call causes the named directory to become the current working directory, that is, the starting point for path searches of pathnames not beginning with a slash, ‘/.’

The fchdir system call causes the directory referenced by fd to become the current working directory, the starting point for path searches of pathnames not beginning with a slash, ‘/.’

Examples

/**
*  Detailed description   : This test code demonstrates usage of chdir system call
*
*  Preconditions : "Example" directory should be present in current working
   directory.
**/
#include <unistd.h>
int main()
{
  if(chdir("Example") < 0 )
  {
     printf("Failed to change working directory \n");
     return -1 ;
  }
  printf("Working directory changed \n");
  return 0 ;
}

Output

Working directory changed

#include<unistd.h>
#include<stdio.h>
int test_fchdir()
{
   int retVal;
   int rmdr;
   int mkdr = mkdir("test_dir", S_IWUSR);
   if( !mkdr )
   {
     int opn = open("test_dir", O_RDONLY);
     if( opn != -1 )
     {
       retVal = fchdir( opn );
       if( !retVal )
       {
         printf("Fchdir passed");
       }
       else
       {
         printf("Failed");
       }
       int cls = close(opn);
     }
     else
     {
       printf("Failed");
     }
     rmdr = rmdir("test_dir");
   }
   else
   {
     printf("Failed");
   }
}

Output

Fchdir passed

Errors

 The fchdir system call will fail and the current working directory will be unchanged if one or more of the following are true:
[ENOTDIR]
 | The file descriptor does not reference a directory.
[EBADF]
 | The argument fd is not a valid file descriptor.

See also

Feedback

For additional information or queries on this page send feedback


chmod

Name

chmod, fchmod, lchmod
- change permissions of a file

Library

 libc.lib

Synopsis
#include <sys/stat.h>
int chmod (const char *path, mode_t mode);
int fchmod (int fd, mode_t mode);
int lchmod (const char *path, mode_t mode);

Return values

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

Detailed description

 The file permission bits of the file named specified by path or referenced by the file descriptor fd are changed to mode. The chmod system call verifies that the process owner (user) either owns the file specified by path (or fd), or is the super-user. The chmod system call follows symbolic links to operate on the target of the link rather than the link itself.

The lchmod system call is similar to chmod but does not follow symbolic links.

A mode is created from or’d permission bit masks defined in
#include <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 */
#ifndef __BSD_VISIBLE
#define S_ISTXT 0001000    /* sticky bit */
#endif

Note : sticky bit and setuid on exec bit are not supported, permission values for users is considered while premissions values for group and others are ignored(As there is no concept of group and others). An attempt to change file permission to write-only changes the file permission to read-write. Permissions for directory will be ignored.

Limitation: 000 mode is tereated as invalid mode 000mode is tereated as invalid mode(i.e., both read and write permission absent for a file system entry), as symbian file sytem cannot have entries with both read and write permissions absent.

Examples

/*****************************************************************************************
* Detailed description: This test code demonstartes usage of chmod system call, it
* changes mode of file Example.txt in the current working directory to read-only.
*
* Preconditions: Example.txt file should be present in the current working directory.
*****************************************************************************************/
int main()
{
  if(chmod("Example.txt" , 0444) < 0 )
  {
     printf("change mode of file Example.txt failed \n");
     return -1;
  }
  printf("Chmod system call successful \n");
  return 0;
}

Output

Chmod system call successful

/******************************************************************************************
* Detailed description : This sample code demonstrates the usage of fchmod system call, this code
* changes mode of file Example.txt using fchmod system call.
*
******************************************************************************************/
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
int main()
{
 int fd = 0;
 fd = open("Example.txt" , O_CREAT | O_RDWR , 0666);
 if(fd < 0 )   {
    printf("Failed to open file Example.txt\n");
    return -1;
 }
 if(fchmod(fd , 0444) < 0 )  {
    printf("fchmod failed to change mode of file Example.txt \n");
    return -1;
 }
 printf("Fchmod call changed mode of Example.txt \n");
 return 0;
}

Output

Fchmod call changed mode of Example.txt

Errors

 The chmod system call 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 entire path name exceeded 1023 characters(Not supported).
[ENOENT]
 | The named file does not exist.
[EACCES]
 | Search permission is denied for a component of the path prefix(Not supported).
[ELOOP]
 | Too many symbolic links were encountered in translating the pathname( Not supported).
[EPERM]
 | The effective user ID does not match the owner of the file and the effective user ID is not the super-user(Not supported).
[EROFS]
 | The named file resides on a read-only file system(Not supported).
[EFAULT]
 | The path argument points outside the process’s allocated address space(Not supported).
[EFTYPE]
 | An attempt was made to set the sticky bit upon an executable(Not supported).
[EIO] | An I/O error occurred while reading from or writing to the file system(Not supported).

The fchmod system call will fail if:
[EBADF]
 | The descriptor is not valid.
[EINVAL]
 | The fd argument 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 file system(Not supported).

See also

 chmod, chown, open, stat

Feedback

For additional information or queries on this page send feedback


chown

Name

chown, lchown
- change ownership of a file

Library

 libc.lib

Synopsis
#include <unistd.h>
int chown (const char *path, uid_t owner, gid_t group);
int lchown (const char *path, uid_t owner, gid_t group);

Return values

 These functions always return 0.

Detailed description

 chown and lchown are functions belonging to set of APIs which are only build supported and not available functionally. The reason why only build support is extended to these APIs is, symbian operating system does not support creation of multiple users and groups in its environment. More over it may not make sense to have multiple users and groups in the context of a mobile environment.

Errors

 No error values are set.

See also

Feedback

For additional information or queries on this page send feedback


clock

Name

clock - determines processor time

Library

 libc.lib

Synopsis
#include <time.h>
clock_t clock (void);

Return values

 clock is just a build support and hence returns 0.

Detailed description

The clock function determines the amount of processor time used since the invocation of the calling process, measured in CLOCKS_PER_SEC s of a second.

Note: clock system call eventually calls symbian call user::GetCpuTime(), which is not supported from version 8.0b, hence this api is just a build support api.

See also

Feedback

For additional information or queries on this page send feedback


clock_gettime

Name

clock_gettime, clock_settime, clock_getres, clock_getcpuclockid
- clock and time functions

Library

 libc.lib

Synopsis
#include <sys/time.h>
int clock_gettime (clockid_t clock_id, struct timespec *tp);
int clock_settime (clockid_t clock_id, const struct timespec *tp);
int clock_getres (clockid_t clock_id, struct timespec *tp);
int clock_getcpuclockid (pid_t pid, clockid_t* clock_id);

Return values

 All the above APIs return 0 on success and -1 on failure.

Detailed description

 The clock_gettime and clock_settime allow the calling process to retrieve or set the value used by a clock which is specified by clock_id.

The clock_id argument can be one of four values: CLOCK_REALTIME for time that increments as a wall clock should, CLOCK_MONOTONIC which increments in SI seconds, CLOCK_VIRTUAL for time that increments only when the CPU is running in user mode on behalf of the calling process, or CLOCK_PROF for time that increments when the CPU is running in user or kernel mode. As of now Symbian OS exposes only wall clock time at user level,hence we support only CLOCK_REALTIME for all the clock-based APIs.

The structure pointed to by tp is defined in
#include <sys/time.h>as:

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

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

The clock ID of the CPU-time clock of the process specified by pid is returned by the clock_getcpuclockid system call. If pid is zero,the clock ID of the CPU-time clock of the process making the call, is returned in. *clock_id.

Examples

#include <time.h>
#include <stdio.h>
int clock_user()
{
        struct timespec tp;
        int retval;
        clockid_t clockid;
        clock_getres (CLOCK_REALTIME, &tp); //Call clock_getres
        printf ("Real time-clock resolution is %d seconds and %d nanoseconds\n", tp.tv_sec, tp.tv_nsec);
        clock_getcpuclockid (0 ,&clockid); //Call clock_getcpuclockid with pid = 0
        printf ("The clock id for the current process is %d\n", clockid);
        tp.tv_sec = 0;
        tp.tv_nsec = 100;
        retval = clock_settime (CLOCK_REALTIME, &tp); //Call clock_settime with 100ns
        printf ("clock_settime returned %d\n", retval);
        clock_gettime (CLOCK_REALTIME, &tp); //Call clock_gettime to fill tp
        printf ("Time from real time-clock is %d seconds and %d nanoseconds\n", tp.tv_sec, tp.tv_nsec);
        return 0;
}

Output

Real time-clock resolution is 0 seconds and 1000000 nanoseconds
The clock id for the current process is 0
clock_settime returned 0
Time from real time-clock is 0 seconds and 70663000 nanoseconds

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.

See also

 adjtime, ctime

Feedback

For additional information or queries on this page send feedback


close

Name

close - closes a file descriptor

Library

 libc.lib

Synopsis
#include <unistd.h>
int close (int d);

Return values

 The close() function returns the value 0 if successful; otherwise the value -1 is returned and the global variable errno is set to indicate the error.

Detailed description

 The close system call deletes a descriptor from the per-process object reference table. If this is the last reference to the underlying object, the object will be deactivated. For example, on the last close of a file the current seek pointer associated with the file is lost; on the last close of a socket any file descriptor for that file is closed by that process.

When a process exits, all associated file descriptors are freed, but since there is a limit on active descriptors per processes, the close system call is useful when a large quantity of file descriptors are being handled.

Examples

/********************************************************************************************
* Detailed description   : This test code demonstrates usage of close  system call
*
* Preconditions :  None.
*******************************************************************************************/
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <fcntl.h>
int main()
{
  int fd = 0;
  fd = open("Example.txt" , O_CREAT | O_RDWR , 0666);
  if(fd < 0 )
  {
    printf("Failed to open file Example.txt \n");
    return -1;
  }
 if(close(fd) < 0 )
 {
   printf("Failed to close  file Example.txt \n");
   return -1;
 }
 printf("File Example.txt closed \n" );
 return 0;
}

Output

File Example.txt closed

Errors

 The close system call will fail if:
[EBADF]
 | The d argument is not an active descriptor.
[EINTR]
 | An interrupt was received(Not supported).
[ENOSPC]
 | The underlying object did not fit, cached data was lost(Not supported).

See also

 accept, fcntl, flock, open, pipe, socket

Feedback

For additional information or queries on this page send feedback


closedir

Name

opendir, readdir, readdir_r, telldir, seekdir, rewinddir, closedir, dirfd
- directory operations

Library

 libc.lib

Synopsis
#include <sys/types.h>
#include <dirent.h>
DIR * opendir (const char *filename);
struct dirent * readdir (DIR *dirp);
int readdir_r (DIR *dirp, struct dirent *entry, struct dirent **result);
long telldir (DIR *dirp);
void seekdir (DIR *dirp, long loc);
void rewinddir (DIR *dirp);
int closedir (DIR *dirp);
int dirfd (DIR *dirp);

Return values

closedir function returns 0 on success or -1 on failure.

Detailed description

 The opendir function opens the directory named by filename, associates a directory stream with it and returns a pointer to be used to identify the directory stream in subsequent operations. The pointer NULL is returned if filename cannot be accessed, or if it cannot malloc enough memory to hold the whole thing.

The readdir function returns a pointer to the next directory entry. It returns NULL upon reaching the end of the directory or detecting an invalid seekdir operation.

The readdir_r function provides the same functionality as readdir, but the caller must provide a directory entry buffer to store the results in. If the read succeeds, result is pointed at the entry; upon reaching the end of the directory result is set to NULL. The readdir_r function returns 0 on success or an error number to indicate failure.

The telldir function returns the current location associated with the named directory stream. Values returned by telldir are good only for the lifetime of the DIR pointer, dirp, from which they are derived. If the directory is closed and then reopened, prior values returned by telldir will no longer be valid.

The seekdir function sets the position of the next readdir operation on the directory stream. The new position reverts to the one associated with the directory stream when the telldir operation was performed.

The rewinddir function resets the position of the named directory stream to the beginning of the directory.

The closedir function closes the named directory stream and frees the structure associated with the dirp pointer, returning 0 on success. On failure, -1 is returned and the global variable errno is set to indicate the error.

The dirfd function returns the integer file descriptor associated with the named directory stream, see open

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;

Examples

/**
* Detailed description: This test code demonstrates usage of close  system call.
*
* Preconditions: Expects Test directory to be present in current working directory.
**/
 #include <sys/types.h>
 #include <dirent.h>
int main()
{
  DIR *DirHandle;
  if(!(DirHandle = opendir("Test") ) )
  {
     printf("Failed to open directoy Test \n");
     return -1;
  }
  if(closedir(DirHandle) < 0 )
  {
     printf("Close dir failed \n");
     return -1;
  }
  printf("Directory Test closed \n");
  return 0;
}

Output

Directory Test closed

See also

 close, lseek, open, read,
The opendir, readdir, telldir, seekdir, rewinddir, closedir, and dirfd functions appeared in BSD 4.2.

Feedback

For additional information or queries on this page send feedback


CONF_modules_unload - OpenSSL configuration cleanup functions

Name

CONF_modules_free, CONF_modules_load
CONF_modules_unload
OpenSSL configuration cleanup functions.

Library

libcrypto.lib

Synopsis

#include <openssl/conf.h>
void CONF_modules_free(void);
void CONF_modules_unload(int all);
void CONF_modules_finish(void);

Detailed Description

CONF_modules_free() closes down and frees up all memory allocated by all configuration modules.

CONF_modules_finish() calls each configuration modules finish handler to free up any configuration that module may have performed.

CONF_modules_unload() finishes and unloads configuration modules. If all is set to 0 only modules loaded from DSOs will be unloads. If all is 1 all modules, including built-in modules will be unloaded.

Notes

Normally applications will only call CONF_modules_free() at application to tidy up any configuration performed.

Return Values

None of the functions return a value.

See Also

conf(),
OPENSSL_config(),
CONF_modules_load_file()

History

CONF_modules_free(), CONF_modules_unload(), and CONF_modules_finish() first appeared in OpenSSL 0.9.7.

Feedback

For additional information or queries on this page send feedback


CONF_modules_load - OpenSSL configuration functions

Name

CONF_modules_load_file, CONF_modules_load — OpenSSL configuration functions

Library

libcrypto

Synopsis

#include <openssl/conf.h>
int CONF_modules_load_file(const char *filename, const char *appname, unsigned long flags);
int CONF_modules_load(const CONF *cnf, const char *appname, unsigned long flags);

Detailed Description

The function CONF_modules_load_file() configures OpenSSL using file filename and application name appname. If filename is NULL the standard OpenSSL configuration file is used. If appname is NULL the standard OpenSSL application name openssl_conf is used. The behaviour can be customized using flags.

CONF_modules_load() is identical to CONF_modules_load_file() except it read configuration information from cnf.

Notes

The following flags are currently recognized:

CONF_MFLAGS_IGNORE_ERRORS if set errors returned by individual configuration modules are ignored. If not set the first module error is considered fatal and no further modules are loads.

Normally any modules errors will add error information to the error queue. If CONF_MFLAGS_SILENT is set no error information is added.

If CONF_MFLAGS_NO_DSO is set configuration module loading from DSOs is disabled.

CONF_MFLAGS_IGNORE_MISSING_FILE if set will make CONF_load_modules_file() ignore missing configuration files. Normally a missing configuration file return an error.

Return Value

These functions return 1 for success and a zero or negative value for failure. If module errors are not ignored the return code will reflect the return value of the failing module (this will always be zero or negative).

See Also

conf(),
OPENSSL_config(),
CONF_free(), err()

History

CONF_modules_load_file and CONF_modules_load first appeared in OpenSSL 0.9.7.

Feedback

For additional information or queries on this page send feedback

©2005-2006 Nokia


confstr

Name

confstr - get configuration dependent string variables

Library

 libc.lib

Synopsis
#include <unistd.h>
size_t confstr (int name, char *buf, size_t len);

Return values

 If the call to confstr is not successful, 0 is returned and errno is set appropriately. Otherwise, if the variable does not have a configuration defined value, 0 is returned and errno is not modified. Otherwise, the buffer size needed to hold the entire configuration-defined value is returned. If this size is greater than the argument len, the string in buf was truncated.

Detailed description

 The confstr function provides a method for applications to get configuration defined string values.

The name argument specifies the system variable to be queried. Symbolic constants for each name value are found in the include file
#include <unistd.h.>The len argument specifies the size of the buffer referenced by the argument buf. If len is non-zero, buf is a non-null pointer, and name has a value, up to len - 1 bytes of the value are copied into the buffer buf. The copied value is always null terminated.

The available values are as follows:

_CS_PATH
Return a value for the PATH environment variable that finds all the standard utilities.

Examples

#include<unistd.h>
#include<stdio.h>
#include <stdlib.h>

int main()
{
 int n = 0;
 char *buf = NULL;
 int len = 0;

 n = confstr(_CS_PATH, NULL, 0);

 printf("{Expected: 31} %d\n", n);

 if( n == 0 )
    return -1;

 buf = (char *)malloc(n);

 if ( buf == NULL )
 {
    printf("malloc failed!!");
    return -1;
 }

 len = confstr(_CS_PATH, buf, n);

 printf("PATH in buffer: \n%s", buf);
 printf("\nlength: %d", len);
 free(buf);

 return 0;
}

Output

PATH in buffer:
/usr/bin:/bin:/usr/sbin:/sbin:
length: 31

Errors
[EINVAL]
The value of the name argument is invalid.

See also

 pathconf, sysconf

Feedback

For additional information or queries on this page send feedback


connect

Name

connect - initiates a connection on a socket

Library

 libc.lib

Synopsis
#include <sys/types.h>
#include <sys/socket.h>
int connect (int s, const struct sockaddr *name, socklen_t namelen);

Detailed description

 The s argument is a socket. If it is of type SOCK_DGRAM, this call specifies the peer with which the socket is to be associated; this address is that to which datagrams are to be sent, and the only address from which datagrams are to be received. If the socket is of type SOCK_STREAM, this call attempts to make a connection to another socket. The other socket is specified by name, which is an address in the communications space of the socket. Each communications space interprets the name argument in 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.

Examples

#include <sys/socket.h>
#include <netinet/in.h>
#include <unistd.h>
void Connect()
{
   struct sockaddr_in serv_addr;
   int sock_fd;
   serv_addr.sin_family = AF_INET;
   serv_addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
   serv_addr.sin_port = htons(5000);
   sock_fd = socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
   connect(sock_fd,(struct sockaddr*)&serv_addr,sizeof(serv_addr));

   close(sock_fd);
}

Return values

 The connect() 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 connect system call fails if:
[EBADF]
 | The s argument is not a valid descriptor.
[ENOTSOCK]
 | The s argument is a descriptor for a file, not a socket.
[EADDRNOTAVAIL]
 | The specified address is not available on this machine.
[EAFNOSUPPORT]
 | Addresses in the specified address family cannot be used with this socket.
[EISCONN]
 | The socket is already connected.
[ETIMEDOUT]
 | Connection establishment timed out without establishing a connection.
[ECONNREFUSED]
 | The attempt to connect was forcefully rejected.
[ENETUNREACH]
 | The network is not reachable from this host.
[EHOSTUNREACH]
 | The remote host is not reachable from this host.
[EADDRINUSE]
 | The address is already in use.
[EFAULT]
 | The name argument specifies an area outside the process address space.
[EINVAL]
 | The namelen argument is invalid.
[EINPROGRESS]
 | The socket is non-blocking and the connection cannot be completed immediately. It is possible to select for completion by selecting the socket for writing.
[EALREADY]
 | A previous connection attempt has not yet been completed.
[EACCES]
 | An attempt is made to connect to a broadcast address (obtained through the INADDR_BROADCAST constant or the INADDR_NONE return value) through a socket that does not provide broadcast functionality.

The following errors are specific to connecting names in the UNIX domain. These errors may not apply in future versions of the UNIX IPC domain.
[ENOTDIR]
 | A component of the path prefix is not a directory.
[ENAMETOOLONG]
 | A component of a pathname exceeded 255 characters, or an entire path 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 pathname.

See also

 accept, getpeername, getsockname, select, socket
The connect system call appeared in BSD 4.2.

Feedback

For additional information or queries on this page send feedback


copysign

Name

copysign, copysignf, copysignl,
- copy sign of a number

Library

 libm.lib

Synopsis
#include <math.h>
double copysign (double x, double y);
float copysignf (float x, float y);
long double copysignl (long double x, long double y);

Detailed description

 The copysign, copysignf, and copysignl functions return x with its sign changed to y ’s.

Examples

#include <math.h>
void main( void )
{
   double x1 = 0, x2 = -4, y;
   y = copysign( x1, x2 );
   printf( "copysign(%f , %f) = %f\n", x1, x2, y );
   y = copysignf( x1, x2 );
   printf( "copysignf(%f , %f) = %f\n", x1, x2, y );
   y = copysignl( x1, x2 );
   printf( "copysignl(%f , %f) = %f\n", x1, x2, y );
}

Output

copysign ( 0, -4 ) = -0.0
copysignf( 0, -4 ) = -0.0
copysignl( 0, -4 ) = -0.0

See also

 fabs, fdim, ieee, math

Feedback

For additional information or queries on this page send feedback


cos

Name

cos, cosf, cosl,
- cosine function

Library

 libm.lib

Synopsis
#include <math.h>
double cos (double x);
float cosf (float x);
long double cos (long double x);

Return values

 The cos, cosf, and cosl functions return the cosine value.

Detailed description

 The cos and cosf functions compute the cosine of x (measured in radians). A large magnitude argument may yield a result with little or no significance. The function cosl is an alias to the function cos.

Examples

#include <math.h>
int main( void )
{
   double pi = 3.1415926535;
   double x, y;
   x = pi / 2;
   y = cos( x );
   printf( "cos( %f ) = %f\n", x, y );
   y = cosf( x );
   printf( "cosf( %f ) = %f\n",x, y );
   y = cosl( x );
   printf( "cosl( %f ) = %f\n",x, y );
}

Output

cos ( 1.570796 ) = 0.000000
cosf( 1.570796 ) = 0.000000
cosl( 1.570796 ) = 0.000000

See also

 acos, asin, atan, atan2, cosh, math, sin, sinh, tan, tanh
The cos function conforms to -isoC.

Feedback

For additional information or queries on this page send feedback


cosh

Name

cosh, coshf, coshl
- hyperbolic cosine function

Library

 libm.lib

Synopsis
#include <math.h>
double cosh (double x);
float coshf (float x);
long double cosh (long double x);

Detailed description

 The cosh, and coshf functions compute the hyperbolic cosine of x. The function coshl is an alias to the function cosh.

Examples

#include <math.h>
int main( void )
{
   double pi = 3.1415926535;
   double x, y;
   x = pi / 2;
   y = cosh( x );
   printf( "cosh( %f ) = %f\n", x, y );
   y = coshf( x );
   printf( "coshf( %f ) = %f\n",x, y );
   y = coshl( x );
   printf( "coshl( %f ) = %f\n",x, y );
}

Output

cosh( 1.570796 ) = 2.509178
coshf( 1.570796 ) = 2.509178
coshl( 1.570796 ) = 2.509178

See also

 acos, asin, atan, atan2, cos, math, sin, sinh, tan, tanh
The cosh function conforms to -isoC.

Feedback

For additional information or queries on this page send feedback


creat

Name

creat - creates a file or device

Library

 libc.lib

Synopsis
#include <fcntl.h>
int creat (const char *path, mode_t mode);

Return values

open and creat return the new file descriptor, or -1 if an error occurred(in which case, errno is set appropriately).

atime , mtime fields are set to the current time. If the file is modified because of the O_TRUNC flag, its atime , mtime fields are set to the current time.

Detailed description

 This interface is made obsolete by:
open

The creat function is the same as:

open(path, O_CREAT | O_TRUNC | O_WRONLY, mode);

Limitation :Creating a new file doesn’t alter the time stamp of parent directory, created entry has only two time stamps access and modification timestamps.
Creation time stamp of the file is not supported, here accesstime stamp is equal to modification time stamp.

Examples

/***************************************************************************************
* Detailed description   : This test code demonstrates creat system call usage, it creates a
* in current working directory(if file exists then it is truncated.
*
* Preconditions : None
***************************************************************************************/
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
int main()
{
 int fd = 0;
  fd = creat("Example.txt" , 0666);
  if(fd < 0 )
  {
    printf("File creation failed \n");
    return -1;
  }
  printf("Example.txt file created \n");
  return 0;
}

Output

Example.txt file created

See also

 open

Feedback

For additional information or queries on this page send feedback


crypt

Name

crypt
- password and data encryption

Library

 libcrypt.lib

Synopsis
#include <unistd.h>
char * crypt (const char *key, const char *salt);

Return values

 The crypt function returns a pointer to the encrypted value on success, and NULL on failure.

Detailed description

 The crypt function performs password hashing with additional code added to thwart dictionary attack. Different algorithms can be used in the hash. Currently the implementation supports Data Encryption Standard (DES) and MD5 hash algorithms. However, the actual algorithm used during the call to crypt depends on the salt parameter.

The first argument to crypt is the data to hash (usually a password), in a NULL -terminated string. The second is the salt, in one of two forms:

Modular | If salt begins with the string "$digit$" then the Modular Crypt Format is used.
Traditional
 | salt parameter is a two-character string chosen from the set [a-zA-Z0-9./].

Modular crypt:

If salt begins with the string $digit$ then Modular Crypt Format is used. The digit identifies the algorithm used for encryption. Currently MD5 hash is implemented. So digit will be 1 and hence the second argument to this function will be a string beginning with "$1$" followed by at most 8 characters (actual salt to be used in the encryption), and optionally terminated by "$" If the optional "$" is included then the characters following the dollar sign are ignored. The output of this operation will be a string containing 34 characters in the format "$1$<string>$"

"<string>" consists of the actual salt (the at most 8 characters string following "$1$" in the salt), followed by 22 bytes of data from the set [a-zA-Z0-9./].

Other crypt formats may be easily added. An example salt would be:
$4$thesalt$rest

Traditional crypt:

It is based on Data Encryption Standard algorithm (DES). salt is a two-character string chosen from the set [a-zA-Z0-9./]. In order to thwart the Dictionary Attack, the two-character salt is used to perturb the algorithm in 4096 ways.

The 56-bit key for the DES algorithm is obtained by taking the lowest 7 bits of each of the first eight characters of the key. The key thus obtained is used to encrypt a constant string (a string containing all zeroes).

The return value of this function is a pointer to a static buffer. So the function is not reentrant.

Example

#include <stdlib.h>
#include <unistd.h>
void crypt_user()
{
        char *p = NULL,
             *q = NULL;
        /* Invoke crypt() to perform password hashing */
        p = crypt("password", "S1");    /* p contains the hash of "password"
                                                 * when "S1" is used as the key. DES
                                                 * encryption algoritm is used in this
                                                 * scenario
                                                 */
        q = crypt("password", "$1$Salt1");
                                                /* q contains the hash of "password"
                                                 * as computed by the MD5 hash algorithm
                                                 */
}

See also

Bugs

 Output of crypt differs from that of Linux’s when NULL passed as salt.

Feedback

For additional information or queries on this page send feedback


CRYPTO_cleanup_all_ex_data

Name

CRYPTO_cleanup_all_ex_data:This function is used to cleanup application specific data and should be called before the application shuts down to avoid memory leaks.

Synopsis

void CRYPTO_cleanup_all_ex_data(void)

Detailed description

This function is used to cleanup application specific data and should be called before the application shuts down to avoid memory leaks.

Feedback

For additional information or queries on this page send feedback

© 2006-2007 Nokia


CRYPTO_get_ex_data - internal application specific data functions

Name

CRYPTO_set_ex_data, CRYPTO_get_ex_data — internal application specific data functions

Library

libcrypto.lib

Synopsis

int CRYPTO_set_ex_data(CRYPTO_EX_DATA *r, int idx, void *arg);
void *CRYPTO_get_ex_data(CRYPTO_EX_DATA *r, int idx);

Detailed Description

Several OpenSSL structures can have application specific data attached to them. These functions are used internally by OpenSSL to manipulate application specific data attached to a specific structure.

These functions should only be used by applications to manipulate CRYPTO_EX_DATA structures passed to the new_func(), free_func() and dup_func() callbacks: as passed to RSA_get_ex_new_index() for example.

CRYPTO_set_ex_data() is used to set application specific data, the data is supplied in the arg parameter and its precise meaning is up to the application.

CRYPTO_get_ex_data() is used to retrieve application specific data. The data is returned to the application, this will be the same value as supplied to a previous CRYPTO_set_ex_data() call.

Return Values

CRYPTO_set_ex_data() returns 1 on success or 0 on failure.

CRYPTO_get_ex_data() returns the application data or 0 on failure. 0 may also be valid application data but currently it can only fail if given an invalid idx parameter.

On failure an error code can be obtained from ERR_get_error().

See Also

RSA_get_ex_new_index(),
DSA_get_ex_new_index(),
DH_get_ex_new_index()

History

CRYPTO_set_ex_data() and CRYPTO_get_ex_data() have been available since SSLeay 0.9.0.

Feedback

For additional information or queries on this page send feedback


ctermid

Name

ctermid - gets controlling terminal name

Library

 libc.lib

Synopsis
#include <stdio.h>
char * ctermid (char *buf);
char * ctermid_r (char *buf);

Return values

 Upon successful completion, a non- NULL pointer is returned. Otherwise, a NULL pointer is returned and the global variable errno is set to indicate the error.

Detailed description

 The ctermid function generates a string, that, when used as a pathname, refers to the current controlling terminal of the calling process.

If buf is the NULL pointer, a pointer to a static area is returned. Otherwise, the pathname is copied into the memory referenced by buf. The argument buf is assumed to be at least L_ctermid (as defined in the include file
#include <stdio.h )>bytes long.

The ctermid_r function provides the same functionality as ctermid except that if buf is a NULL pointer, NULL is returned.

The current implementation simply returns ‘/dev/tty.’

Errors

 The current implementation detects no error conditions.

See also
The ctermid function conforms to -p1003.1-88.

Bugs

 By default the ctermid function writes all information to an internal static object. Subsequent calls to ctermid will modify the same object.

Feedback

For additional information or queries on this page send feedback


ctime

Name

asctime, asctime_r, ctime, ctime_r, difftime
gmtime, gmtime_r, localtime, localtime_r, mktime

- transform date and time to broken-down time ASCII

Library

 libc.lib

Synopsis
#include <time.h>
char * ctime (const time_t *clock);
double difftime (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_t mktime (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);

Return values

mktime ) in case an error was detected.

Detailed description

 The functions ctime, gmtime and localtime all take as an argument a time value representing the time in seconds since the Epoch (00:00:00 UTC, January 1, 1970; see time

The function localtime converts the time value pointed at by clock, and returns a pointer to a "struct tm" (described below) which contains the broken-out time information for the value after adjusting for the current time zone (and any other factors such as Daylight Saving Time). Time zone adjustments are performed as specified by the TZ environment variable (see tzset The function localtime uses tzset to initialize time conversion information if tzset has not already been called by the process.

After filling in the tm structure, localtime sets the tm_isdst’s Nth element of tzname to a pointer to a ASCII string that is the time zone abbreviation to be used with localtime’s (return, value.);

The function gmtime similarly converts the time value, but without any time zone 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 same manner 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 caller must provide the output buffer buf to store the result, which must be at least 26 characters long. The localtime_r and gmtime_r functions provide the same functionality as localtime and gmtime respectively, except the caller must provide the output buffer result.

The asctime function converts the broken down time in the structure tm pointed at by *tm to the form shown in the example above.

The asctime_r function provides the same functionality as asctime except the caller provide the output buffer buf to store the result, which must be at least 26 characters long.

The functions mktime converts the broken-down time in the structure pointed to by tm into a time value with the same encoding as that of the values returned by the time function (that is, seconds from the Epoch, UTC). The mktime function interprets the input structure according to the current timezone setting (see tzset

The original values of the tm_wday and tm_yday components of the structure are ignored, and the original values of the other components are not restricted to their normal ranges, and will be normalized if needed. For example, October 40 is changed into November 9, a tm_hour of -1 means 1 hour before midnight, tm_mday of 0 means the day preceding the current month, and tm_mon of -2 means 2 months before January of tm_year. (A positive or zero value for tm_isdst causes mktime to presume initially that summer time (for example, Daylight Saving Time) is or is not in effect for the specified time, respectively. A negative value for tm_isdst causes the mktime function to attempt to define whether summer time is in effect for the specified time. The tm_isdst and tm_gmtoff members are forced to zero by timegm.)

On successful completion, the values of the tm_wday and tm_yday components of the structure are set appropriately, and the other components are set to represent the specified calendar time, but with their values forced to their normal ranges; the final value of tm_mday is not set until tm_mon and tm_year are determined. The mktime function returns the specified calendar time; if the calendar time cannot be 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
#include <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.

Examples

//Example usage of asctime,localtime and gmtime:
#include <time.h>
#include <stdio.h>
int main(){
        time_t t;
        struct tm *timeptr;
        char* asc_time;
        t = time (NULL); //Get current time in seconds from Epoc
        //Fill tm struct w.r.t localtime using localtime
        timeptr = localtime (&t);
        //Use this to convert it to a string indicating time w.r.t localtime
        asc_time = asctime (timeptr);
        printf ("Time from asctime w.r.t localtime : %s", asc_time);
        //Fill tm struct w.r.t GMT using gmtime
        timeptr = gmtime (&t);
        //Use this to convert it to a string indicating time w.r.t GMT
        asc_time = asctime (timeptr);
        printf ("Time from asctime w.r.t gmtime : %s", asc_time);
        return 0;
}

Output

Time from asctime w.r.t localtime : Thu Jun 22 10:42:27 2006
Time from asctime w.r.t gmtime : Thu Jun 22 05:12:27 2006

//Example usage of ctime,mktime:
#include <time.h>
#include <stdio.h>
int main(){
        time_t t;
        struct tm timeptr;
        char* c_time;
        //Fill the tm struct with values
        timeptr.tm_year = 2001;
        timeptr.tm_mon = 6;
        timeptr.tm_mday = 4;
        timeptr.tm_hour = 0;
        timeptr.tm_min = 0;
        timeptr.tm_sec = 1;
        timeptr.tm_isdst = -1;
        t = mktime (&timeptr); //Call mktime to make time in seconds w.r.t epoc
        //Convert this to a string indicating time using ctime
        c_time = ctime (&t);
        printf ("Time from ctime : %s", c_time);
        return 0;
}

Output

Time from ctime : Thu Jan  1 05:29:59 1970

//Example usage of difftime:
#include <time.h>
#include <unistd.h>
#include <stdio.h>
int main(){
        time_t t0,t1,t2;
        //Set initial and final values
        t0 = 10;
        t1 = 20;
        t2 = difftime (t1, t0); //Find the time difference using difftime
        printf ("Result of difftime = %d", t2);
        return 0;
}

Output

Result of difftime = 10

See also

 gettimeofday, getenv, time, tzset
The asctime, ctime, difftime, gmtime, localtime, and mktime functions conform to -isoC, and conform to -p1003.1-96 provided the selected local timezone does not contain a leap-second table.

The asctime_r, ctime_r, gmtime_r, and localtime_r functions are expected to conform to -p1003.1-96 (again provided the selected local timezone does not contain a leap-second table).

The timegm function is not specified by any standard; its function cannot be completely emulated using the standard functions described above.

This manual page is derived from the time package contributed to Berkeley by Arthur Olson and which appeared in BSD 4.3.

Bugs

 Except for difftime, mktime, and the _r variants of the other functions, these functions leaves their result in an internal static object and return a pointer to that object. Subsequent calls to these function will modify the same object.

The C Standard provides no mechanism for a program to modify its current local timezone 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 subsequent call to tzset

Feedback

For additional information or queries on this page send feedback


i2d_ASN1_OBJECT - ASN1 OBJECT IDENTIFIER functions

Name

d2i_ASN1_OBJECT, i2d_ASN1_OBJECT — ASN1 OBJECT IDENTIFIER functions

Library

libcrypto.lib

Synopsis

#include <openssl/objects.h>
ASN1_OBJECT *d2i_ASN1_OBJECT(ASN1_OBJECT **a, unsigned char **pp, long length);
int i2d_ASN1_OBJECT(ASN1_OBJECT *a, unsigned char **pp);

Detailed Description

These functions decode and encode an ASN1 OBJECT IDENTIFIER.

Otherwise these behave in a similar way to
d2i_X509() and
i2d_X509()
described in the d2i_X509() manual page.

See Also

d2i_X509()

History

TBA

Feedback

For additional information or queries on this page send feedback


i2d_DHparams - PKCS#3 DH parameter functions.

Name

d2i_DHparams, i2d_DHparams — PKCS#3 DH parameter functions

Library

libcrypto.lib

Synopsis

#include <openssl/dh.h>
DH *d2i_DHparams(DH **a, unsigned char **pp, long length);
int i2d_DHparams(DH *a, unsigned char **pp);

Detailed Description

These functions decode and encode PKCS#3 DH parameters using the DHparameter structure described in PKCS#3.

Otherwise these behave in a similar way to
d2i_X509() and

i2d_X509()
described in the d2i_X509() manual page.

See Also

d2i_X509()

History

TBA

Feedback

For additional information or queries on this page send feedback


i2d_DSA_SIG - DSA key encoding and parsing functions.

Name

d2i_DSAPublicKey, i2d_DSAPublicKey
d2i_DSAPrivateKey, i2d_DSAPrivateKey
d2i_DSA_PUBKEY, i2d_DSA_PUBKEY
d2i_DSA_SIG, i2d_DSA_SIG

DSA key encoding and parsing functions

Library

libcrypto.lib

Synopsis

#include <openssl/dsa.h>
#include <openssl/x509.h>
DSA * d2i_DSAPublicKey(DSA **a, const unsigned char **pp, long length);
int i2d_DSAPublicKey(const DSA *a, unsigned char **pp);
DSA * d2i_DSA_PUBKEY(DSA **a, const unsigned char **pp, long length);
int i2d_DSA_PUBKEY(const DSA *a, unsigned char **pp);
DSA * d2i_DSAPrivateKey(DSA **a, const unsigned char **pp, long length);
int i2d_DSAPrivateKey(const DSA *a, unsigned char **pp);
DSA * d2i_DSAparams(DSA **a, const unsigned char **pp, long length);
int i2d_DSAparams(const DSA *a, unsigned char **pp);
DSA * d2i_DSA_SIG(DSA_SIG **a, const unsigned char **pp, long length);
int i2d_DSA_SIG(const DSA_SIG *a, unsigned char **pp);

Detailed Description

d2i_DSAPublicKey() and i2d_DSAPublicKey() decode and encode the DSA public key components structure.

d2i_DSA_PUBKEY() and i2d_DSA_PUBKEY() decode and encode an DSA public key using a SubjectPublicKeyInfo (certificate public key) structure.

d2i_DSAPrivateKey(), i2d_DSAPrivateKey() decode and encode the DSA private key components.

d2i_DSAparams(), i2d_DSAparams() decode and encode the DSA parameters using a Dss-Parms structure as defined in RFC2459.

d2i_DSA_SIG(), i2d_DSA_SIG() decode and encode a DSA signature using a Dss-Sig-Value structure as defined in RFC2459.

The usage of all of these functions is similar to the d2i_X509() and i2d_X509() described in the d2i_X509() manual page.

Notes

The DSA structure passed to the private key encoding functions should have all the private key components present.

The data encoded by the private key functions is unencrypted and therefore offers no private key security.

The DSA_PUBKEY functions should be used in preference to the DSAPublicKey functions when encoding public keys because they use a standard format.

The DSAPublicKey functions use an non standard format the actual data encoded depends on the value of the write_params field of the a key parameter. If write_params is zero then only the pub_key field is encoded as an INTEGER. If write_params is 1 then a SEQUENCE consisting of the p, q, g and pub_key respectively fields are encoded.

The DSAPrivateKey functions also use a non standard structure consisting consisting of a SEQUENCE containing the p, q, g and pub_key and priv_key fields respectively.

See Also

d2i_X509()

History

TBA

Feedback

For additional information or queries on this page send feedback


i2d_PKCS8PrivateKey_nid_fp - PKCS#8 format private key functions

Name

d2i_PKCS8PrivateKey_bio, d2i_PKCS8PrivateKey_fp
i2d_PKCS8PrivateKey_bio, i2d_PKCS8PrivateKey_fp
i2d_PKCS8PrivateKey_nid_bio, i2d_PKCS8PrivateKey_nid_fp

PKCS#8 format private key functions

Library

libcrypto.lib

Synopsis

#include <openssl/evp.h>
EVP_PKEY *d2i_PKCS8PrivateKey_bio(BIO *bp, EVP_PKEY **x, pem_password_cb *cb, void *u);
EVP_PKEY *d2i_PKCS8PrivateKey_fp(FILE *fp, EVP_PKEY **x, pem_password_cb *cb, void *u);
int i2d_PKCS8PrivateKey_bio(BIO *bp, EVP_PKEY *x, const EVP_CIPHER *enc, char *kstr, int klen, pem_password_cb *cb, void *u);
int i2d_PKCS8PrivateKey_fp(FILE *fp, EVP_PKEY *x, const EVP_CIPHER *enc, char *kstr, int klen, pem_password_cb *cb, void *u);
int i2d_PKCS8PrivateKey_nid_bio(BIO *bp, EVP_PKEY *x, int nid, char *kstr, int klen, pem_password_cb *cb, void *u);
int i2d_PKCS8PrivateKey_nid_fp(FILE *fp, EVP_PKEY *x, int nid, char *kstr, int klen, pem_password_cb *cb, void *u);

Detailed Description

The PKCS#8 functions encode and decode private keys in PKCS#8 format using both PKCS#5 v1.5 and PKCS#5 v2.0 password based encryption algorithms.

Other than the use of DER as opposed to PEM these functions are identical to the corresponding PEM function as described in the pem() manual page.

Notes

Before using these functions OpenSSL_add_all_algorithms() should be called to initialize the internal algorithm lookup tables otherwise errors about unknown algorithms will occur if an attempt is made to decrypt a private key.

These functions are currently the only way to store encrypted private keys using DER format.

Currently all the functions use BIOs or FILE pointers, there are no functions which work directly on memory: this can be readily worked around by converting the buffers to memory BIOs, see BIO_s_mem() for details.

See Also

pem()

Feedback

For additional information or queries on this page send feedback


d2i_Netscape_RSA - RSA public and private key encoding functions.

Name

d2i_RSAPublicKey, i2d_RSAPublicKey
d2i_RSAPrivateKey, i2d_RSAPrivateKey
d2i_RSA_PUBKEY, i2d_RSA_PUBKEY
i2d_Netscape_RSA, d2i_Netscape_RSA

RSA public and private key encoding functions

Library

libcrypto.lib

Synopsis

#include <openssl/rsa.h>
#include <openssl/x509.h>
RSA * d2i_RSAPublicKey(RSA **a, unsigned char **pp, long length);
int i2d_RSAPublicKey(RSA *a, unsigned char **pp);
RSA * d2i_RSA_PUBKEY(RSA **a, unsigned char **pp, long length);
int i2d_RSA_PUBKEY(RSA *a, unsigned char **pp);
RSA * d2i_RSAPrivateKey(RSA **a, unsigned char **pp, long length);
int i2d_RSAPrivateKey(RSA *a, unsigned char **pp);
int i2d_Netscape_RSA(RSA *a, unsigned char **pp, int (*cb)());
RSA * d2i_Netscape_RSA(RSA **a, unsigned char **pp, long length, int (*cb)());

Detailed Description

d2i_RSAPublicKey() and i2d_RSAPublicKey() decode and encode a PKCS#1 RSAPublicKey structure.

d2i_RSA_PUBKEY() and i2d_RSA_PUBKEY() decode and encode an RSA public key using a SubjectPublicKeyInfo (certificate public key) structure.

d2i_RSAPrivateKey(), i2d_RSAPrivateKey() decode and encode a PKCS#1 RSAPrivateKey structure.

d2i_Netscape_RSA(), i2d_Netscape_RSA() decode and encode an RSA private key in NET format.

The usage of all of these functions is similar to the
d2i_X509() and

i2d_X509() described in the
 d2i_X509()
manual page.

Notes

The RSA structure passed to the private key encoding functions should have all the PKCS#1 private key components present.

The data encoded by the private key functions is unencrypted and therefore offers no private key security.

The NET format functions are present to provide compatibility with certain very old software. This format has some severe security weaknesses and should be avoided if possible.

See Also

d2i_X509()

History

TBA

Feedback

For additional information or queries on this page send feedback


i2d_SSL_SESSION - convert SSL_SESSION object from/to ASN1 representation

Name

d2i_SSL_SESSION, i2d_SSL_SESSION

converts SSL_SESSION object from/to ASN1 representation

Library

libssl.lib

Synopsis

#include <openssl/ssl.h>
SSL_SESSION *d2i_SSL_SESSION(SSL_SESSION **a, const unsigned char **pp, long length);
int i2d_SSL_SESSION(SSL_SESSION *in, unsigned char **pp);

Detailed Description

d2i_SSL_SESSION() transforms the external ASN1 representation of an SSL/TLS session, stored as binary data at location pp with length length, into an SSL_SESSION object.

i2d_SSL_SESSION() transforms the SSL_SESSION object in into the ASN1 representation and stores it into the memory location pointed to by pp. The length of the resulting ASN1 representation is returned. If pp is the NULL pointer, only the length is calculated and returned.

Notes

The SSL_SESSION object is built from several malloc()ed parts, it can therefore not be moved, copied or stored directly. In order to store session data on disk or into a database, it must be transformed into a binary ASN1 representation.

When using d2i_SSL_SESSION(), the SSL_SESSION object is automatically allocated. The reference count is 1, so that the session must be explicitly removed using SSL_SESSION_free(), unless the SSL_SESSION object is completely taken over, when being called inside the get_session_cb() (see SSL_CTX_sess_set_get_cb()).

SSL_SESSION objects keep internal link information about the session cache list, when being inserted into one SSL_CTX object's session cache. One SSL_SESSION object, regardless of its reference count, must therefore only be used with one SSL_CTX object (and the SSL objects created from this SSL_CTX object).

When using i2d_SSL_SESSION(), the memory location pointed to by pp must be large enough to hold the binary representation of the session. There is no known limit on the size of the created ASN1 representation, so the necessary amount of space should be obtained by first calling i2d_SSL_SESSION() with pp=NULL, and obtain the size needed, then allocate the memory and call i2d_SSL_SESSION() again.

Return Values

d2i_SSL_SESSION() returns a pointer to the newly allocated SSL_SESSION object. In case of failure the NULL-pointer is returned and the error message can be retrieved from the error stack.

i2d_SSL_SESSION() returns the size of the ASN1 representation in bytes. When the session is not valid, 0 is returned and no operation is performed.

See Also

ssl(),
SSL_SESSION_free(),
SSL_CTX_sess_set_get_cb()

Feedback

For additional information or queries on this page send feedback


i2d_X509_fp - X509 encode and decode functions

Name

d2i_X509, i2d_X509
d2i_X509_bio, d2i_X509_fp
i2d_X509_bio, i2d_X509_fp

X509 encode and decode functions

Library

libcrypto.lib

Synopsis

#include <openssl/x509.h>
X509 *d2i_X509(X509 **px, const unsigned char **in, int len);
int i2d_X509(X509 *x, unsigned char **out);
X509 *d2i_X509_bio(BIO *bp, X509 **x);
X509 *d2i_X509_fp(FILE *fp, X509 **x);
int i2d_X509_bio(X509 *x, BIO *bp);
int i2d_X509_fp(X509 *x, FILE *fp);

Detailed Description

The X509 encode and decode routines encode and parse an X509 structure, which represents an X509 certificate.

d2i_X509() attempts to decode len bytes at *in. If successful a pointer to the X509 structure is returned. If an error occurred then NULL is returned. If px is not NULL then the returned structure is written to *px. If *px is not NULL then it is assumed that *px contains a valid X509 structure and an attempt is made to reuse it. If the call is successful *in is incremented to the byte following the parsed data.

i2d_X509() encodes the structure pointed to by x into DER format. If out is not NULL is writes the DER encoded data to the buffer at *out, and increments it to point after the data just written. If the return value is negative an error occurred, otherwise it returns the length of the encoded data.

For OpenSSL 0.9.7 and later if *out is NULL memory will be allocated for a buffer and the encoded data written to it. In this case *out is not incremented and it points to the start of the data just written.

d2i_X509_bio() is similar to d2i_X509() except it attempts to parse data from BIO bp.

d2i_X509_fp() is similar to d2i_X509() except it attempts to parse data from FILE pointer fp.

i2d_X509_bio() is similar to i2d_X509() except it writes the encoding of the structure x to BIO bp and it returns 1 for success and 0 for failure.

i2d_X509_fp() is similar to i2d_X509() except it writes the encoding of the structure x to BIO bp and it returns 1 for success and 0 for failure.

Examples

Allocate and encode the DER encoding of an X509 structure:
 int len;
 unsigned char *buf, *p;
 len = i2d_X509(x, NULL);
 buf = OPENSSL_malloc(len);
 if (buf == NULL)     /* error */
 p = buf;
 i2d_X509(x, &p);

If OpenSSL 0.9.7 or later is used then this can be simplified to:

 int len;
 unsigned char *buf;
 buf = NULL;
 len = i2d_X509(x, &buf);
 if (len < 0)     /* error */

Attempt to decode a buffer:

 X509 *x;
 unsigned char *buf, *p;
 int len;
 /* Something to setup buf and len */
 p = buf;
 x = d2i_X509(NULL, &p, len);
 if (x == NULL)  /* Some error */

Alternative technique:

 X509 *x;
 unsigned char *buf, *p;
 int len;
 /* Something to setup buf and len */
 p = buf;
 x = NULL;
 if(!d2i_X509(&x, &p, len))    /* Some error */

Notes

The letters i and d in for example i2d_X509 stand for ``internal'' (that is an internal C structure) and ``DER''. So that i2d_X509 converts from internal to DER.

The functions can also understand BER forms.

The actual X509 structure passed to i2d_X509() must be a valid populated X509 structure it can not simply be fed with an empty structure such as that returned by X509_new().

The encoded data is in binary form and may contain embedded zeroes. Therefore any FILE pointers or BIOs should be opened in binary mode. Functions such as strlen() will not return the correct length of the encoded structure.

The ways that *in and *out are incremented after the operation can trap the unwary. See the WARNINGS section for some common errors.

The reason for the auto increment behaviour is to reflect a typical usage of ASN1 functions: after one structure is encoded or decoded another will processed after it.

Warnings

The use of temporary variable is mandatory. A common mistake is to attempt to use a buffer directly as follows:

 int len;
 unsigned char *buf;
 len = i2d_X509(x, NULL);
 buf = OPENSSL_malloc(len);
 if (buf == NULL)         /* error */
 i2d_X509(x, &buf);  /* Other stuff ... */
 OPENSSL_free(buf);

This code will result in buf apparently containing garbage because it was incremented after the call to point after the data just written. Also buf will no longer contain the pointer allocated by OPENSSL_malloc() and the subsequent call to OPENSSL_free() may well crash.

The auto allocation feature (setting buf to NULL) only works on OpenSSL 0.9.7 and later. Attempts to use it on earlier versions will typically cause a segmentation violation.

Another trap to avoid is misuse of the xp argument to d2i_X509():

 X509 *x;
 if (!d2i_X509(&x, &p, len))         /* Some error */

This will probably crash somewhere in d2i_X509(). The reason for this is that the variable x is uninitialized and an attempt will be made to interpret its (invalid) value as an X509 structure, typically causing a segmentation violation. If x is set to NULL first then this will not happen.

Bugs

In some versions of OpenSSL the ``reuse'' behaviour of d2i_X509() when *px is valid is broken and some parts of the reused structure may persist if they are not present in the new one. As a result the use of this ``reuse'' behaviour is strongly discouraged.

i2d_X509() will not return an error in many versions of OpenSSL, if mandatory fields are not initialized due to a programming error then the encoded structure may contain invalid data or omit the fields entirely and will not be parsed by d2i_X509(). This may be fixed in future so code should not assume that i2d_X509() will always succeed.

Return Values

d2i_X509(), d2i_X509_bio() and d2i_X509_fp() return a valid X509 structure or NULL if an error occurs. The error code that can be obtained by ERR_get_error().

i2d_X509(), i2d_X509_bio() and i2d_X509_fp() return a the number of bytes successfully encoded or a negative value if an error occurs. The error code can be obtained by ERR_get_error().

i2d_X509_bio() and i2d_X509_fp() returns 1 for success and 0 if an error occurs The error code can be obtained by ERR_get_error().

See Also

ERR_get_error()

History

d2i_X509, i2d_X509, d2i_X509_bio, d2i_X509_fp, i2d_X509_bio and i2d_X509_fp are available in all versions of SSLeay and OpenSSL.

Feedback

For additional information or queries on this page send feedback


i2d_X509_ALGOR - AlgorithmIdentifier functions.

Name

d2i_X509_ALGOR, i2d_X509_ALGOR — AlgorithmIdentifier functions

Library

libcrypto.lib

Synopsis

#include <openssl/x509.h>
X509_ALGOR *d2i_X509_ALGOR(X509_ALGOR **a, unsigned char **pp, long length);
int i2d_X509_ALGOR(X509_ALGOR *a, unsigned char **pp);

Detailed Description

These functions decode and encode an X509_ALGOR structure which is equivalent to the AlgorithmIdentifier structure.

Otherwise these behave in a similar way to
d2i_X509() and
i2d_X509()
described in the d2i_X509() manual page.

See Also

d2i_X509()

History

TBA

Feedback

For additional information or queries on this page send feedback


i2d_X509_CRL_fp - PKCS#10 certificate request functions.

Name

d2i_X509_CRL, i2d_X509_CRL
d2i_X509_CRL_bio, d2i_509_CRL_fp
i2d_X509_CRL_bio, i2d_X509_CRL_fp

PKCS#10 certificate request functions

Library

libcrypto.lib

Synopsis

#include <openssl/x509.h>
X509_CRL *d2i_X509_CRL(X509_CRL **a, const unsigned char **pp, long length);
int i2d_X509_CRL(X509_CRL *a, unsigned char **pp);
X509_CRL *d2i_X509_CRL_bio(BIO *bp, X509_CRL **x);
X509_CRL *d2i_X509_CRL_fp(FILE *fp, X509_CRL **x);
int i2d_X509_CRL_bio(X509_CRL *x, BIO *bp);
int i2d_X509_CRL_fp(X509_CRL *x, FILE *fp);

Detailed Description

These functions decode and encode an X509 CRL (certificate revocation list).

Otherwise the functions behave in a similar way to d2i_X509() and i2d_X509() described in the d2i_X509() manual page.

See Also

d2i_X509()

History

TBA

Feedback

For additional information or queries on this page send feedback


i2d_X509_NAME - X509_NAME encoding functions

Name

d2i_X509_NAME, i2d_X509_NAME — X509_NAME encoding functions

Library

libcrypto.lib

Synopsis

#include <openssl/x509.h>
X509_NAME *d2i_X509_NAME(X509_NAME **a, unsigned char **pp, long length);
int i2d_X509_NAME(X509_NAME *a, unsigned char **pp);

Detailed Description

These functions decode and encode an X509_NAME structure which is the same as the Name type defined in RFC2459 (and elsewhere) and used for example in certificate subject and issuer names.

Otherwise the functions behave in a similar way to
 d2i_X509() and
 i2d_X509()
described in the d2i_X509() manual page.

See Also

d2i_X509()

History

TBA

Feedback

For additional information or queries on this page send feedback


i2d_X509_REQ_fp - PKCS#10 certificate request functions.

Name

d2i_X509_REQ, i2d_X509_REQ
d2i_X509_REQ_bio, d2i_X509_REQ_fp
i2d_X509_REQ_bio, i2d_X509_REQ_fp

PKCS#10 certificate request functions

Library

libcrypto.lib

Synopsis

#include <openssl/x509.h>
X509_REQ *d2i_X509_REQ(X509_REQ **a, const unsigned char **pp, long length);
int i2d_X509_REQ(X509_REQ *a, unsigned char **pp);
X509_REQ *d2i_X509_REQ_bio(BIO *bp, X509_REQ **x);
X509_REQ *d2i_X509_REQ_fp(FILE *fp, X509_REQ **x);
int i2d_X509_REQ_bio(X509_REQ *x, BIO *bp);
int i2d_X509_REQ_fp(X509_REQ *x, FILE *fp);

Detailed Description

These functions decode and encode a PKCS#10 certificate request.

Otherwise these behave in a similar way to
d2i_X509() and
i2d_X509()
described in the d2i_X509() manual page.

See Also

d2i_X509()

History

TBA

Feedback

For additional information or queries on this page send feedback


i2d_X509_SIG - DigestInfo functions.

Name

d2i_X509_SIG, i2d_X509_SIG — DigestInfo functions

Library

libcrypto.lib

Synopsis

#include <openssl/x509.h>
X509_SIG *d2i_X509_SIG(X509_SIG **a, unsigned char **pp, long length);
int i2d_X509_SIG(X509_SIG *a, unsigned char **pp);

Detailed Description

These functions decode and encode an X509_SIG structure which is equivalent to the DigestInfo structure defined in PKCS#1 and PKCS#7.

Otherwise these behave in a similar way to
d2i_X509() and
i2d_X509()
described in the d2i_X509() manual page.

See Also

d2i_X509()

History

TBA

Feedback

For additional information or queries on this page send feedback


Class Definitions

Class upper

 Includes characters that can be classified as uppercase letters.
The uppercase letters <A> to <Z>, as defined by every character set are automatically included in this class.
No character specified for the keywords digit, punct, cntrl or space shall be specified.

Example:
In the POSIX locale, the 26 uppercase letters shall be included:

A B C D E F G H I J K L M N O P Q R S T U V W X Y Z

Class lower

 Includes characters that can be classified as lowercase letters.
The lowercase letters <a> to <z>, as defined by every character set are automatically included in this class.
No character specified for the keywords cntrl, digit, punct, or space shall be specified.

Example:
In the POSIX locale, the 26 lowercase letters shall be included:

a b c d e f g h i j k l m n o p q r s t u v w x y z

Class alpha

 Includes characters that can be classified as letters/alphabets.

No character specified for the keywords cntrl, digit, punct, or space shall be specified.
Characters classified as either upper or lower are automatically included in this class.

Example:
In the POSIX locale, all characters in the classes upper and lower shall be included.

Class digit

 Includes characters that can be classified as numeric digits. Only the digits <zero>, <one>, <two>, <three>, <four>, <five>, <six>, <seven>, <eight>, and <nine> shall be specified, and in contiguous ascending sequence by numerical value. The digits <zero> to <nine> of every character set are automatically included in this class.

Example:
In the POSIX locale, only:

0 1 2 3 4 5 6 7 8 9

shall be included.

Class alnum

 Includes characters that can be classified as letters and digits(characters used to represent numeric value). Only the characters specified for the class alpha and class digit shall be specified.

Class space

 Includes characters that can be classified as white-space characters.
No character specified for the keywords upper, lower, alpha, digit, graph, or xdigit shall be specified.
Any characters included in the class blank and the <newline>, <carriage-return>, <space>, <form-feed>, <tab>, and <vertical-tab> of the every character set are automatically included in this class.

Example:
In the POSIX locale, at a minimum, the <space>, <form-feed>, <newline>, <carriage-return>, <tab>, and <vertical-tab> shall be included.

Class blank

 Includes characters that can be classified as <blank>s. The <space> and <tab> are automatically included in this class.

Example:
In the POSIX locale, only the <space> and <tab> shall be included.

Class cntrl

 Includes characters that can be classified as control characters.
No character specified for the keywords upper, lower, alpha, digit, punct, graph, print, or xdigit shall be specified.

Example:
In the POSIX locale, no characters in classes alpha or print shall be included.

Class punct

 Includes characters that can be classified as punctuation characters.
No character specified for the keywords upper, lower, alpha, digit, cntrl, xdigit, or as the <space> shall be specified.

Example:
In the POSIX locale, neither the <space> nor any characters in classes alpha, digit, or cntrl shall be included.

Class graph

 Includes characters that can be classified as printable characters, not including the <space>. Characters specified for the keywords upper, lower, alpha, digit, xdigit, and punct are automatically included in this class. No character specified for the keyword cntrl shall be specified.

Example:
In the POSIX locale, all characters in classes alpha, digit, and punct shall be included; no characters in class cntrl shall be included.

Class print

 Includes characters that can be classified as printable characters, including the <space>. Characters specified for the keywords upper, lower, alpha, digit, xdigit, punct, graph, and the <space> are automatically included in this class. No character specified for the keyword cntrl shall be specified.

Example:
In the POSIX locale, all characters in class graph shall be included; no characters in class cntrl shall be included.

Class toupper

 Defines the mapping of lowercase letters to uppercase letters, within that character set.

Example:
In the POSIX locale, at a minimum, the 26 lowercase characters:

a b c d e f g h i j k l m n o p q r s t u v w x y z

shall be mapped to the corresponding 26 uppercase characters:

A B C D E F G H I J K L M N O P Q R S T U V W X Y Z

Class tolower

 Defines the mapping of uppercase letters to lowercase letters, within that character set.

In the POSIX locale, at a minimum, the 26 uppercase characters:

Example:
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z

shall be mapped to the corresponding 26 lowercase characters:

a b c d e f g h i j k l m n o p q r s t u v w x y z

Class xdigit

 Includes characters that can be classified as hexadecimal digits.

Only the characters defined for the class digit shall be specified, in contiguous ascending sequence by numerical value, followed by one or more sets of six characters representing the hexadecimal digits 10 to 15 inclusive, with each set in ascending order (for example, <A>, <B>, <C>, <D>, <E>, <F>, <a>, <b>, <c>, <d>, <e>, <f>). The digits <zero> to <nine>, the uppercase letters <A> to <F>, and the lowercase letters <a> to <f> of the portable character set are automatically included in this class.

Example:
In the POSIX locale, only:

0 1 2 3 4 5 6 7 8 9 A B C D E F a b c d e f

shall be included.

Notes

 Each of these classes include the respective characters as mentioned above, from all the locales supported. This means each class is a pool of characters belonging to the mentioned category, from various locales supported.


DES_enc_write - DES encryption

Name

DES_random_key, DES_set_key, DES_key_sched
DES_set_key_checked, DES_set_key_unchecked
DES_set_odd_parity, DES_is_weak_key
DES_ecb_encrypt, DES_ecb2_encrypt
DES_ecb3_encrypt, DES_ncbc_encrypt
DES_cfb_encrypt, DES_ofb_encrypt
DES_pcbc_encrypt, DES_cfb64_encrypt
DES_ofb64_encrypt, DES_xcbc_encrypt
DES_ede2_cbc_encrypt, DES_ede2_cfb64_encrypt
DES_ede2_ofb64_encrypt, DES_ede3_cbc_encrypt
DES_ede3_cbcm_encrypt, DES_ede3_cfb64_encrypt
DES_ede3_ofb64_encrypt, DES_cbc_cksum
DES_quad_cksum, DES_string_to_key
DES_string_to_2keys, DES_fcrypt
DES_crypt, DES_enc_read, DES_enc_write

The variants of DES and other crypto algorithms of OpenSSL

Library

libcrypto.lib

Synopsis

#include <openssl/des.h>
void DES_random_key(DES_cblock *ret);
int DES_set_key(const_DES_cblock *key, DES_key_schedule *schedule);
int DES_key_sched(const_DES_cblock *key, DES_key_schedule *schedule);
int DES_set_key_checked(const_DES_cblock *key, DES_key_schedule *schedule);
void DES_set_key_unchecked(const_DES_cblock *key, DES_key_schedule *schedule);
void DES_set_odd_parity(DES_cblock *key);
int DES_is_weak_key(const_DES_cblock *key);
void DES_ecb_encrypt(const_DES_cblock *input, DES_cblock *output, DES_key_schedule *ks, int enc);
void DES_ecb2_encrypt(const_DES_cblock *input, DES_cblock *output, DES_key_schedule *ks1, DES_key_schedule *ks2, int enc);
void DES_ecb3_encrypt(const_DES_cblock *input, DES_cblock *output, DES_key_schedule *ks1, DES_key_schedule *ks2,
                      DES_key_schedule *ks3, int enc);
void DES_ncbc_encrypt(const unsigned char *input, unsigned char *output, long length, DES_key_schedule *schedule,
                      DES_cblock *ivec, int enc);
void DES_cfb_encrypt(const unsigned char *in, unsigned char *out, int numbits, long length, DES_key_schedule *schedule,
                     DES_cblock *ivec, int enc);
void DES_ofb_encrypt(const unsigned char *in, unsigned char *out, int numbits, long length, DES_key_schedule *schedule,
                     DES_cblock *ivec);
void DES_pcbc_encrypt(const unsigned char *input, unsigned char *output, long length, DES_key_schedule *schedule,
                      DES_cblock *ivec, int enc);
void DES_cfb64_encrypt(const unsigned char *in, unsigned char *out, long length, DES_key_schedule *schedule,
                       DES_cblock *ivec, int *num, int enc);
void DES_ofb64_encrypt(const unsigned char *in, unsigned char *out, long length, DES_key_schedule *schedule,
                       DES_cblock *ivec, int *num);
void DES_xcbc_encrypt(const unsigned char *input, unsigned char *output, long length, DES_key_schedule *schedule,
                      DES_cblock *ivec, const_DES_cblock *inw, const_DES_cblock *outw, int enc);
void DES_ede2_cbc_encrypt(const unsigned char *input, unsigned char *output, long length, DES_key_schedule *ks1,
                          DES_key_schedule *ks2, DES_cblock *ivec, int enc);
void DES_ede2_cfb64_encrypt(const unsigned char *in, unsigned char *out, long length, DES_key_schedule *ks1,
        DES_key_schedule *ks2, DES_cblock *ivec, int *num, int enc);
void DES_ede2_ofb64_encrypt(const unsigned char *in, unsigned char *out, long length, DES_key_schedule *ks1,
                            DES_key_schedule *ks2, DES_cblock *ivec, int *num);
void DES_ede3_cbc_encrypt(const unsigned char *input, unsigned char *output, long length, DES_key_schedule *ks1,
                          DES_key_schedule *ks2, DES_key_schedule *ks3, DES_cblock *ivec, int enc);
void DES_ede3_cbcm_encrypt(const unsigned char *in, unsigned char *out, long length, DES_key_schedule *ks1,
                           DES_key_schedule *ks2, DES_key_schedule *ks3, DES_cblock *ivec1, DES_cblock *ivec2, int enc);
void DES_ede3_cfb64_encrypt(const unsigned char *in, unsigned char *out, long length, DES_key_schedule *ks1,
                            DES_key_schedule *ks2, DES_key_schedule *ks3, DES_cblock *ivec, int *num, int enc);
void DES_ede3_ofb64_encrypt(const unsigned char *in, unsigned char *out, long length, DES_key_schedule *ks1,
                            DES_key_schedule *ks2, DES_key_schedule *ks3, DES_cblock *ivec, int *num);
DES_LONG DES_cbc_cksum(const unsigned char *input, DES_cblock *output, long length, DES_key_schedule *schedule,
                       const_DES_cblock *ivec);
DES_LONG DES_quad_cksum(const unsigned char *input, DES_cblock output[], long length, int out_count, DES_cblock *seed);
void DES_string_to_key(const char *str, DES_cblock *key);
void DES_string_to_2keys(const char *str, DES_cblock *key1, DES_cblock *key2);
char *DES_fcrypt(const char *buf, const char *salt, char *ret);
char *DES_crypt(const char *buf, const char *salt);
int DES_enc_read(int fd, void *buf, int len, DES_key_schedule *sched, DES_cblock *iv);
int DES_enc_write(int fd, const void *buf, int len, DES_key_schedule *sched, DES_cblock *iv);

Detailed Description

This library contains a fast implementation of the DES encryption algorithm.

There are two phases to the use of DES encryption. The first is the generation of a DES_key_schedule from a key, the second is the actual encryption. A DES key is of type DES_cblock. This type is consists of 8 bytes with odd parity. The least significant bit in each byte is the parity bit. The key schedule is an expanded form of the key; it is used to speed the encryption process.

DES_random_key() generates a random key. The PRNG must be seeded prior to using this function (see rand()). If the PRNG could not generate a secure key, 0 is returned.

Before a DES key can be used, it must be converted into the architecture dependent DES_key_schedule via the DES_set_key_checked() or DES_set_key_unchecked() function.

DES_set_key_checked() will check that the key passed is of odd parity and is not a week or semi-weak key. If the parity is wrong, then -1 is returned. If the key is a weak key, then -2 is returned. If an error is returned, the key schedule is not generated.

DES_set_key() works like DES_set_key_checked() if the DES_check_key flag is non-zero, otherwise like DES_set_key_unchecked(). These functions are available for compatibility; it is recommended to use a function that does not depend on a global variable.

DES_set_odd_parity() sets the parity of the passed key to odd.

DES_is_weak_key() returns 1 is the passed key is a weak key, 0 if it is ok. The probability that a randomly generated key is weak is 1/2^52, so it is not really worth checking for them.

The following routines mostly operate on an input and output stream of DES_cblocks.

DES_ecb_encrypt() is the basic DES encryption routine that encrypts or decrypts a single 8-byte DES_cblock in electronic code book (ECB) mode. It always transforms the input data, pointed to by input, into the output data, pointed to by the output argument. If the encrypt argument is non-zero (DES_ENCRYPT), the input (cleartext) is encrypted in to the output (ciphertext) using the key_schedule specified by the schedule argument, previously set via DES_set_key. If encrypt is zero (DES_DECRYPT), the input (now ciphertext) is decrypted into the output (now cleartext). Input and output may overlap. DES_ecb_encrypt() does not return a value.

DES_ecb3_encrypt() encrypts/decrypts the input block by using three-key Triple-DES encryption in ECB mode. This involves encrypting the input with ks1, decrypting with the key schedule ks2, and then encrypting with ks3. This routine greatly reduces the chances of brute force breaking of DES and has the advantage of if ks1, ks2 and ks3 are the same, it is equivalent to just encryption using ECB mode and ks1 as the key.

The macro DES_ecb2_encrypt() is provided to perform two-key Triple-DES encryption by using ks1 for the final encryption.

DES_ncbc_encrypt() encrypts/decrypts using the cipher-block-chaining (CBC) mode of DES. If the encrypt argument is non-zero, the routine cipher-block-chain encrypts the cleartext data pointed to by the input argument into the ciphertext pointed to by the output argument, using the key schedule provided by the schedule argument, and initialization vector provided by the ivec argument. If the length argument is not an integral multiple of eight bytes, the last block is copied to a temporary area and zero filled. The output is always an integral multiple of eight bytes.

DES_xcbc_encrypt() is RSA's DESX mode of DES. It uses inw and outw to 'whiten' the encryption. inw and outw are secret (unlike the iv) and are as such, part of the key. So the key is sort of 24 bytes. This is much better than CBC DES.

DES_ede3_cbc_encrypt() implements outer triple CBC DES encryption with three keys. This means that each DES operation inside the CBC mode is really an C=E(ks3,D(ks2,E(ks1,M))). This mode is used by SSL.

The DES_ede2_cbc_encrypt() macro implements two-key Triple-DES by reusing ks1 for the final encryption. C=E(ks1,D(ks2,E(ks1,M))). This form of Triple-DES is used by the RSAREF library.

DES_pcbc_encrypt() encrypt/decrypts using the propagating cipher block chaining mode used by Kerberos v4. Its parameters are the same as DES_ncbc_encrypt().

DES_cfb_encrypt() encrypt/decrypts using cipher feedback mode. This method takes an array of characters as input and outputs and array of characters. It does not require any padding to 8 character groups. Note: the ivec variable is changed and the new changed value needs to be passed to the next call to this function. Since this function runs a complete DES ECB encryption per numbits, this function is only suggested for use when sending small numbers of characters.

DES_cfb64_encrypt() implements CFB mode of DES with 64bit feedback. It is useful because this routine will allows encryption of an arbitrary number of bytes, no 8 byte padding. Each call to this routine will encrypt the input bytes to output and then update ivec and num. num contains 'how far' we are though ivec. If this does not make much sense, read more about cfb mode of DES .

DES_ede3_cfb64_encrypt() and
 DES_ede2_cfb64_encrypt() is the same as
DES_cfb64_encrypt()
except that Triple-DES is used.

DES_ofb_encrypt() encrypts using output feedback mode. This method takes an array of characters as input and outputs and array of characters. It does not require any padding to 8 character groups. Note: the ivec variable is changed and the new changed value needs to be passed to the next call to this function. Since this function runs a complete DES ECB encryption per numbits, this function is only suggested for use when sending small numbers of characters.

DES_ofb64_encrypt() is the same as DES_cfb64_encrypt() using Output Feed Back mode.

DES_ede3_ofb64_encrypt() and DES_ede2_ofb64_encrypt() is the same as DES_ofb64_encrypt(), using Triple-DES.

The following functions are included in the DES library for compatibility with the MIT Kerberos library.

DES_cbc_cksum() produces an 8 byte checksum based on the input stream (via CBC encryption). The last 4 bytes of the checksum are returned and the complete 8 bytes are placed in output. This function is used by Kerberos v4. Other applications should use EVP_DigestInit() etc. instead.

DES_quad_cksum() is a Kerberos v4 function. It returns a 4 byte checksum from the input bytes. The algorithm can be iterated over the input, depending on out_count, 1, 2, 3 or 4 times. If output is non-NULL, the 8 bytes generated by each pass are written into output.

The following are DES-based transformations:

DES_fcrypt() is a fast version of the Unix crypt() function. This version takes only a small amount of space relative to other fast crypt() implementations. This is different to the normal crypt in that the third parameter is the buffer that the return value is written into. It needs to be at least 14 bytes long. This function is thread safe, unlike the normal crypt.

DES_crypt() is a faster replacement for the normal system crypt(). This function calls DES_fcrypt() with a static array passed as the third parameter. This emulates the normal non-thread safe semantics of crypt().

DES_enc_write() writes len bytes to file descriptor fd from buffer buf. The data is encrypted via pcbc_encrypt (default) using sched for the key and iv as a starting vector. The actual data send down fd consists of 4 bytes (in network byte order) containing the length of the following encrypted data. The encrypted data then follows, padded with random data out to a multiple of 8 bytes.

DES_enc_read() is used to read len bytes from file descriptor fd into buffer buf. The data being read from fd is assumed to have come from DES_enc_write() and is decrypted using sched for the key schedule and iv for the initial vector.

Warning: The data format used by DES_enc_write() and DES_enc_read() has a cryptographic weakness: when asked to write more than MAXWRITE bytes, DES_enc_write() will split the data into several chunks that are all encrypted using the same IV. So do not use these functions unless sure about the results of the action(in which case they might not be used anyway). They cannot handle non-blocking sockets. DES_enc_read() uses an internal state and thus cannot be used on multiple files.

DES_rw_mode is used to specify the encryption mode to use with DES_enc_read() and DES_end_write(). If set to DES_PCBC_MODE (the default), DES_pcbc_encrypt is used. If set to DES_CBC_MODE DES_cbc_encrypt is used.

Notes

Single-key DES is insecure due to its short key size. ECB mode is not suitable for most applications; see des_modes().

The evp() library provides higher-level encryption functions.

Bugs

DES_3cbc_encrypt() is flawed and must not be used in applications.

DES_cbc_encrypt() does not modify ivec; use DES_ncbc_encrypt() instead.

DES_cfb_encrypt() and DES_ofb_encrypt() operates on input of 8 bits. What this means is that if numbits is set to 12, and length to 2, the first 12 bits will come from the 1st input byte and the low half of the second input byte. The second 12 bits will have the low 8 bits taken from the 3rd input byte and the top 4 bits taken from the 4th input byte. The same holds for output. This function has been implemented this way because most people will be using a multiple of 8 and because things could ugly when pulling bytes input bytes apart.

DES_string_to_key() is available for backward compatibility with the MIT library. New applications should use a cryptographic hash function. The same applies for DES_string_to_2key().

Conforming To

ANSI X3.106

The des library was written to be source code compatible with the MIT Kerberos library.

See Also

crypto(),
des_modes(), evp(),
rand()

History

In OpenSSL 0.9.7, all des_ functions were renamed to DES_ to avoid clashes with older versions of libdes. Compatibility des_ functions are provided for a short while, as well as crypt(). Declarations for these are in <openssl/des_old.h>. There is no DES_ variant for des_random_seed(). This will happen to other functions as well if they are deemed redundant (des_random_seed() just calls RAND_seed() and is present for backward compatibility only), buggy or already scheduled for removal.

des_cbc_cksum(), des_cbc_encrypt(), des_ecb_encrypt(),
des_is_weak_key(), des_key_sched(), des_pcbc_encrypt(),
des_quad_cksum(),  des_random_key()
and des_string_to_key()
are available in the MIT Kerberos library;
des_check_key_parity(),  des_fixup_key_parity()
and  des_is_weak_key()
are available in newer versions of that library.

des_set_key_checked() and des_set_key_unchecked() were added in OpenSSL 0.9.5.

des_generate_random_block(), des_init_random_number_generator(),
des_new_random_key(),
des_set_random_generator_seed() and
des_set_sequence_number()
and des_rand_data()
are used in newer
versions of Kerberos but are not implemented here.

des_random_key() generated cryptographically weak random data in SSLeay and in OpenSSL prior version 0.9.5, as well as in the original MIT library.

Author

Eric Young (eay@cryptsoft.com) Modified for the OpenSSL project (http://www.openssl.org).

Feedback

For additional information or queries on this page send feedback


DES - the variants of DES and other crypto algorithms of OpenSSL

Name

Modes of DES — the variants of DES and other crypto algorithms of OpenSSL

Library

libcrypto.lib

Detailed Description

Several crypto algorithms for OpenSSL can be used in a number of modes. Those are used for using block ciphers in a way similar to stream ciphers, among other things.

Overview

Electronic Codebook Mode (ECB)

Normally, this is found as the function algorithm_ecb_encrypt().

    • 64 bits are enciphered at a time.

    • The order of the blocks can be rearranged without detection.

    • The same plaintext block always produces the same ciphertext block (for the same key) making it vulnerable to a 'dictionary attack'.

    • An error will only affect one ciphertext block.

Cipher Block Chaining Mode (CBC)

Normally, this is found as the function algorithm_cbc_encrypt(). Be aware that des_cbc_encrypt() is not really DES CBC (it does not update the IV); use des_ncbc_encrypt() instead.

  • a multiple of 64 bits are enciphered at a time.

    • The CBC mode produces the same ciphertext whenever the same plaintext is encrypted using the same key and starting variable.

    • The chaining operation makes the ciphertext blocks dependent on the current and all preceding plaintext blocks and therefore blocks can not be rearranged.

    • The use of different starting variables prevents the same plaintext enciphering to the same ciphertext.

    • An error will affect the current and the following ciphertext blocks.

Cipher Feedback Mode (CFB)

Normally, this is found as the function algorithm_cfb_encrypt().

    • a number of bits (j) <= 64 are enciphered at a time.

    • The CFB mode produces the same ciphertext whenever the same plaintext is encrypted using the same key and starting variable.

    • The chaining operation makes the ciphertext variables dependent on the current and all preceding variables and therefore j-bit variables are chained together and can not be rearranged.

    • The use of different starting variables prevents the same plaintext enciphering to the same ciphertext.

    • The strength of the CFB mode depends on the size of k (maximal if j == k). In my implementation this is always the case.

    • Selection of a small value for j will require more cycles through the encipherment algorithm per unit of plaintext and thus cause greater processing overheads.

    • Only multiples of j bits can be enciphered.

    • An error will affect the current and the following ciphertext variables.

Output Feedback Mode (OFB)

Normally, this is found as the function algorithm_ofb_encrypt().

    • a number of bits (j) <= 64 are enciphered at a time.

    • The OFB mode produces the same ciphertext whenever the same plaintext enciphered using the same key and starting variable. More over, in the OFB mode the same key stream is produced when the same key and start variable are used. Consequently, for security reasons a specific start variable should be used only once for a given key.

    • The absence of chaining makes the OFB more vulnerable to specific attacks.

    • The use of different start variables values prevents the same plaintext enciphering to the same ciphertext, by producing different key streams.

    • Selection of a small value for j will require more cycles through the encipherment algorithm per unit of plaintext and thus cause greater processing overheads.

    • Only multiples of j bits can be enciphered.

    • OFB mode of operation does not extend ciphertext errors in the resultant plaintext output. Every bit error in the ciphertext causes only one bit to be in error in the deciphered plaintext.

    • OFB mode is not self-synchronizing. If the two operation of encipherment and decipherment get out of synchronism, the system needs to be re-initialized.

    • Each re-initialization should use a value of the start variable different from the start variable values used before with the same key. The reason for this is that an identical bit stream would be produced each time from the same parameters. This would be susceptible to a 'known plaintext' attack.

Triple ECB Mode

Normally, this is found as the function algorithm_ecb3_encrypt().

    • Encrypt with key1, decrypt with key2 and encrypt with key3 again.

    • As for ECB encryption but increases the key length to 168 bits. There are theoretic attacks that can be used that make the effective key length 112 bits, but this attack also requires 2^56 blocks of memory, not very likely, even for the NSA.

    • If both keys are the same it is equivalent to encrypting once with just one key.

    • If the first and last key are the same, the key length is 112 bits. There are attacks that could reduce the effective key strength to only slightly more than 56 bits, but these require a lot of memory.

    • If all 3 keys are the same, this is effectively the same as normal ecb mode.

Triple CBC Mode

Normally, this is found as the function algorithm_ede3_cbc_encrypt().

    • Encrypt with key1, decrypt with key2 and then encrypt with key3.

    • As for CBC encryption but increases the key length to 168 bits with the same restrictions as for triple ecb mode.

Notes

This text was been written in large parts by Eric Young in his original documentation for SSLeay, the predecessor of OpenSSL. In turn, he attributed it to:

AS 2805.5.2
Australian Standard
Electronic funds transfer - Requirements for interfaces,
Part 5.2: Modes of operation for an n-bit block cipher algorithm
Appendix A

See Also

des()

Feedback

For additional information or queries on this page send feedback


dh - Diffie-Hellman key agreement

Name

dh — implement the Diffie-Hellman key agreement protocol

Library

libcrypto.lib

Synopsis

#include <openssl/dh.h>
#include <openssl/engine.h>
DH *   DH_new(void);
void   DH_free(DH *dh);
int    DH_size(const DH *dh);
DH *   DH_generate_parameters(int prime_len, int generator, void (*callback)(int, int, void *), void *cb_arg);
int    DH_check(const DH *dh, int *codes);
int    DH_generate_key(DH *dh);
int    DH_compute_key(unsigned char *key, BIGNUM *pub_key, DH *dh);
void DH_set_default_method(const DH_METHOD *meth);
const DH_METHOD *DH_get_default_method(void);
int DH_set_method(DH *dh, const DH_METHOD *meth);
DH *DH_new_method(ENGINE *engine);
const DH_METHOD *DH_OpenSSL(void);
int DH_get_ex_new_index(long argl, char *argp, int (*new_func)(), int (*dup_func)(), void (*free_func)());
int DH_set_ex_data(DH *d, int idx, char *arg);
char *DH_get_ex_data(DH *d, int idx);
DH *   d2i_DHparams(DH **a, unsigned char **pp, long length);
int    i2d_DHparams(const DH *a, unsigned char **pp);
int    DHparams_print_fp(FILE *fp, const DH *x);
int    DHparams_print(BIO *bp, const DH *x);

Detailed Description

These functions implement the Diffie-Hellman key agreement protocol. The generation of shared DH parameters is described in DH_generate_parameters(); DH_generate_key() describes how to perform a key agreement.

The DH structure consists of several BIGNUM components.

 struct
        {
        BIGNUM *p;              // prime number (shared)
        BIGNUM *g;              // generator of Z_p (shared)
        BIGNUM *priv_key;       // private DH value x
        BIGNUM *pub_key;        // public DH value g^x
        // ...
        };
 DH

Note that DH keys may use non-standard DH_METHOD implementations, either directly or by the use of ENGINE modules. In some cases (e.g.. an ENGINE providing support for hardware-embedded keys), these BIGNUM values will not be used by the implementation or may be used for alternative data storage. For this reason, applications should generally avoid using DH structure elements directly and instead use API functions to query or modify keys.

See Also

dhparam(), bn(),
dsa(),
err(),
rand(), rsa(),
engine(),
DH_set_method(),
DH_new(),
DH_get_ex_new_index(),
DH_generate_parameters(),
DH_compute_key(), d2i_DHparams(),
RSA_print()

Feedback

For additional information or queries on this page send feedback


DH_compute_key - perform Diffie-Hellman key exchange

Name

DH_generate_key, DH_compute_key — performs Diffie-Hellman key exchange

Library

libcrypto.lib

Synopsis

#include <openssl/dh.h>
int DH_generate_key(DH *dh);
int DH_compute_key(unsigned char *key, BIGNUM *pub_key, DH *dh);

Detailed Description

DH_generate_key() performs the first step of a Diffie-Hellman key exchange by generating private and public DH values. By calling DH_compute_key(), these are combined with the other party's public value to compute the shared key.

DH_generate_key() expects dh to contain the shared parameters dh->p and dh->g. It generates a random private DH value unless dh->priv_key is already set, and computes the corresponding public value dh->pub_key, which can then be published.

DH_compute_key() computes the shared secret from the private DH value in dh and the other party's public value in pub_key and stores it in key. key must point to DH_size(dh) bytes of memory.

Return Values

DH_generate_key() returns 1 on success, 0 otherwise.

DH_compute_key() returns the size of the shared secret on success, -1 on error.

The error codes can be obtained by ERR_get_error().

See Also

dh(),
ERR_get_error(),
rand(), DH_size()

History

DH_generate_key() and DH_compute_key() are available in all versions of SSLeay and OpenSSL.

Feedback

For additional information or queries on this page send feedback


DH_check - generate and check Diffie-Hellman parameters

Name

DH_generate_parameters, DH_check — generates and check Diffie-Hellman parameters

Library

libcrypto.lib

Synopsis

#include <openssl/dh.h>
DH *DH_generate_parameters(int prime_len, int generator, void (*callback)(int, int, void *), void *cb_arg);
int DH_check(DH *dh, int *codes);

Detailed Description

DH_generate_parameters() generates Diffie-Hellman parameters that can be shared among a group of users, and returns them in a newly allocated DH structure. The pseudo-random number generator must be seeded prior to calling DH_generate_parameters().

prime_len is the length in bits of the safe prime to be generated. generator is a small number > 1, typically 2 or 5.

A callback function may be used to provide feedback about the progress of the key generation. If callback is not NULL, it will be called as described in BN_generate_prime() while a random prime number is generated, and when a prime has been found, callback(3, 0, cb_arg) is called.

DH_check() validates Diffie-Hellman parameters. It checks that p is a safe prime, and that g is a suitable generator. In the case of an error, the bit flags DH_CHECK_P_NOT_SAFE_PRIME or DH_NOT_SUITABLE_GENERATOR are set in *codes. DH_UNABLE_TO_CHECK_GENERATOR is set if the generator cannot be checked, i.e. it does not equal 2 or 5.

Return Values

DH_generate_parameters() returns a pointer to the DH structure, or NULL if the parameter generation fails. The error codes can be obtained by ERR_get_error().

DH_check() returns 1 if the check could be performed, 0 otherwise.

Notes

DH_generate_parameters() may run for several hours before finding a suitable prime.

The parameters generated by DH_generate_parameters() are not to be used in signature schemes.

Bugs

If generator is not 2 or 5, dh->g=generator is not a usable generator.

See Also

dh(),
ERR_get_error(),
rand(),
DH_free()

History

DH_check() is available in all versions of SSLeay and OpenSSL. The cb_arg argument to DH_generate_parameters() was added in SSLeay 0.9.0.

In versions before OpenSSL 0.9.5, DH_CHECK_P_NOT_STRONG_PRIME is used instead of DH_CHECK_P_NOT_SAFE_PRIME.

Feedback

For additional information or queries on this page send feedback

©2005-2006 Nokia


DH_get_ex_data - add application specific data to DH structures

Name

DH_get_ex_new_index, DH_set_ex_data
DH_get_ex_data

Adds application specific data to DH structures

Library

libcrypto.lib

Synopsis

#include <openssl/dh.h>
int DH_get_ex_new_index(long argl, void *argp, CRYPTO_EX_new *new_func, CRYPTO_EX_dup *dup_func, CRYPTO_EX_free *free_func);
int DH_set_ex_data(DH *d, int idx, void *arg);
char *DH_get_ex_data(DH *d, int idx);

Detailed Description

These functions handle application specific data in DH
structures. Their usage is identical to that of
RSA_get_ex_new_index(),  RSA_set_ex_data() and
RSA_get_ex_data()
as described in RSA_get_ex_new_index().

See Also

RSA_get_ex_new_index(), dh()

History

DH_get_ex_new_index(),
DH_set_ex_data() and
 DH_get_ex_data() are
available since OpenSSL 0.9.5.

Feedback

For additional information or queries on this page send feedback


DH_free - allocate and free DH objects

Name

DH_new, DH_free — Allocates and frees DH objects

Library

libcrypto

Synopsis

#include <openssl/dh.h>
DH* DH_new(void);
void DH_free(DH *dh);

Detailed Description

DH_new() allocates and initializes a DH structure.

DH_free() frees the DH structure and its components. The values are erased before the memory is returned to the system.

Return Values

If the allocation fails, DH_new() returns NULL and sets an error code that can be obtained by ERR_get_error(). Otherwise it returns a pointer to the newly allocated structure.

DH_free() returns no value.

See Also

dh(),
ERR_get_error(),
DH_generate_parameters(),
DH_generate_key()

History

DH_new() and DH_free() are available in all versions of SSLeay and OpenSSL.

Feedback

For additional information or queries on this page send feedback

©2005-2006 Nokia


DH_OpenSSL - select DH method

Name

DH_set_default_method, DH_get_default_method
DH_set_method, DH_new_method
DH_OpenSSL

selects DH method

Library

libcrypto

Synopsis

#include <openssl/dh.h>
#include <openssl/engine.h>
void DH_set_default_method(const DH_METHOD *meth);
const DH_METHOD *DH_get_default_method(void);
int DH_set_method(DH *dh, const DH_METHOD *meth);
DH *DH_new_method(ENGINE *engine);
const DH_METHOD *DH_OpenSSL(void);

Detailed Description

A DH_METHOD specifies the functions that OpenSSL uses for Diffie-Hellman operations. By modifying the method, alternative implementations such as hardware accelerators may be used. IMPORTANT: See the NOTES section for important information about how these DH API functions are affected by the use of ENGINE API calls.

Initially, the default DH_METHOD is the OpenSSL internal implementation, as returned by DH_OpenSSL().

DH_set_default_method() makes meth the default method for all DH structures created later. NB: This is true only whilst no ENGINE has been set as a default for DH, so this function is no longer recommended.

DH_get_default_method() returns a pointer to the current default DH_METHOD. However, the meaningfulness of this result is dependant on whether the ENGINE API is being used, so this function is no longer recommended.

DH_set_method() selects meth to perform all operations using the key dh. This will replace the DH_METHOD used by the DH key and if the previous method was supplied by an ENGINE, the handle to that ENGINE will be released during the change. It is possible to have DH keys that only work with certain DH_METHOD implementations (e.g.. from an ENGINE module that supports embedded hardware-protected keys), and in such cases attempting to change the DH_METHOD for the key can have unexpected results.

DH_new_method() allocates and initializes a DH structure so that engine will be used for the DH operations. If engine is NULL, the default ENGINE for DH operations is used, and if no default ENGINE is set, the DH_METHOD controlled by DH_set_default_method() is used.

DH_Method Structure

 typedef struct dh_meth_st
 {
     /* name of the implementation */
        const char *name;
     /* generate private and public DH values for key agreement */
        int (*generate_key)(DH *dh);
     /* compute shared secret */
        int (*compute_key)(unsigned char *key, BIGNUM *pub_key, DH *dh);
     /* compute r = a ^ p mod m (May be NULL for some implementations) */
        int (*bn_mod_exp)(DH *dh, BIGNUM *r, BIGNUM *a, const BIGNUM *p,
                                const BIGNUM *m, BN_CTX *ctx,
                                BN_MONT_CTX *m_ctx);
     /* called at DH_new */
        int (*init)(DH *dh);
     /* called at DH_free */
        int (*finish)(DH *dh);
        int flags;
        char *app_data; /* ?? */
 } DH_METHOD;

Return Values

DH_OpenSSL() and DH_get_default_method() return pointers to the respective DH_METHODs.

DH_set_default_method() returns no value.

DH_set_method() returns non-zero if the provided meth was successfully set as the method for dh (including unloading the ENGINE handle if the previous method was supplied by an ENGINE).

DH_new_method() returns NULL and sets an error code that can be obtained by ERR_get_error() if the allocation fails. Otherwise it returns a pointer to the newly allocated structure.

Notes

As of version 0.9.7, DH_METHOD implementations are grouped together with other algorithmic APIs (e.g.. RSA_METHOD, EVP_CIPHER, etc) in ENGINE modules. If a default ENGINE is specified for DH functionality using an ENGINE API function, that will override any DH defaults set using the DH API (i.e.. DH_set_default_method()). For this reason, the ENGINE API is the recommended way to control default implementations for use in DH and other cryptographic algorithms.

See Also

dh(), DH_new()

History

DH_set_default_method(), DH_get_default_method(), DH_set_method(),

DH_new_method() and
 DH_OpenSSL() were added in OpenSSL 0.9.4.

DH_set_default_openssl_method() and DH_get_default_openssl_method() replaced DH_set_default_method() and DH_get_default_method() respectively, and DH_set_method() and DH_new_method() were altered to use ENGINEs rather than DH_METHODs during development of the engine version of OpenSSL 0.9.6. For 0.9.7, the handling of defaults in the ENGINE API was restructured so that this change was reversed, and behaviour of the other functions resembled more closely the previous behaviour. The behaviour of defaults in the ENGINE API now transparently overrides the behaviour of defaults in the DH API without requiring changing these function prototypes.

Feedback

For additional information or queries on this page send feedback

©2005-2006 Nokia


DH_size - get Diffie-Hellman prime size

Name

DH_size — gets Diffie-Hellman prime size

Library

libcrypto

Synopsis

#include <openssl/dh.h>
int DH_size(DH *dh);

Detailed Description

This function returns the Diffie-Hellman size in bytes. It can be used to determine how much memory must be allocated for the shared secret computed by DH_compute_key().

dh->p must not be NULL.

Return Value

The size in bytes.

See Also

dh(), DH_generate_key()

History

DH_size() is available in all versions of SSLeay and OpenSSL.

Feedback

For additional information or queries on this page send feedback

©2005-2006 Nokia


S60 3rd Edition API Reference: C:/Gen_5.0/Generation/api_ref/ Directory Reference

S60 Open C
API Reference Guide and Developer Guides
api_ref

api_ref Directory Reference

Directories

directory epoc32

© Nokia 2007

Back to top


S60 3rd Edition API Reference: C:/Gen_5.0/Generation/api_ref/epoc32/ Directory Reference

S60 Open C
API Reference Guide and Developer Guides
api_ref » epoc32

epoc32 Directory Reference

Directories

directory include

© Nokia 2007

Back to top


S60 3rd Edition API Reference: C:/Gen_5.0/Generation/api_ref/epoc32/include/ Directory Reference

S60 Open C
API Reference Guide and Developer Guides
api_ref » epoc32 » include

include Directory Reference

Files

file display.inl
Defines the inline constructors for the display data classes.

© Nokia 2007

Back to top


S60 3rd Edition API Reference: Directory Hierarchy

S60 Open C
API Reference Guide and Developer Guides

S60 3rd Edition API Reference Directories

This directory hierarchy is sorted roughly, but not completely, alphabetically:
  • api_ref
    • epoc32
      • include

© Nokia 2007

Back to top


S60 3rd Edition API Reference: display.inl File Reference

S60 Open C
API Reference Guide and Developer Guides
api_ref » epoc32 » include

display.inl File Reference

Detailed Description

Defines the inline constructors for the display data classes.

© Nokia 2007

Back to top


div

Name

div
- computes quotient and remainder of an integer division

Library

 libc.lib

Synopsis
#include <stdlib.h>
div_t div (int num, int denom);

Return values

 The div function returns a structure of type div_t that contains two int members named quot (quotient) and rem (remainder).

Detailed description

 The div function computes the value num/denom and returns the quotient and remainder in a structure named div_t that contains two int members named quot and rem.

Examples

#include <stdlib.h>
#include <stdio.h>

void main( void )
{
 int numer = -14;
 int denom = -3;
 int exp_numer = 0;

 /* call to div */
 div_t x = div(numer, denom);

 printf("Result->\n Quotient = %d\n Remainder = %d\n", x.quot, x.rem);

 exp_numer = (denom * x.quot) + x.rem;

 if( exp_numer == (numer) )
    printf("Result is same as the expected output");
 else
    printf("Unexpected output");

 return 0;
}

Output

Result->
Quotient = 4
Remainder = -2
Result is same as the expected output

See also

 ldiv, lldiv

Feedback

For additional information or queries on this page send feedback


dlopen

Name

dlopen, dlsym, dlerror, dlclose
- programming interface to dynamic linking loader

Library

 libdl.lib

Synopsis
#include <dlfcn.h>
void * dlopen (const char *path, int mode);
void * dlsym (void * restrict handle, const char * restrict symbol);
char * dlerror (void);
int dlclose (void *handle);

Detailed description

 These functions provide interfaces to the services of the Symbian Loader Server. Operations are provided to load dynamic link libraries (DLLs) into the current process’s address space, to obtain the address bindings of symbols exported by the DLLs, and to remove the DLLs from the process’s address space when their use is no longer required.

The dlopen function loads the DLL specified in the path argument, and returns a descriptor if successful. The descriptor thus returned can be used for later references to the DLL within the calls to dlsym and dlclose. The user side code should not attempt to modify or interpret the value of the descriptor returned by dlopen. If the DLL specified by the path argument is not in the address space prior to the call to dlopen, it is loaded into the address space. When the DLL is first loaded into the address space, constructors of the DLL’s global objects are invoked. If the DLL specified by the path argument has already been placed in the process’s address space in a previous call to dlopen, invoking dlopen, on the same DLL does not add it a second time, but the reference count of dlopen operations on that DLL is incremented. Invoking dlclose on the DLL handle decrements the reference count associated with the DLL. When this reference count reaches zero, the DLL is unloaded from the process address space. Hence, the dynamic library (DLL) thus loaded is not deallocated until dlclose is called on it as many times as dlopen has succeeded on it. dlopen returns NULL is path argument is NULL.

The mode parameter determines the type of operation performed by dlopen with respect to the symbol address relocations and the visibility of the symbols to other shared libraries loaded by the process. In the implementation, the mode argument has the same effect regardless of its value. And it is to resolve all the external function references immediately within dlopen. This is because the external function references are bound immediately by dlopen. So, for all practical purposes the mode parameter’s value could be assumed to be RTLD_NOW ORed with RTLD_LOCAL. Once a DLL is loaded into the address space, all the symbols exported by it can only be accessed by specifying the handle associated with the DLL. The behaviour is outlined below.

mode must contain one of the following values, possibly ORed with additional flags which will be described subsequently:
RTLD_LAZY | In the current implementation this flag causes the external function names to be resolved prior to returning from dlopen.
RTLD_NOW | In the current implementation this flag causes the external function names to be resolved prior to returning from dlopen.

One of the following flags may be ORed into the mode argument:
RTLD_GLOBAL | Symbols exported from this shared library object will not be available for the processing of relocation addresses of any other shared library object.
RTLD_LOCAL | Symbols exported from this shared library object will not be available for the processing of relocation of addresses in any other shared library object.

If path argument contains a slash character, the entire argument is used as the pathname for the file. C: is considered as the root, and C:\ is prefixed to the path argument to locate the shared library object. If on the other hand, path contains just the name of the shared library to be loaded, then the default search order for the loader is sys\bin. The string in path argument should be limited to a maximum of 256 characters.

dlopen returns the handle for the dynamic library loaded into the address space of the current process.

dlsym function returns the address binding of the symbol associated with the ordinal number. The NULL-terminated character string symbol, consists of the ordinal number (address lookup is based on ordinal number). The symbols exported by shared objects/DLLs added to the address space by dlopen can be accessed only through calls to dlsym.

In the implementation, the symbol names per se are not searched. Instead dlsym locates the symbol name corresponding to the ordinal number and returns the address of the memory location where the symbol is loaded. So the ordinal numbers form the crux of the name lookup. Since all handles have to be identified explicitly (that is, as returned by dlopen ), dlsym returns NULL when presented with special handles such as RTLD_NEXT, RTLD_SELF and RTLD_DEFAULT. The implementation treats a NULL handle to dlsym as an error and returns NULL.

The dlsym function returns a null pointer if the symbol (ordinal) cannot be found, and sets an error condition which may be queried with dlerror.

The dlerror function returns a null-terminated character string describing the last error that occurred during a call to dlopen, dlsym, or dlclose. If no such error has occurred, dlerror returns a null pointer. At each call to dlerror, the error indication is reset. Thus in the case of two calls to dlerror, where the second call follows the first immediately, the second call will always return a null pointer.

The dlclose function deletes a reference to the DLL referenced by handle. If the reference count drops to 0, the DLL is removed from the address space, and handle is rendered invalid. Just before removing the DLL from the current process’s address space, the destructors of the DLL’s global objects are invoked. If dlclose is successful, it returns 0. Otherwise it returns -1, and sets an error condition that can be interrogated with dlerror.

Notes

 The ordinal numbers associated with the functions could be got from the DLL’s .def file.

Example

The following code snippet illustrates the usage of dl functions. The example DLL name is MathDll.dll. The function that needs to be accessed is abs().

#include <stdio.h>
#include <dlfcn.h>
int libdl_user()
{
    void *handle = NULL;
    typedef float (*ABS)(float);
    ABS abs = NULL;
    /* Load the DLL dynamically */
    handle = dlopen("MathDll.dll", RTLD_NOW | RTLD_LOCAL);
    if(!handle)
    {
        /* dlopen failed to load the DLL */
        const char *p = dlerror();
        printf("%s", p);
        return -1;
    }
    /* DLL load is successful */
    /* Lookup the address of abs function within the DLL */
    abs = (ABS) dlsym(handle, "1");    /* ordinal number associated with abs() is 1 */
    if(!abs)
    {
        const char *q = dlerror();
        printf("%s", p);
        return -1;
    }
    float num = (*abs)(-100);
    printf("The absolute value of -100 is %f\n", num);
    /* Close the DLL */
    if(dlclose(handle))
    {
        /* An error occured while attempting to close the DLL */
        const char *r = dlerror();
        printf("%s\n", r);
        return -1;
    }
}

Errors

 The dlopen, and dlsym functions return a null pointer in the event of 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 a call to dlerror. The errno variable will be non-zero in case of an error. The callers are expected to set this variable to zero prior to invoking any of the dl functions.

See also

Feedback

For additional information or queries on this page send feedback


drem

Name

drem, dremf, dreml
- floating-point remainder functions

Library

 libm.lib

Synopsis
#include <math.h>
double drem (double x);
float dremf (float x);
long double dreml (long double x);

Return values

 The drem() function returns the remainder, unless y is zero.

Detailed description

 The drem dremf and the dreml functions compute the remainder of dividing x by y. The return value is x - n * y, where n is the quotient of x / y, rounded to the nearest integer. If the quotient is 1/2, it is rounded to the even number. The function dreml an alias to the function drem.

Examples

#include <math.h>
void main()
{
   double x1 = 6.4, x2 = 2, y;
   y = drem( x1, x2 );
   printf( "drem(%f , %f) = %f\n", x1, x2, y );
   y = dremf( x1, x2 );
   printf( "dremf(%f , %f) = %f\n", x1, x2, y );
   y = dreml( x1, x2 );
   printf( "dreml(%f , %f) = %f\n", x1, x2, y );
}

Output

drem ( 6.4, 2 ) = 0.4
dremf( 6.4, 2 ) = 0.4
dreml( 6.4, 2 ) = 0.4

Feedback

For additional information or queries on this page send feedback


dsa - Digital Signature Algorithm

Name

dsa — Digital Signature Algorithm

Library

libcrypto

Synopsis

#include <openssl/dsa.h>
#include <openssl/engine.h>
DSA *  DSA_new(void);
void   DSA_free(DSA *dsa);
int    DSA_size(const DSA *dsa);
DSA *  DSA_generate_parameters(int bits, unsigned char *seed, int seed_len, int *counter_ret, unsigned long *h_ret,
                               void (*callback)(int, int, void *), void *cb_arg);
DH *   DSA_dup_DH(const DSA *r);
int    DSA_generate_key(DSA *dsa);
int    DSA_sign(int dummy, const unsigned char *dgst, int len, unsigned char *sigret, unsigned int *siglen, DSA *dsa);
int    DSA_sign_setup(DSA *dsa, BN_CTX *ctx, BIGNUM **kinvp, BIGNUM **rp);
int    DSA_verify(int dummy, const unsigned char *dgst, int len, const unsigned char *sigbuf, int siglen, DSA *dsa);
void DSA_set_default_method(const DSA_METHOD *meth);
const DSA_METHOD *DSA_get_default_method(void);
int DSA_set_method(DSA *dsa, const DSA_METHOD *meth);
DSA *DSA_new_method(ENGINE *engine);
const DSA_METHOD *DSA_OpenSSL(void);
int DSA_get_ex_new_index(long argl, char *argp, int (*new_func)(), int (*dup_func)(), void (*free_func)());
int DSA_set_ex_data(DSA *d, int idx, char *arg);
char *DSA_get_ex_data(DSA *d, int idx);
DSA_SIG *DSA_SIG_new(void);
void   DSA_SIG_free(DSA_SIG *a);
int    i2d_DSA_SIG(const DSA_SIG *a, unsigned char **pp);
DSA_SIG *d2i_DSA_SIG(DSA_SIG **v, unsigned char **pp, long length);
DSA_SIG *DSA_do_sign(const unsigned char *dgst, int dlen, DSA *dsa);
int    DSA_do_verify(const unsigned char *dgst, int dgst_len, DSA_SIG *sig, DSA *dsa);
DSA *  d2i_DSAPublicKey(DSA **a, unsigned char **pp, long length);
DSA *  d2i_DSAPrivateKey(DSA **a, unsigned char **pp, long length);
DSA *  d2i_DSAparams(DSA **a, unsigned char **pp, long length);
int    i2d_DSAPublicKey(const DSA *a, unsigned char **pp);
int    i2d_DSAPrivateKey(const DSA *a, unsigned char **pp);
int    i2d_DSAparams(const DSA *a,unsigned char **pp);
int    DSAparams_print(BIO *bp, const DSA *x);
int    DSAparams_print_fp(FILE *fp, const DSA *x);
int    DSA_print(BIO *bp, const DSA *x, int off);
int    DSA_print_fp(FILE *bp, const DSA *x, int off);

Detailed Description

These functions implement the Digital Signature Algorithm (DSA). The generation of shared DSA parameters is described in DSA_generate_parameters(); DSA_generate_key() describes how to generate a signature key. Signature generation and verification are described in DSA_sign().

The DSA structure consists of several BIGNUM components.

 struct
        {
        BIGNUM *p;              // prime number (public)
        BIGNUM *q;              // 160-bit subprime, q | p-1 (public)
        BIGNUM *g;              // generator of subgroup (public)
        BIGNUM *priv_key;       // private key x
        BIGNUM *pub_key;        // public key y = g^x
        // ...
        }
 DSA;

In public keys, priv_key is NULL.

Note that DSA keys may use non-standard DSA_METHOD implementations, either directly or by the use of ENGINE modules. In some cases (e.g. an ENGINE providing support for hardware-embedded keys), these BIGNUM values will not be used by the implementation or may be used for alternative data storage. For this reason, applications should generally avoid using DSA structure elements directly and instead use API functions to query or modify keys.

Conforming To

US Federal Information Processing Standard FIPS 186 (Digital Signature Standard, DSS), ANSI X9.30

See Also

bn(),
dh(), err(),
rand(),
rsa(), sha(),
engine(),
DSA_new(),
DSA_size(),
DSA_generate_parameters(),
DSA_dup_DH(),
DSA_generate_key(),
DSA_sign(),
DSA_set_method(),
DSA_get_ex_new_index(),
RSA_print()

Feedback

For additional information or queries on this page send feedback

©2005-2006 Nokia


DSA_do_verify - raw DSA signature operations

Name

DSA_do_sign, DSA_do_verify — raw DSA signature operations

Library

libcrypto

Synopsis

#include <openssl/dsa.h>
DSA_SIG *DSA_do_sign(const unsigned char *dgst, int dlen, DSA *dsa);
int DSA_do_verify(const unsigned char *dgst, int dgst_len, DSA_SIG *sig, DSA *dsa);

Detailed Description

DSA_do_sign() computes a digital signature on the len byte message digest dgst using the private key dsa and returns it in a newly allocated DSA_SIG structure.

DSA_sign_setup() may be used to precompute part of the signing operation in case signature generation is time-critical.

DSA_do_verify() verifies that the signature sig matches a given message digest dgst of size len. dsa is the signer's public key.

Return Values

DSA_do_sign() returns the signature, NULL on error. DSA_do_verify() returns 1 for a valid signature, 0 for an incorrect signature and -1 on error. The error codes can be obtained by ERR_get_error().

See Also

dsa(),
ERR_get_error(),
rand(),
DSA_SIG_new(),
DSA_sign()

History

DSA_do_sign() and DSA_do_verify() were added in OpenSSL 0.9.3.

Feedback

For additional information or queries on this page send feedback

©2005-2006 Nokia


DSA_dup_DH - create a DH structure out of DSA structure

Name

DSA_dup_DH — creates a DH structure out of DSA structure

Library

libcrypto

Synopsis

#include <openssl/dsa.h>
DH * DSA_dup_DH(const DSA *r);

Detailed Description

DSA_dup_DH() duplicates DSA parameters/keys as DH parameters/keys. q is lost during that conversion, but the resulting DH parameters contain its length.

Return Value

DSA_dup_DH() returns the new DH structure, and NULL on error. The error codes can be obtained by ERR_get_error().

Notes

Be careful to avoid small subgroup attacks when using this.

See Also

dh(), dsa(), ERR_get_error()

History

DSA_dup_DH() was added in OpenSSL 0.9.4.

Feedback

For additional information or queries on this page send feedback

©2005-2006 Nokia


DSA_generate_key - generate DSA key pair

Name

DSA_generate_key — generate DSA key pair

Library

libcrypto

Synopsis

#include <openssl/dsa.h>
int DSA_generate_key(DSA *a);

Detailed Description

DSA_generate_key() expects a to contain DSA parameters. It generates a new key pair and stores it in a->pub_key and a->priv_key.

The PRNG must be seeded prior to calling DSA_generate_key().

Return Value

DSA_generate_key() returns 1 on success, 0 otherwise. The error codes can be obtained by ERR_get_error().

See Also

dsa(),
ERR_get_error(),
rand(),

DSA_generate_parameters()

History

DSA_generate_key() is available since SSLeay 0.8.

Feedback

For additional information or queries on this page send feedback

©2005-2006 Nokia


DSA_generate_parameters - generate DSA parameters

Name

DSA_generate_parameters — generate DSA parameters

Library

libcrypto.lib

Synopsis

#include <openssl/dsa.h>
DSA *DSA_generate_parameters(int bits, unsigned char *seed, int seed_len, int *counter_ret, unsigned long *h_ret,
                             void (*callback)(int, int, void *), void *cb_arg);

Detailed Description

DSA_generate_parameters() generates primes p and q and a generator g for use in the DSA.

bits is the length of the prime to be generated; the DSS allows a maximum of 1024 bits.

If seed is NULL or seed_len < 20, the primes will be generated at random. Otherwise, the seed is used to generate them. If the given seed does not yield a prime q, a new random seed is chosen and placed at seed.

DSA_generate_parameters() places the iteration count in *counter_ret and a counter used for finding a generator in *h_ret, unless these are NULL.

A callback function may be used to provide feedback about the progress of the key generation. If callback is not NULL, it will be called as follows:

    • When a candidate for q is generated, callback(0, m++, cb_arg) is called (m is 0 for the first candidate).

    • When a candidate for q has passed a test by trial division, callback(1, -1, cb_arg) is called. While a candidate for q is tested by Miller-Rabin primality tests, callback(1, i, cb_arg) is called in the outer loop (once for each witness that confirms that the candidate may be prime); i is the loop counter (starting at 0).

    • When a prime q has been found, callback(2, 0, cb_arg) and callback(3, 0, cb_arg) are called.

    • Before a candidate for p (other than the first) is generated and tested, callback(0, counter, cb_arg) is called.

    • When a candidate for p has passed the test by trial division, callback(1, -1, cb_arg) is called. While it is tested by the Miller-Rabin primality test, callback(1, i, cb_arg) is called in the outer loop (once for each witness that confirms that the candidate may be prime). i is the loop counter (starting at 0).

    • When p has been found, callback(2, 1, cb_arg) is called.

    • When the generator has been found, callback(3, 1, cb_arg) is called.

Return Value

DSA_generate_parameters() returns a pointer to the DSA structure, or NULL if the parameter generation fails. The error codes can be obtained by ERR_get_error().

Bugs

Seed lengths > 20 are not supported.

See Also

dsa(),
ERR_get_error(),
rand(),
DSA_free()

History

DSA_generate_parameters() appeared in SSLeay 0.8. The cb_arg argument was added in SSLeay 0.9.0. In versions up to OpenSSL 0.9.4, callback(1, ...) was called in the inner loop of the Miller-Rabin test whenever it reached the squaring step (the parameters to callback did not reveal how many witnesses had been tested); since OpenSSL 0.9.5, callback(1, ...) is called as in BN_is_prime(), i.e. once for each witness =cut

Feedback

For additional information or queries on this page send feedback


DSA_get_ex_data - add application specific data to DSA structures

Name

DSA_get_ex_new_index, DSA_set_ex_data
DSA_get_ex_data

Adds application specific data to DSA structures

Library

libcrypto

Synopsis

#include <openssl/DSA.h>
int DSA_get_ex_new_index(long argl, void *argp, CRYPTO_EX_new *new_func, CRYPTO_EX_dup *dup_func, CRYPTO_EX_free *free_func);
int DSA_set_ex_data(DSA *d, int idx, void *arg);
char *DSA_get_ex_data(DSA *d, int idx);

Detailed Description

These functions handle application specific data in DSA
structures. Their usage is identical to that of
RSA_get_ex_new_index(),  RSA_set_ex_data()
and RSA_get_ex_data()
as described in RSA_get_ex_new_index().

See Also

RSA_get_ex_new_index(), dsa()

History

DSA_get_ex_new_index(),
DSA_set_ex_data() and
DSA_get_ex_data() are
available since OpenSSL 0.9.5.

Feedback

For additional information or queries on this page send feedback

©2005-2006 Nokia


DSA_free - allocate and free DSA objects

Name

DSA_new, DSA_free — allocate and free DSA objects

Library

libcrypto.lib

Synopsis

#include <openssl/dsa.h>
DSA* DSA_new(void);
void DSA_free(DSA *dsa);

Detailed Description

DSA_new() allocates and initializes a DSA structure. It is equivalent to calling DSA_new_method(NULL).

DSA_free() frees the DSA structure and its components. The values are erased before the memory is returned to the system.

Return Values

If the allocation fails, DSA_new() returns NULL and sets an error code that can be obtained by ERR_get_error(). Otherwise it returns a pointer to the newly allocated structure.

DSA_free() returns no value.

See Also

dsa(),
ERR_get_error(),
DSA_generate_parameters(),
DSA_generate_key()

History

DSA_new() and DSA_free() are available in all versions of SSLeay and OpenSSL.

Feedback

For additional information or queries on this page send feedback


DSA_OpenSSL - select DSA method

Name

DSA_set_default_method, DSA_get_default_method
DSA_set_method, DSA_new_method
DSA_OpenSSL

select DSA method

Library

libcrypto.lib

Synopsis

#include <openssl/dsa.h>
#include <openssl/engine.h>
void DSA_set_default_method(const DSA_METHOD *meth);
const DSA_METHOD *DSA_get_default_method(void);
int DSA_set_method(DSA *dsa, const DSA_METHOD *meth);
DSA *DSA_new_method(ENGINE *engine);
DSA_METHOD *DSA_OpenSSL(void);

Detailed Description

A DSA_METHOD specifies the functions that OpenSSL uses for DSA operations. By modifying the method, alternative implementations such as hardware accelerators may be used. IMPORTANT: See the NOTES section for important information about how these DSA API functions are affected by the use of ENGINE API calls.

Initially, the default DSA_METHOD is the OpenSSL internal implementation, as returned by DSA_OpenSSL().

DSA_set_default_method() makes meth the default method for all DSA structures created later. NB: This is true only whilst no ENGINE has been set as a default for DSA, so this function is no longer recommended.

DSA_get_default_method() returns a pointer to the current default DSA_METHOD. However, the meaningfulness of this result is dependant on whether the ENGINE API is being used, so this function is no longer recommended.

DSA_set_method() selects meth to perform all operations using the key rsa. This will replace the DSA_METHOD used by the DSA key and if the previous method was supplied by an ENGINE, the handle to that ENGINE will be released during the change. It is possible to have DSA keys that only work with certain DSA_METHOD implementations (e.g. from an ENGINE module that supports embedded hardware-protected keys), and in such cases attempting to change the DSA_METHOD for the key can have unexpected results.

DSA_new_method() allocates and initializes a DSA structure so that engine will be used for the DSA operations. If engine is NULL, the default engine for DSA operations is used, and if no default ENGINE is set, the DSA_METHOD controlled by DSA_set_default_method() is used.

The DSA_Method Structure

struct
 {
     /* name of the implementation */
        const char *name;

  /* sign */
     DSA_SIG *(*dsa_do_sign)(const unsigned char *dgst, int dlen, DSA *dsa);
  /* pre-compute k^-1 and r */
     int (*dsa_sign_setup)(DSA *dsa, BN_CTX *ctx_in, BIGNUM **kinvp, BIGNUM **rp);
  /* verify */
     int (*dsa_do_verify)(const unsigned char *dgst, int dgst_len, DSA_SIG *sig, DSA *dsa);
  /* compute rr = a1^p1 * a2^p2 mod m (May be NULL for some implementations) */
     int (*dsa_mod_exp)(DSA *dsa, BIGNUM *rr, BIGNUM *a1, BIGNUM *p1, BIGNUM *a2, BIGNUM *p2, BIGNUM *m, BN_CTX *ctx,
          BN_MONT_CTX *in_mont);
  /* compute r = a ^ p mod m (May be NULL for some implementations) */
     int (*bn_mod_exp)(DSA *dsa, BIGNUM *r, BIGNUM *a, const BIGNUM *p, const BIGNUM *m, BN_CTX *ctx, BN_MONT_CTX *m_ctx);
  /* called at DSA_new */
     int (*init)(DSA *DSA);
  /* called at DSA_free */
     int (*finish)(DSA *DSA);
     int flags;
     char *app_data; /* ?? */
 } DSA_METHOD;

Return Values

DSA_OpenSSL() and DSA_get_default_method() return pointers to the respective DSA_METHODs.

DSA_set_default_method() returns no value.

DSA_set_method() returns non-zero if the provided meth was successfully set as the method for dsa (including unloading the ENGINE handle if the previous method was supplied by an ENGINE).

DSA_new_method() returns NULL and sets an error code that can be obtained by ERR_get_error() if the allocation fails. Otherwise it returns a pointer to the newly allocated structure.

Notes

As of version 0.9.7, DSA_METHOD implementations are grouped together with other algorithmic APIs (e.g. RSA_METHOD, EVP_CIPHER, etc) in ENGINE modules. If a default ENGINE is specified for DSA functionality using an ENGINE API function, that will override any DSA defaults set using the DSA API (i.e.. DSA_set_default_method()). For this reason, the ENGINE API is the recommended way to control default implementations for use in DSA and other cryptographic algorithms.

See Also

dsa(), DSA_new()

History

DSA_set_default_method(), DSA_get_default_method(), DSA_set_method(),
DSA_new_method() and
DSA_OpenSSL() were added in OpenSSL 0.9.4.

DSA_set_default_openssl_method() and DSA_get_default_openssl_method() replaced DSA_set_default_method() and DSA_get_default_method() respectively, and DSA_set_method() and DSA_new_method() were altered to use ENGINEs rather than DSA_METHODs during development of the engine version of OpenSSL 0.9.6. For 0.9.7, the handling of defaults in the ENGINE API was restructured so that this change was reversed, and behaviour of the other functions resembled more closely the previous behaviour. The behaviour of defaults in the ENGINE API now transparently overrides the behaviour of defaults in the DSA API without requiring changing these function prototypes.

Feedback

For additional information or queries on this page send feedback


DSA_SIG_free - allocate and free DSA signature objects

Name

DSA_SIG_new, DSA_SIG_free — allocate and free DSA signature objects

Library

libcrypto.lib

Synopsis

#include <openssl/dsa.h>
DSA_SIG *DSA_SIG_new(void);
void   DSA_SIG_free(DSA_SIG *a);

Detailed Description

DSA_SIG_new() allocates and initializes a DSA_SIG structure.

DSA_SIG_free() frees the DSA_SIG structure and its components. The values are erased before the memory is returned to the system.

Return Values

If the allocation fails, DSA_SIG_new() returns NULL and sets an error code that can be obtained by ERR_get_error(). Otherwise it returns a pointer to the newly allocated structure.

DSA_SIG_free() returns no value.

See Also

dsa(),
ERR_get_error(),
DSA_do_sign()

History

DSA_SIG_new() and DSA_SIG_free() were added in OpenSSL 0.9.3.

Feedback

For additional information or queries on this page send feedback


DSA_verify - DSA signatures

Name

DSA_sign, DSA_sign_setup
DSA_verify

DSA signatures

Library

libcrypto.lib

Synopsis

#include <openssl/dsa.h>
int  DSA_sign(int type, const unsigned char *dgst, int len, unsigned char *sigret, unsigned int *siglen, DSA *dsa);
int  DSA_sign_setup(DSA *dsa, BN_CTX *ctx, BIGNUM **kinvp, BIGNUM **rp);
int  DSA_verify(int type, const unsigned char *dgst, int len, unsigned char *sigbuf, int siglen, DSA *dsa);

Detailed Description

DSA_sign() computes a digital signature on the len byte message digest dgst using the private key dsa and places its ASN.1 DER encoding at sigret. The length of the signature is places in *siglen. sigret must point to DSA_size(dsa) bytes of memory.

DSA_sign_setup() may be used to precompute part of the signing operation in case signature generation is time-critical. It expects dsa to contain DSA parameters. It places the precomputed values in newly allocated BIGNUMs at *kinvp and *rp, after freeing the old ones unless *kinvp and *rp are NULL. These values may be passed to DSA_sign() in dsa->kinv and dsa->r. ctx is a pre-allocated BN_CTX or NULL.

DSA_verify() verifies that the signature sigbuf of size siglen matches a given message digest dgst of size len. dsa is the signer's public key.

The type parameter is ignored.

The PRNG must be seeded before DSA_sign() (or DSA_sign_setup()) is called.

Return Values

DSA_sign() and DSA_sign_setup() return 1 on success, 0 on error. DSA_verify() returns 1 for a valid signature, 0 for an incorrect signature and -1 on error. The error codes can be obtained by ERR_get_error().

Conforming To

US Federal Information Processing Standard FIPS 186 (Digital Signature Standard, DSS), ANSI X9.30

See Also

dsa(),
ERR_get_error(),
rand(),
DSA_do_sign()

History

DSA_sign() and DSA_verify() are available in all versions of SSLeay. DSA_sign_setup() was added in SSLeay 0.8.

Feedback

For additional information or queries on this page send feedback


DSA_size - get DSA signature size

Name

DSA_size — get DSA signature size

Library

libcrypto.lib

Synopsis

#include <openssl/dsa.h>
int DSA_size(const DSA *dsa);

Detailed Description

This function returns the size of an ASN.1 encoded DSA signature in bytes. It can be used to determine how much memory must be allocated for a DSA signature.

dsa->q must not be NULL.

Return Value

The size in bytes.

See Also

dsa(), DSA_sign()

History

DSA_size() is available in all versions of SSLeay and OpenSSL.

Feedback

For additional information or queries on this page send feedback


dup

Name

dup, dup2
- duplicate a file descriptor

Library

 libc.lib

Synopsis
#include <unistd.h>
int dup (int oldd);
int dup2 (int oldd, int newd);

Return values

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

Detailed description

 The dup system call duplicates an existing object descriptor and returns its value to the calling process ( newd = dup (oldd, ).);
The argument oldd is a small non-negative integer index in the per-process descriptor table.

The new descriptor returned by the 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 newd in any way. Thus if newd and oldd are duplicate references to an open file, read, write and lseek calls all move a single pointer into the file, and append mode, non-blocking I/O and asynchronous I/O options are shared between the references. If a separate pointer into the file is desired, a different object reference to the file must be obtained by issuing an additional open system call.

In dup2, the value of the new descriptor newd is specified. If this descriptor is already in use and oldd != newd, the descriptor is first deallocated as if the close system 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.

Limitation: dup2(int oldfd, int newfd); The return value of dup2 can be different from the one user expected to be (newfd). So, user of dup2 have to use return value of dup2 as the new allocated fd rather than the one which is been passed to dup2 (newfd). As per the standard, newfd and return values are the same, if dup2 is successful.

Examples

/**
  *Detailed description : Sample usage of dup system call
**/
#include <unistd.h>
#include <fcntl.h>
#include <stdio.h>
int main()
{
  int fd;
  FILE *Fil;
  int Newfd;
  fd = open("Example.txt" , O_CREAT | O_RDWR , 0666);
  if(fd < 0 )  {
     printf("Failed to open file Example.txt \n");
     return -1;
  }
  Newfd  = dup(fd );
  if(Newfd < 0 )
  {
    printf("Failed to duplicate file descriptor \n");
    return -1 ;
  }
  close(fd);
  close(Newfd);
  printf("New Duped fd is %d \n" , Newfd);
  return 0;
}

Output

New Duped fd is 4

/**
  *Detailed description : Sample usage of dup system call
**/
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <stdio.h>
int main()
{
  int fd;
  FILE *Fil;
  int Newfd;
  fd = open("Example.txt" , O_CREAT | O_RDWR , 0666);
  if(fd < 0 )  {
     printf("Failed to open file Example.txt \n");
     return -1;
  }
  Newfd  = dup2(fd  , 4);
  if(Newfd < 0 )  {
    printf("Failed to duplicate file descriptor \n");
    return -1;
  }
  close(fd);
  close(Newfd);
  printf("New Duped fd is %d \n" , Newfd);
  return 0;
}

Output

New Duped fd is 4

Errors

 The dup and dup2 system calls fail if:
[EBADF]
 | The oldd or newd argument is not a valid active descriptor
[EMFILE]
 | Too many descriptors are active.

See also

 accept, close, fcntl, getdtablesize, open, pipe, socket

Feedback

For additional information or queries on this page send feedback


encrypt

Name

encrypt, setkey
- encrypt 64-bit messages

Library

 libcrypt.lib

Synopsis
#include <unistd.h>
void encrypt (char block[64], int edflag);
#include <stdlib.h>
void setkey (const char *key);

Return values

 The encrypt and setkey functions do not return any value.

Detailed description

 encrypt() function encrypts and decrypts 64-bit messages. The algorithm used to perform encryption/decryption is Data Encryption Standard (DES).

setkey() is invoked to set the key for the DES machine. setkey()’ s key parameter is an array of 64 bytes, and the numerical value of each byte in this array is either 0 or 1. The 56-bit key for the DES algorithm is computed from the key parameter.

encrypt function either encrypts or decrypts the data block. The exact operation depends on the value of edflag parameter. block is encrypted if edflag parameter is 0, and decrypted if 1 is being passed as the value of edflag parameter. block is an array of 64 bytes, wherein the numerical value of each byte is either 0 or 1. Like the setkey’ s key parameter, block is a bit vector representation of the actual value that is encoded. It is modified in place to return the result.

encrypt and setkey are not reentrant as the key is stored statically.

Errors

 errno should be set to zero prior to calling any of the above functions. The behavior of encrypt will be undefined if size of block argument is not 64.

Example

#include <stdlib.h>
#include <unistd.h>
void encrypt_user()
{
        /* bit vector containing the key */
        char key[64] =
        {
                        0, 0, 0, 0, 0, 0, 0, 1,
                        0, 0, 1, 1, 0, 0, 0, 1,
                        1, 1, 0, 1, 1, 0, 0, 1,
                        0, 1, 1, 0, 0, 0, 0, 1,
                        1, 0, 0, 1, 1, 1, 0, 1,
                        1, 1, 0, 0, 0, 0, 0, 1,
                        0, 0, 1, 1, 0, 1, 1, 1,
                        0, 1, 1, 0, 1, 1, 1, 0
        };
        /* bit vector containing the data block to be encrypted */
        char block[64] =
        {
                0, 1, 0, 1, 1, 1, 0, 0,
                1, 1, 0, 1, 0, 1, 0, 1,
                0, 1, 0, 0, 1, 1, 0, 0,
                1, 0, 1, 0, 1, 0, 0, 0,
                0, 0, 1, 1, 1, 1, 0, 1,
                1, 1, 1, 0, 1, 1, 1, 1,
                0, 1, 0, 1, 0, 1, 1, 1,
                1, 1, 0, 1, 1, 0, 1, 0
        };
        setkey(key);            /* Set the key for DES encryption */

        /* Perform encryption/decryption of the message block */
        encrypt(block, 0);      /* Encryption. The input block is modified in place
                                         * to return the output to the user
                                         */
        encrypt(block, 1);      /* Decryption. The input block is modified in place
                                         * to return the result of the decryption operation
                                         */
}

See also

Bugs

 If encrypt is called without priorly invoking setkey the implementation assumes a bit vector consisting of all zeroes as the key for the DES algorithm. In this scenaro the outcome of encrypt function is different from that of Linux’s.

Feedback

For additional information or queries on this page send feedback


engine - ENGINE cryptographic module support

Name

engine - ENGINE cryptographic module support

Synopsis

#include <openssl/engine.h>
ENGINE *ENGINE_get_first(void);
ENGINE *ENGINE_get_last(void);
ENGINE *ENGINE_get_next(ENGINE *e);
ENGINE *ENGINE_get_prev(ENGINE *e);
int ENGINE_add(ENGINE *e);
int ENGINE_remove(ENGINE *e);
ENGINE *ENGINE_by_id(const char *id);
int ENGINE_init(ENGINE *e);
int ENGINE_finish(ENGINE *e);
void ENGINE_load_openssl(void);
void ENGINE_load_dynamic(void);
#ifndef OPENSSL_NO_STATIC_ENGINE
void ENGINE_load_4758cca(void);
void ENGINE_load_aep(void);
void ENGINE_load_atalla(void);
void ENGINE_load_chil(void);
void ENGINE_load_cswift(void);
void ENGINE_load_gmp(void);
void ENGINE_load_nuron(void);
void ENGINE_load_sureware(void);
void ENGINE_load_ubsec(void);
#endif
void ENGINE_load_cryptodev(void);
void ENGINE_load_builtin_engines(void);
void ENGINE_cleanup(void);
ENGINE *ENGINE_get_default_RSA(void);
ENGINE *ENGINE_get_default_DSA(void);
ENGINE *ENGINE_get_default_DH(void);
ENGINE *ENGINE_get_default_RAND(void);
ENGINE *ENGINE_get_cipher_engine(int nid);
ENGINE *ENGINE_get_digest_engine(int nid);
int ENGINE_set_default_RSA(ENGINE *e);
int ENGINE_set_default_DSA(ENGINE *e);
int ENGINE_set_default_DH(ENGINE *e);
int ENGINE_set_default_RAND(ENGINE *e);
int ENGINE_set_default_ciphers(ENGINE *e);
int ENGINE_set_default_digests(ENGINE *e);
int ENGINE_set_default_string(ENGINE *e, const char *list);
int ENGINE_set_default(ENGINE *e, unsigned int flags);
unsigned int ENGINE_get_table_flags(void);
void ENGINE_set_table_flags(unsigned int flags);
int ENGINE_register_RSA(ENGINE *e);
void ENGINE_unregister_RSA(ENGINE *e);
void ENGINE_register_all_RSA(void);
int ENGINE_register_DSA(ENGINE *e);
void ENGINE_unregister_DSA(ENGINE *e);
void ENGINE_register_all_DSA(void);
int ENGINE_register_DH(ENGINE *e);
void ENGINE_unregister_DH(ENGINE *e);
void ENGINE_register_all_DH(void);
int ENGINE_register_RAND(ENGINE *e);
void ENGINE_unregister_RAND(ENGINE *e);
void ENGINE_register_all_RAND(void);
int ENGINE_register_STORE(ENGINE *e);
void ENGINE_unregister_STORE(ENGINE *e);
void ENGINE_register_all_STORE(void);
int ENGINE_register_ciphers(ENGINE *e);
void ENGINE_unregister_ciphers(ENGINE *e);
void ENGINE_register_all_ciphers(void);
int ENGINE_register_digests(ENGINE *e);
void ENGINE_unregister_digests(ENGINE *e);
void ENGINE_register_all_digests(void);
int ENGINE_register_complete(ENGINE *e);
int ENGINE_register_all_complete(void);
int ENGINE_ctrl(ENGINE *e, int cmd, long i, void *p, void (*f)(void));
int ENGINE_cmd_is_executable(ENGINE *e, int cmd);
int ENGINE_ctrl_cmd(ENGINE *e, const char *cmd_name, long i, void *p, void (*f)(void), int cmd_optional);
int ENGINE_ctrl_cmd_string(ENGINE *e, const char *cmd_name, const char *arg, int cmd_optional);
int ENGINE_set_ex_data(ENGINE *e, int idx, void *arg);
void *ENGINE_get_ex_data(const ENGINE *e, int idx);
int ENGINE_get_ex_new_index(long argl, void *argp, CRYPTO_EX_new *new_func, CRYPTO_EX_dup *dup_func, CRYPTO_EX_free *free_func);
ENGINE *ENGINE_new(void);
int ENGINE_free(ENGINE *e);
int ENGINE_up_ref(ENGINE *e);
int ENGINE_set_id(ENGINE *e, const char *id);
int ENGINE_set_name(ENGINE *e, const char *name);
int ENGINE_set_RSA(ENGINE *e, const RSA_METHOD *rsa_meth);
int ENGINE_set_DSA(ENGINE *e, const DSA_METHOD *dsa_meth);
int ENGINE_set_DH(ENGINE *e, const DH_METHOD *dh_meth);
int ENGINE_set_RAND(ENGINE *e, const RAND_METHOD *rand_meth);
int ENGINE_set_STORE(ENGINE *e, const STORE_METHOD *rand_meth);
int ENGINE_set_destroy_function(ENGINE *e, ENGINE_GEN_INT_FUNC_PTR destroy_f);
int ENGINE_set_init_function(ENGINE *e, ENGINE_GEN_INT_FUNC_PTR init_f);
int ENGINE_set_finish_function(ENGINE *e, ENGINE_GEN_INT_FUNC_PTR finish_f);
int ENGINE_set_ctrl_function(ENGINE *e, ENGINE_CTRL_FUNC_PTR ctrl_f);
int ENGINE_set_load_privkey_function(ENGINE *e, ENGINE_LOAD_KEY_PTR loadpriv_f);
int ENGINE_set_load_pubkey_function(ENGINE *e, ENGINE_LOAD_KEY_PTR loadpub_f);
int ENGINE_set_ciphers(ENGINE *e, ENGINE_CIPHERS_PTR f);
int ENGINE_set_digests(ENGINE *e, ENGINE_DIGESTS_PTR f);
int ENGINE_set_flags(ENGINE *e, int flags);
int ENGINE_set_cmd_defns(ENGINE *e, const ENGINE_CMD_DEFN *defns);
const char *ENGINE_get_id(const ENGINE *e);
const char *ENGINE_get_name(const ENGINE *e);
const RSA_METHOD *ENGINE_get_RSA(const ENGINE *e);
const DSA_METHOD *ENGINE_get_DSA(const ENGINE *e);
const DH_METHOD *ENGINE_get_DH(const ENGINE *e);
const RAND_METHOD *ENGINE_get_RAND(const ENGINE *e);
const STORE_METHOD *ENGINE_get_STORE(const ENGINE *e);
ENGINE_GEN_INT_FUNC_PTR ENGINE_get_destroy_function(const ENGINE *e);
ENGINE_GEN_INT_FUNC_PTR ENGINE_get_init_function(const ENGINE *e);
ENGINE_GEN_INT_FUNC_PTR ENGINE_get_finish_function(const ENGINE *e);
ENGINE_CTRL_FUNC_PTR ENGINE_get_ctrl_function(const ENGINE *e);
ENGINE_LOAD_KEY_PTR ENGINE_get_load_privkey_function(const ENGINE *e);
ENGINE_LOAD_KEY_PTR ENGINE_get_load_pubkey_function(const ENGINE *e);
ENGINE_CIPHERS_PTR ENGINE_get_ciphers(const ENGINE *e);
ENGINE_DIGESTS_PTR ENGINE_get_digests(const ENGINE *e);
const EVP_CIPHER *ENGINE_get_cipher(ENGINE *e, int nid);
const EVP_MD *ENGINE_get_digest(ENGINE *e, int nid);
int ENGINE_get_flags(const ENGINE *e);
const ENGINE_CMD_DEFN *ENGINE_get_cmd_defns(const ENGINE *e);
EVP_PKEY *ENGINE_load_private_key(ENGINE *e, const char *key_id, UI_METHOD *ui_method, void *callback_data);
EVP_PKEY *ENGINE_load_public_key(ENGINE *e, const char *key_id, UI_METHOD *ui_method, void *callback_data);
void ENGINE_add_conf_module(void);

Detailed Description

These functions create, manipulate, and use cryptographic modules in the form of ENGINE objects. These objects act as containers for implementations of cryptographic algorithms, and support a reference-counted mechanism to allow them to be dynamically loaded in and out of the running application.

The cryptographic functionality that can be provided by an ENGINE implementation includes the following abstractions;

 RSA_METHOD - for providing alternative RSA implementations
 DSA_METHOD, DH_METHOD, RAND_METHOD
 STORE_METHOD - similarly for other OpenSSL APIs
 EVP_CIPHER - potentially multiple cipher algorithms (indexed by 'nid')
 EVP_DIGEST - potentially multiple hash algorithms (indexed by 'nid')
 key-loading - loading public and/or private EVP_PKEY keys

Reference counting and handles

Due to the modular nature of the ENGINE API, pointers to ENGINEs need to be treated as handles - i.e. not only as pointers, but also as references to the underlying ENGINE object. i.e.,. one should obtain a new reference when making copies of an ENGINE pointer if the copies will be used (and released) independently.

ENGINE objects have two levels of reference-counting to match the way in which the objects are used. At the most basic level, each ENGINE pointer is inherently a structural reference - a structural reference is required to use the pointer value at all, as this kind of reference is a guarantee that the structure can not be deallocated until the reference is released.

However, a structural reference provides no guarantee that the ENGINE is initiliased and able to use any of its cryptographic implementations. Indeed it's quite possible that most ENGINEs will not initialize at all in typical environments, as ENGINEs are typically used to support specialized hardware. To use an ENGINE's functionality, a functional reference is required. This kind of reference can be considered a specialized form of structural reference, because each functional reference implicitly contains a structural reference as well - however to avoid difficult-to-find programming bugs, it is recommended to treat the two kinds of reference independently. If there is a functional reference to an ENGINE, it is guaranteed that the ENGINE has been initialized ready to perform cryptographic operations and will remain uninitialized until after the reference is released.

Structural references

This basic type of reference is used for instantiating new ENGINEs, iterating across OpenSSL's internal linked-list of loaded ENGINEs, reading information about an ENGINE, etc. Essentially a structural reference is sufficient if there is only a need to query or manipulate the data of an ENGINE implementation rather than use its functionality.

The ENGINE_new() function returns a structural reference to a new (empty) ENGINE object. There are other ENGINE API functions that return structural references such as; ENGINE_by_id(), ENGINE_get_first(), ENGINE_get_last(), ENGINE_get_next(), ENGINE_get_prev(). All structural references should be released by a corresponding to call to the ENGINE_free() function - the ENGINE object itself will only actually be cleaned up and deallocated when the last structural reference is released.

It should also be noted that many ENGINE API function calls that accept a structural reference will internally obtain another reference - typically this happens whenever the supplied ENGINE will be needed by OpenSSL after the function has returned. E.g. the function to add a new ENGINE to OpenSSL's internal list is ENGINE_add() - if this function returns success, then OpenSSL will have stored a new structural reference internally so the caller is still responsible for freeing their own reference with ENGINE_free() when they are finished with it. In a similar way, some functions will automatically release the structural reference passed to it if part of the function's job is to do so. E.g.. the ENGINE_get_next() and ENGINE_get_prev() functions are used for iterating across the internal ENGINE list - they will return a new structural reference to the next (or previous) ENGINE in the list or NULL if at the end (or beginning) of the list, but in either case the structural reference passed to the function is released on behalf of the caller.

To clarify a particular function's handling of references, one should always consult that function's documentation ``man'' page, or failing that the openssl/engine.h header file includes some hints.

Functional references

As mentioned, functional references exist when the cryptographic functionality of an ENGINE is required to be available. A functional reference can be obtained in one of two ways; from an existing structural reference to the required ENGINE, or by asking OpenSSL for the default operational ENGINE for a given cryptographic purpose.

To obtain a functional reference from an existing structural reference, call the ENGINE_init() function. This returns zero if the ENGINE was not already operational and couldn't be successfully initialized (e.g.. lack of system drivers, no special hardware attached, etc), otherwise it will return non-zero to indicate that the ENGINE is now operational and will have allocated a new functional reference to the ENGINE. All functional references are released by calling ENGINE_finish() (which removes the implicit structural reference as well).

The second way to get a functional reference is by asking OpenSSL for a default implementation for a given task, e.g. by ENGINE_get_default_RSA(), ENGINE_get_default_cipher_engine(), etc. These are discussed in the next section, though they are not usually required by application programmers as they are used automatically when creating and using the relevant algorithm-specific types in OpenSSL, such as RSA, DSA, EVP_CIPHER_CTX, etc.

Default implementations

For each supported abstraction, the ENGINE code maintains an internal table of state to control which implementations are available for a given abstraction and which should be used by default. These implementations are registered in the tables and indexed by an 'nid' value, because abstractions like EVP_CIPHER and EVP_DIGEST support many distinct algorithms and modes, and ENGINEs can support arbitrarily many of them. In the case of other abstractions like RSA, DSA, etc, there is only one ``algorithm'' so all implementations implicitly register using the same 'nid' index.

When a default ENGINE is requested for a given abstraction/algorithm/mode, (e.g. when calling RSA_new_method(NULL)), a ``get_default'' call will be made to the ENGINE subsystem to process the corresponding state table and return a functional reference to an initialized ENGINE whose implementation should be used. If no ENGINE should (or can) be used, it will return NULL and the caller will operate with a NULL ENGINE handle - this usually equates to using the conventional software implementation. In the latter case, OpenSSL will from then on behave the way it used to before the ENGINE API existed.

Each state table has a flag to note whether it has processed this ``get_default'' query since the table was last modified, because to process this question it must iterate across all the registered ENGINEs in the table trying to initialize each of them in turn, in case one of them is operational. If it returns a functional reference to an ENGINE, it will also cache another reference to speed up processing future queries (without needing to iterate across the table). Likewise, it will cache a NULL response if no ENGINE was available so that future queries won't repeat the same iteration unless the state table changes. This behaviour can also be changed; if the ENGINE_TABLE_FLAG_NOINIT flag is set (using ENGINE_set_table_flags()), no attempted initializations will take place, instead the only way for the state table to return a non-NULL ENGINE to the ``get_default'' query will be if one is expressly set in the table. E.g. ENGINE_set_default_RSA() does the same job as ENGINE_register_RSA() except that it also sets the state table's cached response for the ``get_default'' query. In the case of abstractions like EVP_CIPHER, where implementations are indexed by 'nid', these flags and cached-responses are distinct for each 'nid' value.

Application requirements

This section will explain the basic things an application programmer should support to make the most useful elements of the ENGINE functionality available to the user. The first thing to consider is whether the programmer wishes to make alternative ENGINE modules available to the application and user. OpenSSL maintains an internal linked list of ``visible'' ENGINEs from which it has to operate - at start-up, this list is empty and in fact if an application does not call any ENGINE API calls and it uses static linking against openssl, then the resulting application binary will not contain any alternative ENGINE code at all. So the first consideration is whether any/all available ENGINE implementations should be made visible to OpenSSL - this is controlled by calling the various ``load'' functions, e.g.

 /* Make the "dynamic" ENGINE available */
 void ENGINE_load_dynamic(void);
 /* Make the CryptoSwift hardware acceleration support available */
 void ENGINE_load_cswift(void);
 /* Make support for nCipher's "CHIL" hardware available */
 void ENGINE_load_chil(void);
 ...
 /* Make ALL ENGINE implementations bundled with OpenSSL available */
 void ENGINE_load_builtin_engines(void);

Having called any of these functions, ENGINE objects would have been dynamically allocated and populated with these implementations and linked into OpenSSL's internal linked list. At this point it is important to mention an important API function;

 void ENGINE_cleanup(void);

If no ENGINE API functions are called at all in an application, then there are no inherent memory leaks to worry about from the ENGINE functionality, however if any ENGINEs are loaded, even if they are never registered or used, it is necessary to use the ENGINE_cleanup() function to correspondingly cleanup before program exit, if the caller wishes to avoid memory leaks. This mechanism uses an internal callback registration table so that any ENGINE API functionality that knows it requires cleanup can register its cleanup details to be called during ENGINE_cleanup(). This approach allows ENGINE_cleanup() to clean up after any ENGINE functionality that the program uses, yet does not automatically create linker dependencies to all possible ENGINE functionality - only the cleanup callbacks required by the functionality used will be required by the linker.

The fact that ENGINEs are made visible to OpenSSL (and thus are linked into the program and loaded into memory at run-time) does not mean they are ``registered'' or called into use by OpenSSL automatically - that behaviour is something for the application to control. Some applications will want to allow the user to specify exactly which ENGINE they want used if any is to be used at all. Others may prefer to load all support and have OpenSSL automatically use at run-time any ENGINE that is able to successfully initialize - i.e. to assume that this corresponds to acceleration hardware attached to the machine or some such thing. There are probably numerous other ways in which applications may prefer to handle things, so we will simply illustrate the consequences as they apply to a couple of simple cases and leave developers to consider these and the source code to openssl's built-in utilities as guides.

Using a specific ENGINE implementation

Here we'll assume an application has been configured by its user or admin to want to use the ``ACME'' ENGINE if it is available in the version of OpenSSL the application was compiled with. If it is available, it should be used by default for all RSA, DSA, and symmetric cipher operation, otherwise OpenSSL should use its built-in software as per usual. The following code illustrates how to approach this;

 ENGINE *e;
 const char *engine_id = "ACME";
 ENGINE_load_builtin_engines();
 e = ENGINE_by_id(engine_id);
 if(!e)
     /* the engine isn't available */
     return;
 if(!ENGINE_init(e)) {
     /* the engine couldn't initialise, release 'e' */
     ENGINE_free(e);
     return;
 }
 if(!ENGINE_set_default_RSA(e))
     /* This should only happen when 'e' cannot initialise, but the previous
      * statement suggests it did. */
     abort();
 ENGINE_set_default_DSA(e);
 ENGINE_set_default_ciphers(e);
 /* Release the functional reference from ENGINE_init() */
 ENGINE_finish(e);
 /* Release the structural reference from ENGINE_by_id() */
 ENGINE_free(e);

Automatically using builtin ENGINE implementations

Here we'll assume we want to load and register all ENGINE implementations bundled with OpenSSL, such that for any cryptographic algorithm required by OpenSSL - if there is an ENGINE that implements it and can be initialise, it should be used. The following code illustrates how this can work;

 /* Load all bundled ENGINEs into memory and make them visible */
 ENGINE_load_builtin_engines();
 /* Register all of them for every algorithm they collectively implement */
 ENGINE_register_all_complete();

That's all that's required. E.g. the next time OpenSSL tries to set up an RSA key, any bundled ENGINEs that implement RSA_METHOD will be passed to ENGINE_init() and if any of those succeed, that ENGINE will be set as the default for RSA use from then on.

Advanced configuration support

There is a mechanism supported by the ENGINE framework that allows each ENGINE implementation to define an arbitrary set of configuration ``commands'' and expose them to OpenSSL and any applications based on OpenSSL. This mechanism is entirely based on the use of name-value pairs and assumes ASCII input (no unicode or UTF for now!), so it is ideal if applications want to provide a transparent way for users to provide arbitrary configuration ``directives'' directly to such ENGINEs. It is also possible for the application to dynamically interrogate the loaded ENGINE implementations for the names, descriptions, and input flags of their available ``control commands'', providing a more flexible configuration scheme. However, if the user is expected to know which ENGINE device he/she is using (in the case of specialized hardware, this goes without saying) then applications may not need to concern themselves with discovering the supported control commands and simply prefer to pass settings into ENGINEs exactly as they are provided by the user.

Before illustrating how control commands work, it is worth mentioning what they are typically used for. Broadly speaking there are two uses for control commands; the first is to provide the necessary details to the implementation (which may know nothing at all specific to the host system) so that it can be initialized for use. This could include the path to any driver or config files it needs to load, required network addresses, smart-card identifiers, passwords to initialise protected devices, logging information, etc etc. This class of commands typically needs to be passed to an ENGINE before attempting to initialise it, i.e. before calling ENGINE_init(). The other class of commands consist of settings or operations that tweak certain behaviour or cause certain operations to take place, and these commands may work either before or after ENGINE_init(), or in some cases both. ENGINE implementations should provide indications of this in the descriptions attached to builtin control commands and/or in external product documentation.

Issuing control commands to an ENGINE

Let's illustrate by example; a function for which the caller supplies the name of the ENGINE it wishes to use, a table of string-pairs for use before initialization, and another table for use after initialization. Note that the string-pairs used for control commands consist of a command ``name'' followed by the command ``parameter'' - the parameter could be NULL in some cases but the name can not. This function should initialise the ENGINE (issuing the ``pre'' commands beforehand and the ``post'' commands afterwards) and set it as the default for everything except RAND and then return a boolean success or failure.

 int generic_load_engine_fn(const char *engine_id,
                            const char **pre_cmds, int pre_num,
                            const char **post_cmds, int post_num)
 {
     ENGINE *e = ENGINE_by_id(engine_id);
     if(!e) return 0;
     while(pre_num--) {
         if(!ENGINE_ctrl_cmd_string(e, pre_cmds[0], pre_cmds[1], 0)) {
             fprintf(stderr, "Failed command (%s - %s:%s)\n", engine_id,
                 pre_cmds[0], pre_cmds[1] ? pre_cmds[1] : "(NULL)");
             ENGINE_free(e);
             return 0;
         }
         pre_cmds += 2;
     }
     if(!ENGINE_init(e)) {
         fprintf(stderr, "Failed initialisation\n");
         ENGINE_free(e);
         return 0;
     }
     /* ENGINE_init() returned a functional reference, so free the structural
      * reference from ENGINE_by_id(). */
     ENGINE_free(e);
     while(post_num--) {
         if(!ENGINE_ctrl_cmd_string(e, post_cmds[0], post_cmds[1], 0)) {
             fprintf(stderr, "Failed command (%s - %s:%s)\n", engine_id,
                 post_cmds[0], post_cmds[1] ? post_cmds[1] : "(NULL)");
             ENGINE_finish(e);
             return 0;
         }
         post_cmds += 2;
     }
     ENGINE_set_default(e, ENGINE_METHOD_ALL & ~ENGINE_METHOD_RAND);
     /* Success */
     return 1;
 }

Note that ENGINE_ctrl_cmd_string() accepts a boolean argument that can relax the semantics of the function - if set non-zero it will only return failure if the ENGINE supported the given command name but failed while executing it, if the ENGINE does not support the command name it will simply return success without doing anything. In this case we assume the user is only supplying commands specific to the given ENGINE so we set this to FALSE.

Discovering supported control commands

It is possible to discover at run-time the names, numerical-ids, descriptions and input parameters of the control commands supported by an ENGINE using a structural reference. Note that some control commands are defined by OpenSSL itself and it will intercept and handle these control commands on behalf of the ENGINE, i.e. the ENGINE's ctrl() handler is not used for the control command. openssl/engine.h defines an index, ENGINE_CMD_BASE, that all control commands implemented by ENGINEs should be numbered from. Any command value lower than this symbol is considered a ``generic'' command is handled directly by the OpenSSL core routines.

It is using these ``core'' control commands that one can discover the control commands implemented by a given ENGINE, specifically the commands;

 #define ENGINE_HAS_CTRL_FUNCTION               10
 #define ENGINE_CTRL_GET_FIRST_CMD_TYPE         11
 #define ENGINE_CTRL_GET_NEXT_CMD_TYPE          12
 #define ENGINE_CTRL_GET_CMD_FROM_NAME          13
 #define ENGINE_CTRL_GET_NAME_LEN_FROM_CMD      14
 #define ENGINE_CTRL_GET_NAME_FROM_CMD          15
 #define ENGINE_CTRL_GET_DESC_LEN_FROM_CMD      16
 #define ENGINE_CTRL_GET_DESC_FROM_CMD          17
 #define ENGINE_CTRL_GET_CMD_FLAGS              18

Whilst these commands are automatically processed by the OpenSSL framework code, they use various properties exposed by each ENGINE to process these queries. An ENGINE has 3 properties it exposes that can affect how this behaves; it can supply a ctrl() handler, it can specify ENGINE_FLAGS_MANUAL_CMD_CTRL in the ENGINE's flags, and it can expose an array of control command descriptions. If an ENGINE specifies the ENGINE_FLAGS_MANUAL_CMD_CTRL flag, then it will simply pass all these ``core'' control commands directly to the ENGINE's ctrl() handler (and thus, it must have supplied one), so it is up to the ENGINE to reply to these ``discovery'' commands itself. If that flag is not set, then the OpenSSL framework code will work with the following rules;

 if no ctrl() handler supplied;
     ENGINE_HAS_CTRL_FUNCTION returns FALSE (zero),
     all other commands fail.
 if a ctrl() handler was supplied but no array of control commands;
     ENGINE_HAS_CTRL_FUNCTION returns TRUE,
     all other commands fail.
 if a ctrl() handler and array of control commands was supplied;
     ENGINE_HAS_CTRL_FUNCTION returns TRUE,
     all other commands proceed processing ...

If the ENGINE's array of control commands is empty then all other commands will fail, otherwise; ENGINE_CTRL_GET_FIRST_CMD_TYPE returns the identifier of the first command supported by the ENGINE, ENGINE_GET_NEXT_CMD_TYPE takes the identifier of a command supported by the ENGINE and returns the next command identifier or fails if there are no more, ENGINE_CMD_FROM_NAME takes a string name for a command and returns the corresponding identifier or fails if no such command name exists, and the remaining commands take a command identifier and return properties of the corresponding commands. All except ENGINE_CTRL_GET_FLAGS return the string length of a command name or description, or populate a supplied character buffer with a copy of the command name or description. ENGINE_CTRL_GET_FLAGS returns a bitwise-OR'd mask of the following possible values;

 #define ENGINE_CMD_FLAG_NUMERIC                (unsigned int)0x0001
 #define ENGINE_CMD_FLAG_STRING                 (unsigned int)0x0002
 #define ENGINE_CMD_FLAG_NO_INPUT               (unsigned int)0x0004
 #define ENGINE_CMD_FLAG_INTERNAL               (unsigned int)0x0008

If the ENGINE_CMD_FLAG_INTERNAL flag is set, then any other flags are purely informational to the caller - this flag will prevent the command being usable for any higher-level ENGINE functions such as ENGINE_ctrl_cmd_string(). ``INTERNAL'' commands are not intended to be exposed to text-based configuration by applications, administrations, users, etc. These can support arbitrary operations via ENGINE_ctrl(), including passing to and/or from the control commands data of any arbitrary type. These commands are supported in the discovery mechanisms simply to allow applications determine if an ENGINE supports certain specific commands it might want to use (e.g. application ``foo'' might query various ENGINEs to see if they implement ``FOO_GET_VENDOR_LOGO_GIF'' - and ENGINE could therefore decide whether or not to support this ``foo''-specific extension).

Future developments

The ENGINE API and internal architecture is currently being reviewed. Slated for possible release in 0.9.8 is support for transparent loading of ``dynamic'' ENGINEs (built as self-contained shared-libraries). This would allow ENGINE implementations to be provided independently of OpenSSL libraries and/or OpenSSL-based applications, and would also remove any requirement for applications to explicitly use the ``dynamic'' ENGINE to bind to shared-library implementations.

See Also

rsa(),
dsa(), dh(),
rand()

Feedback

For additional information or queries on this page send feedback


erf

Name

erf, erff, erfl, erfc, erfcf, erfcl
- error function and complementary error function

Library

 libm.lib

Synopsis
#include <math.h>
double erf (double x);
float erff (float x);
long double erf (long double x);
double erfc (double x);
float erfcf (float x);
long double erfcl (long double x);

Detailed 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/sqrt(pi)*integral from 0 to x of exp(-t*t) dt.
erf(x) :=
(2/v/pi)I00x0exp(-t20)dt.

The erfc, erfcf, and erfcl functions calculate the complementary error function 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.

The functions erfl and erfcl
are aliases to the functions erf and erfc respectively.

Examples

#include <math.h>
int main( void )
{
   double x, y;
   x = 0.75;
   y = erf( x );
   printf( "erf( %f ) = %f\n", x, y );
   y = erff( x );
   printf( "erff( %f ) = %f\n",x, y );
   y = erfl( x );
   printf( "erfl( %f ) = %f\n",x, y );
   y = erfc( x );
   printf( "erf( %f ) = %f\n", x, y );
   y = erfcf( x );
   printf( "erff( %f ) = %f\n",x, y );
   y = erfcl( x );
   printf( "erfl( %f ) = %f\n",x, y );
}

Output

erf ( 0.75 )  = 0.711156
erff( 0.75 )  = 0.711156
erfl( 0.75 )  = 0.711156
erfc( 0.75 )  = 0.288844
erfcf( 0.75 ) = 0.288844
erfcl( 0.75 ) = 0.288844

See also

 math

Feedback

For additional information or queries on this page send feedback


err - error codes

Name

err — information about where the error occurred

Library

libcrypto.lib

Synopsis

#include <openssl/err.h>
unsigned long ERR_get_error(void);
unsigned long ERR_peek_error(void);
unsigned long ERR_get_error_line(const char **file, int *line);
unsigned long ERR_peek_error_line(const char **file, int *line);
unsigned long ERR_get_error_line_data(const char **file, int *line, const char **data, int *flags);
unsigned long ERR_peek_error_line_data(const char **file, int *line, const char **data, int *flags);
int ERR_GET_LIB(unsigned long e);
int ERR_GET_FUNC(unsigned long e);
int ERR_GET_REASON(unsigned long e);
void ERR_clear_error(void);
char *ERR_error_string(unsigned long e, char *buf);
const char *ERR_lib_error_string(unsigned long e);
const char *ERR_func_error_string(unsigned long e);
const char *ERR_reason_error_string(unsigned long e);
void ERR_print_errors(BIO *bp);
void ERR_print_errors_fp(FILE *fp);
void ERR_load_crypto_strings(void);
void ERR_free_strings(void);
void ERR_remove_state(unsigned long pid);
void ERR_put_error(int lib, int func, int reason, const char *file, int line);
void ERR_add_error_data(int num, ...);
void ERR_load_strings(int lib,ERR_STRING_DATA str[]);
unsigned long ERR_PACK(int lib, int func, int reason);
int ERR_get_next_error_library(void);

Detailed Description

When a call to the OpenSSL library fails, this is usually signaled by the return value, and an error code is stored in an error queue associated with the current thread. The err library provides functions to obtain these error codes and textual error messages.

The ERR_get_error() manpage describes how to access error codes.

Error codes contain information about where the error occurred, and what went wrong. ERR_GET_LIB() describes how to extract this information. A method to obtain human-readable error messages is described in ERR_error_string().

ERR_clear_error() can be used to clear the error queue.

Note that ERR_remove_state() should be used to avoid memory leaks when threads are terminated.

Adding New Error Codes to OpenSSL

See ERR_put_error() to record error codes in the OpenSSL error system from within the application.

The remainder of this section is of interest only to add new error codes to OpenSSL or add error codes from external libraries.

Reporting errors

Each sub-library has a specific macro XXXerr() that is used to report errors. Its first argument is a function code XXX_F_..., the second argument is a reason code XXX_R_.... Function codes are derived from the function names; reason codes consist of textual error descriptions. For example, the function ssl23_read() reports a ``handshake failure'' as follows:

 SSLerr(SSL_F_SSL23_READ, SSL_R_SSL_HANDSHAKE_FAILURE);

Function and reason codes should consist of upper case characters, numbers and underscores only. The error file generation script translates function codes into function names by looking in the header files for an appropriate function name, if none is found it just uses the capitalized form such as ``SSL23_READ'' in the above example.

The trailing section of a reason code (after the ``_R_'') is translated into lower case and underscores changed to spaces.

When using new function or reason codes, run make errors. The necessary #defines will then automatically be added to the sub-library's header file.

Although a library will normally report errors using its own specific XXXerr macro, another library's macro can be used. This is normally only done when a library wants to include ASN1 code which must use the ASN1err() macro.

Adding new libraries

When adding a new sub-library to OpenSSL, assign it a library number ERR_LIB_XXX, define a macro XXXerr() (both in err.h), add its name to ERR_str_libraries[] (in crypto/err/err.c), and add ERR_load_XXX_strings() to the ERR_load_crypto_strings() function (in crypto/err/err_all.c). Finally, add an entry

 L      XXX     xxx.h   xxx_err.c

to crypto/err/openssl.ec, and add xxx_err.c to the Makefile. Running make errors will then generate a file xxx_err.c, and add all error codes used in the library to xxx.h.

Additionally the library include file must have a certain form. Typically it will initially look like this:

 #ifndef HEADER_XXX_H
 #define HEADER_XXX_H
 #ifdef __cplusplus
 extern "C" {
 #endif
 /* Include files */
 #include <openssl/bio.h>
 #include <openssl/x509.h>
 /* Macros, structures and function prototypes */
 /* BEGIN ERROR CODES */

The BEGIN ERROR CODES sequence is used by the error code generation script as the point to place new error codes, any text after this point will be overwritten when make errors is run. The closing #endif etc will be automatically added by the script.

The generated C error code file xxx_err.c will load the header files stdio.h, openssl/err.h and openssl/xxx.h so the header file must load any additional header files containing any definitions it uses.

Using Error Codes in External Libraries

It is also possible to use OpenSSL's error code scheme in external libraries. The library needs to load its own codes and call the OpenSSL error code insertion script mkerr.pl explicitly to add codes to the header file and generate the C error code file. This will normally be done if the external library needs to generate new ASN1 structures but it can also be used to add more general purpose error code handling.

TBA more details

Internals

The error queues are stored in a hash table with one ERR_STATE entry for each pid. ERR_get_state() returns the current thread's ERR_STATE. An ERR_STATE can hold up to ERR_NUM_ERRORS error codes. When more error codes are added, the old ones are overwritten, on the assumption that the most recent errors are most important.

Error strings are also stored in hash table. The hash tables can be obtained by calling ERR_get_err_state_table(void) and ERR_get_string_table(void) respectively.

See Also

CRYPTO_set_id_callback(),
CRYPTO_set_locking_callback(),
ERR_get_error(),
ERR_GET_LIB(),
ERR_clear_error(),
ERR_error_string(),
ERR_print_errors(),
ERR_load_crypto_strings(),
ERR_remove_state(),
ERR_put_error(),
ERR_load_strings(),
SSL_get_error()

Feedback

For additional information or queries on this page send feedback


ERR_clear_error - clear the error queue

Name

ERR_clear_error — clear the error queue

Library

libcrypto.lib

Synopsis

#include <openssl/err.h>
void ERR_clear_error(void);

Detailed Description

ERR_clear_error() empties the current thread's error queue.

Return Values

ERR_clear_error() has no return value.

See Also

err(), ERR_get_error()

History

ERR_clear_error() is available in all versions of SSLeay and OpenSSL.

Feedback

For additional information or queries on this page send feedback


ERR_reason_error_string - obtain human-readable error message

Name

ERR_error_string, ERR_error_string_n
ERR_lib_error_string, ERR_func_error_string
ERR_reason_error_string

obtain human-readable error message

Library

libcrypto.lib

Synopsis

#include <openssl/err.h>
char *ERR_error_string(unsigned long e, char *buf);
void ERR_error_string_n(unsigned long e, char *buf, size_t len);
const char *ERR_lib_error_string(unsigned long e);
const char *ERR_func_error_string(unsigned long e);
const char *ERR_reason_error_string(unsigned long e);

Detailed Description

ERR_error_string() generates a human-readable string representing the error code e, and places it at buf. buf must be at least 120 bytes long. If buf is NULL, the error string is placed in a static buffer. ERR_error_string_n() is a variant of ERR_error_string() that writes at most len characters (including the terminating 0) and truncates the string if necessary. For ERR_error_string_n(), buf may not be NULL.

The string will have the following format:

 error:[error code]:[library name]:[function name]:[reason string]

error code is an 8 digit hexadecimal number, library name, function name and reason string are ASCII text.

ERR_lib_error_string(),
ERR_func_error_string() and

ERR_reason_error_string() return the library name, function
name and reason string respectively.

The OpenSSL error strings should be loaded by calling ERR_load_crypto_strings() or, for SSL applications, SSL_load_error_strings() first. If there is no text string registered for the given error code, the error string will contain the numeric code.

ERR_print_errors() can be used to print all error codes currently in the queue.

Return Values

ERR_error_string() returns a pointer to a static buffer containing the string if buf == NULL, buf otherwise.

ERR_lib_error_string(),
ERR_func_error_string() and

ERR_reason_error_string()
return the strings, and NULL if
none is registered for the error code.

See Also

err(),
ERR_get_error(),
ERR_load_crypto_strings(),
SSL_load_error_strings(),
ERR_print_errors()

History

ERR_error_string() is available in all versions of SSLeay and OpenSSL. ERR_error_string_n() was added in OpenSSL 0.9.6.

Feedback

For additional information or queries on this page send feedback


ERR_peek_last_error_line_data - obtain error code and data

Name

ERR_get_error, ERR_peek_error
ERR_peek_last_error, ERR_get_error_line
ERR_peek_error_line, ERR_peek_last_error_line
ERR_get_error_line_data, ERR_peek_error_line_data
ERR_peek_last_error_line_data

obtain error code and data

Library

libcrypto.lib

Synopsis

#include <openssl/err.h>
unsigned long ERR_get_error(void);
unsigned long ERR_peek_error(void);
unsigned long ERR_peek_last_error(void);
unsigned long ERR_get_error_line(const char **file, int *line);
unsigned long ERR_peek_error_line(const char **file, int *line);
unsigned long ERR_peek_last_error_line(const char **file, int *line);
unsigned long ERR_get_error_line_data(const char **file, int *line, const char **data, int *flags);
unsigned long ERR_peek_error_line_data(const char **file, int *line, const char **data, int *flags);
unsigned long ERR_peek_last_error_line_data(const char **file, int *line, const char **data, int *flags);

Detailed Description

ERR_get_error() returns the earliest error code from the thread's error queue and removes the entry. This function can be called repeatedly until there are no more error codes to return.

ERR_peek_error() returns the earliest error code from the thread's error queue without modifying it.

ERR_peek_last_error() returns the latest error code from the thread's error queue without modifying it.

See ERR_GET_LIB() for obtaining information about location and reason of the error, and ERR_error_string() for human-readable error messages.

ERR_get_error_line(), ERR_peek_error_line() and ERR_peek_last_error_line() are the same as the above, but they additionally store the file name and line number where the error occurred in *file and *line, unless these are NULL.

ERR_get_error_line_data(), ERR_peek_error_line_data() and ERR_get_last_error_line_data() store additional data and flags associated with the error code in *data and *flags, unless these are NULL. *data contains a string if *flags&ERR_TXT_STRING. If it has been allocated by OPENSSL_malloc(), *flags&ERR_TXT_MALLOCED is true.

Return Values

The error code, or 0 if there is no error in the queue.

See Also

err(),
ERR_error_string(),
ERR_GET_LIB()

History

ERR_get_error(), ERR_peek_error(), ERR_get_error_line() and ERR_peek_error_line() are available in all versions of SSLeay and OpenSSL. ERR_get_error_line_data() and ERR_peek_error_line_data() were added in SSLeay 0.9.0. ERR_peek_last_error(), ERR_peek_last_error_line() and ERR_peek_last_error_line_data() were added in OpenSSL 0.9.7.

Feedback

For additional information or queries on this page send feedback


ERR_GET_REASON - get library, function and reason code

Name

ERR_GET_LIB, ERR_GET_FUNC
ERR_GET_REASON

get library, function and reason code

Library

libcrypto.lib

Synopsis

#include <openssl/err.h>
int ERR_GET_LIB(unsigned long e);
int ERR_GET_FUNC(unsigned long e);
int ERR_GET_REASON(unsigned long e);

Detailed Description

The error code returned by ERR_get_error() consists of a library number, function code and reason code. ERR_GET_LIB(), ERR_GET_FUNC() and ERR_GET_REASON() can be used to extract these.

The library number and function code describe where the error occurred, the reason code is the information about what went wrong.

Each sub-library of OpenSSL has a unique library number; function and reason codes are unique within each sub-library. Note that different libraries may use the same value to signal different functions and reasons.

ERR_R_... reason codes such as ERR_R_MALLOC_FAILURE are globally unique. However, when checking for sub-library specific reason codes, be sure to also compare the library number.

ERR_GET_LIB(), ERR_GET_FUNC() and ERR_GET_REASON() are macros.

Return Values

The library number, function code and reason code respectively.

See Also

err(), ERR_get_error()

History

ERR_GET_LIB(), ERR_GET_FUNC() and ERR_GET_REASON() are available in all versions of SSLeay and OpenSSL.

Feedback

For additional information or queries on this page send feedback


ERR_free_strings - load and free error strings

Name

ERR_load_crypto_strings, SSL_load_error_strings
ERR_free_strings

load and free error strings

Library

libcrypto.lib

Synopsis

#include <openssl/err.h>
void ERR_load_crypto_strings(void);
void ERR_free_strings(void);
#include <openssl/ssl.h>
void SSL_load_error_strings(void);

Detailed Description

ERR_load_crypto_strings() registers the error strings for all libcrypto functions. SSL_load_error_strings() does the same, but also registers the libssl error strings.

One of these functions should be called before generating textual error messages. However, this is not required when memory usage is an issue.

ERR_free_strings() frees all previously loaded error strings.

Return Values

ERR_load_crypto_strings(),
SSL_load_error_strings() and

ERR_free_strings() return no values.

See Also

err(), ERR_error_string()

History

ERR_load_error_strings(),
SSL_load_error_strings() and

ERR_free_strings()
are available in all versions of SSLeay and
OpenSSL.

Feedback

For additional information or queries on this page send feedback


ERR_get_next_error_library - load arbitrary error strings

Name

ERR_load_strings, ERR_PACK
ERR_get_next_error_library

load arbitrary error strings

Library

libcrypto.lib

Synopsis

#include <openssl/err.h>
void ERR_load_strings(int lib, ERR_STRING_DATA str[]);
int ERR_get_next_error_library(void);
unsigned long ERR_PACK(int lib, int func, int reason);

Detailed Description

ERR_load_strings() registers error strings for library number lib.

str is an array of error string data:

 typedef struct ERR_string_data_st
 {
   unsigned long error;
   char *string;
 } ERR_STRING_DATA;

The error code is generated from the library number and a function and reason code: error = ERR_PACK(lib, func, reason). ERR_PACK() is a macro.

The last entry in the array is {0,0}.

ERR_get_next_error_library() can be used to assign library numbers to user libraries at runtime.

Return Values

ERR_load_strings() returns no value. ERR_PACK() return the error code. ERR_get_next_error_library() returns a new library number.

See Also

err(), ERR_load_strings()

History

ERR_load_error_strings() and ERR_PACK() are available in all versions of SSLeay and OpenSSL. ERR_get_next_error_library() was added in SSLeay 0.9.0.

Feedback

For additional information or queries on this page send feedback


ERR_print_errors_fp - print error messages

Name

ERR_print_errors, ERR_print_errors_fp — print error messages

Library

libcrypto.lib

Synopsis

#include <openssl/err.h>
void ERR_print_errors(BIO *bp);
void ERR_print_errors_fp(FILE *fp);

Detailed Description

ERR_print_errors() is a convenience function that prints the error strings for all errors that OpenSSL has recorded to bp, thus emptying the error queue.

ERR_print_errors_fp() is the same, except that the output goes to a FILE.

The error strings will have the following format:

 [pid]:error:[error code]:[library name]:[function name]:[reason string]:[file name]:[line]:[optional text message]

error code is an 8 digit hexadecimal number. library name, function name and reason string are ASCII text, as is optional text message if one was set for the respective error code.

If there is no text string registered for the given error code, the error string will contain the numeric code.

Return Values

ERR_print_errors() and ERR_print_errors_fp() return no values.

See Also

err(),
ERR_error_string(),
ERR_get_error(),
ERR_load_crypto_strings(),
SSL_load_error_strings()

History

ERR_print_errors() and ERR_print_errors_fp() are available in all versions of SSLeay and OpenSSL.

Feedback

For additional information or queries on this page send feedback


ERR_add_error_data - record an error

Name

ERR_put_error, ERR_add_error_data — record an error

Library

libcrypto.lib

Synopsis

#include <openssl/err.h>
void ERR_put_error(int lib, int func, int reason, const char *file, int line);
void ERR_add_error_data(int num, ...);

Detailed Description

ERR_put_error() adds an error code to the thread's error queue. It signals that the error of reason code reason occurred in function func of library lib, in line number line of file. This function is usually called by a macro.

ERR_add_error_data() associates the concatenation of its num string arguments with the error code added last.

ERR_load_strings() can be used to register error strings so that the application can a generate human-readable error messages for the error code.

Return Values

ERR_put_error() and ERR_add_error_data() return no values.

See Also

err(), ERR_load_strings()

History

ERR_put_error() is available in all versions of SSLeay and OpenSSL. ERR_add_error_data() was added in SSLeay 0.9.0.

Feedback

For additional information or queries on this page send feedback


ERR_remove_state - free a thread's error queue

Name

ERR_remove_state — free a thread's error queue

Library

libcrypto.lib

Synopsis

#include <openssl/err.h>
void ERR_remove_state(unsigned long pid);

Detailed Description

ERR_remove_state() frees the error queue associated with thread pid. If pid == 0, the current thread will have its error queue removed.

Since error queue data structures are allocated automatically for new threads, they must be freed when threads are terminated in order to avoid memory leaks.

Return Value

ERR_remove_state() returns no value.

See Also

err()

History

ERR_remove_state() is available in all versions of SSLeay and OpenSSL.

Feedback

For additional information or queries on this page send feedback


ERR_pop_to_mark - set marks and pop errors until mark

Name

ERR_set_mark, ERR_pop_to_mark — set marks and pop errors until mark

Library

libcrypto.lib

Synopsis

#include <openssl/err.h>
int ERR_set_mark(void);
int ERR_pop_to_mark(void);

Detailed Description

ERR_set_mark() sets a mark on the current topmost error record if there is one.

ERR_pop_to_mark() will pop the top of the error stack until a mark is found. The mark is then removed. If there is no mark, the whole stack is removed.

Return Values

ERR_set_mark() returns 0 if the error stack is empty, otherwise 1.

ERR_pop_to_mark() returns 0 if there was no mark in the error stack, which implies that the stack became empty, otherwise 1.

See Also

err()

History

ERR_set_mark() and ERR_pop_to_mark() were added in OpenSSL 0.9.8.

Feedback

For additional information or queries on this page send feedback


evp - high-level cryptographic functions

Name

evp — provides a high-level interface cryptographic functions

Library

libcrypto.lib

Synopsis

#include <openssl/evp.h>

Detailed Description

The EVP library provides a high-level interface to cryptographic functions.

EVP_Seal... and EVP_Open... provide public key encryption and decryption to implement digital ``envelopes''.

The EVP_Sign... and EVP_Verify... functions implement digital signatures.

Symmetric encryption is available with the EVP_Encrypt... functions. The EVP_Digest... functions provide message digests.

Algorithms are loaded with OpenSSL_add_all_algorithms().

All the symmetric algorithms (ciphers) and digests can be replaced by ENGINE modules providing alternative implementations. If ENGINE implementations of ciphers or digests are registered as defaults, then the various EVP functions will automatically use those implementations automatically in preference to built in software implementations. For more information, consult the engine() man page.

See Aslo

EVP_DigestInit(),
EVP_EncryptInit(),
EVP_OpenInit(),
EVP_SealInit(),
EVP_SignInit(),
EVP_VerifyInit(),
OpenSSL_add_all_algorithms(),
engine()

Feedback

For additional information or queries on this page send feedback


EVP_BytesToKey - password based encryption routine

Name

EVP_BytesToKey — password based encryption routine

Library

libcrypto.lib

Synopsis

#include <openssl/evp.h>
int EVP_BytesToKey(const EVP_CIPHER *type,const EVP_MD *md, const unsigned char *salt, const unsigned char *data, int datal,
                   int count, unsigned char *key,unsigned char *iv);

Detailed Description

EVP_BytesToKey() derives a key and IV from various parameters. type is the cipher to derive the key and IV for. md is the message digest to use. The salt parameter is used as a salt in the derivation: it should point to an 8 byte buffer or NULL if no salt is used. data is a buffer containing datal bytes which is used to derive the keying data. count is the iteration count to use. The derived key and IV will be written to key and iv respectively.

Notes

A typical application of this function is to derive keying material for an encryption algorithm from a password in the data parameter.

Increasing the count parameter slows down the algorithm which makes it harder for an attacker to perform a brute force attack using a large number of candidate passwords.

If the total key and IV length is less than the digest length and MD5 is used then the derivation algorithm is compatible with PKCS#5 v1.5 otherwise a non standard extension is used to derive the extra data.

Newer applications should use more standard algorithms such as PKCS#5 v2.0 for key derivation.

Key Derivation Algorithm

The key and IV is derived by concatenating D_1, D_2, etc until enough data is available for the key and IV. D_i is defined as:

        D_i = HASH^count(D_(i-1) || data || salt)

where || denotes concatenation, D_0 is empty, HASH is the digest algorithm in use, HASH^1(data) is simply HASH(data), HASH^2(data) is HASH(HASH(data)) and so on.

The initial bytes are used for the key and the subsequent bytes for the IV.

Return Values

EVP_BytesToKey() returns the size of the derived key in bytes.

See Also

evp(),
rand(),
EVP_EncryptInit()

History

Feedback

For additional information or queries on this page send feedback


EVP_get_digestbyobj - EVP digest routines

Name

EVP_MD_CTX_init, EVP_MD_CTX_create,
EVP_DigestInit_ex, EVP_DigestUpdate,
EVP_DigestFinal_ex, EVP_MD_CTX_cleanup
EVP_MD_CTX_destroy, EVP_MAX_MD_SIZE,
EVP_MD_CTX_copy_ex, EVP_MD_CTX_copy,
EVP_MD_type, EVP_MD_pkey_type
EVP_MD_size, EVP_MD_block_size,
EVP_MD_CTX_md, EVP_MD_CTX_size,
EVP_MD_CTX_block_size, EVP_MD_CTX_type
EVP_md_null, EVP_md2,
EVP_md5, EVP_sha,
VP_sha1, EVP_dss
EVP_dss1, EVP_get_digestbyname
EVP_get_digestbynid, EVP_get_digestbyobj

EVP digest routines

Library

libcrypto.lib

Synopsis

#include <openssl/evp.h>
void EVP_MD_CTX_init(EVP_MD_CTX *ctx);
EVP_MD_CTX *EVP_MD_CTX_create(void);
int EVP_DigestInit_ex(EVP_MD_CTX *ctx, const EVP_MD *type, ENGINE *impl);
int EVP_DigestUpdate(EVP_MD_CTX *ctx, const void *d, size_t cnt);
int EVP_DigestFinal_ex(EVP_MD_CTX *ctx, unsigned char *md, unsigned int *s);
int EVP_MD_CTX_cleanup(EVP_MD_CTX *ctx);
void EVP_MD_CTX_destroy(EVP_MD_CTX *ctx);
int EVP_MD_CTX_copy_ex(EVP_MD_CTX *out,const EVP_MD_CTX *in);
int EVP_DigestInit(EVP_MD_CTX *ctx, const EVP_MD *type);
int EVP_DigestFinal(EVP_MD_CTX *ctx, unsigned char *md, unsigned int *s);
int EVP_MD_CTX_copy(EVP_MD_CTX *out,EVP_MD_CTX *in);
#define EVP_MAX_MD_SIZE (16+20) /* The SSLv3 md5+sha1 type */
#define EVP_MD_type(e)                 ((e)->type)
#define EVP_MD_pkey_type(e)            ((e)->pkey_type)
#define EVP_MD_size(e)                 ((e)->md_size)
#define EVP_MD_block_size(e)           ((e)->block_size)
#define EVP_MD_CTX_md(e)               (e)->digest)
#define EVP_MD_CTX_size(e)             EVP_MD_size((e)->digest)
#define EVP_MD_CTX_block_size(e)       EVP_MD_block_size((e)->digest)
#define EVP_MD_CTX_type(e)             EVP_MD_type((e)->digest)
const EVP_MD *EVP_md_null(void);
const EVP_MD *EVP_md2(void);
const EVP_MD *EVP_md5(void);
const EVP_MD *EVP_sha(void);
const EVP_MD *EVP_sha1(void);
const EVP_MD *EVP_dss(void);
const EVP_MD *EVP_dss1(void);
const EVP_MD *EVP_get_digestbyname(const char *name);
#define EVP_get_digestbynid(a) EVP_get_digestbyname(OBJ_nid2sn(a))
#define EVP_get_digestbyobj(a) EVP_get_digestbynid(OBJ_obj2nid(a))

Detailed Description

The EVP digest routines are a high level interface to message digests.

EVP_MD_CTX_init() initializes digest contet ctx.

EVP_MD_CTX_create() allocates, initializes and returns a digest contet.

EVP_DigestInit_ex() sets up digest context ctx to use a digest type from ENGINE impl. ctx must be initialized before calling this function. type will typically be supplied by a function such as EVP_sha1(). If impl is NULL then the default implementation of digest type is used.

EVP_DigestUpdate() hashes cnt bytes of data at d into the digest context ctx. This function can be called several times on the same ctx to hash additional data.

EVP_DigestFinal_ex() retrieves the digest value from ctx and places it in md. If the s parameter is not NULL then the number of bytes of data written (i.e. the length of the digest) will be written to the integer at s, at most EVP_MAX_MD_SIZE bytes will be written. After calling EVP_DigestFinal_ex() no additional calls to EVP_DigestUpdate() can be made, but EVP_DigestInit_ex() can be called to initialize a new digest operation.

EVP_MD_CTX_cleanup() cleans up digest context ctx, it should be called after a digest context is no longer needed.

EVP_MD_CTX_destroy() cleans up digest context ctx and frees up the space allocated to it, it should be called only on a context created using EVP_MD_CTX_create().

EVP_MD_CTX_copy_ex() can be used to copy the message digest state from in to out. This is useful if large amounts of data are to be hashed which only differ in the last few bytes. out must be initialized before calling this function.

EVP_DigestInit() behaves in the same way as EVP_DigestInit_ex() except the passed context ctx does not have to be initialized, and it always uses the default digest implementation.

EVP_DigestFinal() is similar to EVP_DigestFinal_ex() except the digest contet ctx is automatically cleaned up.

EVP_MD_CTX_copy() is similar to EVP_MD_CTX_copy_ex() except the destination out does not have to be initialized.

EVP_MD_size() and EVP_MD_CTX_size() return the size of the message digest when passed an EVP_MD or an EVP_MD_CTX structure, i.e. the size of the hash.

EVP_MD_block_size() and EVP_MD_CTX_block_size() return the block size of the message digest when passed an EVP_MD or an EVP_MD_CTX structure.

EVP_MD_type() and EVP_MD_CTX_type() return the NID of the OBJECT IDENTIFIER representing the given message digest when passed an EVP_MD structure. For example EVP_MD_type(EVP_sha1()) returns NID_sha1. This function is normally used when setting ASN1 OIDs.

EVP_MD_CTX_md() returns the EVP_MD structure corresponding to the passed EVP_MD_CTX.

EVP_MD_pkey_type() returns the NID of the public key signing algorithm associated with this digest. For example EVP_sha1() is associated with RSA so this will return NID_sha1WithRSAEncryption. This ``link'' between digests and signature algorithms may not be retained in future versions of OpenSSL.

EVP_md2(), EVP_md5(), EVP_sha(), EVP_sha1(), return EVP_MD structures for the MD2, MD5, SHA, SHA1. The associated signature algorithm is RSA in each case.

EVP_dss() and EVP_dss1() return EVP_MD structures for SHA and SHA1 digest algorithms but using DSS (DSA) for the signature algorithm.

EVP_md_null() is a ``null'' message digest that does nothing: i.e. the hash it returns is of zero length.

EVP_get_digestbyname(), EVP_get_digestbynid() and EVP_get_digestbyobj() return an EVP_MD structure when passed a digest name, a digest NID or an ASN1_OBJECT structure respectively. The digest table must be initialized using, for example, OpenSSL_add_all_digests() for these functions to work.

Examples

This example digests the data ``Test Message\n'' and ``Hello World\n'', using the digest name passed on the command line.
 #include <stdio.h>
 #include <openssl/evp.h>
 main(int argc, char *argv[])
 {
 EVP_MD_CTX mdctx;
 const EVP_MD *md;
 char mess1[] = "Test Message\n";
 char mess2[] = "Hello World\n";
 unsigned char md_value[EVP_MAX_MD_SIZE];
 int md_len, i;
 OpenSSL_add_all_digests();
 if(!argv[1]) {
        printf("Usage: mdtest digestname\n");
        exit();
 }
 md = EVP_get_digestbyname(argv[1]);
 if(!md) {
        printf("Unknown message digest %s\n", argv[1]);
        exit();
 }
 EVP_MD_CTX_init(&mdctx);
 EVP_DigestInit_ex(&mdctx, md, NULL);
 EVP_DigestUpdate(&mdctx, mess1, strlen(mess1));
 EVP_DigestUpdate(&mdctx, mess2, strlen(mess2));
 EVP_DigestFinal_ex(&mdctx, md_value, &md_len);
 EVP_MD_CTX_cleanup(&mdctx);
 printf("Digest is: ");
 for(i = 0; i < md_len; i++) printf("%02x", md_value[i]);
 printf("\n");
 }

Return Values

EVP_DigestInit_ex(),
EVP_DigestUpdate() and
 EVP_DigestFinal_ex() return 1 for
success and 0 for failure.

EVP_MD_CTX_copy_ex() returns 1 if successful or 0 for failure.

EVP_MD_type(), EVP_MD_pkey_type() and EVP_MD_type() return the NID of the corresponding OBJECT IDENTIFIER or NID_undef if none exists.

EVP_MD_size(), EVP_MD_block_size(), EVP_MD_CTX_size(e), EVP_MD_size(), EVP_MD_CTX_block_size() and EVP_MD_block_size() return the digest or block size in bytes.

EVP_md_null(), EVP_md2(), EVP_md5(), EVP_sha(), EVP_sha1(), EVP_dss(), EVP_dss1(), return pointers to the corresponding EVP_MD structures.

EVP_get_digestbyname(),
EVP_get_digestbynid() and
 EVP_get_digestbyobj()
return either an EVP_MD structure or NULL if an error occurs.

Notes

The EVP interface to message digests should almost always be used in preference to the low level interfaces. This is because the code then becomes transparent to the digest used and much more flexible.

SHA1 is the digest of choice for new applications. The other digest algorithms are still in common use.

For most applications the impl parameter to EVP_DigestInit_ex() will be set to NULL to use the default digest implementation.

The functions EVP_DigestInit(), EVP_DigestFinal() and EVP_MD_CTX_copy() are obsolete but are retained to maintain compatibility with existing code. New applications should use EVP_DigestInit_ex(), EVP_DigestFinal_ex() and EVP_MD_CTX_copy_ex() because they can efficiently reuse a digest context instead of initializing and cleaning it up on each call and allow non default implementations of digests to be specified.

In OpenSSL 0.9.7 and later if digest contexts are not cleaned up after use memory leaks will occur.

Bugs

The link between digests and signing algorithms results in a situation where EVP_sha1() must be used with RSA and EVP_dss1() must be used with DSS even though they are identical digests.

See Also

evp(),
hmac(), md2(),
md5(), sha(), dgst()

History

EVP_DigestInit(), EVP_DigestUpdate() and EVP_DigestFinal() are available in all versions of SSLeay and OpenSSL.

EVP_MD_CTX_init(), EVP_MD_CTX_create(), EVP_MD_CTX_copy_ex(), EVP_MD_CTX_cleanup(), EVP_MD_CTX_destroy(), EVP_DigestInit_ex() and EVP_DigestFinal_ex() were added in OpenSSL 0.9.7.

EVP_md_null(), EVP_md2(), EVP_md5(), EVP_sha(), EVP_sha1(), EVP_dss(), EVP_dss1(), were changed to return truly const EVP_MD * in OpenSSL 0.9.7.

Feedback

For additional information or queries on this page send feedback


EVP_CIPHER_CTX_set_padding - EVP cipher routines

Name

EVP_CIPHER_CTX_init, EVP_EncryptInit_ex,
EVP_EncryptUpdate, EVP_EncryptFinal_ex,
EVP_DecryptInit_ex, EVP_DecryptUpdate
EVP_DecryptFinal_ex, EVP_CipherInit_ex,
EVP_CipherUpdate, EVP_CipherFinal_ex,
EVP_CIPHER_CTX_set_key_length, EVP_CIPHER_CTX_ctrl
EVP_CIPHER_CTX_cleanup, EVP_EncryptInit,
EVP_EncryptFinal, EVP_DecryptInit,
EVP_DecryptFinal, EVP_CipherInit, EVP_CipherFinal,
EVP_get_cipherbyname, EVP_get_cipherbynid
EVP_get_cipherbyobj, EVP_CIPHER_nid,
EVP_CIPHER_block_size, EVP_CIPHER_key_length,
EVP_CIPHER_iv_length, EVP_CIPHER_flags
EVP_CIPHER_mode, EVP_CIPHER_type,
EVP_CIPHER_CTX_cipher, EVP_CIPHER_CTX_nid,
EVP_CIPHER_CTX_block_size, EVP_CIPHER_CTX_key_length
EVP_CIPHER_CTX_iv_length, EVP_CIPHER_CTX_get_app_data,
EVP_CIPHER_CTX_set_app_data, EVP_CIPHER_CTX_type,
EVP_CIPHER_CTX_flags, EVP_CIPHER_CTX_mode
EVP_CIPHER_param_to_asn1, EVP_CIPHER_asn1_to_param,
EVP_CIPHER_CTX_set_padding

EVP cipher routines

Library

libcrypto.lib

Synopsis

#include <openssl/evp.h>
void EVP_CIPHER_CTX_init(EVP_CIPHER_CTX *a);
int EVP_EncryptInit_ex(EVP_CIPHER_CTX *ctx, const EVP_CIPHER *type, ENGINE *impl, unsigned char *key, unsigned char *iv);
int EVP_EncryptUpdate(EVP_CIPHER_CTX *ctx, unsigned char *out, int *outl, unsigned char *in, int inl);
int EVP_EncryptFinal_ex(EVP_CIPHER_CTX *ctx, unsigned char *out, int *outl);
int EVP_DecryptInit_ex(EVP_CIPHER_CTX *ctx, const EVP_CIPHER *type, ENGINE *impl, unsigned char *key, unsigned char *iv);
int EVP_DecryptUpdate(EVP_CIPHER_CTX *ctx, unsigned char *out, int *outl, unsigned char *in, int inl);
int EVP_DecryptFinal_ex(EVP_CIPHER_CTX *ctx, unsigned char *outm, int *outl);
int EVP_CipherInit_ex(EVP_CIPHER_CTX *ctx, const EVP_CIPHER *type, ENGINE *impl, unsigned char *key, unsigned char *iv,
                      int enc);
int EVP_CipherUpdate(EVP_CIPHER_CTX *ctx, unsigned char *out, int *outl, unsigned char *in, int inl);
int EVP_CipherFinal_ex(EVP_CIPHER_CTX *ctx, unsigned char *outm, int *outl);
int EVP_EncryptInit(EVP_CIPHER_CTX *ctx, const EVP_CIPHER *type, unsigned char *key, unsigned char *iv);
int EVP_EncryptFinal(EVP_CIPHER_CTX *ctx, unsigned char *out, int *outl);
int EVP_DecryptInit(EVP_CIPHER_CTX *ctx, const EVP_CIPHER *type, unsigned char *key, unsigned char *iv);
int EVP_DecryptFinal(EVP_CIPHER_CTX *ctx, unsigned char *outm, int *outl);
int EVP_CipherInit(EVP_CIPHER_CTX *ctx, const EVP_CIPHER *type, unsigned char *key, unsigned char *iv, int enc);
int EVP_CipherFinal(EVP_CIPHER_CTX *ctx, unsigned char *outm, int *outl);
int EVP_CIPHER_CTX_set_padding(EVP_CIPHER_CTX *x, int padding);
int EVP_CIPHER_CTX_set_key_length(EVP_CIPHER_CTX *x, int keylen);
int EVP_CIPHER_CTX_ctrl(EVP_CIPHER_CTX *ctx, int type, int arg, void *ptr);
int EVP_CIPHER_CTX_cleanup(EVP_CIPHER_CTX *a);
const EVP_CIPHER *EVP_get_cipherbyname(const char *name);
#define EVP_get_cipherbynid(a) EVP_get_cipherbyname(OBJ_nid2sn(a))
#define EVP_get_cipherbyobj(a) EVP_get_cipherbynid(OBJ_obj2nid(a))
#define EVP_CIPHER_nid(e)              ((e)->nid)
#define EVP_CIPHER_block_size(e)       ((e)->block_size)
#define EVP_CIPHER_key_length(e)       ((e)->key_len)
#define EVP_CIPHER_iv_length(e)                ((e)->iv_len)
#define EVP_CIPHER_flags(e)            ((e)->flags)
#define EVP_CIPHER_mode(e)             ((e)->flags) & EVP_CIPH_MODE)
int EVP_CIPHER_type(const EVP_CIPHER *ctx);
#define EVP_CIPHER_CTX_cipher(e)       ((e)->cipher)
#define EVP_CIPHER_CTX_nid(e)          ((e)->cipher->nid)
#define EVP_CIPHER_CTX_block_size(e)   ((e)->cipher->block_size)
#define EVP_CIPHER_CTX_key_length(e)   ((e)->key_len)
#define EVP_CIPHER_CTX_iv_length(e)    ((e)->cipher->iv_len)
#define EVP_CIPHER_CTX_get_app_data(e) ((e)->app_data)
#define EVP_CIPHER_CTX_set_app_data(e,d) ((e)->app_data=(char *)(d))
#define EVP_CIPHER_CTX_type(c)         EVP_CIPHER_type(EVP_CIPHER_CTX_cipher(c))
#define EVP_CIPHER_CTX_flags(e)        ((e)->cipher->flags)
#define EVP_CIPHER_CTX_mode(e)         ((e)->cipher->flags & EVP_CIPH_MODE)
int EVP_CIPHER_param_to_asn1(EVP_CIPHER_CTX *c, ASN1_TYPE *type);
int EVP_CIPHER_asn1_to_param(EVP_CIPHER_CTX *c, ASN1_TYPE *type);

Detailed Description

The EVP cipher routines are a high level interface to certain symmetric ciphers.

EVP_CIPHER_CTX_init() initializes cipher contex ctx.

EVP_EncryptInit_ex() sets up cipher context ctx for encryption with cipher type from ENGINE impl. ctx must be initialized before calling this function. type is normally supplied by a function such as EVP_des_cbc(). If impl is NULL then the default implementation is used. key is the symmetric key to use and iv is the IV to use (if necessary), the actual number of bytes used for the key and IV depends on the cipher. It is possible to set all parameters to NULL except type in an initial call and supply the remaining parameters in subsequent calls, all of which have type set to NULL. This is done when the default cipher parameters are not appropriate.

EVP_EncryptUpdate() encrypts inl bytes from the buffer in and writes the encrypted version to out. This function can be called multiple times to encrypt successive blocks of data. The amount of data written depends on the block alignment of the encrypted data: as a result the amount of data written may be anything from zero bytes to (inl + cipher_block_size - 1) so outl should contain sufficient room. The actual number of bytes written is placed in outl.

If padding is enabled (the default) then EVP_EncryptFinal_ex() encrypts the ''final'' data, that is any data that remains in a partial block. It uses standard block padding (aka PKCS padding). The encrypted final data is written to out which should have sufficient space for one cipher block. The number of bytes written is placed in outl. After this function is called the encryption operation is finished and no further calls to EVP_EncryptUpdate() should be made.

If padding is disabled then EVP_EncryptFinal_ex() will not encrypt any more data and it will return an error if any data remains in a partial block: that is if the total data length is not a multiple of the block size.

EVP_DecryptInit_ex(), EVP_DecryptUpdate() and EVP_DecryptFinal_ex() are the corresponding decryption operations. EVP_DecryptFinal() will return an error code if padding is enabled and the final block is not correctly formatted. The parameters and restrictions are identical to the encryption operations except that if padding is enabled the decrypted data buffer out passed to EVP_DecryptUpdate() should have sufficient room for (inl + cipher_block_size) bytes unless the cipher block size is 1 in which case inl bytes is sufficient.

EVP_CipherInit_ex(), EVP_CipherUpdate() and EVP_CipherFinal_ex() are functions that can be used for decryption or encryption. The operation performed depends on the value of the enc parameter. It should be set to 1 for encryption, 0 for decryption and -1 to leave the value unchanged (the actual value of 'enc' being supplied in a previous call).

EVP_CIPHER_CTX_cleanup() clears all information from a cipher context and free up any allocated memory associate with it. It should be called after all operations using a cipher are complete so sensitive information does not remain in memory.

EVP_EncryptInit(), EVP_DecryptInit() and
 EVP_CipherInit() behave in a
similar way to EVP_EncryptInit_ex(), EVP_DecryptInit_ex and
EVP_CipherInit_ex() except the ctx paramter does not need to be
initialized and they always use the default cipher implementation.

EVP_EncryptFinal(), EVP_DecryptFinal() and
 EVP_CipherFinal() behave in a
similar way to EVP_EncryptFinal_ex(),  EVP_DecryptFinal_ex() and
EVP_CipherFinal_ex() except
 ctx is automatically cleaned up
after the call.

EVP_get_cipherbyname(), EVP_get_cipherbynid() and EVP_get_cipherbyobj() return an EVP_CIPHER structure when passed a cipher name, a NID or an ASN1_OBJECT structure.

EVP_CIPHER_nid() and EVP_CIPHER_CTX_nid() return the NID of a cipher when passed an EVP_CIPHER or EVP_CIPHER_CTX structure. The actual NID value is an internal value which may not have a corresponding OBJECT IDENTIFIER.

EVP_CIPHER_CTX_set_padding() enables or disables padding. By default encryption operations are padded using standard block padding and the padding is checked and removed when decrypting. If the pad parameter is zero then no padding is performed, the total amount of data encrypted or decrypted must then be a multiple of the block size or an error will occur.

EVP_CIPHER_key_length() and EVP_CIPHER_CTX_key_length() return the key length of a cipher when passed an EVP_CIPHER or EVP_CIPHER_CTX structure. The constant EVP_MAX_KEY_LENGTH is the maximum key length for all ciphers. Note: although EVP_CIPHER_key_length() is fixed for a given cipher, the value of EVP_CIPHER_CTX_key_length() may be different for variable key length ciphers.

EVP_CIPHER_CTX_set_key_length() sets the key length of the cipher ctx. If the cipher is a fixed length cipher then attempting to set the key length to any value other than the fixed value is an error.

EVP_CIPHER_iv_length() and EVP_CIPHER_CTX_iv_length() return the IV length of a cipher when passed an EVP_CIPHER or EVP_CIPHER_CTX. It will return zero if the cipher does not use an IV. The constant EVP_MAX_IV_LENGTH is the maximum IV length for all ciphers.

EVP_CIPHER_block_size() and EVP_CIPHER_CTX_block_size() return the block size of a cipher when passed an EVP_CIPHER or EVP_CIPHER_CTX structure. The constant EVP_MAX_IV_LENGTH is also the maximum block length for all ciphers.

EVP_CIPHER_type() and EVP_CIPHER_CTX_type() return the type of the passed cipher or context. This ``type'' is the actual NID of the cipher OBJECT IDENTIFIER as such it ignores the cipher parameters and 40 bit RC2 and 128 bit RC2 have the same NID. If the cipher does not have an object identifier or does not have ASN1 support this function will return NID_undef.

EVP_CIPHER_CTX_cipher() returns the EVP_CIPHER structure when passed an EVP_CIPHER_CTX structure.

EVP_CIPHER_mode() and EVP_CIPHER_CTX_mode() return the block cipher mode: EVP_CIPH_ECB_MODE, EVP_CIPH_CBC_MODE, EVP_CIPH_CFB_MODE or EVP_CIPH_OFB_MODE. If the cipher is a stream cipher then EVP_CIPH_STREAM_CIPHER is returned.

EVP_CIPHER_param_to_asn1() sets the AlgorithmIdentifier ``parameter'' based on the passed cipher. This will typically include any parameters and an IV. The cipher IV (if any) must be set when this call is made. This call should be made before the cipher is actually ``used'' (before any EVP_EncryptUpdate(), EVP_DecryptUpdate() calls for example). This function may fail if the cipher does not have any ASN1 support.

EVP_CIPHER_asn1_to_param() sets the cipher parameters based on an ASN1 AlgorithmIdentifier ``parameter''. The precise effect depends on the cipher In the case of RC2, for example, it will set the IV and effective key length. This function should be called after the base cipher type is set but before the key is set. For example EVP_CipherInit() will be called with the IV and key set to NULL, EVP_CIPHER_asn1_to_param() will be called and finally EVP_CipherInit() again with all parameters except the key set to NULL. It is possible for this function to fail if the cipher does not have any ASN1 support or the parameters cannot be set (for example the RC2 effective key length is not supported.

EVP_CIPHER_CTX_ctrl() allows various cipher specific parameters to be determined and set. Currently only the RC2 effective key length and the number of rounds of RC5 can be set.

Examples

Get the number of rounds used in RC5:
 int nrounds;
 EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GET_RC5_ROUNDS, 0, &nrounds);

Get the RC2 effective key length:

 int key_bits;
 EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GET_RC2_KEY_BITS, 0, &key_bits);

Set the number of rounds used in RC5:

 int nrounds;
 EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_SET_RC5_ROUNDS, nrounds, NULL);

Set the effective key length used in RC2:

 int key_bits;
 EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_SET_RC2_KEY_BITS, key_bits, NULL);

Return Values

EVP_EncryptInit_ex(),
EVP_EncryptUpdate() and
 EVP_EncryptFinal_ex()
return 1 for success and 0 for failure.

EVP_DecryptInit_ex() and EVP_DecryptUpdate() return 1 for success and 0 for failure. EVP_DecryptFinal_ex() returns 0 if the decrypt failed or 1 for success.

EVP_CipherInit_ex() and EVP_CipherUpdate() return 1 for success and 0 for failure. EVP_CipherFinal_ex() returns 0 for a decryption failure or 1 for success.

EVP_CIPHER_CTX_cleanup() returns 1 for success and 0 for failure.

EVP_get_cipherbyname(),
EVP_get_cipherbynid() and
 EVP_get_cipherbyobj()
return an EVP_CIPHER structure or NULL on error.

EVP_CIPHER_nid() and EVP_CIPHER_CTX_nid() return a NID.

EVP_CIPHER_block_size() and EVP_CIPHER_CTX_block_size() return the block size.

EVP_CIPHER_key_length() and EVP_CIPHER_CTX_key_length() return the key length.

EVP_CIPHER_CTX_set_padding() always returns 1.

EVP_CIPHER_iv_length() and EVP_CIPHER_CTX_iv_length() return the IV length or zero if the cipher does not use an IV.

EVP_CIPHER_type() and EVP_CIPHER_CTX_type() return the NID of the cipher's OBJECT IDENTIFIER or NID_undef if it has no defined OBJECT IDENTIFIER.

EVP_CIPHER_CTX_cipher() returns an EVP_CIPHER structure.

EVP_CIPHER_param_to_asn1() and EVP_CIPHER_asn1_to_param() return 1 for success or zero for failure.

Cipher Listing

All algorithms have a fixed key length unless otherwise stated.

EVP_enc_null()
Null cipher: does nothing.

EVP_des_cbc(void), EVP_des_ecb(void), EVP_des_cfb(void), EVP_des_ofb(void)
DES in CBC, ECB, CFB and OFB modes respectively.

EVP_des_ede_cbc(void), EVP_des_ede(), EVP_des_ede_ofb(void), EVP_des_ede_cfb(void)
Two key triple DES in CBC, ECB, CFB and OFB modes respectively.

EVP_des_ede3_cbc(void), EVP_des_ede3(), EVP_des_ede3_ofb(void), EVP_des_ede3_cfb(void)
Three key triple DES in CBC, ECB, CFB and OFB modes respectively.

EVP_desx_cbc(void)
DESX algorithm in CBC mode.

EVP_rc4(void)
RC4 stream cipher. This is a variable key length cipher with default key length 128 bits.

EVP_rc4_40(void)
RC4 stream cipher with 40 bit key length. This is obsolete and new code should use EVP_rc4() and the EVP_CIPHER_CTX_set_key_length() function.

EVP_idea_cbc() EVP_idea_ecb(void), EVP_idea_cfb(void), EVP_idea_ofb(void), EVP_idea_cbc(void)
IDEA encryption algorithm in CBC, ECB, CFB and OFB modes respectively.

EVP_rc2_cbc(void), EVP_rc2_ecb(void), EVP_rc2_cfb(void), EVP_rc2_ofb(void)
RC2 encryption algorithm in CBC, ECB, CFB and OFB modes respectively. This is a variable key length cipher with an additional parameter called ``effective key bits'' or ``effective key length''. By default both are set to 128 bits.

EVP_rc2_40_cbc(void), EVP_rc2_64_cbc(void)
RC2 algorithm in CBC mode with a default key length and effective key length of 40 and 64 bits. These are obsolete and new code should use EVP_rc2_cbc(), EVP_CIPHER_CTX_set_key_length() and EVP_CIPHER_CTX_ctrl() to set the key length and effective key length.

EVP_rc5_32_12_16_cbc(void), EVP_rc5_32_12_16_ecb(void), EVP_rc5_32_12_16_cfb(void), EVP_rc5_32_12_16_ofb(void)
RC5 encryption algorithm in CBC, ECB, CFB and OFB modes respectively. This is a variable key length cipher with an additional ``number of rounds'' parameter. By default the key length is set to 128 bits and 12 rounds.

Notes

Where possible the EVP interface to symmetric ciphers should be used in preference to the low level interfaces. This is because the code then becomes transparent to the cipher used and much more flexible.

PKCS padding works by adding n padding bytes of value n to make the total length of the encrypted data a multiple of the block size. Padding is always added so if the data is already a multiple of the block size n will equal the block size. For example if the block size is 8 and 11 bytes are to be encrypted then 5 padding bytes of value 5 will be added.

When decrypting the final block is checked to see if it has the correct form.

Although the decryption operation can produce an error if padding is enabled, it is not a strong test that the input data or key is correct. A random block has better than 1 in 256 chance of being of the correct format and problems with the input data earlier on will not produce a final decrypt error.

If padding is disabled then the decryption operation will always succeed if the total amount of data decrypted is a multiple of the block size.

The functions EVP_EncryptInit(), EVP_EncryptFinal(), EVP_DecryptInit(), EVP_CipherInit() and EVP_CipherFinal() are obsolete but are retained for compatibility with existing code. New code should use EVP_EncryptInit_ex(), EVP_EncryptFinal_ex(), EVP_DecryptInit_ex(), EVP_DecryptFinal_ex(), EVP_CipherInit_ex() and EVP_CipherFinal_ex() because they can reuse an existing context without allocating and freeing it up on each call.

Bugs

For RC5 the number of rounds can currently only be set to 8, 12 or 16. This is a limitation of the current RC5 code rather than the EVP interface.

EVP_MAX_KEY_LENGTH and EVP_MAX_IV_LENGTH only refer to the internal ciphers with default key lengths. If custom ciphers exceed these values the results are unpredictable. This is because it has become standard practice to define a generic key as a fixed unsigned char array containing EVP_MAX_KEY_LENGTH bytes.

The ASN1 code is incomplete (and sometimes inaccurate) it has only been tested for certain common S/MIME ciphers (RC2, DES, triple DES) in CBC mode.

See Also

evp()

History

EVP_CIPHER_CTX_init(), EVP_EncryptInit_ex(), EVP_EncryptFinal_ex(),
EVP_DecryptInit_ex(), EVP_DecryptFinal_ex(), EVP_CipherInit_ex(),
EVP_CipherFinal_ex()
and EVP_CIPHER_CTX_set_padding() appeared in
OpenSSL 0.9.7.

Feedback

For additional information or queries on this page send feedback


EVP_OpenFinal - EVP envelope decryption

Name

EVP_OpenInit, EVP_OpenUpdate
EVP_OpenFinal

EVP envelope decryption

Library

libcrypto.lib

Synopsis

#include <openssl/evp.h>
int EVP_OpenInit(EVP_CIPHER_CTX *ctx,EVP_CIPHER *type,unsigned char *ek, int ekl,unsigned char *iv,EVP_PKEY *priv);
int EVP_OpenUpdate(EVP_CIPHER_CTX *ctx, unsigned char *out, int *outl, unsigned char *in, int inl);
int EVP_OpenFinal(EVP_CIPHER_CTX *ctx, unsigned char *out, int *outl);

Detailed Description

The EVP envelope routines are a high level interface to envelope decryption. They decrypt a public key encrypted symmetric key and then decrypt data using it.

EVP_OpenInit() initializes a cipher context ctx for decryption with cipher type. It decrypts the encrypted symmetric key of length ekl bytes passed in the ek parameter using the private key priv. The IV is supplied in the iv parameter.

EVP_OpenUpdate() and
 EVP_OpenFinal() have exactly the same properties
as the  EVP_DecryptUpdate() and
 EVP_DecryptFinal() routines, as
documented on the EVP_EncryptInit() manual
page.

Notes

It is possible to call EVP_OpenInit() twice in the same way as EVP_DecryptInit(). The first call should have priv set to NULL and (after setting any cipher parameters) it should be called again with type set to NULL.

If the cipher passed in the type parameter is a variable length cipher then the key length will be set to the value of the recovered key length. If the cipher is a fixed length cipher then the recovered key length must match the fixed cipher length.

Return Values

EVP_OpenInit() returns 0 on error or a non zero integer (actually the recovered secret key size) if successful.

EVP_OpenUpdate() returns 1 for success or 0 for failure.

EVP_OpenFinal() returns 0 if the decrypt failed or 1 for success.

See Also

evp(),
rand(),
EVP_EncryptInit(),
EVP_SealInit()

History

Feedback

For additional information or queries on this page send feedback


EVP_PKEY_free - private key allocation functions.

Name

EVP_PKEY_new, EVP_PKEY_free — private key allocation functions

Library

libcrypto.lib

Synopsis

#include <openssl/evp.h>
EVP_PKEY *EVP_PKEY_new(void);
void EVP_PKEY_free(EVP_PKEY *key);

Detailed Description

The EVP_PKEY_new() function allocates an empty EVP_PKEY structure which is used by OpenSSL to store private keys.

EVP_PKEY_free() frees up the private key key.

Notes

The EVP_PKEY structure is used by various OpenSSL functions which require a general private key without reference to any particular algorithm.

The structure returned by EVP_PKEY_new() is empty. To add a private key to this empty structure the functions described in EVP_PKEY_set1_RSA() should be used.

Return Values

EVP_PKEY_new() returns either the newly allocated EVP_PKEY structure of NULL if an error occurred.

EVP_PKEY_free() does not return a value.

See Also

EVP_PKEY_set1_RSA()

History

TBA

Feedback

For additional information or queries on this page send feedback


EVP_PKEY_type - EVP_PKEY assignment functions.

Name

EVP_PKEY_set1_RSA, EVP_PKEY_set1_DSA
EVP_PKEY_set1_DH, EVP_PKEY_set1_EC_KEY
EVP_PKEY_get1_RSA, EVP_PKEY_get1_DSA
EVP_PKEY_get1_DH, EVP_PKEY_get1_EC_KEY
EVP_PKEY_assign_RSA, EVP_PKEY_assign_DSA
EVP_PKEY_assign_DH, EVP_PKEY_assign_EC_KEY
EVP_PKEY_type

EVP_PKEY assignment functions

Library

libcrypto.lib

Synopsis

#include <openssl/evp.h>
int EVP_PKEY_set1_RSA(EVP_PKEY *pkey,RSA *key);
int EVP_PKEY_set1_DSA(EVP_PKEY *pkey,DSA *key);
int EVP_PKEY_set1_DH(EVP_PKEY *pkey,DH *key);
int EVP_PKEY_set1_EC_KEY(EVP_PKEY *pkey,EC_KEY *key);
RSA *EVP_PKEY_get1_RSA(EVP_PKEY *pkey);
DSA *EVP_PKEY_get1_DSA(EVP_PKEY *pkey);
DH *EVP_PKEY_get1_DH(EVP_PKEY *pkey);
EC_KEY *EVP_PKEY_get1_EC_KEY(EVP_PKEY *pkey);
int EVP_PKEY_assign_RSA(EVP_PKEY *pkey,RSA *key);
int EVP_PKEY_assign_DSA(EVP_PKEY *pkey,DSA *key);
int EVP_PKEY_assign_DH(EVP_PKEY *pkey,DH *key);
int EVP_PKEY_assign_EC_KEY(EVP_PKEY *pkey,EC_KEY *key);
int EVP_PKEY_type(int type);

Detailed Description

EVP_PKEY_set1_RSA(), EVP_PKEY_set1_DSA(), EVP_PKEY_set1_DH() and EVP_PKEY_set1_EC_KEY() set the key referenced by pkey to key.

EVP_PKEY_get1_RSA(), EVP_PKEY_get1_DSA(),
EVP_PKEY_get1_DH() and

EVP_PKEY_get1_EC_KEY()
return the referenced key in pkey or
NULL if the key is not of the correct type.

EVP_PKEY_assign_RSA() EVP_PKEY_assign_DSA(), EVP_PKEY_assign_DH() and EVP_PKEY_assign_EC_KEY() also set the referenced key to key however these use the supplied key internally and so key will be freed when the parent pkey is freed.

EVP_PKEY_type() returns the type of key corresponding to the value type. The type of a key can be obtained with EVP_PKEY_type(pkey->type). The return value will be EVP_PKEY_RSA, EVP_PKEY_DSA, EVP_PKEY_DH or EVP_PKEY_EC for the corresponding key types or NID_undef if the key type is unassigned.

Notes

In accordance with the OpenSSL naming convention the key obtained from or assigned to the pkey using the 1 functions must be freed as well as pkey.

EVP_PKEY_assign_RSA(), EVP_PKEY_assign_DSA(),
 EVP_PKEY_assign_DH(),

EVP_PKEY_assign_EC_KEY() are implemented as macros.

Return Values

EVP_PKEY_set1_RSA(), EVP_PKEY_set1_DSA(), EVP_PKEY_set1_DH() and EVP_PKEY_set1_EC_KEY() return 1 for success or 0 for failure.

EVP_PKEY_get1_RSA(), EVP_PKEY_get1_DSA(), EVP_PKEY_get1_DH()s EVP_PKEY_get1_EC_KEY() return the referenced key or NULL if an error occurred.

EVP_PKEY_assign_RSA(), EVP_PKEY_assign_DSA(),
 EVP_PKEY_assign_DH()
and  EVP_PKEY_assign_EC_KEY()
return 1 for success and 0 for failure.

See Also

EVP_PKEY_new()

History

TBA

Feedback

For additional information or queries on this page send feedback


EVP_SealFinal - EVP envelope encryption

Name

EVP_SealInit, EVP_SealUpdate
EVP_SealFinal

EVP envelope encryption

Library

libcrypto.lib

Synopsis

#include <openssl/evp.h>
int EVP_SealInit(EVP_CIPHER_CTX *ctx, const EVP_CIPHER *type, unsigned char **ek, int *ekl, unsigned char *iv,
                 EVP_PKEY **pubk, int npubk);
int EVP_SealUpdate(EVP_CIPHER_CTX *ctx, unsigned char *out, int *outl, unsigned char *in, int inl);
int EVP_SealFinal(EVP_CIPHER_CTX *ctx, unsigned char *out, int *outl);

Detailed Description

The EVP envelope routines are a high level interface to envelope encryption. They generate a random key and IV (if required) then "envelope'' it by using public key encryption. Data can then be encrypted using this key.

EVP_SealInit() initializes a cipher context ctx for encryption with cipher type using a random secret key and IV. type is normally supplied by a function such as EVP_des_cbc(). The secret key is encrypted using one or more public keys, this allows the same encrypted data to be decrypted using any of the corresponding private keys. ek is an array of buffers where the public key encrypted secret key will be written, each buffer must contain enough room for the corresponding encrypted key: that is ek[i] must have room for EVP_PKEY_size(pubk[i]) bytes. The actual size of each encrypted secret key is written to the array ekl. pubk is an array of npubk public keys.

The iv parameter is a buffer where the generated IV is written to. It must contain enough room for the corresponding cipher's IV, as determined by (for example) EVP_CIPHER_iv_length(type).

If the cipher does not require an IV then the iv parameter is ignored and can be NULL.

EVP_SealUpdate() and
 EVP_SealFinal()
have exactly the same properties
as the  EVP_EncryptUpdate() and
 EVP_EncryptFinal() routines, as
documented on the EVP_EncryptInit() manual
page.

Return Values

EVP_SealInit() returns 0 on error or npubk if successful.

EVP_SealUpdate() and EVP_SealFinal() return 1 for success and 0 for failure.

Notes

Because a random secret key is generated the random number generator must be seeded before calling EVP_SealInit().

The public key must be RSA because it is the only OpenSSL public key algorithm that supports key transport.

Envelope encryption is the usual method of using public key encryption on large amounts of data, this is because public key encryption is slow but symmetric encryption is fast. So symmetric encryption is used for bulk encryption and the small random symmetric key used is transferred using public key encryption.

It is possible to call EVP_SealInit() twice in the same way as EVP_EncryptInit(). The first call should have npubk set to 0 and (after setting any cipher parameters) it should be called again with type set to NULL.

See Also

evp(),
rand(),
EVP_EncryptInit(),
EVP_OpenInit()

History

EVP_SealFinal() did not return a value before OpenSSL 0.9.7.

Feedback

For additional information or queries on this page send feedback


EVP_SignFinal - EVP signing functions

Name

EVP_SignInit, EVP_SignUpdate
EVP_SignFinal

EVP signing functions

Library

libcrypto.lib

Synopsis

#include <openssl/evp.h>
int EVP_SignInit_ex(EVP_MD_CTX *ctx, const EVP_MD *type, ENGINE *impl);
int EVP_SignUpdate(EVP_MD_CTX *ctx, const void *d, unsigned int cnt);
int EVP_SignFinal(EVP_MD_CTX *ctx,unsigned char *sig,unsigned int *s, EVP_PKEY *pkey);
void EVP_SignInit(EVP_MD_CTX *ctx, const EVP_MD *type);
int EVP_PKEY_size(EVP_PKEY *pkey);

Detailed Description

The EVP signature routines are a high level interface to digital signatures.

EVP_SignInit_ex() sets up signing context ctx to use digest type from ENGINE impl. ctx must be initialized with EVP_MD_CTX_init() before calling this function.

EVP_SignUpdate() hashes cnt bytes of data at d into the signature context ctx. This function can be called several times on the same ctx to include additional data.

EVP_SignFinal() signs the data in ctx using the private key pkey and places the signature in sig. The number of bytes of data written (i.e. the length of the signature) will be written to the integer at s, at most EVP_PKEY_size(pkey) bytes will be written.

EVP_SignInit() initializes a signing context ctx to use the default implementation of digest type.

EVP_PKEY_size() returns the maximum size of a signature in bytes. The actual signature returned by EVP_SignFinal() may be smaller.

Return Values

EVP_SignInit_ex(), EVP_SignUpdate() and EVP_SignFinal() return 1 for success and 0 for failure.

EVP_PKEY_size() returns the maximum size of a signature in bytes.

The error codes can be obtained by ERR_get_error().

Notes

The EVP interface to digital signatures should almost always be used in preference to the low level interfaces. This is because the code then becomes transparent to the algorithm used and much more flexible.

Due to the link between message digests and public key algorithms the correct digest algorithm must be used with the correct public key type. A list of algorithms and associated public key algorithms appears in EVP_DigestInit().

When signing with DSA private keys the random number generator must be seeded or the operation will fail. The random number generator does not need to be seeded for RSA signatures.

The call to EVP_SignFinal() internally finalizes a copy of the digest context. This means that calls to EVP_SignUpdate() and EVP_SignFinal() can be called later to digest and sign additional data.

Since only a copy of the digest context is ever finalized the context must be cleaned up after use by calling EVP_MD_CTX_cleanup() or a memory leak will occur.

Bugs

Older versions of this documentation wrongly stated that calls to EVP_SignUpdate() could not be made after calling EVP_SignFinal().

See Also

EVP_VerifyInit(),
EVP_DigestInit(),
err(),
evp(), hmac(),
md2(),
md5(), sha(), dgst()

History

EVP_SignInit(), EVP_SignUpdate() and EVP_SignFinal() are available in all versions of SSLeay and OpenSSL.

EVP_SignInit_ex() was added in OpenSSL 0.9.7.


EVP_VerifyFinal - EVP signature verification functions

Name

EVP_VerifyInit, EVP_VerifyUpdate
EVP_VerifyFinal

EVP signature verification functions

Library

libcrypto.lib

Synopsis

#include <openssl/evp.h>
int EVP_VerifyInit_ex(EVP_MD_CTX *ctx, const EVP_MD *type, ENGINE *impl);
int EVP_VerifyUpdate(EVP_MD_CTX *ctx, const void *d, unsigned int cnt);
int EVP_VerifyFinal(EVP_MD_CTX *ctx,unsigned char *sigbuf, unsigned int siglen,EVP_PKEY *pkey);
int EVP_VerifyInit(EVP_MD_CTX *ctx, const EVP_MD *type);

Detailed Description

The EVP signature verification routines are a high level interface to digital signatures.

EVP_VerifyInit_ex() sets up verification context ctx to use digest type from ENGINE impl. ctx must be initialized by calling EVP_MD_CTX_init() before calling this function.

EVP_VerifyUpdate() hashes cnt bytes of data at d into the verification context ctx. This function can be called several times on the same ctx to include additional data.

EVP_VerifyFinal() verifies the data in ctx using the public key pkey and against the siglen bytes at sigbuf.

EVP_VerifyInit() initializes verification context ctx to use the default implementation of digest type.

Return Values

EVP_VerifyInit_ex() and EVP_VerifyUpdate() return 1 for success and 0 for failure.

EVP_VerifyFinal() returns 1 for a correct signature, 0 for failure and -1 if some other error occurred.

The error codes can be obtained by ERR_get_error().

Notes

The EVP interface to digital signatures should almost always be used in preference to the low level interfaces. This is because the code then becomes transparent to the algorithm used and much more flexible.

Due to the link between message digests and public key algorithms the correct digest algorithm must be used with the correct public key type. A list of algorithms and associated public key algorithms appears in EVP_DigestInit().

The call to EVP_VerifyFinal() internally finalizes a copy of the digest context. This means that calls to EVP_VerifyUpdate() and EVP_VerifyFinal() can be called later to digest and verify additional data.

Since only a copy of the digest context is ever finalized the context must be cleaned up after use by calling EVP_MD_CTX_cleanup() or a memory leak will occur.

Bugs

Older versions of this documentation wrongly stated that calls to EVP_VerifyUpdate() could not be made after calling EVP_VerifyFinal().

See Also

evp(),
EVP_SignInit(),
EVP_DigestInit(),
err(),
hmac(), md2(),
md5(), sha(), dgst()

History

EVP_VerifyInit(), EVP_VerifyUpdate() and EVP_VerifyFinal() are available in all versions of SSLeay and OpenSSL.

EVP_VerifyInit_ex() was added in OpenSSL 0.9.7

Feedback

For additional information or queries on this page send feedback


exit

Name

exit, _Exit
- cause normal program termination

Library

 libc.lib

Synopsis
#include <stdlib.h>
void exit (int status);
void _Exit (int status);

Return values

 The exit and _Exit functions never return.

Detailed description

 The exit and _Exit functions terminate a process.

Before termination, exit performs the following functions in the order listed:

  1. Call the functions registered with the atexit function, in the reverse order of their registration.
  2. Flush all open output streams.
  3. Close all open streams.
  4. Unlink all files created with the tmpfile function.

The _Exit function terminates without calling the functions registered with the atexit function, and may or may not perform the other actions listed. Both functions make the low-order eight bits of the status argument available to a parent process which has called a wait function.

The C Standard (-isoC-99) defines the values 0, EXIT_SUCCESS, and EXIT_FAILURE as possible values of status. Cooperating processes may use other values.

Note that exit does nothing to prevent bottomless recursion should a function registered using atexit itself call exit. Such functions must call _Exit instead (although this has other effects as well which may not be desired).

Examples

/**
  * Detailed description : Sample usage of exit system call.
**/
#include <stdlib.h>

void main()
{
  exit(0) ; //Here 0 is exit status of the process
}

See also

 _exit, wait, atexit, tmpfile

Feedback

For additional information or queries on this page send feedback


exp

Name

exp, expf, expl,exp2, exp2f, exp2l, expm1, expm1f, expm1f, expm1l
log, logf, logl, log10, log10f, log10l, log1p, log1pf, log1pl

pow, powf, powl,

- exponential, logarithm, power functions

Library

 libm.lib

Synopsis
#include <math.h>
double exp (double x);
float expf (float x);
long double expl (long double x);
double exp2 (double x);
float exp2f (float x);
long double exp2l (long double x);
double expm1 (double x);
float expm1f (float x);
long double expm1l (long double x);
double log (double x);
float logf (float x);
long double logl (long double x);
double log10 (double x);
float log10f (float x);
long double log10l (long double x);
double log1p (double x);
float log1pf (float x);
long double log1pl (long double x);
double pow (double x, double y);
float powf (float x, float y);
long double powl (long double x, long double y);

Return values

 These functions will return the appropriate computation unless an error occurs or an argument is out of range. The functions pow (x, y);
and powf (x, y);
return an NaN if x < 0 and y is not an integer. An attempt to take the logarithm of ±0 will return infinity. An attempt to take the logarithm of a negative number will return a NaN.

Detailed description

 The exp and expf functions compute the base e exponential value of the given argument x.

The exp2 and exp2f functions compute the base 2 exponential of the given argument x.

The expm1 and expm1f functions compute the value exp(x)-1 accurately even for tiny argument x.

The log and logf functions compute the value of the natural logarithm of argument x.

The log10 and log10f functions compute the value of the logarithm of argument x to base 10.

The log1p and log1pf functions compute the value of log(1+x) accurately even for tiny argument x.

The pow and powf functions compute the value of x to the exponent y.

Here the long double version APIs are aliases to the double version APIs. All apis <function>l behaves similiar to that <function>.

Examples

#include <math.h>
int main( void )
{
   double x, y;
   x = 1.0;
   y = exp( x );
   printf( "exp( %f ) = %f\n", x, y );
   y = expf( x );
   printf( "expf( %f ) = %f\n",x, y );
   y = expl( x );
   printf( "expl( %f ) = %f\n",x, y );
   x = 0.0;
   y = exp2( x );
   printf( "exp2( %f ) = %f\n", x, y );
   y = exp2f( x );
   printf( "exp2f( %f ) = %f\n",x, y );
   y = exp2l( x );
   printf( "exp2l( %f ) = %f\n",x, y );
   x = 1.0 ;
   y = expm1( x );
   printf( "expm1( %f ) = %f\n", x, y );
   y = expm1f( x );
   printf( "expm1f( %f ) = %f\n",x, y );
   y = expm1l( x );
   printf( "expm1l( %f ) = %f\n",x, y );
}

Output

exp   ( 1.0 ) = 2.718282
expf  ( 1.0 ) = 2.718282
expl  ( 1.0 ) = 2.718282
exp2  ( 0.0 ) = 1.000000
exp2f ( 0.0 ) = 1.000000
exp2l ( 0.0 ) = 1.000000
expm1 ( 1.0 ) = 1.718281
expm1f( 1.0 ) = 1.718281
expm1l( 1.0 ) = 1.718281

Notes

 The functions exp(x)-1 and log(1+x) are called expm1 and logp1 in BASIC on the Hewlett-Packard HP -71B and APPLE Macintosh, EXP1 and LN1 in Pascal, exp1 and log1 in C on APPLE Macintoshes, where they have been provided to make sure financial calculations of ((1+x)**n-1)/x, namely expm1(n*log1p(x))/x, will be accurate when x is tiny. They also provide accurate inverse hyperbolic functions.

The function pow (x, 0);
returns x**0 = 1 for all x including x = 0, oo, and NaN . Previous implementations of pow may have defined x**0 to be undefined in some or all of these cases. Here are reasons for returning x**0 = 1 always:

  1. Any program that already tests whether x is zero (or infinite or NaN) before computing x**0 cannot care whether 0**0 = 1 or not. Any program that depends upon 0**0 to be invalid is dubious anyway since that expression’s meaning and, if invalid, its consequences vary from one computer system to another.
  2. Some Algebra texts (e.g. Sigler’s) define x**0 = 1 for all x, including x = 0. This is compatible with the convention that accepts a[0] as the value of polynomial
    p(x) = a[0]*x**0 + a[1]*x**1 + a[2]*x**2 +...+ a[n]*x**n

    at x = 0 rather than reject a[0]*0**0 as invalid.

  3. Analysts will accept 0**0 = 1 despite that x**y can approach anything or nothing as x and y approach 0 independently. The reason for setting 0**0 = 1 anyway is this:
    If x(z) and y(z) are

 any
functions analytic (expandable
in power series) in z around z = 0, and if there
x(0) = y(0) = 0, then x(z)**y(z) -> 1 as z -> 0.

  4. If 0**0 = 1, then oo**0 = 1/0**0 = 1 too; and then NaN**0 = 1 too because x**0 = 1 for all finite and infinite x, i.e., independently of x.

See also

 math

Feedback

For additional information or queries on this page send feedback


fabs

Name

fabs, fabsf, fabsl
- absolute value of floating-point number

Library

 libm.lib

Synopsis
#include <math.h>
double fabs (double x);
float fabsf (float x);
long double fabsl (long double x);

Return values

 The fabs, fabsf and fabsl functions return the absolute value of x.

Detailed description

 The fabs, fabsf and fabsl functions compute the absolute value of a floating-point number x.

Examples

#include  <stdio.h>
#include  <math.h>
int main( void )
{
   double dx = -3.141593, dy;
   dy = fabs( dx );
   printf( "fabs( %f ) = %f\n", dx, dy );
   dy = fabsf( dx );
   printf( "fabsf( %f ) = %f\n", dx, dy );
   dy = fabsl( dx );
   printf( "fabsl( %f ) = %f\n", dx, dy );
}

Output

fabs( -3.141593  ) = 3.141593
fabsf( -3.141593 ) = 3.141593
fabsl( -3.141593 ) = 3.141593

See also

 abs, ceil, floor, ieee, math, rint

Feedback

For additional information or queries on this page send feedback


fclose

Name

fclose - closes a stream

Library

 libc.lib

Synopsis
#include <stdio.h>
int fclose (FILE *stream);

Return values

 Upon successful completion 0 is returned. Otherwise, EOF is returned and the global variable errno is set to indicate the error. In either case no further access to the stream is possible.

Detailed description

 The fclose function dissociates the named stream from its underlying file or set of functions. If the stream was being used for output, any buffered data is written first, using fflush.

Examples

/****************** this program shows opening and closing of a file using fclose api **************/
#include <stdio.h>
int main()
{
        FILE *fp;
        fp = fopen("c:\\input.txt", "w+");
        if(fp == NULL)
                {
                printf("file opening failed");
                return -1;
                }

        printf("file opened successfully: Perform file operations now\n");

        if(!fclose(fp))
                {
                printf("file closed successfully");
                return 0;
                }
        else
                {
                printf("file closing failed");
                return -1;
                }
}

Output

file opened successfully: Perform file operations now
file closed successfully

Errors

 The fclose function may also fail and set errno for any of the errors specified for the routines close or fflush.

Notes

 The fclose function does not handle NULL arguments; they will result in a segmentation violation. This is intentional - it makes it easier to make sure programs written under
are bug free. This behaviour is an implementation detail, and programs should not rely upon it.

Feedback

For additional information or queries on this page send feedback


fcntl

Name

fcntl - manipulates file descriptor

Library

 libc.lib

Synopsis
#include <fcntl.h>
int fcntl (int fd, int cmd, ...);

Return values

 Upon successful completion, the value returned depends on cmd as follows:
F_DUPFD | A new file descriptor.
F_GETFD | Value of flag (only the low-order bit is defined).
F_GETFL | Value of flags.
F_GETOWN | Value of file descriptor owner(Not supported).
other | Value other than -1.

Otherwise, a value of -1 is returned and errno is set to indicate the error.

Detailed description

 The fcntl system call provides for control over descriptors. The argument fd is a descriptor to be operated on by cmd as described below. Depending on the value of cmd, fcntl can take an additional third argument int arg.
F_DUPFD Return a new descriptor as follows:

  • Lowest numbered available descriptor greater than or equal to arg.
  • Same object references as the original descriptor.
  • New descriptor shares the same file offset if the object was a file.
  • Same access mode (read, write or read/write).
  • Same file status flags (i.e., both file descriptors share the same file status flags).
  • The close-on-exec flag associated with the new file descriptor is set to remain open across execve system calls.
Limitation :Here the difference between two fd’s passed  should not be greater than 8 , if the difference between
two fd’s is greater than 8 then behaviour of fcntl system call is undefined.
An example call would be:

fcntl (5, F_DUPFL, 10);
Here difference between two fd’s is  (10 - 5) = 5 which is less than 8

F_GETFD | Get the close-on-exec flag associated with the file descriptor fd as FD_CLOEXEC. If the returned value ANDed with FD_CLOEXEC is 0, the file will remain open across exec, otherwise the file will be closed upon execution of exec ( arg is ignored).
F_SETFD | Set the close-on-exec flag associated with fd to arg, where arg is either 0 or FD_CLOEXEC, as described above.
F_GETFL | Get descriptor status flags, as described below ( arg is ignored).
F_SETFL | Set descriptor status flags to arg.
F_GETOWN | Get the process ID or process group currently receiving SIGIO and SIGURG signals; process groups are returned as negative values ( arg is ignored)(Not supported).
F_SETOWN | Set the process or process group to receive SIGIO and SIGURG signals; process groups are specified by supplying arg as negative, otherwise arg is interpreted as a process ID(Not supported).

The flags for the F_GETFL and F_SETFL flags are as follows:
O_NONBLOCK | Non-blocking I/O; if no data is available to a read system call, or if a write operation would block, the read or write call returns -1 with the error (This flag is Not supported for files) EAGAIN.
O_APPEND | Force each write to append at the end of file; corresponds to the O_APPEND flag of open. (Setting this flag in fcntl currently has no effect on subsequent write system calls)
O_DIRECT | Minimize or eliminate the cache effects of reading and writing. The system will attempt to avoid caching the data read or written. If it cannot avoid caching the data, it will minimize the impact the data has on the cache. Use of this flag can drastically reduce performance if not used with care(Not supported).
O_ASYNC | Enable the SIGIO signal to be sent to the process group when I/O is possible, e.g., upon availability of data to be read(Not supported).

Several commands are available for doing advisory file locking; they all operate on the following structure:

struct flock {
        off_t   l_start;        /* starting offset */
        off_t   l_len;          /* len = 0 means until end of file */
        pid_t   l_pid;          /* lock owner */
        short   l_type;         /* lock type: read/write, etc. */
        short   l_whence;       /* type of l_start */
};

The commands available for advisory record locking are as follows:
F_GETLK | Get the first lock that blocks the lock description pointed to by the third argument, arg, taken as a pointer to a struct flock (see above). The information retrieved overwrites the information passed to fcntl in the flock structure. If no lock is found that would prevent this lock from being created, the structure is left unchanged by this system call except for the lock type which is set to F_UNLCK (Not supported).
F_SETLK | Set or clear a file segment lock according to the lock description pointed to by the third argument, arg, taken as a pointer to a struct flock (see above). F_SETLK is used to establish shared (or read) locks (F_RDLCK) or exclusive (or write) locks, (F_WRLCK,) as well as remove either type of lock (F_UNLCK.) If a shared or exclusive lock cannot be set, fcntl returns immediately with EAGAIN(Not supported).
F_SETLKW | This command is the same as F_SETLK except that if a shared or exclusive lock is blocked by other locks, the process waits until the request can be satisfied. If a signal that is to be caught is received while fcntl is waiting for a region, the fcntl will be interrupted if the signal handler has not specified the SA_RESTART( Not supported).

When a shared lock has been set on a segment of a file, other processes can set shared locks on that segment or a portion of it. A shared lock prevents any other process from setting an exclusive lock on any portion of the protected area. A request for a shared lock fails if the file descriptor was not opened with read access.

An exclusive lock prevents any other process from setting a shared lock or an exclusive lock on any portion of the protected area. A request for an exclusive lock fails if the file was not opened with write access.

The value of l_whence is SEEK_SET, SEEK_CUR, or SEEK_END to indicate that the relative offset, l_start bytes, will be measured from the start of the file, current position, or end of the file, respectively. The value of l_len is the number of consecutive bytes to be locked. If l_len is negative, l_start means end edge of the region. The l_pid field is only used with F_GETLK to return the process ID of the process holding a blocking lock. After a successful F_GETLK request, the value of l_whence is SEEK_SET.

Locks may start and extend beyond the current end of a file, but may not start or extend before the beginning of the file. A lock is set to extend to the largest possible value of the file offset for that file if l_len is set to zero. If l_whence and l_start point to the beginning of the file, and l_len is zero, the entire file is locked. If an application wishes only to do entire file locking, the flock system call is much more efficient.

There is at most one type of lock set for each byte in the file. Before a successful return from an F_SETLK or an F_SETLKW request when the calling process has previously existing locks on bytes in the region specified by the request, the previous lock type for each byte in the specified region is replaced by the new lock type. As specified above under the descriptions of shared locks and exclusive locks, an F_SETLK or an F_SETLKW request fails or blocks respectively when another process has existing locks on bytes in the specified region and the type of any of those locks conflicts with the type specified in the request.

This interface follows the completely stupid semantics of System V and -p1003.1-88 that require that all locks associated with a file for a given process are removed when any file descriptor for that file is closed by that process. This semantic means that applications must be aware of any files that a subroutine library may access. For example if an application for updating the password file locks the password file database while making the update, and then calls getpwnam to retrieve a record, the lock will be lost because getpwnam opens, reads, and closes the password database. The database close will release all locks that the process has associated with the database, even if the library routine never requested a lock on the database. Another minor semantic problem with this interface is that locks are not inherited by a child process created using the fork system call. The flock interface has much more rational last close semantics and allows locks to be inherited by child processes. The flock system call is recommended for applications that want to ensure the integrity of their locks when using library routines or wish to pass locks to their children.

The fcntl, flock, and lockf locks are compatible. Processes using different locking interfaces can cooperate over the same file safely. However, only one of such interfaces should be used within the same process. If a file is locked by a process through flock, any record within the file will be seen as locked from the viewpoint of another process using fcntl or lockf, and vice versa. Note that fcntl (F_GETLK);
returns -1 in l_pid if the process holding a blocking lock previously locked the file descriptor by flock.

All locks associated with a file for a given process are removed when the process terminates.

All locks obtained before a call to execve remain in effect until the new program releases them. If the new program does not know about the locks, they will not be released until the program exits.

A potential for deadlock occurs if a process controlling a locked region is put to sleep by attempting to lock the locked region of another process. This implementation detects that sleeping until a locked region is unlocked would cause a deadlock and fails with an EDEADLK error.

Examples

/**
  * Detailed description : Sample usafe of fcntl system call
**/
#include <stdio.h>
#include <fcntl.h>
int main()
{
  int fd  = 0;
  int flags = 0;
  fd = open("Example.txt " , O_CREAT | O_RDWR  , 0666);
  if(fd < 0 )
  {
     printf("Failed to open file Example.txt\n");
     return -1;
  }
  if( (flags = fcntl(fd , F_GETFL) ) < 0 )
  {
     printf("Fcntl system call failed \n");
     return -1;
  }
  printf("Flags of the file %o \n" , flags);
  return 0;
}

Output

Flags of the file 2

Errors

 The fcntl system call will fail if:
[EAGAIN]
The argument cmd is F_SETLK, the type of lock (l_type) is a shared lock (F_RDLCK) or exclusive lock (F_WRLCK,) and the segment of a file to be locked is already exclusive-locked by another process; or the type is an exclusive lock and some portion of the segment of a file to be locked is already shared-locked or exclusive-locked by another process(Not supported).
[EBADF]
The fd argument is not a valid open file descriptor.

The argument cmd is F_SETLK or F_SETLKW, the type of lock (l_type) is a shared lock (F_RDLCK,) and fd is not a valid file descriptor open for reading(Not supported).

The argument cmd is F_SETLK or F_SETLKW, the type of lock (l_type) is an exclusive lock (F_WRLCK,) and fd is not a valid file descriptor open for writing(Not supported).

[EDEADLK]
The argument cmd is F_SETLKW, and a deadlock condition was detected(Not supported).
[EINTR]
The argument cmd is F_SETLKW, and the system call was interrupted by a signal (Not supported).
[EINVAL]
The cmd argument is F_DUPFD and arg is negative or greater than the maximum allowable number (see getdtablesize

The argument cmd is F_GETLK, F_SETLK or F_SETLKW and the data to which arg points is not valid(Not supported).

[EMFILE]
The argument cmd is F_DUPFD and the maximum number of file descriptors permitted for the process are already in use, or no file descriptors greater than or equal to arg are available.
[ENOLCK]
The argument cmd is F_SETLK or F_SETLKW, and satisfying the lock or unlock request would result in the number of locked regions in the system exceeding a system-imposed limit(Not supported).
[EOPNOTSUPP]
The argument cmd is F_GETLK, F_SETLK or F_SETLKW and fd refers to a file for which locking is not supported.
[EOVERFLOW]
The argument cmd is F_GETLK, F_SETLK or F_SETLKW and an off_t calculation overflowed(Not supported).
[EPERM]
The cmd argument is F_SETOWN and the process ID or process group given as an argument is in a different session than the caller(Not supported).
[ESRCH]
The cmd argument is F_SETOWN and the process ID given as argument is not in use(Not supported).

In addition, if fd refers to a descriptor open on a terminal device (as opposed to a descriptor open on a socket), a cmd of F_SETOWN can fail for the same reasons as in tcsetpgrp and a cmd of F_GETOWN for the reasons as stated in tcgetpgrp.

See also

 close, flock, getdtablesize, open

Feedback

For additional information or queries on this page send feedback


fdatasync

Name

fdatasync - synchronizes a fileâs in-core data with that on disk

Library

 libc.lib

Synopsis
#include <unistd.h>
int fdatasync (int fd);

Return values

 If successful,the function shall return the value 0; otherwise, it shall return the value -1 and set errno to indicate the error.

Detailed description

 The fdatasync system call causes all modified data and attributes of fd to be moved to a permanent storage device. This normally results in all in-core modified copies of buffers for the associated file to be written to a disk. The fdatasync() function forces all the queued I/O operations associated that file, as indicated by the file descriptor fd, to the synchronized I/O completion state.

The functionality shall be equivalent to fsync() with the symbol -> _POSIX_SYNCHRONIZED_IO defined. This has an exception that all I/O operations shall be completed, before the call.

The fdatasync should be used by programs that require a file to be in a known state, for example, in building a simple transaction facility.

Examples

#include<unistd.h>
#include<stdio.h>
#define KMAXCHARS 100
int test_fdatasync()
{
   char* array = "abcdefghijklmnopqrstuvwxyz";
   struct stat buf;
   if((fd = open(file , O_CREAT | O_RDWR , 0666))  < 0)
   {
      printf("Failed  to create file");
   }
   size_t size = write(fd,array, KMAXCHARS);
   if(fdatasync(fd) < 0)
   {
     printf("Fdatasync failed");
     int retrn = remove(file);
     return -1;
   }
  int retVal2 = fstat( fp, &buf );
  if(!retVal2)
  {
    size_t bufsize = buf.st_size;
    if (bufsize == size)
    {
      printf("file size = %d\n", size);
      printf("Fdatasync passed");
      int retrn = remove(file);
      return 0;
    }
  }
}

Output

file size = 50
Fdatasync passed

Errors

 The errors defined for fsync are the ones defined for fdatasync.

See also

 sync, fsync

Feedback

For additional information or queries on this page send feedback


fdim

Name

fdim, fdimf, fdiml
- positive difference

Library

 libm.lib

Synopsis
#include <math.h>
double fdim (double x, double y);
float fdimf (float x, float y);
long double fdiml (long double x, long double y);

Detailed description

 The fdim, fdimf, and fdiml functions return the positive difference between x and y. That is, if x- y is positive, then x- y is returned. If either x or y is an NaN, then an NaN is returned. Otherwise, the result is +0.0.

Examples

#include <math.h>
int main( void )
{
   double x1 = 0, x2 = -9, y;
   y = fdim( x1, x2 );
   printf( "fdim(%f , %f) = %f\n", x1, x2, y );
   y = fdimf( x1, x2 );
   printf( "fdimf(%f , %f) = %f\n", x1, x2, y );
   y = fdiml( x1, x2 );
   printf( "fdiml(%f , %f) = %f\n", x1, x2, y );
}

Output

fdim ( 0, -9 ) = 9
fdimf( 0, -9 ) = 9
fdiml( 0, -9 ) = 9

See also

 fabs, fmax, math

Feedback

For additional information or queries on this page send feedback


feclearexcept

Name

feclearexcept, fegetexceptflag, feraiseexcept, fesetexceptflag, fetestexcept
- C99 floating point rounding and exception handling

Library

 libm.lib

Synopsis
#include <fenv.h>
int feclearexcept (int excepts);
int fegetexceptflag (fexcept_t *flagp, int excepts);
int feraiseexcept (int excepts);
int fesetexceptflag (const fexcept_t *flagp, int excepts);
int fetestexcept (int excepts);

Return values

 These functions don’t serve any purpose, as long as there is no math co-processor in the phones.

If there is a hardware FPU, the above function will works as follows:

the feclearexcept, fegetexceptflag, feraiseexcept, and fesetexceptflag functions return 0 upon success, and non-zero otherwise. The fetestexcept function returns the bitwise OR of the values of the current exception flags that were requested.

Detailed description

 These functios are expanded as blank definitions as there is no hardware floating point phones in Series 60 phones.

If there is a hardware floating point unit, These functions will be expanded as ARM inline assembly codes. This is controlled by flag ARM_HARD_FLOAT.

See also

 fegetenv

Feedback

For additional information or queries on this page send feedback


fegetenv

Name

fegetenv, feholdexcept, fesetenv, feupdateenv
- C99 floating point rounding and exception handling

Library

 libm.lib

Synopsis
#include <fenv.h>
int fegetenv (fenv_t *envp);
int feholdexcept (fenv_t *envp);
int fesetenv (const fenv_t *envp);
int feupdateenv (const fenv_t *envp);

Return values

 The fegetenv, feholdexcept, fesetenv, and feupdateenv functions return 0 if they succeed, and non-zero otherwise.

Detailed description

 The floating-point environment includes exception flags and masks, the current rounding mode, and other architecture-specific settings. However, it does not include the floating-point register file.

The fegetenv function stores the current floating-point environment in the object pointed to by envp, whereas feholdexcept saves the current environment, then clears all exception flags and masks all floating-point exceptions.

The fesetenv function restores a previously saved environment. The feupdateenv function restores a saved environment as well, but it also raises any exceptions that were set in the environment it replaces.

The feholdexcept function is often used with feupdateenv or fesetenv to suppress spurious exceptions that occur as a result of intermediate computations.

See also

 feclearexcept fegetenv

Feedback

For additional information or queries on this page send feedback


fegetround

Name

fegetround, fesetround
- C99 floating point rounding and exception handling

Library

 libm.lib

Synopsis
#include <fenv.h> #pragma STDC FENV_ACCESS ON
int fegetround (void);
int fesetround (int round);

Return values

 The fegetround routine returns the current rounding mode. The fesetround function returns 0 on success and non-zero otherwise; however, the present implementation always succeeds.

Detailed description

 The fegetround function determines the current floating-point rounding mode, and the fesetround function sets the current rounding mode to round. The rounding mode is one of FE_TONEAREST, FE_DOWNWARD, FE_UPWARD, or FE_TOWARDZERO, as described in fenv.h.

These routines first appeared in 5.3 . They supersede the non-standard fpgetround and fpsetround functions.

Feedback

For additional information or queries on this page send feedback


ferror

Name

clearerr, feof, ferror, fileno
- check and reset stream status

Library

 libc.lib

Synopsis
#include <stdio.h>
void clearerr (FILE *stream);
int feof (FILE *stream);
int ferror (FILE *stream);
int fileno (FILE *stream);

Detailed description

 The function clearerr clears the end-of-file and error indicators for the stream pointed to by stream.

The function feof tests the end-of-file indicator for the stream pointed to by stream, returning non-zero if it is set. The end-of-file indicator can only be cleared by 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 descriptor.

Examples

/****************** this program shows finding error set using ferror **************/
/****************** and clearing it using clearerr functions ***********************/
#include <stdio.h>
int main()
{
        char a;
        FILE* fp = fopen("c:\\input.txt", "w");
        fprintf(fp, "%s", "abcdefghijklmn");
        fprintf(fp, "%c", '\n');
        fprintf(fp, "%s", "fdsfdsafsdabcdefghijklmn");
        fclose(fp);
        fp=fopen("c:\\input.txt","r");
        if (fp == NULL)
                {
                printf("fopen failed\n");
                return -1;
                }
        else
                {
                fwrite(&a, sizeof(char), 1, fp);
                if (ferror (fp))
                        printf("error set in file stream\n");
                else
                        {
                        fclose(fp);
                        return -1;
                        }
                clearerr(fp);
                if (!ferror(fp))
                        printf("error cleared in file stream\n");
                else printf("error still unexpected set in file stream\n");
                fclose (fp);
                }
        return 0;
}

Output

error set in file stream
error cleared in file stream

Errors

 These functions should not fail and do not set the external variable errno.

See also

 open, flockfile

Feedback

For additional information or queries on this page send feedback


fflush

Name

fflush - flushes a stream

Library

 libc.lib

Synopsis
#include <stdio.h>
int fflush (FILE *stream);

Return values

 Upon successful completion 0 is returned. Otherwise, EOF is returned and the global variable errno is set to indicate the error.

Detailed description

 The function fflush forces a write of all buffered data for the given output or update stream via the stream’s underlying write function. The open status of the stream is unaffected.

If the stream argument is NULL, fflush flushes all open output streams.

Examples

/****************** this program shows flushing user space buffered data using fflush **************/
#include <stdio.h>
int main()
{
        FILE *fp;
        int retval = 0;
        char name[20] = "c:\\flush1.txt";
        fp = fopen(name, "w+");
        if(fp == NULL)
                {
                printf("Error : File open");
                return -1;
                }
        setvbuf(fp, NULL, _IOFBF, 100);  // set to full buffering with NULL buffer
        fprintf(fp, "we are trying to buffer 100 characters at once with NULL buffer.");

        retval = fflush(fp);
        if (retval)
                {
                printf("fflush failed\n");
                fclose(fp);
                unlink(name);
                return -1;
                }
        else printf("Buffer successfully flushed\n");
        fclose(fp);
        unlink(name);
        return 0;
}

Output

we are trying to buffer 100 characters at once with NULL buffer.
Buffer successfully flushed

Errors
[EBADF]
The stream argument is not an open stream, or, in the case of fflush, not a stream open for writing.

The function fflush may also fail and set errno for any of the errors specified for the routine write.

See also

 write, fclose, fopen, setbuf

Feedback

For additional information or queries on this page send feedback


ffs

Name

ffs, ffsl, fls, flsl
- find first bit set in a word

Library

 libc.lib

Synopsis
#include <strings.h>
int ffs (int value);
int ffsl (long value);
int fls (int value);
int flsl (long value);

Return values

Detailed description

 The ffs and ffsl functions find the first bit set in value and return the index of that bit.

The fls and flsl functions find the last bit set in value and return the index of that bit.

Bits are numbered starting from 1, starting at the right-most (least significant) bit. A return value of zero from any of these functions means that the argument was zero.

Examples

#include <string.h>
#include <stdio.h>
int main()
{
    int i = 0x10;
    int j = ffs(i);
    if(j == 5) printf("First bit position in 0x10 is %d\n",j);
    return 0;
}

Output

First bit position in 0x10 is 5

Feedback

For additional information or queries on this page send feedback


fgets

Name

fgets, gets
- input of characters and strings

Library

 libc.lib

Synopsis
#include <stdio.h>
char * fgets (char * restrict str, int size, FILE * restrict stream);
char * gets (char *str);

Return values

 Upon successful completion, fgets and gets return a pointer to the string. If end-of-file occurs before any characters are read, they return NULL and the buffer contents remain unchanged. If an error occurs, they return NULL and the buffer contents are indeterminate. The fgets and gets functions do not distinguish between end-of-file and error, and callers must use feof and ferror to determine which occurred.

Detailed description

 The fgets function reads at most one less than the number of characters specified by size from the given stream and stores them in the string str. Reading stops 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 is appended to end the string.

The gets function is equivalent to fgets with an infinite size and a stream of stdin, except that the newline character (if any) is not stored in the string. It is the caller’s responsibility to ensure that the input line, if any, is sufficiently short to fit in the string.

Examples

/****************** this program shows reading characters from a file using fgets **************/
/****************** consider input.txt has the following content: ******************************/
/****************** abcdefghijklmn **********************************************************************/
/****************** fdsfdsafsdabcdefghijklmn*************************************************************/
#include <stdio.h>
int main(void)
{
        char buf[20];
        FILE* fp = fopen("c:\\input.txt", "w");
        fprintf(fp, "%s", "abcdefghijklmn");
        fprintf(fp, "%c", "\n");
        fprintf(fp, "%s", "fdsfdsafsdabcdefghijklmn");
        fclose(fp);

        fp = fopen("C:\\input.txt","r");
        if(fp == NULL)
                {
                printf("fopen failed\n");
                return -1;
                }
        if(fgets(buf,18,fp) != NULL)
                printf("%s", buf);
        else
                printf("Buffer is empty\n");

        buf[0] = '\0';
        if(fgets(buf,2,fp) != NULL)
                printf("%s\n", buf);
        else
                printf("Buffer is empty\n");
        fclose(fp);
        return 0;
}

Output

abcdefghijklmn
fdsfdsafsdabcdefghijklmn

Errors
[EBADF]
The given stream is not a readable stream.

The function fgets may also fail and set errno for any of the errors specified for the routines fflush, fstat, read, or malloc.

The function gets may also fail and set errno for any of the errors specified for the routine getchar.

Security considerations

 The gets function cannot be used securely. Because of its lack of bounds checking, and the inability for the calling program to reliably determine the length of the next incoming line, the use of this function enables malicious users to arbitrarily change a running program’s functionality through a buffer overflow attack. It is strongly suggested that the fgets function be used in all cases.

See also

 feof, ferror, fgetln,

Feedback

For additional information or queries on this page send feedback


fgetws

Name

fgetws - reads a wide character string from a FILE stream

Library

 libc.lib

Synopsis
#include <stdio.h>
#include <wchar.h>
wchar_t * fgetws (wchar_t * restrict ws, int n, FILE * restrict fp);

Return values

 Upon successful completion, fgetws returns ws. If end-of-file occurs before any characters are read, fgetws returns NULL and the buffer contents remain unchanged. If an error occurs, fgetws returns NULL and the buffer contents are indeterminate. The fgetws function does not distinguish between end-of-file and error, and callers must use feof and ferror to determine which occurred.

Detailed description

 The fgetws function reads at most one less than the number of characters specified by n from the given fp and stores them in the wide character string ws. Reading stops 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 is appended to end the string.

Examples

#include <stdio.h>
#include <wchar.h>
/* Illustrates how to use fgetws API */
wchar_t *example_fgetws(wchar_t *buf)
{
 FILE *fp = NULL;
 wint_t retval;
 int n;
 /* for example, 10 characters to be read */
 n = 10;
 /* opening the input file */
 fp = fopen("input.txt","r");
 if(fp == NULL)
 {
  wprintf(L"Error: File open\n");
  return (-1);
 }
 /* Read characters from the opened file */
 retval = fgetws(buf, n, fp);
 /* Close the file open for reading */
 fclose(fp);
 /* return the character read from the file */
 return (buf);
}

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 valid multibyte character.

The function fgetws may also fail and set errno for any of the errors specified for the routines fflush, fstat, read, or malloc.

See also

 feof, ferror, fgets
The fgetws function conforms to -p1003.1-2001.

Feedback

For additional information or queries on this page send feedback


S60 3rd Edition API Reference: File Index

S60 Open C
API Reference Guide and Developer Guides

S60 3rd Edition API Reference File List

Here is a list of all files with brief descriptions:
display.inl Defines the inline constructors for the display data classes

© Nokia 2007

Back to top


finite

Name

finite, finitef, finitel
- test for infinity or not-a-number (NaN)

Library

 libm.lib

Synopsis
#include <math.h>
double finite (double x);
float finitef (float x);
long double finitel (long double x);

Detailed description

 The finite finitef and finitel functions return a non-zero value if value is neither infinite nor a "not-a-number" (NaN) value, and 0 otherwise.

Examples

#include <math.h>
int main( void )
{
   double x;
   int y;
   x = 1.34565;
   y = finite( x );
   printf( "finite( %f ) =  %d\n", x, y );
   y = finitef( x );
   printf( "finitef( %f ) = %d\n",x, y );
   y = finitel( x );
   printf( "finitel( %f ) = %d\n",x, y );
}

Output

finite ( 1.34565 ) = 1
finitef( 1.34565 ) = 1
finitel( 1.34565 ) =

Feedback

For additional information or queries on this page send feedback


flockfile

Name

flockfile, ftrylockfile, funlockfile
- lock FILE for stdio

Library

 libc.lib

Synopsis
#include <stdio.h>
void flockfile (FILE *stream);
int ftrylockfile (FILE *stream);
void funlockfile (FILE *stream);

Return values

 The flockfile and funlockfile functions return no value.

The ftrylockfile function returns zero if the stream was successfully locked, non-zero otherwise.

Detailed description

 These functions provide explicit application-level locking of stdio streams. They can be used to avoid output from multiple threads being interspersed, input being dispersed among multiple readers, and to avoid the overhead of locking the stream for each operation.

The flockfile function acquires an exclusive lock on the specified stream. If another thread has already locked the stream, flockfile will block until the lock is released.

The ftrylockfile function is a non-blocking version of flockfile; if the lock cannot be acquired immediately, ftrylockfile returns non-zero instead of blocking.

The funlockfile function releases the lock on a stream acquired by an earlier call to flockfile or ftrylockfile.

These functions behave as if there is a lock count associated with each stream. Each time flockfile is called on the stream, the count is incremented, and each time funlockfile is called on the stream, the count is decremented. The lock is only actually released when the count reaches zero.

Examples

#include <stdio.h>
#include <unistd.h>
#include <pthread.h> //link to the lib -libpthread

void* somefun(void* args)
{
FILE *fp = (FILE *)args;
printf("in thr 2\n");
flockfile(fp);
printf("aquired lock!\n");
fputc('a', fp); //fputc_unlocked() is more relevant
printf("after a from thr 2\n");
sleep(3);
printf("after sleep from thr 2\n");
fputc('b', fp);
printf("after b from thr 2\n");
fputc('c', fp);
printf("after c from thr 2\n");
funlockfile(fp);
fclose(fp);
}
int main()
{
pthread_t obj;
FILE *fp = fopen("c:\\chk.txt", "w");
if(fp)
{
        flockfile(fp);
        fputc('x', fp); //fputc_unlocked() is more relevant
        printf("after x from thr 1\n");
        sleep(5);
        printf("after sleep from thr 1\n");
        pthread_create(&obj, NULL, somefun, fp);
        printf("after calling thr 2 from thr 1\n");
        fputc('y', fp);
        printf("after y from thr 1\n");
        fputc('z', fp);
        printf("after z from thr 1\n");
        funlockfile(fp);
        printf("gave up lock in thr 1\n");
}
pthread_exit((void *)0);
}

Output

after x from thr 1
after sleep from thr 1
in thr 2
after calling thr 2 from thr 1
after y from thr 1
after z from thr 1
gave up lock in thr 1
acquired lock!
after a from thr 2
after sleep from thr 2
after b from thr 2
after c from thr 2

Note: The printing takes quite some time and hence the
output may not look exactly like the above one.
(try printing to the files if you are very particular)

#include <stdio.h>
#include <unistd.h>
#include <pthread.h> //link to lib -libpthread
#include <errno.h>

void* somefun(void* args)
{

FILE *fp = (FILE *)args;

printf("in thr 2\n");

int i = ftrylockfile(fp);
if(i == 0)
{
        printf("aquired lock!\n");
        fputc('a', fp);
        printf("after a from thr 2\n");
        sleep(3);
        printf("after sleep from thr 2\n");
        fputc('b', fp);
        printf("after b from thr 2\n");
        fputc('c', fp);
        printf("after c from thr 2\n");
        funlockfile(fp);
        printf("gave up lock in thr 2\n");
}
else
        printf("couldn't aquire lock\n");
}
int main()
{
pthread_t obj;

FILE *fp = fopen("c:\\chk.txt", "w");

if(fp)
{
        flockfile(fp);
        fputc('x', fp);
        printf("after x from thr 1\n");
        sleep(5);
        printf("after sleep from thr 1\n");
        pthread_create(&obj, NULL, somefun, fp);
        printf("after calling thr 2 from thr 1\n");
        fputc('y', fp);
        printf("after y from thr 1\n");
        fputc('z', fp);
        printf("after z from thr 1\n");
        funlockfile(fp);
        printf("gave up lock in thr 1\n");
        sleep(5);
        fclose(fp);
}
pthread_exit((void *)0);
}

Output

after x from thr 1
after sleep from thr 1
in thr 2
couldn’t acquire lock
after calling thr 2 from thr 1
after y from thr 1
after z from thr 1
gave up lock in thr 1

Note: The printing takes quite some time and hence the
output may not look exactly like the above one.
(try printing to the files if you are very particular)

See also

 getc_unlocked, putc_unlocked

Feedback

For additional information or queries on this page send feedback


floor

Name

floor, floorf, floorl
- Returns the largest integral value not greater than argument

Library

 libm.lib

Synopsis
#include <math.h>
double floor (double x);
float floorf (float x);
long double floorl (long double x);

Return values

x is integral or infinite, x itself is returned.

Detailed description

 The floor, floorf, and floorl functions return the largest integral value less than or equal to x, expressed as a floating-point number.

Examples

#include <math.h>
int main( void )
{
   double y;
   y = floor( 2.8 );
   printf( "The floor of 2.8 is %f\n", y );
   y = floorf( 2.8 );
   printf( "The floorf of 2.8 is %f\n", y );
   y = floorl( 2.8 );
   printf( "The floorl of 2.8 is %f\n", y );
}

Output

The floor  of 2.8 is 2.000000
The floorf of 2.8 is 2.000000
The floorl of 2.8 is 2.000000

See also

 abs, ceil, fabs, ieee, math, rint, round, trunc

Feedback

For additional information or queries on this page send feedback


fma

Name

fma, fmaf, fmal
- floating-point multiply and add

Library

 libm.lib

Synopsis
#include <math.h>
double fma (double x, double y, double z);
float fmaf (float x, float y, float z);
long double fmal (long double x, long double y, long double z);

Detailed description

 The fma, fmaf, and fmal functions return (x * y) + z, computed with only one rounding error. Using the ordinary multiplication and addition operators, by contrast, results in two roundings: one for the intermediate product and one for the final result.

For instance, the expression 1.2e100 * 2.0e208 - 1.4e308 produces oo due to overflow in the intermediate product, whereas fma(1.2e100, 2.0e208, -1.4e308) returns approximately 1.0e308.

The fused multiply-add operation is often used to improve the accuracy of calculations such as dot products. It may also be used to improve performance on machines that implement it natively. The macros FP_FAST_FMA, FP_FAST_FMAF and FP_FAST_FMAL may be defined in
#include <math.h>to indicate that fma, fmaf, and fmal (respectively) have comparable or faster speed than a multiply operation followed by an add operation.

Examples

#include <math.h>
int main()
{
   double x1 = 1, x2 = 2, x3 =3, y;
   y = fma( x1, x2, x3 );
   printf( "fma(%f , %f , %f) = %f\n", x1, x2, x3, y );
   y = fmaf( x1, x2, x3 );
   printf( "fmaf(%f , %f , %f) = %f\n", x1, x2, x3, y );
   y = fmal( x1, x2, x3 );
   printf( "fmal(%f , %f , %f) = %f\n", x1, x2, x3, y );
}

Output

fma ( 1, 2, 3 ) = 5
fmaf( 1, 2, 3 ) = 5
fmal( 1, 2, 3 ) = 5

Implementation notes

 In general, these routines will behave as one would expect if x * y + z were computed with unbounded precision and range, then rounded to the precision of the return type. However, on some platforms,

See also

 math

Feedback

For additional information or queries on this page send feedback


fmax

Name

fmax, fmaxf, fmaxl, fmin, fminf, fminl
- find maximum value

Library

 libm.lib

Synopsis
#include <math.h>
double fmax (double x, double y);
float fmaxf (float x, float y);
long double fmaxl (long double x, long double y);
double fmin (double x, double y);
float fminf (float x, float y);
long double fminl (long double x, long double y);

Detailed description

 The fmax, fmaxf, and fmaxl functions return the larger of x and y, and likewise, 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 an NaN(Not a Number), then the other argument is returned. If both arguments are NaN(Not a Number)s, then the result is an NaN(Not a Number).

Examples

#include <math.h>
int main( void )
{
   double y;
   y = fmax( 0, -9 );
   printf( "fmax ( 0, -9) = %f\n", y );
   y = fmaxf( 0, -9 );
   printf( "fmaxf( 0, -9) = %f\n", y );
   y = fmaxl( 0, -9 );
   printf( "fmaxl( 0, -9) = %f\n", y );
   y = fmin( 0, -9 );
   printf( "fmin ( 0, -9) = %f\n", y );
   y = fminf( 0, -9 );
   printf( "fminf ( 0, -9) = %f\n", y );
   y = fminl( 0, -9 );
   printf( "fminl ( 0, -9) = %f\n", y );
}

Output

fmax( 0, -9 ) = 0
fmaxf( 0, -9 ) = 0
fmaxl( 0, -9 ) = 0
fmin( 0, -9 ) = -9
fminf( 0, -9 ) = -9
fminl( 0, -9 ) = -9

See also

 fabs, fdim, math

Feedback

For additional information or queries on this page send feedback


fmod

Name

fmod, fmodf, fmodl
- floating-point remainder function

Library

 libm.lib

Synopsis
#include <math.h>
double fmod (double x, double y);
float fmodf (float x, float y);
long double fmodl (long double x, long double y);

Return values

 The fmod, fmodf, and fmodl functions return the value x - i * y, for some integer i such that, if y is non-zero, the result has the same sign as x and magnitude less than the magnitude of y. If y is zero, whether a domain error occurs or the fmod and fmodf function returns zero is implementation-defined.

Detailed description

 The fmod, fmodf, and fmodl functions compute the floating-point remainder of x / y. fmodl is an alias to the function fmod.

Examples

#include <math.h>
int main()
{
   double x1 = 6.5, x2 = 2.25, y;
   y = fmod( x1, x2 );
   printf( "fmod(%f , %f) = %f\n", x1, x2, y );
   y = fmodf( x1, x2 );
   printf( "fmodf(%f , %f) = %f\n", x1, x2, y );
   y = fmodl( x1, x2 );
   printf( "fmodl(%f , %f) = %f\n", x1, x2, y );
}

Output

fmod ( 6.4, 2 ) = 2.0
fmodf( 6.4, 2 ) = 2.0
fmodl( 6.4, 2 ) = 2.0

See also

 math

Feedback

For additional information or queries on this page send feedback


fopen

Name

fopen, fdopen, freopen
- stream open functions

Library

 libc.lib

Synopsis
#include <stdio.h>
FILE * fopen (const char * restrict path, const char * restrict mode);
FILE * fdopen (int fildes, const char *mode);
FILE * freopen (const char *path, const char *mode, FILE *stream);

Return values

 Upon successful completion fopen, fdopen and freopen return a FILE pointer. Otherwise, NULL is returned and the global variable errno is set to indicate the error.

Detailed description

 The fopen function opens the file whose name is the string pointed to by path and 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 the file.
"r+" | Open for reading and writing. The stream is positioned at the beginning of the file.
"w" | Truncate to zero length or create text file for writing. The stream is positioned at the beginning of the file.
"w+" | Open for reading and writing. The file is created if it does not exist, otherwise it 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 is positioned at the end of the file. Subsequent writes to the file will always end up at the then current end of file, irrespective of any intervening fseek or similar.
"a+" | Open for reading and writing. The file is created if it does not exist. The stream is positioned at the end of the file. Subsequent writes to the file will always end up at the then current end of file, irrespective of any intervening fseek or similar.

The mode string can also include the letter ‘‘b’’ either as a third character or as a character between the characters in any of the two-character strings described above. This is strictly for compatibility with -isoC and has no effect; the ‘‘b’’ is ignored.

Reads and writes may be intermixed on read/write streams in any order, and do not require an intermediate seek as in previous versions of stdio. This is not portable to other systems, however; ANSI C requires that a file positioning function intervene between 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. When the stream is closed via fclose, fildes is closed also.

The freopen function opens the file whose name is the string pointed to by path and associates the stream pointed to by stream with it. The original stream (if it exists) is closed. The mode argument is used just as in the fopen function.

If the path argument is NULL, freopen attempts to re-open the file associated with stream with a new mode. The new mode must be compatible with the mode that the stream was originally opened with:

  • Streams originally opened with mode "r" can only be reopened with that same mode.
  • Streams originally opened with mode "a" can be reopened with the same mode, or mode "w."
  • Streams originally opened with mode "w" can be reopened with the same mode, or mode "a."
  • Streams originally opened with mode "r+," "w+," or "a+" can be reopened with any mode.

The primary use of the freopen function is to change the file associated with a standard text stream (stderr, stdin, or stdout).

Examples

/****************** this program shows opening  in write mode,write data and close **************/
/****************** again open in append mode and write data***** ******************************/
/***************************** Check file c:\fopen.txt*****************************************/
#include <stdio.h>
int main(void)
{
        FILE *fp;
        char name[20] = "c:\fopen1.txt";

        if ((fp = fopen (name, "w")) == NULL)
        {
        printf("Error creating file");
        return -1;
        }
        printf("Opened file \n");
      fprintf(fp, "This is the first line\n");
      printf("Wrote to file\n");
      fclose (fp);
      printf("Closed file\n");
      if ((fp = fopen (name, "a")) == NULL)
      {
      printf("Error opening file");
      return -1;
      }
      printf("Opened file for appending\n");
      fprintf(fp, "This is the second line\n");
      fclose (fp);
      printf("closed file, check output in c:\ fopen.txt file\n");
      unlink(name);
      return 0;
}

Output

Opened file
Wrote to file
Closed file
Opened file for appending
closed file, check output in c:\ fopen.txt file

Errors
[EINVAL]
The mode argument to fopen, fdopen, or freopen was invalid.

The fopen, fdopen and freopen functions may also fail and set errno for any of the errors specified for the routine malloc.

The fopen function may also fail and set errno for any of the errors specified for the routine open.

The fdopen function may also fail and set errno for any of the errors specified for the routine fcntl.

The freopen function may also fail and set errno for any of the errors specified for the routines

Note

1) Mode values for group and others will be ignored for file creation, execute bit and setuid on exec bit on an file do not have any effect while file creation.Default working
directoy of a process is initialized to C:\private\UID (UID of the calling application), and any data written into this C:\private\UID directory persists between phone resets.

2) If the specified file is a symbolic link and the file it is pointing to is invalid, the symbolic link file will be removed automatically.

Limitations

 A file cannot be created with write-only permissions and any attempt to do so will result in a file with read-write permissions. open, fclose and fflush.

See also

 open, fclose, fileno, fseek

Feedback

For additional information or queries on this page send feedback


fpclassify

Name

fpclassify, isfinite, isinf, isnan, isnormal
- floating-point classification macros

Library

 libm.lib

Synopsis
#include <math.h>
int fpclassify (real-floating x);
int isfinite (real-floating x);
int isinf (real-floating x);
int isnan (real-floating x);
int isnormal (real-floating x);

Detailed description

 The fpclassify macro takes an argument of x and returns one of the following manifest 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 macros return non-zero if and only if x is an infinity, NaN, or a non-zero normalized number, respectively.

The symbol

 isnanf
is provided as an alias to

 isnan
for compatibility, and its use is deprecated.
#include <math.h>
void main()
{
double x1 = 6.5, x2 = 2.25;
int y;
y = fpclassify( x1);
/* Use the Predefine Macro to
determine the Return Values
interpretation
*/
switch( y ){
case FP_INFINITE: printf("%f is a Infinite Value\n", x1);break;
case FP_NAN:   printf("%f is a NAN Value\n", x1);break;
case FP_NORMAL:   printf("%f is a Normalized Floating point Value\n", x1);break;
case FP_SUBNORMAL:printf("%f is a Subnormalized Floating point Number\n", x1);break;
case FP_ZERO:     printf("%f is a Zero\n", x1);break;
case default:     printf("%f is a Invalid Input", x1);break;
}
y = isfinite( x1 );
printf( "isfinite(%f) = %d\n", x1,  y );
y = isinf( x1);
printf( "isinf(%f) = %d\n", x1 y );
y = isnan( x1);
printf( "isnan(%f) = %f\n", x1, y );
y = isnormal( x1);
printf( isnormal(%f) = %f\n", x1,  y );
}

Output

6.5 is a Normalized Floating point Value\n
isfinite(6.5) = 1
isinf(6.5)    = 1
isnan(6.5)    = 0
isnormal(6.5) = 1

See also

 math, signbit

Feedback

For additional information or queries on this page send feedback


fputs

Name

fputs, puts
- output of characters and strings

Library

 libc.lib

Synopsis
#include <stdio.h>
int fputs (const char *str, FILE *stream);
int puts (const char *str);

Return values

 The fputs function returns 0 on success and EOF on error; puts returns a nonnegative integer on success and EOF on error.

Detailed description

 The function fputs writes the string pointed to by str to the stream pointed to by stream.

The function puts writes the string str, and a terminating newline character, to the stream stdout.

Examples

/****************** this program shows writing characters from a file using fputs **************/
/****************** consider input.txt has the following content: ******************************/
/****************** hello world ****************************************************************/
#include <stdio.h>
int main(void)
{
        int wretval;
        char rs1[50],rs2[50];
        char *rptr;
        int retval;
        FILE* fp = fopen("c:\\input.txt", "w");
        fprintf(fp, "%s", "abcdefghijklmn");
        fprintf(fp, "%c", "\n");
        fprintf(fp, "%s", "fdsfdsafsdabcdefghijklmn");
        fclose(fp);
        fp = fopen("c:\\input.txt","r");
        if(fp == NULL)
        {
        printf("fopen failed\n");
        return -1;
        }
        rptr = fgets(rs1,12,fp);
        if(rptr == NULL)
        {
        printf("fgets failed\n");
        fclose(fp);
        return -1;
        }
        fclose(fp);
        fp = fopen("c:\\puts1.txt","w+");
        if(fp == NULL)
        {
        printf("fopen failed\n");
        return -1;
        }
        wretval = fputs(rs1,fp);
        if(wretval == EOF)
        {
        printf("fputs failed\n");
        fclose(fp);
        return -1;
        }
        fclose(fp);
        fp = fopen("C:\\puts1.txt","r");
        if(fp == NULL)
        {
        printf("fopen failed\n");
        return -1;
        }
        rptr = fgets(rs2,12,fp);
        if(rptr == NULL)
        {
        printf("fgets failed\n");
        fclose(fp);
        return -1;
        }
        printf("file reading returned \"%s\"\n",rs2);
        fclose(fp);
        unlink("C:\\puts1.txt");

        return 0;
}

Output

file reading returned "abcdefghijk"

Security considerations

 The fputs function can be misused by a malicious user to arbitrarily change the functionality of a program under execution using the buffer overflow attack. The buffer overflow attack is possible in the since the function assumes that an infinitely long string is passed to it. Thus users must ensure that they do not overflow the actual space.

Errors
[EBADF]
The stream argument is not a writable stream.

The functions fputs and puts may also fail and set errno for any of the errors specified for the routines write.

See also

 ferror, fputws, putc,

Feedback

For additional information or queries on this page send feedback


fputws

Name

fputws - writes a wide character string to a FILE stream

Library

 libc.lib

Synopsis
#include <stdio.h>
#include <wchar.h>
int fputws (const wchar_t * restrict ws, FILE * restrict fp);

Return values

 The fputws function returns 0 on success and -1 on error.

Detailed description

 The fputws function writes the wide character string pointed to by ws to the stream pointed to by fp.

Examples

#include <stdio.h>
#include <wchar.h>
/* Illustrates how to use fputws API */
int example_fputws(wchar_t *buf)
{
 FILE *fp = NULL;
 int retval;
 /* open the file for writing*/
 fp = fopen("write.txt","r");
 if(fp == NULL)
 {
  wprintf(L"Error: File open\n");
  return (-1);
 }
 /* Write the characters into the file */
 retval = fputws(buf, fp);
 /* Close the file open for writing */
 fclose(fp);
 /* return the number of characters written */
 /* into the file */
 return (retval);
}

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 specified for the routine write.

Security considerations

 Please refer fputs

See also

 ferror, fputs, putwc,
The fputws function conforms to -p1003.1-2001.

Feedback

For additional information or queries on this page send feedback


fread

Name

fread, fwrite
- binary stream input/output

Library

 libc.lib

Synopsis
#include <stdio.h>
size_t fread (void * restrict ptr, size_t size, size_t nmemb, FILE * restrict stream);
size_t fwrite (const void * restrict ptr, size_t size, size_t nmemb, FILE * restrict stream);

Return values

 The functions fread and fwrite advance the file position indicator for the stream by the number of bytes read or written. They return the number of objects read or written. If an error occurs, or the end-of-file is reached, the return value is a short object count (or zero).

The function fread does not distinguish between end-of-file and error, and callers must use feof and ferror to determine which occurred. The function fwrite returns a value less than nmemb only if a write error has occurred.

Detailed description

 The function fread reads nmemb objects, each size bytes long, from the stream pointed to by stream, storing them at the location given by ptr.

The function fwrite writes nmemb objects, each size bytes long, to the stream pointed to by stream, obtaining them from the location given by ptr.

Examples

/****************** this program shows reading characters from a file using fread **************/
/****************** consider input.txt has the following content: ******************************/
/****************** hi ****************************************************************/
#include <stdio.h>
int main()
{
        char a;
        FILE* fp = fopen("c:\\input.txt", "w");
        fprintf(fp, "%s", "abcdefghijklmn");
        fprintf(fp, "%c", ’\n’);
        fprintf(fp, "%s", "fdsfdsafsdabcdefghijklmn");
        fclose(fp);
        fp = fopen("c:\\input.txt", "r");
        if (fp == NULL)
                {
                printf ("fopen failed\n");
                return -1;
                }
        // read single chars at a time, stopping on EOF or error:
        while (fread(&a, sizeof(char), 1, fp), !feof(fp) && !ferror(fp))
                {
                printf("I read \"%c\"\n",a);
                }
        if (ferror(fp)) //Some error occurred
                {
                fclose(fp);
                return -1;
                }
        fclose(fp);
        return 0;
}

Output

I read "h"
I read "i"

See also

 read, write

Feedback

For additional information or queries on this page send feedback


frexp

Name

frexp, frexpf, frexpl
- convert floating-point number to fractional and integral components

Library

 libm.lib

Synopsis
#include <math.h>
double frexp (double value, int *exp);
float frexpf (float value, int *exp);
long double frexpl (long double value, int *exp);

Return values

 These functions return the value x, such that x is a double with magnitude in the interval [1/2, 1) or zero, and value equals x times 2 raised to the power *exp. If value is zero, both parts of the result are zero.

Detailed description

 The frexp, frexpf, and frexpl functions break a floating-point number into a normalized fraction and an integral power of 2. They store the integer in the int object pointed to by exp. As there is no long double is not supported by SYMBIAN, frexpl (is, aliased, to, the);
frexp

Examples

void main( void )
{
   double x1 = 4.0 , y;
   int res;
   y = frexp( x1, &res );
   printf( "frexp(%f , &res):: Int Part: %d and Fractional Part: %f \n", x1, res, y );
   y = frexpf( x1, &res );
   printf( "frexpf(%f , &res):: Int Part: %d and Fractional Part: %f \n", x1, res, y );
   y = frexpl( x1, &res );
   printf( "frexpl(%f , &res):: Int Part: %d and Fractional Part: %f \n", x1, res, y );
}

Output

frexp ( 4.0 , &res ) :: Int Part: 3 and Fractional Part: 0.5
frexpf( 4.0,  &res ) :: Int Part: 3 and Fractional Part: 0.5
frexpl( 4.0,  &res ) :: Int Part: 3 and Fractional Part: 0.5

Feedback

For additional information or queries on this page send feedback


fseek

Name

fgetpos, fseek, fsetpos, ftell, rewind
- reposition a stream

Library

 libc.lib

Synopsis
#include <stdio.h>
int fseek (FILE *stream, long offset, int whence);
long ftell (FILE *stream);
void rewind (FILE *stream);
int fgetpos (FILE * restrict stream, fpos_t * restrict pos);
int fsetpos (FILE *stream, const fpos_t *pos);

Return values

 The rewind function returns no value.

Upon successful completion, ftell return the current offset. Otherwise, -1 is returned and the global variable errno is set to indicate the error.

Detailed description

 The fseek function sets the file position indicator for the stream pointed to by stream. The new position, measured in bytes, is obtained by adding offset bytes to the position specified by whence. If whence is set to SEEK_SET, SEEK_CUR, or SEEK_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 and ungetwc functions on the same stream.

The fseek function call does not allows the file offset to be set beyond the end of the existing end-of-file of the file.

The ftell function obtains the current value of the file position indicator for the stream pointed to by

stream.

The rewind function sets the file position indicator for the stream pointed to by stream 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. Since rewind does not return a value, an application wishing to detect errors should clear errno, then call rewind, and if errno is non-zero, assume an error has occurred. The fgetpos and fsetpos functions are alternate interfaces for retrieving and setting the current position in the file, similar to ftell and fseek, except that the current position is stored in an opaque object of type fpos_t pointed to by pos. These functions provide a portable way to seek to offsets larger than those that can be represented by a long int. They may also store additional state information in the fpos_t object to facilitate seeking within files containing multibyte characters with state-dependent encodings. Although fpos_t has traditionally been an integral type, applications cannot assume that it is; in particular, they must not perform arithmetic on objects of this type. If the stream is a wide character stream, the position specified by the combination of offset and whence must contain the first byte of a multibyte sequence.

Examples

/****************** this program shows setting file offset using fseek **************/
#include <stdio.h>
int main(void)
{
        int retval;
        FILE* fp = fopen("c:\\input.txt", "w");
        fprintf(fp, "%s", "abcdefghijklmn");
        fprintf(fp, "%c", '\n');
        fprintf(fp, "%s", "fdsfdsafsdabcdefghijklmn");
        fclose(fp);
        fp = fopen("c:\\input.txt", "r");
        if (fp == NULL)
        {
        printf ("fopen failed\n");
        return -1;
        }
        retval = fseek(fp, 3, SEEK_SET); // seek to the 20th byte of the file
        if (retval)
        {
        printf ("fseek failed\n");
        return -1;
        }

        long pos = ftell(fp);
        if (pos ==3)
        {
        printf("offset setting proper\n");
        }
        fclose(fp);
        return 0;
}

Output

offset setting proper

Errors

[EBADF]
 | The stream argument is not a seekable stream.
[EINVAL]
 | The whence argument is invalid or the resulting file-position indicator would be set to a negative value.
[EOVERFLOW]
 | The resulting file offset would be a value which cannot be represented correctly in an object of type long for fseek and ftell.
[ESPIPE]
 | The file descriptor underlying stream is associated with a pipe or FIFO or file-position indicator value is unspecified (see ungetc).

The functions fgetpos, fseek, fsetpos, and ftell, may also fail and set errno for any of the errors specified for the routines fflush, fstat, lseek, and malloc.

See also

 lseek, ungetc, ungetw

Feedback

For additional information or queries on this page send feedback


fstat

Name

stat, lstat, fstat, __xstat,__lxstat
- get file status

Library

 libc.lib

Synopsis
#include <sys/types.h>
#include <sys/stat.h>
int stat (const char *path, struct stat *sb);
int lstat (const char *path, struct stat *sb);
int fstat (int fd, struct stat *sb);
int __xstat (int version, const char *path, struct stat *sb);
int __lxstat (int version, const char *path, struct stat *sb);

Return values

 On success, zero is returned. On error, -1 is returned, and errno is set appropriately.

Detailed description

 The stat system call obtains information about the file pointed to by path. Read, write or execute permission of the named file is not required, but all directories listed in the path name leading to the file must be searchable.

The lstat system call is like stat except in the case where the named file is a symbolic link, in which case lstat returns information about the link, while stat returns information about the file the link references.

The fstat system call obtains the same information about an open file known by the file descriptor fd.

The __xstat and __lxstat system calls are exactly similar to stat and lstat functionality.

The sb argument is a pointer to a stat structure as defined by
#include <sys/stat.h>and into which information is placed concerning the file.

The fields of struct stat related to the file system are as follows:
st_dev | The numeric ID of the device containing the file.
st_ino | The file’s inode number.
st_nlink
 | The number of hard links to the file.

The st_dev and st_ino fields together identify the file uniquely within the system.

The time-related fields of struct stat are as follows:
st_atime | Time when file data last accessed. Changed by the utimes, read and readv system calls.
st_mtime | Time when file data last modified. Changed by the mkdir, mkfifo, utimes, write and writev system calls.
st_ctime | Time when file status was last changed (inode data modification). Changed by the chmod, chown, creat, link, mkdir, mkfifo, rename, rmdir, symlink, truncate, unlink, utimes, write and writev system calls.
st_birthtime
 | Time when the inode was created.

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 the struct stat are as follows:
st_size | The file size in bytes.
st_blksize
 | The optimal I/O block size for the file.
st_blocks | The actual number of blocks allocated for the file in 512-byte units. As short symbolic links are stored in the inode, this number may be zero.

The access-related fields of struct stat are as follows:
st_uid | The user ID of the file’s owner.
st_gid | The group ID of the file.
st_mode
 | Status of the file (see below).

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

#include <sys/stat.h,> access and chmod The following macros are available to test whether a st_mode value passed in the m argument corresponds to a file of the specified type: S_ISBLK (m); S_ISCHR (m); S_ISDIR (m); S_ISFIFO (m); S_ISLNK (m); S_ISREG (m); S_ISSOCK (m); S_ISWHT (m);
Test for a block special file.
Test for a character special file.
Test for a directory.
Test for a pipe or FIFO special file.
Test for a symbolic link. NOTE: Inode structure is not supported by symbian and hence link count updation is not possible. Check for symbolic link would always fail because of this reason.
Test for a regular file.
Test for a socket.
Test for a whiteout.

The macros evaluate to a non-zero value if the test is true or to the value 0 if the test is false.

Limitation: stat and fstat will not give size of directory, here st_size of stat structure is set to zero when stat/fstat call is made on a directory file descriptor. creation time stamp size is not supported by symbian and hence it is set to zero.

Examples

/**
 * Detailed description  : Sample usage of stat system call
 * Preconditions : Example.txt file should be present in working directory
**/
#include <fcntl.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
int main()
{
  struct stat buf;
   if(stat("Example.txt", &buf) < 0 )
   {
      printf("Failed to stat Example.txt \n");
      return -1;
   }
   printf("Stat system call succeeded \n");
   return 0;
 }
/**
 * Detailed description  : Sample usage of fstat system call
 *
**/
#include <fcntl.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
int main()
{
  struct stat buf;
   int fd = open("Example.txt" , O_RDONLY | O_CREAT  , 0666);
   if(fstat(fd  , &buf) < 0 )
   {
      printf("Failed to stat Example.txt \n");
      return -1;
   }
   printf("Stat system call succeeded \n");
   close(fd);
   return 0;
 }

Output

Stat system call succeeded

Output

Stat system call succeeded

Compatibility

 Previous versions of the system used different types for the st_dev, st_uid, st_gid, st_rdev, st_size, st_blksize and st_blocks fields.

Errors

 The stat and lstat system calls will fail if:
[EACCES]
 | Search permission is denied for a component of the path prefix.
[EFAULT]
 | The sb or path argument points to an invalid address.
[EIO] | An I/O error occurred while reading from or writing to the file system.
[ELOOP]
 | Too many symbolic links were encountered in translating the pathname.
[ENAMETOOLONG]
 | A component of a pathname exceeded 255 characters, or an entire path name exceeded 1023 characters.
[ENOENT]
 | The named file does not exist.
[ENOTDIR]
 | A component of the path prefix is not a directory.
[EOVERFLOW]
 | The file size in bytes cannot be represented correctly in the structure pointed to by sb.

The fstat system call will fail if:
[EBADF]
 | The fd argument is not a valid open file descriptor.
[EFAULT]
 | The sb argument points to an invalid address.
[EIO] | An I/O error occurred while reading from or writing to the file system.
[EOVERFLOW]
 | The file size in bytes cannot be represented correctly in the structure pointed to by sb.

See also

 access, chmod, chown, utimes, symlink,
The stat and fstat system calls are expected to conform to -p1003.1-90.
The stat and fstat system calls appeared in AT&T v7. The lstat system call appeared in BSD 4.2.

Bugs

 Applying fstat to a socket (and thus to a pipe) returns a zeroed buffer, except for the blocksize field, and a unique device and inode number.

Feedback

For additional information or queries on this page send feedback


fsync

Name

fsync - synchronizes a file's complete in-core state with that on disk

Library

 libc.lib

Synopsis
#include <unistd.h>
int fsync (int fd);

Return values
.Rv -std fsync

Detailed description

 The fsync system call causes all modified data and attributes of fd to be moved to a permanent storage device. This normally results in all in-core modified copies of buffers for the associated file to be written to a disk.

The fsync system call should be used by programs that require a file to be in a known state, for example, in building a simple transaction facility.

Examples

/**
  * Detailed description : Simple usage of fsync system call.
  * Preconditions : Example.txt if present should not a ready-only file
**/
#include <unistd.h>
#include <fcntl.h>
int main()
{
  int fd = 0;
  fd = open("Example.txt" , O_CREAT | O_RDWR , 0666);
  if(fd < 0 )
  {
     printf("Failed to open file Example.txt \n");
     return -1;
  }
  if(fsync(fd) < 0 )
  {
     printf("fsync system call failed \n");
     return -1;
  }
  close(fd);
  printf("fsync system call succeeded \n");
  return 0;
}

Output

fsync system call succeeded

Errors

 The fsync fails if:
[EBADF]
 | The fd argument is not a valid descriptor.
[EINVAL]
 | The fd argument refers to a socket, not to a file.
[EIO] | An I/O error occurred while reading from or writing to the file system.

See also

 sync, syncer, sync
The fsync system call appeared in BSD 4.2.

Feedback

For additional information or queries on this page send feedback


ftok

Name

ftok - converts a pathname and a project identifier to a System V IPC key

Library

 libc.lib

Synopsis
#include <sys/types.h>
#include <sys/ipc.h>
key_t ftok (const char *path, int id);

Return values

 The ftok function will return -1 if path does not exist or if it cannot be accessed by the calling process. On success the generated key_t value is returned.

Detailed description

 The ftok function attempts to create a unique key suitable for use with the msgget, semget and shmget functions given the path of an existing file and a user-selectable id.

The specified path must specify an existing file that is accessible to the calling process or the call will fail. Also, note that links to files will return the same key, given the same id.

Examples

#include <sys/types.h>
#include <sys/ipc.h>
#include <stdio.h>

int main(void)
{
    char *pathame = "C:\\XXX";
    int proj_id = 100;
    key_t fkey;
    if ((fkey = ftok(pathame, proj_id)) == -1) {
        printf("ftok() failed\n");
    }
    return 0;
}

See also

 semget, shmget, msgget

Feedback

For additional information or queries on this page send feedback


fwide

Name

fwide - sets and determines the orientation of a FILE stream

Library

 libc.lib

Synopsis
#include <stdio.h>
#include <wchar.h>
int fwide (FILE *stream, int mode);

Return values

 The fwide function returns a value according to orientation after the call of fwide; a value less than zero if byte-oriented, a value greater than zero if wide-oriented, and zero if the stream has no orientation.

Detailed 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 unchanged. 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.

Examples

#include <stdio.h>
#include <wchar.h>
/* Illustrates how to use fwide API */
int example_fwide(void)
{
 FILE *fp = NULL;
 int retval;
 int mode;
 /* open a file */
 fp = fopen("input.txt","r");
 if(fp == NULL)
 {
  wprintf(L"Error: File open\n");
  return (-1);
 }
 /* set the mode to wide*/
 mode = 1;
 /* set the orientation of the file */
 retval = fwide(fp, mode);
 /*     check   the     return value */
 if(retval ==   1)
 {
        wprintf(L"Mode set to WIDE\n");
 }
 else
 {
        wprintf(L"Error setting the mode to wide!!\n");
 }
 /* set the mode to determine the orientation */
 mode = 0;
 /* Read back the orientation that was set */
 retval = fwide(fp ,mode);
 if(retval == 1)
 {
        wprintf("Mode not changed\n");
 }
 else
 {
        wprintf("Error, mode changed!!\n");
 }
 /* Close the file open for writing */
 fclose(fp);
 /* return the mode of fp */
 return (retval);
}

See also

 ferror, fgetc, fgetwc, fopen, fputc, fputwc, freopen

Feedback

For additional information or queries on this page send feedback


gai_strerror

Name

gai_strerror - network address and service translation

Synopsis
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
const char * gai_strerror (int ecode);

Return values

 The gai_strerror function returns a pointer to the error message string corresponding to ecode. If ecode is out of range, an implementation-specific error message string is returned.

Detailed description

 The gai_strerror function returns an error message string corresponding to the error code returned by getaddrinfo or getnameinfo.

The following error codes and their meaning are defined in
#include <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

Examples

#include <stdio.h>
#include <netdb.h>
#include <netinet/in.h>
int main()
{
      struct addrinfo *result;
      char hostname[80];
      int error;
      if (error = getaddrinfo("www.nokia.com",NULL, NULL, &result))
      {
              fprintf(stderr, "error using getaddrinfo: %s\n", gai_strerror(error));
      }
      if (result)
      {
              if (error = getnameinfo(result->ai_addr, sizeof(struct sockaddr), hostname, sizeof(hostname), NULL,0,0))
              {
                      printf( "error using getnameinfo: %s\n", gai_strerror(error));
              }
      }
return 0;
}

See also

 getaddrinfo, getnameinfo

Feedback

For additional information or queries on this page send feedback


getaddrinfo

Name

getaddrinfo, freeaddrinfo
- network address and service translation

Synopsis

 #include <sys/types.h> #include <sys/socket.h> #include <netdb.h>
int
.Fo getaddrinfo const char *hostname const char *servname const struct addrinfo *hints struct addrinfo **res
.Fc
void freeaddrinfo (struct addrinfo *ai);

Return values

 getaddrinfo returns zero on success or one of the error codes listed in gai_strerror if an error occurs.

Detailed description

 The getaddrinfo function is used to get a list of IP addresses and port numbers for host hostname and service servname. It is a replacement for and provides more flexibility than the gethostbyname and getservbyname functions.

The hostname and servname arguments are either pointers to NUL-terminated strings or the null pointer. An acceptable value for hostname is either a valid host name or a numeric host address string consisting of a dotted decimal IPv4 address. The servname is either a decimal port number or a service name listed in services. At least 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 */
};

This structure can be used to provide hints concerning the type of socket that the caller supports or wishes to use. The caller can supply the following structure elements in hints:
ai_family | The protocol family that should be used. When ai_family is set to PF_UNSPEC, it means the caller will accept any protocol family supported by 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 socket type.
ai_protocol | Indicates which transport protocol is desired, IPPROTO_UDP or IPPROTO_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 call to getaddrinfo will return a NUL-terminated string containing the canonical name of the specified hostname in the ai_canonname element of the first addrinfo structure returned.
AI_NUMERICHOST
 | If the AI_NUMERICHOST bit is set, it indicates that hostname should be treated as a numeric string defining an IPv4 address and no name resolution should be attempted.
AI_PASSIVE | If the AI_PASSIVE bit is set it indicates that the returned socket address structure is intended for use in a call to bind. In this case, if the hostname argument is the null pointer, then the IP address portion of the socket address structure will be set to INADDR_ANY for an IPv4 address If the AI_PASSIVE bit is not set, the returned socket address structure will be ready for use in a call to connect for a connection-oriented protocol or connect if a connectionless protocol was chosen. The IP address portion of the socket address structure will be set to the loopback address if hostname is the null pointer and AI_PASSIVE is not set.

All other elements of the addrinfo structure passed via hints must be zero or the null pointer.

If hints is the null pointer, getaddrinfo behaves as if the caller provided a struct addrinfo with ai_family set to PF_UNSPEC and all other elements set to zero or NULL.

After a successful call to getaddrinfo, *res is a pointer to a linked list of one or more addrinfo structures. The list can be traversed by following the ai_next pointer in each addrinfo 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 a call to socket For each addrinfo structure in the list, the ai_addr member points to a filled-in socket address structure of length ai_addrlen.

This implementation of

The current implementation assumes a one-to-one relationship between the interface and link, which is not necessarily true from the specification.

All of the information returned by getaddrinfo is dynamically allocated: the addrinfo structures themselves as well as the socket address structures and the canonical host name strings included in the addrinfo structures.

Memory allocated for the dynamically allocated structures created by a successful call to getaddrinfo is released by the freeaddrinfo function. The ai pointer should be a addrinfo structure created by a call to getaddrinfo.

Examples

#include <stdio.h>
#include <sys/types.h>
#include <netdb.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.
int main()
{
int error;
char *hostname=”www,yahoo.com”;
char *servname=”http”;
struct addrinfo hint;
struct addrinfo *res;
hint.ai_flags=AI_CANONNAME];
hint.ai_family=AF_INET;
hint.ai_socktype=SOCK_STREAM;
hint.ai_protocol=6];
error=getaddrinfo(hostname,servname,&hint,&res);
if (error)
printf(“getaddrinfo failed”);
else
printf(“getaddrinfo passed”);
freeaddrinfo(res);
return 0;
}

See also

 bind, connect, send, socket, gai_strerror, gethostbyname, getnameinfo, getservent
Protocol Independence Using the Sockets API
The getaddrinfo function is defined by the -p1003.1g-2000 draft specification and documented in RFC 3493, "Basic Socket Interface Extensions for IPv6."

Feedback

For additional information or queries on this page send feedback


getc

Name

fgetc, getc, getc_unlocked, getchar, getchar_unlocked, getw
- input of characters and strings

Library

 libc.lib

Synopsis
#include <stdio.h>
int fgetc (FILE *stream);
int getc (FILE *stream);
int getc_unlocked (FILE *stream);
int getchar ();
int getchar_unlocked (void);
int getw (FILE *stream);

Return values

 If successful, these routines return the next requested object from the stream. Character values are returned as an unsigned char converted to an int. If the stream is at end-of-file or a read error occurs, the routines return EOF. The routines and ferror must be used to distinguish between end-of-file and error. If an error occurs, the global variable errno is set to indicate the error. The end-of-file condition is remembered, even on a terminal, and all subsequent attempts to read will return EOF until the condition is cleared with

Detailed description

 The fgetc function obtains the next input character (if present) from the stream pointed at by stream, or the next character pushed back on the stream via ungetc.

The getc function acts essentially identically to fgetc, but is a macro that expands in-line.

The getchar function is equivalent to getc (stdin.);

The getw function obtains the next int (if present) from the stream pointed at by stream.

The getc_unlocked and getchar_unlocked functions are equivalent to getc and getchar respectively, except that the caller is responsible for locking the stream with flockfile before calling them. These functions may be used to avoid the overhead of locking the stream for each character, and to avoid input being dispersed among multiple threads reading from the same stream.

Examples

/****************** this program shows reading from file using getc **************/
/****************** consider input.txt has the following content: ****************/
/****************** hi ***********************************************************/
#include <stdio.h>
int main(void)
{
        int retval;
        FILE* fp = fopen("c:\\input.txt", "w");
        fprintf(fp, "%s", "abcdefghijklmn");
        fprintf(fp, "%c", ’\n’);
        fprintf(fp, "%s", "fdsfdsafsdabcdefghijklmn");
        fclose(fp);
        fp = fopen("C:\\input.txt","r");
        if(fp == NULL)
        {
        printf("fopen failed\n");
        return -1;
        }
        while((int)(retval = getc(fp) )!= EOF)
        {
        printf("%c", retval);
        }
        fclose(fp);
        return 0;
}

Output

hi

See also

 ferror, flockfile, fopen, fread, getwc, putc, ungetc

Limitation

 Since EOF is a valid integer value, feof and ferror must be used to check for failure after calling getw. The size and byte order of an int varies from one machine to another, and getw is not recommended for portable applications.

Feedback

For additional information or queries on this page send feedback


getcwd

Name

getcwd - gets current working directory

Library

 libc.lib

Synopsis
#include <unistd.h>
char * getcwd (char *buf, size_t size);

Return values

 Upon successful completion, a pointer to the pathname is returned. Otherwise a NULL 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 memory referenced by buf.

Detailed description

 The getcwd function copies the absolute pathname of the current working directory into the memory referenced by buf and returns a pointer to buf. The size argument is the size, in bytes, of the array referenced by buf.

If buf is NULL, space is allocated as indicated by size to store the pathname and the current working directory is returned as long as the size bytes are sufficient to hold the working directory name. This space may later be free’d.

This routine has traditionally been used by programs to save the name of a working directory for the purpose of returning to it. A much faster and less error-prone method of accomplishing this is to open the current directory (‘.’) and use the fchdir function to return.

Examples

#include<unistd.h>
#include<stdio.h>
#include <stdlib.h>
#define BUF_SIZE 100

int main()
{
 //change directory to c:
 int c;
 long size = BUF_SIZE;
 char *buf = NULL;
 char *ptr = NULL;

 c = chdir("c:\\");

 buf = (char *)malloc((size_t)size);

 if (buf != NULL && c == 0)
 {
  //call getcwd to fetch teh current directory
  ptr = getcwd(buf, (size_t)size);
  printf("getcwd returned: %s\n", ptr);
 }

 return 0;
}

Output

getcwd returned: c:

Errors

 The getcwd function will fail if:
[EACCES]
 | Read or search permission was denied for a component of the pathname.
[EINVAL]
 | The size argument is zero and buf is not a null pointer.
[ENOENT]
 | A component of the pathname no longer exists.
[ENOMEM]
 | Insufficient memory is available.
[ERANGE]
 | The size argument is less than the length of the working directory name. Allocate a bigger array and try again.

Notes

 The getcwd function returns the default working directory as c:\private\XXXXXXXX (where XXXXXXXX is the UID of the process) as the default session path is initialised to c:\private\current_process’_UID, in case of symbian.

See also

 chdir, malloc, strerror

Feedback

For additional information or queries on this page send feedback


getdirentries

Name

getdirentries - gets directory entries in a filesystem independent format

Library

 libc.lib

Synopsis
#include <sys/types.h>
#include <dirent.h>
int getdirentries (int fd, char *buf, int nbytes, long *basep);

Return values

 If successful, the number of bytes actually transferred is returned. Otherwise, -1 is returned and the global variable errno is set to indicate the error.

Detailed description

 The getdirentries system call read directory entries from the directory referenced by the file descriptor fd into the buffer pointed to by buf, in a file system independent format. Up to nbytes of data will be transferred. The nbytes argument must be greater than or equal to the block size associated with the file, see stat. Some file systems may not support these system calls with buffers smaller than this size.

The data in the buffer is a series of dirent structures each containing the following entries:

u_int32_t d_fileno;
u_int16_t d_reclen;
u_int8_t  d_type;
u_int8_t  d_namlen;
char      d_name[MAXNAMELEN + 1];       /* see below */

The d_fileno entry is a number which is unique for each distinct file in the file system. Files that are linked by hard links (see link) have the same d_fileno. The d_reclen entry is the length, in bytes, of the directory record. The d_type entry is the type of the file pointed to by the directory record. The file type values are defined in <sys/dirent.h>. Presently, file type is not supported. d_type entry is set to 0. The d_name entry contains a null terminated file name. The d_namlen entry specifies the length of the file name excluding the null byte. Thus the actual size of d_name may vary from 1 to MAXNAMELEN + 1.

Entries may be separated by extra space. The d_reclen entry may be used as an offset from the start of a dirent structure to the next structure, if any.

The actual number of bytes transferred is returned. The current position pointer associated with fd is set to point to the next block of entries. The pointer may not advance by the number of bytes returned by getdirentries A value of zero is returned when the end of the directory has been reached.

The getdirentries system call writes the position of the block read into the location pointed to by basep. Alternatively, the current position pointer may be set and retrieved by lseek. The current position pointer should only be set to a value returned by lseek, a value returned in the location pointed to by basep ( (getdirentries);
only) or zero.

Examples

/****************** reading directory stream using getdirenttries *******************/
/****************** considering directory c:    emp already exists ********************/
#include <stdio.h>
int main()
{
        int retval;
        long basep=(off_t) 0;
        char buf[1024];
        struct dirent * d;
        char * dname="C:\       emp\
        char * fname="C:\       emp\\input.txt";
        int fd,fd1;
        fd1=open(fname,O_WRONLY|O_CREAT);
        if(fd==-1)
                {
                printf("file creation failed\n");
                return -1;
                }
        fd=open(dname,O_RDONLY);
        if(fd==-1)
                {
                printf("directory opening failed\n");
                return -1;
                }
        retval = getdirentries (fd, buf,(unsigned int)sizeof (buf),&basep);
        if(retval == -1)
        {
                printf("getdirentries call failed\n");
                return -1;
        }

        d=(struct dirent *)buf;

        printf("name of the file in the newly created directory is \"%s\"\n",d-d_name);

        close(fd1);
        close(fd);
        return 0;
}

Output

name of the file in the newly created directory is "input.txt"

Errors

 The getdirentries system call will fail if:
[EBADF]
 | The fd argument is not a valid file descriptor open for reading.
[EFAULT]
 | Either buf or basep point outside the allocated address space.
[EINVAL]
 | The file referenced by fd is not a directory, or nbytes is too small for returning a directory entry or block of entries, or the current position pointer is invalid.
[EIO] | An I/O error occurred while reading from or writing to the file system.

See also

 lseek, open

Feedback

For additional information or queries on this page send feedback


getdtablesize

Name

getdtablesize - get descriptor table size

Library

 libc.lib

Synopsis
#include <unistd.h>
int getdtablesize (void);

Return values

Detailed description

 Each process has a fixed size descriptor table, which is guaranteed to have at least 20 slots. The entries in the descriptor table are numbered with small integers starting at 0. The getdtablesize system call returns the size of this table.

Examples

#include <stdio.h>
int main()
{
        printf("maximum number of files that can be opened by a process is %d\n",getdtablesize());
}

Output

maximum number of files that can be opened by a process is 1024

See also

 close, dup, open

Feedback

For additional information or queries on this page send feedback


getenv

Name

getenv, putenv, setenv, unsetenv
- environment variable functions

Library

 libc.lib

Synopsis
#include <stdlib.h>
char * getenv (const char *name);
int setenv (const char *name, const char *value, int overwrite);
int putenv (const char *string);
void unsetenv (const char *name);

Return values

 The getenv function returns the value of the environment variable as a NUL -terminated string. If the variable name is not in the current environment, NULL is returned.

The setenv and putenv functions return the value 0 if successful; otherwise the value -1 is returned and the global variable errno is set to indicate the error.

The unsetenv function never returns.

Detailed description

 These functions set, unset and fetch environment variables from the host environment list. For compatibility with differing environment conventions, the given arguments name and value may be appended and prepended, respectively, with an equal sign "=."

The getenv function obtains the current value of the environment variable, name.

The setenv function inserts or resets the environment variable name in the current environment list. If the variable name does not exist in the list, it is inserted with the given value. If the variable does exist, the argument overwrite is tested; if overwrite is 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 equivalent to:

setenv(name, value, 1);

The unsetenv function deletes all instances of the variable name pointed to by name from the list.

Examples

#include <stdlib.h> //getenv
#include <stdio.h> //printf

int main( void )
{
  int iret = putenv("PATH=c:\sys\bin;");

  if( iret == -1)
     printf( "putenv() failed!!\n" );

   /* fetch new value. */
  char *psc = getenv("PATH");

  if( psc != NULL )
      printf( "new PATH variable is: %s\n", psc );

  return 0;
}

Output

new PATH variable is: c:\sys\bin;

#include <stdlib.h> //setenv, getenv
#include <stdio.h> //printf

int main( void )
{
   char *var;

   /* Unset the value of the HOME environment variable
    * to make sure that it is non-existing.
    */
   unsetenv( "HOME" );

   /* Set the value of HOME environment with no overwrite option */
   int iret = setenv("HOME", "/home", 0);

   if(iret == -1)
      printf( "Setenv failed!!" );

   /* Get new value. */
   var = getenv( "HOME" );

   if( var != NULL )
      printf( "new HOME variable is: %s\n", var );

   /* Set the value of HOME environment with the overwrite option */
   iret = setenv("HOME", "/check", 1);

   /* Get new value. */
   var = getenv( "HOME" );

   if( var != NULL )
      printf( "new HOME variable is: %s\n", var );

   return 0;
}

Output

new HOME variable is: \home
new HOME variable is: \check

Errors
[ENOMEM]
The function setenv or putenv failed because they were unable to allocate memory for the environment.

Feedback

For additional information or queries on this page send feedback


getgid

Name

getgid, getegid
- get group identity

Library

 libc.lib

Synopsis
#include <sys/types.h>
#include <unistd.h>
gid_t getgid (void);
gid_t getegid (void);

Return values

 These functions always return 0.

Detailed description

 getgid and getegid are functions belonging to set of APIs which are only build supported and not available functionally. The reason why only build support is extended to these APIs is, symbian operating system does not support creation of multiple users and groups in its environment. More over it may not make sense to have multiple users and groups in the context of a mobile environment.

Errors

 No error values are set.

See also

Feedback

For additional information or queries on this page send feedback


getgrent

Name

getgrent, getgrnam, getgrnam_r, getgrgid, getgrgid_r, setgroups,setgrent, endgrent
- get group file entry

Library

 libc.lib

Synopsis
#include <grp.h>
struct group * getgrent (void);
struct group * getgrnam (const char *name);
int getgrnam_r (const char *name, struct group *grp, char *buffer, size_t bufsize, struct group **result);
struct group * getgrgid (gid_t gid);
int getgrgid_r (gid_t gid, struct group *grp, char *buffer, size_t bufsize, struct group **result);
int setgroups (int n, const gid_t* ngroups);
int setgrent (void);
void endgrent (void);

Return values

 The functions getgrent, getgrnam, and getgrgid, return a pointer to a group structure on success or NULL if the entry is not found or if an error occurs. If an error does occur, errno will be set. The functions getgrnam_r and getgrgid_r return 0 if no error occurred, or an error number to indicate failure. It is not an error if a matching entry is not found. (Thus, if result is set to NULL and the return value is 0, no matching entry exists.)

The setgrent return the value 1 if successful, otherwise the value 0 is returned. The endgrent API has no return value.

Detailed description

 These APIs belongs to set which are only build supported and not available functionally. The reason why only build support is extended to these APIs is that Symbian operating system does not support the creation of multiple users and groups in its environment. Moreover it may not make sense to have multiple users and groups in the context of a mobile environment.

We refer to the structure group found in the include file
#include <grp.h>
struct group {
        char    *gr_name;       /* group name */
        char    *gr_passwd;     /* group password */
        gid_t   gr_gid;         /* group id */
        char    **gr_mem;       /* group members */
};

The functions getgrnam and getgrgid returns the default values for a single user system i.e., gr_name,gr_passwd,gr_gid set to root,NULL and 0 respectively and gr_mem has just one entry,that of root as a single user in case the input parameter gid/name is 0/ root else the error number is set and NULL is returned by the APIs.

The getgrent when called the first time by an application returns the pointer to a valid group, that of the simulated single-user group.Subsequent calls return NULL until setgrent is called

The functions getgrnam_r, and getgrgid_r are thread-safe versions of getgrnam, and getgrgid respectively. The caller must provide storage for the results of the search in the grp, buffer, bufsize, and result arguments. When these functions are successful, the grp argument will be filled-in, and a pointer to that argument will be stored in result. If an entry is not found or an error occurs, result will be set to NULL.

The setgrent function sets the library such that subsequent getgrent call returns a filled group structure.

The endgrent function sets up the library such that the subsequent getgrent call returns NULL. The setgroups API returns success status just for the sake of build support.The actual function cannot be supported.

Examples

#include <grp.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
/*A user function that takes gid as parameter to call getgrgid
Can be replaced by function that takes char* grnam to call getgrnam*/
void grgid_user(int gid)
{
        struct group* gr_gid;   /*This struct is filled by the getgrgid call*/
        setgrent ();            /*Set read to start of database*/
        /*Call to getgrgid with gid as parameter..could also be replaced with getgrnam
        with grnam as parameter*/
        gr_gid = getgrgid (gid);
        if(gr_gid == NULL)      /*End of database reached*/
                return;
        else
                printf ("For gid = %d ,group name = %s", gid, gr_gid->gr_name); /*Print a valid group name*/
        endgrent ();            /*Set the read pointer to the end of database*/
        /*In case of our library,the user has to free the resources allocated
        by the API call itself*/
        free (gr_gid->gr_mem);
        free (gr);
}

Output

For gid = 0 ,group name = root

#include <grp.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
/*A user function that takes char* grnam as parameter to call getgrnam_r
Can be replaced by function that takes int gid to call getgrgid_r*/
void grgid_r_user(char* grnam)
{
        /*We have to allocate memory for the structures for the getgrnam_r thread-safe call*/
        struct group* gr_nam = (struct group*)malloc (sizeof (struct group));
        gr_nam->gr_mem = (char**)malloc (sizeof(char**));
        char* buffer=(char*)malloc(sizeof(struct group));
        size_t bufsize=sizeof(buffer);
        struct group* tempresult;
        int result;
        setgrent ();            /*Set read to start of database*/
        /*Call to getgrnam_r with grnam as parameter..could also be replaced with getgrgid_r
        with grgid as parameter*/
        int result=getgrnam_r(grnam, gr_nam, buffer, bufsize, &tempresult);
        if(result != 0) /*End of database reached*/
                return;
        else
                printf ("For grnam = %s ,group id = "%d", grnam, gr_nam->gr_gid); /*Print a valid group name*/
        endgrent ();            /*Set the read pointer to the end of database*/
        /*The user has to free the resources allocated*/
        free(buffer);
        free (gr_gid->gr_mem);
        free (gr);
}

Output

For grnam = root ,group id = 0

#include <grp.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
/*A user function that takes calls getgrent API*/
void getgrent_user()
{
        struct group* gr_ent;   /*This struct is filled by the getgrent call*/
        setgrent ();            /*Set read to start of database*/
        /*Call to getgrent */
        gr_ent = getgrent ();
        if(gr_ent == NULL)      /*End of database reached*/
                return;
        else
                /*Print a valid group name*/
                printf ("gid = %d ,group name = %s", gr_ent->gid, gr_ent->gr_name);
        endgrent ();            /*Set the read pointer to the end of database*/
        /*In case of our library,the user has to free the resources allocated
        by the API call itself*/
        free (gr_ent->gr_mem);
        free (gr_ent);
}

Output

gid = 0 ,group name = root

Errors

 The getgrgid,getgrnam will fail if:
[ERANGE]
 | Not enough memory to allocate the structures.
[ENOENT]
 | If an invalid gid or grnam is passed to the APIs. The getgrgid_r,getgrnam_r will fail if:
[ENOENT]
 | If an invalid gid or grnam is passed to the APIs.

Feedback

For additional information or queries on this page send feedback


getgroups

Name

getgroups - gets list of supplementary group IDs

Library

 libc.lib

Synopsis
#include <sys/types.h>
#include <unistd.h>
int getgroups (int gidsetlen, gid_t *gidset);

Return values

 These functions always return 0.

Detailed description

 The getgroups function belongs to set of APIs which are only build supported and not available functionally. The reason why only build support is extended to these APIs is, symbian operating system does not support creation of multiple users and groups in its environment. More over it may not make sense to have multiple users and groups in the context of a mobile environment.

Errors

 No error values are set.

See also

Feedback

For additional information or queries on this page send feedback


gethostbyname

Name

gethostbyname, gethostbyaddr
- get network host entry

Library

 libc.lib

Synopsis
#include <netdb.h>
struct hostent * gethostbyname (const char *name);
struct hostent * gethostbyaddr (const char *addr, int len, int type);

Return values

 gethostbyname, and gethostbyaddr returns NULL if an error occurs or else will return a valid hostent structure

Detailed description

 The

The gethostbyname, and gethostbyaddr functions each return a pointer to an object with the following structure describing an internet host referenced by name or by address, respectively.

The name argument passed to gethostbyname should point to a NUL -terminated hostname. The addr argument passed to gethostbyaddr should point to an address which is len bytes long, in binary form (i.e., not an IP address in human readable ASCII form). The type argument specifies the address family (e.g. AF_INET, etc.) of this address.

The structure returned contains either the information obtained from the name server,

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 backward 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 compatibility.

When using the nameserver, gethostbyname will search for the named host in the current domain and its parents unless the name ends in a dot.

getaddrinfo and getnameinfo functions are preferred over the gethostbyname, and gethostbyaddr functions.

Examples

#include<stdio.h>
#include<arpa/inet.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <string.h>
Int main()
{
struct hostent *hp = 0;
char *test_url=www.google.com:
hp = gethostbyname(test_url);
if(hp==NULL)
printf(“gethostbyname failed”):
else
printf(“gethostbyname passed”);
return 0;
}

Output

Gethostbyname passed

#include<stdio.h>
#include<arpa/inet.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <string.h>
#define urlsize 50
Int main()
{
struct hostent *hp = 0;
char addr[256];
unsigned long  test_addr;
strcpy(addr,” 147.243.3.83”);
test_addr=inet_addr(addr);
struct hostent *hp;
hp=gethostbyaddr((const char *)&test_addr,sizeof(test_addr),AF_INET);
if(hp)
printf(“DNS query resolved”);
else
printf(“gethostbyaddr failed”);
return 0;
}

Diagnostics

 Error return status from gethostbyname and gethostbyaddr is indicated by return of a NULL pointer. The external integer h_errno may then be checked to see whether this is a temporary failure or an invalid or unknown host. The routine If its argument string is non- NULL, it is printed, followed by a colon and a space. The error message is printed with a trailing newline.

The variable h_errno can have the following values:
TRY_AGAIN | This is usually a temporary error and means that the local server 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 a non-recoverable error.

See also

 getaddrinfo, getnameinfo

Caveat

Bugs

 These functions use a thread-specific data storage; if the data is needed for future use, it should be copied before any subsequent calls overwrite it.

Though these functions are thread-safe, still it is recommended to use the getaddrinfo family of functions, instead.

Only the Internet address format is currently understood.

Feedback

For additional information or queries on this page send feedback


getnameinfo

Name

getnameinfo - address-to-name translation in protocol-independent manner

Synopsis

 #include <sys/types.h> #include <sys/socket.h> #include <netdb.h>
int
.Fo getnameinfo const struct sockaddr *sa socklen_t salen char *host size_t hostlen char *serv size_t servlen int flags
.Fc

Return values

 getnameinfo returns zero on success or one of the error codes listed in gai_strerror if an error occurs.

Detailed description

 The getnameinfo function is used to convert a sockaddr structure to a pair of host name and service strings. It is a replacement for and provides more flexibility than the gethostbyaddr and getservbyport functions and is the converse of the getaddrinfo function.

The sockaddr structure sa should point to sockaddr_in (for IPv4) that is salen bytes long.

The host and service names associated with sa are stored in host and serv which have length parameters hostlen and servlen. The maximum value for hostlen is 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 byte for 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 returned instead.
NI_NUMERICHOST | Return the address in numeric form, as if calling inet_ntop, instead of a host name.
NI_NAMEREQD | A name is required. If the host name cannot be found in DNS and this flag is set, a non-zero error code is returned. If the host name is not found and the flag is not set, the address is returned in numeric form.
NI_NUMERICSERV | The service name is returned as a digit string representing the port number.
NI_DGRAM | Specifies that the service being looked up is a datagram service, and causes getservbyport to be called with a second argument of "udp" instead of its default of "tcp." This is required for the few ports (512-514) that have different services for UDP and TCP.

Examples

#include <stdio.h>
#include <netdb.h>
#include <netinet/in.h>
int main()
{
     struct addrinfo *result;
     char hostname[80];
     int error;
     if (error = getaddrinfo("www.yahoo.com",NULL, NULL, &result))
     {
            fprintf(stderr, "error using getaddrinfo: %s\n", gai_strerror(error));
     }
     if (result)
     {
            if (error = getnameinfo(result->ai_addr, sizeof(struct sockaddr), hostname, sizeof(hostname), NULL,0,0))
            {
                   printf( "error using getnameinfo: %s\n", gai_strerror(error));
            }
    }
return 0;
}

See also

 gai_strerror, getaddrinfo, inet_ntop
Basic Socket Interface Extensions for IPv6
Protocol Independence Using the Sockets API
The getnameinfo function is defined by the -p1003.1g-2000 draft specification and documented in RFC 2553, "Basic Socket Interface Extensions for IPv6."

Caveats

 getnameinfo can return both numeric and FQDN forms of the address specified in sa. There is no return value that indicates whether the string returned in host is a result of binary to numeric-text translation (like inet_ntop or is the result of a DNS reverse lookup. Because of this, malicious parties could set up a PTR record as 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 is actually 127.0.0.1.

To prevent such attacks, the use of NI_NAMEREQD is recommended when the result of getnameinfo is used for access control purposes:

struct sockaddr *sa;
socklen_t salen;
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);
}

Feedback

For additional information or queries on this page send feedback


getopt

Name

getopt - parses command line options

Library

 libc.lib

Synopsis
#include <unistd.h>

extern char *optarg;

extern int optind;

extern int optopt;

extern int opterr;

extern int optreset;

int getopt (int argc, char * const argv[], const char *optstring);

Return values

 The getopt function returns the next known option character in optstring. If getopt encounters a character not found in optstring or if it detects a missing option argument, it returns ‘?’ (question mark. If optstring has a leading ‘:’ then a missing option argument causes ‘:’ to be returned instead of ‘?.’ In either case, the variable optopt is set to the character that caused the error. The getopt function returns -1 when the argument list is exhausted.

Detailed description

 The getopt function incrementally parses a command line argument list argv and returns the next known option character. An option character is known if it has been specified in the string of accepted option characters, optstring.

The option string optstring may contain the following elements: individual characters, 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." It does not matter to getopt if a following argument has leading white space.

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 subsequent call to getopt. The variable optopt saves the last known option character returned by getopt.

The variables opterr and optind are both initialized to 1. The optind variable may be set to another value before a set of calls to getopt in order to skip over more or less argv entries.

In order to use getopt to evaluate multiple sets of arguments, or to evaluate a single set of arguments multiple times, the variable optreset must be set to 1 before the second and each additional set of calls to getopt, and the variable optind must be reinitialized.

The getopt function returns -1 when the argument list is exhausted. The interpretation of options in the argument list may be cancelled by the option ‘--’ (double dash) which causes getopt to signal the end of argument processing and return -1. When all options have been processed (i.e., up to the first non-option argument), getopt returns -1.

Examples

#include <unistd.h>
#include <stdio.h>
#include <fcntl.h>
#include <errno.h>
#include <string.h>

int main()
{
        int argc = 3;

        char *argv[] =
         {
                 "getopt","-f","hi"
         };

        int bflag, ch, fd;
        bflag = 0;

        while ((ch = getopt(argc, argv, "bf:")) != -1) {

        switch (ch) {
        case 'b':
                bflag = 1;
                printf("option is 'b' \n");
                break;
        case 'f':
                printf("option is 'f' \n");
                if ((fd = open(optarg, O_RDONLY, 0)) != 0) {
                        (void)fprintf(stderr,
                           "myname: %s: %s\n", optarg, strerror(errno));
                }
                break;
        case '?':
                printf("missing option!");
        default:
                printf("unknown option!");
        }

}
argc -= optind;
return 0;
}

Output

option is ’f’
myname: hi: No such file or directory

Security considerations

 The getopt function can be misused by a malicious user to arbitrarily change the functionality of a program under execution using the buffer overflow attack.

Diagnostics

 If the getopt function encounters a character not found in the string optstring or detects a missing option argument it writes an error message to the stderr and returns ‘?.’ Setting opterr to a zero will disable these error messages. If optstring has a leading ‘:’ then a missing option argument causes a ‘:’ to be returned in addition to suppressing any error messages.

Option arguments are allowed to begin with "-"; this is reasonable but reduces the amount of error checking possible.

See also

 getopt_long,

Bugs

 The getopt function was once specified to return EOF instead of -1. This was changed by -p1003.2-92 to decouple getopt from
#include <stdio.h>

A single dash "-" may be specified as a character in optstring, however it should never have an argument associated with it. This allows getopt to be used with programs that expect "-" as an option flag. This practice is wrong, and should not be used in any current development. It is provided for backward compatibility only. Care should be taken not to use ‘-’ as the first character in optstring to avoid a semantic conflict with GNU getopt, which assigns different meaning to an optstring that begins with a ‘-.’ By default, a single dash causes getopt to return -1.

It is also possible to handle digits as option letters. This allows getopt to be used with 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 backward compatibility only. The following code fragment works in most cases.

int ch;
long length;
char *p, *ep;
while ((ch = getopt(argc, argv, "0123456789")) != -1)
        switch (ch) {
        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] == ’-’ Am]Am] p[1] == ch Am]Am] !p[2]) {
                        length = ch - ’0’;
                        ep = "";
                } else if (argv[optind] Am]Am] argv[optind][1] == ch) {
                        length = strtol((p = argv[optind] + 1),
                            Am]ep, 10);
                        optind++;
                        optreset = 1;
                } else
                        usage();
                if (*ep != ’\0’)
                        errx(EX_USAGE, "illegal number -- %s", p);
                break;
        }

Feedback

For additional information or queries on this page send feedback


getopt_long

Name

getopt_long - parses command line options

Library

 libc.lib

Synopsis
#include <getopt.h>

extern char *optarg;

extern int optind;

extern int optopt;

extern int opterr;

extern int optreset;

int getopt_long (int argc, char * const *argv, const char *optstring, const struct option *longopts, int *longindex);

Return values

 If the flag field in struct option is NULL, getopt_long returns the value specified in the val field, which is usually just the corresponding short option. If flag is not NULL, this function returns 0 and stores val in the location pointed to by flag. This function returns ‘:’ if there was a missing option argument, ‘?’ if the user specified an unknown or ambiguous option, and -1 when the argument list has been exhausted.

Detailed description

 The getopt_long function is similar to getopt but it accepts options in two forms: words and characters. The getopt_long function provides a superset of the functionality of getopt. The getopt_long function can be used in two ways. In the first way, every long option understood by the program has a corresponding short option, and the option structure is only used to translate from long options to short options. When used in this fashion, getopt_long behaves identically to getopt. This is a good way to add long option processing to an existing program with the minimum of rewriting.

In the second mechanism, a long option sets a flag in the option structure passed, or will store a pointer to the command line argument in the option structure passed to it for options that take arguments. Additionally, the long option’s argument may be specified as a single argument with an equal sign, e.g.,

     myprogram --myoption=somevalue
When a long option is processed, the call to getopt_long will return 0. For this reason, long option processing without shortcuts is not backwards compatible with getopt. It is possible to combine these methods, providing for long options processing with short option equivalents for some options. Less frequently used options would be processed as long options only. The getopt_long call requires a structure to be initialized describing the long options. The structure is:
struct option {
        char *name;
        int has_arg;
        int *flag;
        int val;
};

The name field should contain the option name without the leading double dash.

The has_arg field should be one of:

no_argument | no argument to the option is expect
required_argument
 | an argument to the option is required
optional_argument
 | an argument to the option may be presented.

If flag is not NULL, then the integer pointed to by it will be set to the value in the val field. If the flag field is NULL, then the val field will be returned. Setting flag to NULL and setting val to the corresponding short option will make this function act just like getopt.

If the longindex field is not NULL, then the integer pointed to by it will be set to the index of the long option relative to longopts.

The last element of the longopts array has to be filled with zeroes.

Examples

#include <unistd.h>
#include <stdio.h>
#include <fcntl.h>
#include <getopt.h>
#include <errno.h>
int main()
{
    int bflag, ch, fd;
    int daggerset;

    int argc = 3;

    char *argv[] = { "getopt", "--daggerset","hi" };

    struct option  longopts[] = {
      { "buffy",      no_argument,            NULL,           'b' },
      { "fluoride",   required_argument,      NULL,           'f' },
      { "daggerset",  no_argument,           &daggerset,   1 },
      { NULL,         0,                      NULL,           0 }
    };

    bflag = 0;

    while ((ch = getopt_long(argc, argv, "bf:", longopts, NULL)) != -1) {
        switch (ch) {

                case 'b':
                    printf("option is \"buffy\"\n");
                bflag = 1;
                break;

                case 'f':
                    printf("option is \"fluoride\"\n");
                if ((fd = open(optarg, O_RDONLY, 0)) == -1)
                        printf("unable to open %s", optarg);
                break;

                case 0:
                if (daggerset) {
                        fprintf(stderr,"Buffy will use her dagger to apply \nfluoride to dracula's teeth\n");
                }
                break;
          default:
                printf("unknown option\n");

        }//end of switch
    }//end of while

return 0;
}

Output

Buffy will use her dagger to apply fluoride to dracula’s teeth

See also

 getopt

Feedback

For additional information or queries on this page send feedback


getpagesize

Name

getpagesize - get memory page size

Library

 libc.lib

Synopsis
#include <unistd.h>
int getpagesize (void);

Detailed description

 The getpagesize function returns the number of bytes in a page. Page granularity is the granularity of many of the memory management calls.

The page size is a system page size and may not be the same as the underlying hardware page size.

Examples

#include<unistd.h>
#include<stdio.h>
int test_getpagesize()
{
   int retVal = 0;
   retVal = getpagesize();
   if( retVal >= 0)
   {
      printf("getpagesize passed");
      printf("\n retVal  = %d " retVal);
      return retVal;
   }
   else
   {
   printf("Failed");
   return -1;
   }
}

Output

getpagesize passed
retVal = 4096

See also

 sbrk

Feedback

For additional information or queries on this page send feedback


getpeername

Name

getpeername - gets name of connected peer socket

Library

 libc.lib

Synopsis
#include <sys/types.h>
#include <sys/socket.h>
int getpeername (int s, struct sockaddr * restrict name, socklen_t * restrict namelen);

Return values

 The getpeername() function returns the value 0 if successful; otherwise the value -1 is returned and the global variable errno is set to indicate the error.

Detailed description

 The getpeername system call returns the name of the peer connected to socket s. The namelen argument 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 is truncated if the buffer provided is too small.

Examples

#include <sys/socket.h>
#include <netinet/in.h>
#include <unistd.h>
void GetSockName()
{
   int sock_fd;
   int newsock_fd;
   struct sockaddr_in addr;
   struct sockaddr_in ss;
   struct sockaddr_in new_socket;
   unsigned int len;
   unsigned int addr_len;

   sock_fd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);

   addr.sin_family = AF_INET;
   addr.sin_addr.s_addr = htonl(INADDR_ANY);
   addr.sin_port = htons(5000);
   bind(sock_fd,(struct sockaddr*)&addr,sizeof(addr));
   listen(sock_fd,1);
   newsock_fd = accept(sock_fd,(struct sockaddr*)&new_socket,&addr_len); // Code blocks here

   // Assuming client has connected to the server.
   len = sizeof(ss);
   getpeername(sock_fd,(struct sockaddr*)&ss,&len);
   close(newsock_fd);
   close(sock_fd);
 }

Errors

 The call succeeds unless:
[EBADF]
 | The argument s is not a valid descriptor.
[ECONNRESET]
 | The connection has been reset by the peer.
[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 the operation.
[EFAULT]
 | The name argument points to memory not in a valid part of the process address space.
[EINVAL]
 | The namelen argument is invalid.

See also

 accept, bind, getsockname, socket
The getpeername system call appeared in BSD 4.2.

Feedback

For additional information or queries on this page send feedback


getpgid

Name

getpgrp, getpgid
- get process group

Synopsis
#include <unistd.h>
pid_t getpgrp (void);
pid_t getpgid (pid_t pid);

Return values

 These functions always return 0.

Detailed description

 getpgrp and getpgid are functions belonging to set of APIs which are only build supported and not available functionally. The reason why only build support is extended to these APIs is, symbian operating system does not support creation of multiple users and groups in its environment. More over it may not make sense to have multiple users and groups in the context of a mobile environment.

Errors

 No error values are set.

See also

Feedback

For additional information or queries on this page send feedback


getpgrp

Name

getpgrp - gets process group

Library

 libc.lib

Synopsis
#include <unistd.h>
pid_t getpgrp (void);
pid_t getpgid (pid_t pid);

Return values

 These functions always return 0.

Detailed description

 getpgrp and getpgid are functions belonging to set of APIs which are only build supported and not available functionally. The reason why only build support is extended to these APIs is, symbian operating system does not support creation of multiple users and groups in its environment. More over it may not make sense to have multiple users and groups in the context of a mobile environment.

Errors

 No error values are set.

See also

Feedback

For additional information or queries on this page send feedback


getpid

Name

getpid, getppid
- get process identification

Library

 libc.lib

Synopsis
#include <sys/types.h>
#include <unistd.h>
pid_t getpid (void);
pid_t getppid (void);

Detailed description

 The getpid system call returns the process ID of the calling process. Though the ID is guaranteed to be unique, it should NOT be used for constructing temporary file names, for security reasons; see mkstemp instead.

The getppid system call returns the process ID of the parent of the calling process.

Examples

/**
 * Detailed description : Sample usage of getpid system call
 **/
#include <unistd.h>
int main()
{
  pid_t pid ;
  if((pid = getpid()) < 0 )
  {
     printf("getpid system call failed \n") ;
     return -1 ;
  }
  printf("pid of this process is %d \n " , pid) ;
  return 0 ;
}

Errors

 The getpid and getppid system calls are always successful, and no return value is reserved to indicate an error.

See also

Feedback

For additional information or queries on this page send feedback


getpriority

Name

getpriority, setpriority
- get/set program scheduling priority

Library

 libc.lib

Synopsis
#include <sys/time.h>
#include <sys/resource.h>
int getpriority (int which, int who);
int setpriority (int which, int who, int prio);

Return values

 Since getpriority can legitimately return the value -1, it is necessary to clear the external variable errno prior to the call, then check it afterward to determine if a -1 is an error or a legitimate value.

The setpriority returns 0 on success and -1 on error with the errno set.

Detailed description

 The scheduling priority of the process, process group, or user, as indicated by which and who is obtained with the getpriority system call and set with the setpriority system call. The which argument is one of PRIO_PROCESS, PRIO_PGRP, or PRIO_USER, and who is interpreted relative to which (a process identifier for PRIO_PROCESS, process group identifier for PRIO_PGRP, and a user ID for PRIO_USER ). A zero value of who denotes the current process, process group, or user. The prio argument is a value in the range -20 to 20. The default priority is 0; lower priorities cause more favorable scheduling.

If the prio is greater than the greatest priority supported, it is set to the greatest priority supported. If the prio is lesser than the least priority supported, it is set to the least priority supported.

Examples

#include<sys/resource.h>
#include<unistd.h>
#include<stdio.h>
int test_getpriority()
{
   int retVal;
   errno = 0;
   retVal = getpriority(PRIO_PROCESS, 0);
   if((retVal == -1) && (errno == ENOSYS))
   {
      printf("Failed");
      return -1;
   }
   else
   {
      printf("getpriority passed");
      printf("\npriority = %d ", retVal);
   }
   return 0;
}

Output

getpriority passed
priority = 0

#include<sys/resource.h>
#include<unistd.h>
#include<stdio.h>
int test_setpriority()
{
   int retVal;
   errno = 0;
   retVal = setpriority(PRIO_PROCESS, 0, 0);

   if((retVal == -1) && (errno == ENOSYS))
   {
      printf(“Failed”);
      return -1;
   }
   else
   {
      printf("Setpriority passed");
      printf("\n getpriority now: %d", getpriority(PRIO_PROCESS,0))
    }
   return 0;
}

Output

Setpriority passed
getpriority now: 0

Limitations

1. The values PRIO_PGRP and PRIO_USER for the which and any value other than 0 for who are not supported, when given return ENOSYS.

2. To effectively increase or decrease the priority of the process, one should consider the following:
Highest -16 to -20
Above Normal -6 to -15
Normal +4 to -5
Below Normal +14 to +5
Lowest +20 to +15

3. The setting of the priority to values -16 to -20 is not supported, the use of which sets errno to EINVAL.

Errors

[ENOSYS] -> The which argument was one of PRIO_PGRP, or PRIO_USER. and/or who was other than 0.

[EINVAL] ->The process tried to set the priority to a value from among -16 to -20.

See also

 nice

Feedback

For additional information or queries on this page send feedback


getprotobynumber

Name

getprotobynumber, getprotobyname
- get protocol entry

Library

 libc.lib

Synopsis
#include <netdb.h>
struct protoent * getprotobyname (const char *name);
struct protoent * getprotobynumber (int proto);

Return values

 Null pointer (0) returned on error.

Detailed description

 The getprotobyname, and getprotobynumber functions each return a pointer to an object with the following structure from 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.
p_proto | The protocol number.

The getprotobyname function and getprotobynumber sequentially search from the beginning of the database until a matching protocol name or protocol number is found,

Examples

#include<netinet/in.h>
#include<arpa/inet.h>
#include<stdio.h>
#include<string.h>
#include<netdb.h>
Int main()
{
struct protoent *p =0;
char *protoname=”tcp”;
p=getprotobyname(protoname);
if(p!=NULL)
printf(“protocol not supported:);
else
printf(“protocol supported”);
return 0;
}

Output

Protocol supported/not supported based on the support for protocol

#include<netinet/in.h>
#include<arpa/inet.h>
#include<stdio.h>
#include<string.h>
#include<netdb.h>
int main()
{
struct protoent *p =0;
int protonum=6;
p=getprotobynumber(protonum);
if(p!=NULL)
printf(“protocol not supported:);
else
printf(“protocol supported”);
return 0;
}

Output

Protocol supported/not supported based on the support for protocol
The getprotobynumber, getprotobyname, functions appeared in BSD 4.2 .

Bugs

 These functions use a thread-specific data space; if the data is needed for future use, it should be copied before any subsequent calls overwrite it. Only the Internet protocols are currently understood.

Feedback

For additional information or queries on this page send feedback


getpwent

Name

getpwent, getpwnam, getpwnam_r, getpwuid, getpwuid_r, setpwent, endpwent
- password database operations

Library

 libc.lib

Synopsis
#include <sys/types.h>
#include <pwd.h>
struct passwd * getpwent (void);
struct passwd * getpwnam (const char *login);
int getpwnam_r (const char *name, struct passwd *pwd, char *buffer, size_t bufsize, struct passwd **result);
struct passwd * getpwuid (uid_t uid);
int getpwuid_r (uid_t uid, struct passwd *pwd, char *buffer, size_t bufsize, struct passwd **result);
void setpwent (void);
void endpwent (void);

Return values

 The functions getpwent, getpwnam, and getpwuid return a valid pointer to a passwd structure on success or NULL if the entry is not found or if an error occurs. If an error does occur, errno will be set. The functions getpwnam_r, and getpwuid_r return 0 if no error occurred, or an error number to indicate failure. It is not an error if a matching entry is not found. (Thus, if result is NULL and the return value is 0, no matching entry exists.)

The endpwent and setpwent functions have no return value.

Detailed description

 These APIs belongs to set which are only build supported and not available functionally. The reason why only build support is extended to these APIs is that Symbian operating system does not support the creation of multiple users and groups in its environment. Moreover it may not make sense to have multiple users and groups in the context of a mobile environment.

We refer to the structure
#include <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 */
        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 returns the default values for a single user system i.e., pw_name,pw_passwd,pw_uid and pw_gid set to root,NULL,0 and 0 respectively in case the input parameter uid/login is 0/ root else the error number is set and NULL is returned by the APIs.

The getpwent when called the first time by an application returns the pointer to a valid passwd structure,that of the simulated single-user group.Subsequent calls return NULL until setpwent is called

The functions getpwnam_r, and getpwuid_r are thread-safe versions of getpwnam, and getpwuid, respectively. The caller must provide storage for the results of the search in the pwd, buffer, bufsize, and result arguments. When these functions are successful, the pwd argument will be filled-in, and a pointer to that argument will be stored in result. If an entry is not found or an error occurs, result will be set to NULL.

The setpwent function sets the library such that subsequent getpwent call returns a filled passwd structure.

endpwent function sets up the library such that the subsequent getpwent call returns NULL.

Examples

#include <pwd.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
/*A user function that takes uid as parameter to call getpwuid
Can be replaced by function that takes char* pwnam to call getpwnam*/
void pwuid_user(int uid)
{
        struct passwd* pw_uid;  /*This struct is filled by the getpwuid call*/
        setpwent ();            /*Set read to start of database*/
        /*Call to getpwuid with uid as parameter..could also be replaced with getpwnam
        with pwnam as parameter*/
        pw_uid = getpwuid (uid);
        if(pw_uid == NULL)      /*End of database reached*/
                return;
        else
                printf ("For uid = %d ,user name = %s", uid, pw_uid->pw_name); /*Print a valid user name*/
        endpwent ();            /*Set the read pointer to the end of database
        /*In case of our library,the user has to free the resources allocated
        by the API call itself*/
        free (pw_uid->pw_mem);
        free (pw);
}

Output

For uid = 0 ,user name = root

#include <pwd.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
/*A user function that takes char* pwnam as parameter to call getpwnam_r
Can be replaced by function that takes int uid to call getpwuid_r*/
void pwuid_r_user(char* pwnam)
{
        /*We have to allocate memory for the structures for the getpwnam_r thread-safe call*/
        struct passwd* pw_nam = (struct passwd*)malloc (sizeof (struct passwd));
        pw_nam->pw_mem = (char**)malloc (sizeof(char**));
        char* buffer=(char*)malloc(sizeof(struct passwd));
        size_t bufsize=sizeof(buffer);
        struct passwd* tempresult;
        int result;
        setpwent ();            /*Set read to start of database*/
        /*Call to getpwnam_r with pwnam as parameter..could also be replaced with getpwuid_r
        with pwuid as parameter*/
        int result=getpwnam_r(pwnam, pw_nam, buffer, bufsize, &tempresult);
        if(result != 0) /*End of database reached*/
                return;
        else
                printf ("For user = %s ,uid = "%d", pwnam, pw_nam->pw_uid); /*Print a valid uid*/
        endpwent ();            /*Set the read pointer to the end of database*/
        /*The user has to free the resources allocated*/
        free(buffer);
        free (pw_uid->pw_mem);
        free (pw);
}

Output

For pwnam = root uid = 0

#include <pwd.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
/*A user function that takes calls getpwent API*/
void getpwent_user()
{
        struct passwd* pw_ent;  /*This struct is filled by the getpwent call*/
        setpwent ();            /*Set read to start of database*/
        /*Call to getpwent */
        pw_ent = getpwent ();
        if(pw_ent == NULL)      /*End of database reached*/
                return;
        else
                /*Print a valid passwd name*/
                printf ("uid = %d ,user name = %s", pw_ent->uid, pw_ent->pw_name);
        endpwent ();            /*Set the read pointer to the end of database*/
        /*In case of our library,the user has to free the resources allocated
        by the API call itself*/
        free (pw_ent->pw_mem);
        free (pw_ent);
}

Output

uid = 0 ,user name = root

Errors

 The getpwuid,getpwnam will fail if:
[ERANGE]
 | Not enough memory to allocate the structures.
[ENOENT]
 | If an invalid uid or login is passed to the APIs. The getpwuid_r,getpwnam_r will fail if:
[ENOENT]
 | If an invalid uid or pwnam is passed to the APIs.

See also

 getgrent,

Bugs

 The functions getpwent, getpwnam, and getpwuid, leave their results in an internal static object and return a pointer to that object. Subsequent calls to the same function will modify the same object.

The functions getpwent, endpwent, and setpwent are fairly useless in a networked environment and should be avoided, if possible

Feedback

For additional information or queries on this page send feedback


getservent

Name

getservent, getservbyport, getservbyname, setservent, endservent
- get service entry

Library

 libc.lib

Synopsis
#include <netdb.h>
struct servent * getservent
struct servent * getservbyname (const char *name, const char *proto);
struct servent * getservbyport (int port, const char *proto);
void setservent (int stayopen);
void endservent (void);

Return values

getservent, getservbyname and getservbyport functions return the servent structure, or a NULL pointer if an error occurs or the end of the file is reached.

Detailed description

 The getservent, getservbyname, and getservbyport functions each return a pointer to an object with the following structure containing the broken-out fields of a line in the network services data base, c:/sys/data/services.
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.
s_aliases
 | A zero terminated list of alternate names for the service.
s_port | The port number at which the service resides. Port numbers are returned 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 necessary.

The setservent function opens and rewinds the file.

The endservent function closes the file.

The getservbyname and getservbyport functions sequentially search from the beginning of the file until a matching protocol name or port number (which must be specified in network byte order) is found, or until EOF is encountered. If a protocol name is also supplied (non- NULL ), searches must also match the protocol.

Examples

#include<stdio.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include<string.h>
#include<netdb.h>
int main()
{
Char *service=”http”;
Char *protocol=”tcp”:
Struct servent *p=0;
P=getservbyname(service,protocol);
if(p!=NULL)
printf(“service not supported:);
else
printf(“Service  supported”);
return 0;
}

#include<stdio.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include<string.h>
#include<netdb.h>
int main()
{
struct servent *p;
char *protocol=”tcp”;
int port;
port=htons(80);
p=(port,protocol);
if(p)
{
Printf(“port is  assigned”);
else
printf(“port is not assigned”);
}

Output

Port is assigned

#include<stdio.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include<string.h>
#include<netdb.h>
Int main()
{
struct servent *p;
p=getservent();
if(p)
printf(“getservent successful”);
else
printf(“getservent failed”);
return 0;
}

Output

Getservent passed

#include<stdio.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include<string.h>
#include<netdb.h>
int main()
{
int stayopen=1;
retservent(stayopen):
return 0;
}

#include<stdio.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include<string.h>
#include<netdb.h>
int main()
{
struct servent *p;
  p=getservent();
if(p)
endservent();
return 0;
}

Files
c:/system/data/services

Diagnostics

 Null pointer (0) returned on EOF or error.
The getservent, getservbyport, getservbyname, setservent, and endservent functions appeared in BSD 4.2.

Bugs

 These functions use a thread-specific data storage; if the data is needed for future use, it should be copied before any subsequent calls overwrite it. Expecting port numbers to fit in a 32 bit quantity is probably naive.

Feedback

For additional information or queries on this page send feedback


getsockname

Name

getsockname - gets socket name

Library

 libc.lib

Synopsis
#include <sys/types.h>
#include <sys/socket.h>
int getsockname (int s, struct sockaddr * restrict name, socklen_t * restrict namelen);

Return values

 The getsockname() function returns the value 0 if successful; otherwise the value -1 is returned and the global variable errno is set to indicate the error.

Detailed description

 The getsockname system call returns the current name for the specified socket. The namelen argument 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).

Examples

#include <sys/socket.h>
#include <netinet/in.h>
#include <unistd.h>
TInt GetSockName()
{
   int sock_fd;
   struct sockaddr_in addr,ss;
   unsigned int len;

   sock_fd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);

   addr.sin_family = AF_INET;
   addr.sin_addr.s_addr = htonl(INADDR_ANY);
   addr.sin_port = htons(5000);
   bind(sock_fd,(struct sockaddr*)&addr,sizeof(addr));

  len=sizeof(ss);
  getsockname(sock_fd,(struct sockaddr*)&ss,&len);
  close(sock_fd);
}

Errors

 The call succeeds unless:
[EBADF]
 | The argument s is not a valid descriptor.
[ECONNRESET]
 | The connection has been reset by the peer.
[ENOTSOCK]
 | The argument s is a file, not a socket.
[ENOBUFS]
 | Insufficient resources were available in the system to perform the operation.
[EFAULT]
 | The name argument points to memory not in a valid part of the process address space.
[EINVAL]
 | The namelen argument is not valid.

See also

 bind, getpeername, socket
The getsockname system call appeared in BSD 4.2.

Feedback

For additional information or queries on this page send feedback


getsockopt

Name

getsockopt, setsockopt
- get and set options on sockets

Library

 libc.lib

Synopsis
#include <sys/types.h>
#include <sys/socket.h>
int getsockopt (int s, int level, int optname, void * restrict optval, socklen_t * restrict optlen);
int setsockopt (int s, int level, int optname, const void *optval, socklen_t optlen);

Return values

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

Detailed description

 The getsockopt and setsockopt system calls manipulate the options associated with a socket. Options may exist at multiple protocol levels; they are always present at the uppermost "socket" level.

When manipulating socket options the level at which the option resides and the name 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 protocol number 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 be set to the protocol number of TCP;

The optval and optlen arguments are used to access option values for setsockopt. For getsockopt they identify a buffer in which the value for the requested option(s) are to be returned. For getsockopt, optlen is a value-result argument, initially containing the size of the buffer pointed to by optval, and modified on return to indicate the actual size of the value returned. If no option value is to be supplied or returned, optval may be NULL.

The optname argument and any specified options are passed uninterpreted to the appropriate protocol module for interpretation. The include file
#include <sys/socket.h>contains definitions for socket level options, described below. Options at other protocol levels vary in format and name; consult the appropriate entries in section 4 of the manual.

Most socket-level options utilize an int argument for optval. For setsockopt, the argument should be non-zero to enable a boolean option, or zero if the option is to be disabled. SO_LINGER uses a struct linger argument, defined in

#include <sys/socket.h,>which specifies the desired state of the option and the linger interval (see below). SO_SNDTIMEO and SO_RCVTIMEO use a struct timeval argument, defined in
#include <sys/time.h.>

The following options are recognized at the socket level. Except as noted, each may be 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_ACCEPTFILTER            set accept filter on listening socket
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_REUSEADDR indicates that the rules used in validating addresses supplied in a bind system call should allow reuse of local addresses. SO_REUSEPORT allows completely duplicate bindings by multiple processes if they all set SO_REUSEPORT before binding the port. This option permits multiple instances of a program to each receive UDP/IP multicast or broadcast datagrams destined for the bound port. SO_KEEPALIVE enables the periodic transmission of messages on a connected socket. SO_DONTROUTE indicates that outgoing messages should bypass the standard routing facilities. Instead, messages are directed to the appropriate network interface according to the network portion of the destination address.

SO_LINGER controls the action taken when unsent messages are queued on socket and a close is performed. If the socket promises reliable delivery of data and SO_LINGER is set, the system will block the process on the close attempt until it is 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 setsockopt system call when SO_LINGER is requested). If SO_LINGER is disabled and a close is issued, the system will process the close in a manner that allows the process to continue as quickly as possible.

The option SO_BROADCAST requests permission to send broadcast datagrams on the socket. Broadcast was a privileged operation in earlier versions of the system. With protocols that support out-of-band data, the SO_OOBINLINE option requests that out-of-band data be placed in the normal data input queue as received; it will then be accessible with recv or read calls without the MSG_OOB flag. Some protocols always behave as if this option is set. SO_SNDBUF and SO_RCVBUF are options to adjust the normal buffer sizes allocated for output and input buffers, respectively. The buffer size may be increased for high-volume connections, or may be decreased to limit the possible backlog of incoming data. The system places an absolute maximum on these values, which is accessible through the sysctl MIB variable "kern.ipc.maxsockbuf."

SO_SNDLOWAT is an option to set the minimum count for output operations. Most output operations process all of the data supplied by the call, delivering data to the protocol for transmission and blocking as necessary for flow control. Nonblocking output operations will process as much data as permitted subject to flow control without blocking, but will process no data if flow control does not allow the smaller of the low water mark value or the entire request to be processed. A select operation testing the ability to write to a socket will return true only if the low water mark amount could be processed. The default value for SO_SNDLOWAT is set to a convenient size for network efficiency, often 1024. SO_RCVLOWAT is an option to set the minimum count for input operations. In general, receive calls will block until any (non-zero) amount of data is received, then return with the smaller of the amount available or the amount requested. The default value for SO_RCVLOWAT is 1. If SO_RCVLOWAT is set to a larger value, blocking receive calls normally wait until they have received the smaller of the low water mark value or the requested amount.

SO_SNDTIMEO is an option to set a timeout value for output operations. It accepts a struct timeval argument with the number of seconds and microseconds used to limit waits for output operations to complete. If a send operation has blocked for this much time, it returns with a partial count or with the error EWOULDBLOCK if no data were sent. In the current implementation, this timer is restarted each time additional data are delivered to the protocol, implying that the limit applies to output portions ranging in size from the low water mark to the high water mark for output. SO_RCVTIMEO is an option to set a timeout value for input operations. It accepts a struct timeval argument with the number of seconds and microseconds used to limit waits for input operations to complete. In the current implementation, this timer is restarted each time additional data are received by the protocol, and thus the limit is in effect an inactivity timer. If a receive operation has been blocked for this much time without receiving additional data, it returns with a short count or with the error EWOULDBLOCK if no data were received.

SO_ACCEPTFILTER places an accept_filter on the socket, which will filter incoming connections on a listening stream socket before being presented for accept. Once more, listen must be called on the socket before trying to install the filter on it, or else the setsockopt system call will fail.

struct  accept_filter_arg {
        char    af_name[16];
        char    af_arg[256-16];
};

The optval argument should point to a struct accept_filter_arg that will select and configure the accept_filter. The af_name argument should be filled with the name of the accept filter that the application wishes to place on the listening socket. The optional argument af_arg can be passed to the accept filter specified by af_name to provide additional configuration options at attach time. Passing in an optval of NULL will remove the filter.

Finally, SO_TYPE and SO_ERROR are options used only with getsockopt. SO_TYPE returns the type of the socket, such as SOCK_STREAM; it is useful for servers that inherit sockets on startup. SO_ERROR returns any pending error on the socket and clears the error status. It may be used to check for asynchronous errors on connected datagram sockets or for other asynchronous errors.

Examples

#include <sys/socket.h>
#include <netinet/in.h>
#include <unistd.h>
void SocketOptions()
{
   int sock_fd;
   int optval = 1;
   unsigned int optlen = sizeof(optval);
   int rdoptval;
   sock_fd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
   setsockopt(sock_fd,SOL_SOCKET,SO_KEEPALIVE,&optval,optlen);
   getsockopt(sock_fd,SOL_SOCKET,SO_KEEPALIVE,(void*)&rdoptval,&optlen);
close(sock_fd);
}

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 process address space. For getsockopt, this error may also be returned if optlen is not in a valid part of the process address space.

See also

 ioctl, socket,

The getsockopt system call appeared in BSD 4.2.

Feedback

For additional information or queries on this page send feedback


gettext

Name

gettext, dgettext, dcgettext - Translates the messages

Library

libintl.lib

Synopsis

#include <libintl.h>

char * gettext (const char *msgid);
char * dgettext (const char *domainname, const char *msgid);
char * dcgettext(const char *domainname, const char *msgid, int category);

Return values

If the translation for the text string was found in one of the specified message catalogs, converts the text string to the current locale's codeset and returns. Do not modify or free the returned string as it is statically allocated in the function.

If the translation for the text string was not found, the msgid is returned.

Detailed description

The gettext(), dgettext(), dcgettext() functions try to translate a text string into the user's native language, by looking up the translation in a message catalog.
The argument msgid specifies the message to be translated. Conventionally, it is the English version of the message with non-ASCII characters replaced by ASCII approximations.The translators work with message catalogs, called the PO files, that contain messages in both English and their translated versions. Use the msgfmt utility to install the PO file.

The message domain for gettext() function is specified by the preceding textdomain() function call.

For dgettext() and dcgettext() functions the message domain is specified by the argument domainname. If the argument domainname is NULL, then use the message domain specified in the preceding textdomain() function.
For dcgettext() function, the argument category determines the locale facet, it is one of the constants defined in the <locale.h>header, excluding LC_ALL.

The message catalogs used by the functions is at the pathname dirname/locale/category/domainname.mo. dirname is the directory specified through the bindtextdomain() function.

Errors

errno is not modified.

Feedback

For additional information or queries on this page send feedback

© 2006-2007 Nokia


gettimeofday

Name

gettimeofday - gets time of day

Library

 libc.lib

Synopsis
#include <sys/time.h>
int gettimeofday (struct timeval *tp, struct timezone *tzp);

Return values

 The gettimeofday function returns 0 for success, or -1 for failure.

Detailed description

 The system’s notion of the current Greenwich time and the current time zone is obtained with the gettimeofday system call, and set with the settimeofday system call. The time is expressed in seconds and microseconds since midnight (0 hour), January 1, 1970. The resolution of the system clock 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 or set.

The structures pointed to by tp and tzp are defined in
#include <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 time westward from Greenwich), and a flag that, if nonzero, indicates that Daylight Saving time applies locally during the appropriate part of the year.

Examples

#include <stdio.h>
#include <sys/time.h>

int main()
{
  struct timeval *tv;
  struct timezone *tz;
  int i = gettimeofday(tv, tz);

  printf("tv: %d, %d\n", tv->tv_sec, tv->tv_usec);
  printf("tz: %d, %d\n", tz->tz_minuteswest, tz->tz_dsttime);
  return 0;
}

Output

tv: 1474660693, -326937770
tz: 7804688, 3

See also

 adjtime, clock_gettime, ctime

Feedback

For additional information or queries on this page send feedback


getuid

Name

getuid, geteuid
- get user identification

Library

 libc.lib

Synopsis
#include <unistd.h>
#include <sys/types.h>
uid_t getuid (void);
uid_t geteuid (void);

Return values

 These functions always return 0.

Detailed description

 getuid and geteuid are functions belonging to set of APIs which are only build supported and not available functionally. The reason why only build support is extended to these APIs is, symbian operating system does not support creation of multiple users and groups in its environment. More over it may not make sense to have multiple users and groups in the context of a mobile environment.

Errors

 No error values are set.

See also

Feedback

For additional information or queries on this page send feedback


getwc

Name

fgetwc, getwc, getwchar
- read a wide character from a FILE stream

Library

 libc.lib

Synopsis
#include <stdio.h>
#include <wchar.h>
wint_t fgetwc (FILE *stream);
wint_t getwc (FILE *stream);
wint_t getwchar

Return values

 If successful, these routines return the next wide character from the stream. If the stream is at end-of-file or a read error occurs, the routines return WEOF. The routines feof and ferror must be used to distinguish between end-of-file and error. If an error occurs, the global variable errno is set to indicate the error. The end-of-file condition is remembered, even on a terminal, and all subsequent attempts to read will return WEOF until the condition is cleared with clearerr.

Detailed description

 The fgetwc function obtains the next input wide character (if present) from the stream pointed at by stream, or the next character pushed back on the stream via ungetwc.

The getwc function acts essentially identical to fgetwc.

The getwchar function is equivalent to getwc with the argument stdin.

Examples

/* Illustrates how to use fgetwc API */
#include <stdio.h>
#include <wchar.h>
wint_t example_fgetwc(void)
{
 FILE *fp = NULL;
 wint_t retval;

 /* opening the input file */
 fp = fopen("input.txt","r");
 if(fp == NULL)
 {
  wprintf(L"Error: File open\n");
  return (-1);
 }
 /* Read a character from the opened file */
 retval = fgetwc(fp);
 /* Close the file open for reading */
 fclose(fp);
 /* return the character read from the file */
 return (retval);
}

/* Illustrates how to use getwc API */
#include <stdio.h>
#include <wchar.h>
wint_t example_getwc(void)
{
 FILE *fp =  NULL;
 wint_t retval;

 /* opening the input file */
 fp = fopen("input.txt","r");
 if(fp == NULL)
 {
  wprintf(L"Error: File open\n");
  return (-1);
 }
 /* Read a character from the opened file */
 retval = getwc(fp);
 /* Close the file open for reading */
 fclose(fp);
 /* return the character read from the file */
 return (retval);
}

/* Illustrates how to use getwchar API */
#include <stdio.h>
#include <wchar.h>
wint_t example_getwchar(void)
{
 wint_t retval;

 /* Read a character from standard input */
 retval = getwchar();
 /* return the character read */
 return (retval);
}

See also

 ferror, fopen, fread, getc, putwc, ungetwc

Feedback

For additional information or queries on this page send feedback


getws

Name

getws - reads a wide character string from stdin

Library

 libc.lib

Synopsis
#include <wchar.h>
wchar_t * getws (wchar_t * restrict ws);

Return values

 Upon successful completion, getws returns ws. The getws function does not distinguish between end-of-file and error, and callers must use feof and ferror to determine which occurred.

Detailed description

The getws function is equivalent to fgetws with an infinite size and a stream of stdin, except that the wide character newline(if any) is not stored in the string. It is the caller’s responsibility to ensure that the input line, if any, is sufficiently short to fit in the string.

Examples

#include <stdio.h>
#include <wchar.h>
/* Illustrates how to use getws API */
int example_getws()
        {
        FILE* stdop = freopen("c:\stdop","w+",stdout);
        FILE* stdip = freopen("c:\stdip","w+",stdin);
        FILE* stder = freopen("c:\stder","w+",stderr);
        wchar_t* buf = (wchar_t*)malloc(sizeof(wchar_t)*50);
        wchar_t s[100];
        int ret = 0;
        size_t size = fwrite("abdcef\n", 1, 6, stdip);          //write to stdin
        fclose(stdip);
        stdip = freopen("c:\stdip","r", stdin);
        getws(s);               // read a line (from stdin)
        putws(s);               //write to stdout
        fclose(stdop);
        stdop = freopen("c:\stdop","r", stdout);
        fgetws(buf,7,stdop);            //read from stdout
        if(wcsncmp(s, buf,6))
                {
                ret = -1;
                }
        fclose(stdin);
        fclose(stder);
        fclose(stdop);
        remove("c:\stdop");
        remove("c:\stdip");
        remove("c:\stder");
        return ret;
        }

Output

abcdef
abcdef

Security considerations

 The getws function cannot be used securely. Because of its lack of bounds checking, and the inability for the calling program to reliably determine the length of the next incoming line, the use of this function enables malicious users to arbitrarily change a running program’s functionality through a buffer overflow attack. It is strongly suggested that the fgetws function be used in all cases.

Errors

 The getws function will fail if:
[EFAULT]
The given ws argument is NULL.

The function getws may also fail and set errno for any of the errors specified for the routines fflush, fstat, read, fgetws, or malloc.

See also

 feof, ferror, fgets, fgetws, gets

Feedback

For additional information or queries on this page send feedback


Arrays

Name

Arrays — Arrays of arbitrary elements which grow automatically as elements are added.

Library

glib.lib

Synopsis

#include <glib.h>

GArray;
GArray*     g_array_new                     (gboolean zero_terminated, gboolean clear_, guint element_size);
GArray*     g_array_sized_new               (gboolean zero_terminated, gboolean clear_, guint element_size,
                                             guint reserved_size);
#define     g_array_append_val              (a,v)
GArray*     g_array_append_vals             (GArray *array, gconstpointer data, guint len);
#define     g_array_prepend_val             (a,v)
GArray*     g_array_prepend_vals            (GArray *array, gconstpointer data, guint len);
#define     g_array_insert_val              (a,i,v)
GArray*     g_array_insert_vals             (GArray *array, guint index_, gconstpointer data, guint len);
GArray*     g_array_remove_index            (GArray *array, guint index_);
GArray*     g_array_remove_index_fast       (GArray *array, guint index_);
GArray*     g_array_remove_range            (GArray *array, guint index_, guint length);
void        g_array_sort                    (GArray *array, GCompareFunc compare_func);
void        g_array_sort_with_data          (GArray *array, GCompareDataFunc compare_func, gpointer user_data);
#define     g_array_index                   (a,t,i)
GArray*     g_array_set_size                (GArray *array, guint length);
gchar*      g_array_free                    (GArray *array, gboolean free_segment);

Detailed Description

Arrays are similar to standard C arrays, except that they grow automatically as elements are added.

Array elements can be of any size (though all elements of one array are the same size), and the array can be automatically cleared to '0's and zero-terminated.

To create a new array use g_array_new().

To add elements to an array, use
g_array_append_val(),

g_array_append_vals(),

g_array_prepend_val(), and g_array_prepend_vals().

To access an element of an array, use g_array_index().

To set the size of an array, use g_array_set_size().

To free an array, use g_array_free().

Example 5. Using a GArray to store gint values

  GArray *garray;
  gint i;

  /* We create a new array to store gint values.
     We do not want it zero-terminated or cleared to 0's. */
  garray = g_array_new (FALSE, FALSE, sizeof (gint));
  for (i = 0; i < 10000; i++)
    g_array_append_val (garray, i);

  for (i = 0; i < 10000; i++)
    if (g_array_index (garray, gint, i) != i)
      g_print ("ERROR: got %d instead of %d\n",
               g_array_index (garray, gint, i), i);

  g_array_free (garray, TRUE);

Details

GArray

typedef struct {
  gchar *data;
  guint len;
} GArray;

Contains the public fields of an Array.

gchar *data; | a pointer to the element data. The data may be moved as elements are added to the GArray.
guint len; | the number of elements in the GArray.

g_array_new ()

GArray*     g_array_new     (gboolean zero_terminated, gboolean clear_, guint element_size);

Creates a new GArray.

zero_terminated : | TRUE if the array should have an extra element at the end which is set to 0.
clear_ : | TRUE if GArray elements should be automatically cleared to 0 when they are allocated.
element_size : | the size of each element in bytes.
Returns : | the new GArray.

g_array_sized_new ()

GArray*     g_array_sized_new    (gboolean zero_terminated, gboolean clear_, guint element_size, guint reserved_size);

Creates a new GArray with reserved_size elements pre-allocated. This avoids frequent reallocation, if more elements are to be added to the array. Note however, that the size of the array is still 0.

zero_terminated : | TRUE if the array should have an extra element at the end with all bits cleared.
clear_ : | TRUE if all bits in the array should be cleared to 0 on allocation.
element_size : | size of each element in the array.
reserved_size : | number of elements pre-allocated.
Returns : | the new GArray.

g_array_append_val()

#define     g_array_append_val(a,v)

Adds the value on to the end of the array. The array will grow in size automatically if necessary.

Note

Note: g_array_append_val() is a macro which uses a reference to the value parameter v. This means that literal values such as "27" cannot be used. Use variables.

a : | a GArray.
v : | the value to append to the GArray.
Returns : | the GArray.

g_array_append_vals ()

GArray*     g_array_append_vals             (GArray *array, gconstpointer data, guint len);

Adds len elements onto the end of the array.

array : | a GArray.
data : | a pointer to the elements to append to the end of the array.
len : | the number of elements to append.
Returns : | the GArray.

g_array_prepend_val()

#define     g_array_prepend_val(a,v)

Adds the value on to the start of the array. The array will grow in size automatically if necessary.

This operation is slower than g_array_append_val() since the existing elements in the array have to be moved to make space for the new element.

Note

Note: g_array_prepend_val() is a macro which uses a reference to the value parameter v. This means that literal values such as "27" cannot be used.Use variables.

a : | a GArray.
v : | the value to prepend to the GArray.
Returns : | the GArray.

g_array_prepend_vals ()

GArray*     g_array_prepend_vals            (GArray *array, gconstpointer data, guint len);

Adds len elements onto the start of the array.

This operation is slower than g_array_append_vals() since the existing elements in the array have to be moved to make space for the new elements.

array : | a GArray.
data : | a pointer to the elements to prepend to the start of the array.
len : | the number of elements to prepend.
Returns : | the GArray.

g_array_insert_val()

#define     g_array_insert_val(a,i,v)

Inserts an element into an array at the given index.

Note

Note: g_array_insert_val() is a macro which uses a reference to the value parameter v. This means that literal values such as "27" cannot be used.Use variables.

a : | a GArray.
i : | the index to place the element at.
v : | the value to insert into the array.
Returns : | the GArray.

g_array_insert_vals ()

GArray*     g_array_insert_vals        (GArray *array, guint index_, gconstpointer data, guint len);

Inserts len elements into a GArray at the given index.

array : | a GArray.
index_ : | the index to place the elements at.
data : | a pointer to the elements to insert.
len : | the number of elements to insert.
Returns : | the GArray.

g_array_remove_index ()

GArray*     g_array_remove_index         (GArray *array, guint index_);

Removes the element at the given index from a GArray. The following elements are moved down one place.

array : | a GArray.
index_ : | the index of the element to remove.
Returns : | the GArray.

g_array_remove_index_fast ()

GArray*     g_array_remove_index_fast       (GArray *array, guint index_);

Removes the element at the given index from a GArray. The last element in the array is used to fill in the space, so this function does not preserve the order of the GArray. But it is faster than g_array_remove_index().

array : | a GArray.
index_ : | the index of the element to remove.
Returns : | the GArray.

g_array_remove_range ()

GArray*     g_array_remove_range        (GArray *array, guint index_, guint length);

Removes the given number of elements starting at the given index from a GArray. The following elements are moved to close the gap.

array : | a GArray.
index_ : | the index of the first element to remove.
length : | the number of elements to remove.
Returns : | the GArray.

g_array_sort ()

void     g_array_sort     (GArray *array, GCompareFunc compare_func);

Sorts a GArray using compare_func which should be a qsort()-style comparison function (returns less than zero for first arg is less than second arg, zero for equal, greater zero if first arg is greater than second arg).

If two array elements compare equal, their order in the sorted array is undefined.

array : | a GArray.
compare_func : | comparison function.

g_array_sort_with_data ()

void     g_array_sort_with_data      (GArray *array, GCompareDataFunc compare_func, gpointer user_data);

Like g_array_sort(), but the comparison function receives an extra user data argument.

array : | a GArray.
compare_func : | comparison function.
user_data : | data to pass to compare_func.

g_array_index()

#define     g_array_index(a,t,i)

Returns the element of a GArray at the given index. The return value is cast to the given type.

Example 6. Getting a pointer to an element in a GArray

  EDayViewEvent *event;

  /* This gets a pointer to the 3rd element in the array of EDayViewEvent
     structs. */
  event = &g_array_index (events, EDayViewEvent, 3);

a : | a GArray.
t : | the type of the elements.
i : | the index of the element to return.
Returns : | the element of the GArray at the index given by i.

g_array_set_size ()

GArray*     g_array_set_size          (GArray *array, guint length);

Sets the size of the array, expanding it if necessary. If the array was created with clear_ set to TRUE, the new elements are set to 0.

array : | a GArray.
length : | the new size of the GArray.
Returns : | the GArray.

g_array_free ()

gchar*      g_array_free           (GArray *array, gboolean free_segment);

Frees the memory allocated for the GArray. If free_segment is TRUE it frees the memory block holding the elements as well. Pass FALSE to free the GArray wrapper but preserve the underlying array for use elsewhere.

Note

Note: If array elements contain dynamically-allocated memory, they should be freed first.

array : | a GArray.
free_segment : | if TRUE the actual element data is freed as well.
Returns : | the element data if free_segment is FALSE, otherwise NULL

Feedback

For additional information or queries on this page send feedback


Asynchronous Queues

Name

Asynchronous Queues — asynchronous communication between threads.

Library

glib.lib

Synopsis

#include <glib.h>

GAsyncQueue;
GAsyncQueue* g_async_queue_new                 (void);
GAsyncQueue* g_async_queue_ref                 (GAsyncQueue *queue);
void         g_async_queue_unref               (GAsyncQueue *queue);
void         g_async_queue_push                (GAsyncQueue *queue, gpointer data);
void        g_async_queue_push_sorted          (GAsyncQueue *queue, gpointer data, GCompareDataFunc func, gpointer user_data);

gpointer    g_async_queue_pop                  (GAsyncQueue *queue);
gpointer    g_async_queue_try_pop              (GAsyncQueue *queue);
gpointer    g_async_queue_timed_pop            (GAsyncQueue *queue, GTimeVal *end_time);
gint        g_async_queue_length               (GAsyncQueue *queue);

void        g_async_queue_sort                 (GAsyncQueue *queue, GCompareDataFunc func, gpointer user_data);

void        g_async_queue_lock                 (GAsyncQueue *queue);
void        g_async_queue_unlock               (GAsyncQueue *queue);
void        g_async_queue_ref_unlocked         (GAsyncQueue *queue);
void        g_async_queue_unref_and_unlock     (GAsyncQueue *queue);
void        g_async_queue_push_unlocked        (GAsyncQueue *queue, gpointer data);
void        g_async_queue_push_sorted_unlocked (GAsyncQueue *queue, GCompareDataFunc func, gpointer user_data);
gpointer    g_async_queue_pop_unlocked         (GAsyncQueue *queue);
gpointer    g_async_queue_try_pop_unlocked     (GAsyncQueue *queue);
gpointer    g_async_queue_timed_pop_unlocked
                                               (GAsyncQueue *queue, GTimeVal *end_time);
gint        g_async_queue_length_unlocked      (GAsyncQueue *queue);
void        g_async_queue_sort_unlocked        (GAsyncQueue *queue, GCompareDataFunc func, gpointer user_data);

Detailed Description

Often there is a need to communicate between different threads. In general it is safer not to do this by shared memory, but by explicit message passing. These messages only make sense asynchronously for multi-threaded applications though, a synchronous operation could as well be done in the same thread.

Asynchronous queues are an exception from most other GLib data structures, as they can be used simultaneously from multiple threads without explicit locking and they bring their own built-in reference counting. This is because the nature of an asynchronous queue is that it will always be used by at least 2 concurrent threads.

For using an asynchronous queue first create it using g_async_queue_new(). A newly-created queue will get the reference count 1. Whenever another thread is creating a new reference of (that is, pointer to) the queue, it has to increase the reference count (using g_async_queue_ref()). Also, before removing this reference, the reference count has to be decreased (using g_async_queue_unref()). After that the queue might no longer exist hence it must not be accessed after that point.

A thread, which wants to send a message to that queue simply calls g_async_queue_push() to push the message to the queue.

A thread, which is expecting messages from an asynchronous queue simply calls g_async_queue_pop() for that queue. If no message is available in the queue at that point, the thread is now put to sleep until a message arrives. The message will be removed from the queue and returned. The functions g_async_queue_try_pop() and g_async_queue_timed_pop() can be used to only check for the presence of messages or to only wait a certain time for messages respectively.

For almost every function there exist two variants, one that locks the queue and one that does not. That way the queue lock can be held (acquire it with g_async_queue_lock() and release it with g_async_queue_unlock()) over multiple queue accessing instructions. This can be necessary to ensure the integrity of the queue, but should only be used when really necessary, as it can make life harder if used unwisely. Normally the locking function variants should be used (those without the suffix _unlocked).

Details

GAsyncQueue

typedef struct _GAsyncQueue GAsyncQueue;

The GAsyncQueue struct is an opaque data structure, which represents an asynchronous queue. It should only be accessed through the g_async_queue_* functions.

g_async_queue_new ()

GAsyncQueue* g_async_queue_new              (void);

Creates a new asynchronous queue with the initial reference count of 1.

Returns : the new GAsyncQueue.

g_async_queue_ref ()

GAsyncQueue* g_async_queue_ref              (GAsyncQueue *queue);

Increases the reference count of the asynchronous queue by 1. There is no need to hold the lock to call this function.

queue : | a GAsyncQueue.
Returns : | the queue that was passed in (since 2.6)

g_async_queue_unref ()

void        g_async_queue_unref             (GAsyncQueue *queue);

Decreases the reference count of the asynchronous queue by 1. If the reference count went to 0, the queue will be destroyed and the memory allocated will be freed. The users are not allowed to use the queue afterwards, as it might have disappeared. Hold the lock to call this function.

queue : a GAsyncQueue.

g_async_queue_push ()

void        g_async_queue_push           (GAsyncQueue *queue, gpointer data);

Pushes the data into the queue. data must not be NULL.

queue : | a GAsyncQueue.
data : | data to push into the queue.

g_async_queue_push_sorted ()

void     g_async_queue_push_sorted       (GAsyncQueue *queue, gpointer data, GCompareDataFunc func, gpointer user_data);

Inserts data into queue using func to determine the new position.

This function requires that the queue is sorted before pushing on new elements.

This function will lock queue before it sorts the queue and unlock it when it is finished.

For an example of func see g_async_queue_sort().

queue : | a GAsyncQueue
data : | the data to push into the queue
func : | the GCompareDataFunc is used to sort queue. This function is passed two elements of the queue. The function should return 0 if they are equal, a negative value if the first element should be higher in the queue or a positive value if the first element should be lower in the queue than the second element.
user_data : | user data passed to func.

g_async_queue_pop ()

gpointer    g_async_queue_pop           (GAsyncQueue *queue);

Pops data from the queue. This function blocks until data become available.

queue : | a GAsyncQueue.
Returns : | data from the queue.

g_async_queue_try_pop ()

gpointer    g_async_queue_try_pop           (GAsyncQueue *queue);

Tries to pop data from the queue. If no data is available, NULL is returned.

queue : | a GAsyncQueue.
Returns : | data from the queue or NULL, when no data is available immediately.

g_async_queue_timed_pop ()

gpointer    g_async_queue_timed_pop         (GAsyncQueue *queue, GTimeVal *end_time);

Pops data from the queue. If no data is received before end_time, NULL is returned.

To easily calculate end_time a combination of g_get_current_time() and g_time_val_add() can be used.

queue : | a GAsyncQueue.
end_time : | a GTimeVal, determining the final time.
Returns : | data from the queue or NULL, when no data is received before end_time.

g_async_queue_length ()

gint        g_async_queue_length            (GAsyncQueue *queue);

Returns the length of the queue, negative values mean waiting threads, positive values mean available entries in the queue. Actually this function returns the number of data items in the queue minus the number of waiting threads. Thus a return value of 0 could mean 'n' entries in the queue and 'n' thread waiting. That can happen due to locking of the queue or due to scheduling.

queue : | a GAsyncQueue.
Returns : | the length of the queue.

g_async_queue_sort ()

void      g_async_queue_sort             (GAsyncQueue *queue, GCompareDataFunc func, gpointer user_data);

Sorts queue using func.

This function will lock queue before it sorts the queue and unlock it when it is finished.

To sort a list of priority numbers to make sure the lowest priority would be at the top of the queue, use the following code snippet:

 gint32 id1;
 gint32 id2;

 id1 = GPOINTER_TO_INT (element1);
 id2 = GPOINTER_TO_INT (element2);

 return (id1 > id2 ? +1 : id1 == id2 ? 0 : -1);
queue : | a GAsyncQueue
func : | the GCompareDataFunc is used to sort queue. This function is passed two elements of the queue. The function should return 0 if they are equal, a negative value if the first element should be higher in the queue or a positive value if the first element should be lower in the queue than the second element.
user_data : | user data passed to func

g_async_queue_lock ()

void        g_async_queue_lock              (GAsyncQueue *queue);

Acquires the queue's lock. After that,call the g_async_queue_*_unlocked() function variants on that queue. Otherwise it will deadlock.

queue : a GAsyncQueue.

g_async_queue_unlock ()

void        g_async_queue_unlock            (GAsyncQueue *queue);

Releases the queue's lock.

queue : a GAsyncQueue.

g_async_queue_ref_unlocked ()

void        g_async_queue_ref_unlocked      (GAsyncQueue *queue);

Increases the reference count of the asynchronous queue by 1.

Note

Warning: g_async_queue_ref_unlocked is deprecated and should not be used in newly-written code.
Increases the reference count of the asynchronous queue by 1.

Deprecated: Since 2.8, reference counting is done atomically so g_async_queue_ref() can be used regardless of the queue's lock.

queue : a GAsyncQueue.

g_async_queue_unref_and_unlock ()

void        g_async_queue_unref_and_unlock   (GAsyncQueue *queue);

Decreases the reference count of the asynchronous queue by 1 and releases the lock. This function must be called while holding the queue's lock. If the reference count went to 0, the queue will be destroyed and the memory allocated will be freed.

Deprecated: Since 2.8, reference counting is done atomically so g_async_queue_unref() can be used regardless of the queue's lock.

queue : a GAsyncQueue.

g_async_queue_push_unlocked ()

void        g_async_queue_push_unlocked     (GAsyncQueue *queue, gpointer data);

Pushes the data into the queue. data must not be NULL. This function must be called while holding the queue's lock.

queue : | a GAsyncQueue.
data : | data to push into the queue.

g_async_queue_push_sorted_unlocked ()

void   g_async_queue_push_sorted_unlocked   (GAsyncQueue *queue, gpointer data, GCompareDataFunc func, gpointer user_data);

Inserts data into queue using func to determine the new position.

This function requires that the queue is sorted before pushing on new elements.

This function is called while holding the queue's lock.

For an example of func see g_async_queue_sort().

queue : | a GAsyncQueue
data : | the data to push into the queue
func : | the GCompareDataFunc is used to sort queue. This function is passed two elements of the queue. The function should return 0 if they are equal, a negative value if the first element should be higher in the queue or a positive value if the first element should be lower in the queue than the second element.
user_data : | user data passed to func.

g_async_queue_pop_unlocked ()

gpointer    g_async_queue_pop_unlocked      (GAsyncQueue *queue);

Pops data from the queue. This function blocks until data become available. This function must be called while holding the queue's lock.

queue : | a GAsyncQueue.
Returns : | data from the queue.

g_async_queue_try_pop_unlocked ()

gpointer    g_async_queue_try_pop_unlocked  (GAsyncQueue *queue);

Tries to pop data from the queue. If no data is available, NULL is returned. This function must be called while holding the queue's lock.

queue : | a GAsyncQueue.
Returns : | data from the queue or NULL, when no data is available immediately.

g_async_queue_timed_pop_unlocked ()

gpointer    g_async_queue_timed_pop_unlocked    (GAsyncQueue *queue, GTimeVal *end_time);

Pops data from the queue. If no data is received before end_time, NULL is returned. This function must be called while holding the queue's lock.

To easily calculate end_time a combination of g_get_current_time() and g_time_val_add() can be used.

queue : | a GAsyncQueue.
end_time : | a GTimeVal, determining the final time.
Returns : | data from the queue or NULL, when no data is received before end_time.

g_async_queue_length_unlocked ()

gint       g_async_queue_length_unlocked        (GAsyncQueue *queue);

Returns the length of the queue, negative values mean waiting threads, positive values mean available entries in the queue. Actually this function returns the number of data items in the queue minus the number of waiting threads. Thus a return value of 0 could mean 'n' entries in the queue and 'n' thread waiting. That can happen due to locking of the queue or due to scheduling. This function must be called while holding the queue's lock.

queue : | a GAsyncQueue.
Returns : | the length of the queue.

g_async_queue_sort_unlocked ()

void        g_async_queue_sort_unlocked     (GAsyncQueue *queue, GCompareDataFunc func, gpointer user_data);

Sorts queue using func.

This function is called while holding the queue's lock.

queue : | a GAsyncQueue
func : | the GCompareDataFunc is used to sort queue. This function is passed two elements of the queue. The function should return 0 if they are equal, a negative value if the first element should be higher in the queue or a positive value if the first element should be lower in the queue than the second element.
user_data : | user data passed to func

Feedback

For additional information or queries on this page send feedback


Atomic Operations

Name

Atomic Operations — used to automatically access integers and pointers

Library

glib.lib

Synopsis

#include <glib.h>

gint         g_atomic_int_get                          (gint *atomic);
void         g_atomic_int_add                          (gint *atomic, gint val);
gint         g_atomic_int_exchange_and_add             (gint *atomic, gint val);

gboolean     g_atomic_int_compare_and_exchange         (gint *atomic, gint oldval, gint newval);
gpointer     g_atomic_pointer_get                      (gpointer *atomic);
gboolean     g_atomic_pointer_compare_and_exchange     (gpointer *atomic, gpointer oldval, gpointer newval);
void         g_atomic_int_inc                          (gint *atomic);
gboolean     g_atomic_int_dec_and_test                 (gint *atomic);

Detailed Description

The following functions can be used to automatically access integers and pointers. They are implemented as inline assembler functions on most platforms and use slower fall-backs otherwise. Using them can sometimes save the user from using a performance-expensive GMutex to protect the integer or pointer.

The most important usage is reference counting. Using g_atomic_int_inc() and g_atomic_int_dec_and_test() makes reference counting a very fast operation.

Note

Note: Do not directly read integers or pointers concurrently accessed by other threads with the following functions directly. Always use g_atomic_int_get() and g_atomic_pointer_get() respectively. They are acting as a memory barrier.
When using those functions for anything apart from simple reference counting, be aware of the implications of doing that. So if in doubt, use a GMutex. Do not use anything other than g_atomic_int_inc() and g_atomic_int_dec_and_test() if there is no prior knowledge about memory barriers.
It is not safe to set an integer or pointer just by assigning to it, when it is concurrently accessed by other threads with the following functions. Use g_atomic_int_compare_and_exchange() or g_atomic_pointer_compare_and_exchange() respectively.

Details

g_atomic_int_get ()

gint      g_atomic_int_get       (gint *atomic);

Reads the value of the integer pointed to by atomic. Also acts as a memory barrier.

atomic : | a pointer to an integer.
Returns : | the value of *atomic.

g_atomic_int_set ()

void        g_atomic_int_set                (volatile gint *atomic, gint newval);

Sets the value of the integer pointed to by atomic. Also acts as a memory barrier.

atomic : | a pointer to an integer
newval : | the new value

g_atomic_int_add ()

void     g_atomic_int_add       (gint *atomic, gint val);

Atomically adds val to the integer pointed to by atomic. Also acts as a memory barrier.

atomic : | a pointer to an integer.
val : | the value to add to *atomic.

g_atomic_int_exchange_and_add ()

gint     g_atomic_int_exchange_and_add       (gint *atomic, gint val);

Atomically adds val to the integer pointed to by atomic. It returns the value of *atomic just before the addition took place. Also acts as a memory barrier.

atomic : | a pointer to an integer.
val : | the value to add to *atomic.
Returns : | the value of *atomic before the addition.

g_atomic_int_compare_and_exchange ()

gboolean    g_atomic_int_compare_and_exchange      (gint *atomic, gint oldval, gint newval);

Compares oldval with the integer pointed to by atomic and if they are equal, atomically exchanges *atomic with newval. Also acts as a memory barrier.

atomic : | a pointer to an integer.
oldval : | the assumed old value of *atomic.
newval : | the new value of *atomic.
Returns : | TRUE, if *atomic was equal oldval. FALSE otherwise.

g_atomic_pointer_get ()

gpointer    g_atomic_pointer_get        (gpointer *atomic);

Reads the value of the pointer pointed to by atomic. Also acts as a memory barrier.

atomic : | a pointer to a gpointer.
Returns : | the value to add to *atomic.

g_atomic_pointer_set ()

void        g_atomic_pointer_set            (volatile gpointer *atomic, gpointer newval);

Sets the value of the pointer pointed to by atomic. Also acts as a memory barrier.

atomic : | a pointer to a gpointer
newval : | the new value

g_atomic_pointer_compare_and_exchange ()

gboolean    g_atomic_pointer_compare_and_exchange       (gpointer *atomic, gpointer oldval, gpointer newval);

Compares oldval with the pointer pointed to by atomic and if they are equal, atomically exchanges *atomic with newval. Also acts as a memory barrier.

atomic : | a pointer to a gpointer.
oldval : | the assumed old value of *atomic.
newval : | the new value of *atomic.
Returns : | TRUE, if *atomic was equal oldval. FALSE otherwise.

g_atomic_int_inc ()

void        g_atomic_int_inc             (gint *atomic);

Atomically increments the integer pointed to by atomic by 1.

atomic : a pointer to an integer.

g_atomic_int_dec_and_test ()

gboolean    g_atomic_int_dec_and_test     (gint *atomic);

Atomically decrements the integer pointed to by atomic by 1.

atomic : | a pointer to an integer.
Returns : | TRUE, if the integer pointed to by atomic is 0 after decrementing it.

See Also

GMutex:

GLib mutual exclusions.

Feedback

For additional information or queries on this page send feedback


Automatic String Completion

Name

Automatic String Completion — support for automatic completion using a group of target strings.

Library

glib.lib

Synopsis

#include <glib.h>
GCompletion;
GCompletion*   g_completion_new                (GCompletionFunc func);
gchar*         (*GCompletionFunc)              (gpointer);
void           g_completion_add_items          (GCompletion *cmp, GList *items);
void           g_completion_remove_items       (GCompletion *cmp, GList *items);
void           g_completion_clear_items        (GCompletion *cmp);
GList*         g_completion_complete           (GCompletion *cmp, const gchar *prefix, gchar **new_prefix);
GList*         g_completion_complete_utf8      (GCompletion *cmp, const gchar *prefix, gchar **new_prefix);
void           g_completion_set_compare        (GCompletion *cmp, GCompletionStrncmpFunc strncmp_func);
gint           (*GCompletionStrncmpFunc)       (const gchar *s1, const gchar *s2, gsize n);
void           g_completion_free               (GCompletion *cmp);

Detailed Description

GCompletion provides support for automatic completion of a string using any group of target strings. It is typically used for file name completion as is common in many UNIX shells.

A GCompletion is created using g_completion_new(). Target items are added and removed with g_completion_add_items(), g_completion_remove_items() and g_completion_clear_items(). A completion attempt is requested with g_completion_complete() or g_completion_complete_utf8(). When no longer needed, the GCompletion is freed with g_completion_free().

Items in the completion can be simple strings (e.g. filenames), or pointers to arbitrary data structures. If data structures are used, provide a GCompletionFunc in g_completion_new(), which retrieves the item's string from the data structure. Change the way in which strings are compared by setting a different GCompletionStrncmpFunc in g_completion_set_compare().

Details

GCompletion

typedef struct {
  GList* items;
  GCompletionFunc func;

  gchar* prefix;
  GList* cache;
  GCompletionStrncmpFunc strncmp_func;
} GCompletion;

The data structure used for automatic completion.

GList *items; | list of target items (strings or data structures).
GCompletionFunc func; | function which is called to get the string associated with a target item. It is NULL if the target items are strings.
gchar *prefix; | the last prefix passed to g_completion_complete() or g_completion_complete_utf8().
GList *cache; | the list of items which begin with prefix.
GCompletionStrncmpFunc strncmp_func; | The function to use when comparing strings. Use g_completion_set_compare() to modify this function.

g_completion_new ()

GCompletion* g_completion_new          (GCompletionFunc func);

Creates a new GCompletion.

func : | the function to be called to return the string representing an item in the GCompletion, or NULL if strings are going to be used as the GCompletion items.
Returns : | the new GCompletion

GCompletionFunc ()

gchar*      (*GCompletionFunc)         (gpointer);

Specifies the type of the function passed to g_completion_new(). It should return the string corresponding to the given target item. Use this function when data structures are used as GCompletion items.

Param1 : | the completion item
Returns : | the string corresponding to the item

g_completion_add_items ()

void        g_completion_add_items     (GCompletion *cmp, GList *items);

Adds items to the GCompletion.

cmp : | the GCompletion
items : | the list of items to add

g_completion_remove_items ()

void        g_completion_remove_items  (GCompletion *cmp, GList *items);

Removes items from a GCompletion.

cmp : | the GCompletion
items : | the items to remove

g_completion_clear_items ()

void        g_completion_clear_items   (GCompletion *cmp);

Removes all items from the GCompletion.

cmp : the GCompletion

g_completion_complete ()

GList*      g_completion_complete      (GCompletion *cmp, const gchar *prefix, gchar **new_prefix);

Attempts to complete the string prefix using the GCompletion target items.

cmp : | the GCompletion
prefix : | the prefix string, typically typed by the user, which is compared with each of the items.
new_prefix : | if non-NULL, returns the longest prefix which is common to all items that matched prefix, or NULL if no items matched prefix. This string should be freed when no longer needed.
Returns : | the list of items whose strings begin with prefix. This should not be changed.

g_completion_complete_utf8 ()

GList*      g_completion_complete_utf8      (GCompletion *cmp, const gchar *prefix, gchar **new_prefix);

Attempts to complete the string prefix using the GCompletion target items. In contrast to g_completion_complete(), this function returns the largest common prefix that is a valid UTF-8 string, omitting a possible common partial character.

Use this function instead of g_completion_complete() if the items are UTF-8 strings.

cmp : | the GCompletion
prefix : | the prefix string, typically used by the user, which is compared with each of the items
new_prefix : | if non-NULL, returns the longest prefix which is common to all items that matched prefix, or NULL if no items matched prefix. This string should be freed when no longer needed.
Returns : | the list of items whose strings begin with prefix. This should not be changed.

g_completion_set_compare ()

void        g_completion_set_compare        (GCompletion *cmp, GCompletionStrncmpFunc strncmp_func);

Sets the function to use for string comparisons. The default string comparison function is strncmp().

cmp : | a GCompletion
strncmp_func : | the string comparison function

GCompletionStrncmpFunc ()

gint        (*GCompletionStrncmpFunc)       (const gchar *s1, const gchar *s2, gsize n);

Specifies the type of the function passed to g_completion_set_compare(). Use this function when strings are used as GCompletion items.

s1 : | string to compare with s2.
s2 : | string to compare with s1.
n : | maximal number of bytes to compare.
Returns : | an integer less than, equal to, or greater than zero if the first n bytes of s1 is found, respectively, to be less than, to match, or to be greater than the first n bytes of s2.

g_completion_free ()

void        g_completion_free         (GCompletion *cmp);

Frees all memory used by the GCompletion.

cmp : a GCompletion

Feedback

For additional information or queries on this page send feedback


Balanced Binary Trees

Name

Balanced Binary Trees — a sorted collection of key/value pairs optimized for searching and traversing in order.

Library

glib.lib

Synopsis

#include <glib.h>

GTree;
GTree*      g_tree_new                   (GCompareFunc key_compare_func);
GTree*      g_tree_new_with_data         (GCompareDataFunc key_compare_func, gpointer key_compare_data);
GTree*      g_tree_new_full              (GCompareDataFunc key_compare_func, gpointer key_compare_data,
                                          GDestroyNotify key_destroy_func, GDestroyNotify value_destroy_func);

void        g_tree_insert                (GTree *tree, gpointer key, gpointer value);
void        g_tree_replace               (GTree *tree, gpointer key, gpointer value);
gint        g_tree_nnodes                (GTree *tree);
gint        g_tree_height                (GTree *tree);
gpointer    g_tree_lookup                (GTree *tree, gconstpointer key);
gboolean    g_tree_lookup_extended       (GTree *tree, gconstpointer lookup_key, gpointer *orig_key, gpointer *value);
void        g_tree_foreach               (GTree *tree, GTraverseFunc func, gpointer user_data);
void        g_tree_traverse              (GTree *tree, GTraverseFunc traverse_func, GTraverseType traverse_type,
                                          gpointer user_data);
gboolean    (*GTraverseFunc)             (gpointer key, gpointer value, gpointer data);
enum        GTraverseType;
gpointer    g_tree_search                (GTree *tree, GCompareFunc search_func, gconstpointer user_data);
gboolean    g_tree_remove                (GTree *tree, gconstpointer key);
gboolean    g_tree_steal                 (GTree *tree, gconstpointer key);
void        g_tree_destroy               (GTree *tree);

Detailed Description

The GTree structure and its associated functions provide a sorted collection of key/value pairs optimized for searching and traversing in order.

To create a new GTree use g_tree_new().

To insert a key/value pair into a GTree use g_tree_insert().

To lookup the value corresponding to a given key, use g_tree_lookup() and g_tree_lookup_extended().

To find out the number of nodes in a GTree, use g_tree_nnodes(). To get the height of a GTree, use g_tree_height().

To traverse a GTree, calling a function for each node visited in the traversal, use g_tree_foreach().

To remove a key/value pair use g_tree_remove().

To destroy a GTree, use g_tree_destroy().

Details

GTree

typedef struct _GTree GTree;

The GTree struct is an opaque data structure representing a Balanced Binary Tree. It should be accessed only by using the following functions.

g_tree_new ()

GTree*      g_tree_new     (GCompareFunc key_compare_func);

Creates a new GTree.

key_compare_func : | the function used to order the nodes in the GTree. It should return values similar to the standard strcmp() function - 0 if the two arguments are equal, a negative value if the first argument comes before the second, or a positive value if the first argument comes after the second.
Returns : | a new GTree.

g_tree_new_with_data ()

GTree*   g_tree_new_with_data       (GCompareDataFunc key_compare_func, gpointer key_compare_data);

Creates a new GTree with a comparison function that accepts user data. See g_tree_new() for more details.

key_compare_func : | qsort()-style comparison function.
key_compare_data : | data to pass to comparison function.
Returns : | a new GTree.

g_tree_new_full ()

GTree*   g_tree_new_full       (GCompareDataFunc key_compare_func, gpointer key_compare_data, GDestroyNotify key_destroy_func,
                                GDestroyNotify value_destroy_func);

Creates a new GTree like g_tree_new() and allows to specify functions to free the memory allocated for the key and value that get called when removing the entry from the GTree.

key_compare_func : | qsort()-style comparison function.
key_compare_data : | data to pass to comparison function.
key_destroy_func : | a function to free the memory allocated for the key used when removing the entry from the GTree or NULL when there is no need to supply such a function.
value_destroy_func : | a function to free the memory allocated for the value used when removing the entry from the GTree or NULL when there is no need to supply such a function.
Returns : | a new GTree.

g_tree_insert ()

void        g_tree_insert       (GTree *tree, gpointer key, gpointer value);

Inserts a key/value pair into a GTree. If the given key already exists in the GTree its corresponding value is set to the new value. If supplied with a value_destroy_func when creating the GTree, the old value is freed using that function. If supplied with a key_destroy_func when creating the GTree, the passed key is freed using that function.

The tree is automatically 'balanced' as new key/value pairs are added, so that the distance from the root to every leaf is as small as possible.

tree : | a GTree.
key : | the key to insert.
value : | the value corresponding to the key.

g_tree_replace ()

void        g_tree_replace      (GTree *tree, gpointer key, gpointer value);

Inserts a new key and value into a GTree similar to g_tree_insert(). The difference is that if the key already exists in the GTree, it gets replaced by the new key. If supplied with a value_destroy_func when creating the GTree, the old value is freed using that function. If supplied with a key_destroy_func when creating the GTree, the old key is freed using that function.

The tree is automatically 'balanced' as new key/value pairs are added, so that the distance from the root to every leaf is as small as possible.

tree : | a GTree.
key : | the key to insert.
value : | the value corresponding to the key.

g_tree_nnodes ()

gint        g_tree_nnodes         (GTree *tree);

Gets the number of nodes in a GTree.

tree : | a GTree.
Returns : | the number of nodes in the GTree.

g_tree_height ()

gint        g_tree_height         (GTree *tree);

Gets the height of a GTree.

If the GTree contains no nodes, the height is 0. If the GTree contains only one root node the height is 1. If the root node has children the height is 2, etc.

tree : | a GTree.
Returns : | the height of the GTree.

g_tree_lookup ()

gpointer    g_tree_lookup         (GTree *tree, gconstpointer key);

Gets the value corresponding to the given key. Since a GTree is automatically balanced as key/value pairs are added, key lookup is very fast.

tree : | a GTree.
key : | the key to look up.
Returns : | the value corresponding to the key, or NULL if the key was not found.

g_tree_lookup_extended ()

gboolean    g_tree_lookup_extended          (GTree *tree, gconstpointer lookup_key, gpointer *orig_key, gpointer *value);

Looks up a key in the GTree, returning the original key and the associated value and a gboolean which is TRUE if the key was found. This is useful if the memory allocated for the original key needs to be freed, for example before calling g_tree_remove().

tree : | a GTree.
lookup_key : | the key to look up.
orig_key : | returns the original key.
value : | returns the value associated with the key.
Returns : | TRUE if the key was found in the GTree.

g_tree_foreach ()

void        g_tree_foreach              (GTree *tree, GTraverseFunc func, gpointer user_data);

Calls the given function for each of the key/value pairs in the GTree. The function is passed the key and value of each pair, and the given data parameter. The tree is traversed in sorted order.

The tree may not be modified while iterating over it (cannot add/remove items). To remove all items matching a predicate, add each item to a list in the GTraverseFunc when traversing the tree, then walk the list and remove each item.

tree : | a GTree.
func : | the function to call for each node visited. If this function returns TRUE, the traversal is stopped.
user_data : | user data to pass to the function.

g_tree_traverse ()

void        g_tree_traverse         (GTree *tree, GTraverseFunc traverse_func, GTraverseType traverse_type, gpointer user_data);

Calls the given function for each node in the GTree.

Note

Warning: g_tree_traverse is deprecated and should not be used in newly-written code. The order of a balanced tree is somewhat arbitrary. To visit all nodes in sorted order, use g_tree_foreach() instead. To visit nodes in a different order, consider using an N-ary Tree.

tree : | a GTree.
traverse_func : | the function to call for each node visited. If this function returns TRUE, the traversal is stopped.
traverse_type : | the order in which nodes are visited, one of G_IN_ORDER, G_PRE_ORDER and G_POST_ORDER.
user_data : | user data to pass to the function.

GTraverseFunc ()

gboolean    (*GTraverseFunc)          (gpointer key, gpointer value, gpointer data);

Specifies the type of function passed to g_tree_traverse(). It is passed the key and value of each node, together with the user_data parameter passed to g_tree_traverse(). If the function returns TRUE, the traversal is stopped.

key : | a key of a GTree node.
value : | the value corresponding to the key.
data : | user data passed to g_tree_traverse().
Returns : | TRUE to stop the traversal.

enum GTraverseType

typedef enum
{
  G_IN_ORDER,
  G_PRE_ORDER,
  G_POST_ORDER,
  G_LEVEL_ORDER
} GTraverseType;

Specifies the type of traversal performed by g_tree_traverse(), g_node_traverse() and g_node_find().

G_IN_ORDER | visits a node's left child first, then the node itself, then its right child. This is the one to use if the output must be sorted according to the compare function.
G_PRE_ORDER | visits a node, then its children.
G_POST_ORDER | visits the node's children, then the node itself.
G_LEVEL_ORDER | is not implemented for Balanced Binary Trees. For N-ary Trees, it visits the root node first, then its children, then its grandchildren, and so on. Note that this is less efficient than the other orders.

g_tree_search ()

gpointer    g_tree_search           (GTree *tree, GCompareFunc search_func, gconstpointer user_data);

Searches a GTree using search_func.

The search_func is called with a pointer to the key of a key/value pair in the tree, and the passed in user_data. If search_func returns 0 for a key/value pair, then g_tree_search_func() will return the value of that pair. If search_func returns -1, searching will proceed among the key/value pairs that have a smaller key; if search_func returns 1, searching will proceed among the key/value pairs that have a larger key.

tree : | a GTree.
search_func : | a function used to search the GTree.
user_data : | the data passed as the second argument to the search_func function.
Returns : | the value corresponding to the found key, or NULL if the key was not found.

g_tree_remove ()

gboolean    g_tree_remove          (GTree *tree, gconstpointer key);

Removes a key/value pair from a GTree.

If the GTree was created using g_tree_new_full(), the key and value are freed using the supplied destroy functions, otherwise make sure that any dynamically allocated values are freed manually. If the key does not exist in the GTree, the function does nothing.

tree : | a GTree.
key : | the key to remove.
Returns : | TRUE if the key was found (prior to 2.8, this function returned nothing)

g_tree_steal ()

gboolean    g_tree_steal           (GTree *tree, gconstpointer key);

Removes a key and its associated value from a GTree without calling the key and value destroy functions.
If the key does not exist in the GTree, the function does nothing.

tree : | a GTree.
key : | the key to remove.
Returns : | TRUE if the key was found (prior to 2.8, this function returned nothing)

g_tree_destroy ()

void        g_tree_destroy         (GTree *tree);

Destroys the GTree. If keys and/or values are dynamically allocated, either free them first or create the GTree using g_tree_new_full(). In the latter case the destroy functions supplied will be called on all keys and values before destroying the GTree.

tree : a GTree.

Feedback

For additional information or queries on this page send feedback


Basic Types

Name

Basic Types — standard GLib types, defined for ease-of-use and portability.

Library

glib.lib

Synopsis

#include <glib.h>

typedef gboolean;
typedef gpointer;
typedef gconstpointer;
typedef gchar;
typedef guchar;

typedef gint;
typedef guint;
typedef gshort;
typedef gushort;
typedef glong;
typedef gulong;

typedef gint8;
typedef guint8;
typedef gint16;
typedef guint16;
typedef gint32;
typedef guint32;

#define G_HAVE_GINT64
typedef gint64;
typedef guint64;
#define
    G_GINT64_CONSTANT
    (val)

typedef gfloat;
typedef gdouble;

typedef gsize;
typedef gssize;

Detailed Description

GLib defines a number of commonly used types, which can be divided into 4 groups:

  • New types which are not part of standard C - gboolean, gsize, gssize.

  • Integer types which are guaranteed to be the same size across all platforms - gint8, guint8, gint16, guint16, gint32, guint32, gint64, guint64.

  • Types which are easier to use than their standard C counterparts - gpointer, gconstpointer, guchar, guint, gushort, gulong.

  • Types which correspond exactly to standard C types, but are included for completeness - gchar, gint, gshort, glong, gfloat, gdouble.

Details

gboolean

typedef gint   gboolean;

A standard boolean type. Variables of this type should only contain the value TRUE or FALSE.

gpointer

typedef void* gpointer;

An untyped pointer. gpointer looks better and is easier to use than void*.

gconstpointer

typedef const void *gconstpointer;

An untyped pointer to constant data. The data pointed to should not be changed.

This is typically used in function prototypes to indicate that the data pointed to will not be altered by the function.

gchar

typedef char   gchar;

Corresponds to the standard C char type.

guchar

typedef unsigned char   guchar;

Corresponds to the standard C unsigned char type.

gint

typedef int    gint;

Corresponds to the standard C int type. Values of this type can range from G_MININT to G_MAXINT.

guint

typedef unsigned int    guint;

Corresponds to the standard C unsigned int type. Values of this type can range from 0 to G_MAXUINT.

gshort

typedef  short gshort;

Corresponds to the standard C short type. Values of this type can range from G_MINSHORT to G_MAXSHORT.

gushort

typedef  unsigned short gushort;

Corresponds to the standard C unsigned short type. Values of this type can range from 0 to G_MAXUSHORT.

glong

typedef  long  glong;

Corresponds to the standard C long type. Values of this type can range from G_MINLONG to G_MAXLONG.

gulong

typedef unsigned long   gulong;

Corresponds to the standard C unsigned long type. Values of this type can range from 0 to G_MAXULONG.

gint8

typedef signed char gint8;

A signed integer guaranteed to be 8 bits on all platforms. Values of this type can range from -128 to 127.

guint8

typedef unsigned char guint8;

An unsigned integer guaranteed to be 8 bits on all platforms. Values of this type can range from 0 to 255.

gint16

typedef signed short gint16;

A signed integer guaranteed to be 16 bits on all platforms. Values of this type can range from -32,768 to 32,767.

guint16

typedef unsigned short guint16;

An unsigned integer guaranteed to be 16 bits on all platforms. Values of this type can range from 0 to 65,535.

gint32

typedef signed int gint32;

A signed integer guaranteed to be 32 bits on all platforms. Values of this type can range from -2,147,483,648 to 2,147,483,647.

guint32

typedef unsigned int guint32;

An unsigned integer guaranteed to be 32 bits on all platforms. Values of this type can range from 0 to 4,294,967,295.

G_HAVE_GINT64

#define G_HAVE_GINT64 1          /* deprecated, always true */

Warning

G_HAVE_GINT64 is deprecated and should not be used in newly-written code. GLib requires 64-bit integer support since version 2.0, therefore G_HAVE_GINT64 is always defined.

This macro is defined if 64-bit signed and unsigned integers are available on the platform.

gint64

G_GNUC_EXTENSION typedef signed long long gint64;

A signed integer guaranteed to be 64 bits on all platforms on which it is available (see G_HAVE_GINT64). Values of this type can range from -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807.

guint64

G_GNUC_EXTENSION typedef unsigned long long guint64;

An unsigned integer guaranteed to be 64 bits on all platforms on which it is available (see G_HAVE_GINT64). Values of this type can range from 0 to 18,446,744,073,709,551,615.

G_GINT64_CONSTANT()

#define G_GINT64_CONSTANT(val)	(G_GNUC_EXTENSION (val##LL))

This macro is used to insert 64-bit integer literals into the source code.

val : a literal integer value, e.g. 0x1d636b02300a7aa7U.

G_GUINT64_CONSTANT()

#define G_GUINT64_CONSTANT(val)	(G_GNUC_EXTENSION (val##ULL))

This macro is used to insert 64-bit unsigned integer literals into the source code.

val : a literal integer value, e.g. 0x1d636b02300a7aa7U

gfloat

typedef float   gfloat;

Corresponds to the standard C float type. Values of this type can range from -G_MAXFLOAT to G_MAXFLOAT.

gdouble

typedef double  gdouble;

Corresponds to the standard C double type. Values of this type can range from -G_MAXDOUBLE to G_MAXDOUBLE.

gsize

typedef unsigned int gsize;

An unsigned 32-bit integer intended to represent sizes of data structures.

gssize

typedef signed int gssize;

A signed 32-bit integer intended to represent sizes of data structures.

Feedback

For additional information or queries on this page send feedback


Byte Arrays

Name

Byte Arrays — arrays of bytes which grow automatically as elements are added.

Library

glib.lib

Synopsis

#include <glib.h>

GByteArray;
GByteArray* g_byte_array_new                  (void);
GByteArray* g_byte_array_sized_new            (guint reserved_size);
GByteArray* g_byte_array_append               (GByteArray *array, const guint8 *data, guint len);
GByteArray* g_byte_array_prepend              (GByteArray *array, const guint8 *data, guint len);
GByteArray* g_byte_array_remove_index         (GByteArray *array, guint index_);
GByteArray* g_byte_array_remove_index_fast    (GByteArray *array, guint index_);
GByteArray* g_byte_array_remove_range         (GByteArray *array, guint index_, guint length);
void        g_byte_array_sort                 (GByteArray *array, GCompareFunc compare_func);
void        g_byte_array_sort_with_data       (GByteArray *array, GCompareDataFunc compare_func, gpointer user_data);
GByteArray* g_byte_array_set_size             (GByteArray *array, guint length);
guint8*     g_byte_array_free                 (GByteArray *array, gboolean free_segment);

Detailed Description

GByteArray is based on GArray, to provide arrays of bytes which grow automatically as elements are added.

  • To create a new GByteArray use g_byte_array_new().
  • To add elements to a GByteArray, use g_byte_array_append(), and g_byte_array_prepend().
  • To set the size of a GByteArray, use g_byte_array_set_size().
  • To free a GByteArray, use g_byte_array_free().

Example 8. Using a GByteArray

  GByteArray *gbarray;
  gint i;

  gbarray = g_byte_array_new ();
  for (i = 0; i < 10000; i++)
    g_byte_array_append (gbarray, (guint8*) "abcd", 4);

  for (i = 0; i < 10000; i++)
    {
      g_assert (gbarray->data[4*i] == 'a');
      g_assert (gbarray->data[4*i+1] == 'b');
      g_assert (gbarray->data[4*i+2] == 'c');
      g_assert (gbarray->data[4*i+3] == 'd');
    }

  g_byte_array_free (gbarray, TRUE);

Details

GByteArray

typedef struct {
  guint8 *data;
  guint	  len;
} GByteArray;

The GByteArray struct allows access to the public fields of a GByteArray.

guint8 *data; | a pointer to the element data. The data may be moved as elements are added to the GByteArray.
guint len; | the number of elements in the GByteArray.

g_byte_array_new ()

GByteArray* g_byte_array_new              (void);

Creates a new GByteArray.

Returns : the new GByteArray.

g_byte_array_sized_new ()

GByteArray* g_byte_array_sized_new        (guint reserved_size);

Creates a new GByteArray with reserved_size bytes preallocated. This avoids frequent reallocation, when adding many bytes to the array. Note however that the size of the array is still 0.

reserved_size : | number of bytes preallocated.
Returns : | the new GByteArray.

g_byte_array_append ()

GByteArray* g_byte_array_append           (GByteArray *array, const guint8 *data, guint len);

Adds the given bytes to the end of the GByteArray. The array will grow in size automatically if necessary.

array : | a GByteArray.
data : | the byte data to be added.
len : | the number of bytes to add.
Returns : | the GByteArray.

g_byte_array_prepend ()

GByteArray* g_byte_array_prepend          (GByteArray *array, const guint8 *data, guint len);

Adds the given data to the start of the GByteArray. The array will grow in size automatically if necessary.

array : | a GByteArray.
data : | the byte data to be added.
len : | the number of bytes to add.
Returns : | the GByteArray.

g_byte_array_remove_index ()

GByteArray* g_byte_array_remove_index       (GByteArray *array, guint index_);

Removes the byte at the given index from a GByteArray. The following bytes are moved down one place.

array : | a GByteArray.
index_ : | the index of the byte to remove.
Returns : | the GByteArray.

g_byte_array_remove_index_fast ()

GByteArray* g_byte_array_remove_index_fast   (GByteArray *array, guint index_);

Removes the byte at the given index from a GByteArray. The last element in the array is used to fill in the space, so this function does not preserve the order of the GByteArray. But it is faster than g_byte_array_remove_index().

array : | a GByteArray.
index_ : | the index of the byte to remove.
Returns : | the GByteArray.

g_byte_array_remove_range ()

GByteArray* g_byte_array_remove_range       (GByteArray *array, guint index_, guint length);

Removes the given number of bytes starting at the given index from a GByteArray. The following elements are moved to close the gap.

array : | a GByteArray.
index_ : | the index of the first byte to remove.
length : | the number of bytes to remove.
Returns : | the GByteArray.

g_byte_array_sort ()

void       g_byte_array_sort         (GByteArray *array, GCompareFunc compare_func);

Sorts a byte array, using compare_func which should be a qsort()-style comparison function (returns -1 for first arg is less than second arg, 0 for equal, 1 if first arg is greater than second arg).

array : | a GByteArray.
compare_func : | comparison function.

g_byte_array_sort_with_data ()

void     g_byte_array_sort_with_data     (GByteArray *array, GCompareDataFunc compare_func, gpointer user_data);

Like g_byte_array_sort(), but the comparison function takes a user data argument.

array : | a GByteArray.
compare_func : | comparison function.
user_data : | data to pass to compare_func.

g_byte_array_set_size ()

GByteArray* g_byte_array_set_size     (GByteArray *array, guint length);

Sets the size of the GByteArray, expanding it if necessary.

array : | a GByteArray.
length : | the new size of the GByteArray.
Returns : | the GByteArray.

g_byte_array_free ()

guint8*     g_byte_array_free         (GByteArray *array, gboolean free_segment);

Frees the memory allocated by the GByteArray. If free_segment is TRUE it frees the actual byte data.

array : | a GByteArray.
free_segment : | if TRUE the actual byte data is freed as well.
Returns : | the element data if free_segment is FALSE, otherwise NULL

Feedback

For additional information or queries on this page send feedback


Byte Order Macros

Name

Byte Order Macros — a portable way to convert between different byte orders.

Library

glib.lib

Synopsis

#include <glib.h>

#define     G_BYTE_ORDER
#define     G_LITTLE_ENDIAN
#define     G_BIG_ENDIAN
#define     G_PDP_ENDIAN

#define     g_htonl              (val)
#define     g_htons              (val)
#define     g_ntohl              (val)
#define     g_ntohs              (val)

#define     GINT_FROM_BE         (val)
#define     GINT_FROM_LE         (val)
#define     GINT_TO_BE           (val)
#define     GINT_TO_LE           (val)

#define     GUINT_FROM_BE        (val)
#define     GUINT_FROM_LE        (val)
#define     GUINT_TO_BE          (val)
#define     GUINT_TO_LE          (val)

#define     GLONG_FROM_BE        (val)
#define     GLONG_FROM_LE        (val)
#define     GLONG_TO_BE          (val)
#define     GLONG_TO_LE          (val)

#define     GULONG_FROM_BE       (val)
#define     GULONG_FROM_LE       (val)
#define     GULONG_TO_BE         (val)
#define     GULONG_TO_LE         (val)

#define     GINT16_FROM_BE       (val)
#define     GINT16_FROM_LE       (val)
#define     GINT16_TO_BE         (val)
#define     GINT16_TO_LE         (val)

#define     GUINT16_FROM_BE      (val)
#define     GUINT16_FROM_LE      (val)
#define     GUINT16_TO_BE        (val)
#define     GUINT16_TO_LE        (val)

#define     GINT32_FROM_BE       (val)
#define     GINT32_FROM_LE       (val)
#define     GINT32_TO_BE         (val)
#define     GINT32_TO_LE         (val)

#define     GUINT32_FROM_BE      (val)
#define     GUINT32_FROM_LE      (val)
#define     GUINT32_TO_BE        (val)
#define     GUINT32_TO_LE        (val)

#define     GINT64_FROM_BE       (val)
#define     GINT64_FROM_LE       (val)
#define     GINT64_TO_BE         (val)
#define     GINT64_TO_LE         (val)

#define     GUINT64_FROM_BE      (val)
#define     GUINT64_FROM_LE      (val)
#define     GUINT64_TO_BE        (val)
#define     GUINT64_TO_LE        (val)

#define     GUINT16_SWAP_BE_PDP  (val)
#define     GUINT16_SWAP_LE_BE   (val)
#define     GUINT16_SWAP_LE_PDP  (val)

#define     GUINT32_SWAP_BE_PDP  (val)
#define     GUINT32_SWAP_LE_BE   (val)
#define     GUINT32_SWAP_LE_PDP  (val)

#define     GUINT64_SWAP_LE_BE   (val)

Detailed Description

These macros provide a portable way to determine the host byte order and to convert values between different byte orders.

The byte order is the order in which bytes are stored to create larger data types such as the gint and glong values. The host byte order is the byte order used on the current machine.

Some processors store the most significant bytes (i.e. the bytes that hold the largest part of the value) first. These are known as big-endian processors.

Other processors (notably the x86 family) store the most significant byte last. These are known as little-endian processors.

Finally, to complicate matters, some other processors store the bytes in a rather curious order known as PDP-endian. For a 4-byte word, the 3rd most significant byte is stored first, then the 4th, then the 1st and finally the 2nd.

Obviously there is a problem when these different processors communicate with each other, for example over networks or by using binary file formats. This is where these macros come in. They are typically used to convert values into a byte order which has been agreed on for use when communicating between different processors. The Internet uses what is known as 'network byte order' as the standard byte order (which is in fact the big-endian byte order).

Note that the byte order conversion macros may evaluate their arguments multiple times, thus do not use them with arguments which have side-effects.

Details

G_BYTE_ORDER

#define G_BYTE_ORDER G_LITTLE_ENDIAN

The host byte order. This can be either G_LITTLE_ENDIAN or G_BIG_ENDIAN (support for G_PDP_ENDIAN may be added in future.)

G_LITTLE_ENDIAN

#define G_LITTLE_ENDIAN 1234

Specifies one of the possible types of byte order. See G_BYTE_ORDER.

G_BIG_ENDIAN

#define G_BIG_ENDIAN    4321

Specifies one of the possible types of byte order. See G_BYTE_ORDER.

G_PDP_ENDIAN

#define G_PDP_ENDIAN    3412		/* unused, need specific PDP check */

Specifies one of the possible types of byte order (currently unused). See G_BYTE_ORDER.

g_htonl()

#define     g_htonl(val)

Converts a 32-bit integer value from host to network byte order.

val : | a 32-bit integer value in host byte order.
Returns : | val converted to network byte order.

g_htons()

#define     g_htons(val)

Converts a 16-bit integer value from host to network byte order.

val : | a 16-bit integer value in host byte order.
Returns : | val converted to network byte order.

g_ntohl()

#define     g_ntohl(val)

Converts a 32-bit integer value from network to host byte order.

val : | a 32-bit integer value in network byte order.
Returns : | val converted to host byte order.

g_ntohs()

#define     g_ntohs(val)

Converts a 16-bit integer value from network to host byte order.

val : | a 16-bit integer value in network byte order.
Returns : | val converted to host byte order.

GINT_FROM_BE()

#define GINT_FROM_BE(val)	(GINT_TO_BE (val))

Converts a gint value from big-endian to host byte order.

val : | a gint value in big-endian byte order.
Returns : | val converted to host byte order.

GINT_FROM_LE()

#define GINT_FROM_LE(val)	(GINT_TO_LE (val))

Converts a gint value from little-endian to host byte order.

val : | a gint value in little-endian byte order.
Returns : | val converted to host byte order.

GINT_TO_BE()

#define GINT_TO_BE(val)		((gint) GINT32_TO_BE (val))

Converts a gint value from host byte order to big-endian.

val : | a gint value in host byte order.
Returns : | val converted to big-endian byte order.

GINT_TO_LE()

#define GINT_TO_LE(val)		((gint) GINT32_TO_LE (val))

Converts a gint value from host byte order to little-endian.

val : | a gint value in host byte order.
Returns : | val converted to little-endian byte order.

GUINT_FROM_BE()

#define GUINT_FROM_BE(val)	(GUINT_TO_BE (val))

Converts a guint value from big-endian to host byte order.

val : | a guint value in big-endian byte order.
Returns : | val converted to host byte order.

GUINT_FROM_LE()

#define GUINT_FROM_LE(val)	(GUINT_TO_LE (val))

Converts a guint value from little-endian to host byte order.

val : | a guint value in little-endian byte order.
Returns : | val converted to host byte order.

GUINT_TO_BE()

#define GUINT_TO_BE(val)	((guint) GUINT32_TO_BE (val))

Converts a guint value from host byte order to big-endian.

val : | a guint value in host byte order.
Returns : | val converted to big-endian byte order.

GUINT_TO_LE()

#define GUINT_TO_LE(val)	((guint) GUINT32_TO_LE (val))

Converts a guint value from host byte order to little-endian.

val : | a guint value in host byte order.
Returns : | val converted to little-endian byte order.

GLONG_FROM_BE()

#define GLONG_FROM_BE(val)	(GLONG_TO_BE (val))

Converts a glong value from big-endian to the host byte order.

val : | a glong value in big-endian byte order.
Returns : | val converted to host byte order.

GLONG_FROM_LE()

#define GLONG_FROM_LE(val)	(GLONG_TO_LE (val))

Converts a glong value from little-endian to host byte order.

val : | a glong value in little-endian byte order.
Returns : | val converted to host byte order.

GLONG_TO_BE()

#define GLONG_TO_BE(val)	((glong) GINT32_TO_BE (val))

Converts a glong value from host byte order to big-endian.

val : | a glong value in host byte order.
Returns : | val converted to big-endian byte order.

GLONG_TO_LE()

#define GLONG_TO_LE(val)	((glong) GINT32_TO_LE (val))

Converts a glong value from host byte order to little-endian.

val : | a glong value in host byte order.
Returns : | val converted to little-endian.

GULONG_FROM_BE()

#define GULONG_FROM_BE(val)	(GULONG_TO_BE (val))

Converts a gulong value from big-endian to host byte order.

val : | a gulong value in big-endian byte order.
Returns : | val converted to host byte order.

GULONG_FROM_LE()

#define GULONG_FROM_LE(val)	(GULONG_TO_LE (val))

Converts a gulong value from little-endian to host byte order.

val : | a gulong value in little-endian byte order.
Returns : | val converted to host byte order.

GULONG_TO_BE()

#define GULONG_TO_BE(val)	((gulong) GUINT32_TO_BE (val))

Converts a gulong value from host byte order to big-endian.

val : | a gulong value in host byte order.
Returns : | val converted to big-endian.

GULONG_TO_LE()

#define GULONG_TO_LE(val)	((gulong) GUINT32_TO_LE (val))

Converts a gulong value from host byte order to little-endian.

val : | a gulong value in host byte order.
Returns : | val converted to little-endian.

GINT16_FROM_BE()

#define GINT16_FROM_BE(val)	(GINT16_TO_BE (val))

Converts a gint16 value from big-endian to host byte order.

val : | a gint16 value in big-endian byte order.
Returns : | val converted to host byte order.

GINT16_FROM_LE()

#define GINT16_FROM_LE(val)	(GINT16_TO_LE (val))

Converts a gint16 value from little-endian to host byte order.

val : | a gint16 value in little-endian byte order.
Returns : | val converted to host byte order.

GINT16_TO_BE()

#define GINT16_TO_BE(val)	((gint16) GUINT16_SWAP_LE_BE (val))

Converts a gint16 value from host byte order to big-endian.

val : | a gint16 value in host byte order.
Returns : | val converted to big-endian.

GINT16_TO_LE()

#define GINT16_TO_LE(val)	((gint16) (val))

Converts a gint16 value from host byte order to little-endian.

val : | a gint16 value in host byte order.
Returns : | val converted to little-endian.

GUINT16_FROM_BE()

#define GUINT16_FROM_BE(val)	(GUINT16_TO_BE (val))

Converts a guint16 value from big-endian to host byte order.

val : | a guint16 value in big-endian byte order.
Returns : | val converted to host byte order.

GUINT16_FROM_LE()

#define GUINT16_FROM_LE(val)	(GUINT16_TO_LE (val))

Converts a guint16 value from little-endian to host byte order.

val : | a guint16 value in little-endian byte order.
Returns : | val converted to host byte order.

GUINT16_TO_BE()

#define GUINT16_TO_BE(val)	(GUINT16_SWAP_LE_BE (val))

Converts a guint16 value from host byte order to big-endian.

val : | a guint16 value in host byte order.
Returns : | val converted to big-endian.

GUINT16_TO_LE()

#define GUINT16_TO_LE(val)	((guint16) (val))

Converts a guint16 value from host byte order to little-endian.

val : | a guint16 value in host byte order.
Returns : | val converted to little-endian.

GINT32_FROM_BE()

#define GINT32_FROM_BE(val)	(GINT32_TO_BE (val))

Converts a gint32 value from big-endian to host byte order.

val : | a gint32 value in big-endian byte order.
Returns : | val converted to host byte order.

GINT32_FROM_LE()

#define GINT32_FROM_LE(val)	(GINT32_TO_LE (val))

Converts a gint32 value from little-endian to host byte order.

val : | a gint32 value in little-endian byte order.
Returns : | val converted to host byte order.

GINT32_TO_BE()

#define GINT32_TO_BE(val)	((gint32) GUINT32_SWAP_LE_BE (val))

Converts a gint32 value from host byte order to big-endian.

val : | a gint32 value in host byte order.
Returns : | val converted to big-endian.

GINT32_TO_LE()

#define GINT32_TO_LE(val)	((gint32) (val))

Converts a gint32 value from host byte order to little-endian.

val : | a gint32 value in host byte order.
Returns : | val converted to little-endian.

GUINT32_FROM_BE()

#define GUINT32_FROM_BE(val)	(GUINT32_TO_BE (val))

Converts a guint32 value from big-endian to host byte order.

val : | a guint32 value in big-endian byte order.
Returns : | val converted to host byte order.

GUINT32_FROM_LE()

#define GUINT32_FROM_LE(val)	(GUINT32_TO_LE (val))

Converts a guint32 value from little-endian to host byte order.

val : | a guint32 value in little-endian byte order.
Returns : | val converted to host byte order.

GUINT32_TO_BE()

#define GUINT32_TO_BE(val)	(GUINT32_SWAP_LE_BE (val))

Converts a guint32 value from host byte order to big-endian.

val : | a guint32 value in host byte order.
Returns : | val converted to big-endian.

GUINT32_TO_LE()

#define GUINT32_TO_LE(val)	((guint32) (val))

Converts a guint32 value from host byte order to little-endian.

val : | a guint32 value in host byte order.
Returns : | val converted to little-endian.

GINT64_FROM_BE()

#define GINT64_FROM_BE(val)	(GINT64_TO_BE (val))

Converts a gint64 value from big-endian to host byte order.

val : | a gint64 value in big-endian byte order.
Returns : | val converted to host byte order.

GINT64_FROM_LE()

#define GINT64_FROM_LE(val)	(GINT64_TO_LE (val))

Converts a gint64 value from little-endian to host byte order.

val : | a gint64 value in little-endian byte order.
Returns : | val converted to host byte order.

GINT64_TO_BE()

#define GINT64_TO_BE(val)	((gint64) GUINT64_SWAP_LE_BE (val))

Converts a gint64 value from host byte order to big-endian.

val : | a gint64 value in host byte order.
Returns : | val converted to big-endian.

GINT64_TO_LE()

#define GINT64_TO_LE(val)	((gint64) (val))

Converts a gint64 value from host byte order to little-endian.

val : | a gint64 value in host byte order.
Returns : | val converted to little-endian.

GUINT64_FROM_BE()

#define GUINT64_FROM_BE(val)	(GUINT64_TO_BE (val))

Converts a guint64 value from big-endian to host byte order.

val : | a guint64 value in big-endian byte order.
Returns : | val converted to host byte order.

GUINT64_FROM_LE()

#define GUINT64_FROM_LE(val)	(GUINT64_TO_LE (val))

Converts a guint64 value from little-endian to host byte order.

val : | a guint64 value in little-endian byte order.
Returns : | val converted to host byte order.

GUINT64_TO_BE()

#define GUINT64_TO_BE(val)	(GUINT64_SWAP_LE_BE (val))

Converts a guint64 value from host byte order to big-endian.

val : | a guint64 value in host byte order.
Returns : | val converted to big-endian.

GUINT64_TO_LE()

#define GUINT64_TO_LE(val)	((guint64) (val))

Converts a guint64 value from host byte order to little-endian.

val : | a guint64 value in host byte order.
Returns : | val converted to little-endian.

GUINT16_SWAP_BE_PDP()

#define GUINT16_SWAP_BE_PDP(val)	(GUINT16_SWAP_LE_BE (val))

Converts a guint16 value between big-endian and pdp-endian byte order. The conversion is symmetric so it can be used both ways.

val : | a guint16 value in big-endian or pdp-endian byte order.
Returns : | val converted to the opposite byte order.

GUINT16_SWAP_LE_BE()

#define     GUINT16_SWAP_LE_BE(val)

Converts a guint16 value between little-endian and big-endian byte order. The conversion is symmetric so it can be used both ways.

val : | a guint16 value in little-endian or big-endian byte order.
Returns : | val converted to the opposite byte order.

GUINT16_SWAP_LE_PDP()

#define GUINT16_SWAP_LE_PDP(val)	((guint16) (val))

Converts a guint16 value between little-endian and pdp-endian byte order. The conversion is symmetric so it can be used both ways.

val : | a guint16 value in little-endian or pdp-endian byte order.
Returns : | val converted to the opposite byte order.

GUINT32_SWAP_BE_PDP()

#define     GUINT32_SWAP_BE_PDP(val)

Converts a guint32 value between big-endian and pdp-endian byte order. The conversion is symmetric so it can be used both ways.

val : | a guint32 value in big-endian or pdp-endian byte order.
Returns : | val converted to the opposite byte order.

GUINT32_SWAP_LE_BE()

#define     GUINT32_SWAP_LE_BE(val)

Converts a guint32 value between little-endian and big-endian byte order. The conversion is symmetric so it can be used both ways.

val : | a guint32 value in little-endian or big-endian byte order.
Returns : | val converted to the opposite byte order.

GUINT32_SWAP_LE_PDP()

#define     GUINT32_SWAP_LE_PDP(val)

Converts a guint32 value between little-endian and pdp-endian byte order. The conversion is symmetric so it can be used both ways.

val : | a guint32 value in little-endian or pdp-endian byte order.
Returns : | val converted to the opposite byte order.

GUINT64_SWAP_LE_BE()

#define     GUINT64_SWAP_LE_BE(val)

Converts a guint64 value between little-endian and big-endian byte order. The conversion is symmetric so it can be used both ways.

val : | a guint64 value in little-endian or big-endian byte order.
Returns : | val converted to the opposite byte order.

Feedback

For additional information or queries on this page send feedback


Caches

Name

Caches — sharing of complex data structures, in order to save system resources.

Library

glib.lib

Synopsis

#include <glib.h>

GCache;
GCache*    g_cache_new                     (GCacheNewFunc value_new_func, GCacheDestroyFunc value_destroy_func,
                                            GCacheDupFunc key_dup_func, GCacheDestroyFunc key_destroy_func,
                                            GHashFunc hash_key_func, GHashFunc hash_value_func, GEqualFunc key_equal_func);
gpointer   g_cache_insert                  (GCache *cache, gpointer key);
void       g_cache_remove                  (GCache *cache, gconstpointer value);
void       g_cache_destroy                 (GCache *cache);

void       g_cache_key_foreach             (GCache *cache, GHFunc func, gpointer user_data);
void       g_cache_value_foreach           (GCache *cache, GHFunc func, gpointer user_data);

void       (*GCacheDestroyFunc)            (gpointer value);
gpointer   (*GCacheDupFunc)                (gpointer value);
gpointer   (*GCacheNewFunc)                (gpointer key);

Detailed Description

A GCache allows sharing of complex data structures, in order to save system resources.

GTK+ uses caches for GtkStyles and GdkGCs. These consume a lot of resources, so a GCache is used to see if a GtkStyle or GdkGC with the required properties already exists. If it does, then the existing object is used instead of creating a new one.

GCache uses keys and values. A GCache key describes the properties of a particular resource. A GCache value is the actual resource.

Details

GCache

typedef struct _GCache GCache;

The GCache struct is an opaque data structure containing information about a GCache. It should only be accessed via the following functions.

g_cache_new ()

GCache*     g_cache_new              (GCacheNewFunc value_new_func, GCacheDestroyFunc value_destroy_func,
                                      GCacheDupFunc key_dup_func, GCacheDestroyFunc key_destroy_func,
                                      GHashFunc hash_key_func, GHashFunc hash_value_func, GEqualFunc key_equal_func);

Creates a new GCache.

value_new_func : | a function to create a new object given a key. This is called by g_cache_insert() if an object with the given key does not already exist.
value_destroy_func : | a function to destroy an object. It is called by g_cache_remove() when the object is no longer needed (i.e. its reference count drops to 0).
key_dup_func : | a function to copy a key. It is called by g_cache_insert() if the key does not already exist in the GCache.
key_destroy_func : | a function to destroy a key. It is called by g_cache_remove() when the object is no longer needed (i.e. its reference count drops to 0).
hash_key_func : | a function to create a hash value from a key.
hash_value_func : | a function to create a hash value from a value.
key_equal_func : | a function to compare two keys. It should return TRUE if the two keys are equivalent.
Returns : | a new GCache.

g_cache_insert ()

gpointer    g_cache_insert           (GCache *cache, gpointer key);

Gets the value corresponding to the given key, creating it if necessary. It first checks if the value already exists in the GCache, by using the key_equal_func function passed to g_cache_new(). If it does already exist it is returned, and its reference count is increased by one. If the value does not currently exist, if is created by calling the value_new_func. The key is duplicated by calling key_dup_func and the duplicated key and value are inserted into the GCache.

cache : | a GCache.
key : | a key describing a GCache object.
Returns : | a pointer to a GCache value.

g_cache_remove ()

void        g_cache_remove           (GCache *cache, gconstpointer value);

Decreases the reference count of the given value. If it drops to 0 then the value and its corresponding key are destroyed, using the value_destroy_func and key_destroy_func passed to g_cache_new().

cache : | a GCache.
value : | the value to remove.

g_cache_destroy ()

void        g_cache_destroy          (GCache *cache);

Frees the memory allocated for the GCache.
Note that it does not destroy the keys and values which were contained in the GCache.

cache : a GCache.

g_cache_key_foreach ()

void        g_cache_key_foreach      (GCache *cache, GHFunc func, gpointer user_data);

Calls the given function for each of the keys in the GCache.

Note

func is passed three parameters, the value and key of a cache entry and the user_data. The order of value and key is different from the order in which g_hash_table_foreach() passes key-value pairs to its callback function !

cache : | a GCache.
func : | the function to call with each GCache key.
user_data : | user data to pass to the function.

g_cache_value_foreach ()

void        g_cache_value_foreach     (GCache *cache, GHFunc func, gpointer user_data);

Calls the given function for each of the values in the GCache.

Warning

g_cache_value_foreach has been deprecated since version 2.10 and should not be used in newly-written code. The reason is that it passes pointers to internal data structures to func; use g_cache_key_foreach() instead

cache : | a GCache.
func : | the function to call with each GCache value.
user_data : | user data to pass to the function.

GCacheDestroyFunc ()

void        (*GCacheDestroyFunc)      (gpointer value);

Specifies the type of the value_destroy_func and key_destroy_func functions passed to g_cache_new(). The functions are passed a pointer to the GCache key or GCache value and should free any memory and other resources associated with it.

value : the GCache value to destroy.

GCacheDupFunc ()

gpointer    (*GCacheDupFunc)          (gpointer value);

Specifies the type of the key_dup_func function passed to g_cache_new(). The function is passed a key (not a value as the prototype implies) and should return a duplicate of the key.

value : | the GCache key to destroy (not a GCache value as it seems).
Returns : | a copy of the GCache key.

GCacheNewFunc ()

gpointer    (*GCacheNewFunc)          (gpointer key);

Specifies the type of the value_new_func function passed to g_cache_new(). It is passed a GCache key and should create the value corresponding to the key.

key : | a GCache key.
Returns : | a new GCache value corresponding to the key.

Feedback

For additional information or queries on this page send feedback


Character Set Conversion

Name

Character Set Conversion — convert strings between different character sets using iconv().

Library

glib.lib

Synopsis

#include <glib.h>

gchar*      g_convert                       (const gchar *str, gssize len, const gchar *to_codeset, const gchar *from_codeset,
                                             gsize *bytes_read, gsize *bytes_written, GError **error);
gchar*      g_convert_with_fallback         (const gchar *str, gssize len, const gchar *to_codeset, const gchar *from_codeset,
                                             gchar *fallback, gsize *bytes_read, gsize *bytes_written, GError **error);
            GIConv;
gchar*      g_convert_with_iconv            (const gchar *str, gssize len, GIConv converter, gsize *bytes_read,
                                             gsize *bytes_written, GError **error);
#define     G_CONVERT_ERROR
GIConv      g_iconv_open                    (const gchar *to_codeset, const gchar *from_codeset);
size_t      g_iconv                         (GIConv converter, gchar **inbuf, gsize *inbytes_left, gchar **outbuf,
                                             gsize *outbytes_left);
gint        g_iconv_close                   (GIConv converter);
gchar*      g_locale_to_utf8                (const gchar *opsysstring, gssize len, gsize *bytes_read, gsize *bytes_written,
                                             GError **error);
gchar*      g_filename_to_utf8              (const gchar *opsysstring, gssize len, gsize *bytes_read, gsize *bytes_written,
                                             GError **error);
gchar*      g_filename_from_utf8            (const gchar *utf8string, gssize len, gsize *bytes_read, gsize *bytes_written,
                                             GError **error);
gchar*      g_filename_from_uri             (const gchar *uri, gchar **hostname, GError **error);
gchar*      g_filename_to_uri               (const gchar *filename, const gchar *hostname, GError **error);
gboolean    g_get_filename_charsets         (G_CONST_RETURN gchar ***charsets);
gchar*      g_filename_display_name         (const gchar *filename);
gchar*      g_filename_display_basename     (const gchar *filename);
gchar**     g_uri_list_extract_uris         (const gchar *uri_list);
gchar*      g_locale_from_utf8              (const gchar *utf8string, gssize len, gsize *bytes_read, gsize *bytes_written,
                                             GError **error);
enum        GConvertError;

gboolean    g_get_charset                   (G_CONST_RETURN char **charset);

Detailed Description

File Name Encodings

Historically, Unix has not had a defined encoding for file names: a file name is valid as long as it does not have path separators in it ("/"). However, displaying file names may require conversion: from the character set in which they were created, to the character set in which the application operates. Consider the Spanish file name "Presentación.sxi". If the application which created it uses ISO-8859-1 for its encoding, then the actual file name on disk would look like this:

Character:  P  r  e  s  e  n  t  a  c  i  ó  n  .  s  x  i
Hex code:   50 72 65 73 65 6e 74 61 63 69 f3 6e 2e 73 78 69

However, if the application uses UTF-8, the actual file name on disk would look like this:

Character:  P  r  e  s  e  n  t  a  c  i  ó     n  .  s  x  i
Hex code:   50 72 65 73 65 6e 74 61 63 69 c3 b3 6e 2e 73 78 69

Glib uses UTF-8 for its strings, and GUI toolkits like GTK+ that use Glib do the same thing. If a file name is obtained from the file system, for example, from readdir(3) or from g_dir_read_name(), then the file name must be converted into UTF -8 before displaying it to the user. The opposite case is when the user types the name of a file and wishes to save: the toolkit will give a string in UTF-8 encoding, that needs to be converted to the character set used for file names before the file can be created either with open(2), or fopen(3).

By default, Glib assumes that file names on disk are in UTF-8 encoding. This is a valid assumption for file systems which were created relatively recently, most applications use UTF-8 encoding for their strings and that is also what they use for the file names they create. However, older file systems may still contain file names created in "older" encodings, such as ISO-8859-1. In this case, for compatibility reasons, instruct Glib to use that particular encoding for file names rather than UTF-8. This can be done by specifying the encoding for file names in the G_FILENAME_ENCODING environment variable. For example, if the installation uses ISO-8859-1 for file names, put this in the ~/.profile:

export G_FILENAME_ENCODING=ISO-8859-1

Glib provides the functions g_filename_to_utf8() and g_filename_from_utf8() to perform the necessary conversions. These functions convert file names from the encoding specified in G_FILENAME_ENCODING to UTF-8 and vice-versa. Figure 1, “Conversion between File Name Encodings” illustrates how these functions are used to convert between UTF-8 and the encoding for file names in the file system.

Figure 1. Conversion between File Name Encodings

Conversion between File Name Encodings

Checklist for Application Writers

This section is a practical summary of the detailed description above. Use this as a checklist of things to do, to make sure the application's process file name encodings correctly.

  1. If a file name is obtained from the file system, from a function such as readdir(3) or gtk_file_chooser_get_filename(), there is no need to performany conversion to pass that file name to functions like open(2), rename(2), or fopen(3) — those are "raw" file names which the file system understands.

  2. If there is a need to display a file name, convert it to UTF-8 first by using g_filename_to_utf8(). If the conversion fails, display a string like "Unknown file name". Do not convert this string back into the encoding used for file names if is has to be passed to the file system; use the original file name instead. For example, the document window of a word processor could display "Unknown file name" in its title bar but still let the user save the file, as it would keep the raw file name internally. This can happen if the user has not set the G_FILENAME_ENCODING environment variable even though the user has files whose names are not encoded in UTF-8.

  3. If the user interface lets the user type a file name for saving or renaming, convert it to the encoding used for file names in the file system by using g_filename_from_utf8(). Pass the converted file name to functions like fopen(3). If conversion fails, ask the user to enter a different file name. This can happen if the user types Japanese characters when G_FILENAME_ENCODING is set to ISO-8859-1, for example.

Details

g_convert ()

gchar*      g_convert           (const gchar *str, gssize len, const gchar *to_codeset, const gchar *from_codeset,
                                 gsize *bytes_read, gsize *bytes_written, GError **error);

Converts a string from one character set to another.

Use g_iconv() for streaming conversions[2].

str : | the string to convert
len : | the length of the string, or -1 if the string is nul-terminated[1].
to_codeset : | name of character set into which to convert str
from_codeset : | character set of str.
bytes_read : | location to store the number of bytes in the input string that were successfully converted, or NULL. Even if the conversion was successful, this may be less than len if there were partial characters at the end of the input. If the error G_CONVERT_ERROR_ILLEGAL_SEQUENCE occurs, the value stored will the byte offset after the last valid input sequence.
bytes_written : | the number of bytes stored in the output buffer (not including the terminating nul).
error : | location to store the error occurring, or NULL to ignore errors. Any of the errors in GConvertError may occur.
Returns : | If the conversion was successful, a newly allocated nul-terminated string, which must be freed with g_free(). Otherwise NULL and error will be set.

g_convert_with_fallback ()

gchar*     g_convert_with_fallback       (const gchar *str, gssize len, const gchar *to_codeset, const gchar *from_codeset,
                                          gchar *fallback, gsize *bytes_read, gsize *bytes_written, GError **error);

Converts a string from one character set to another, possibly including fallback sequences for characters not representable in the output. Note that it is not guaranteed that the specification for the fallback sequences in fallback will be honored. Some systems may do a approximate conversion from from_codeset to to_codeset in their iconv() functions, in which case GLib will simply return that approximate conversion.

Use g_iconv() for streaming conversions[2].

str : | the string to convert
len : | the length of the string, or -1 if the string is nul-terminated[1].
to_codeset : | name of character set into which to convert str
from_codeset : | character set of str.
fallback : | UTF-8 string to use in place of character not present in the target encoding. (The string must be representable in the target encoding). If NULL, characters not in the target encoding will be represented as Unicode escapes \uxxxx or \Uxxxxyyyy.
bytes_read : | location to store the number of bytes in the input string that were successfully converted, or NULL. Even if the conversion was successful, this may be less than len if there were partial characters at the end of the input.
bytes_written : | the number of bytes stored in the output buffer (not including the terminating nul).
error : | location to store the error occurring, or NULL to ignore errors. Any of the errors in GConvertError may occur.
Returns : | If the conversion was successful, a newly allocated nul-terminated string, which must be freed with g_free(). Otherwise NULL and error will be set.

GIConv

typedef struct _GIConv GIConv;

The GIConv struct wraps an iconv() conversion descriptor. It contains private data and should only be accessed using the following functions.

g_convert_with_iconv ()

gchar*    g_convert_with_iconv       (const gchar *str, gssize len, GIConv converter, gsize *bytes_read, gsize *bytes_written,
                                      GError **error);

Converts a string from one character set to another.

Use g_iconv() for streaming conversions[2].

str : | the string to convert
len : | the length of the string, or -1 if the string is nul-terminated[1].
converter : | conversion descriptor from g_iconv_open()
bytes_read : | location to store the number of bytes in the input string that were successfully converted, or NULL. Even if the conversion was successful, this may be less than len if there were partial characters at the end of the input. If the error G_CONVERT_ERROR_ILLEGAL_SEQUENCE occurs, the value stored will the byte offset after the last valid input sequence.
bytes_written : | the number of bytes stored in the output buffer (not including the terminating nul).
error : | location to store the error occurring, or NULL to ignore errors. Any of the errors in GConvertError may occur.
Returns : | If the conversion was successful, a newly allocated nul-terminated string, which must be freed with g_free(). Otherwise NULL and error will be set.

G_CONVERT_ERROR

#define G_CONVERT_ERROR g_convert_error_quark()

Error domain for character set conversions. Errors in this domain will be from the GConvertError enumeration. See GError for information on error domains.

g_iconv_open ()

GIConv      g_iconv_open           (const gchar *to_codeset, const gchar *from_codeset);

Same as the standard UNIX routine iconv_open(), but may be implemented via libiconv on UNIX flavors that lack a native implementation.

GLib provides g_convert() and g_locale_to_utf8() which are likely more convenient than the raw iconv wrappers.

to_codeset : | destination codeset
from_codeset : | source codeset
Returns : | a "conversion descriptor", or (GIConv)-1 if opening the converter failed.

g_iconv ()

size_t      g_iconv             (GIConv converter, gchar **inbuf, gsize *inbytes_left, gchar **outbuf, gsize *outbytes_left);

Same as the standard UNIX routine iconv(), but may be implemented via libiconv on UNIX flavors that lack a native implementation.

GLib provides g_convert() and g_locale_to_utf8() which are likely more convenient than the raw iconv wrappers.

converter : | conversion descriptor from g_iconv_open()
inbuf : | bytes to convert
inbytes_left : | inout parameter, bytes remaining to convert in inbuf
outbuf : | converted output bytes
outbytes_left : | inout parameter, bytes available to fill in outbuf
Returns : | count of non-reversible conversions, or -1 on error

g_iconv_close ()

gint        g_iconv_close       (GIConv converter);

Same as the standard UNIX routine iconv_close(), but may be implemented via libiconv on UNIX flavors that lack a native implementation. Should be called to clean up the conversion descriptor from g_iconv_open() when conversion is completed.

GLib provides g_convert() and g_locale_to_utf8() which are likely more convenient than the raw iconv wrappers.

converter : | a conversion descriptor from g_iconv_open()
Returns : | -1 on error, 0 on success

g_locale_to_utf8 ()

gchar*      g_locale_to_utf8    (const gchar *opsysstring, gssize len, gsize *bytes_read, gsize *bytes_written, GError **error);

Converts a string which is in the encoding used for strings by the C runtime (usually the same as that used by the operating system) in the current locale into a UTF-8 string.

opsysstring : | a string in the encoding of the current locale. On Windows this means the system codepage.
len : | the length of the string, or -1 if the string is nul-terminated[1].
bytes_read : | location to store the number of bytes in the input string that were successfully converted, or NULL. Even if the conversion was successful, this may be less than len if there were partial characters at the end of the input. If the error G_CONVERT_ERROR_ILLEGAL_SEQUENCE occurs, the value stored will the byte offset after the last valid input sequence.
bytes_written : | the number of bytes stored in the output buffer (not including the terminating nul).
error : | location to store the error occuring, or NULL to ignore errors. Any of the errors in GConvertError may occur.
Returns : | The converted string, or NULL on an error.

g_filename_to_utf8 ()

gchar*      g_filename_to_utf8   (const gchar *opsysstring, gssize len, gsize *bytes_read, gsize *bytes_written, GError **error);

Converts a string which is in the encoding used by GLib for filenames into a UTF-8 string. Note that on Windows GLib uses UTF-8 for filenames.

opsysstring : | a string in the encoding for filenames
len : | the length of the string, or -1 if the string is nul-terminated[1].
bytes_read : | location to store the number of bytes in the input string that were successfully converted, or NULL. Even if the conversion was successful, this may be less than len if there were partial characters at the end of the input. If the error G_CONVERT_ERROR_ILLEGAL_SEQUENCE occurs, the value stored will the byte offset after the last valid input sequence.
bytes_written : | the number of bytes stored in the output buffer (not including the terminating nul).
error : | location to store the error occuring, or NULL to ignore errors. Any of the errors in GConvertError may occur.
Returns : | The converted string, or NULL on an error.

g_filename_from_utf8 ()

gchar*      g_filename_from_utf8   (const gchar *utf8string, gssize len, gsize *bytes_read, gsize *bytes_written,
                                    GError **error);

Converts a string from UTF-8 to the encoding GLib uses for filenames. Note that on Windows GLib uses UTF-8 for filenames.

utf8string : | a UTF-8 encoded string.
len : | the length of the string, or -1 if the string is nul-terminated.
bytes_read : | location to store the number of bytes in the input string that were successfully converted, or NULL. Even if the conversion was successful, this may be less than len if there were partial characters at the end of the input. If the error G_CONVERT_ERROR_ILLEGAL_SEQUENCE occurs, the value stored will the byte offset after the last valid input sequence.
bytes_written : | the number of bytes stored in the output buffer (not including the terminating nul).
error : | location to store the error occuring, or NULL to ignore errors. Any of the errors in GConvertError may occur.
Returns : | The converted string, or NULL on an error.

g_filename_from_uri ()

gchar*      g_filename_from_uri     (const gchar *uri, gchar **hostname, GError **error);

Converts an escaped ASCII-encoded URI to a local filename in the encoding used for filenames.

uri : | a uri describing a filename (escaped, encoded in ASCII).
hostname : | Location to store hostname for the URI, or NULL. If there is no hostname in the URI, NULL will be stored in this location.
error : | location to store the error occuring, or NULL to ignore errors. Any of the errors in GConvertError may occur.
Returns : | a newly-allocated string holding the resulting filename, or NULL on an error.

g_filename_to_uri ()

gchar*      g_filename_to_uri       (const gchar *filename, const gchar *hostname, GError **error);

Converts an absolute filename to an escaped ASCII-encoded URI.

filename : | an absolute filename specified in the GLib file name encoding, which is the on-disk file name bytes on Unix, and UTF-8 on Windows
hostname : | A UTF-8 encoded hostname, or NULL for none.
error : | location to store the error occuring, or NULL to ignore errors. Any of the errors in GConvertError may occur.
Returns : | a newly-allocated string holding the resulting URI, or NULL on an error.

g_get_filename_charsets ()

gboolean    g_get_filename_charsets  (G_CONST_RETURN gchar ***charsets);

Determines the preferred character sets used for filenames. The first character set from the charsets is the filename encoding, the subsequent character sets are used when trying to generate a displayable representation of a filename, see g_filename_display_name().

On Unix, the character sets are determined by consulting the environment variables G_FILENAME_ENCODING and G_BROKEN_FILENAMES. On Windows, the character set used in the GLib API is always UTF-8 and said environment variables have no effect.

G_FILENAME_ENCODING may be set to a comma-separated list of character set names. The special token "locale" is taken to mean the character set for the current locale. If G_FILENAME_ENCODING is not set, but G_BROKEN_FILENAMES is, the character set of the current locale is taken as the filename encoding. If neither environment variable is set, UTF-8 is taken as the filename encoding, but the character set of the current locale is also put in the list of encodings.

The returned charsets belong to GLib and must not be freed.

Note that on Unix, regardless of the locale character set or G_FILENAME_ENCODING value, the actual file names present on a system might be in any random encoding or just gibberish.

charsets : | return location for the NULL-terminated list of encoding names
Returns : | TRUE if the filename encoding is UTF-8.

g_filename_display_name ()

gchar*      g_filename_display_name         (const gchar *filename);

Converts a filename into a valid UTF-8 string. The conversion is not necessarily reversible, so keep the original around and use the return value of this function only for display purposes. Unlike g_filename_to_utf8(), the result is guaranteed to be non-NULL even if the filename actually isn't in the GLib file name encoding.

If the whole pathname of the file is known, use g_filename_display_basename(), since it allows for location-based translation of filenames.

filename : | a pathname hopefully in the GLib file name encoding
Returns : | a newly allocated string containing a rendition of the filename in valid UTF-8

g_filename_display_basename ()

gchar*      g_filename_display_basename     (const gchar *filename);

Returns the display basename for the particular filename, guaranteed to be valid UTF-8. The display name might not be identical to the filename, for instance there might be problems converting it to UTF-8, and some files can be translated in the display

Pass the whole absolute pathname to this functions so that translation of well known locations can be done.

This function is preferred over g_filename_display_name() if the whole path is known, as it allows translation.

filename : | an absolute pathname in the GLib file name encoding
Returns : | a newly allocated string containing a rendition of the basename of the filename in valid UTF-8

g_uri_list_extract_uris ()

gchar**     g_uri_list_extract_uris         (const gchar *uri_list);

Splits an URI list conforming to the text/uri-list mime type defined in RFC 2483 into individual URIs, discarding any comments. The URIs are not validated.

uri_list : | an URI list
Returns : | a newly allocated NULL-terminated list of strings holding the individual URIs. The array should be freed with g_strfreev().

g_locale_from_utf8 ()

gchar*      g_locale_from_utf8          (const gchar *utf8string, gssize len, gsize *bytes_read, gsize *bytes_written,
                                         GError **error);

Converts a string from UTF-8 to the encoding used for strings by the C runtime (usually the same as that used by the operating system) in the current locale.

utf8string : | a UTF-8 encoded string
len : | the length of the string, or -1 if the string is nul-terminated[1].
bytes_read : | location to store the number of bytes in the input string that were successfully converted, or NULL. Even if the conversion was successful, this may be less than len if there were partial characters at the end of the input. If the error G_CONVERT_ERROR_ILLEGAL_SEQUENCE occurs, the value stored will the byte offset after the last valid input sequence.
bytes_written : | the number of bytes stored in the output buffer (not including the terminating nul).
error : | location to store the error occuring, or NULL to ignore errors. Any of the errors in GConvertError may occur.
Returns : | The converted string, or NULL on an error.

enum GConvertError

typedef enum
{
  G_CONVERT_ERROR_NO_CONVERSION,
  G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
  G_CONVERT_ERROR_FAILED,
  G_CONVERT_ERROR_PARTIAL_INPUT,
  G_CONVERT_ERROR_BAD_URI,
  G_CONVERT_ERROR_NOT_ABSOLUTE_PATH
} GConvertError;

Error codes returned by character set conversion routines.

G_CONVERT_ERROR_NO_CONVERSION | Conversion between the requested character sets is not supported.
G_CONVERT_ERROR_ILLEGAL_SEQUENCE | Invalid byte sequence in conversion input.
G_CONVERT_ERROR_FAILED | Conversion failed for some reason.
G_CONVERT_ERROR_PARTIAL_INPUT | Partial character sequence at end of input.
G_CONVERT_ERROR_BAD_URI | URI is invalid.
G_CONVERT_ERROR_NOT_ABSOLUTE_PATH | Pathname is not an absolute path.

g_get_charset ()

gboolean    g_get_charset          (G_CONST_RETURN char **charset);

Obtains the character set for the current locale; this character set might be used as an argument to g_convert(), to convert from the current locale's encoding to some other encoding. (Frequently g_locale_to_utf8() and g_locale_from_utf8() are nice shortcuts, though.)

The return value is TRUE if the locale's encoding is UTF-8, in that case avoid calling g_convert().

The string returned in charset is not allocated, and should not be freed.

charset : | return location for character set name
Returns : | TRUE if the returned charset is UTF-8

Feedback

For additional information or queries on this page send feedback

[1] Note that some encodings may allow null bytes to occur inside strings. In that case, using -1 for the len parameter is unsafe.

[2] Despite the fact that byes_read can return information about partial characters, the g_convert_... functions are not generally suitable for streaming. If the underlying converter being used maintains internal state, then this will not be preserved across successive calls to g_convert(), g_convert_with_iconv() or g_convert_with_fallback(). (An example of this is the GNU C converter for CP1255 which does not emit a base character until it knows that the next character is not a mark that could combine with the base character.)


Commandline option parser

Name

Commandline option parser — parses commandline options.

Library

glib.lib

Synopsis

#include <glib.h>

enum         GOptionError;
#define      G_OPTION_ERROR
gboolean     (*GOptionArgFunc)                           (const gchar *option_name, const gchar *value, gpointer data,
                                                          GError **error);
             GOptionContext;
GOptionContext* g_option_context_new                     (const gchar *parameter_string);
void        g_option_context_free                        (GOptionContext *context);
gboolean    g_option_context_parse                       (GOptionContext *context, gint *argc, gchar ***argv, GError **error);

void        g_option_context_set_help_enabled            (GOptionContext *context, gboolean help_enabled);
gboolean    g_option_context_get_help_enabled            (GOptionContext *context);
void        g_option_context_set_ignore_unknown_options  (GOptionContext *context, gboolean ignore_unknown);
gboolean    g_option_context_get_ignore_unknown_options  (GOptionContext *context);
enum        GOptionArg;
enum        GOptionFlags;
#define     G_OPTION_REMAINING
            GOptionEntry;
void        g_option_context_add_main_entries        (GOptionContext *context, const GOptionEntry *entries,
                                                      const gchar *translation_domain);
            GOptionGroup;
void        g_option_context_add_group               (GOptionContext *context, GOptionGroup *group);
void        g_option_context_set_main_group          (GOptionContext *context, GOptionGroup *group);
GOptionGroup* g_option_context_get_main_group        (GOptionContext *context);
GOptionGroup* g_option_group_new                     (const gchar *name, const gchar *description, GDestroyNotify destroy
                                                      const gchar *help_description, gpointer user_data,);
void        g_option_group_free                      (GOptionGroup *group);
void        g_option_group_add_entries               (GOptionGroup *group, const GOptionEntry *entries);
gboolean    (*GOptionParseFunc)                      (GOptionContext *context, GOptionGroup *group, gpointer data,
                                                      GError **error);
void        g_option_group_set_parse_hooks           (GOptionGroup *group, GOptionParseFunc pre_parse_func,
                                                      GOptionParseFunc post_parse_func);
void        (*GOptionErrorFunc)                      (GOptionContext *context, GOptionGroup *group, gpointer data,
                                                      GError **error);
void        g_option_group_set_error_hook            (GOptionGroup *group, GOptionErrorFunc error_func);
const gchar* (*GTranslateFunc)                       (const gchar *str, gpointer data);
void        g_option_group_set_translate_func        (GOptionGroup *group, GTranslateFunc func, gpointer data,
                                                      GDestroyNotify destroy_notify);
void        g_option_group_set_translation_domain    (GOptionGroup *group, const gchar *domain);

Detailed Description

The GOption commandline parser is intended to be a simpler replacement for the popt library. It supports short and long commandline options, as shown in the following example:

testtreemodel -r 1 --max-size 20 --rand --display=:1.0 -vb -- file1 file2

The example demonstrates a number of features of the GOption commandline parser

  • Options can be single letters, prefixed by a single dash. Multiple short options can be grouped behind a single dash.

  • Long options are prefixed by two consecutive dashes.

  • Options can have an extra argument, which can be a number, a string or a filename. For long options, the extra argument can be appended with an equals sign after the option name.

  • Non-option arguments are returned to the application as rest arguments.

  • An argument consisting solely of two dashes turns off further parsing, any remaining arguments (even those starting with a dash) are returned to the application as rest arguments.

Another important feature of GOption is that it can automatically generate nicely formatted help output. Unless it is explicitly turned off with g_option_context_set_help_enabled(), GOption will recognize the --help, -?, --help-all and --help-groupname options (where groupname is the name of a GOptionGroup) and write a text similar to the one shown in the following example to stdout.

Usage:
  testtreemodel [OPTION...] - test tree model performance

Help Options:
  -?, --help               Show help options
  --help-all               Show all help options
  --help-gtk               Show GTK+ Options

Application Options:
  -r, --repeats=N          Average over N repetitions
  -m, --max-size=M         Test up to 2^M items
  --display=DISPLAY        X display to use
  -v, --verbose            Be verbose
  -b, --beep               Beep when done
  --rand                   Randomize the data

GOption groups options in GOptionGroups, which makes it easy to incorporate options from multiple sources. The intended use for this is to let applications collect option groups from the libraries it uses, add them to their GOptionContext, and parse all options by a single call to g_option_context_parse(). See gtk_get_option_group() for an example.

If an option is declared to be of type string or filename, GOption takes care of converting it to the right encoding; strings are returned in UTF-8, filenames are returned in the GLib filename encoding.

Here is a complete example of setting up GOption to parse the example commandline above and produce the example help output

static gint repeats = 2;
static gint max_size = 8;
static gboolean verbose = FALSE;
static gboolean beep = FALSE;
static gboolean rand = FALSE;

static GOptionEntry entries[] =
{
{ "repeats", 'r', 0, G_OPTION_ARG_INT, &repeats, "Average over N repetitions", "N" },
{ "max-size", 'm', 0, G_OPTION_ARG_INT, &max_size, "Test up to 2^M items", "M" },
{ "verbose", 'v', 0, G_OPTION_ARG_NONE, &verbose, "Be verbose", NULL },
{ "beep", 'b', 0, G_OPTION_ARG_NONE, &beep, "Beep when done", NULL },
{ "rand", 0, 0, G_OPTION_ARG_NONE, &rand, "Randomize the data", NULL },
{ NULL }
};

int
main (int argc, char *argv[])
{
GError *error = NULL;

context = g_option_context_new ("- test tree model performance");
g_option_context_add_main_entries (context, entries, GETTEXT_PACKAGE);
g_option_context_add_group (context, gtk_get_option_group (TRUE));
g_option_context_parse (context, &argc, &argv, &error);

/* ... */
}

Details

enum GOptionError

typedef enum
{
  G_OPTION_ERROR_UNKNOWN_OPTION,
  G_OPTION_ERROR_BAD_VALUE,
  G_OPTION_ERROR_FAILED
} GOptionError;

Error codes returned by option parsing.

G_OPTION_ERROR_UNKNOWN_OPTION | An option was not known to the parser. This error will only be reported, if the parser hasn't been instructed to ignore unknown options, see g_option_context_set_ignore_unknown_options().
G_OPTION_ERROR_BAD_VALUE | A value couldn't be parsed.
G_OPTION_ERROR_FAILED | A GOptionArgFunc callback failed.

G_OPTION_ERROR

#define G_OPTION_ERROR (g_option_error_quark ())

Error domain for option parsing. Errors in this domain will be from the GOptionError enumeration. See GError for information on error domains.

GOptionArgFunc ()

gboolean    (*GOptionArgFunc)          (const gchar *option_name, const gchar *value, gpointer data, GError **error);

The type of function to be passed as callback for G_OPTION_ARG_CALLBACK options.

option_name : | The name of the option being parsed. This will be either a single dash followed by a single letter (for a short name) or two dashes followed by a long option name.
value : | The value to be parsed.
data : | User data added to the GOptionGroup containing the option when it was created with g_option_group_new()
error : | A return location for errors. The error code G_OPTION_ERROR_FAILED is intended to be used for errors in GOptionArgFunc callbacks.
Returns : | TRUE if the option was successfully parsed, FALSE if an error occurred

GOptionContext

typedef struct _GOptionContext GOptionContext;

A GOptionContext struct defines which options are accepted by the commandline option parser. The struct has only private fields and should not be directly accessed.

g_option_context_new ()

GOptionContext* g_option_context_new        (const gchar *parameter_string);

Creates a new option context.

The parameter_text can serve multiple purposes. It can be used to add descriptions for "rest" arguments, which are not parsed by the GOptionContext, typically something like "FILES" or "FILE1 FILE2...". (If G_OPTION_REMAINING is used for collecting "rest" arguments, GLib handles this automatically by using the arg_description of the corresponding GOptionEntry in the usage summary.)

Another common usage is to give a summary of the program functionality. This can be a short summary on the same line, like " - frob the strings", or a longer description in a paragraph below the usage summary. In this case, parameter_string should start with two new lines, to separate the description from the usage summary: "\n\nA program to frob strings, which will..."

parameter_string : | a string which is displayed in the first line of --help output, after programname [OPTION...]
Returns : | a newly created GOptionContext, which must be freed with g_option_context_free() after use.

g_option_context_free ()

void        g_option_context_free           (GOptionContext *context);

Frees context and all the groups which have been added to it.

context : a GOptionContext

g_option_context_parse ()

gboolean    g_option_context_parse          (GOptionContext *context, gint *argc, gchar ***argv, GError **error);

Parses the command line arguments, recognizing options which have been added to context. A side-effect of calling this function is that g_set_prgname() will be called.

If the parsing is successful, any parsed arguments are removed from the array and argc and argv are updated accordingly. A '--' option is stripped from argv unless there are unparsed options before and after it, or some of the options after it start with '-'. In case of an error, argc and argv are left unmodified.

If automatic --help support is enabled (see g_option_context_set_help_enabled()), and the argv array contains one of the recognized help options, this function will produce help output to stdout and call exit (0).

context : | a GOptionContext
argc : | a pointer to the number of command line arguments.
argv : | a pointer to the array of command line arguments.
error : | a return location for errors
Returns : | TRUE if the parsing was successful, FALSE if an error occurred

g_option_context_set_help_enabled ()

void        g_option_context_set_help_enabled        (GOptionContext *context, gboolean help_enabled);

Enables or disables automatic generation of --help output. By default, g_option_context_parse() recognizes --help, -?, --help-all and --help-groupname and creates suitable output to stdout.

context : | a GOptionContext
help_enabled : | TRUE to enable --help, FALSE to disable it

g_option_context_get_help_enabled ()

gboolean    g_option_context_get_help_enabled          (GOptionContext *context);

Returns whether automatic --help generation is turned on for context. See g_option_context_set_help_enabled().

context : | a GOptionContext
Returns : | TRUE if automatic help generation is turned on.

g_option_context_set_ignore_unknown_options ()

void        g_option_context_set_ignore_unknown_options      (GOptionContext *context, gboolean ignore_unknown);

Sets whether to ignore unknown options or not. If an argument is ignored, it is left in the argv array after parsing. By default, g_option_context_parse() treats unknown options as error.

This setting does not affect non-option arguments (i.e. arguments which do not start with a dash). But note that GOption cannot reliably determine whether a non-option belongs to a preceding unknown option.

context : | a GOptionContext
ignore_unknown : | TRUE to ignore unknown options, FALSE to produce an error when unknown options are met

g_option_context_get_ignore_unknown_options ()

gboolean    g_option_context_get_ignore_unknown_options     (GOptionContext *context);

Returns whether unknown options are ignored or not. See g_option_context_set_ignore_unknown_options().

context : | a GOptionContext
Returns : | TRUE if unknown options are ignored.

enum GOptionArg

typedef enum
{
  G_OPTION_ARG_NONE,
  G_OPTION_ARG_STRING,
  G_OPTION_ARG_INT,
  G_OPTION_ARG_CALLBACK,
  G_OPTION_ARG_FILENAME,
  G_OPTION_ARG_STRING_ARRAY,
  G_OPTION_ARG_FILENAME_ARRAY
} GOptionArg;

The GOptionArg enum values determine which type of extra argument the options expect to find. If an option expects an extra argument, it can be specified in several ways; with a short option: -x arg, with a long option: --name arg or combined in a single argument: --name=arg.

G_OPTION_ARG_NONE | No extra argument. This is useful for simple flags.
G_OPTION_ARG_STRING | The option takes a string argument.
G_OPTION_ARG_INT | The option takes an integer argument.
G_OPTION_ARG_CALLBACK | The option provides a callback to parse the extra argument.
G_OPTION_ARG_FILENAME | The option takes a filename as argument.
G_OPTION_ARG_STRING_ARRAY | The option takes a string argument, multiple uses of the option are collected into an array of strings.
G_OPTION_ARG_FILENAME_ARRAY | The option takes a filename as argument, multiple uses of the option are collected into an array of strings.

enum GOptionFlags

typedef enum
{
  G_OPTION_FLAG_HIDDEN		= 1 << 0,
  G_OPTION_FLAG_IN_MAIN		= 1 << 1,
  G_OPTION_FLAG_REVERSE		= 1 << 2,
  G_OPTION_FLAG_NO_ARG		= 1 << 3,
  G_OPTION_FLAG_FILENAME	= 1 << 4,
  G_OPTION_FLAG_OPTIONAL_ARG    = 1 << 5,
  G_OPTION_FLAG_NOALIAS	        = 1 << 6
} GOptionFlags;

Flags which modify individual options.

G_OPTION_FLAG_HIDDEN | The option does not appear in --help output.
G_OPTION_FLAG_IN_MAIN | The option appears in the main section of the --help output, even if it is defined in a group.
G_OPTION_FLAG_REVERSE | For options of the G_OPTION_ARG_NONE kind, this flag indicates that the sense of the option is reversed.
G_OPTION_FLAG_NO_ARG | For options of the G_OPTION_ARG_CALLBACK kind, this flag indicates that the callback does not take any argument (like a G_OPTION_ARG_NONE option). Since 2.8
G_OPTION_FLAG_FILENAME | For options of the G_OPTION_ARG_CALLBACK kind, this flag indicates that the argument should be passed to the callback in the GLib filename encoding rather than UTF-8. Since 2.8
G_OPTION_FLAG_OPTIONAL_ARG | For options of the G_OPTION_ARG_CALLBACK kind, this flag indicates that the argument supply is optional. If no argument is given then data of GOptionParseFunc will be set to NULL. Since 2.8
G_OPTION_FLAG_NOALIAS | This flag turns off the automatic conflict resolution which prefixes long option names with groupname- if there is a conflict. This option should only be used in situations where aliasing is necessary to model some legacy commandline interface. It is not safe to use this option, unless all option groups are under direct control. Since 2.8.

G_OPTION_REMAINING

#define G_OPTION_REMAINING ""

If a long option in the main group has this name, it is not treated as a regular option. Instead it collects all non-option arguments which would otherwise be left in argv. The option must be of type G_OPTION_ARG_STRING_ARRAY or G_OPTION_ARG_FILENAME_ARRAY.

Using G_OPTION_REMAINING instead of simply scanning argv for leftover arguments has the advantage that GOption takes care of necessary encoding conversions for strings or filenames.

GOptionEntry

typedef struct {
  const gchar *long_name;
  gchar        short_name;
  gint         flags;

  GOptionArg   arg;
  gpointer     arg_data;

  const gchar *description;
  const gchar *arg_description;
} GOptionEntry;

A GOptionEntry defines a single option. To have an effect, they must be added to a GOptionGroup with g_option_context_add_main_entries() or g_option_group_add_entries().

const gchar *long_name; | The long name of an option can be used to specify it in a commandline as --long_name. Every option must have a long name. To resolve conflicts if multiple option groups contain the same long name, it is also possible to specify the option as --groupname-long_name.
gchar short_name; | If an option has a short name, it can be specified -short_name in a commandline. short_name must be a printable ASCII character different from '-', or zero if the option has no short name.
gint flags; | Flags from GOptionFlags.
GOptionArg arg; | The type of the option, as a GOptionArg.
gpointer arg_data; If the arg type is G_OPTION_ARG_CALLBACK, then arg_data must point to a GOptionArgFunc callback function, which will be called to handle the extra argument. Otherwise, arg_data is a pointer to a location to store the value, the required type of the location depends on the arg type:
G_OPTION_ARG_NONE | gboolean
G_OPTION_ARG_STRING | gchar*
G_OPTION_ARG_INT | gint
G_OPTION_ARG_FILENAME | gchar*
G_OPTION_ARG_STRING_ARRAY | gchar**
G_OPTION_ARG_FILENAME_ARRAY | gchar**
const gchar *description; | the description for the option in --help output. The description is translated using the translate_func of the group, see g_option_group_set_translation_domain().
const gchar *arg_description; | The placeholder to use for the extra argument parsed by the option in --help output. The arg_description is translated using the translate_func of the group, see g_option_group_set_translation_domain().

g_option_context_add_main_entries ()

void        g_option_context_add_main_entries        (GOptionContext *context, const GOptionEntry *entries, const gchar *translation_domain);

A convenience function which creates a main group if it does not exist, adds the entries to it and sets the translation domain.

context : | a GOptionContext
entries : | a NULL-terminated array of GOptionEntrys
translation_domain : | a translation domain to use for translating the --help output for the options in entries with gettext(), or NULL

GOptionGroup

typedef struct _GOptionGroup GOptionGroup;

A GOptionGroup struct defines the options in a single group. The struct has only private fields and should not be directly accessed.

All options in a group share the same translation function. Libraries which need to parse commandline options are expected to provide a function for getting a GOptionGroup holding their options, which the application can then add to its GOptionContext.

g_option_context_add_group ()

void        g_option_context_add_group      (GOptionContext *context, GOptionGroup *group);

Adds a GOptionGroup to the context, so that parsing with context will recognize the options in the group. Note that the group will be freed together with the context when g_option_context_free() is called, so do not free the group after adding it to a context.

context : | a GOptionContext
group : | the group to add

g_option_context_set_main_group ()

void        g_option_context_set_main_group          (GOptionContext *context, GOptionGroup *group);

Sets a GOptionGroup as main group of the context. This has the same effect as calling g_option_context_add_group(), the only difference is that the options in the main group are treated differently when generating --help output.

context : | a GOptionContext
group : | the group to set as main group

g_option_context_get_main_group ()

GOptionGroup* g_option_context_get_main_group       (GOptionContext *context);

Returns a pointer to the main group of context.

context : | a GOptionContext
Returns : | the main group of context, or NULL if context does not have a main group. Note that group belongs to context and should not be modified or freed.

g_option_group_new ()

GOptionGroup* g_option_group_new       (const gchar *name, const gchar *description, const gchar *help_description, gpointer user_data, GDestroyNotify destroy);

Creates a new GOptionGroup.

name : | the name for the option group, this is used to provide help for the options in this group with --help-name
description : | a description for this group to be shown in --help. This string is translated using the translation domain or translation function of the group
help_description : | a description for the --help-name option. This string is translated using the translation domain or translation function of the group
user_data : | user data that will be passed to the pre- and post-parse hooks, the error hook and to callbacks of G_OPTION_ARG_CALLBACK options, or NULL
destroy : | a function that will be called to free user_data, or NULL
Returns : | a newly created option group. It should be added to a GOptionContext or freed with g_option_group_free().

g_option_group_free ()

void        g_option_group_free             (GOptionGroup *group);

Frees a GOptionGroup. Note do not free groups which have been added to a GOptionContext.

group : a GOptionGroup

g_option_group_add_entries ()

void        g_option_group_add_entries      (GOptionGroup *group, const GOptionEntry *entries);

Adds the options specified in entries to group.

group : | a GOptionGroup
entries : | a NULL-terminated array of GOptionEntrys

GOptionParseFunc ()

gboolean    (*GOptionParseFunc)             (GOptionContext *context, GOptionGroup *group, gpointer data, GError **error);

The type of function that can be called before and after parsing.

context : | The active GOptionContext
group : | The group to which the function belongs
data : | User data added to the GOptionGroup containing the option when it was created with g_option_group_new()
error : | A return location for error details
Returns : | TRUE if the function completed successfully, FALSE if an error occurred

g_option_group_set_parse_hooks ()

void        g_option_group_set_parse_hooks       (GOptionGroup *group, GOptionParseFunc pre_parse_func,
                                                  GOptionParseFunc post_parse_func);

Associates two functions with group which will be called from g_option_context_parse() before the first option is parsed and after the last option has been parsed, respectively.

Note that the user data to be passed to pre_parse_func and post_parse_func can be specified when constructing the group with g_option_group_new().

group : | a GOptionGroup
pre_parse_func : | a function to call before parsing, or NULL
post_parse_func : | a function to call after parsing, or NULL

GOptionErrorFunc ()

void        (*GOptionErrorFunc)             (GOptionContext *context, GOptionGroup *group, gpointer data, GError **error);

The type of function to be used as callback when a parse error occurs.

context : | The active GOptionContext
group : | The group to which the function belongs
data : | User data added to the GOptionGroup containing the option when it was created with g_option_group_new()
error : | The GError containing details about the parse error

g_option_group_set_error_hook ()

void        g_option_group_set_error_hook     (GOptionGroup *group, GOptionErrorFunc error_func);

Associates a function with group which will be called from g_option_context_parse() when an error occurs.

Note that the user data to be passed to pre_parse_func and post_parse_func can be specified when constructing the group with g_option_group_new().

group : | a GOptionGroup
error_func : | a function to call when an error occurs

GTranslateFunc ()

const gchar* (*GTranslateFunc)              (const gchar *str, gpointer data);

The type of functions which are used to translate user-visible strings, for --help output.

str : | the untranslated string
data : | user data specified when installing the function, e.g. in g_option_group_set_translate_func()
Returns : | a translation of the string for the current locale. The returned string is owned by GLib and must not be freed.

g_option_group_set_translate_func ()

void        g_option_group_set_translate_func       (GOptionGroup *group, GTranslateFunc func, GDestroyNotify destroy_notify,
                                                     gpointer data,);

Sets the function which is used to translate user-visible strings, for --help output. Different groups can use different GTranslateFuncs. If func is NULL, strings are not translated.

Set only the translation domain if gettext() is used, see g_option_group_set_translation_domain().

group : | a GOptionGroup
func : | the GTranslateFunc, or NULL
data : | user data to pass to func, or NULL
destroy_notify : | a function which gets called to free data, or NULL

g_option_group_set_translation_domain ()

void    g_option_group_set_translation_domain     (GOptionGroup *group, const gchar *domain);

A convenience function to use gettext() for translating user-visible strings.

group : | a GOptionGroup
domain : | the domain to use

Feedback

For additional information or queries on this page send feedback


Glib Core Application Support

The Main Event Loop - manages all available sources of events.
Threads - thread abstraction; including threads, different mutexes, conditions and thread private data.
Thread Pools - pools of threads to execute work concurrently.
Asynchronous Queues - asynchronous communication between threads.
Dynamic Loading of Modules - portable method for dynamically loading 'plug-ins'.
Memory Allocation - general memory-handling.
IO Channels - portable support for using files, pipes and sockets.
Error Reporting - a system for reporting errors.
Message Output and Debugging Functions - functions to output messages and help debug applications.
Message Logging - versatile support for logging messages with different levels of importance.


Datasets

Name

Datasets — associate groups of data elements with particular memory locations.

Library

glib.lib

Synopsis

#include <glib.h>

#define     g_dataset_id_set_data           (l, k, d)
void        g_dataset_id_set_data_full      (gconstpointer dataset_location, GQuark key_id, gpointer data,
                                             GDestroyNotify destroy_func);
void        (*GDestroyNotify)               (gpointer data);
gpointer    g_dataset_id_get_data           (gconstpointer dataset_location, GQuark key_id);
#define     g_dataset_id_remove_data        (l, k)
gpointer    g_dataset_id_remove_no_notify   (gconstpointer dataset_location, GQuark key_id);

#define     g_dataset_set_data              (l, k, d)
#define     g_dataset_set_data_full         (l, k, d, f)
#define     g_dataset_get_data              (l, k)
#define     g_dataset_remove_data           (l, k)
#define     g_dataset_remove_no_notify      (l, k)

void        g_dataset_foreach               (gconstpointer dataset_location, GDataForeachFunc func, gpointer user_data);
void        (*GDataForeachFunc)             (GQuark key_id, gpointer data, gpointer user_data);
void        g_dataset_destroy               (gconstpointer dataset_location);

Detailed Description

Datasets associate groups of data elements with particular memory locations. These are useful to associate data with a structure returned from an external library. Since the structure cannot be modified, use its location in memory as the key into a dataset, where any number of data elements can be associated with it.

There are two forms of most of the dataset functions. The first form uses strings to identify the data elements associated with a location. The second form uses GQuark identifiers, which are created with a call to g_quark_from_string() or g_quark_from_static_string(). The second form is quicker, since it does not require looking up the string in the hash table of GQuark identifiers.

There is no function to create a dataset. It is automatically created as soon as elements are added to it.

To add data elements to a dataset use
g_dataset_id_set_data(),
g_dataset_id_set_data_full(),
g_dataset_set_data()
and g_dataset_set_data_full().

To get data elements from a dataset use g_dataset_id_get_data() and g_dataset_get_data().

To iterate over all data elements in a dataset use g_dataset_foreach() (not thread-safe).

To remove data elements from a dataset use g_dataset_id_remove_data() and g_dataset_remove_data().

To destroy a dataset, use g_dataset_destroy().

Details

g_dataset_id_set_data()

#define     g_dataset_id_set_data(l, k, d)

Sets the data element associated with the given GQuark id. Any previous data with the same key is removed, and its destroy function is called.

l : | the location identifying the dataset.
k : | the GQuark id to identify the data element.
d : | the data element.

g_dataset_id_set_data_full ()

void        g_dataset_id_set_data_full      (gconstpointer dataset_location, GQuark key_id, gpointer data,
                                             GDestroyNotify destroy_func);

Sets the data element associated with the given GQuark id, and also the function to call when the data element is destroyed. Any previous data with the same key is removed, and its destroy function is called.

dataset_location : | the location identifying the dataset.
key_id : | the GQuark id to identify the data element.
data : | the data element.
destroy_func : | the function to call when the data element is removed. This function will be called with the data element and can be used to free any memory allocated for it.

GDestroyNotify ()

void        (*GDestroyNotify)               (gpointer data);

Specifies the type of function which is called when a data element is destroyed. It is passed the pointer to the data element and should free any memory and resources allocated for it.

data : the data element.

g_dataset_id_get_data ()

gpointer    g_dataset_id_get_data           (gconstpointer dataset_location, GQuark key_id);

Gets the data element corresponding to a GQuark.

dataset_location : | the location identifying the dataset.
key_id : | the GQuark id to identify the data element.
Returns : | the data element corresponding to the GQuark, or NULL if it is not found.

g_dataset_id_remove_data()

#define     g_dataset_id_remove_data(l, k)

Removes a data element from a dataset. The data element's destroy function is called if it has been set.

l : | the location identifying the dataset.
k : | the GQuark id identifying the data element.

g_dataset_id_remove_no_notify ()

gpointer    g_dataset_id_remove_no_notify      (gconstpointer dataset_location, GQuark key_id);

Removes an element, without calling its destroy notification function.

dataset_location : | the location identifying the dataset.
key_id : | the GQuark ID identifying the data element.
Returns : | the data previously stored at key_id, or NULL if none.

g_dataset_set_data()

#define     g_dataset_set_data (l, k, d)

Sets the data corresponding to the given string identifier.

l : | the location identifying the dataset.
k : | the string to identify the data element.
d : | the data element.

g_dataset_set_data_full()

#define     g_dataset_set_data_full (l, k, d, f)

Sets the data corresponding to the given string identifier, and the function to call when the data element is destroyed.

l : | the location identifying the dataset.
k : | the string to identify the data element.
d : | the data element.
f : | the function to call when the data element is removed. This function will be called with the data element and can be used to free any memory allocated for it.

g_dataset_get_data()

#define     g_dataset_get_data (l, k)

Gets the data element corresponding to a string.

l : | the location identifying the dataset.
k : | the string identifying the data element.
Returns : | the data element corresponding to the string, or NULL if it is not found.

g_dataset_remove_data()

#define     g_dataset_remove_data (l, k)

Removes a data element corresponding to a string. Its destroy function is called if it has been set.

l : | the location identifying the dataset.
k : | the string identifying the data element.

g_dataset_remove_no_notify()

#define     g_dataset_remove_no_notify (l, k)

Removes an element, without calling its destroy notifier.

l : | the location identifying the dataset.
k : | the string identifying the data element.

g_dataset_foreach ()

void        g_dataset_foreach              (gconstpointer dataset_location, GDataForeachFunc func, gpointer user_data);

Calls the given function for each data element which is associated with the given location. Note that this function is NOT thread-safe. So unless datalist can be protected from any modifications during invocation of this function, it should not be called.

dataset_location : | the location identifying the dataset.
func : | the function to call for each data element.
user_data : | user data to pass to the function.

GDataForeachFunc ()

void        (*GDataForeachFunc)            (GQuark key_id, gpointer data, gpointer user_data);

Specifies the type of function passed to g_dataset_foreach(). It is called with each GQuark id and associated data element, together with the user_data parameter supplied to g_dataset_foreach().

key_id : | the GQuark id to identifying the data element.
data : | the data element.
user_data : | user data passed to g_dataset_foreach().

g_dataset_destroy ()

void        g_dataset_destroy              (gconstpointer dataset_location);

Destroys the dataset, freeing all memory allocated, and calling any destroy functions set for data elements.

dataset_location : the location identifying the dataset.

Feedback

For additional information or queries on this page send feedback


Date and Time Functions

Name

Date and Time Functions — calendrical calculations and miscellaneous time stuff.

Library

glib.lib

Synopsis

#include <glib.h>

#define     G_USEC_PER_SEC
            GTimeVal;
void        g_get_current_time              (GTimeVal *result);
void        g_usleep                        (gulong microseconds);
void        g_time_val_add                  (GTimeVal *time_, glong microseconds);

            GDate;
typedef     GTime;
enum        GDateDMY;
typedef     GDateDay;
enum        GDateMonth;
typedef     GDateYear;
enum        GDateWeekday;

#define     G_DATE_BAD_DAY
#define     G_DATE_BAD_JULIAN
#define     G_DATE_BAD_YEAR

GDate*      g_date_new                      (void);
GDate*      g_date_new_dmy                  (GDateDay day, GDateMonth month, GDateYear year);
GDate*      g_date_new_julian               (guint32 julian_day);
void        g_date_clear                    (GDate *date, guint n_dates);
void        g_date_free                     (GDate *date);

void        g_date_set_day                  (GDate *date, GDateDay day);
void        g_date_set_month                (GDate *date, GDateMonth month);
void        g_date_set_year                 (GDate *date, GDateYear year);
void        g_date_set_dmy                  (GDate *date, GDateDay day, GDateMonth month, GDateYear y);
void        g_date_set_julian               (GDate *date, guint32 julian_date);
void        g_date_set_time                 (GDate *date, GTime time_);
void        g_date_set_parse                (GDate *date, const gchar *str);

void        g_date_add_days                 (GDate *date, guint n_days);
void        g_date_subtract_days            (GDate *date, guint n_days);
void        g_date_add_months               (GDate *date, guint n_months);
void        g_date_subtract_months          (GDate *date, guint n_months);
void        g_date_add_years                (GDate *date, guint n_years);
void        g_date_subtract_years           (GDate *date, guint n_years);
gint        g_date_days_between             (const GDate *date1, const GDate *date2);
gint        g_date_compare                  (const GDate *lhs, const GDate *rhs);
void        g_date_clamp                    (GDate *date, const GDate *min_date, const GDate *max_date);
void        g_date_order                    (GDate *date1, GDate *date2);

GDateDay    g_date_get_day                  (const GDate *date);
GDateMonth  g_date_get_month                (const GDate *date);
GDateYear   g_date_get_year                 (const GDate *date);
guint32     g_date_get_julian               (const GDate *date);
GDateWeekday g_date_get_julian             (const GDate *date);
guint       g_date_get_day_of_year          (const GDate *date);

guint8      g_date_get_days_in_month        (GDateMonth month, GDateYear year);
gboolean    g_date_is_first_of_month        (const GDate *date);
gboolean    g_date_is_last_of_month         (const GDate *date);
gboolean    g_date_is_leap_year             (GDateYear year);
guint       g_date_get_monday_week_of_year  (const GDate *date);
guint8      g_date_get_monday_weeks_in_year (GDateYear year);
guint       g_date_get_sunday_week_of_year  (const GDate *date);
guint8      g_date_get_sunday_weeks_in_year (GDateYear year);
guint       g_date_get_iso8601_week_of_year (const GDate *date);

gsize       g_date_strftime                 (gchar *s, gsize slen, const gchar *format, const GDate *date);
void        g_date_to_struct_tm             (const GDate *date, struct tm *tm);

gboolean    g_date_valid                    (const GDate *date);
gboolean    g_date_valid_day                (GDateDay day);
gboolean    g_date_valid_month              (GDateMonth month);
gboolean    g_date_valid_year               (GDateYear year);
gboolean    g_date_valid_dmy                (GDateDay day, GDateMonth month, GDateYear year);
gboolean    g_date_valid_julian             (guint32 julian_date);
gboolean    g_date_valid_weekday            (GDateWeekday weekday);

Detailed Description

The GDate data structure represents a day between January 1, Year 1, and sometime a few thousand years in the future (right now it will go to the year 65535 or so, but g_date_set_parse() only parses up to the year 8000 or so - just count on "a few thousand"). GDate is meant to represent everyday dates, not astronomical dates or historical dates or ISO timestamps or the like. It extrapolates the current Gregorian calendar forward and backward in time; there is no attempt to change the calendar to match time periods or locations. GDate does not store time information; it represents a day.

The GDate implementation has several nice features; it is only a 64-bit struct, so storing large numbers of dates is very efficient. It can keep both a Julian and day-month-year representation of the date, since some calculations are much easier with one representation or the other. A Julian representation is simply a count of days since some fixed day in the past; for GDate the fixed day is January 1, 1 AD. ("Julian" dates in the GDate API are not really Julian dates in the technical sense; technically, Julian dates count from the start of the Julian period, Jan 1, 4713 BC).

GDate is simple to use. First a "blank" date is needed; a date is dynamically allocated from g_date_new(), or by declaring an automatic variable or array and initializing it to a sane state by calling g_date_clear(). A cleared date is sane; it's safe to call g_date_set_dmy() and the other mutator functions to initialize the value of a cleared date. However, a cleared date is initially invalid, meaning that it does not represent a day that exists. It is undefined to call any of the date calculation routines on an invalid date. If a date is obtained from a user or other unpredictable source, check its validity with the g_date_valid() predicate. g_date_valid() is also used to check for errors with g_date_set_parse() and other functions that can fail. Dates can be invalidated by calling g_date_clear() again.

It is very important to use the API to access the GDate struct. Often only the day-month-year or only the Julian representation is valid. Sometimes neither is valid. Use the API.
GLib does not contain any time-manipulation functions; however, there is a GTime typedef and a GTimeVal struct which represents a more precise time (with microseconds). A request for the current time as a GTimeVal with g_get_current_time() can be placed.

Details

G_USEC_PER_SEC

#define G_USEC_PER_SEC 1000000

Number of microseconds in one second (1 million). This macro is provided for code readability.

GTimeVal

typedef struct {
  glong tv_sec;
  glong tv_usec;
} GTimeVal;

Represents a precise time, with seconds and microseconds. Similar to the struct timeval returned by the gettimeofday() UNIX call.

glong tv_sec; | seconds.
glong tv_usec; | microseconds.

g_get_current_time ()

void        g_get_current_time           (GTimeVal *result);

Equivalent to the UNIX gettimeofday() function, but portable.

result : GTimeVal structure in which to store current time.

g_usleep ()

void        g_usleep                     (gulong microseconds);

Pauses the current thread for the given number of microseconds. There are 1 million microseconds per second (represented by the G_USEC_PER_SEC macro). g_usleep() may have limited precision, depending on hardware and operating system; do not rely on the exact length of the sleep.

microseconds : number of microseconds to pause.

g_time_val_add ()

void        g_time_val_add               (GTimeVal *time_, glong microseconds);

Adds the given number of microseconds to time_. microseconds can also be negative to decrease the value of time_.

time_ : | a GTimeVal
microseconds : | number of microseconds to add to time

GDate

typedef struct {
  guint julian_days : 32; /* julian days representation - we use a
                           *  bitfield hoping that 64 bit platforms
                           *  will pack this whole struct in one big
                           *  int
                           */

  guint julian : 1;    /* julian is valid */
  guint dmy    : 1;    /* dmy is valid */

  /* DMY representation */
  guint day    : 6;
  guint month  : 4;
  guint year   : 16;
} GDate;

Represents a day between January 1, Year 1 and a few thousand years in the future. None of its members should be accessed directly. If the GDate is obtained from g_date_new(), it will be safe to mutate but invalid and thus not safe for calendrical computations. If it is declared on the stack, it will contain garbage so must be initialized with g_date_clear(). g_date_clear() makes the date invalid but sane. An invalid date does not represent a day, it's "empty." A date becomes valid after it is set to a Julian day or to a day, month, and year.

guint julian_days : 32: | the Julian representation of the date
guint julian : 1: | this bit is set if julian_days is valid
guint dmy : 1: | this is set if day, month and year are valid
guint day : 6: | the day of the day-month-year representation of the date, as a number between 1 and 31
guint month : 4: | the day of the day-month-year representation of the date, as a number between 1 and 12
guint year : 16: | the day of the day-month-year representation of the date

GTime

typedef gint32  GTime;

Simply a replacement for time_t. Unrelated to GTimer.

Note that GTime is defined to always be a 32bit integer, unlike time_t which may be 64bit on some systems. Therefore, GType will overflow in the year 2038, and the address of a GTime variable as argument to the UNIX time() function cannot be used. Instead, do the following:

time_t ttime;
GTime gtime;

time (&ttime);
gtime = (GTime)ttime;

enum GDateDMY

typedef enum
{
  G_DATE_DAY   = 0,
  G_DATE_MONTH = 1,
  G_DATE_YEAR  = 2
} GDateDMY;

This enumeration is not used in the API, but may be useful if there is a need to mark a number as a day, month, or year.

G_DATE_DAY | a day
G_DATE_MONTH | a month
G_DATE_YEAR | a year

GDateDay

typedef guint8  GDateDay;   /* day of the month */

Integer representing a day of the month; between 1 and 31. G_DATE_BAD_DAY represents an invalid day of the month.

enum GDateMonth

typedef enum
{
  G_DATE_BAD_MONTH = 0,
  G_DATE_JANUARY   = 1,
  G_DATE_FEBRUARY  = 2,
  G_DATE_MARCH     = 3,
  G_DATE_APRIL     = 4,
  G_DATE_MAY       = 5,
  G_DATE_JUNE      = 6,
  G_DATE_JULY      = 7,
  G_DATE_AUGUST    = 8,
  G_DATE_SEPTEMBER = 9,
  G_DATE_OCTOBER   = 10,
  G_DATE_NOVEMBER  = 11,
  G_DATE_DECEMBER  = 12
} GDateMonth;

Enumeration representing a month; values are G_DATE_JANUARY, G_DATE_FEBRUARY, etc. G_DATE_BAD_MONTH is the invalid value.

G_DATE_BAD_MONTH | invalid value.
G_DATE_JANUARY | January.
G_DATE_FEBRUARY | February.
G_DATE_MARCH | March.
G_DATE_APRIL | April.
G_DATE_MAY | May.
G_DATE_JUNE | June.
G_DATE_JULY | July.
G_DATE_AUGUST | August.
G_DATE_SEPTEMBER | September.
G_DATE_OCTOBER | October.
G_DATE_NOVEMBER | November.
G_DATE_DECEMBER | December.

GDateYear

typedef guint16 GDateYear;

Integer representing a year; G_DATE_BAD_YEAR is the invalid value. The year must be 1 or higher; negative (BC) years are not allowed. The year is represented with four digits.

enum GDateWeekday

typedef enum
{
  G_DATE_BAD_WEEKDAY  = 0,
  G_DATE_MONDAY       = 1,
  G_DATE_TUESDAY      = 2,
  G_DATE_WEDNESDAY    = 3,
  G_DATE_THURSDAY     = 4,
  G_DATE_FRIDAY       = 5,
  G_DATE_SATURDAY     = 6,
  G_DATE_SUNDAY       = 7
} GDateWeekday;

Enumeration representing a day of the week; G_DATE_MONDAY, G_DATE_TUESDAY, etc. G_DATE_BAD_WEEKDAY is an invalid weekday.

G_DATE_BAD_WEEKDAY | invalid value.
G_DATE_MONDAY | Monday.
G_DATE_TUESDAY | Tuesday.
G_DATE_WEDNESDAY | Wednesday.
G_DATE_THURSDAY | Thursday.
G_DATE_FRIDAY | Friday.
G_DATE_SATURDAY | Saturday.
G_DATE_SUNDAY | Sunday.

G_DATE_BAD_DAY

#define G_DATE_BAD_DAY    0U

Represents an invalid GDateDay.

G_DATE_BAD_JULIAN

#define G_DATE_BAD_JULIAN 0U

Represents an invalid Julian day number.

G_DATE_BAD_YEAR

#define G_DATE_BAD_YEAR   0U

Represents an invalid year.

g_date_new ()

GDate*      g_date_new                    (void);

Allocates a GDate and initializes it to a sane state. The new date will be cleared (as if g_date_clear()) was called but invalid (it will not represent an existing day). Free the return value with g_date_free().

Returns : a newly-allocated GDate.

g_date_new_dmy ()

GDate*      g_date_new_dmy                (GDateDay day, GDateMonth month, GDateYear year);

Like g_date_new(), but also sets the value of the date. Assuming the day-month-year triplet passed represents an existing day, the returned date will be valid.

day : | day of the month.
month : | month of the year.
year : | year
Returns : | a newly-allocated GDate initialized with day, month, and year.

g_date_new_julian ()

GDate*      g_date_new_julian             (guint32 julian_day);

Like g_date_new(), but also sets the value of the date. Assuming the Julian day number passed is valid (greater than 0, less than an unreasonably large number), the returned date will be valid.

julian_day : | days since January 1, Year 1.
Returns : | a newly-allocated GDate initialized with julian_day.

g_date_clear ()

void        g_date_clear                  (GDate *date, guint n_dates);

Initializes one or more GDate structs to a sane but invalid state. The cleared dates will not represent an existing date, but will not contain garbage. Useful to init a date declared on the stack. Validity can be tested with g_date_valid().

date : | pointer to one or more dates to clear.
n_dates : | number of dates to clear.

g_date_free ()

void        g_date_free                   (GDate *date);

Frees a GDate returned from g_date_new().

date : a GDate.

g_date_set_day ()

void        g_date_set_day                (GDate *date, GDateDay day);

Sets the day of the month for a GDate. If the resulting day-month-year triplet is invalid, the date will be invalid.

date : | a GDate.
day : | day to set.

g_date_set_month ()

void        g_date_set_month              (GDate *date, GDateMonth month);

Sets the month of the year for a GDate. If the resulting day-month-year triplet is invalid, the date will be invalid.

date : | a GDate.
month : | month to set.

g_date_set_year ()

void        g_date_set_year               (GDate *date, GDateYear year);

Sets the year for a GDate. If the resulting day-month-year triplet is invalid, the date will be invalid.

date : | a GDate.
year : | year to set.

g_date_set_dmy ()

void        g_date_set_dmy                (GDate *date, GDateDay day, GDateMonth month, GDateYear y);

Sets the value of a GDate from a day, month, and year. The day-month-year triplet must be valid; if not sure, call g_date_valid_dmy() to check before it is set.

date : | a GDate.
day : | day.
month : | month.
y : | year.

g_date_set_julian ()

void        g_date_set_julian             (GDate *date, guint32 julian_date);

Sets the value of a GDate from a Julian day number.

date : | a GDate.
julian_date : | Julian day number (days since January 1, Year 1).

g_date_set_time ()

void        g_date_set_time               (GDate *date, GTime time_);

Warning

g_date_set_time is deprecated and should not be used in newly-written code.

Sets the value of a date from a GTime value.

Deprecated:2.10: Use g_date_set_time_t() instead.

date : | a GDate.
time_ : | GTime value to set.

g_date_set_time_t ()

void        g_date_set_time_t           (GDate *date, time_t timet);

Sets the value of a date from a time_t value.

To set the value of a date to the current day, use the following code:

g_date_set_time_t (date, time (NULL));

date : | a GDate
timet : | time_t value to set

g_date_set_time_val ()

void        g_date_set_time_val             (GDate *date, GTimeVal *timeval);

Sets the value of a date from a GTimeVal value. Note that the tv_usec member is ignored, because GDate cannot make use of the additional precision.

date : | a GDate
timeval : | GTimeVal value to set

g_date_set_parse ()

void        g_date_set_parse               (GDate *date, const gchar *str);

Parses a user-inputted string str, and try to figure out what date it represents, taking the current locale into account. If the string is successfully parsed, the date will be valid after the call. Otherwise, it will be invalid. To check whether the parsing succeeded use g_date_valid().

This function is not appropriate for file formats and the like; it is not very precise, and it's exact behavior varies with the locale. It is intended to be a heuristic routine that guesses what the user means by a given string (and it does work pretty well in that capacity).

date : | a GDate to fill in.
str : | string to parse.

g_date_add_days ()

void        g_date_add_days                (GDate *date, guint n_days);

Increments a date some number of days. To move forward by weeks, add weeks*7 days. The date must be valid.

date : | a GDate to increment.
n_days : | number of days to move the date forward.

g_date_subtract_days ()

void        g_date_subtract_days           (GDate *date, guint n_days);

Moves a date some number of days into the past. To move by weeks, just move by weeks*7 days. The date must be valid.

date : | a GDate to decrement.
n_days : | number of days to move.

g_date_add_months ()

void        g_date_add_months              (GDate *date, guint n_months);

Increments a date by some number of months. If the day of the month is greater than 28, this routine may change the day of the month (because the destination month may not have the current day in it). The date must be valid.

date : | a GDate to increment.
n_months : | number of months to move forward.

g_date_subtract_months ()

void        g_date_subtract_months         (GDate *date, guint n_months);

Moves a date some number of months into the past. If the current day of the month does not exist in the destination month, the day of the month may change. The date must be valid.

date : | a GDate to decrement.
n_months : | number of months to move.

g_date_add_years ()

void        g_date_add_years               (GDate *date, guint n_years);

Increments a date by some number of years. If the date is February 29, and the destination year is not a leap year, the date will be changed to February 28. The date must be valid.

date : | a GDate to increment.
n_years : | number of years to move forward.

g_date_subtract_years ()

void        g_date_subtract_years          (GDate *date, guint n_years);

Moves a date some number of years into the past. If the current day does not exist in the destination year (i.e. it's February 29 and moved to a non-leap-year) then the day is changed to February 29. The date must be valid.

date : | a GDate to decrement.
n_years : | number of years to move.

g_date_days_between ()

gint        g_date_days_between            (const GDate *date1, const GDate *date2);

Computes the number of days between two dates. If date2 is prior to date1, the returned value is negative. Both dates must be valid.

date1 : | the first date.
date2 : | the second date.
Returns : | the number of days between date1 and date2.

g_date_compare ()

gint        g_date_compare                 (const GDate *lhs, const GDate *rhs);

qsort()-style comparsion function for dates. Both dates must be valid.

lhs : | first date to compare.
rhs : | second date to compare.
Returns : | 0 for equal, less than zero if lhs is less than rhs, greater than zero if lhs is greater than rhs.

g_date_clamp ()

void        g_date_clamp                   (GDate *date, const GDate *min_date, const GDate *max_date);

If date is prior to min_date, sets date equal to min_date. If date falls after max_date, sets date equal to max_date. Either min_date and max_date may be NULL. All non-NULL dates must be valid.

date : | a GDate to clamp.
min_date : | minimum accepted value for date.
max_date : | maximum accepted value for date.

g_date_order ()

void        g_date_order                   (GDate *date1, GDate *date2);

Checks if date1 is less than or equal to date2, and swap the values if this is not the case.

date1 : | the first date.
date2 : | the second date.

g_date_get_day ()

GDateDay    g_date_get_day                 (const GDate *date);

Returns the day of the month. The date must be valid.

date : | a GDate to extract the day of the month from.
Returns : | day of the month.

g_date_get_month ()

GDateMonth  g_date_get_month               (const GDate *date);

Returns the month of the year. The date must be valid.

date : | a GDate to get the month from.
Returns : | month of the year as a GDateMonth.

g_date_get_year ()

GDateYear   g_date_get_year                (const GDate *date);

Returns the year of a GDate. The date must be valid.

date : | a GDate.
Returns : | year in which the date falls.

g_date_get_julian ()

guint32     g_date_get_julian              (const GDate *date);

Returns the Julian day or "serial number" of the GDate. The Julian day is simply the number of days since January 1, Year 1; i.e., January 1, Year 1 is Julian day 1; January 2, Year 1 is Julian day 2, etc. The date must be valid.

date : | a GDate to extract the Julian day from.
Returns : | Julian day.

g_date_get_weekday ()

GDateWeekday g_date_get_weekday            (const GDate *date);

Returns the day of the week for a GDate. The date must be valid.

date : | a GDate.
Returns : | day of the week as a GDateWeekday.

g_date_get_day_of_year ()

guint       g_date_get_day_of_year         (const GDate *date);

Returns the day of the year, where Jan 1 is the first day of the year. The date must be valid.

date : | a GDate to extract day of year from.
Returns : | day of the year.

g_date_get_days_in_month ()

guint8      g_date_get_days_in_month       (GDateMonth month, GDateYear year);

Returns the number of days in a month, taking leap years into account.

month : | month.
year : | year.
Returns : | number of days in month during the year.

g_date_is_first_of_month ()

gboolean    g_date_is_first_of_month       (const GDate *date);

Returns TRUE if the date is on the first of a month. The date must be valid.

date : | a GDate to check.
Returns : | TRUE if the date is the first of the month.

g_date_is_last_of_month ()

gboolean    g_date_is_last_of_month        (const GDate *date);

Returns TRUE if the date is the last day of the month. The date must be valid.

date : | a GDate to check.
Returns : | TRUE if the date is the last day of the month.

g_date_is_leap_year ()

gboolean    g_date_is_leap_year             (GDateYear year);

Returns TRUE if the year is a leap year.

year : | year to check.
Returns : | TRUE if the year is a leap year.

g_date_get_monday_week_of_year ()

guint       g_date_get_monday_week_of_year  (const GDate *date);

Returns the week of the year, where weeks are understood to start on Monday. If the date is before the first Monday of the year, return 0. The date must be valid.

date : | a GDate.
Returns : | week of the year.

g_date_get_monday_weeks_in_year ()

guint8      g_date_get_monday_weeks_in_year (GDateYear year);

Returns the number of weeks in the year, where weeks are taken to start on Monday. Will be 52 or 53. The date must be valid. (Years always have 52 7-day periods, plus 1 or 2 extra days depending on whether it's a leap year. This function is basically tells how many Mondays are in the year, i.e. there are 53 Mondays if one of the extra days happens to be a Monday.)

year : | a year.
Returns : | number of Mondays in the year.

g_date_get_sunday_week_of_year ()

guint       g_date_get_sunday_week_of_year  (const GDate *date);

Returns the week of the year during which this date falls, if weeks are understood to being on Sunday. The date must be valid. Can return 0 if the day is before the first Sunday of the year.

date : | a GDate.
Returns : | week number.

g_date_get_sunday_weeks_in_year ()

guint8      g_date_get_sunday_weeks_in_year (GDateYear year);

Returns the number of weeks in the year, where weeks are taken to start on Sunday. Will be 52 or 53. The date must be valid. (Years always have 52 7-day periods, plus 1 or 2 extra days depending on whether it is a leap year. This function is basically tells how many Sundays are in the year, i.e. there are 53 Sundays if one of the extra days happens to be a Sunday.)

year : | year to count weeks in.
Returns : | number of weeks.

g_date_get_iso8601_week_of_year ()

guint       g_date_get_iso8601_week_of_year (const GDate *date);

Returns the week of the year, where weeks are interpreted according to ISO 8601.

date : | a valid GDate
Returns : | ISO 8601 week number of the year.

g_date_strftime ()

gsize       g_date_strftime           (gchar *s, gsize slen, const gchar *format, const GDate *date);

Generates a printed representation of the date, in a locale-specific way. Works just like the standard C strftime() function, but only accepts date-related formats; time-related formats give undefined results. Date must be valid.

s : | destination buffer.
slen : | buffer size.
format : | format string.
date : | valid GDate.
Returns : | number of characters written to the buffer, or 0 the buffer was too small.

g_date_to_struct_tm ()

void        g_date_to_struct_tm       (const GDate *date, struct tm *tm);

Fills in the date-related bits of a struct tm using the date value. Initializes the non-date parts with something sane but meaningless.

date : | a GDate to set the struct tm from.
tm : | struct tm to fill.

g_date_valid ()

gboolean    g_date_valid              (const GDate *date);

Returns TRUE if the GDate represents an existing day. The date must not contain garbage; it should have been initialized with g_date_clear() if it was not allocated by one of the g_date_new() variants.

date : | a GDate to check.
Returns : | Whether the date is valid.

g_date_valid_day ()

gboolean    g_date_valid_day          (GDateDay day);

Returns TRUE if the day of the month is valid (a day is valid if it's between 1 and 31 inclusive).

day : | day to check.
Returns : | TRUE if the day is valid.

g_date_valid_month ()

gboolean    g_date_valid_month        (GDateMonth month);

Returns TRUE if the month value is valid. The 12 GDateMonth enumeration values are the only valid months.

month : | month.
Returns : | TRUE if the month is valid.

g_date_valid_year ()

gboolean    g_date_valid_year         (GDateYear year);

Returns TRUE if the year is valid. Any year greater than 0 is valid, though there is a 16-bit limit to what GDate will understand.

year : | year.
Returns : | TRUE if the year is valid.

g_date_valid_dmy ()

gboolean    g_date_valid_dmy          (GDateDay day, GDateMonth month, GDateYear year);

Returns TRUE if the day-month-year triplet forms a valid, existing day in the range of days GDate understands (Year 1 or later, no more than a few thousand years in the future).

day : | day.
month : | month.
year : | year.
Returns : | TRUE if the date is a valid one.

g_date_valid_julian ()

gboolean    g_date_valid_julian        (guint32 julian_date);

Returns TRUE if the Julian day is valid. Anything greater than zero is basically a valid Julian, though there is a 32-bit limit.

julian_date : | Julian day to check.
Returns : | TRUE if the Julian day is valid.

g_date_valid_weekday ()

gboolean    g_date_valid_weekday       (GDateWeekday weekday);

Returns TRUE if the weekday is valid. The 7 GDateWeekday enumeration values are the only valid weekdays.

weekday : | weekday.
Returns : | TRUE if the weekday is valid.

Feedback

For additional information or queries on this page send feedback


Double-ended Queues

Name

Double-ended Queues — double-ended queue data structure.

Library

glib.lib

Synopsis

#include <glib.h>

GQueue;
GQueue*     g_queue_new                     (void);
void        g_queue_free                    (GQueue *queue);
gboolean    g_queue_is_empty                (GQueue *queue);
guint       g_queue_get_length              (GQueue *queue);
void        g_queue_reverse                 (GQueue *queue);
GQueue*     g_queue_copy                    (GQueue *queue);
void        g_queue_foreach                 (GQueue *queue, GFunc func, gpointer user_data);
GList*      g_queue_find                    (GQueue *queue, gconstpointer data);
GList*      g_queue_find_custom             (GQueue *queue, gconstpointer data, GCompareFunc func);
void        g_queue_sort                    (GQueue *queue, GCompareDataFunc compare_func, gpointer user_data);
void        g_queue_push_head               (GQueue *queue, gpointer data);
void        g_queue_push_tail               (GQueue *queue, gpointer data);
void        g_queue_push_nth                (GQueue *queue, gpointer data, gint n);
gpointer    g_queue_pop_head                (GQueue *queue);
gpointer    g_queue_pop_tail                (GQueue *queue);
gpointer    g_queue_pop_nth                 (GQueue *queue, guint n);
gpointer    g_queue_peek_head               (GQueue *queue);
gpointer    g_queue_peek_tail               (GQueue *queue);
gpointer    g_queue_peek_nth                (GQueue *queue, guint n);
gint        g_queue_index                   (GQueue *queue, gconstpointer data);
void        g_queue_remove                  (GQueue *queue, gconstpointer data);
void        g_queue_remove_all              (GQueue *queue, gconstpointer data);
void        g_queue_insert_before           (GQueue *queue, GList *sibling, gpointer data);
void        g_queue_insert_after            (GQueue *queue, GList *sibling, gpointer data);
void        g_queue_insert_sorted           (GQueue *queue, gpointer data, GCompareDataFunc func, gpointer user_data);
void        g_queue_push_head_link          (GQueue *queue, GList *link_);
void        g_queue_push_tail_link          (GQueue *queue, GList *link_);
void        g_queue_push_nth_link           (GQueue *queue, gint n, GList *link_);
GList*      g_queue_pop_head_link           (GQueue *queue);
GList*      g_queue_pop_tail_link           (GQueue *queue);
GList*      g_queue_pop_nth_link            (GQueue *queue, guint n);
GList*      g_queue_peek_head_link          (GQueue *queue);
GList*      g_queue_peek_tail_link          (GQueue *queue);
GList*      g_queue_peek_nth_link           (GQueue *queue, guint n);
gint        g_queue_link_index              (GQueue *queue, GList *link_);
void        g_queue_unlink                  (GQueue *queue, GList *link_);
void        g_queue_delete_link             (GQueue *queue, GList *link_);

Detailed Description

The GQueue structure and its associated functions provide a standard queue data structure. Internally, GQueue uses the same data structure as GList to store elements.

The data contained in each element can be either integer values, by using one of the Type Conversion Macros, or simply pointers to any type of data.

To create a new GQueue, use g_queue_new().

To add elements, use

g_queue_push_head(),

g_queue_push_head_link(),

g_queue_push_tail() and

g_queue_push_tail_link().

To remove elements, use g_queue_pop_head() and g_queue_pop_tail().

To free the entire queue, use g_queue_free().

Details

GQueue

typedef struct {
  GList *head;
  GList *tail;
  guint  length;
} GQueue;

Contains the public fields of a Queue.

GList *head; | a pointer to the first element of the queue.
GList *tail; | a pointer to the last element of the queue.
guint length; | the number of elements in the queue.

g_queue_new ()

GQueue*     g_queue_new            (void);

Creates a new GQueue.

Returns : a new GQueue.

g_queue_free ()

void        g_queue_free           (GQueue *queue);

Frees the memory allocated for the GQueue.

queue : a GQueue.

g_queue_is_empty ()

gboolean    g_queue_is_empty       (GQueue *queue);

Returns TRUE if the queue is empty.

queue : | a GQueue.
Returns : | TRUE if the queue is empty.

g_queue_get_length ()

guint       g_queue_get_length    (GQueue *queue);

Returns the number of items in queue.

queue : | a GQueue
Returns : | The number of items in queue.

g_queue_reverse ()

void        g_queue_reverse     (GQueue *queue);

Reverses the order of the items in queue.

queue : a GQueue

g_queue_copy ()

GQueue*     g_queue_copy        (GQueue *queue);

Copies a queue. Note that is a shallow copy. If the elements in the queue consist of pointers to data, the pointers are copied, but the actual data is not.

queue : | a GQueue
Returns : | A copy of queue

g_queue_foreach ()

void        g_queue_foreach     (GQueue *queue, GFunc func, gpointer user_data);

Calls func for each element in the queue passing user_data to the function.

queue : | a GQueue
func : | the function to call for each element's data
user_data : | user data to pass to func

g_queue_find ()

GList*      g_queue_find       (GQueue *queue, gconstpointer data);

Finds the first link in queue which contains data.

queue : | a GQueue
data : | data to find
Returns : | The first link in queue which contains data.

g_queue_find_custom ()

GList*      g_queue_find_custom     (GQueue *queue, gconstpointer data, GCompareFunc func);

Finds an element in a GQueue, using a supplied function to find the desired element. It iterates over the queue, calling the given function which should return 0 when the desired element is found. The function takes two gconstpointer arguments, the GQueue element's data as the first argument and the given user data as the second argument.

queue : | a GQueue
data : | user data passed to func
func : | a GCompareFunc to call for each element. It should return 0 when the desired element is found
Returns : | The found link, or NULL if it wasn't found

g_queue_sort ()

void        g_queue_sort           (GQueue *queue, GCompareDataFunc compare_func, gpointer user_data);

Sorts queue using compare_func.

queue : | a GQueue
compare_func : | the GCompareDataFunc used to sort queue. This function is passed two elements of the queue and should return 0 if they are equal, a negative value if the first comes before the second, and a positive value if the second comes before the first.
user_data : | user data passed to compare_func

g_queue_push_head ()

void        g_queue_push_head      (GQueue *queue, gpointer data);

Adds a new element at the head of the queue.

queue : | a GQueue.
data : | the data for the new element.

g_queue_push_tail ()

void        g_queue_push_tail      (GQueue *queue, gpointer data);

Adds a new element at the tail of the queue.

queue : | a GQueue.
data : | the data for the new element.

g_queue_push_nth ()

void        g_queue_push_nth      (GQueue *queue, gpointer data, gint n);

Inserts a new element into queue at the given position

queue : | a GQueue
data : | the data for the new element
n : | the position to insert the new element. If n is negative or larger than the number of elements in the queue, the element is added to the end of the queue.

g_queue_pop_head ()

gpointer    g_queue_pop_head     (GQueue *queue);

Removes the first element of the queue.

queue : | a GQueue.
Returns : | the data of the first element in the queue, or NULL if the queue is empty.

g_queue_pop_tail ()

gpointer    g_queue_pop_tail     (GQueue *queue);

Removes the last element of the queue.

queue : | a GQueue.
Returns : | the data of the last element in the queue, or NULL if the queue is empty.

g_queue_pop_nth ()

gpointer    g_queue_pop_nth      (GQueue *queue, guint n);

Removes the n'th element of queue.

queue : | a GQueue
n : | the position of the element.
Returns : | the element's data, or NULL if n is off the end of queue.

g_queue_peek_head ()

gpointer    g_queue_peek_head     (GQueue *queue);

Returns the first element of the queue.

queue : | a GQueue.
Returns : | the data of the first element in the queue, or NULL if the queue is empty.

g_queue_peek_tail ()

gpointer    g_queue_peek_tail     (GQueue *queue);

Returns the last element of the queue.

queue : | a GQueue.
Returns : | the data of the last element in the queue, or NULL if the queue is empty.

g_queue_peek_nth ()

gpointer    g_queue_peek_nth      (GQueue *queue, guint n);

Returns the n'th element of queue.

queue : | a GQueue
n : | the position of the element.
Returns : | The data for the n'th element of queue, or NULL if n is off the end of queue.

g_queue_index ()

gint        g_queue_index         (GQueue *queue, gconstpointer data);

Returns the position of the first element in queue which contains data.

queue : | a GQueue
data : | the data to find.
Returns : | The position of the first element in queue which contains data, or -1 if no element in queue contains data.

g_queue_remove ()

void        g_queue_remove        (GQueue *queue, gconstpointer data);

Removes the first element in queue that contains data.

queue : | a GQueue
data : | data to remove.

g_queue_remove_all ()

void        g_queue_remove_all    (GQueue *queue, gconstpointer data);

Remove all elements in queue which contains data.

queue : | a GQueue
data : | data to remove

g_queue_insert_before ()

void      g_queue_insert_before   (GQueue *queue, GList *sibling, gpointer data);

Inserts data into queue before sibling, which must be part of queue.

queue : | a GQueue
sibling : | a GList link that must be part of queue
data : | the data to insert

g_queue_insert_after ()

void     g_queue_insert_after     (GQueue *queue, GList *sibling, gpointer data);

Inserts data into queue after sibling

sibling must be part of queue

queue : | a GQueue
sibling : | a GList link that must be part of queue
data : | the data to insert

g_queue_insert_sorted ()

void    g_queue_insert_sorted     (GQueue *queue, gpointer data, GCompareDataFunc func, gpointer user_data);

Inserts data into queue using func to determine the new position.

queue : | a GQueue
data : | the data to insert
func : | the GCompareDataFunc used to compare elements in the queue. It is called with two elements of the queue and user_data. It should return 0 if the elements are equal, a negative value if the first element comes before the second, and a positive value if the second element comes before the first.
user_data : | user data passed to func.

g_queue_push_head_link ()

void   g_queue_push_head_link     (GQueue *queue, GList *link_);

Adds a new element at the head of the queue.

queue : | a GQueue.
link_ : | a single GList element, not a list with more than one element.

g_queue_push_tail_link ()

void   g_queue_push_tail_link    (GQueue *queue, GList *link_);

Adds a new element at the tail of the queue.

queue : | a GQueue.
link_ : | a single GList element, not a list with more than one element.

g_queue_push_nth_link ()

void   g_queue_push_nth_link     (GQueue *queue, gint n, GList *link_);

Inserts link into queue at the given position.

queue : | a GQueue
n : | the position to insert the link. If this is negative or larger than the number of elements in queue, the link is added to the end of queue.
link_ : | the link to add to queue

g_queue_pop_head_link ()

GList*   g_queue_pop_head_link    (GQueue *queue);

Removes the first element of the queue.

queue : | a GQueue.
Returns : | the GList element at the head of the queue, or NULL if the queue is empty.

g_queue_pop_tail_link ()

GList*   g_queue_pop_tail_link    (GQueue *queue);

Removes the last element of the queue.

queue : | a GQueue.
Returns : | the GList element at the tail of the queue, or NULL if the queue is empty.

g_queue_pop_nth_link ()

GList*   g_queue_pop_nth_link     (GQueue *queue, guint n);

Removes and returns the link at the given position.

queue : | a GQueue
n : | the link's position
Returns : | The n'th link, or NULL if n is off the end of queue.

g_queue_peek_head_link ()

GList*   g_queue_peek_head_link    (GQueue *queue);

Returns the first link in queue.

queue : | a GQueue
Returns : | the first link in queue, or NULL if queue is empty

g_queue_peek_tail_link ()

GList*   g_queue_peek_tail_link    (GQueue *queue);

Returns the last link in queue.

queue : | a GQueue
Returns : | the last link in queue, or NULL if queue is empty

g_queue_peek_nth_link ()

GList*   g_queue_peek_nth_link     (GQueue *queue, guint n);

Returns the link at the given position.

queue : | a GQueue
n : | the position of the link
Returns : | The link at the n'th position, or NULL if n is off the end of the list

g_queue_link_index ()

gint     g_queue_link_index      (GQueue *queue, GList *link_);

Returns the position of link_ in queue.

queue : | a Gqueue
link_ : | A GList link
Returns : | The position of link_, or -1 if the link is not part of queue

g_queue_unlink ()

void    g_queue_unlink          (GQueue *queue, GList *link_);

Unlinks link_ so that it will no longer be part of queue. The link is not freed. link_ must be part of queue.

queue : | a GQueue
link_ : | a GList link that must be part of queue

g_queue_delete_link ()

void   g_queue_delete_link      (GQueue *queue, GList *link_);

Removes link_ from queue and frees it.

link_ must be part of queue.

queue : | a GQueue
link_ : | a GList link that must be part of queue

Feedback

For additional information or queries on this page send feedback


Double-ended Queues

Name

Doubly-Linked Lists lists containing integer values or pointers to data, with the ability to iterate over the list in both directions.

Library

glib.lib

Synopsis

#include <glib.h>

GList;
GList*      g_list_append                   (GList *list, gpointer data);
GList*      g_list_prepend                  (GList *list, gpointer data);
GList*      g_list_insert                   (GList *list, gpointer data, gint position);
GList*      g_list_insert_before            (GList *list, GList *sibling, gpointer data);
GList*      g_list_insert_sorted            (GList *list, gpointer data, GCompareFunc func);
GList*      g_list_remove                   (GList *list, gconstpointer data);
GList*      g_list_remove_link              (GList *list, GList *llink);
GList*      g_list_delete_link              (GList *list, GList *link_);
GList*      g_list_remove_all               (GList *list, gconstpointer data);
void        g_list_free                     (GList *list);

GList*      g_list_alloc                    (void);
void        g_list_free_1                   (GList *list);

guint       g_list_length                   (GList *list);
GList*      g_list_copy                     (GList *list);
GList*      g_list_reverse                  (GList *list);
GList*      g_list_sort                     (GList *list, GCompareFunc compare_func);
gint        (*GCompareFunc)                 (gconstpointer a, gconstpointer b);
GList*      g_list_sort_with_data           (GList *list, GCompareDataFunc compare_func, gpointer user_data);
gint        (*GCompareDataFunc)             (gconstpointer a, gconstpointer b, gpointer user_data);
GList*      g_list_concat                   (GList *list1, GList *list2);
void        g_list_foreach                  (GList *list, GFunc func, gpointer user_data);
void        (*GFunc)                        (gpointer data, gpointer user_data);

GList*      g_list_first                    (GList *list);
GList*      g_list_last                     (GList *list);
#define     g_list_previous                 (list)
#define     g_list_next                     (list)
GList*      g_list_nth                      (GList *list, guint n);
gpointer    g_list_nth_data                 (GList *list, guint n);
GList*      g_list_nth_prev                 (GList *list, guint n);

GList*      g_list_find                     (GList *list, gconstpointer data);
GList*      g_list_find_custom              (GList *list, gconstpointer data, GCompareFunc func);
gint        g_list_position                 (GList *list, GList *llink);
gint        g_list_index                    (GList *list, gconstpointer data);

void        g_list_push_allocator           (GAllocator *allocator);
void        g_list_pop_allocator            (void);

Detailed Description

The GList structure and its associated functions provide a standard doubly-linked list data structure.

Each element in the list contains a piece of data, together with pointers which link to the previous and next elements in the list. Using these pointers it is possible to move through the list in both directions (unlike the Singly-Linked Lists which only allows movement through the list in the forward direction).

The data contained in each element can be either integer values, by using one of the Type Conversion Macros, or simply pointers to any type of data.

List elements are allocated in blocks using a GAllocator, which is more efficient than allocating elements individually.

Note that most of the GList functions expect to be passed a pointer to the first element in the list. The functions which insert elements return the new start of the list, which may have changed.

There is no function to create a GList. NULL is considered to be the empty list so, set a GList* to NULL.

To add elements, use g_list_append(), g_list_prepend(), g_list_insert() and g_list_insert_sorted().

To remove elements, use g_list_remove().

To find elements in the list use g_list_first(),
g_list_last(),
g_list_next(),
g_list_previous(),
g_list_nth(),
g_list_nth_data(),
g_list_find()
and
g_list_find_custom().

To find the index of an element use g_list_position() and g_list_index().

To call a function for each element in the list use g_list_foreach().

To free the entire list, use g_list_free().

Details

GList

typedef struct {
  gpointer data;
  GList *next;
  GList *prev;
} GList;

The GList struct is used for each element in a doubly-linked list.

gpointer data; | holds the element's data, which can be a pointer to any kind of data, or any integer value using the Type Conversion Macros.
GList *next; | contains the link to the next element in the list.
GList *prev; | contains the link to the previous element in the list.

g_list_append ()

GList*      g_list_append                   (GList *list, gpointer data);

Adds a new element on to the end of the list. Note that g_list_append() has to traverse the entire list to find the end, which is inefficient when adding multiple elements. A common idiom to avoid the inefficiency is to prepend the elements and reverse the list when all elements have been added.

Note

Note: The return value is the new start of the list, which may have changed, so make sure to store the new value.

  /* Notice that these are initialized to the empty list. */
  GList *list = NULL, *number_list = NULL;

  /* This is a list of strings. */
  list = g_list_append (list, "first");
  list = g_list_append (list, "second");

  /* This is a list of integers. */
  number_list = g_list_append (number_list, GINT_TO_POINTER (27));
  number_list = g_list_append (number_list, GINT_TO_POINTER (14));
list : | a pointer to a GList.
data : | the data for the new element.
Returns : | the new start of the GList.

g_list_prepend ()

GList*      g_list_prepend                  (GList *list, gpointer data);

Adds a new element on to the start of the list.

  /* Notice that it is initialized to the empty list. */
  GList *list = NULL;
  list = g_list_prepend (list, "last");
  list = g_list_prepend (list, "first");
list : | a pointer to a GList.
data : | the data for the new element.
Returns : | the new start of the GList.

g_list_insert ()

GList*      g_list_insert                   (GList *list, gpointer data, gint position);

Inserts a new element into the list at the given position.

list : | a pointer to a GList.
data : | the data for the new element.
position : | the position to insert the element. If this is negative, or is larger than the number of elements in the list, the new element is added on to the end of the list.
Returns : | the new start of the GList.

g_list_insert_before ()

GList*      g_list_insert_before            (GList *list, GList *sibling, gpointer data);

Inserts a new element into the list before the given position.

list : | a pointer to a GList.
sibling : | the list element before which the new element is inserted or NULL to insert at the end of the list.
data : | the data for the new element.
Returns : | the new start of the GList.

g_list_insert_sorted ()

GList*      g_list_insert_sorted            (GList *list, gpointer data, GCompareFunc func);

Inserts a new element into the list, using the given comparison function to determine its position.

list : | a pointer to a GList.
data : | the data for the new element.
func : | the function to compare elements in the list. It should return a number > 0 if the first parameter comes after the second parameter in the sort order.
Returns : | the new start of the GList.

g_list_remove ()

GList*      g_list_remove                   (GList *list, gconstpointer data);

Removes an element from a GList. If two elements contain the same data, only the first is removed. If none of the elements contain the data, the GList is unchanged.

list : | a GList.
data : | the data of the element to remove.
Returns : | the new start of the GList.

g_list_remove_link ()

GList*      g_list_remove_link              (GList *list, GList *llink);

Removes an element from a GList, without freeing the element. The removed element's prev and next links are set to NULL, so that it becomes a self-contained list with one element.

list : | a GList.
llink : | an element in the GList.
Returns : | the new start of the GList, without the element.

g_list_delete_link ()

GList*      g_list_delete_link              (GList *list, GList *link_);

Deletes the node link_ from list.

list : | a GList.
link_ : | node to delete from list.
Returns : | the new head of list.

g_list_remove_all ()

GList*      g_list_remove_all               (GList *list, gconstpointer data);

Removes all list nodes with data equal to data. Returns the new head of the list. Contrast with g_list_remove() which removes only the first node matching the given data.

list : | a GList.
data : | data to remove.
Returns : | new head of list.

g_list_free ()

void        g_list_free                     (GList *list);

Frees all of the memory used by a GList. The freed elements are added to the GAllocator free list.

Note

Note: If list elements contain dynamically-allocated memory, they should be freed first.

list : a GList.

g_list_alloc ()

GList*      g_list_alloc                    (void);

Allocates space for one GList element. It is called by g_list_append(), g_list_prepend(), g_list_insert() and g_list_insert_sorted() and so is rarely used on its own.

Returns : a pointer to the newly-allocated GList element.

g_list_free_1 ()

void        g_list_free_1                   (GList *list);

Frees one GList element. It is usually used after g_list_remove_link().

list : a GList element.

g_list_length ()

guint       g_list_length                   (GList *list);

Gets the number of elements in a GList.

list : | a GList.
Returns : | the number of elements in the GList.

g_list_copy ()

GList*      g_list_copy                     (GList *list);

Copies a GList.

Note that this is a "shallow" copy. If the list elements consist of pointers to data, the pointers are copied but the actual data isn't.

list : | a GList.
Returns : | a copy of list.

g_list_reverse ()

GList*      g_list_reverse                  (GList *list);

Reverses a GList. It simply switches the next and prev pointers of each element.

list : | a GList.
Returns : | the start of the reversed GList.

g_list_sort ()

GList*      g_list_sort                     (GList *list, GCompareFunc compare_func);

Sorts a GList using the given comparison function.

list : | a GList.
compare_func : | the comparison function used to sort the GList. This function is passed the data from 2 elements of the GList and should return 0 if they are equal, a negative value if the first element comes before the second, or a positive value if the first element comes after the second.
Returns : | the start of the sorted GList.

GCompareFunc ()

gint        (*GCompareFunc)                 (gconstpointer a, gconstpointer b);

Specifies the type of a comparison function used to compare two values. The function should return a negative integer if the first value comes before the second, 0 if they are equal, or a positive integer if the first value comes after the second.

a : | a value.
b : | a value to compare with.
Returns : | negative value if a < b; zero if a = b; positive value if a > b.

g_list_sort_with_data ()

GList*      g_list_sort_with_data           (GList *list, GCompareDataFunc compare_func, gpointer user_data);

Like g_list_sort(), but the comparison function accepts a user data argument.

list : | a GList.
compare_func : | comparison function.
user_data : | user data to pass to comparison function.
Returns : | the new head of list.

GCompareDataFunc ()

gint        (*GCompareDataFunc)             (gconstpointer a, gconstpointer b, gpointer user_data);

Specifies the type of a comparison function used to compare two values. The function should return a negative integer if the first value comes before the second, 0 if they are equal, or a positive integer if the first value comes after the second.

a : | a value.
b : | a value to compare with.
user_data : | user data to pass to comparison function.
Returns : | negative value if a < b; zero if a = b; positive value if a > b.

g_list_concat ()

GList*      g_list_concat                   (GList *list1, GList *list2);

Adds the second GList onto the end of the first GList. Note that the elements of the second GList are not copied. They are used directly.

list1 : | a GList.
list2 : | the GList to add to the end of the first GList.
Returns : | the start of the new GList.

g_list_foreach ()

void        g_list_foreach                  (GList *list, GFunc func, gpointer user_data);

Calls a function for each element of a GList.

list : | a GList.
func : | the function to call with each element's data.
user_data : | user data to pass to the function.

GFunc ()

void        (*GFunc)                        (gpointer data, gpointer user_data);

Specifies the type of functions passed to g_list_foreach() and g_slist_foreach().

data : | the element's data.
user_data : | user data passed to g_list_foreach() or g_slist_foreach().

g_list_first ()

GList*      g_list_first                    (GList *list);

Gets the first element in a GList.

list : | a GList.
Returns : | the first element in a GList, or NULL if the GList has no elements.

g_list_last ()

GList*      g_list_last                     (GList *list);

Gets the last element in a GList.

list : | a GList.
Returns : | the last element in the GList, or NULL if the GList has no elements.

g_list_previous()

#define     g_list_previous(list)

A convenient macro to get the previous element in a GList.

list : | an element in a GList.
Returns : | the previous element, or NULL if there are no previous elements.

g_list_next()

#define     g_list_next(list)

A convenient macro to get the next element in a GList.

list : | an element in a GList.
Returns : | the next element, or NULL if there are no more elements.

g_list_nth ()

GList*      g_list_nth                      (GList *list, guint n);

Gets the element at the given position in a GList.

list : | a GList.
n : | the position of the element, counting from 0.
Returns : | the element, or NULL if the position is off the end of the GList.

g_list_nth_data ()

gpointer    g_list_nth_data                 (GList *list, guint n);

Gets the data of the element at the given position.

list : | a GList.
n : | the position of the element.
Returns : | the element's data, or NULL if the position is off the end of the GList.

g_list_nth_prev ()

GList*      g_list_nth_prev                 (GList *list, guint n);

Gets the element n places before list.

list : | a GList.
n : | the position of the element, counting from 0.
Returns : | the element, or NULL if the position is off the end of the GList.

g_list_find ()

GList*      g_list_find                     (GList *list, gconstpointer data);

Finds the element in a GList which contains the given data.

list : | a GList.
data : | the element data to find.
Returns : | the found GList element, or NULL if it is not found.

g_list_find_custom ()

GList*      g_list_find_custom              (GList *list, gconstpointer data, GCompareFunc func);

Finds an element in a GList, using a supplied function to find the desired element. It iterates over the list, calling the given function which should return 0 when the desired element is found. The function takes two gconstpointer arguments, the GList element's data as the first argument and the given user data.

list : | a GList.
data : | user data passed to the function.
func : | the function to call for each element. It should return 0 when the desired element is found.
Returns : | the found GList element, or NULL if it is not found.

g_list_position ()

gint        g_list_position                 (GList *list, GList *llink);

Gets the position of the given element in the GList (starting from 0).

list : | a GList.
llink : | an element in the GList.
Returns : | the position of the element in the GList, or -1 if the element is not found.

g_list_index ()

gint        g_list_index                    (GList *list, gconstpointer data);

Gets the position of the element containing the given data (starting from 0).

list : | a GList.
data : | the data to find.
Returns : | the index of the element containing the data, or -1 if the data is not found.

g_list_push_allocator ()

void        g_list_push_allocator           (GAllocator *allocator);

Sets the allocator to use to allocate GList elements. Use g_list_pop_allocator() to restore the previous allocator.

Note that this function is not available if GLib has been compiled with --disable-mem-pools

allocator : the GAllocator to use when allocating GList elements.

g_list_pop_allocator ()

void        g_list_pop_allocator            (void);

Restores the previous GAllocator, used when allocating GList elements. Note that this function is not available if GLib has been compiled with --disable-mem-pools.

Feedback

For additional information or queries on this page send feedback


glib-Dynamic Loading of Modules

Name

Dynamic Loading of Modules — portable method for dynamically loading 'plug-ins'.

Library

glib.lib

Synopsis

#include <gmodule.h>

            GModule;
gboolean    g_module_supported              (void);
gchar*      g_module_build_path             (const gchar *directory,
                                             const gchar *module_name);
GModule*    g_module_open                   (const gchar *file_name,
                                             GModuleFlags flags);
enum        GModuleFlags;
gboolean    g_module_symbol                 (GModule *module,
                                             const gchar *symbol_name,
                                             gpointer *symbol);
const gchar* g_module_name                  (GModule *module);
void        g_module_make_resident          (GModule *module);
gboolean    g_module_close                  (GModule *module);
const gchar* g_module_error                 (void);

const gchar* (*GModuleCheckInit)            (GModule *module);
void        (*GModuleUnload)                (GModule *module);
#define     G_MODULE_SUFFIX
#define     G_MODULE_EXPORT
#define     G_MODULE_IMPORT

Detailed Description

These functions provide a portable way to dynamically load object files (commonly known as 'plug-ins'). The current implementation supports all systems that provide an implementation of dlopen() (e.g. Linux/Sun), as well as HP-UX via its shl_load() mechanism, and Windows platforms via DLLs.

A program which wants to use these functions must be linked to the libraries output by the command pkg-config --libs gmodule-2.0.

To use them first determine whether dynamic loading is supported on the platform by calling g_module_supported(). If it is supported,open a module with g_module_open(), find the module's symbols (e.g. function names) with g_module_symbol(), and later close the module with g_module_close(). g_module_name() will return the file name of a currently opened module.

If any of the above functions fail, the error status can be found with g_module_error().

The GModule implementation features reference counting for opened modules, and supports hook functions within a module which are called when the module is loaded and unloaded (see GModuleCheckInit and GModuleUnload ).

If the module introduces static data to common subsystems in the running program, e.g. through calling g_quark_from_static_string ("my-module-stuff"), it must ensure that it is never unloaded, by calling g_module_make_resident().

Example 12. Calling a function defined in a GModule

/* the function signature for 'say_hello' */
typedef void (* SayHelloFunc) (const char *message);

gboolean
just_say_hello (const char *filename, GError **error)
{
  SayHelloFunc  say_hello;
  GModule      *module;

  module = g_module_open (filename, G_MODULE_BIND_LAZY);
  if (!module)
    {
      g_set_error (error, FOO_ERROR, FOO_ERROR_BLAH,
           "%s", g_module_error ());
      return FALSE;
    }

  if (!g_module_symbol (module, "say_hello", (gpointer *)&say_hello))
    {
      g_set_error (error, SAY_ERROR, SAY_ERROR_OPEN,
           "%s: %s", filename, g_module_error ());
      if (!g_module_close (module))
    g_warning ("%s: %s", filename, g_module_error ());
      return FALSE;
    }

  /* call our function in the module */
  say_hello ("Hello world!");

  if (!g_module_close (module))
    g_warning ("%s: %s", filename, g_module_error ());

  return TRUE;
}

Details

GModule

typedef struct _GModule GModule;

The GModule struct is an opaque data structure to represent a Dynamically-Loaded Module. It should only be accessed via the following functions.

g_module_supported ()

gboolean    g_module_supported              (void);

Checks if modules are supported on the current platform.

Returns : TRUE if modules are supported.

g_module_build_path ()

gchar*      g_module_build_path             (const gchar *directory,
                                             const gchar *module_name);

A portable way to build the filename of a module. The platform-specific prefix and suffix are added to the filename, if needed, and the result is added to the directory, using the correct separator character.

The directory should specify the directory where the module can be found. It can be NULL or an empty string to indicate that the module is in a standard platform-specific directory, though this is not recommended since the wrong module may be found.

For example, calling g_module_build_path() on a Linux system with a directory of /lib and a module_name of "mylibrary" will return /lib/libmylibrary.so. On a Windows system, using \Windows as the directory it will return \Windows\mylibrary.dll.

directory : | the directory where the module is. This can be NULL or the empty string to indicate that the standard platform-specific directories will be used, though that is not recommended.
module_name : | the name of the module.
Returns : | the complete path of the module, including the standard library prefix and suffix. This should be freed when no longer needed.

g_module_open ()

GModule*    g_module_open                   (const gchar *file_name,
                                             GModuleFlags flags);

Opens a module. If the module has already been opened, its reference count is incremented.

First of all g_module_open() tries to open file_name as a module. If that fails and file_name has the ".la"-suffix (and is a libtool archive) it tries to open the corresponding module. If that fails and it does not have the proper module suffix for the platform (G_MODULE_SUFFIX), this suffix will be appended and the corresponding module will be opended. If that fails and file_name does not have the ".la"-suffix, this suffix is appended and g_module_open() tries to open the corresponding module. If eventually that fails as well, NULL is returned.

file_name : | the name of the file containing the module, or NULL to obtain a GModule representing the main program itself.
flags : | the flags used for opening the module. This can be the logical OR of any of the GModuleFlags.
Returns : | a GModule on success, or NULL on failure.

enum GModuleFlags

typedef enum
{
  G_MODULE_BIND_LAZY	= 1 << 0,
  G_MODULE_BIND_LOCAL	= 1 << 1,
  G_MODULE_BIND_MASK	= 0x03
} GModuleFlags;

Flags passed to g_module_open(). Note that these flags are not supported on all platforms.

G_MODULE_BIND_LAZY | specifies that symbols are only resolved when needed. The default action is to bind all symbols when the module is loaded.
G_MODULE_BIND_LOCAL | specifies that symbols in the module should not be added to the global name space. The default action on most platforms is to place symbols in the module in the global name space, which may cause conflicts with existing symbols.
G_MODULE_BIND_MASK | mask for all flags.

g_module_symbol ()

gboolean    g_module_symbol                 (GModule *module,
                                             const gchar *symbol_name,
                                             gpointer *symbol);

Gets a symbol pointer from a module.

module : | a GModule.
symbol_name : | the name of the symbol to find.
symbol : | returns the pointer to the symbol value.
Returns : | TRUE on success.

g_module_name ()

const gchar* g_module_name                  (GModule *module);

Gets the filename from a GModule.

module : | a GModule.
Returns : | the filename of the module, or "main" if the module is the main program itself.

g_module_make_resident ()

void        g_module_make_resident          (GModule *module);

Ensures that a module will never be unloaded. Any future g_module_close() calls on the module will be ignored.

module : a GModule to make permanently resident.

g_module_close ()

gboolean    g_module_close                  (GModule *module);

Closes a module.

module : | a GModule to close.
Returns : | TRUE on success.

g_module_error ()

const gchar* g_module_error                 (void);

Gets a string describing the last module error.

Returns : a string describing the last module error.

GModuleCheckInit ()

const gchar* (*GModuleCheckInit)            (GModule *module);

Specifies the type of the module initialization function. If a module contains a function named g_module_check_init() it is called automatically when the module is loaded. It is passed the GModule structure and should return NULL on success or a string describing the initialization error.

module : the GModule corresponding to the module which has just been loaded. Returns : NULL on success, or a string describing the initialization error.

GModuleUnload ()

void        (*GModuleUnload)                (GModule *module);

Specifies the type of the module function called when it is unloaded. If a module contains a function named g_module_unload() it is called automatically when the module is unloaded. It is passed the GModule structure.

module : the GModule about to be unloaded.

G_MODULE_SUFFIX

#define G_MODULE_SUFFIX "so"

Expands to the proper shared library suffix for the current platform without the leading dot. For the most Unices and Linux this is "so", for some HP-UX versions this is "sl" and for Windows this is "dll".

G_MODULE_EXPORT

#define     G_MODULE_EXPORT

Used to declare functions exported by modules.

G_MODULE_IMPORT

#define	G_MODULE_IMPORT		extern

Used to declare functions imported from modules.

Feedback

For additional information or queries on this page send feedback


Error Reporting

Name

Error Reporting — Error Reporting is a system for reporting errors.

Library

glib.lib

Synopsis

#include <glib.h>

GError;
GError*     g_error_new                     (GQuark domain, gint code, const gchar *format, ...);
GError*     g_error_new_literal             (GQuark domain, gint code, const gchar *message);
void        g_error_free                    (GError *error);
GError*     g_error_copy                    (const GError *error);
gboolean    g_error_matches                 (const GError *error, GQuark domain, gint code);
void        g_set_error                     (GError **err, GQuark domain, gint code, const gchar *format, ...);
void        g_propagate_error               (GError **dest, GError *src);
void        g_clear_error                   (GError **err);

Detailed Description

GLib provides a standard method of reporting errors from a called function to the calling code. (This is the same problem solved by exceptions in other languages.) It's important to understand that this method is both a data type (the GError object) and a set of rules. If GError is used incorrectly, then the code will not interoperate properly with other code that uses GError, and users of the API will probably get confused.

First and foremost: GError should only be used to report recoverable runtime errors, never to report programming errors. If the programmer has made mistakes, then use g_warning(), g_return_if_fail(), g_assert(), g_error(), or some similar facility. (Incidentally, remember that the g_error() function should only be used for programming errors, it should not be used to print any error reportable via GError.)

Examples of recoverable runtime errors are "file not found" or "failed to parse input." Examples of programming errors are "NULL passed to strcmp()" or "attempted to free the same pointer twice." These two kinds of errors are fundamentally different: runtime errors should be handled or reported to the user, programming errors should be eliminated by fixing the bug in the program. This is why most functions in GLib and GTK+ do not use the GError facility.

Functions that can fail take a return location for a GError as their last argument. For example:

gboolean g_file_get_contents (const gchar *filename, gchar      **contents, gsize       *length, GError     **error);

If a non-NULL value is passed for the error argument, it should point to a location where an error can be placed. For example:

gchar *contents;
GError *err = NULL;
g_file_get_contents ("foo.txt", &contents, NULL, &err);
g_assert ((contents == NULL && err != NULL) || (contents != NULL && err == NULL));
if (err != NULL)
  {
    /* Report error to user, and free error */
    g_assert (contents == NULL);
    fprintf (stderr, "Unable to read file: %s\n", err->message);
    g_error_free (err);
  }
else
  {
    /* Use file contents */
    g_assert (contents != NULL);
  }

Note that err != NULL in this example is a reliable indicator of whether g_file_get_contents() failed. Additionally, g_file_get_contents() returns a boolean which indicates whether it was successful.

Because g_file_get_contents() returns FALSE on failure, pass NULL for the error argument if there is no need to display the error message but need to know whether it failed.

if (g_file_get_contents ("foo.txt", &contents, NULL, NULL)) /* ignore errors */
  /* no error occurred */ ;
else
  /* error */ ;

The GError object contains three fields: domain indicates the module that the error-reporting function is located in, code indicates the specific error that occurred, and message is a user-readable error message with as many details as possible. Several functions are provided to deal with an error received from a called function: g_error_matches() returns TRUE if the error matches a given domain and code, g_propagate_error() copies an error into an error location (so the calling function will receive it), and g_clear_error() clears an error location by freeing the error and resetting the location to NULL. To display an error to the user, simply display error->message, perhaps along with additional context known only to the calling function (the file being opened, or whatever -- though in the g_file_get_contents() case, error->message already contains a filename).

When implementing a function that can report errors, the basic tool is g_set_error(). Typically, if a fatal error occurs use g_set_error(), then return immediately. g_set_error() does nothing if the error location passed to it is NULL. Here's an example:

gint
foo_open_file (GError **error)
{
  gint fd;

  fd = open ("file.txt", O_RDONLY);

  if (fd < 0)
    {
      g_set_error (error,
                   FOO_ERROR,                 /* error domain */
                   FOO_ERROR_BLAH,            /* error code */
                   "Failed to open file: %s", /* error message format string */
                   g_strerror (errno));
      return -1;
    }
  else
    return fd;
}

Things are somewhat more complicated if the user calls another function that can report a GError. If the sub-function indicates fatal errors in some way other than reporting a GError, such as by returning TRUE on success, do the following:

gboolean
my_function_that_can_fail (GError **err)
{
  g_return_val_if_fail (err == NULL || *err == NULL, FALSE);

  if (!sub_function_that_can_fail (err))
    {
       /* assert that error was set by the sub-function */
       g_assert (err == NULL || *err != NULL);
       return FALSE;
    }

  /* otherwise continue, no error occurred */
  g_assert (err == NULL || *err == NULL);
}

If the sub-function does not indicate errors other than by reporting a GError, a temporary GError should be created since the passed-in one may be NULL. g_propagate_error() is intended for use in this case.

gboolean
my_function_that_can_fail (GError **err)
{
  GError *tmp_error;

  g_return_val_if_fail (err == NULL || *err == NULL, FALSE);

  tmp_error = NULL;
  sub_function_that_can_fail (&tmp_error);

  if (tmp_error != NULL)
    {
       /* store tmp_error in err, if err != NULL,
        * otherwise call g_error_free() on tmp_error
        */
       g_propagate_error (err, tmp_error);
       return FALSE;
    }

  /* otherwise continue, no error occurred */
}

Error pileups are always a bug. For example, this code is incorrect:

gboolean
my_function_that_can_fail (GError **err)
{
  GError *tmp_error;

  g_return_val_if_fail (err == NULL || *err == NULL, FALSE);

  tmp_error = NULL;
  sub_function_that_can_fail (&tmp_error);
  other_function_that_can_fail (&tmp_error);

  if (tmp_error != NULL)
    {
       g_propagate_error (err, tmp_error);
       return FALSE;
    }
}

tmp_error should be checked immediately after sub_function_that_can_fail(), and either cleared or propagated upward. The rule is: after each error, either handle the error, or return it to the calling function. Note that passing NULL for the error location is the equivalent of handling an error by always doing nothing about it. So the following code is fine, assuming errors in sub_function_that_can_fail() are not fatal to my_function_that_can_fail():

gboolean
my_function_that_can_fail (GError **err)
{
  GError *tmp_error;

  g_return_val_if_fail (err == NULL || *err == NULL, FALSE);

  sub_function_that_can_fail (NULL); /* ignore errors */

  tmp_error = NULL;
  other_function_that_can_fail (&tmp_error);

  if (tmp_error != NULL)
    {
       g_propagate_error (err, tmp_error);
       return FALSE;
    }
}

Note that passing NULL for the error location ignores errors; it is equivalent to try { sub_function_that_can_fail(); } catch (...) {} in C++. It does not mean to leave errors unhandled; it means to handle them by doing nothing.

Error domains and codes are conventionally named as follows:

  • The error domain is called <NAMESPACE>_<MODULE>_ERROR, for example G_EXEC_ERROR or G_THREAD_ERROR.

  • The error codes are in an enumeration called <Namespace><Module>Error; for example, GThreadError or GSpawnError.

  • Members of the error code enumeration are called <NAMESPACE>_<MODULE>_ERROR_<CODE>, for example G_SPAWN_ERROR_FORK or G_THREAD_ERROR_AGAIN.

  • If there's a "generic" or "unknown" error code for unrecoverable errors it does not make sense to distinguish with specific codes, it should be called <NAMESPACE>_<MODULE>_ERROR_FAILED, for example G_SPAWN_ERROR_FAILED or G_THREAD_ERROR_FAILED.

Summary of rules for use of GError:

  • Do not report programming errors via GError.

  • The last argument of a function that returns an error should be a location where a GError can be placed (i.e. "GError** error"). If GError is used with varargs, the GError** should be the last argument before the "...".

  • The caller may pass NULL for the GError** if, not interested in details of the exact error that occurred.

  • If NULL is passed for the GError** argument, then errors should not be returned to the caller, but the function should still abort and return if an error occurs. That is, control flow should not be affected by whether the caller wants to get a GError.

  • If a GError is reported, then the function by definition had a fatal failure and did not complete whatever it was supposed to do. If the failure was not fatal, then it was handled and not reported. If it was fatal, then it must be reported and other things in progress must be discontinued.

  • A GError* must be initialized to NULL before passing its address to a function that can report errors.

  • "Piling up" errors is always a bug. That is, if a new GError is assigned to a GError* that is non-NULL, thus overwriting the previous error, it indicates that the opreation was aborted instead of discontinued.If continued, the previous error should be cleared with g_clear_error(). g_set_error() will complain if errors are piled up.

  • By convention, if a boolean value is returned indicating success then TRUE means success and FALSE means failure. If FALSE is returned, the error must be set to a non-NULL value.

  • A NULL return value is also frequently used to mean that an error occurred. It should be clear form the documentation whether NULL is a valid return value in non-error cases; if NULL is a valid value, then users must check whether an error was returned to see if the function succeeded.

  • When implementing a function that can report errors, add a check at the top of the function that the error return location is either NULL or contains a NULL error (e.g. g_return_if_fail (error == NULL || *error == NULL);).

Details

GError

typedef struct {
  GQuark       domain;
  gint         code;
  gchar       *message;
} GError;

The GError structure contains information about an error that has occurred.

GQuark domain; | error domain, e.g. G_FILE_ERROR.
gint code; | error code, e.g. G_FILE_ERROR_NOENT.
gchar *message; | human-readable informative error message.

g_error_new ()

GError*     g_error_new           (GQuark domain, gint code, const gchar *format, ...);

Creates a new GError with the given domain and code, and a message formatted with format.

domain : | error domain
code : | error code
format : | printf()-style format for error message
... : | parameters for message format
Returns : | a new GError

g_error_new_literal ()

GError*     g_error_new_literal   (GQuark domain, gint code, const gchar *message);

Creates a new GError; unlike g_error_new(), message is not a printf()-style format string. Use this function if message contains text over whom there is no control, that could include printf() escape sequences.

domain : | error domain
code : | error code
message : | error message
Returns : | a new GError

g_error_free ()

void        g_error_free          (GError *error);

Frees a GError and associated resources.

error : a GError

g_error_copy ()

GError*     g_error_copy          (const GError *error);

Makes a copy of error.

error : | a GError
Returns : | a new GError

g_error_matches ()

gboolean    g_error_matches      (const GError *error, GQuark domain, gint code);

Returns TRUE if error matches domain and code, FALSE otherwise.

error : | a GError
domain : | an error domain
code : | an error code
Returns : | whether error has domain and code

g_set_error ()

void        g_set_error         (GError **err, GQuark domain, gint code, const gchar *format, ...);

Does nothing if err is NULL; if err is non-NULL, then *err must be NULL. A new GError is created and assigned to *err.

err : | a return location for a GError, or NULL
domain : | error domain
code : | error code
format : | printf()-style format
... : | args for format

g_propagate_error ()

void        g_propagate_error   (GError **dest, GError *src);

If dest is NULL, free src; otherwise, moves src into *dest. *dest must be NULL.

dest : | error return location
src : | error to move into the return location

g_clear_error ()

void        g_clear_error       (GError **err);

If err is NULL, does nothing. If err is non-NULL, calls g_error_free() on *err and sets *err to NULL.

err : GError return location

Feedback

For additional information or queries on this page send feedback


File Utilities

Name

File Utilities — various file-related functions.

Library

glib.lib

Synopsis

#include <glib.h>
#include <glib/gstdio.h>

enum        GFileError;
#define     G_FILE_ERROR
enum        GFileTest;
GFileError  g_file_error_from_errno         (gint err_no);
gboolean    g_file_get_contents             (const gchar *filename, gchar **contents, gsize *length, GError **error);
gboolean    g_file_set_contents             (const gchar *filename, const gchar *contents, gssize length, GError **error);
gboolean    g_file_test                     (const gchar *filename, GFileTest test);
gint        g_mkstemp                       (gchar *tmpl);
gint        g_file_open_tmp                 (const gchar *tmpl, gchar **name_used, GError **error);
gchar*      g_file_read_link                (const gchar *filename, GError **error);
int         g_mkdir_with_parents            (const gchar *pathname, int mode);

GDir;
GDir*       g_dir_open                      (const gchar *path, guint flags, GError **error);
const gchar* g_dir_read_name                (GDir *dir);
void        g_dir_rewind                    (GDir *dir);
void        g_dir_close                     (GDir *dir);

            GMappedFile;
GMappedFile* g_mapped_file_new              (const gchar *filename, gboolean writable, GError **error);
void        g_mapped_file_free              (GMappedFile *file);
gsize       g_mapped_file_get_length        (GMappedFile *file);
gchar*      g_mapped_file_get_contents      (GMappedFile *file);

int         g_open                          (const gchar *filename, int flags, int mode);
int         g_rename                        (const gchar *oldfilename, const gchar *newfilename);
int         g_mkdir                         (const gchar *filename, int mode);
int         g_stat                          (const gchar *filename, struct stat *buf);
int         g_lstat                         (const gchar *filename, struct stat *buf);
int         g_unlink                        (const gchar *filename);
int         g_remove                        (const gchar *filename);
int         g_rmdir                         (const gchar *filename);
FILE*       g_fopen                         (const gchar *filename, const gchar *mode);
FILE*       g_freopen                       (const gchar *filename, const gchar *mode, FILE *stream);
int         g_chmod                         (const gchar *filename, int mode);
int         g_access                        (const gchar *filename, int mode);
int         g_creat                         (const gchar *filename, int mode);
int         g_chdir                         (const gchar *path);

Detailed Description

There is a group of functions which wrap the common POSIX functions dealing with
filenames (g_open(), g_rename(),
g_mkdir(),
g_stat(),
g_unlink(),
g_remove(),
g_fopen(),
g_freopen()).
The point of these wrappers is to make it possible to handle file names with any
Unicode characters in them on Windows without having to use ifdefs and the wide
character API in the application code.

The pathname argument should be in the GLib file name encoding. On POSIX this is the actual on-disk encoding which might correspond to the locale settings of the process (or the G_FILENAME_ENCODING environment variable), or not.

On Windows the GLib file name encoding is UTF-8. Note that the Microsoft C library does not use UTF-8, but has separate APIs for current system code page and wide characters (UTF-16). The GLib wrappers call the wide character API if present (on modern Windows systems), otherwise convert to/from the system code page.

Another group of functions allows to open and read directories in the GLib file
name encoding. These are g_dir_open(),
g_dir_read_name(),
g_dir_rewind(),

g_dir_close().

Details

enum GFileError

typedef enum
{
  G_FILE_ERROR_EXIST, G_FILE_ERROR_ISDIR, G_FILE_ERROR_ACCES, G_FILE_ERROR_NAMETOOLONG, G_FILE_ERROR_NOENT, G_FILE_ERROR_NOTDIR,
  G_FILE_ERROR_NXIO, G_FILE_ERROR_NODEV, G_FILE_ERROR_ROFS, G_FILE_ERROR_TXTBSY, G_FILE_ERROR_FAULT, G_FILE_ERROR_LOOP, G_FILE_ERROR_NOSPC,
  G_FILE_ERROR_NOMEM, G_FILE_ERROR_MFILE, G_FILE_ERROR_NFILE, G_FILE_ERROR_BADF, G_FILE_ERROR_INVAL, G_FILE_ERROR_PIPE, G_FILE_ERROR_AGAIN,
  G_FILE_ERROR_INTR, G_FILE_ERROR_IO, G_FILE_ERROR_PERM, G_FILE_ERROR_NOSYS, G_FILE_ERROR_FAILED
} GFileError;

Values corresponding to errno codes returned from file operations on UNIX. Unlike errno codes, GFileError values are available on all systems, even Windows. The exact meaning of each code depends on what sort of file operation was performed; the UNIX documentation gives more details. The following error code descriptions come from the GNU C Library manual, and are under the copyright of that manual.

It's not very portable to make detailed assumptions about exactly which errors will be returned from a given operation. Some errors don't occur on some systems, etc., sometimes there are subtle differences in when a system will report a given error, etc.

G_FILE_ERROR_EXIST | Operation not permitted; only the owner of the file (or other resource) or processes with special privileges can perform the operation.
G_FILE_ERROR_ISDIR | File is a directory; cannot open a directory for writing, or create or remove hard links to it.
G_FILE_ERROR_ACCES | Permission denied; the file permissions do not allow the attempted operation.
G_FILE_ERROR_NAMETOOLONG | Filename too long.
G_FILE_ERROR_NOENT | No such file or directory. This is a "file doesn't exist" error for ordinary files that are referenced in contexts where they are expected to already exist.
G_FILE_ERROR_NOTDIR | A file that is not a directory was specified when a directory is required.
G_FILE_ERROR_NXIO | No such device or address. The system tried to use the device represented by the specified file , and it could not find the device. This can mean that the device file was installed incorrectly, or that the physical device is missing or not correctly attached to the computer.
G_FILE_ERROR_NODEV | This file is of a type that does not support mapping.
G_FILE_ERROR_ROFS | The directory containing the new link cannot be modified because it is on a read-only file system.
G_FILE_ERROR_TXTBSY | Text file busy.
G_FILE_ERROR_FAULT | Passed in a pointer to bad memory. (GLib will not reliably return this, do not pass in pointers to bad memory.)
G_FILE_ERROR_LOOP | Too many levels of symbolic links were encountered in looking up a file name. This often indicates a cycle of symbolic links.
G_FILE_ERROR_NOSPC | No space left on device; write operation on a file failed because the disk is full.
G_FILE_ERROR_NOMEM | No memory available. The system cannot allocate more virtual memory because its capacity is full.
G_FILE_ERROR_MFILE | The current process has too many files open and cannot open any more. Duplicate descriptors do count toward this limit.
G_FILE_ERROR_NFILE | There are too many distinct file openings in the entire system.
G_FILE_ERROR_BADF | Bad file descriptor; for example, I/O on a descriptor that has been closed or reading from a descriptor open only for writing (or vice versa).
G_FILE_ERROR_INVAL | Invalid argument. This is used to indicate various kinds of problems with passing the wrong argument to a library function.
G_FILE_ERROR_PIPE | Broken pipe; there is no process reading from the other end of a pipe. Every library function that returns this error code also generates a `SIGPIPE' signal; this signal terminates the program if not handled or blocked. Thus, the program will never actually see this code unless it has handled or blocked `SIGPIPE'.
G_FILE_ERROR_AGAIN | Resource temporarily unavailable; the call might work if tried again later.
G_FILE_ERROR_INTR | Interrupted function call; an asynchronous signal occurred and prevented completion of the call. When this happens, try the call again.
G_FILE_ERROR_IO | Input/output error; usually used for physical read or write errors. i.e. the disk or other physical device hardware is returning errors.
G_FILE_ERROR_PERM | Operation not permitted; only the owner of the file (or other resource) or processes with special privileges can perform the operation.
G_FILE_ERROR_NOSYS | Function not implemented; this indicates that the system is missing some functionality.
G_FILE_ERROR_FAILED | Does not correspond to a UNIX error code; this is the standard "failed for unspecified reason" error code present in all GError error code enumerations. Returned if no specific code applies.

G_FILE_ERROR

#define G_FILE_ERROR g_file_error_quark ()

Error domain for file operations. Errors in this domain will be from the GFileError enumeration. See GError for information on error domains.

enum GFileTest

typedef enum
{
  G_FILE_TEST_IS_REGULAR    = 1 << 0,
  G_FILE_TEST_IS_SYMLINK    = 1 << 1,
  G_FILE_TEST_IS_DIR        = 1 << 2,
  G_FILE_TEST_IS_EXECUTABLE = 1 << 3,
  G_FILE_TEST_EXISTS        = 1 << 4
} GFileTest;

A test to perform on a file using g_file_test().

G_FILE_TEST_IS_REGULAR | TRUE if the file is a regular file (not a symlink or directory)
G_FILE_TEST_IS_SYMLINK | TRUE if the file is a symlink.
G_FILE_TEST_IS_DIR | TRUE if the file is a directory.
G_FILE_TEST_IS_EXECUTABLE | TRUE if the file is executable.
G_FILE_TEST_EXISTS | TRUE if the file exists. It may or may not be a regular file.

g_file_error_from_errno ()

GFileError  g_file_error_from_errno         (gint err_no);

Gets a GFileError constant based on the passed-in errno. For example, if EEXIST is passed-in this function returns G_FILE_ERROR_EXIST. Unlike errno values, portably assume that all GFileError values will exist.

Normally a GFileError value goes into a GError returned from a function that manipulates files. Use g_file_error_from_errno() when constructing a GError.

err_no : | an "errno" value
Returns : | GFileError corresponding to the given errno

g_file_get_contents ()

gboolean    g_file_get_contents             (const gchar *filename, gchar **contents, gsize *length, GError **error);

Reads an entire file into allocated memory, with good error checking.

If the call was successful, it returns TRUE and sets contents to the file contents and length to the length of the file contents in bytes. The string stored in contents will be null-terminated, so for text files pass NULL for the length argument. If the call was not successful, it returns FALSE and sets error. The error domain is G_FILE_ERROR. Possible error codes are those in the GFileError enumeration. In the error case, contents is set to NULL and length is set to zero.

filename : | name of a file to read contents from, in the GLib file name encoding
contents : | location to store an allocated string
length : | location to store length in bytes of the contents, or NULL
error : | return location for a GError, or NULL
Returns : | TRUE on success, FALSE if an error occurred

g_file_set_contents ()

gboolean    g_file_set_contents        (const gchar *filename, const gchar *contents, gssize length, GError **error);

Writes all of contents to a file named filename, with good error checking. If a file called filename already exists it will be overwritten.

This write is atomic in the sense that it is first written to a temporary file which is then renamed to the final name. Notes:

  • On Unix, if filename already exists hard links to filename will break. Also since the file is recreated, existing permissions, access control lists, metadata etc. may be lost. If filename is a symbolic link, the link itself will be replaced, not the linked file.
  • On Windows renaming a file will not remove an existing file with the new name, so on Windows there is a race condition between the existing file being removed and the temporary file being renamed.
  • On Windows there is no way to remove a file that is open to some process, or mapped into memory. Thus, this function will fail if filename already exists and is open.

If the call was successful, it returns TRUE. If the call was not successful, it returns FALSE and sets error. The error domain is G_FILE_ERROR. Possible error codes are those in the GFileError enumeration.

filename : | name of a file to write contents to, in the GLib file name encoding
contents : | string to write to the file
length : | length of contents, or -1 if contents is a nul-terminated string
error : | return location for a GError, or NULL
Returns : | TRUE on success, FALSE if an error occurred

g_file_test ()

gboolean    g_file_test         (const gchar *filename, GFileTest test);

Returns TRUE if any of the tests in the bitfield test are TRUE. For example, (G_FILE_TEST_EXISTS | G_FILE_TEST_IS_DIR) will return TRUE if the file exists; the check whether it is a directory does not matter since the existence test is TRUE. With the current set of available tests, there is no point passing in more than one test at a time.

Apart from G_FILE_TEST_IS_SYMLINK all tests follow symbolic links, so for a symbolic link to a regular file g_file_test() will return TRUE for both G_FILE_TEST_IS_SYMLINK and G_FILE_TEST_IS_REGULAR.

Note, that for a dangling symbolic link g_file_test() will return TRUE for G_FILE_TEST_IS_SYMLINK and FALSE for all other flags.

Never use g_file_test() to test whether it is safe to perform an operation, because there is always the possibility of the condition changing before the actual operation is perfromed. For example,the use of G_FILE_TEST_IS_SYMLINK to know whether it is is safe to write to a file without being tricked into writing into a different location. It does not work.

/* DON'T DO THIS */
 if (!g_file_test (filename, G_FILE_TEST_IS_SYMLINK)) {
   fd = g_open (filename, O_WRONLY);
   /* write to fd */
 }

Another thing to note is that G_FILE_TEST_EXISTS and G_FILE_TEST_IS_EXECUTABLE are implemented using the access() system call. This usually does not matter, but if the program is setuid or setgid it means that these tests will give the answer for the real user ID and group ID, rather than the effective user ID and group ID.

On Windows, there are no symlinks, so testing for G_FILE_TEST_IS_SYMLINK will always return FALSE. Testing for G_FILE_TEST_IS_EXECUTABLE will just check that the file exists and its name indicates that it is executable, checking for well-known extensions and those listed in the PATHEXT environment variable.

filename : | a filename to test in the GLib file name encoding
test : | bitfield of GFileTest flags
Returns : | whether a test was TRUE

g_mkstemp ()

gint        g_mkstemp            (gchar *tmpl);

Opens a temporary file. See the mkstemp() documentation on most UNIX-like systems. This is a portability wrapper, which simply calls mkstemp() on systems that have it, and implements it in GLib otherwise.

The parameter is a string that should match the rules for mkstemp(), i.e. end in "XXXXXX". The X string will be modified to form the name of a file that did not exist. The string should be in the GLib file name encoding. Most importantly, on Windows it should be in UTF-8.

tmpl : | template filename
Returns : | A file handle (as from open()) to the file opened for reading and writing. The file is opened in binary mode on platforms where there is a difference. The file handle should be closed with close(). In case of errors, -1 is returned.

g_file_open_tmp ()

gint        g_file_open_tmp             (const gchar *tmpl, gchar **name_used, GError **error);

Opens a file for writing in the preferred directory for temporary files (as returned by g_get_tmp_dir()).

tmpl should be a string in the GLib file name encoding ending with six 'X' characters, as the parameter to g_mkstemp() (or mkstemp()). However, unlike these functions, the template should only be a basename, no directory components are allowed. If template is NULL, a default template is used.

Note that in contrast to g_mkstemp() (and mkstemp()) tmpl is not modified, and might thus be a read-only literal string.

The actual name used is returned in name_used if non-NULL. This string should be freed with g_free() when not needed any longer. The returned name is in the GLib file name encoding.

tmpl : | Template for file name, as in g_mkstemp(), basename only
name_used : | location to store actual name used
error : | return location for a GError
Returns : | A file handle (as from open()) to the file opened for reading and writing. The file is opened in binary mode on platforms where there is a difference. The file handle should be closed with close(). In case of errors, -1 is returned and error will be set.

g_file_read_link ()

gchar*      g_file_read_link                (const gchar *filename, GError **error);

Reads the contents of the symbolic link filename like the POSIX readlink() function. The returned string is in the encoding used for filenames. Use g_filename_to_utf8() to convert it to UTF-8.

filename : | the symbolic link
error : | return location for a GError
Returns : | A newly allocated string with the contents of the symbolic link, or NULL if an error occurred.

g_mkdir_with_parents ()

int         g_mkdir_with_parents            (const gchar *pathname, int mode);

Create a directory if it does not already exist. Create intermediate parent directories as needed, too.

pathname : | a pathname in the GLib file name encoding
mode : | permissions to use for newly created directories
Returns : | 0 if the directory already exists, or was successfully created. Returns -1 if an error occurred, with errno set.

GDir

typedef struct _GDir GDir;

An opaque structure representing an opened directory.

g_dir_open ()

GDir*       g_dir_open            (const gchar *path, guint flags, GError **error);

Opens a directory for reading. The names of the files in the directory can then be retrieved using g_dir_read_name().

path : | the path to the directory interested in. On Unix in the on-disk encoding. On Windows in UTF-8
flags : | Currently must be set to 0. Reserved for future use.
error : | return location for a GError, or NULL. If non-NULL , an error will be set if and only if g_dir_open() fails.
Returns : | a newly allocated GDir on success, NULL on failure. If non-NULL, free the result with g_dir_close() when finished with it.

g_dir_read_name ()

const gchar* g_dir_read_name         (GDir *dir);

Retrieves the name of the next entry in the directory. The '.' and '..' entries are omitted. On Windows, the returned name is in UTF-8. On Unix, it is in the on-disk encoding.

dir : | a GDir* created by g_dir_open()
Returns : | The entry's name or NULL if there are no more entries. The return value is owned by GLib and must not be modified or freed.

g_dir_rewind ()

void        g_dir_rewind                    (GDir *dir);

Resets the given directory. The next call to g_dir_read_name() will return the first entry again.

dir : a GDir* created by g_dir_open()

g_dir_close ()

void        g_dir_close                     (GDir *dir);

Closes the directory and deallocates all related resources.

dir : a GDir* created by g_dir_open()

GMappedFile

typedef struct _GMappedFile GMappedFile;

The GMappedFile represents a file mapping created with g_mapped_file_new(). It has only private members and should not be accessed directly.

g_mapped_file_new ()

GMappedFile* g_mapped_file_new              (const gchar *filename, gboolean writable, GError **error);

Maps a file into memory. On UNIX, this is using the mmap() function.

If writable is TRUE, the mapped buffer may be modified, otherwise it is an error to modify the mapped buffer. Modifications to the buffer are not visible to other processes mapping the same file, and are not written back to the file.

Note that modifications of the underlying file might affect the contents of the GMappedFile. Therefore, mapping should only be used if the file will not be modified, or if all modifications of the file are done atomically (e.g. using g_file_set_contents()).

filename : | The path of the file to load, in the GLib filename encoding
writable : | wether the mapping should be writable
error : | return location for a GError, or NULL
Returns : | a newly allocated GMappedFile which must be freed with g_mapped_file_free(), or NULL if the mapping failed.

g_mapped_file_free ()

void        g_mapped_file_free              (GMappedFile *file);

Unmaps the buffer of file and frees it.

file : a GMappedFile

g_mapped_file_get_length ()

gsize       g_mapped_file_get_length        (GMappedFile *file);

Returns the length of the contents of a GMappedFile.

file : | a GMappedFile
Returns : | the length of the contents of file.

g_mapped_file_get_contents ()

gchar*      g_mapped_file_get_contents      (GMappedFile *file);

Returns the contents of a GMappedFile.

Note that the contents may not be zero-terminated, even if the GMappedFile is backed by a text file.

file : | a GMappedFile
Returns : | the contents of file.

g_open ()

int         g_open            (const gchar *filename, int flags, int mode);

A wrapper for the POSIX open() function. The open() function is used to convert a pathname into a file descriptor. Note that on POSIX systems file descriptors are implemented by the operating system. On Windows, it is the C library that implements open() and file descriptors. The actual Windows API for opening files is something different.

See the C library manual for more details about open().

filename : | a pathname in the GLib file name encoding (UTF-8 on Windows)
flags : | as in open()
mode : | as in open()
Returns : | a new file descriptor, or -1 if an error occurred. The return value can be used exactly like the return value from open().

g_rename ()

int         g_rename             (const gchar *oldfilename, const gchar *newfilename);

A wrapper for the POSIX rename() function. The rename() function renames a file, moving it between directories if required.

See the C library manual for more details about how rename() . Note in particular that on Win9x it is not possible to rename a file if a file with the new name already exists. Also it is not possible in general on Windows to rename an open file.

oldfilename : | a pathname in the GLib file name encoding (UTF-8 on Windows)
newfilename : | a pathname in the GLib file name encoding
Returns : | 0 if the renaming succeeded, -1 if an error occurred

g_mkdir ()

int         g_mkdir               (const gchar *filename, int mode);

A wrapper for the POSIX mkdir() function. The mkdir() function attempts to create a directory with the given name and permissions.

See the C library manual for more details about mkdir().

filename : | a pathname in the GLib file name encoding (UTF-8 on Windows)
mode : | permissions to use for the newly created directory
Returns : | 0 if the directory was successfully created, -1 if an error occurred

g_stat ()

int         g_stat              (const gchar *filename, struct stat *buf);

A wrapper for the POSIX stat() function. The stat() function returns information about a file.

See the C library manual for more details about stat().

filename : | a pathname in the GLib file name encoding (UTF-8 on Windows)
buf : | a pointer to a stat struct, which will be filled with the file information
Returns : | 0 if the information was successfully retrieved, -1 if an error occurred

g_lstat ()

int         g_lstat          (const gchar *filename, struct stat *buf);

A wrapper for the POSIX lstat() function. The lstat() function is like stat() except that in the case of symbolic links, it returns information about the symbolic link itself and not the file that it refers to. If the system does not support symbolic links g_lstat() is identical to g_stat().

See the C library manual for more details about lstat().

filename : | a pathname in the GLib file name encoding (UTF-8 on Windows)
buf : | a pointer to a stat struct, which will be filled with the file information
Returns : | 0 if the information was successfully retrieved, -1 if an error occurred

g_unlink ()

int         g_unlink               (const gchar *filename);

A wrapper for the POSIX unlink() function. The unlink() function deletes a name from the filesystem. If this was the last link to the file and no processes have it opened, the diskspace occupied by the file is freed.

See the C library manual for more details about unlink(). Note that on Windows, it is in general not possible to delete files that are open to some process, or mapped into memory.

filename : | a pathname in the GLib file name encoding (UTF-8 on Windows)
Returns : | 0 if the name was successfully deleted, -1 if an error occurred

g_remove ()

int         g_remove               (const gchar *filename);

A wrapper for the POSIX remove() function. The remove() function deletes a name from the filesystem.

See the C library manual for more details about remove(). On Unix, remove() removes also directories, as it calls unlink() for files and rmdir() for directories. On Windows, although remove() in the C library only works for files, this function tries first remove() and then if that fails rmdir(), and thus works for both files and directories. Note however, that on Windows, it is in general not possible to remove a file that is open to some process, or mapped into memory.

If this function fails on Windows not much can be infered from the errno value. rmdir() is tried regardless of what caused remove() to fail. Any errno value set by remove() will be overwritten by that set by rmdir().

filename : | a pathname in the GLib file name encoding (UTF-8 on Windows)
Returns : | 0 if the file was successfully removed, -1 if an error occurred

g_rmdir ()

int         g_rmdir               (const gchar *filename);

A wrapper for the POSIX rmdir() function. The rmdir() function deletes a directory from the filesystem.

See the C library manual for more details about rmdir().

filename : | a pathname in the GLib file name encoding (UTF-8 on Windows)
Returns : | 0 if the directory was successfully removed, -1 if an error occurred

g_fopen ()

FILE*       g_fopen               (const gchar *filename, const gchar *mode);

A wrapper for the POSIX fopen() function. The fopen() function opens a file and associates a new stream with it.

See the C library manual for more details about fopen().

filename : | a pathname in the GLib file name encoding (UTF-8 on Windows)
mode : | a string describing the mode in which the file should be opened
Returns : | A FILE pointer if the file was successfully opened, or NULL if an error occurred

g_freopen ()

FILE*       g_freopen            (const gchar *filename, const gchar *mode, FILE *stream);

A wrapper for the POSIX freopen() function. The freopen() function opens a file and associates it with an existing stream.

See the C library manual for more details about freopen().

filename : | a pathname in the GLib file name encoding (UTF-8 on Windows)
mode : | a string describing the mode in which the file should be opened
stream : | an existing stream which will be reused, or NULL
Returns : | A FILE pointer if the file was successfully opened, or NULL if an error occurred.

g_chmod ()

int         g_chmod             (const gchar *filename, int mode);

A wrapper for the POSIX chmod() function. The chmod() function is used to set the permissions of a file system object. Note that on Windows the file protection mechanism is not at all POSIX-like, and the underlying chmod() function in the C library just sets or clears the READONLY attribute. It does not touch any ACL. Software that needs to manage file permissions on Windows exactly should use the Win32 API.

See the C library manual for more details about chmod().

filename : | a pathname in the GLib file name encoding (UTF-8 on Windows)
mode : | as in chmod()
Returns : | zero if the operation succeeded, -1 on error.

g_access ()

int         g_access            (const gchar *filename, int mode);

A wrapper for the POSIX access() function. This function is used to test a pathname for one or several of read, write or execute permissions, or just existence. On Windows, the underlying access() function in the C library only checks the READONLY attribute, and does not look at the ACL at all. Software that needs to handle file permissions on Windows more exactly should use the Win32 API.

See the C library manual for more details about access().

filename : | a pathname in the GLib file name encoding (UTF-8 on Windows)
mode : | as in access()
Returns : | zero if the pathname refers to an existing file system object that has all the tested permissions, or -1 otherwise or on error.

g_creat ()

int         g_creat               (const gchar *filename, int mode);

A wrapper for the POSIX creat() function. The creat() function is used to convert a pathname into a file descriptor, creating a file if necessar. Note that on POSIX systems file descriptors are implemented by the operating system. On Windows, it is the C library that implements creat() and file descriptors. The actual Windows API for opening files is something different.

See the C library manual for more details about creat().

filename : | a pathname in the GLib file name encoding (UTF-8 on Windows)
mode : | as in creat()
Returns : | a new file descriptor, or -1 if an error occurred. The return value can be used exactly like the return value from creat().

g_chdir ()

int         g_chdir             (const gchar *path);

A wrapper for the POSIX chdir() function. The function changes the current directory of the process to path.

See the C library manual for more details about chdir().

path : | a pathname in the GLib file name encoding (UTF-8 on Windows)
Returns : | 0 on success, -1 if an error occurred.

Feedback

For additional information or queries on this page send feedback


glib-genmarshal

Name

glib-genmarshal — C code marshaller generation utility for GLib closures.

Library

gobject.lib

Synopsis

glib-genmarshal [options...] [files...]

Detailed Description

glib-genmarshal is a small utility that generates C code marshallers for callback functions of the GClosure mechanism in the GObject sublibrary of GLib. The marshaller functions have a standard signature, they get passed in the invoking closure, an array of value structures holding the callback function parameters and a value structure for the return value of the callback. The marshaller is then responsible to call the respective C code function of the closure with all the parameters on the stack and to collect its return value.

Invocation

glib-genmarshal takes a list of marshallers to generate as input. The marshaller list is either read from standard input or from files passed as additional arguments on the command line.

Options

--header | Generate header file contents of the marshallers.
--body | Generate C code file contents of the marshallers.
--prefix=string, --prefix string | Specify marshaller prefix. The default prefix is `g_cclosure_marshal'.
--skip-source | Skip source location remarks in generated comments.
--nostdinc | Do not use the standard marshallers of the GObject library, and skip gmarshal.h include directive in generated header files.
--g-fatal-warnings | Make warnings fatal, that is, exit immediately once a warning occurs.
-h, --help | Print brief help and exit.
-v, --version | Print version and exit.

Marshaller list format

The marshaller lists are processed line by line, a line can contain a comment in the form of

# this is a comment

or a marshaller specification of the form

RTYPE:PTYPE
RTYPE:PTYPE,PTYPE
RTYPE:PTYPE,PTYPE,PTYPE

(up to 16 PTYPEs may be present).

The RTYPE part specifies the callback's return type and the PTYPEs right to the colon specify the callback's parameter list, except for the first and the last arguments which are always pointers.

Parameter types

Currently, the following types are supported:

VOID | indicates no return type, or no extra parameters. If VOID is used as the parameter list, no additional parameters may be present.
BOOLEAN | for boolean types (gboolean)
CHAR | for signed char types (gchar)
UCHAR | for unsigned char types (guchar)
INT | for signed integer types (gint)
UINT | for unsigned integer types (guint)
LONG | for signed long integer types (glong)
ULONG | for unsigned long integer types (gulong)
INT64 | for signed 64bit integer types (gint64)
UINT64 | for unsigned 64bit integer types (guint64)
ENUM | for enumeration types (gint)
FLAGS | for flag enumeration types (guint)
FLOAT | for single-precision float types (gfloat)
DOUBLE | for double-precision float types (gdouble)
STRING | for string types (gchar*)
BOXED | for boxed (anonymous but reference counted) types (GBoxed*)
PARAM | for GParamSpec or derived types (GParamSpec*)
POINTER | for anonymous pointer types (gpointer)
OBJECT | for GObject or derived types (GObject*)
NONE | deprecated alias for VOID
BOOL | deprecated alias for BOOLEAN

Examples

To generate marshallers for the following callback functions:

void   foo (gpointer data1, gpointer data2);
void   bar (gpointer data1, gint  param1, gpointer data2);
gfloat baz (gpointer data1, gboolean param1, guchar param2, gpointer data2);

The marshaller list has to look like this:

VOID:VOID
VOID:INT
FLOAT:BOOLEAN,UCHAR

The generated marshallers have the arguments
encoded in their function name. For this particular list, they are

g_cclosure_marshal_VOID__VOID(),
g_cclosure_marshal_VOID__INT(),
g_cclosure_marshal_FLOAT__BOOLEAN_UCHAR().

They can be used directly for GClosures or be
passed in as the GSignalCMarshaller c_marshaller; argument upon creation of
signals:

GClosure *cc_foo, *cc_bar, *cc_baz;

cc_foo = g_cclosure_new (NULL, foo, NULL);
g_closure_set_marshal (cc_foo, g_cclosure_marshal_VOID__VOID);
cc_bar = g_cclosure_new (NULL, bar, NULL);
g_closure_set_marshal (cc_bar, g_cclosure_marshal_VOID__INT);
cc_baz = g_cclosure_new (NULL, baz, NULL);
g_closure_set_marshal (cc_baz, g_cclosure_marshal_FLOAT__BOOLEAN_UCHAR);

Bugs

None known yet.

Author

glib-genmarshal has been written by Tim Janik <timj@gtk.org>.

This manual page was provided by Tim Janik <timj@gtk.org>.

See also

glib-mkenums()

Feedback

For additional information or queries on this page send feedback


Glob-style pattern matching

Name

Glob-style pattern matching — matches strings against patterns containing '*' (wildcard) and '?' (joker).

Library

glib.lib

Synopsis

#include <glib.h>

GPatternSpec;
GPatternSpec* g_pattern_spec_new              (const gchar *pattern);
void          g_pattern_spec_free             (GPatternSpec *pspec);
gboolean      g_pattern_spec_equal            (GPatternSpec *pspec1, GPatternSpec *pspec2);
gboolean      g_pattern_match                 (GPatternSpec *pspec, guint string_length, const gchar *string,
                                               const gchar *string_reversed);
gboolean      g_pattern_match_string          (GPatternSpec *pspec, const gchar *string);
gboolean      g_pattern_match_simple          (const gchar *pattern, const gchar *string);

Detailed Description

The g_pattern_match* functions match a string against a pattern containing '*' and '?' wildcards with similar semantics as the standard glob() function: '*' matches an arbitrary, possibly empty, string, '?' matches an arbitrary character.

Note that in contrast to glob(), the '/' character can be matched by the wildcards, there are no '[...]' character ranges and '*' and '?' can not be escaped to include them literally in a pattern.

When multiple strings must be matched against the same pattern, it is better to compile the pattern to a GPatternSpec using g_pattern_spec_new() and use g_pattern_match_string() instead of g_pattern_match_simple(). This avoids the overhead of repeated pattern compilation.

Details

GPatternSpec

typedef struct _GPatternSpec GPatternSpec;

A GPatternSpec is the 'compiled' form of a pattern. This structure is opaque and its fields cannot be accessed directly.

g_pattern_spec_new ()

GPatternSpec* g_pattern_spec_new         (const gchar *pattern);

Compiles a pattern to a GPatternSpec.

pattern : | a zero-terminated UTF-8 encoded string.
Returns : | a newly-allocated GPatternSpec.

g_pattern_spec_free ()

void        g_pattern_spec_free        (GPatternSpec *pspec);

Frees the memory allocated for the GPatternSpec.

pspec : a GPatternSpec.

g_pattern_spec_equal ()

gboolean    g_pattern_spec_equal      (GPatternSpec *pspec1, GPatternSpec *pspec2);

Compares two compiled pattern specs and returns whether they will match the same set of strings.

pspec1 : | a GPatternSpec.
pspec2 : | another GPatternSpec.
Returns : | Whether the compiled patterns are equal.

g_pattern_match ()

gboolean    g_pattern_match          (GPatternSpec *pspec, guint string_length, const gchar *string, const gchar *string_reversed);

Matches a string against a compiled pattern. Passing the correct length of the string given is mandatory. The reversed string can be omitted by passing NULL, this is more efficient if the reversed version of the string to be matched is not at hand, as g_pattern_match() will only construct it if the compiled pattern requires reverse matches.

Note that, if the user code will (possibly) match a string against a multitude of patterns containing wildcards, chances are high that some patterns will require a reversed string. In this case, it's more efficient to provide the reversed string to avoid multiple constructions thereof in the various calls to g_pattern_match().

Note also that the reverse of a UTF-8 encoded string can in general not be obtained by g_strreverse(). This works only if the string doesn't contain any multibyte characters. Glib offers the g_utf_strreverse() function to reverse UTF-8 encoded strings.

pspec : | a GPatternSpec.
string_length : | the length of string.
string : | the UTF-8 encoded string to match.
string_reversed : | the reverse of string or NULL.
Returns : | TRUE if string matches pspec.

g_pattern_match_string ()

gboolean    g_pattern_match_string          (GPatternSpec *pspec, const gchar *string);

Matches a string against a compiled pattern. If the string is to be matched against more than one pattern, consider using g_pattern_match() instead while supplying the reversed string.

pspec : | a GPatternSpec.
string : | the UTF-8 encoded string to match.
Returns : | TRUE if string matches pspec.

g_pattern_match_simple ()

gboolean    g_pattern_match_simple          (const gchar *pattern, const gchar *string);

Matches a string against a pattern given as a string. If this function is to be called in a loop, it's more efficient to compile the pattern once with g_pattern_spec_new() and call g_pattern_match_string() repetitively.

pattern : | the UTF-8 encoded pattern.
string : | the UTF-8 encoded string to match.
Returns : | TRUE if string matches pspec.

Feedback

For additional information or queries on this page send feedback


Hash Tables

Name

Hash Tables — Hash Tables associations between keys and values so that given a key the value can be found quickly.

Library

glib.lib

Synopsis

#include <glib.h>

GHashTable;
GHashTable* g_hash_table_new                (GHashFunc hash_func, GEqualFunc key_equal_func);
GHashTable* g_hash_table_new_full           (GHashFunc hash_func, GEqualFunc key_equal_func,
                                             GDestroyNotify key_destroy_func, GDestroyNotify value_destroy_func);
guint       (*GHashFunc)                    (gconstpointer key);
gboolean    (*GEqualFunc)                   (gconstpointer a, gconstpointer b);
void        g_hash_table_insert             (GHashTable *hash_table, gpointer key, gpointer value);
void        g_hash_table_replace            (GHashTable *hash_table, gpointer key, gpointer value);
guint       g_hash_table_size               (GHashTable *hash_table);
gpointer    g_hash_table_lookup             (GHashTable *hash_table, gconstpointer key);
gboolean    g_hash_table_lookup_extended    (GHashTable *hash_table, gconstpointer lookup_key, gpointer *orig_key,
                                             gpointer *value);
void        g_hash_table_foreach            (GHashTable *hash_table, GHFunc func, gpointer user_data);
gpointer    g_hash_table_find               (GHashTable *hash_table, GHRFunc predicate, gpointer user_data);

void        (*GHFunc)                       (gpointer key, gpointer value, gpointer user_data);
gboolean    g_hash_table_remove             (GHashTable *hash_table, gconstpointer key);
gboolean    g_hash_table_steal              (GHashTable *hash_table, gconstpointer key);
guint       g_hash_table_foreach_remove     (GHashTable *hash_table, GHRFunc func, gpointer user_data);
guint       g_hash_table_foreach_steal      (GHashTable *hash_table, GHRFunc func, gpointer user_data);
gboolean    (*GHRFunc)                      (gpointer key, gpointer value, gpointer user_data);
#define     g_hash_table_freeze             (hash_table)
#define     g_hash_table_thaw               (hash_table)
void        g_hash_table_destroy            (GHashTable *hash_table);
GHashTable* g_hash_table_ref                (GHashTable *hash_table);
void        g_hash_table_unref              (GHashTable *hash_table);

gboolean    g_direct_equal                  (gconstpointer v1, gconstpointer v2);
guint       g_direct_hash                   (gconstpointer v);
gboolean    g_int_equal                     (gconstpointer v1, gconstpointer v2);
guint       g_int_hash                      (gconstpointer v);
gboolean    g_str_equal                     (gconstpointer v1, gconstpointer v2);
guint       g_str_hash                      (gconstpointer v);

Detailed Description

A GHashTable provides associations between keys and values which is optimized so that given a key, the associated value can be found very quickly.

Note that neither keys nor values are copied when inserted into the GHashTable, so they must exist for the lifetime of the GHashTable. This means that the use of static strings is OK, but temporary strings (i.e. those created in buffers and those returned by GTK+ widgets) should be copied with g_strdup() before being inserted.

If keys or values are dynamically allocated, be careful to ensure that they are freed when they are removed from the GHashTable, and also when they are overwritten by new insertions into the GHashTable. It is also not advisable to mix static strings and dynamically-allocated strings in a GHashTable, because it then becomes difficult to determine whether the string should be freed.

To create a GHashTable, use g_hash_table_new().

To insert a key and value into a GHashTable, use g_hash_table_insert().

To lookup a value corresponding to a given key, use g_hash_table_lookup() and g_hash_table_lookup_extended().

To remove a key and value, use g_hash_table_remove().

To call a function for each key and value pair use g_hash_table_foreach().

To destroy a GHashTable use g_hash_table_destroy().

Details

GHashTable

typedef struct _GHashTable GHashTable;

The GHashTable struct is an opaque data structure to represent a Hash Table. It should only be accessed via the following functions.

g_hash_table_new ()

GHashTable* g_hash_table_new                (GHashFunc hash_func, GEqualFunc key_equal_func);

Creates a new GHashTable.

hash_func : | a function to create a hash value from a key. Hash values are used to determine where keys are stored within the GHashTable data structure. The g_direct_hash(), g_int_hash() and g_str_hash() functions are provided for some common types of keys. If hash_func is NULL, g_direct_hash() is used.
key_equal_func : | a function to check two keys for equality. This is used when looking up keys in the GHashTable. The g_direct_equal(), g_int_equal() and g_str_equal() functions are provided for the most common types of keys. If key_equal_func is NULL, keys are compared directly in a similar fashion to g_direct_equal(), but without the overhead of a function call.
Returns : | a new GHashTable.

g_hash_table_new_full ()

GHashTable* g_hash_table_new_full          (GHashFunc hash_func, GEqualFunc key_equal_func, GDestroyNotify key_destroy_func,
                                            GDestroyNotify value_destroy_func);

Creates a new GHashTable like g_hash_table_new() with a reference count of 1 and allows to specify functions to free the memory allocated for the key and value that get called when removing the entry from the GHashTable.

hash_func : | a function to create a hash value from a key.
key_equal_func : | a function to check two keys for equality.
key_destroy_func : | a function to free the memory allocated for the key used when removing the entry from the GHashTable or NULL if there is no need to supply such a function.
value_destroy_func : | a function to free the memory allocated for the value used when removing the entry from the GHashTable or NULL if there is no need to supply such a function.
Returns : | a new GHashTable.

GHashFunc ()

guint       (*GHashFunc)          (gconstpointer key);

Specifies the type of the hash function which is passed to g_hash_table_new() when a GHashTable is created.

The function is passed a key and should return a guint hash value. The functions g_direct_hash(), g_int_hash() and g_str_hash() provide hash functions which can be used when the key is a gpointer, gint, and gchar* respectively.

FIXME: Need more here. The hash values should be evenly distributed over a fairly large range? The modulus is taken with the hash table size (a prime number) to find the 'bucket' to place each key into. The function should also be very fast, since it is called for each key lookup.

key : | a key.
Returns : | the hash value corresponding to the key.

GEqualFunc ()

gboolean    (*GEqualFunc)                (gconstpointer a, gconstpointer b);

Specifies the type of a function used to test two values for equality. The function should return TRUE if both values are equal and FALSE otherwise.

a : | a value.
b : | a value to compare with.
Returns : | TRUE if a = b; FALSE otherwise.

g_hash_table_insert ()

void        g_hash_table_insert         (GHashTable *hash_table, gpointer key, gpointer value);

Inserts a new key and value into a GHashTable.

If the key already exists in the GHashTable its current value is replaced with the new value. If supplied a value_destroy_func when creating the GHashTable, the old value is freed using that function. If supplied a key_destroy_func when creating the GHashTable, the passed key is freed using that function.

hash_table : | a GHashTable.
key : | a key to insert.
value : | the value to associate with the key.

g_hash_table_replace ()

void        g_hash_table_replace            (GHashTable *hash_table, gpointer key, gpointer value);

Inserts a new key and value into a GHashTable similar to g_hash_table_insert(). The difference is that if the key already exists in the GHashTable, it gets replaced by the new key. If supplied a value_destroy_func when creating the GHashTable, the old value is freed using that function. If supplied a key_destroy_func when creating the GHashTable, the old key is freed using that function.

hash_table : | a GHashTable.
key : | a key to insert.
value : | the value to associate with the key.

g_hash_table_size ()

guint       g_hash_table_size               (GHashTable *hash_table);

Returns the number of elements contained in the GHashTable.

hash_table : | a GHashTable.
Returns : | the number of key/value pairs in the GHashTable.

g_hash_table_lookup ()

gpointer    g_hash_table_lookup             (GHashTable *hash_table, gconstpointer key);

Looks up a key in a GHashTable. Note that this function cannot distinguish between a key that is not present and one which is present and has the value NULL. If this distinction is needed, use g_hash_table_lookup_extended().

hash_table : | a GHashTable.
key : | the key to look up.
Returns : | the associated value, or NULL if the key is not found.

g_hash_table_lookup_extended ()

gboolean    g_hash_table_lookup_extended       (GHashTable *hash_table, gconstpointer lookup_key, gpointer *orig_key, gpointer *value);

Looks up a key in the GHashTable, returning the original key and the associated value and a gboolean which is TRUE if the key was found. This is useful if the memory allocated for the original key needs to be freed, for example before calling g_hash_table_remove().

hash_table : | a GHashTable.
lookup_key : | the key to look up.
orig_key : | returns the original key.
value : | returns the value associated with the key.
Returns : | TRUE if the key was found in the GHashTable.

g_hash_table_foreach ()

void        g_hash_table_foreach        (GHashTable *hash_table, GHFunc func, gpointer user_data);

Calls the given function for each of the key/value pairs in the GHashTable. The function is passed the key and value of each pair, and the given user_data parameter. The hash table may not be modified while iterating over it (cannot add/remove items). To remove all items matching a predicate, use g_hash_table_foreach_remove().

hash_table : | a GHashTable.
func : | the function to call for each key/value pair.
user_data : | user data to pass to the function.

g_hash_table_find ()

gpointer    g_hash_table_find          (GHashTable *hash_table, GHRFunc predicate, gpointer user_data);

Calls the given function for key/value pairs in the GHashTable until predicate returns TRUE. The function is passed the key and value of each pair, and the given user_data parameter. The hash table may not be modified while iterating over it (cannot add/remove items).

hash_table : | a GHashTable.
predicate : | function to test the key/value pairs for a certain property.
user_data : | user data to pass to the function.
Returns : | The value of the first key/value pair is returned, for which func evaluates to TRUE. If no pair with the requested property is found, NULL is returned.

GHFunc ()

void        (*GHFunc)                  (gpointer key, gpointer value, gpointer user_data);

Specifies the type of the function passed to g_hash_table_foreach(). It is called with each key/value pair, together with the user_data parameter which is passed to g_hash_table_foreach().

key : | a key.
value : | the value corresponding to the key.
user_data : | user data passed to g_hash_table_foreach().

g_hash_table_remove ()

gboolean    g_hash_table_remove        (GHashTable *hash_table, gconstpointer key);

Removes a key and its associated value from a GHashTable.

If the GHashTable was created using g_hash_table_new_full(), the key and value are freed using the supplied destroy functions, otherwise check to make sure that any dynamically allocated values are freed manually.

hash_table : | a GHashTable.
key : | the key to remove.
Returns : | TRUE if the key was found and removed from the GHashTable.

g_hash_table_steal ()

gboolean    g_hash_table_steal              (GHashTable *hash_table, gconstpointer key);

Removes a key and its associated value from a GHashTable without calling the key and value destroy functions.

hash_table : | a GHashTable.
key : | the key to remove.
Returns : | TRUE if the key was found and removed from the GHashTable.

g_hash_table_foreach_remove ()

guint       g_hash_table_foreach_remove     (GHashTable *hash_table, GHRFunc func, gpointer user_data);

Calls the given function for each key/value pair in the GHashTable. If the function returns TRUE, then the key/value pair is removed from the GHashTable. If supplied with a key or value destroy functions when creating the GHashTable, they are used to free the memory allocated for the removed keys and values.

hash_table : | a GHashTable.
func : | the function to call for each key/value pair.
user_data : | user data to pass to the function.
Returns : | the number of key/value pairs removed.

g_hash_table_foreach_steal ()

guint       g_hash_table_foreach_steal      (GHashTable *hash_table, GHRFunc func, gpointer user_data);

Calls the given function for each key/value pair in the GHashTable. If the function returns TRUE, then the key/value pair is removed from the GHashTable, but no key or value destroy functions are called.

hash_table : | a GHashTable.
func : | the function to call for each key/value pair.
user_data : | user data to pass to the function.
Returns : | the number of key/value pairs removed.

GHRFunc ()

gboolean    (*GHRFunc)                  (gpointer key, gpointer value, gpointer user_data);

Specifies the type of the function passed to g_hash_table_foreach_remove(). It is called with each key/value pair, together with the user_data parameter passed to g_hash_table_foreach_remove(). It should return TRUE if the key/value pair should be removed from the GHashTable.

key : | a key.
value : | the value associated with the key.
user_data : | user data passed to g_hash_table_remove().
Returns : | TRUE if the key/value pair should be removed from the GHashTable.

g_hash_table_freeze()

#define     g_hash_table_freeze(hash_table)

This function is deprecated and will be removed in the next major release of GLib. It does nothing.

Note

Warning: g_hash_table_freeze is deprecated and should not be used in newly-written code.

hash_table : a GHashTable

g_hash_table_thaw()

#define     g_hash_table_thaw(hash_table)

This function is deprecated and will be removed in the next major release of GLib. It does nothing.

Note

Warning: g_hash_table_thaw is deprecated and should not be used in newly-written code.

hash_table : a GHashTable

g_hash_table_destroy ()

void        g_hash_table_destroy            (GHashTable *hash_table);

Destroys all keys and values in the GHashTable and decrements its reference count by 1. If keys and/or values are dynamically allocated, either free them first or create the GHashTable with destroy notifiers using g_hash_table_new_full(). In the latter case the destroy functions supplied will be called on all keys and values during the destruction phase.

hash_table : a GHashTable.

g_hash_table_ref ()

GHashTable* g_hash_table_ref                (GHashTable *hash_table);

Atomically increments the reference count of hash_table by one. This function is MT-safe and may be called from any thread.

hash_table : | a valid GHashTable.
Returns : | the passed in GHashTable.

g_hash_table_unref ()

void        g_hash_table_unref              (GHashTable *hash_table);

Atomically decrements the reference count of hash_table by one. If the reference count drops to 0, all keys and values will be destroyed, and all memory allocated by the hash table is released. This function is MT-safe and may be called from any thread.

hash_table : a valid GHashTable.

g_direct_equal ()

gboolean    g_direct_equal                  (gconstpointer v1, gconstpointer v2);

Compares two gpointer arguments and returns TRUE if they are equal. It can be passed to g_hash_table_new() as the key_equal_func parameter, when using pointers as keys in a GHashTable.

v1 : | a key.
v2 : | a key to compare with v1.
Returns : | TRUE if the two keys match.

g_direct_hash ()

guint       g_direct_hash                 (gconstpointer v);

Converts a gpointer to a hash value. It can be passed to g_hash_table_new() as the hash_func parameter, when using pointers as keys in a GHashTable.

v : | a gpointer key
Returns : | a hash value corresponding to the key.

g_int_equal ()

gboolean    g_int_equal                 (gconstpointer v1, gconstpointer v2);

Compares the two gint values being pointed to and returns TRUE if they are equal. It can be passed to g_hash_table_new() as the key_equal_func parameter, when using pointers to integers as keys in a GHashTable.

v1 : | a pointer to a gint key.
v2 : | a pointer to a gint key to compare with v1.
Returns : | TRUE if the two keys match.

g_int_hash ()

guint       g_int_hash                (gconstpointer v);

Converts a pointer to a gint to a hash value. It can be passed to g_hash_table_new() as the hash_func parameter, when using pointers to integers values as keys in a GHashTable.

v : | a pointer to a gint key
Returns : | a hash value corresponding to the key.

g_str_equal ()

gboolean    g_str_equal           (gconstpointer v1, gconstpointer v2);

Compares two strings and returns TRUE if they are equal. It can be passed to g_hash_table_new() as the key_equal_func parameter, when using strings as keys in a GHashTable.

v1 : | a key.
v2 : | a key to compare with v1.
Returns : | TRUE if the two keys match.

g_str_hash ()

guint       g_str_hash           (gconstpointer v);

Converts a string to a hash value. It can be passed to g_hash_table_new() as the hash_func parameter, when using strings as keys in a GHashTable.

v : | a string key.
Returns : | a hash value corresponding to the key.

Feedback

For additional information or queries on this page send feedback


Hook Functions

Name

Hook Functions — Hook Functions supports for manipulating lists of hook functions.

Library

glib.lib

Synopsis

#include <glib.h>

GHookList;
GHook;
void        (*GHookFinalizeFunc)            (GHookList *hook_list, GHook *hook);

void        (*GHookFunc)                    (gpointer data);
gboolean    (*GHookCheckFunc)               (gpointer data);

void        g_hook_list_init                (GHookList *hook_list, guint hook_size);
void        g_hook_list_invoke              (GHookList *hook_list, gboolean may_recurse);
void        g_hook_list_invoke_check        (GHookList *hook_list, gboolean may_recurse);
void        g_hook_list_marshal             (GHookList *hook_list, gboolean may_recurse,
                                             GHookMarshaller marshaller, gpointer marshal_data);
void        (*GHookMarshaller)              (GHook *hook, gpointer marshal_data);
void        g_hook_list_marshal_check       (GHookList *hook_list, gboolean may_recurse, GHookCheckMarshaller marshaller, gpointer marshal_data);
gboolean    (*GHookCheckMarshaller)         (GHook *hook, gpointer marshal_data);
void        g_hook_list_clear               (GHookList *hook_list);

GHook*      g_hook_alloc                    (GHookList *hook_list);
#define     g_hook_append                   ( hook_list, hook )
void        g_hook_prepend                  (GHookList *hook_list, GHook *hook);
void        g_hook_insert_before            (GHookList *hook_list, GHook *sibling, GHook *hook);
void        g_hook_insert_sorted            (GHookList *hook_list, GHook *hook, GHookCompareFunc func);
gint        (*GHookCompareFunc)             (GHook *new_hook, GHook *sibling);
gint        g_hook_compare_ids              (GHook *new_hook, GHook *sibling);

GHook*      g_hook_get                      (GHookList *hook_list, gulong hook_id);
GHook*      g_hook_find                     (GHookList *hook_list, gboolean need_valids, GHookFindFunc func, gpointer data);
gboolean    (*GHookFindFunc)                (GHook *hook, gpointer data);
GHook*      g_hook_find_data                (GHookList *hook_list, gboolean need_valids, gpointer data);
GHook*      g_hook_find_func                (GHookList *hook_list, gboolean need_valids, gpointer func);
GHook*      g_hook_find_func_data           (GHookList *hook_list, gboolean need_valids, gpointer func, gpointer data);

GHook*      g_hook_first_valid              (GHookList *hook_list, gboolean may_be_in_call);
GHook*      g_hook_next_valid               (GHookList *hook_list, GHook *hook, gboolean may_be_in_call);
enum        GHookFlagMask;
#define     G_HOOK_FLAGS                    (hook)
#define     G_HOOK_FLAG_USER_SHIFT

#define     G_HOOK                          (hook)
#define     G_HOOK_IS_VALID                 (hook)
#define     G_HOOK_ACTIVE                   (hook)
#define     G_HOOK_IN_CALL                  (hook)
#define     G_HOOK_IS_UNLINKED              (hook)

GHook*      g_hook_ref                      (GHookList *hook_list, GHook *hook);
void        g_hook_unref                    (GHookList *hook_list, GHook *hook);
void        g_hook_free                     (GHookList *hook_list, GHook *hook);
gboolean    g_hook_destroy                  (GHookList *hook_list, gulong hook_id);
void        g_hook_destroy_link             (GHookList *hook_list, GHook *hook);

Detailed Description

The GHookList, GHook and their related functions provide support for lists of hook functions. Functions can be added and removed from the lists, and the list of hook functions can be invoked.

Details

GHookList

typedef struct {
  gulong	    seq_id;
  guint		    hook_size : 16;
  guint		    is_setup : 1;
  GHook		   *hooks;
  gpointer	    dummy3;
  GHookFinalizeFunc finalize_hook;
  gpointer	    dummy[2];
} GHookList;

The GHookList struct represents a list of hook functions.

gulong seq_id; | the next free GHook id.
guint hook_size : 16; | the size of the GHookList elements, in bytes.
guint is_setup : 1; | 1 if the GHookList has been initialized.
GHook *hooks; | the first GHook element in the list.
gpointer dummy3; |
GHookFinalizeFunc finalize_hook; | the function to call to finalize a GHook element. The default behaviour is to call the hooks destroy function.
gpointer dummy[2]; |

GHookFinalizeFunc ()

void        (*GHookFinalizeFunc)            (GHookList *hook_list, GHook *hook);

Defines the type of function to be called when a hook in a list of hooks gets finalized.

hook_list : | a GHookList.
hook : | the hook in hook_list that gets finalized.

GHook

typedef struct {
  gpointer	 data;
  GHook		*next;
  GHook		*prev;
  guint		 ref_count;
  gulong	 hook_id;
  guint		 flags;
  gpointer	 func;
  GDestroyNotify destroy;
} GHook;

The GHook struct represents a single hook function in a GHookList.

gpointer data; | data which is passed to func when this hook is invoked.
GHook *next; | pointer to the next hook in the list.
GHook *prev; | pointer to the previous hook in the list.
guint ref_count; | the reference count of this hook.
gulong hook_id; | the id of this hook, which is unique within its list.
guint flags; | flags which are set for this hook. See GHookFlagMask for predefined flags.
gpointer func; | the function to call when this hook is invoked. The possible signatures for this function are GHookFunc and GHookCheckFunc.
GDestroyNotify destroy; | the default finalize_hook function of a GHookList calls this member of the hook that is being finalized.

GHookFunc ()

void        (*GHookFunc)           (gpointer data);

Defines the type of a hook function that can be invoked by g_hook_list_invoke().

data : the data field of the GHook is passed to the hook function here.

GHookCheckFunc ()

gboolean    (*GHookCheckFunc)        (gpointer data);

Defines the type of a hook function that can be invoked by g_hook_list_invoke_check().

data : | the data field of the GHook is passed to the hook function here.
Returns : | FALSE if the GHook should be destroyed.

g_hook_list_init ()

void     g_hook_list_init        (GHookList *hook_list, guint hook_size);

Initializes a GHookList. This must be called before the GHookList is used.

hook_list : | a GHookList.
hook_size : | the size of each element in the GHookList, typically sizeof (GHook).

g_hook_list_invoke ()

void    g_hook_list_invoke        (GHookList *hook_list, gboolean may_recurse);

Calls all of the GHook functions in a GHookList.

hook_list : | a GHookList.
may_recurse : | TRUE if functions which are already running (e.g. in another thread) can be called. If set to FALSE, these are skipped.

g_hook_list_invoke_check ()

void   g_hook_list_invoke_check   (GHookList *hook_list, gboolean may_recurse);

Calls all of the GHook functions in a GHookList. Any function which returns FALSE is removed from the GHookList.

hook_list : | a GHookList.
may_recurse : | TRUE if functions which are already running (e.g. in another thread) can be called. If set to FALSE, these are skipped.

g_hook_list_marshal ()

void   g_hook_list_marshal    (GHookList *hook_list, gboolean may_recurse, GHookMarshaller marshaller, gpointer marshal_data);

Calls a function on each valid GHook.

hook_list : | a GHookList.
may_recurse : | TRUE if hooks which are currently running (e.g. in another thread) are considered valid. If set to FALSE, these are skipped.
marshaller : | the function to call for each GHook.
marshal_data : | data to pass to marshaller.

GHookMarshaller ()

void        (*GHookMarshaller)  (GHook *hook, gpointer marshal_data);

Defines the type of function used by g_hook_list_marshal().

hook : | a GHook.
marshal_data : | user data.

g_hook_list_marshal_check ()

void        g_hook_list_marshal_check       (GHookList *hook_list, gboolean may_recurse, GHookCheckMarshaller marshaller, gpointer marshal_data);

Calls a function on each valid GHook and destroys it if the function returns FALSE.

hook_list : | a GHookList.
may_recurse : | TRUE if hooks which are currently running (e.g. in another thread) are considered valid. If set to FALSE, these are skipped.
marshaller : | the function to call for each GHook.
marshal_data : | data to pass to marshaller.

GHookCheckMarshaller ()

gboolean    (*GHookCheckMarshaller)         (GHook *hook, gpointer marshal_data);

Defines the type of function used by g_hook_list_marshal_check().

hook : | a GHook.
marshal_data : | user data.
Returns : | FALSE if hook should be destroyed.

g_hook_list_clear ()

void        g_hook_list_clear             (GHookList *hook_list);

Removes all the GHook elements from a GHookList.

hook_list : a GHookList.

g_hook_alloc ()

GHook*      g_hook_alloc                 (GHookList *hook_list);

Allocates space for a GHook and initializes it.

hook_list : | a GHookList.
Returns : | a new GHook.

g_hook_append()

#define     g_hook_append( hook_list, hook )

Appends a GHook onto the end of a GHookList.

hook_list : | a GHookList.
hook : | the GHook to add to the end of hook_list.

g_hook_prepend ()

void        g_hook_prepend                  (GHookList *hook_list, GHook *hook);

Prepends a GHook on the start of a GHookList.

hook_list : | a GHookList.
hook : | the GHook to add to the start of hook_list.

g_hook_insert_before ()

void        g_hook_insert_before            (GHookList *hook_list, GHook *sibling, GHook *hook);

Inserts a GHook into a GHookList, before a given GHook.

hook_list : | a GHookList.
sibling : | the GHook to insert the new GHook before.
hook : | the GHook to insert.

g_hook_insert_sorted ()

void        g_hook_insert_sorted            (GHookList *hook_list, GHook *hook, GHookCompareFunc func);

Inserts a GHook into a GHookList, sorted by the given function.

hook_list : | a GHookList.
hook : | the GHook to insert.
func : | the comparison function used to sort the GHook elements.

GHookCompareFunc ()

gint        (*GHookCompareFunc)             (GHook *new_hook, GHook *sibling);

Defines the type of function used to compare GHook elements in g_hook_insert_sorted().

new_hook : | the GHook being inserted.
sibling : | the GHook to compare with new_hook.
Returns : | a value <= 0 if new_hook should be before sibling.

g_hook_compare_ids ()

gint        g_hook_compare_ids        (GHook *new_hook, GHook *sibling);

Compares the ids of two GHook elements, returning a negative value if the second id is greater than the first.

new_hook : | a GHook.
sibling : | a GHook to compare with new_hook.
Returns : | a value <= 0 if the id of sibling is >= the id of new_hook.

g_hook_get ()

GHook*      g_hook_get                (GHookList *hook_list, gulong hook_id);

Returns the GHook with the given id, or NULL if it is not found.

hook_list : | a GHookList.
hook_id : | a hook id.
Returns : | the GHook with the given id, or NULL if it is not found.

g_hook_find ()

GHook*      g_hook_find               (GHookList *hook_list, gboolean need_valids, GHookFindFunc func, gpointer data);

Finds a GHook in a GHookList using the given function to test for a match.

hook_list : | a GHookList.
need_valids : | TRUE if GHook elements which have been destroyed should be skipped.
func : | the function to call for each GHook, which should return TRUE when the GHook has been found.
data : | the data to pass to func.
Returns : | the found GHook or NULL if no matching GHook is found.

GHookFindFunc ()

gboolean    (*GHookFindFunc)          (GHook *hook, gpointer data);

Defines the type of the function passed to g_hook_find().

hook : | a GHook.
data : | user data passed to g_hook_find_func().
Returns : | TRUE if the required GHook has been found.

g_hook_find_data ()

GHook*      g_hook_find_data          (GHookList *hook_list, gboolean need_valids, gpointer data);

Finds a GHook in a GHookList with the given data.

hook_list : | a GHookList.
need_valids : | TRUE if GHook elements which have been destroyed should be skipped.
data : | the data to find.
Returns : | the GHook with the given data or NULL if no matching GHook is found.

g_hook_find_func ()

GHook*      g_hook_find_func         (GHookList *hook_list, gboolean need_valids, gpointer func);

Finds a GHook in a GHookList with the given function.

hook_list : | a GHookList.
need_valids : | TRUE if GHook elements which have been destroyed should be skipped.
func : | the function to find.
Returns : | the GHook with the given func or NULL if no matching GHook is found.

g_hook_find_func_data ()

GHook*      g_hook_find_func_data    (GHookList *hook_list, gboolean need_valids, gpointer func, gpointer data);

Finds a GHook in a GHookList with the given function and data.

hook_list : | a GHookList.
need_valids : | TRUE if GHook elements which have been destroyed should be skipped.
func : | the function to find.
data : | the data to find.
Returns : | the GHook with the given func and data or NULL if no matching GHook is found.

g_hook_first_valid ()

GHook*      g_hook_first_valid      (GHookList *hook_list, gboolean may_be_in_call);

Returns the first GHook in a GHookList which has not been destroyed. The reference count for the GHook is incremented, so call g_hook_unref() to restore it when no longer needed. (Or call g_hook_next_valid() to step through the GHookList.)

hook_list : | a GHookList.
may_be_in_call : | TRUE if hooks which are currently running (e.g. in another thread) are considered valid. If set to FALSE, these are skipped.
Returns : | the first valid GHook, or NULL if none are valid.

g_hook_next_valid ()

GHook*      g_hook_next_valid       (GHookList *hook_list, GHook *hook, gboolean may_be_in_call);

Returns the next GHook in a GHookList which has not been destroyed. The reference count for the GHook is incremented, so call g_hook_unref() to restore it when no longer needed. (Or continue to call g_hook_next_valid() until NULL is returned.)

hook_list : | a GHookList.
hook : | the current GHook.
may_be_in_call : | TRUE if hooks which are currently running (e.g. in another thread) are considered valid. If set to FALSE, these are skipped.
Returns : | the next valid GHook, or NULL if none are valid.

enum GHookFlagMask

typedef enum
{
  G_HOOK_FLAG_ACTIVE	    = 1 << 0,
  G_HOOK_FLAG_IN_CALL	    = 1 << 1,
  G_HOOK_FLAG_MASK	    = 0x0f
} GHookFlagMask;

Flags used internally in the GHook implementation.

G_HOOK_FLAG_ACTIVE | set if the hook has not been destroyed.
G_HOOK_FLAG_IN_CALL | set if the hook is currently being run.
G_HOOK_FLAG_MASK | A mask covering all bits reserved for hook flags; see G_HOOK_FLAGS_USER_SHIFT

G_HOOK_FLAGS()

#define	G_HOOK_FLAGS(hook)		(G_HOOK (hook)->flags)

Returns the flags of a hook.

hook : a GHook.

G_HOOK_FLAG_USER_SHIFT

#define G_HOOK_FLAG_USER_SHIFT	(4)

The position of the first bit which is not reserved for internal use be the GHook implementation, i.e. 1 << G_HOOK_FLAG_USER_SHIFT is the first bit which can be used for application-defined flags.

G_HOOK()

#define	G_HOOK(hook)			((GHook*) (hook))

Casts a pointer to a GHook*.

hook : a pointer.

G_HOOK_IS_VALID()

#define     G_HOOK_IS_VALID(hook)

Returns TRUE if the GHook is valid, i.e. it is in a GHookList, it is active and it has not been destroyed.

hook : | a GHook.
Returns : | TRUE if the GHook is valid.

G_HOOK_ACTIVE()

#define     G_HOOK_ACTIVE(hook)

Returns TRUE if the GHook is active, which is normally TRUE until the GHook is destroyed.

hook : | a GHook.
Returns : | TRUE if the GHook is active.

G_HOOK_IN_CALL()

#define     G_HOOK_IN_CALL(hook)

Returns TRUE if the GHook function is currently executing.

hook : | a GHook.
Returns : | TRUE if the GHook function is currently executing.

G_HOOK_IS_UNLINKED()

#define     G_HOOK_IS_UNLINKED(hook)

Returns TRUE if the GHook is not in a GHookList.

hook : | a GHook.
Returns : | TRUE if the GHook is not in a GHookList.

g_hook_ref ()

GHook*      g_hook_ref                (GHookList *hook_list, GHook *hook);

Increments the reference count for a GHook.

hook_list : | a GHookList.
hook : | the GHook to increment the reference count of.
Returns : | the hook that was passed in (since 2.6)

g_hook_unref ()

void        g_hook_unref                (GHookList *hook_list, GHook *hook);

Decrements the reference count of a GHook. If the reference count falls to 0, the GHook is removed from the GHookList and g_hook_free() is called to free it.

hook_list : | a GHookList.
hook : | the GHook to unref.

g_hook_free ()

void        g_hook_free                (GHookList *hook_list, GHook *hook);

Calls the GHookList hook_free function if it exists, and frees the memory allocated for the GHook.

hook_list : | a GHookList.
hook : | the GHook to free.

g_hook_destroy ()

gboolean    g_hook_destroy              (GHookList *hook_list, gulong hook_id);

Destroys a GHook, given its ID.

hook_list : | a GHookList.
hook_id : | a hook ID.
Returns : | TRUE if the GHook was found in the GHookList and destroyed.

g_hook_destroy_link ()

void        g_hook_destroy_link        (GHookList *hook_list, GHook *hook);

Removes one GHook from a GHookList, marking it inactive and calling g_hook_unref() on it.

hook_list : | a GHookList.
hook: | the GHook to remove.

Feedback

For additional information or queries on this page send feedback


Internationalization

Name

Internationalization — Internationalization gettext support macros.

Library

glib.lib

Synopsis

#include <glib.h>
#include <glib/gi18n.h>

#define     _                               (String)
#define     Q_                              (String)
#define     N_                              (String)
const gchar* g_strip_context                (const gchar *msgid, const gchar *msgval);

const gchar* const * g_get_language_names   (void);

Detailed Description

GLib does not force any particular localization method upon its users. But since GLib itself is localized using the gettext() mechanism, it seems natural to offer the de-facto standard gettext() support macros in an easy-to-use form.

In order to use these macros in an application, include glib/gi18n.h. For use in a library, include glib/gi18n-lib.h after defining the GETTEXT_PACKAGE macro suitably for the library:

#define GETTEXT_PACKAGE "gtk20"
#include <glib/gi18n-lib.h>

Details

_()

#define     _(String)

Marks a string for translation, gets replaced with the translated string at runtime.

String : the string to be translated

Q_()

#define     Q_(String)

Like _(), but applies g_strip_context() to the translation. This has the advantage that the string can be adorned with a prefix to guarantee uniqueness and provide context to the translator.

One use case given in the gettext manual is GUI translation, where one could e.g. disambiguate two "Open" menu entries as "File|Open" and "Printer|Open". Another use case is the string "Russian" which may have to be translated differently depending on whether it's the name of a character set or a language. This could be solved by using "charset|Russian" and "language|Russian".

String : the string to be translated, with a '|'-separated prefix which must not be translated

N_()

#define     N_(String)

Marks a string for translation, gets replaced with the untranslated string at runtime. This is useful in situations where the translated strings cannot be directly used, e.g. in string array initializers.

     {
       static const char *messages[] = {
         N_("some very meaningful message"),
         N_("and another one")
       };
       const char *string;
       ...
       string
         = index > 1 ? _("a default message") : gettext (messages[index]);

       fputs (string);
       ...
     }
String : the string to be translated

g_strip_context ()

const gchar* g_strip_context            (const gchar *msgid, const gchar *msgval);

An auxiliary function for gettext() support (see Q_()).

msgid : | a string
msgval : | another string
Returns : | msgval, unless msgval is identical to msgid and contains a '|' character, in which case a pointer to the substring of msgid after the first '|' character is returned.

g_get_language_names ()

const gchar* const * g_get_language_names   (void);

Computes a list of applicable locale names, which can be used to e.g. construct locale-dependent filenames or search paths. The returned list is sorted from most desirable to least desirable and always contains the default locale "C".

For example, if LANGUAGE=de:en_US, then the returned list is "de", "en_US", "en", "C".

This function consults the environment variables LANGUAGE, LC_ALL, LC_MESSAGES and LANG to find the list of locales specified by the user.

Returns : a NULL-terminated array of strings owned by GLib that must not be modified or freed.

See Also

The gettext manual.

Feedback

For additional information or queries on this page send feedback


IO Channels

Name

IO Channels — portable support for using files, pipes and sockets.

Library

glib.lib

Synopsis

#include <glib.h>

GIOChannel;
GIOChannel* g_io_channel_unix_new                (int fd);
gint        g_io_channel_unix_get_fd             (GIOChannel *channel);

GIOChannel* g_io_channel_win32_new_fd            (gint fd);
GIOChannel* g_io_channel_win32_new_socket        (gint socket);
GIOChannel* g_io_channel_win32_new_messages      (guint hwnd);
void        g_io_channel_init                    (GIOChannel *channel);

GIOChannel* g_io_channel_new_file                (const gchar *filename, const gchar *mode, GError **error);
GIOStatus   g_io_channel_read_chars              (GIOChannel *channel, gchar *buf, gsize count, gsize *bytes_read, GError **error);
GIOStatus   g_io_channel_read_unichar            (GIOChannel *channel, gunichar *thechar, GError **error);
GIOStatus   g_io_channel_read_line               (GIOChannel *channel, gchar **str_return,  gsize *length, gsize *terminator_pos, GError **error);
GIOStatus   g_io_channel_read_line_string        (GIOChannel *channel, GString *buffer, gsize *terminator_pos, GError **error);
GIOStatus   g_io_channel_read_to_end             (GIOChannel *channel, gchar **str_return, gsize *length, GError **error);
GIOStatus   g_io_channel_write_chars             (GIOChannel *channel, const gchar *buf, gssize count, gsize *bytes_written, GError **error);
GIOStatus   g_io_channel_write_unichar           (GIOChannel *channel, gunichar thechar, GError **error);
GIOStatus   g_io_channel_flush                   (GIOChannel *channel, GError **error);
GIOStatus   g_io_channel_seek_position           (GIOChannel *channel, gint64 offset, GSeekType type, GError **error);
enum        GSeekType;
GIOStatus   g_io_channel_shutdown                (GIOChannel *channel, gboolean flush, GError **err);

enum        GIOStatus;
enum        GIOChannelError;
#define     G_IO_CHANNEL_ERROR
GIOChannelError g_io_channel_error_from_errno    (gint en);

GIOChannel* g_io_channel_ref                     (GIOChannel *channel);
void        g_io_channel_unref                   (GIOChannel *channel);

GSource*    g_io_create_watch                    (GIOChannel *channel, GIOCondition condition);
guint       g_io_add_watch                       (GIOChannel *channel, GIOCondition condition, GIOFunc func, gpointer user_data);
guint       g_io_add_watch_full                  (GIOChannel *channel, gint priority, GIOCondition condition, GIOFunc func, gpointer user_data,
                                                  GDestroyNotify notify);
enum        GIOCondition;
gboolean    (*GIOFunc)                           (GIOChannel *source, GIOCondition condition, gpointer data);

GIOFuncs;

gsize       g_io_channel_get_buffer_size         (GIOChannel *channel);
void        g_io_channel_set_buffer_size         (GIOChannel *channel, gsize size);
GIOCondition g_io_channel_get_buffer_condition   (GIOChannel *channel);
GIOFlags    g_io_channel_get_flags               (GIOChannel *channel);
GIOStatus   g_io_channel_set_flags               (GIOChannel *channel, GIOFlags flags, GError **error);
enum        GIOFlags;
const gchar* g_io_channel_get_line_term          (GIOChannel *channel, gint *length);
void        g_io_channel_set_line_term           (GIOChannel *channel, const gchar *line_term, gint length);
gboolean    g_io_channel_get_buffered            (GIOChannel *channel);
void        g_io_channel_set_buffered            (GIOChannel *channel, gboolean buffered);
const gchar* g_io_channel_get_encoding           (GIOChannel *channel);
GIOStatus   g_io_channel_set_encoding            (GIOChannel *channel, const gchar *encoding, GError **error);
gboolean    g_io_channel_get_close_on_unref      (GIOChannel *channel);
void        g_io_channel_set_close_on_unref      (GIOChannel *channel, gboolean do_close);

GIOError    g_io_channel_read                    (GIOChannel *channel, gchar *buf, gsize count, gsize *bytes_read);
enum        GIOError;
GIOError    g_io_channel_write                   (GIOChannel *channel, const gchar *buf, gsize count, gsize *bytes_written);
GIOError    g_io_channel_seek                    (GIOChannel *channel, gint64 offset, GSeekType type);
void        g_io_channel_close                   (GIOChannel *channel);

Detailed Description

The GIOChannel data type aims to provide a portable method for using file descriptors, pipes, and sockets, and integrating them into the main event loop. Currently full support is available on UNIX platforms, support for Windows is only partially complete.

To create a new GIOChannel on UNIX systems use g_io_channel_unix_new(). This works for plain file descriptors, pipes and sockets. Alternatively, a channel can be created for a file in a system independent manner using g_io_channel_new_file().

Once a GIOChannel has been created, it can be used in a generic manner with the functions g_io_channel_read_chars(), g_io_channel_write_chars(), g_io_channel_seek_position(), and g_io_channel_shutdown().

To add a GIOChannel to the main event loop use g_io_add_watch() or g_io_add_watch_full(). Here specify the events of interest in on the GIOChannel, and provide a function to be called whenever these events occur.

GIOChannel instances are created with an initial reference count of 1. g_io_channel_ref() and g_io_channel_unref() can be used to increment or decrement the reference count respectively. When the reference count falls to 0, the GIOChannel is freed. (Though it isn't closed automatically, unless it was created using g_io_channel_new_from_file().) Using g_io_add_watch() or g_io_add_watch_full() increments a channel's reference count.

The new functions g_io_channel_read_chars(), g_io_channel_read_line(), g_io_channel_read_line_string(), g_io_channel_read_to_end(), g_io_channel_write_chars(), g_io_channel_seek_position(), and g_io_channel_flush() should not be mixed with the deprecated functions g_io_channel_read(), g_io_channel_write(), and g_io_channel_seek() on the same channel.

Details

GIOChannel

typedef struct {
} GIOChannel;

A data structure representing an IO Channel. The fields should be considered private and should only be accessed with the following functions.

g_io_channel_unix_new ()

GIOChannel* g_io_channel_unix_new           (int fd);

Creates a new GIOChannel given a file descriptor. On UNIX systems this works for plain files, pipes, and sockets.

The returned GIOChannel has a reference count of 1.

The default encoding for GIOChannel is UTF-8. If the application is reading output from a command using via pipe, there maybe a need to set the encoding to the encoding of the current locale (see g_get_charset()) with the g_io_channel_set_encoding() function.

To read raw binary data without interpretation, then call the g_io_channel_set_encoding() function with NULL for the encoding argument.

This function is available in GLib on Windows, too, but avoid using it on Windows. The domain of file descriptors and sockets overlap. There is no way for GLib to know which one is meant in case the argument passed to this function happens to be both a valid file descriptor and socket. If that happens a warning is issued, and GLib assumes that it is the file descriptor that was meant.

fd : | a file descriptor.
Returns : | a new GIOChannel.

g_io_channel_unix_get_fd ()

gint        g_io_channel_unix_get_fd        (GIOChannel *channel);

Returns the file descriptor of the GIOChannel.

On Windows this function returns the file descriptor or socket of the GIOChannel.

channel : | a GIOChannel, created with g_io_channel_unix_new().
Returns : | the file descriptor of the GIOChannel.

g_io_channel_win32_new_fd ()

GIOChannel* g_io_channel_win32_new_fd       (gint fd);

Creates a new GIOChannel given a file descriptor on Windows. This works for file descriptors from the C runtime.

This function works for file descriptors as returned by the open(), creat(), pipe() and fileno() calls in the Microsoft C runtime. In order to meaningfully use this function the code should use the same C runtime as GLib uses, which is msvcrt.dll. Note that in current Microsoft compilers it is near impossible to convince it to build code that would use msvcrt.dll. The last Microsoft compiler version that supported using msvcrt.dll as the C runtime was version 6. The GNU compiler and tool chain for Windows, also known as Mingw, fully supports msvcrt.dll.

A GIOChannel created for a file descriptor and being watched (polled), should not call read() on the file descriptor. This is because adding polling for a file descriptor is implemented in GLib on Windows by starting a thread that sits blocked in a read() from the file descriptor most of the time. All reads from the file descriptor should be done by this internal GLib thread. The code should call only g_io_channel_read().

This function is available only in GLib on Windows.

fd : | a C library file descriptor.
Returns : | a new GIOChannel .

g_io_channel_win32_new_socket ()

GIOChannel* g_io_channel_win32_new_socket   (gint socket);

Creates a new GIOChannel given a socket on Windows.

This function works for sockets created by Winsock. It's available only in GLib on Windows.

Polling a GSource created to watch a channel for a socket puts the socket in non-blocking mode. This is a side-effect of the implementation and unavoidable.

socket : |
Returns : | a new GIOChannel

g_io_channel_win32_new_messages ()

GIOChannel* g_io_channel_win32_new_messages (guint hwnd);

Creates a new GIOChannel given a window handle on Windows.

This function creates a GIOChannel that can be used to poll for Windows messages for the window in question.

hwnd : | a window handle.
Returns : | a new GIOChannel.

g_io_channel_init ()

void        g_io_channel_init               (GIOChannel *channel);

Initializes a GIOChannel struct. This is called by each of the above functions when creating a GIOChannel, and so is not often needed by the application programmer (unless a new type of GIOChannel is being created).

channel : a GIOChannel.

g_io_channel_new_file ()

GIOChannel* g_io_channel_new_file           (const gchar *filename, const gchar *mode, GError **error);

Open a file filename as a GIOChannel using mode mode. This channel will be closed when the last reference to it is dropped, so there is no need to call g_io_channel_close() (though doing so will not cause problems, as long as no attempt is made to access the channel after it is closed).

filename : | A string containing the name of a file.
mode : | One of "r", "w", "a", "r+", "w+", "a+". These have the same meaning as in fopen().
error : | A location to return an error of type G_FILE_ERROR.
Returns : | A GIOChannel on success, NULL on failure.

g_io_channel_read_chars ()

GIOStatus   g_io_channel_read_chars         (GIOChannel *channel, gchar *buf, gsize count, gsize *bytes_read, GError **error);

Replacement for g_io_channel_read() with the new API.

channel : | a GIOChannel
buf : | a buffer to read data into
count : | the size of the buffer. Note that the buffer may not be completely filled even if there is data in the buffer if the remaining data is not a complete character.
bytes_read : | The number of bytes read. This may be zero even on success if count < 6 and the channel's encoding is non-NULL. This indicates that the next UTF-8 character is too wide for the buffer.
error : | A location to return an error of type GConvertError or GIOChannelError.
Returns : | the status of the operation.

g_io_channel_read_unichar ()

GIOStatus   g_io_channel_read_unichar       (GIOChannel *channel, gunichar *thechar, GError **error);

This function cannot be called on a channel with NULL encoding.

channel : | a GIOChannel
thechar : | a location to return a character
error : | A location to return an error of type GConvertError or GIOChannelError
Returns : | a GIOStatus

g_io_channel_read_line ()

GIOStatus   g_io_channel_read_line          (GIOChannel *channel, gchar **str_return, gsize *length, gsize *terminator_pos, GError **error);

Reads a line, including the terminating character(s), from a GIOChannel into a newly-allocated string. str_return will contain allocated memory if the return is G_IO_STATUS_NORMAL.

channel : | a GIOChannel
str_return : | The line read from the GIOChannel, including the line terminator. This data should be freed with g_free() when no longer needed. This is a nul-terminated string. If a length of zero is returned, this will be NULL instead.
length : | location to store length of the read data, or NULL
terminator_pos : | location to store position of line terminator, or NULL
error : | A location to return an error of type GConvertError or GIOChannelError
Returns : | the status of the operation.

g_io_channel_read_line_string ()

GIOStatus   g_io_channel_read_line_string   (GIOChannel *channel, GString *buffer, gsize *terminator_pos, GError **error);

Reads a line from a GIOChannel, using a GString as a buffer.

channel : | a GIOChannel
buffer : | a GString into which the line will be written. If buffer already contains data, the old data will be overwritten.
terminator_pos : | location to store position of line terminator, or NULL
error : | a location to store an error of type GConvertError or GIOChannelError
Returns : | the status of the operation.

g_io_channel_read_to_end ()

GIOStatus   g_io_channel_read_to_end        (GIOChannel *channel, gchar **str_return, gsize *length, GError **error);

Reads all the remaining data from the file.

channel : | a GIOChannel
str_return : | Location to store a pointer to a string holding the remaining data in the GIOChannel. This data should be freed with g_free() when no longer needed. This data is terminated by an extra nul character, but there may be other nulls in the intervening data.
length : | Location to store length of the data
error : | A location to return an error of type GConvertError or GIOChannelError
Returns : | G_IO_STATUS_NORMAL on success. This function never returns G_IO_STATUS_EOF.

g_io_channel_write_chars ()

GIOStatus   g_io_channel_write_chars        (GIOChannel *channel, const gchar *buf, gssize count, gsize *bytes_written, GError **error);

Replacement for g_io_channel_write() with the new API.

On seekable channels with encodings other than NULL or UTF-8, generic mixing of reading and writing is not allowed. A call to g_io_channel_write_chars() may only be made on a channel from which data has been read in the cases described in the documentation for g_io_channel_set_encoding().

channel : | a GIOChannel
buf : | a buffer to write data from
count : | the size of the buffer. If -1, the buffer is taken to be a nul-terminated string.
bytes_written : | The number of bytes written. This can be nonzero even if the return value is not G_IO_STATUS_NORMAL. If the return value is G_IO_STATUS_NORMAL and the channel is blocking, this will always be equal to count if count >= 0.
error : | A location to return an error of type GConvertError or GIOChannelError
Returns : | the status of the operation.

g_io_channel_write_unichar ()

GIOStatus   g_io_channel_write_unichar      (GIOChannel *channel, gunichar thechar, GError **error);

This function cannot be called on a channel with NULL encoding.

channel : | a GIOChannel
thechar : | a character
error : | A location to return an error of type GConvertError or GIOChannelError
Returns : | a GIOStatus

g_io_channel_flush ()

GIOStatus   g_io_channel_flush              (GIOChannel *channel, GError **error);

Flushes the write buffer for the GIOChannel.

channel : | a GIOChannel
error : | location to store an error of type GIOChannelError
Returns : | the status of the operation: One of G_IO_CHANNEL_NORMAL, G_IO_CHANNEL_AGAIN, or G_IO_CHANNEL_ERROR.

g_io_channel_seek_position ()

GIOStatus   g_io_channel_seek_position      (GIOChannel *channel, gint64 offset, GSeekType type, GError **error);

Replacement for g_io_channel_seek() with the new API.

channel : | a GIOChannel
offset : | The offset in bytes from the position specified by type
type : | a GSeekType. The type G_SEEK_CUR is only allowed in those cases where a call to g_io_channel_set_encoding() is allowed. See the documentation for g_io_channel_set_encoding() for details.
error : | A location to return an error of type GIOChannelError
Returns : | the status of the operation.

enum GSeekType

typedef enum
{
  G_SEEK_CUR, G_SEEK_SET, G_SEEK_END
} GSeekType;

An enumeration specifying the base position for a g_io_channel_seek_position() operation.

G_SEEK_CUR | the current position in the file.
G_SEEK_SET | the start of the file.
G_SEEK_END | the end of the file.

g_io_channel_shutdown ()

GIOStatus   g_io_channel_shutdown           (GIOChannel *channel, gboolean flush, GError **err);

Close an IO channel. Any pending data to be written will be flushed if flush is TRUE. The channel will not be freed until the last reference is dropped using g_io_channel_unref().

channel : | a GIOChannel
flush : | if TRUE, flush pending
err : | location to store a GIOChannelError
Returns : | the status of the operation.

enum GIOStatus

typedef enum
{
  G_IO_STATUS_ERROR, G_IO_STATUS_NORMAL, G_IO_STATUS_EOF, G_IO_STATUS_AGAIN
} GIOStatus;

Stati returned by most of the GIOFuncs functions.

G_IO_STATUS_ERROR | An error occurred.
G_IO_STATUS_NORMAL | Success.
G_IO_STATUS_EOF | End of file.
G_IO_STATUS_AGAIN | Resource temporarily unavailable.

enum GIOChannelError

typedef enum
{
  /* Derived from errno */
  G_IO_CHANNEL_ERROR_FBIG, G_IO_CHANNEL_ERROR_INVAL, G_IO_CHANNEL_ERROR_IO, G_IO_CHANNEL_ERROR_ISDIR,
  G_IO_CHANNEL_ERROR_NOSPC, G_IO_CHANNEL_ERROR_NXIO, G_IO_CHANNEL_ERROR_OVERFLOW,
  G_IO_CHANNEL_ERROR_PIPE, /* Other */
  G_IO_CHANNEL_ERROR_FAILED
} GIOChannelError;

Error codes returned by GIOChannel operations.

G_IO_CHANNEL_ERROR_FBIG | File too large.
G_IO_CHANNEL_ERROR_INVAL | Invalid argument.
G_IO_CHANNEL_ERROR_IO | IO error.
G_IO_CHANNEL_ERROR_ISDIR | File is a directory.
G_IO_CHANNEL_ERROR_NOSPC | No space left on device.
G_IO_CHANNEL_ERROR_NXIO | No such device or address.
G_IO_CHANNEL_ERROR_OVERFLOW | Value too large for defined data type.
G_IO_CHANNEL_ERROR_PIPE | Broken pipe.
G_IO_CHANNEL_ERROR_FAILED | Some other error.

G_IO_CHANNEL_ERROR

#define G_IO_CHANNEL_ERROR g_io_channel_error_quark()

Error domain for GIOChannel operations. Errors in this domain will be from the GIOChannelError enumeration. See GError for information on error domains.

g_io_channel_error_from_errno ()

GIOChannelError g_io_channel_error_from_errno       (gint en);

Converts an errno error number to a GIOChannelError.

en : | an errno error number, e.g. EINVAL.
Returns : | a GIOChannelError error number, e.g. G_IO_CHANNEL_ERROR_INVAL.

g_io_channel_ref ()

GIOChannel* g_io_channel_ref                   (GIOChannel *channel);

Increments the reference count of a GIOChannel.

channel : | a GIOChannel.
Returns : | the channel that was passed in (since 2.6)

g_io_channel_unref ()

void        g_io_channel_unref               (GIOChannel *channel);

Decrements the reference count of a GIOChannel.

channel : a GIOChannel.

g_io_create_watch ()

GSource*    g_io_create_watch               (GIOChannel *channel, GIOCondition condition);

Creates a GSource that is dispatched when condition is met for the given channel. For example, if condition is G_IO_IN, the source will be dispatched when there is data available for reading. g_io_add_watch() is a simpler interface to this same functionality, for the case where the source should be added to the default main loop at the default priority.

On Windows, polling a GSource created to watch a channel for a socket puts the socket in non-blocking mode. This is a side-effect of the implementation and unavoidable.

channel : | a GIOChannel to watch
condition : | conditions to watch for
Returns : | a new GSource

g_io_add_watch ()

guint       g_io_add_watch               (GIOChannel *channel, GIOCondition condition, GIOFunc func, gpointer user_data);

Adds the GIOChannel into the main event loop with the default priority.

channel : | a GIOChannel.
condition : | the condition to watch for.
func : | the function to call when the condition is satisfied.
user_data : | user data to pass to func.
Returns : | the event source id.

g_io_add_watch_full ()

guint       g_io_add_watch_full          (GIOChannel *channel, gint priority, GIOCondition condition, GIOFunc func, gpointer user_data, GDestroyNotify notify);

Adds the GIOChannel into the main event loop with the given priority.

channel : | a GIOChannel.
priority : | the priority of the GIOChannel source.
condition : | the condition to watch for.
func : | the function to call when the condition is satisfied.
user_data : | user data to pass to func.
notify : | the function to call when the source is removed.
Returns : | the event source id.

enum GIOCondition

typedef enum
{
  G_IO_IN	GLIB_SYSDEF_POLLIN,
  G_IO_OUT	GLIB_SYSDEF_POLLOUT,
  G_IO_PRI	GLIB_SYSDEF_POLLPRI,
  G_IO_ERR	GLIB_SYSDEF_POLLERR,
  G_IO_HUP	GLIB_SYSDEF_POLLHUP,
  G_IO_NVAL	GLIB_SYSDEF_POLLNVAL
} GIOCondition;

A bitwise combination representing a condition to watch for on an event source.

G_IO_IN | There is data to read.
G_IO_OUT | Data can be written (without blocking).
G_IO_PRI | There is urgent data to read.
G_IO_ERR | Error condition.
G_IO_HUP | Hung up (the connection has been broken, usually for pipes and sockets).
G_IO_NVAL | Invalid request. The file descriptor is not open.

GIOFunc ()

gboolean    (*GIOFunc)              (GIOChannel *source, GIOCondition condition, gpointer data);

Specifies the type of function passed to g_io_add_watch() or g_io_add_watch_full(), which is called when the requested condition on a GIOChannel is satisfied.

source : | the GIOChannel event source.
condition : | the condition which has been satisfied.
data : | user data set in g_io_add_watch() or g_io_add_watch_full().
Returns : | the function should return FALSE if the event source should be removed.

GIOFuncs

typedef struct {
  GIOStatus (*io_read)          (GIOChannel  *channel, gchar   *buf, gsize   count, gsize  *bytes_read, GError  **err);
  GIOStatus (*io_write)         (GIOChannel  *channel, const gchar  *buf, gsize  count, gsize  *bytes_written, GError  **err);
  GIOStatus (*io_seek)          (GIOChannel  *channel, gint64  offset, GSeekType  type, GError   **err);
  GIOStatus (*io_close)         (GIOChannel  *channel, GError  **err);
  GSource*  (*io_create_watch)  (GIOChannel  *channel, GIOCondition  condition);
  void      (*io_free)          (GIOChannel  *channel);
  GIOStatus (*io_set_flags)     (GIOChannel  *channel, GIOFlags  flags, GError  **err);
  GIOFlags  (*io_get_flags)     (GIOChannel  *channel);
} GIOFuncs;

A table of functions used to handle different types of GIOChannel in a generic way.

g_io_channel_get_buffer_size ()

gsize       g_io_channel_get_buffer_size    (GIOChannel *channel);

Gets the buffer size.

channel : | a GIOChannel
Returns : | the size of the buffer.

g_io_channel_set_buffer_size ()

void        g_io_channel_set_buffer_size    (GIOChannel *channel, gsize size);

Sets the buffer size.

channel : | a GIOChannel
size : | the size of the buffer. 0 == pick a good size

g_io_channel_get_buffer_condition ()

GIOCondition g_io_channel_get_buffer_condition       (GIOChannel *channel);

This function returns a GIOCondition depending on whether there is data to be read/space to write data in the internal buffers in the GIOChannel. Only the flags G_IO_IN and G_IO_OUT may be set.

channel : | A GIOChannel
Returns : | A GIOCondition

g_io_channel_get_flags ()

GIOFlags    g_io_channel_get_flags             (GIOChannel *channel);

Gets the current flags for a GIOChannel, including read-only flags such as G_IO_FLAG_IS_READABLE.

The values of the flags G_IO_FLAG_IS_READABLE and G_IO_FLAG_IS_WRITEABLE are cached for internal use by the channel when it is created. If they should change at some later point (e.g. partial shutdown of a socket with the UNIX shutdown() function), the user should immediately call g_io_channel_get_flags() to update the internal values of these flags.

channel : | a GIOChannel
Returns : | the flags which are set on the channel

g_io_channel_set_flags ()

GIOStatus   g_io_channel_set_flags          (GIOChannel *channel, GIOFlags flags, GError **error);

Sets the (writeable) flags in channel to (flags & G_IO_CHANNEL_SET_MASK).

channel : | a GIOChannel.
flags : | the flags to set on the IO channel.
error : | A location to return an error of type GIOChannelError.
Returns : | the status of the operation.

enum GIOFlags

typedef enum
{
  G_IO_FLAG_APPEND = 1 << 0, G_IO_FLAG_NONBLOCK = 1 << 1,
  G_IO_FLAG_IS_READABLE = 1 << 2,	/* Read only flag */
  G_IO_FLAG_IS_WRITEABLE = 1 << 3,	/* Read only flag */
  G_IO_FLAG_IS_SEEKABLE = 1 << 4,	/* Read only flag */
  G_IO_FLAG_MASK = (1 << 5) - 1, G_IO_FLAG_GET_MASK = G_IO_FLAG_MASK,
  G_IO_FLAG_SET_MASK = G_IO_FLAG_APPEND | G_IO_FLAG_NONBLOCK
} GIOFlags;

Specifies properties of a GIOChannel. Some of the flags can only be read with g_io_channel_get_flags(), but not changed with g_io_channel_set_flags().

G_IO_FLAG_APPEND | turns on append mode, corresponds to O_APPEND (see the documentation of the UNIX open() syscall).
G_IO_FLAG_NONBLOCK | turns on nonblocking mode, corresponds to O_NONBLOCK/O_NDELAY (see the documentation of the UNIX open() syscall).
G_IO_FLAG_IS_READABLE | indicates that the io channel is readable. This flag can not be changed.
G_IO_FLAG_IS_WRITEABLE | indicates that the io channel is writable. This flag can not be changed.
G_IO_FLAG_IS_SEEKABLE | indicates that the io channel is seekable, i.e. that g_io_channel_seek_position() can be used on it. This flag can not be changed.
G_IO_FLAG_MASK |
G_IO_FLAG_GET_MASK |
G_IO_FLAG_SET_MASK |

g_io_channel_get_line_term ()

const gchar* g_io_channel_get_line_term            (GIOChannel *channel, gint *length);

This returns the string that GIOChannel uses to determine where in the file a line break occurs. A value of NULL indicates auto detection.

channel : | a GIOChannel
length : | a location to return the length of the line terminator
Returns : | The line termination string. This value is owned by GLib and must not be freed.

g_io_channel_set_line_term ()

void        g_io_channel_set_line_term         (GIOChannel *channel, const gchar *line_term, gint length);

This sets the string that GIOChannel uses to determine where in the file a line break occurs.

channel : | a GIOChannel
line_term : | The line termination string. Use NULL for auto detect. Auto detection breaks on "\n", "\r\n", "\r", "\0", and the Unicode paragraph separator. Auto detection should not be used for anything other than file-based channels.
length : | The length of the termination string. If -1 is passed, the string is assumed to be nul-terminated. This option allows termination strings with embedded nulls.

g_io_channel_get_buffered ()

gboolean    g_io_channel_get_buffered       (GIOChannel *channel);

Returns whether channel is buffered.

channel : | a GIOChannel.
Returns : | TRUE if the channel is buffered.

g_io_channel_set_buffered ()

void        g_io_channel_set_buffered       (GIOChannel *channel, gboolean buffered);

The buffering state can only be set if the channel's encoding is NULL. For any other encoding, the channel must be buffered.

A buffered channel can only be set unbuffered if the channel's internal buffers have been flushed. Newly created channels or channels which have returned G_IO_STATUS_EOF not require such a flush. For write-only channels, a call to g_io_channel_flush() is sufficient. For all other channels, the buffers may be flushed by a call to g_io_channel_seek_position(). This includes the possibility of seeking with seek type G_SEEK_CUR and an offset of zero. Note that this means that socket-based channels cannot be set unbuffered once they have had data read from them.

On unbuffered channels, it is safe to mix read and write calls from the new and old APIs, if this is necessary for maintaining old code.

The default state of the channel is buffered.

channel : | a GIOChannel
buffered : | whether to set the channel buffered or unbuffered

g_io_channel_get_encoding ()

const gchar* g_io_channel_get_encoding      (GIOChannel *channel);

Gets the encoding for the input/output of the channel. The internal encoding is always UTF-8. The encoding NULL makes the channel safe for binary data.

channel : | a GIOChannel
Returns : | A string containing the encoding, this string is owned by GLib and must not be freed.

g_io_channel_set_encoding ()

GIOStatus   g_io_channel_set_encoding       (GIOChannel *channel, const gchar *encoding, GError **error);

Sets the encoding for the input/output of the channel. The internal encoding is always UTF-8. The default encoding for the external file is UTF-8.

The encoding NULL is safe to use with binary data.

The encoding can only be set if one of the following conditions is true:

1. The channel was just created, and has not been written to or read from yet.

2. The channel is write-only.

3. The channel is a file, and the file pointer was just repositioned by a call to g_io_channel_seek_position(). (This flushes all the internal buffers.)

4. The current encoding is NULL or UTF-8.

5. One of the (new API) read functions has just returned G_IO_STATUS_EOF (or, in the case of g_io_channel_read_to_end(), G_IO_STATUS_NORMAL).

6. One of the functions g_io_channel_read_chars() or g_io_channel_read_unichar() has returned G_IO_STATUS_AGAIN or G_IO_STATUS_ERROR. This may be useful in the case of G_CONVERT_ERROR_ILLEGAL_SEQUENCE. Returning one of these statuses from g_io_channel_read_line(), g_io_channel_read_line_string(), or g_io_channel_read_to_end() does not guarantee that the encoding can be changed.

Channels which do not meet one of the above conditions cannot call g_io_channel_seek_position() with an offset of G_SEEK_CUR, and, if they are "seekable", cannot call g_io_channel_write_chars() after calling one of the API "read" functions.

channel : | a GIOChannel
encoding : | the encoding type
error : | location to store an error of type GConvertError.
Returns : | G_IO_STATUS_NORMAL if the encoding was successfully set.

g_io_channel_get_close_on_unref ()

gboolean    g_io_channel_get_close_on_unref (GIOChannel *channel);

Returns whether the file/socket/whatever associated with channel will be closed when channel receives its final unref and is destroyed. The default value of this is TRUE for channels created by g_io_channel_new_file(), and FALSE for all other channels.

channel : | a GIOChannel.
Returns : | Whether the channel will be closed on the final unref of the GIOChannel data structure.

g_io_channel_set_close_on_unref ()

void        g_io_channel_set_close_on_unref     (GIOChannel *channel, gboolean do_close);

Setting this flag to TRUE for a channel already closed can cause problems.

channel : | a GIOChannel
do_close : | Whether to close the channel on the final unref of the GIOChannel data structure. The default value of this is TRUE for channels created by g_io_channel_new_file(), and FALSE for all other channels.

g_io_channel_read ()

GIOError    g_io_channel_read               (GIOChannel *channel, gchar *buf, gsize count, gsize *bytes_read);

Reads data from a GIOChannel.

Note

Warning: g_io_channel_read has been deprecated since version 2.2 and should not be used in newly-written code. Use g_io_channel_read_chars() instead.

channel : | a GIOChannel.
buf : | a buffer to read the data into (which should be at least count bytes long).
count : | the number of bytes to read from the GIOChannel.
bytes_read : | returns the number of bytes actually read.
Returns : | G_IO_ERROR_NONE if the operation was successful.

enum GIOError

typedef enum
{
  G_IO_ERROR_NONE, G_IO_ERROR_AGAIN, G_IO_ERROR_INVAL, G_IO_ERROR_UNKNOWN
} GIOError;

GIOError
is only used by the deprecated functions
g_io_channel_read(),
g_io_channel_write(), and
g_io_channel_seek().

G_IO_ERROR_NONE | no error
G_IO_ERROR_AGAIN | an EAGAIN error occurred
G_IO_ERROR_INVAL | an EINVAL error occurred
G_IO_ERROR_UNKNOWN | another error occurred

g_io_channel_write ()

GIOError    g_io_channel_write              (GIOChannel *channel, const gchar *buf, gsize count, gsize *bytes_written);

Writes data to a GIOChannel.

Note

Warning: g_io_channel_write has been deprecated since version 2.2 and should not be used in newly-written code. Use g_io_channel_write_chars() instead.

channel : | a GIOChannel.
buf : | the buffer containing the data to write.
count : | the number of bytes to write.
bytes_written : | the number of bytes actually written.
Returns : | G_IO_ERROR_NONE if the operation was successful.

g_io_channel_seek ()

GIOError    g_io_channel_seek               (GIOChannel *channel, gint64 offset, GSeekType type);

Sets the current position in the GIOChannel, similar to the standard library function fseek().

Note

Warning: g_io_channel_seek has been deprecated since version 2.2 and should not be used in newly-written code. Use g_io_channel_seek_position() instead.

channel : | a GIOChannel.
offset : | an offset, in bytes, which is added to the position specified by type
type : | the position in the file, which can be G_SEEK_CUR (the current position), G_SEEK_SET (the start of the file), or G_SEEK_END (the end of the file).
Returns : | G_IO_ERROR_NONE if the operation was successful.

g_io_channel_close ()

void        g_io_channel_close              (GIOChannel *channel);
Close an IO channel. Any pending data to be written will be
flushed, ignoring errors.
The channel will not be freed until the
last reference is dropped using g_io_channel_unref().
Note

Warning: g_io_channel_close has been deprecated since version 2.2 and should not be used in newly-written code. Use g_io_channel_shutdown() instead.

channel : A GIOChannel

See Also

gtk_input_add_full(), gtk_input_remove(), gdk_input_add(), gdk_input_add_full(), gdk_input_remove()

Convenience functions for creating GIOChannel instances and adding them to the main event loop.

Feedback

For additional information or queries on this page send feedback


Key-value file parser

Name

Key-value file parser — parses .ini-like config files.

Library

glib.lib

Synopsis

#include <glib.h>

GKeyFile;
#define     G_KEY_FILE_ERROR
enum        GKeyFileError;
enum        GKeyFileFlags;
GKeyFile*   g_key_file_new                       (void);
void        g_key_file_free                      (GKeyFile *key_file);
void        g_key_file_set_list_separator        (GKeyFile *key_file, gchar separator);
gboolean    g_key_file_load_from_file            (GKeyFile *key_file, const gchar *file, GKeyFileFlags flags, GError **error);
gboolean    g_key_file_load_from_data            (GKeyFile *key_file, const gchar *data, gsize length, GKeyFileFlags flags, GError **error);
gboolean    g_key_file_load_from_data_dirs       (GKeyFile *key_file, const gchar *file, gchar **full_path, GKeyFileFlags flags, GError **error);

gchar*      g_key_file_to_data                   (GKeyFile *key_file, gsize *length, GError **error);
gchar*      g_key_file_get_start_group           (GKeyFile *key_file);
gchar**     g_key_file_get_groups                (GKeyFile *key_file, gsize *length);
gchar**     g_key_file_get_keys                  (GKeyFile *key_file, const gchar *group_name, gsize *length, GError **error);
gboolean    g_key_file_has_group                 (GKeyFile *key_file, const gchar *group_name);
gboolean    g_key_file_has_key                   (GKeyFile *key_file, const gchar *group_name, const gchar *key, GError **error);

gchar*      g_key_file_get_value                 (GKeyFile *key_file, const gchar *group_name, const gchar *key, GError **error);
gchar*      g_key_file_get_string                (GKeyFile *key_file, const gchar *group_name, const gchar *key, GError **error);
gchar*      g_key_file_get_locale_string         (GKeyFile *key_file, const gchar *group_name, const gchar *key, const gchar *locale, GError **error);
gboolean    g_key_file_get_boolean               (GKeyFile *key_file, const gchar *group_name, const gchar *key, GError **error);
gint        g_key_file_get_integer               (GKeyFile *key_file, const gchar *group_name, const gchar *key, GError **error);
gchar**     g_key_file_get_string_list           (GKeyFile *key_file, const gchar *group_name, const gchar *key, gsize *length, GError **error);

gchar**     g_key_file_get_locale_string_list    (GKeyFile *key_file, const gchar *group_name, const gchar *key, const gchar *locale, gsize *length, GError **error);
gboolean*   g_key_file_get_boolean_list          (GKeyFile *key_file, const gchar *group_name, const gchar *key, gsize *length, GError **error);
gint*       g_key_file_get_integer_list          (GKeyFile *key_file, const gchar *group_name, const gchar *key, gsize *length, GError **error);
gchar*      g_key_file_get_comment               (GKeyFile *key_file, const gchar *group_name, const gchar *key, GError **error);

void        g_key_file_set_value                 (GKeyFile *key_file, const gchar *group_name, const gchar *key, const gchar *value);
void        g_key_file_set_string                (GKeyFile *key_file, const gchar *group_name, const gchar *key, const gchar *string);
void        g_key_file_set_locale_string         (GKeyFile *key_file, const gchar *group_name, const gchar *key, const gchar *locale,
                                                  const gchar *string);
void        g_key_file_set_boolean               (GKeyFile *key_file, const gchar *group_name, const gchar *key, gboolean value);
void        g_key_file_set_integer               (GKeyFile *key_file, const gchar *group_name, const gchar *key, gint value);
void        g_key_file_set_string_list           (GKeyFile *key_file, const gchar *group_name, const gchar *key, const gchar *const   list[],
                                                  gsize length);
void        g_key_file_set_locale_string_list    (GKeyFile *key_file, const gchar *group_name, const gchar *key, const gchar *locale, const gchar *const   list[],
                                                  gsize length);
void        g_key_file_set_boolean_list          (GKeyFile *key_file, const gchar *group_name, const gchar *key, gboolean list[], gsize length);
void        g_key_file_set_integer_list          (GKeyFile *key_file, const gchar *group_name, const gchar *key, gint list[], gsize length);
void        g_key_file_set_comment               (GKeyFile *key_file, const gchar *group_name, const gchar *key, const gchar *comment, GError **error);
void        g_key_file_remove_group              (GKeyFile *key_file, const gchar *group_name, GError **error);
void        g_key_file_remove_key                (GKeyFile *key_file, const gchar *group_name, const gchar *key, GError **error);
void        g_key_file_remove_comment            (GKeyFile *key_file, const gchar *group_name, const gchar *key, GError **error);

Detailed Description

GKeyFile allows to parse, edit or create files containing groups of key-value pairs, which we call key files for lack of a better name. Several freedesktop.org specifications use key files now, e.g. the Desktop Entry Specification and the Icon Theme Specification.

The syntax of key files is described in detail in the Desktop Entry Specification, here is a quick summary: Key files consists of groups of key-value pairs, interspersed with comments.

# this is just an example
# there can be comments before the first group

[First Group]

Name=Key File Example\this value shows\nescaping

# localized strings are stored in multiple key-value pairs
Welcome=Hello
Welcome[de]=Hallo
Welcome[fr]=Bonjour
Welcome[it]=Ciao

[Another Group]

Numbers=2;20;-200;0

Booleans=true;false;true;true

Lines beginning with a '#' and blank lines are considered comments.

Groups are started by a header line containing the group name enclosed in '[' and ']', and ended implicitly by the start of the next group or the end of the file. Each key-value pair must be contained in a group.

Key-value pairs generally have the form key=value, with the exception of localized strings, which have the form key[locale]=value. Space before and after the '=' character are ignored. New line, tab, carriage return and backslash characters are escaped as \n, \t, \r, and \\, respectively. To preserve initial and final spaces, these can also be escaped as \s.

Key files can store strings (possibly with localized variants), integers, boolean and lists of these. Lists are separated by a separator character, typically ';' or ','. To use the list separator character in a value in a list, it has to be escaped by prefixing it with a backslash.

This syntax is obviously inspired by the .ini files commonly met on Windows, but there are some important differences:

  • .ini files use the ';' character to begin comments, key files use the '#' character.

  • Key files allow only comments before the first group.

  • Key files are always encoded in UTF-8.

  • Key and Group names are case-sensitive, for example a group called [GROUP] is a different group from [group].

Details

GKeyFile

typedef struct _GKeyFile GKeyFile;

The GKeyFile struct contains only private fields and should not be used directly.

G_KEY_FILE_ERROR

#define G_KEY_FILE_ERROR g_key_file_error_quark()

Error domain for key file parsing. Errors in this domain will be from the GKeyFileError enumeration. See GError for information on error domains.

enum GKeyFileError

typedef enum
{
  G_KEY_FILE_ERROR_UNKNOWN_ENCODING, G_KEY_FILE_ERROR_PARSE, G_KEY_FILE_ERROR_NOT_FOUND, G_KEY_FILE_ERROR_KEY_NOT_FOUND,
  G_KEY_FILE_ERROR_GROUP_NOT_FOUND, G_KEY_FILE_ERROR_INVALID_VALUE
} GKeyFileError;

Error codes returned by key file parsing.

G_KEY_FILE_ERROR_UNKNOWN_ENCODING | the text being parsed was in an unknown encoding
G_KEY_FILE_ERROR_PARSE | document was ill-formed
G_KEY_FILE_ERROR_NOT_FOUND | the file was not found
G_KEY_FILE_ERROR_KEY_NOT_FOUND | a requested key was not found
G_KEY_FILE_ERROR_GROUP_NOT_FOUND | a requested group was not found
G_KEY_FILE_ERROR_INVALID_VALUE | a value could not be parsed

enum GKeyFileFlags

typedef enum
{
  G_KEY_FILE_NONE              = 0, G_KEY_FILE_KEEP_COMMENTS     = 1 << 0, G_KEY_FILE_KEEP_TRANSLATIONS = 1 << 1
} GKeyFileFlags;

Flags which influence the parsing.

G_KEY_FILE_NONE | No flags, default behaviour
G_KEY_FILE_KEEP_COMMENTS | Use this flag to write the (possibly modified) contents of the key file back to a file; otherwise all comments will be lost when the key file is written back.
G_KEY_FILE_KEEP_TRANSLATIONS | Use this flag to write the (possibly modified) contents of the key file back to a file; otherwise only the translations for the current language will be written back.

g_key_file_new ()

GKeyFile*   g_key_file_new            (void);

Creates a new empty GKeyFile object. Use g_key_file_load_from_file(), g_key_file_load_from_data() or g_key_file_load_from_data_dirs() to read an existing key file.

Returns : an empty GKeyFile.

g_key_file_free ()

void        g_key_file_free                   (GKeyFile *key_file);

Frees a GKeyFile.

key_file : a GKeyFile

g_key_file_set_list_separator ()

void      g_key_file_set_list_separator      (GKeyFile *key_file, gchar separator);

Sets the character which is used to separate values in lists. Typically ';' or ',' are used as separators. The default list separator is ';'.

key_file : | a GKeyFile
separator : | the separator

g_key_file_load_from_file ()

gboolean    g_key_file_load_from_file       (GKeyFile *key_file, const gchar *file, GKeyFileFlags flags, GError **error);

Loads a key file into an empty GKeyFile structure. If the file could not be loaded then error is set to either a GFileError or GKeyFileError.

key_file : | an empty GKeyFile struct
file : | the path of a filename to load, in the GLib file name encoding
flags : | flags from GKeyFileFlags
error : | return location for a GError, or NULL
Returns : | TRUE if a key file could be loaded, FALSE othewise

g_key_file_load_from_data ()

gboolean    g_key_file_load_from_data       (GKeyFile *key_file, const gchar *data, gsize length, GKeyFileFlags flags, GError **error);

Loads a key file from memory into an empty GKeyFile structure. If the object cannot be created then error is set to a GKeyFileError.

key_file : | an empty GKeyFile struct
data : | key file loaded in memory.
length : | the length of data in bytes
flags : | flags from GKeyFileFlags
error : | return location for a GError, or NULL
Returns : | TRUE if a key file could be loaded, FALSE othewise

g_key_file_load_from_data_dirs ()

gboolean    g_key_file_load_from_data_dirs      (GKeyFile *key_file, const gchar *file, gchar **full_path, GKeyFileFlags flags, GError **error);

This function looks for a key file named file in the paths returned from g_get_user_data_dir() and g_get_system_data_dirs(), loads the file into key_file and returns the file's full path in full_path. If the file could not be loaded then an error is set to either a GFileError or GKeyFileError.

key_file : | an empty GKeyFile struct
file : | a relative path to a filename to open and parse
full_path : | return location for a string containing the full path of the file, or NULL
flags : | flags from GKeyFileFlags
error : | return location for a GError, or NULL
Returns : | TRUE if a key file could be loaded, FALSE othewise

g_key_file_to_data ()

gchar*      g_key_file_to_data                (GKeyFile *key_file, gsize *length, GError **error);

This function outputs key_file as a string.

key_file : | a GKeyFile
length : | return location for the length of the returned string, or NULL
error : | return location for a GError, or NULL
Returns : | a newly allocated string holding the contents of the GKeyFile

g_key_file_get_start_group ()

gchar*      g_key_file_get_start_group      (GKeyFile *key_file);

Returns the name of the start group of the file.

key_file : | a GKeyFile
Returns : | The start group of the key file.

g_key_file_get_groups ()

gchar**     g_key_file_get_groups          (GKeyFile *key_file, gsize *length);

Returns all groups in the key file loaded with key_file. The array of returned groups will be NULL-terminated, so length may optionally be NULL.

key_file : | a GKeyFile
length : | return location for the number of returned groups, or NULL
Returns : | a newly-allocated NULL-terminated array of strings. Use g_strfreev() to free it.

g_key_file_get_keys ()

gchar**     g_key_file_get_keys           (GKeyFile *key_file, const gchar *group_name, gsize *length, GError **error);

Returns all keys for the group name group_name. The array of returned keys will be NULL-terminated, so length may optionally be NULL. In the event that the group_name cannot be found, NULL is returned and error is set to G_KEY_FILE_ERROR_GROUP_NOT_FOUND.

key_file : | a GKeyFile
group_name : | a group name
length : | return location for the number of keys returned, or NULL
error : | return location for a GError, or NULL
Returns : | a newly-allocated NULL-terminated array of strings. Use g_strfreev() to free it.

g_key_file_has_group ()

gboolean    g_key_file_has_group           (GKeyFile *key_file, const gchar *group_name);

Looks whether the key file has the group group_name.

key_file : | a GKeyFile
group_name : | a group name
Returns : | TRUE if group_name is a part of key_file, FALSE otherwise.

g_key_file_has_key ()

gboolean    g_key_file_has_key            (GKeyFile *key_file, const gchar *group_name, const gchar *key, GError **error);

Looks whether the key file has the key key in the group group_name.

key_file : | a GKeyFile
group_name : | a group name
key : | a key name
error : | return location for a GError
Returns : | TRUE if key is a part of group_name, FALSE otherwise.

g_key_file_get_value ()

gchar*      g_key_file_get_value          (GKeyFile *key_file, const gchar *group_name, const gchar *key, GError **error);

Returns the value associated with key under group_name.

In the event the key cannot be found, NULL is returned and error is set to G_KEY_FILE_ERROR_KEY_NOT_FOUND. In the event that the group_name cannot be found, NULL is returned and error is set to G_KEY_FILE_ERROR_GROUP_NOT_FOUND.

key_file : | a GKeyFile
group_name : | a group name
key : | a key
error : | return location for a GError, or NULL
Returns : | a newly allocated string or NULL if the specified key cannot be found.

g_key_file_get_string ()

gchar*      g_key_file_get_string        (GKeyFile *key_file, const gchar *group_name, const gchar *key, GError **error);

Returns the value associated with key under group_name.

In the event the key cannot be found, NULL is returned and error is set to G_KEY_FILE_ERROR_KEY_NOT_FOUND. In the event that the group_name cannot be found, NULL is returned and error is set to G_KEY_FILE_ERROR_GROUP_NOT_FOUND.

key_file : | a GKeyFile
group_name : | a group name
key : | a key
error : | return location for a GError, or NULL
Returns : | a newly allocated string or NULL if the specified key cannot be found.

g_key_file_get_locale_string ()

gchar*      g_key_file_get_locale_string    (GKeyFile *key_file, const gchar *group_name, const gchar *key, const gchar *locale, GError **error);

Returns the value associated with key under group_name translated in the given locale if available. If locale is NULL then the current locale is assumed.

If key cannot be found then NULL is returned and error is set to G_KEY_FILE_ERROR_KEY_NOT_FOUND. If the value associated with key cannot be interpreted or no suitable translation can be found then the untranslated value is returned.

key_file : | a GKeyFile
group_name : | a group name
key : | a key
locale : | a locale or NULL
error : | return location for a GError, or NULL
Returns : | a newly allocated string or NULL if the specified key cannot be found.

g_key_file_get_boolean ()

gboolean    g_key_file_get_boolean          (GKeyFile *key_file, const gchar *group_name, const gchar *key, GError **error);

Returns the value associated with key under group_name as a boolean.

If key cannot be found then the return value is undefined and error is set to G_KEY_FILE_ERROR_KEY_NOT_FOUND. Likewise, if the value associated with key cannot be interpreted as a boolean then the return value is also undefined and error is set to G_KEY_FILE_ERROR_INVALID_VALUE.

key_file : | a GKeyFile
group_name : | a group name
key : | a key
error : | return location for a GError
Returns : | the value associated with the key as a boolean

g_key_file_get_integer ()

gint      g_key_file_get_integer          (GKeyFile *key_file, const gchar *group_name, const gchar *key, GError **error);

Returns the value associated with key under group_name as an integer. If group_name is NULL, the start_group is used.

If key cannot be found then the return value is undefined and error is set to G_KEY_FILE_ERROR_KEY_NOT_FOUND. Likewise, if the value associated with key cannot be interpreted as an integer then the return value is also undefined and error is set to G_KEY_FILE_ERROR_INVALID_VALUE.

key_file : | a GKeyFile
group_name : | a group name
key : | a key
error : | return location for a GError
Returns : | the value associated with the key as an integer.

g_key_file_get_string_list ()

gchar**     g_key_file_get_string_list      (GKeyFile *key_file, const gchar *group_name, const gchar *key, gsize *length,
                                             GError **error);

Returns the values associated with key under group_name.

In the event the key cannot be found, NULL is returned and error is set to G_KEY_FILE_ERROR_KEY_NOT_FOUND. In the event that the group_name cannot be found, NULL is returned and error is set to G_KEY_FILE_ERROR_GROUP_NOT_FOUND.

key_file : | a GKeyFile
group_name : | a group name
key : | a key
length : | return location for the number of returned strings, or NULL
error : | return location for a GError, or NULL
Returns : | a NULL-terminated string array or NULL if the specified key cannot be found. The array should be freed with g_strfreev().

g_key_file_get_locale_string_list ()

gchar**     g_key_file_get_locale_string_list        (GKeyFile *key_file, const gchar *group_name, const gchar *key,
                                                      const gchar *locale, gsize *length,GError **error);

Returns the values associated with key under group_name translated in the given locale if available. If locale is NULL then the current locale is assumed.

If key cannot be found then NULL is returned and error is set to G_KEY_FILE_ERROR_KEY_NOT_FOUND. If the values associated with key cannot be interpreted or no suitable translations can be found then the untranslated values are returned. The returned array is NULL-terminated, so length may optionally be NULL.

key_file : | a GKeyFile
group_name : | a group name
key : | a key
locale : | a locale
length : | return location for the number of returned strings or NULL
error : | return location for a GError or NULL
Returns : | a newly allocated NULL-terminated string array or NULL if the key isn't found. The string array should be freed with g_strfreev().

g_key_file_get_boolean_list ()

gboolean*   g_key_file_get_boolean_list     (GKeyFile *key_file, const gchar *group_name, const gchar *key, gsize *length,
                                             GError **error);

Returns the values associated with key under group_name as booleans. If group_name is NULL, the start_group is used.

If key cannot be found then the return value is undefined and error is set to G_KEY_FILE_ERROR_KEY_NOT_FOUND. Likewise, if the values associated with key cannot be interpreted as booleans then the return value is also undefined and error is set to G_KEY_FILE_ERROR_INVALID_VALUE.

key_file : | a GKeyFile
group_name : | a group name
key : | a key
length : | the number of booleans returned
error : | return location for a GError
Returns : | the values associated with the key as a boolean

g_key_file_get_integer_list ()

gint*      g_key_file_get_integer_list     (GKeyFile *key_file, const gchar *group_name, const gchar *key, gsize *length, GError **error);

Returns the values associated with key under group_name as integers.

If key cannot be found then the return value is undefined and error is set to G_KEY_FILE_ERROR_KEY_NOT_FOUND. Likewise, if the values associated with key cannot be interpreted as integers then the return value is also undefined and error is set to G_KEY_FILE_ERROR_INVALID_VALUE.

key_file : | a GKeyFile
group_name : | a group name
key : | a key
length : | the number of integers returned
error : | return location for a GError
Returns : | the values associated with the key as a integer

g_key_file_get_comment ()

gchar*      g_key_file_get_comment        (GKeyFile *key_file, const gchar *group_name, const gchar *key, GError **error);

Retrieves a comment above key from group_name. group_name. If key is NULL then comment will be read from above group_name. If both key and group_name are NULL, then comment will be read from above the first group in the file.

key_file : | a GKeyFile
group_name : | a group name, or NULL
key : | a key
error : | return location for a GError
Returns : | a comment that should be freed with g_free()

g_key_file_set_value ()

void        g_key_file_set_value          (GKeyFile *key_file, const gchar *group_name, const gchar *key, const gchar *value);

Associates a new value with key under group_name. If key cannot be found then it is created. If group_name cannot be found then it is created.

key_file : | a GKeyFile
group_name : | a group name
key : | a key
value : | a string

g_key_file_set_string ()

void        g_key_file_set_string         (GKeyFile *key_file, const gchar *group_name, const gchar *key, const gchar *string);

Associates a new string value with key under group_name. If key cannot be found then it is created. If group_name cannot be found then it is created.

key_file : | a GKeyFile
group_name : | a group name
key : | a key
string : | a string

g_key_file_set_locale_string ()

void      g_key_file_set_locale_string     (GKeyFile *key_file, const gchar *group_name, const gchar *key, const gchar *locale, const gchar *string);

Associates a string value for key and locale under group_name. If the translation for key cannot be found then it is created.

key_file : | a GKeyFile
group_name : | a group name
key : | a key
locale : | a locale
string : | a string

g_key_file_set_boolean ()

void        g_key_file_set_boolean          (GKeyFile *key_file, const gchar *group_name, const gchar *key, gboolean value);

Associates a new boolean value with key under group_name. If key cannot be found then it is created.

key_file : | a GKeyFile
group_name : | a group name
key : | a key
value : | TRUE or FALSE

g_key_file_set_integer ()

void        g_key_file_set_integer          (GKeyFile *key_file, const gchar *group_name, const gchar *key, gint value);

Associates a new integer value with key under group_name. If key cannot be found then it is created.

key_file : | a GKeyFile
group_name : | a group name
key : | a key
value : | an integer value

g_key_file_set_string_list ()

void        g_key_file_set_string_list      (GKeyFile *key_file, const gchar *group_name, const gchar *key, const gchar *const   list[], gsize length);

Associates a list of string values for key under group_name. If key cannot be found then it is created. If group_name cannot be found then it is created.

key_file : | a GKeyFile
group_name : | a group name
key : | a key
list : | an array of locale string values
length : | number of locale string values in list

g_key_file_set_locale_string_list ()

void     g_key_file_set_locale_string_list        (GKeyFile *key_file, const gchar *group_name, const gchar *key, const gchar *locale, const gchar *const   list[],
                                                   gsize length);

Associates a list of string values for key and locale under group_name. If the translation for key cannot be found then it is created.

key_file : | a GKeyFile
group_name : | a group name
key : | a key
locale : | a locale
list : | a NULL-terminated array of locale string values
length : | the length of list

g_key_file_set_boolean_list ()

void        g_key_file_set_boolean_list     (GKeyFile *key_file, const gchar *group_name, const gchar *key, gboolean list[], gsize length);

Associates a list of boolean values with key under group_name. If key cannot be found then it is created. If group_name is NULL, the start_group is used.

key_file : | a GKeyFile
group_name : | a group name
key : | a key
list : | an array of boolean values
length : | length of list

g_key_file_set_integer_list ()

void        g_key_file_set_integer_list     (GKeyFile *key_file, const gchar *group_name, const gchar *key, gint list[], gsize length);

Associates a list of integer values with key under group_name. If key cannot be found then it is created.

key_file : | a GKeyFile
group_name : | a group name
key : | a key
list : | an array of integer values
length : | number of integer values in list

g_key_file_set_comment ()

void        g_key_file_set_comment       (GKeyFile *key_file, const gchar *group_name, const gchar *key, const gchar *comment, GError **error);

Places a comment above key from group_name. group_name. If key is NULL then comment will be written above group_name. If both key and group_name are NULL, then comment will be written above the first group in the file.

key_file : | a GKeyFile
group_name : | a group name, or NULL
key : | a key
comment : | a comment
error : | return location for a GError

g_key_file_remove_group ()

void        g_key_file_remove_group      (GKeyFile *key_file, const gchar *group_name, GError **error);

Removes the specified group, group_name, from the key file.

key_file : | a GKeyFile
group_name : | a group name
error : | return location for a GError or NULL

g_key_file_remove_key ()

void        g_key_file_remove_key        (GKeyFile *key_file, const gchar *group_name, const gchar *key, GError **error);

Removes key in group_name from the key file.

key_file : | a GKeyFile
group_name : | a group name
key : | a key name to remove
error : | return location for a GError or NULL

g_key_file_remove_comment ()

void        g_key_file_remove_comment   (GKeyFile *key_file, const gchar *group_name, const gchar *key, GError **error);

Removes a comment above key from group_name. group_name. If key is NULL then comment will be written above group_name. If both key and group_name are NULL, then comment will be written above the first group in the file.

key_file : | a GKeyFile
group_name : | a group name, or NULL
key : | a key
error : | return location for a GError

Feedback

For additional information or queries on this page send feedback


Keyed Data Lists

Name

Keyed Data Lists — lists of data elements which are accessible by a string or GQuark identifier.

Library

glib.lib

Synopsis

#include <glib.h>

GData;
void        g_datalist_init                 (GData **datalist);

#define     g_datalist_id_set_data          (dl, q, d)
void        g_datalist_id_set_data_full     (GData **datalist, GQuark key_id, gpointer data, GDestroyNotify destroy_func);
gpointer    g_datalist_id_get_data          (GData **datalist, GQuark key_id);
#define     g_datalist_id_remove_data       (dl, q)
gpointer    g_datalist_id_remove_no_notify  (GData **datalist, GQuark key_id);

#define     g_datalist_set_data             (dl, k, d)
#define     g_datalist_set_data_full        (dl, k, d, f)
#define     g_datalist_get_data             (dl, k)
#define     g_datalist_remove_data          (dl, k)
#define     g_datalist_remove_no_notify     (dl, k)

void        g_datalist_foreach              (GData **datalist, GDataForeachFunc func, gpointer user_data);
void        g_datalist_clear                (GData **datalist);
void        g_datalist_set_flags            (GData **datalist, guint flags);
void        g_datalist_unset_flags          (GData **datalist, guint flags);
guint       g_datalist_get_flags            (GData **datalist);
#define     G_DATALIST_FLAGS_MASK

Detailed Description

Keyed data lists provide lists of arbitrary data elements which can be accessed either with a string or with a GQuark corresponding to the string.

The GQuark methods are quicker, since the strings have to be converted to GQuarks anyway.

Data lists are used for associating arbitrary data with GObjects, using g_object_set_data() and related functions.

To create a datalist, use g_datalist_init().

To add data elements to a datalist use g_datalist_id_set_data(), g_datalist_id_set_data_full(), g_datalist_set_data() and g_datalist_set_data_full().

To get data elements from a datalist use g_datalist_id_get_data() and g_datalist_get_data().

To iterate over all data elements in a datalist use g_datalist_foreach() (not thread-safe).

To remove data elements from a datalist use g_datalist_id_remove_data() and g_datalist_remove_data().

To remove all data elements from a datalist, use g_datalist_clear().

Details

GData

typedef struct _GData GData;

The GData struct is an opaque data structure to represent a Keyed Data List. It should only be accessed via the following functions.

g_datalist_init ()

void        g_datalist_init                 (GData **datalist);

Resets the datalist to NULL. It does not free any memory or call any destroy functions.

datalist : a pointer to a pointer to a datalist.

g_datalist_id_set_data()

#define     g_datalist_id_set_data(dl, q, d)

Sets the data corresponding to the given GQuark id. Any previous data with the same key is removed, and its destroy function is called.

dl : | a datalist.
q : | the GQuark to identify the data element.
d : | the data element, or NULL to remove any previous element corresponding to q.

g_datalist_id_set_data_full ()

void        g_datalist_id_set_data_full     (GData **datalist, GQuark key_id, gpointer data, GDestroyNotify destroy_func);

Sets the data corresponding to the given GQuark id, and the function to be called when the element is removed from the datalist. Any previous data with the same key is removed, and its destroy function is called.

datalist : | a datalist.
key_id : | the GQuark to identify the data element.
data : | the data element or NULL to remove any previous element corresponding to key_id.
destroy_func : | the function to call when the data element is removed. This function will be called with the data element and can be used to free any memory allocated for it. If data is NULL, then destroy_func must also be NULL.

g_datalist_id_get_data ()

gpointer    g_datalist_id_get_data          (GData **datalist, GQuark key_id);

Retrieves the data element corresponding to key_id.

datalist : | a datalist.
key_id : | the GQuark identifying a data element.
Returns : | the data element, or NULL if it is not found.

g_datalist_id_remove_data()

#define     g_datalist_id_remove_data(dl, q)

Removes an element, using its GQuark identifier.

dl : | a datalist.
q : | the GQuark identifying the data element.

g_datalist_id_remove_no_notify ()

gpointer    g_datalist_id_remove_no_notify      (GData **datalist, GQuark key_id);

Removes an element, without calling its destroy notification function.

datalist : | a datalist.
key_id : | the GQuark identifying a data element.
Returns : | the data previously stored at key_id, or NULL if none.

g_datalist_set_data()

#define     g_datalist_set_data(dl, k, d)

Sets the data element corresponding to the given string identifier.

dl : | a datalist.
k : | the string to identify the data element.
d : | the data element, or NULL to remove any previous element corresponding to k.

g_datalist_set_data_full()

#define     g_datalist_set_data_full(dl, k, d, f)

Sets the data element corresponding to the given string identifier, and the function to be called when the data element is removed.

dl : | a datalist.
k : | the string to identify the data element.
d : | the data element, or NULL to remove any previous element corresponding to k.
f : | the function to call when the data element is removed. This function will be called with the data element and can be used to free any memory allocated for it. If d is NULL, then f must also be NULL.

g_datalist_get_data()

#define     g_datalist_get_data(dl, k)

Gets a data element, using its string identifier. This is slower than g_datalist_id_get_data() because the string is first converted to a GQuark.

dl : | a datalist.
k : | the string identifying a data element.
Returns : | the data element, or NULL if it is not found.

g_datalist_remove_data()

#define     g_datalist_remove_data(dl, k)

Removes an element using its string identifier. The data element's destroy function is called if it has been set.

dl : | a datalist.
k : | the string identifying the data element.

g_datalist_remove_no_notify()

#define     g_datalist_remove_no_notify(dl, k)

Removes an element, without calling its destroy notifier.

dl : | a datalist.
k : | the string identifying the data element.

g_datalist_foreach ()

void        g_datalist_foreach            (GData **datalist, GDataForeachFunc func, gpointer user_data);

Calls the given function for each data element of the datalist. The function is called with each data element's GQuark id and data, together with the given user_data parameter. Note that this function is NOT thread-safe. So unless datalist can be protected from any modifications during invocation of this function, it should not be called.

datalist : | a datalist.
func : | the function to call for each data element.
user_data : | user data to pass to the function.

g_datalist_clear ()

void        g_datalist_clear                (GData **datalist);

Frees all the data elements of the datalist. The data elements' destroy functions are called if they have been set.

datalist : a datalist.

g_datalist_set_flags ()

void        g_datalist_set_flags            (GData **datalist, guint flags);

Turns on flag values for a data list. This function is used to keep a small number of boolean flags in an object with a data list without using any additional space. It is not generally useful except in circumstances where space is very tight. (It is used in the base GObject type, for example.)

datalist : | pointer to the location that holds a list
flags : | the flags to turn on. The values of the flags are restricted by G_DATALIST_FLAGS_MASK (currently 3; giving two possible boolean flags). A value for flags that doesn't fit within the mask is an error.

g_datalist_unset_flags ()

void        g_datalist_unset_flags          (GData **datalist, guint flags);

Turns off flag values for a data list. See g_datalist_unset_flags()

datalist : | pointer to the location that holds a list
flags : | the flags to turn off. The values of the flags are restricted by G_DATALIST_FLAGS_MASK (currently 3: giving two possible boolean flags). A value for flags that doesn't fit within the mask is an error.

g_datalist_get_flags ()

guint       g_datalist_get_flags            (GData **datalist);

Gets flags values packed in together with the datalist. See g_datalist_set_flags().

datalist : | pointer to the location that holds a list
Returns : | the flags of the datalist

G_DATALIST_FLAGS_MASK

#define G_DATALIST_FLAGS_MASK 0x3

A bit mask that restricts the possible flags passed to g_datalist_set_flags(). Passing a flags value where flags & ~G_DATALIST_FLAGS_MASK != 0 is an error.

Feedback

For additional information or queries on this page send feedback


Lexical Scanner

Name

Lexical Scanner — Lexical Scanner is a general purpose lexical scanner.

Library

glib.lib

Synopsis

#include <glib.h>

GScanner;
GScanner*   g_scanner_new                   (const GScannerConfig *config_templ);
            GScannerConfig;

void        g_scanner_input_file            (GScanner *scanner, gint input_fd);
void        g_scanner_sync_file_offset      (GScanner *scanner);
void        g_scanner_input_text            (GScanner *scanner, const	gchar *text, guint text_len);
GTokenType  g_scanner_peek_next_token       (GScanner *scanner);
GTokenType  g_scanner_get_next_token        (GScanner *scanner);

guint       g_scanner_cur_line              (GScanner *scanner);
guint       g_scanner_cur_position          (GScanner *scanner);
GTokenType  g_scanner_cur_token             (GScanner *scanner);
GTokenValue g_scanner_cur_value             (GScanner *scanner);
gboolean    g_scanner_eof                   (GScanner *scanner);

guint       g_scanner_set_scope             (GScanner *scanner, guint scope_id);
void        g_scanner_scope_add_symbol      (GScanner *scanner, guint scope_id, const gchar *symbol, gpointer value);
void        g_scanner_scope_foreach_symbol  (GScanner *scanner, guint scope_id, GHFunc func, gpointer user_data);
gpointer    g_scanner_scope_lookup_symbol   (GScanner *scanner, guint scope_id, const gchar *symbol);
void        g_scanner_scope_remove_symbol   (GScanner *scanner, guint scope_id, const gchar *symbol);

#define     g_scanner_freeze_symbol_table   (scanner)
#define     g_scanner_thaw_symbol_table     (scanner)
gpointer    g_scanner_lookup_symbol         (GScanner *scanner, const gchar *symbol);

void        g_scanner_warn                  (GScanner *scanner, const gchar *format, ...);
void        g_scanner_error                 (GScanner *scanner, const gchar *format, ...);
void        g_scanner_unexp_token           (GScanner *scanner, GTokenType expected_token, const gchar *identifier_spec,  const gchar *symbol_spec,
                                             const gchar *symbol_name, const gchar *message, gint is_error);
void        (*GScannerMsgFunc)              (GScanner *scanner, gchar *message, gboolean error);

void        g_scanner_destroy               (GScanner *scanner);

enum        GTokenType;
union       GTokenValue;
enum        GErrorType;
#define     G_CSET_a_2_z
#define     G_CSET_A_2_Z
#define     G_CSET_DIGITS
#define     G_CSET_LATINC
#define     G_CSET_LATINS

#define     g_scanner_add_symbol            ( scanner, symbol, value )
#define     g_scanner_remove_symbol         ( scanner, symbol )
#define     g_scanner_foreach_symbol        ( scanner, func, data )

Detailed Description

The GScanner and its associated functions provide a general purpose lexical scanner.

Details

GScanner

typedef struct {
  /* unused fields */
  gpointer		user_data;
  guint			max_parse_errors;

  /* g_scanner_error() increments this field */
  guint			parse_errors;

  /* name of input stream, featured by the default message handler */
  const gchar		*input_name;

  /* quarked data */
  GData			*qdata;

  /* link into the scanner configuration */
  GScannerConfig	*config;

  /* fields filled in after g_scanner_get_next_token() */
  GTokenType		token;
  GTokenValue		value;
  guint			line;
  guint			position;

  /* fields filled in after g_scanner_peek_next_token() */
  GTokenType		next_token;
  GTokenValue		next_value;
  guint			next_line;
  guint			next_position;

  /* to be considered private */
  GHashTable		*symbol_table;
  gint			input_fd;
  const gchar		*text;
  const gchar		*text_end;
  gchar			*buffer;
  guint			scope_id;

  /* handler function for _warn and _error */
  GScannerMsgFunc	msg_handler;
} GScanner;

The data structure representing a lexical scanner.

Set input_name after creating the scanner, since it is used by the default message handler when displaying warnings and errors. When scanning a file, the file name would be a good choice.

The user_data and max_parse_errors fields are not used.To associate extra data with the scanner place them here.

To use own message handler set the msg_handler field. The type of the message handler function is declared by GScannerMsgFunc.

g_scanner_new ()

GScanner*   g_scanner_new                   (const GScannerConfig *config_templ);

Creates a new GScanner. The config_templ structure specifies the initial settings of the scanner, which are copied into the GScanner config field. The default settings are used if NULL is passed.

config_templ : | the initial scanner settings.
Returns : | the new GScanner.

GScannerConfig

typedef struct {
  /* Character sets
   */
  gchar		*cset_skip_characters;		/* default: " \t\n" */
  gchar		*cset_identifier_first;
  gchar		*cset_identifier_nth;
  gchar		*cpair_comment_single;		/* default: "#\n" */

  /* Should symbol lookup work case sensitive?
   */
  guint		case_sensitive : 1;

  /* Boolean values to be adjusted "on the fly"
   * to configure scanning behaviour.
   */
  guint		skip_comment_multi : 1;		/* C like comment */
  guint		skip_comment_single : 1;	/* single line comment */
  guint		scan_comment_multi : 1;		/* scan multi line comments? */
  guint		scan_identifier : 1;
  guint		scan_identifier_1char : 1;
  guint		scan_identifier_NULL : 1;
  guint		scan_symbols : 1;
  guint		scan_binary : 1;
  guint		scan_octal : 1;
  guint		scan_float : 1;
  guint		scan_hex : 1;			/* `0x0ff0' */
  guint		scan_hex_dollar : 1;		/* `$0ff0' */
  guint		scan_string_sq : 1;		/* string: 'anything' */
  guint		scan_string_dq : 1;		/* string: "\\-escapes!\n" */
  guint		numbers_2_int : 1;		/* bin, octal, hex => int */
  guint		int_2_float : 1;		/* int => G_TOKEN_FLOAT? */
  guint		identifier_2_string : 1;
  guint		char_2_token : 1;		/* return G_TOKEN_CHAR? */
  guint		symbol_2_token : 1;
  guint		scope_0_fallback : 1;		/* try scope 0 on lookups? */
  guint		store_int64 : 1; 		/* use value.v_int64 rather than v_int */
  guint		padding_dummy;
} GScannerConfig;

Specifies the GScanner settings.

cset_skip_characters specifies which characters should be skipped by the scanner (the default is the whitespace characters: space, tab, carriage-return and line-feed).

cset_identifier_first specifies the characters which can start identifiers (the default is G_CSET_a_2_z, "_", and G_CSET_A_2_Z).

cset_identifier_nth specifies the characters which can be used in identifiers, after the first character (the default is G_CSET_a_2_z, "_0123456789", G_CSET_A_2_Z, G_CSET_LATINS, G_CSET_LATINC).

cpair_comment_single specifies the characters at the start and end of single-line comments. The default is "#\n" which means that single-line comments start with a '#' and continue until a '\n' (end of line).

case_sensitive specifies if symbols are case sensitive (the default is FALSE).

skip_comment_multi specifies if multi-line comments are skipped and not returned as tokens (the default is TRUE).

skip_comment_single specifies if single-line comments are skipped and not returned as tokens (the default is TRUE).

scan_comment_multi specifies if multi-line comments are recognized (the default is TRUE).

scan_identifier specifies if identifiers are recognized (the default is TRUE).

scan_identifier_1char specifies if single-character identifiers are recognized (the default is FALSE).

scan_identifier_NULL specifies if NULL is reported as G_TOKEN_IDENTIFIER_NULL. (the default is FALSE).

scan_symbols specifies if symbols are recognized (the default is TRUE).

scan_binary specifies if binary numbers are recognized (the default is FALSE).

scan_octal specifies if octal numbers are recognized (the default is TRUE).

scan_float specifies if floating point numbers are recognized (the default is TRUE).

scan_hex specifies if hexadecimal numbers are recognized (the default is TRUE).

scan_hex_dollar specifies if '$' is recognized as a prefix for hexadecimal numbers (the default is FALSE).

scan_string_sq specifies if strings can be enclosed in single quotes (the default is TRUE).

scan_string_dq specifies if strings can be enclosed in double quotes (the default is TRUE).

numbers_2_int specifies if binary, octal and hexadecimal numbers are reported as G_TOKEN_INT (the default is TRUE).

int_2_float specifies if all numbers are reported as G_TOKEN_FLOAT (the default is FALSE).

identifier_2_string specifies if identifiers are reported as strings (the default is FALSE).

char_2_token specifies if characters are reported by setting token = ch or as G_TOKEN_CHAR (the default is TRUE).

symbol_2_token specifies if symbols are reported by setting token = v_symbol or as G_TOKEN_SYMBOL (the default is FALSE).

scope_0_fallback specifies if a symbol is searched for in the default scope in addition to the current scope (the default is FALSE).

g_scanner_input_file ()

void        g_scanner_input_file            (GScanner *scanner, gint input_fd);

Prepares to scan a file.

scanner : | a GScanner.
input_fd : | a file descriptor.

g_scanner_sync_file_offset ()

void        g_scanner_sync_file_offset      (GScanner *scanner);

Rewinds the file descriptor to the current buffer position and blows the file read ahead buffer. This is useful for third party uses of the scanners filedescriptor, which hooks onto the current scanning position.

scanner : a GScanner.

g_scanner_input_text ()

void        g_scanner_input_text            (GScanner *scanner, const	gchar *text, guint text_len);

Prepares to scan a text buffer.

scanner : | a GScanner.
text : | the text buffer to scan.
text_len : | the length of the text buffer.

g_scanner_peek_next_token ()

GTokenType  g_scanner_peek_next_token       (GScanner *scanner);

Gets the next token, without removing it from the input stream. The token data is placed in the next_token, next_value, next_line, and next_position fields of the GScanner structure.

Note that, while the token is not removed from the input stream (i.e. the next call to g_scanner_get_next_token() will return the same token), it will not be reevaluated. This can lead to surprising results when changing scope after peeking for the next token. Getting the next token after switching the scope will return whatever was peeked before, regardless of any symbols that may have been added or removed in the new scope.

scanner : | a GScanner.
Returns : | the type of the token.

g_scanner_get_next_token ()

GTokenType  g_scanner_get_next_token        (GScanner *scanner);

Gets the next token, removing it from the input stream. The token data is placed in the token, value, line, and position fields of the GScanner structure.

scanner : | a GScanner.
Returns : | the type of the token.

g_scanner_cur_line ()

guint       g_scanner_cur_line              (GScanner *scanner);

Gets the current line in the input stream (counting from 1).

scanner : | a GScanner.
Returns : | the current line.

g_scanner_cur_position ()

guint       g_scanner_cur_position          (GScanner *scanner);

Gets the current position in the current line (counting from 0).

scanner : | a GScanner.
Returns : | the current position on the line.

g_scanner_cur_token ()

GTokenType  g_scanner_cur_token             (GScanner *scanner);

Gets the current token type. This is simply the token field in the GScanner structure.

scanner : | a GScanner.
Returns : | the current token type.

g_scanner_cur_value ()

GTokenValue g_scanner_cur_value             (GScanner *scanner);

Gets the current token value. This is simply the value field in the GScanner structure.

scanner : | a GScanner.
Returns : | the current token value.

g_scanner_eof ()

gboolean    g_scanner_eof                   (GScanner *scanner);

Returns TRUE if the scanner has reached the end of the file or text buffer.

scanner : | a GScanner.
Returns : | TRUE if the scanner has reached the end of the file or text buffer.

g_scanner_set_scope ()

guint       g_scanner_set_scope             (GScanner *scanner, guint scope_id);

Sets the current scope.

scanner : | a GScanner.
scope_id : | the new scope id.
Returns : | the old scope id.

g_scanner_scope_add_symbol ()

void        g_scanner_scope_add_symbol      (GScanner *scanner, guint scope_id, const gchar *symbol, gpointer value);

Adds a symbol to the given scope.

scanner : | a GScanner.
scope_id : | the scope id.
symbol : | the symbol to add.
value : | the value of the symbol.

g_scanner_scope_foreach_symbol ()

void        g_scanner_scope_foreach_symbol    (GScanner *scanner, guint scope_id, GHFunc func, gpointer user_data);

Calls the given function for each of the symbol/value pairs in the given scope of the GScanner. The function is passed the symbol and value of each pair, and the given user_data parameter.

scanner : | a GScanner.
scope_id : | the scope id.
func : | the function to call for each symbol/value pair.
user_data : | user data to pass to the function.

g_scanner_scope_lookup_symbol ()

gpointer    g_scanner_scope_lookup_symbol   (GScanner *scanner, guint scope_id, const gchar *symbol);

Looks up a symbol in a scope and return its value. If the symbol is not bound in the scope, NULL is returned.

scanner : | a GScanner.
scope_id : | the scope id.
symbol : | the symbol to look up.
Returns : | the value of symbol in the given scope, or NULL if symbol is not bound in the given scope.

g_scanner_scope_remove_symbol ()

void        g_scanner_scope_remove_symbol   (GScanner *scanner, guint scope_id, const gchar *symbol);

Removes a symbol from a scope.

scanner : | a GScanner.
scope_id : | the scope id.
symbol : | the symbol to remove.

g_scanner_freeze_symbol_table()

#define     g_scanner_freeze_symbol_table(scanner)
Note

Warning: g_scanner_freeze_symbol_table has been deprecated since version 2.2 and should not be used in newly-written code. This macro does nothing.

scanner : a GScanner.

g_scanner_thaw_symbol_table()

#define     g_scanner_thaw_symbol_table(scanner)
Note

Warning: g_scanner_thaw_symbol_table has been deprecated since version 2.2 and should not be used in newly-written code. This macro does nothing.

scanner : a GScanner.

g_scanner_lookup_symbol ()

gpointer    g_scanner_lookup_symbol         (GScanner *scanner, const gchar *symbol);

Looks up a symbol in the current scope and return its value. If the symbol is not bound in the current scope, NULL is returned.

scanner : | a GScanner.
symbol : | the symbol to look up.
Returns : | the value of symbol in the current scope, or NULL if symbol is not bound in the current scope.

g_scanner_warn ()

void        g_scanner_warn              (GScanner *scanner, const gchar *format, ...);

Outputs a warning message, via the GScanner message handler.

scanner : | a GScanner.
format : | the message format. See the printf() documentation.
... : | the parameters to insert into the format string.

g_scanner_error ()

void        g_scanner_error            (GScanner *scanner, const gchar *format, ...);

Outputs an error message, via the GScanner message handler.

scanner : | a GScanner.
format : | the message format. See the printf() documentation.
... : | the parameters to insert into the format string.

g_scanner_unexp_token ()

void     g_scanner_unexp_token       (GScanner *scanner, GTokenType expected_token, const gchar *identifier_spec, const gchar *symbol_spec, const gchar *symbol_name,
                                      const gchar *message, gint is_error);

Outputs a message through the scanner's msg_handler, resulting from an unexpected token in the input stream.

Do not call g_scanner_peek_next_token() followed by g_scanner_unexp_token() without an intermediate call to g_scanner_get_next_token(), as g_scanner_unexp_token() evaluates the scanner's current token (not the peeked token) to construct part of the message.

scanner : | a GScanner.
expected_token : | the expected token.
identifier_spec : | a string describing how the scanner's user refers to identifiers (NULL defaults to "identifier"). This is used if expected_token is G_TOKEN_IDENTIFIER or G_TOKEN_IDENTIFIER_NULL.
symbol_spec : | a string describing how the scanner's user refers to symbols (NULL defaults to "symbol"). This is used if expected_token is G_TOKEN_SYMBOL or any token value greater than G_TOKEN_LAST.
symbol_name : | the name of the symbol, if the scanner's current token is a symbol.
message : | a message string to output at the end of the warning/error, or NULL.
is_error : | if TRUE it is output as an error. If FALSE it is output as a warning.

GScannerMsgFunc ()

void        (*GScannerMsgFunc)           (GScanner *scanner, gchar *message, gboolean error);

Specifies the type of the message handler function.

scanner : | a GScanner.
message : | the message.
error : | TRUE if the message signals an error, FALSE if it signals a warning.

g_scanner_destroy ()

void        g_scanner_destroy            (GScanner *scanner);

Frees all memory used by the GScanner.

scanner : a GScanner.

enum GTokenType

typedef enum
{
  G_TOKEN_EOF			=   0,

  G_TOKEN_LEFT_PAREN		= '(',
  G_TOKEN_RIGHT_PAREN		= ')',
  G_TOKEN_LEFT_CURLY		= '{',
  G_TOKEN_RIGHT_CURLY		= '}',
  G_TOKEN_LEFT_BRACE		= '[',
  G_TOKEN_RIGHT_BRACE		= ']',
  G_TOKEN_EQUAL_SIGN		= '=',
  G_TOKEN_COMMA			= ',',

  G_TOKEN_NONE			= 256,

  G_TOKEN_ERROR,

  G_TOKEN_CHAR,
  G_TOKEN_BINARY,
  G_TOKEN_OCTAL,
  G_TOKEN_INT,
  G_TOKEN_HEX,
  G_TOKEN_FLOAT,
  G_TOKEN_STRING,

  G_TOKEN_SYMBOL,
  G_TOKEN_IDENTIFIER,
  G_TOKEN_IDENTIFIER_NULL,

  G_TOKEN_COMMENT_SINGLE,
  G_TOKEN_COMMENT_MULTI,
  G_TOKEN_LAST
} GTokenType;

The possible types of token returned from each g_scanner_get_next_token() call.

G_TOKEN_EOF | the end of the file.
G_TOKEN_LEFT_PAREN | a '(' character.
G_TOKEN_LEFT_CURLY | a '{' character.
G_TOKEN_RIGHT_CURLY | a '}' character.

union GTokenValue

union GTokenValue
{
  gpointer	v_symbol;
  gchar		*v_identifier;
  gulong	v_binary;
  gulong	v_octal;
  gulong	v_int;
  guint64       v_int64;
  gdouble	v_float;
  gulong	v_hex;
  gchar		*v_string;
  gchar		*v_comment;
  guchar	v_char;
  guint		v_error;
};

A union holding the value of the token.

enum GErrorType

typedef enum
{
  G_ERR_UNKNOWN,
  G_ERR_UNEXP_EOF,
  G_ERR_UNEXP_EOF_IN_STRING,
  G_ERR_UNEXP_EOF_IN_COMMENT,
  G_ERR_NON_DIGIT_IN_CONST,
  G_ERR_DIGIT_RADIX,
  G_ERR_FLOAT_RADIX,
  G_ERR_FLOAT_MALFORMED
} GErrorType;

The possible errors, used in the v_error field of GTokenValue, when the token is a G_TOKEN_ERROR.

G_ERR_UNKNOWN | unknown error.
G_ERR_UNEXP_EOF | unexpected end of file.
G_ERR_UNEXP_EOF_IN_STRING | unterminated string constant.
G_ERR_UNEXP_EOF_IN_COMMENT | unterminated comment.
G_ERR_NON_DIGIT_IN_CONST | non-digit character in a number.
G_ERR_DIGIT_RADIX | digit beyond radix in a number.
G_ERR_FLOAT_RADIX | non-decimal floating point number.
G_ERR_FLOAT_MALFORMED | malformed floating point number.

G_CSET_a_2_z

#define G_CSET_a_2_z	"abcdefghijklmnopqrstuvwxyz"

The set of lowercase ASCII alphabet characters. Used for specifying valid identifier characters in GScannerConfig.

G_CSET_A_2_Z

#define G_CSET_A_2_Z	"ABCDEFGHIJKLMNOPQRSTUVWXYZ"

The set of uppercase ASCII alphabet characters. Used for specifying valid identifier characters in GScannerConfig.

G_CSET_DIGITS

#define G_CSET_DIGITS	"0123456789"

The set of digits. Used for specifying valid identifier characters in GScannerConfig.

G_CSET_LATINC

#define     G_CSET_LATINC

The set of uppercase ISO 8859-1 alphabet characters which are not ASCII characters. Used for specifying valid identifier characters in GScannerConfig.

G_CSET_LATINS

#define     G_CSET_LATINS

The set of lowercase ISO 8859-1 alphabet characters which are not ASCII characters. Used for specifying valid identifier characters in GScannerConfig.

g_scanner_add_symbol()

#define     g_scanner_add_symbol( scanner, symbol, value )

Adds a symbol to the default scope.

Note

Warning: g_scanner_add_symbol has been deprecated since version 2.2 and should not be used in newly-written code. Use g_scanner_scope_add_symbol() instead.

scanner : | a GScanner.
symbol : | the symbol to add.
value : | the value of the symbol.

g_scanner_remove_symbol()

#define     g_scanner_remove_symbol        ( scanner, symbol )

Removes a symbol from the default scope.

Note

Warning: g_scanner_remove_symbol has been deprecated since version 2.2 and should not be used in newly-written code. Use g_scanner_scope_remove_symbol() instead.

scanner : | a GScanner.
symbol : | the symbol to remove.

g_scanner_foreach_symbol()

#define     g_scanner_foreach_symbol         ( scanner, func, data )

Calls a function for each symbol in the default scope.

Note

Warning: g_scanner_foreach_symbol has been deprecated since version 2.2 and should not be used in newly-written code. Use g_scanner_scope_foreach_symbol() instead.

scanner : | a GScanner.
func : | the function to call with each symbol.
data : | data to pass to the function.

Feedback

For additional information or queries on this page send feedback


Limits of Basic Types

Name

Limits of Basic Types — Limits of Basic Types is a portable method of determining the limits of the standard types.

Library

glib.lib

Synopsis

#include <glib.h>

#define     G_MININT
#define     G_MAXINT
#define     G_MAXUINT

#define     G_MINSHORT
#define     G_MAXSHORT
#define     G_MAXUSHORT

#define     G_MINLONG
#define     G_MAXLONG
#define     G_MAXULONG

#define     G_MININT8
#define     G_MAXINT8
#define     G_MAXUINT8

#define     G_MININT16
#define     G_MAXINT16
#define     G_MAXUINT16

#define     G_MININT32
#define     G_MAXINT32
#define     G_MAXUINT32

#define     G_MININT64
#define     G_MAXINT64
#define     G_MAXUINT64

#define     G_MAXSIZE

#define     G_MINFLOAT
#define     G_MAXFLOAT

#define     G_MINDOUBLE
#define     G_MAXDOUBLE

Detailed Description

These macros provide a portable method to determine the limits of some of the standard integer and floating point types.

Details

G_MININT

#define G_MININT	INT_MIN

The minimum value which can be held in a gint.

G_MAXINT

#define G_MAXINT	INT_MAX

The maximum value which can be held in a gint.

G_MAXUINT

#define G_MAXUINT	UINT_MAX

The maximum value which can be held in a guint.

G_MINSHORT

#define G_MINSHORT	SHRT_MIN

The minimum value which can be held in a gshort.

G_MAXSHORT

#define G_MAXSHORT	SHRT_MAX

The maximum value which can be held in a gshort.

G_MAXUSHORT

#define G_MAXUSHORT	USHRT_MAX

The maximum value which can be held in a gushort.

G_MINLONG

#define G_MINLONG	LONG_MIN

The minimum value which can be held in a glong.

G_MAXLONG

#define G_MAXLONG	LONG_MAX

The maximum value which can be held in a glong.

G_MAXULONG

#define G_MAXULONG	ULONG_MAX

The maximum value which can be held in a gulong.

G_MININT8

#define G_MININT8	((gint8)  0x80)

The minimum value which can be held in a gint8.

G_MAXINT8

#define G_MAXINT8	((gint8)  0x7f)

The maximum value which can be held in a gint8.

G_MAXUINT8

#define G_MAXUINT8	((guint8) 0xff)

The maximum value which can be held in a guint8.

G_MININT16

#define G_MININT16	((gint16)  0x8000)

The minimum value which can be held in a gint16.

G_MAXINT16

#define G_MAXINT16	((gint16)  0x7fff)

The maximum value which can be held in a gint16.

G_MAXUINT16

#define G_MAXUINT16	((guint16) 0xffff)

The maximum value which can be held in a guint16.

G_MININT32

#define G_MININT32	((gint32)  0x80000000)

The minimum value which can be held in a gint32.

G_MAXINT32

#define G_MAXINT32	((gint32)  0x7fffffff)

The maximum value which can be held in a gint32.

G_MAXUINT32

#define G_MAXUINT32	((guint32) 0xffffffff)

The maximum value which can be held in a guint32.

G_MININT64

#define G_MININT64	((gint64) G_GINT64_CONSTANT(0x8000000000000000))

The minimum value which can be held in a gint64.

G_MAXINT64

#define G_MAXINT64	G_GINT64_CONSTANT(0x7fffffffffffffff)

The maximum value which can be held in a gint64.

G_MAXUINT64

#define G_MAXUINT64	G_GINT64_CONSTANT(0xffffffffffffffffU)

The maximum value which can be held in a guint64.

G_MAXSIZE

#define G_MAXSIZE	G_MAXUINT

The maximum value which can be held in a gsize.

G_MINFLOAT

#define G_MINFLOAT	FLT_MIN

The minimum positive value which can be held in a gfloat.

If interested in the smallest value which can be held in a gfloat, use -G_MAX_FLOAT.

G_MAXFLOAT

#define G_MAXFLOAT	FLT_MAX

The maximum value which can be held in a gfloat.

G_MINDOUBLE

#define G_MINDOUBLE	DBL_MIN

The minimum positive value which can be held in a gdouble.

If interested in the smallest value which can be held in a gdouble, use -G_MAXDOUBLE.

G_MAXDOUBLE

#define G_MAXDOUBLE	DBL_MAX

The maximum value which can be held in a gdouble.

Feedback

For additional information or queries on this page send feedback


Memory Allocation

Name

Memory Allocation — Is general memory-handling.

Library

glib.lib

Synopsis

#include <glib.h>

#define     g_new                           (struct_type, n_structs)
#define     g_new0                          (struct_type, n_structs)
#define     g_renew                         (struct_type, mem, n_structs)
#define     g_try_new                       (struct_type, n_structs)
#define     g_try_new0                      (struct_type, n_structs)
#define     g_try_renew                     (struct_type, mem, n_structs)

gpointer    g_malloc                        (gulong n_bytes);
gpointer    g_malloc0                       (gulong n_bytes);
gpointer    g_realloc                       (gpointer mem, gulong n_bytes);
gpointer    g_try_malloc                    (gulong n_bytes);
gpointer    g_try_malloc0                   (gulong n_bytes);
gpointer    g_try_realloc                   (gpointer mem, gulong n_bytes);

void        g_free                          (gpointer mem);

extern      gboolean                        g_mem_gc_friendly;
#define     g_alloca                        (size)
#define     g_newa                          (struct_type, n_structs)

#define     g_memmove                       (dest,src,len)
gpointer    g_memdup                        (gconstpointer mem, guint byte_size);

            GMemVTable;
void        g_mem_set_vtable                (GMemVTable *vtable);
gboolean    g_mem_is_system_malloc          (void);

extern      GMemVTable	*glib_mem_profiler_table;
void        g_mem_profile                   (void);

Detailed Description

These functions provide support for allocating and freeing memory.

Details

g_new()

#define     g_new(struct_type, n_structs)

Allocates n_structs elements of type struct_type. The returned pointer is cast to a pointer to the given type. If n_structs is 0 or if memory allocation failure takes place, it returns NULL.

Since the returned pointer is already casted to the right type, it is normally unnecessary to cast it explicitly, and doing so might hide memory allocation errors.

struct_type : | the type of the elements to allocate.
n_structs : | the number of elements to allocate.
Returns : | a pointer to the allocated memory, cast to a pointer to struct_type.

g_new0()

#define     g_new0(struct_type, n_structs)

Allocates n_structs elements of type struct_type, initialized to 0's. The returned pointer is cast to a pointer to the given type. If n_structs is 0 or if memory allocation failure takes place, it returns NULL.

Since the returned pointer is already casted to the right type, it is normally unnecessary to cast it explicitly, and doing so might hide memory allocation errors.

struct_type : | the type of the elements to allocate.
n_structs : | the number of elements to allocate.
Returns : | a pointer to the allocated memory, cast to a pointer to struct_type.

g_renew()

#define     g_renew(struct_type, mem, n_structs)

Reallocates the memory pointed to by mem, so that it now has space for n_structs elements of type struct_type. It returns the new address of the memory, which may have been moved. If memory allocation failure takes place it returns NULL.

struct_type : | the type of the elements to allocate.
mem : | the currently allocated memory.
n_structs : | the number of elements to allocate.
Returns : | a pointer to the new allocated memory, cast to a pointer to struct_type.

g_try_new()

#define     g_try_new(struct_type, n_structs)

Attempts to allocate n_structs elements of type struct_type, and returns NULL on failure. Contrast with g_new(), which aborts the program on failure. The returned pointer is cast to a pointer to the given type. If n_structs is 0 it returns NULL.

struct_type : | the type of the elements to allocate.
n_structs : | the number of elements to allocate.
Returns : | a pointer to the allocated memory, cast to a pointer to struct_type.

g_try_new0()

#define     g_try_new0(struct_type, n_structs)

Attempts to allocate n_structs elements of type struct_type, initialized to 0's, and returns NULL on failure. Contrast with g_new0(), which aborts the program on failure. The returned pointer is cast to a pointer to the given type. If n_counts is 0 it returns NULL.

struct_type : | the type of the elements to allocate.
n_structs : | the number of elements to allocate.
Returns : | a pointer to the allocated memory, cast to a pointer to struct_type.

g_try_renew()

#define     g_try_renew(struct_type, mem, n_structs)

Attempts to reallocate the memory pointed to by mem, so that it now has space for n_structs elements of type struct_type, and returns NULL on failure. Contrast with g_renew(), which aborts the program on failure. It returns the new address of the memory, which may have been moved.

struct_type : | the type of the elements to allocate.
mem : | the currently allocated memory.
n_structs : | the number of elements to allocate.
Returns : | a pointer to the new allocated memory, cast to a pointer to struct_type.

g_malloc ()

gpointer    g_malloc        (gulong n_bytes);

Allocates n_bytes bytes of memory. If n_bytes is 0 or if memory allocation failure takes place, it returns NULL.

n_bytes : | the number of bytes to allocate.
Returns : | a pointer to the allocated memory.

g_malloc0 ()

gpointer    g_malloc0      (gulong n_bytes);

Allocates n_bytes bytes of memory, initialized to 0's. If n_bytes is 0 or if memory allocation failure takes place, it returns NULL.

n_bytes : | the number of bytes to allocate.
Returns : | a pointer to the allocated memory.

g_realloc ()

gpointer    g_realloc          (gpointer mem, gulong n_bytes);

Reallocates the memory pointed to by mem, so that it now has space for n_bytes bytes of memory. It returns the new address of the memory, which may have been moved. mem may be NULL, in which case it's considered to have zero-length. n_bytes may be 0 or if memory allocation failure takes place, NULL will be returned.

mem : | the memory to reallocate.
n_bytes : | new size of the memory in bytes.
Returns : | the new address of the allocated memory.

g_try_malloc ()

gpointer    g_try_malloc        (gulong n_bytes);

Attempts to allocate n_bytes, and returns NULL on failure. Contrast with g_malloc(), which aborts the program on failure.

n_bytes : | number of bytes to allocate.
Returns : | the allocated memory, or NULL.

g_try_malloc0 ()

gpointer    g_try_malloc0      (gulong n_bytes);

Attempts to allocate n_bytes, initialized to 0's, and returns NULL on failure.

n_bytes : | number of bytes to allocate.
Returns : | the allocated memory, or NULL.

Since 2.8

g_try_realloc ()

gpointer    g_try_realloc       (gpointer mem, gulong n_bytes);

Attempts to realloc mem to a new size, n_bytes, and returns NULL on failure. Contrast with g_realloc(), which aborts the program on failure. If mem is NULL, behaves the same as g_try_malloc().

mem : | previously-allocated memory, or NULL.
n_bytes : | number of bytes to allocate.
Returns : | the allocated memory, or NULL.

g_free ()

void        g_free          (gpointer mem);

Frees the memory pointed to by mem. If mem is NULL it simply returns.

mem : the memory to free.

g_mem_gc_friendly

extern gboolean g_mem_gc_friendly;

This variable is TRUE if the G_DEBUG environment variable includes the key gc-friendly.

g_alloca()

#define     g_alloca(size)

The function alloca() is not supported in Open C. This macro essentially just wraps the g_malloc() function present in libglib and allocates memory on the heap. The allocated memory must be freed using g_free().

size : | number of bytes to allocate.
Returns : | space for size bytes, allocated on the heap.

g_newa()

#define     g_newa(struct_type, n_structs)

Wraps g_alloca() in a more typesafe manner.

struct_type : | Type of memory chunks to be allocated
n_structs : | Number of chunks to be allocated
Returns : | Pointer to stack space for n_structs chunks of type struct_type

g_memmove()

#define     g_memmove(dest,src,len)

Copies a block of memory len bytes long, from src to dest. The source and destination areas may overlap.

In order to use this function, include string.h , because this macro will typically simply resolve to memmove() and GLib does not include string.h.

dest : | the destination address to copy the bytes to.
src : | the source address to copy the bytes from.
len : | the number of bytes to copy.

g_memdup ()

gpointer    g_memdup         (gconstpointer mem, guint byte_size);

Allocates byte_size bytes of memory, and copies byte_size bytes into it from mem. If mem is NULL it returns NULL.

mem : | the memory to copy.
byte_size : | the number of bytes to copy.
Returns : | a pointer to the newly-allocated copy of the memory, or NULL if mem is NULL.

GMemVTable

typedef struct {
  gpointer (*malloc)      (gsize    n_bytes);
  gpointer (*realloc)     (gpointer mem, gsize  n_bytes);
  void     (*free)        (gpointer mem);
  /* optional; set to NULL if not used ! */
  gpointer (*calloc)      (gsize    n_blocks, gsize  n_block_bytes);
  gpointer (*try_malloc)  (gsize    n_bytes);
  gpointer (*try_realloc) (gpointer mem, gsize  n_bytes);
} GMemVTable;

A set of functions used to perform memory allocation. The same GMemVTable must be used for all allocations in the same program; a call to g_mem_set_vtable(), if it exists, should be prior to any use of GLib.

malloc () | function to use for allocating memory.
realloc () | function to use for reallocating memory.
free () | function to use to free memory.
calloc () | function to use for allocating zero-filled memory.
try_malloc () | function to use for allocating memory without a default error handler.
try_realloc () | function to use for reallocating memory without a default error handler.

g_mem_set_vtable ()

void        g_mem_set_vtable      (GMemVTable *vtable);

Sets the GMemVTable to use for memory allocation.Use this to provide custom memory allocation routines. This function must be called before using any other GLib functions. The vtable only needs to provide malloc(), realloc(), and free() functions; GLib can provide default implementations of the others. The malloc() and realloc() implementations should return NULL on failure, GLib will handle error-checking. vtable is copied, so need not persist after this function has been called.

vtable : table of memory allocation routines.

g_mem_is_system_malloc ()

gboolean    g_mem_is_system_malloc    (void);

Checks whether the allocator used by g_malloc() is the system's malloc implementation. If it returns TRUE memory allocated with malloc() can be used interchangeable with memory allocated using g_malloc(). This function is useful for avoiding an extra copy of allocated memory returned by a non-GLib-based API.

A different allocator can be set using g_mem_set_vtable().

Returns : if TRUE, malloc() and g_malloc() can be mixed.

glib_mem_profiler_table

extern GMemVTable	*glib_mem_profiler_table;

A GMemVTable containing profiling variants of the memory allocation functions. Use them together with g_mem_profile() in order to get information about the memory allocation pattern of the program. To access this variable application include glib_global.h.

g_mem_profile ()

void        g_mem_profile          (void);

Outputs a summary of memory usage.

It outputs the frequency of allocations of different sizes, the total number of bytes which have been allocated, the total number of bytes which have been freed, and the difference between the previous two values, i.e. the number of bytes still in use.

Note that this function will not output anything unless the glib_mem_profiler_table with g_mem_set_vtable() has been previously installed.

Feedback

For additional information or queries on this page send feedback


Memory Allocators

Name

Memory Allocators — deprecated way to allocate chunks of memory for GList, GSList and GNode.

Library

glib.lib

Synopsis

#include <glib.h>

GAllocator;
GAllocator* g_allocator_new              (const gchar *name, guint n_preallocs);
void        g_allocator_free             (GAllocator *allocator);

Detailed Description

Prior to 2.10, GAllocator was used as an efficient way to allocate small pieces of memory for use with the GList, GSList and GNode data structures. Since 2.10, it has been completely replaced by the slice allocator and deprecated.

Details

GAllocator

typedef struct _GAllocator GAllocator;
Note

Warning: GAllocator is deprecated and should not be used in newly-written code.

The GAllocator struct contains private data. and should only be accessed using the following functions.

g_allocator_new ()

GAllocator* g_allocator_new               (const gchar *name, guint n_preallocs);

Creates a new GAllocator.

Note

Warning: g_allocator_new has been deprecated since version 2.10 and should not be used in newly-written code.
Use the slice allocator instead.

name : | the name of the GAllocator. This name is used to set the name of the GMemChunk used by the GAllocator, and is only used for debugging.
n_preallocs : | the number of elements in each block of memory allocated. Larger blocks mean less calls to g_malloc(), but some memory may be wasted. (GLib uses 128 elements per block by default.) The value must be between 1 and 65535.
Returns : | a new GAllocator.

g_allocator_free ()

void        g_allocator_free             (GAllocator *allocator);

Frees all of the memory allocated by the GAllocator.

Note

Warning: g_allocator_free has been deprecated since version 2.10 and should not be used in newly-written code. Use the slice allocator instead

allocator: : a GAllocator. .

Feedback

For additional information or queries on this page send feedback


Memory Chunks

Name

Memory Chunks — deprecated way to allocate groups of equal-sized chunks of memory.

Library

glib.lib

Synopsis

#include <glib.h>

GMemChunk;
#define     G_ALLOC_AND_FREE
#define     G_ALLOC_ONLY

GMemChunk*  g_mem_chunk_new                 (const gchar *name, gint atom_size, gulong area_size, gint type);
gpointer    g_mem_chunk_alloc               (GMemChunk *mem_chunk);
gpointer    g_mem_chunk_alloc0              (GMemChunk *mem_chunk);
void        g_mem_chunk_free                (GMemChunk *mem_chunk, gpointer mem);
void        g_mem_chunk_destroy             (GMemChunk *mem_chunk);

#define     g_mem_chunk_create              (type, pre_alloc, alloc_type)
#define     g_chunk_new                     (type, chunk)
#define     g_chunk_new0                    (type, chunk)
#define     g_chunk_free                    (mem, mem_chunk)

void        g_mem_chunk_reset               (GMemChunk *mem_chunk);
void        g_mem_chunk_clean               (GMemChunk *mem_chunk);
void        g_blow_chunks                   (void);

void        g_mem_chunk_info                (void);
void        g_mem_chunk_print               (GMemChunk *mem_chunk);

Detailed Description

Memory chunks provide an space-efficient way to allocate equal-sized pieces of memory, called atoms. However, due to the administrative overhead (in particular for G_ALLOC_AND_FREE, and when used from multiple threads), they are in practice often slower than direct use of g_malloc(). Therefore, memory chunks have been deprecated in favor of the slice allocator, which has been added in 2.10. All internal uses of memory chunks in GLib have been converted to the g_slice API.

There are two types of memory chunks, G_ALLOC_ONLY, and G_ALLOC_AND_FREE.

  • G_ALLOC_ONLY chunks only allow allocation of atoms. The atoms can never be freed individually. The memory chunk can only be free in its entirety.

  • G_ALLOC_AND_FREE chunks do allow atoms to be freed individually. The disadvantage of this is that the memory chunk has to keep track of which atoms have been freed. This results in more memory being used and a slight degradation in performance.

To create a memory chunk use g_mem_chunk_new() or the convenience macro g_mem_chunk_create().

To allocate a new atom use g_mem_chunk_alloc(), g_mem_chunk_alloc0(), or the convenience macros g_chunk_new() or g_chunk_new0().

To free an atom use g_mem_chunk_free(), or the convenience macro g_chunk_free(). (Atoms can only be freed if the memory chunk is created with the type set to G_ALLOC_AND_FREE.)

To free any blocks of memory which are no longer being used, use g_mem_chunk_clean(). To clean all memory chunks, use g_blow_chunks().

To reset the memory chunk, freeing all of the atoms, use g_mem_chunk_reset().

To destroy a memory chunk, use g_mem_chunk_destroy().

To help debug memory chunks, use g_mem_chunk_info() and g_mem_chunk_print().

Example 3. Using a GMemChunk

  GMemChunk *mem_chunk;
  gchar *mem[10000];
  gint i;

  /* Create a GMemChunk with atoms 50 bytes long, and memory blocks holding
     100 bytes. Note that this means that only 2 atoms fit into each memory
     block and so isn't very efficient. */
  mem_chunk = g_mem_chunk_new ("test mem chunk", 50, 100, G_ALLOC_AND_FREE);

  /* Now allocate 10000 atoms. */
  for (i = 0; i < 10000; i++)
    {
      mem[i] = g_chunk_new (gchar, mem_chunk);

      /* Fill in the atom memory with some junk. */
      for (j = 0; j < 50; j++)
    mem[i][j] = i * j;
    }

  /* Now free all of the atoms. Note that since we are going to destroy the
     GMemChunk, this wouldn't normally be used. */
  for (i = 0; i < 10000; i++)
    {
      g_mem_chunk_free (mem_chunk, mem[i]);
    }

  /* We are finished with the GMemChunk, so we destroy it. */
  g_mem_chunk_destroy (mem_chunk);

Example 4. Using a GMemChunk with data structures

  GMemChunk *array_mem_chunk;
  GRealArray *array;

  /* Create a GMemChunk to hold GRealArray structures, using the
     g_mem_chunk_create() convenience macro. We want 1024 atoms in each
     memory block, and we want to be able to free individual atoms. */
  array_mem_chunk = g_mem_chunk_create (GRealArray, 1024, G_ALLOC_AND_FREE);

  /* Allocate one atom, using the g_chunk_new() convenience macro. */
  array = g_chunk_new (GRealArray, array_mem_chunk);

  /* We can now use array just like a normal pointer to a structure. */
  array->data            = NULL;
  array->len             = 0;
  array->alloc           = 0;
  array->zero_terminated = (zero_terminated ? 1 : 0);
  array->clear           = (clear ? 1 : 0);
  array->elt_size        = elt_size;

  /* We can free the element, so it can be reused. */
  g_chunk_free (array, array_mem_chunk);

  /* We destroy the GMemChunk when we are finished with it. */
  g_mem_chunk_destroy (array_mem_chunk);

Details

GMemChunk

typedef struct _GMemChunk GMemChunk;
Note

Warning: GMemChunk is deprecated and should not be used in newly-written code.

The GMemChunk struct is an opaque data structure representing a memory chunk. It should be accessed only through the use of the following functions.

G_ALLOC_AND_FREE

#define G_ALLOC_AND_FREE  2
Note

Warning: G_ALLOC_AND_FREE is deprecated and should not be used in newly-written code.

Specifies the type of a GMemChunk. Used in g_mem_chunk_new() and g_mem_chunk_create() to specify that atoms will be freed individually.

G_ALLOC_ONLY

#define G_ALLOC_ONLY	  1
Note

Warning: G_ALLOC_ONLY is deprecated and should not be used in newly-written code.

Specifies the type of a GMemChunk. Used in g_mem_chunk_new() and g_mem_chunk_create() to specify that atoms will never be freed individually.

g_mem_chunk_new ()

GMemChunk*  g_mem_chunk_new             (const gchar *name, gint atom_size, gulong area_size, gint type);

Creates a new GMemChunk.

Note

Warning: g_mem_chunk_new has been deprecated since version 2.10 and should not be used in newly-written code. Use the slice allocator instead.

name : | a string to identify the GMemChunk. It is not copied so it should be valid for the lifetime of the GMemChunk. It is only used in g_mem_chunk_print(), which is used for debugging.
atom_size : | the size, in bytes, of each element in the GMemChunk.
area_size : | the size, in bytes, of each block of memory allocated to contain the atoms.
type : | the type of the GMemChunk. G_ALLOC_AND_FREE is used if the atoms will be freed individually. G_ALLOC_ONLY should be used if atoms will never be freed individually. G_ALLOC_ONLY is quicker, since it does not need to track free atoms, but it obviously wastes memory if many of the atoms are no longer needed.
Returns : | the new GMemChunk.

g_mem_chunk_alloc ()

gpointer    g_mem_chunk_alloc          (GMemChunk *mem_chunk);

Allocates an atom of memory from a GMemChunk.

Note

Warning: g_mem_chunk_alloc has been deprecated since version 2.10 and should not be used in newly-written code. Use g_slice_alloc() instead.

mem_chunk : | a GMemChunk.
Returns : | a pointer to the allocated atom.

g_mem_chunk_alloc0 ()

gpointer    g_mem_chunk_alloc0         (GMemChunk *mem_chunk);

Allocates an atom of memory from a GMemChunk, setting the memory to 0.

Note

Warning: g_mem_chunk_alloc0 has been deprecated since version 2.10 and should not be used in newly-written code. Use g_slice_alloc0() instead.

mem_chunk : | a GMemChunk.
Returns : | a pointer to the allocated atom.

g_mem_chunk_free ()

void        g_mem_chunk_free          (GMemChunk *mem_chunk, gpointer mem);

Frees an atom in a GMemChunk. This should only be called if the GMemChunk was created with G_ALLOC_AND_FREE. Otherwise it will simply return.

Note

Warning: g_mem_chunk_free has been deprecated since version 2.10 and should not be used in newly-written code. Use g_slice_free1() instead.

mem_chunk : | a GMemChunk.
mem : | a pointer to the atom to free.

g_mem_chunk_destroy ()

void        g_mem_chunk_destroy      (GMemChunk *mem_chunk);

Frees all of the memory allocated for a GMemChunk.

Note

Warning: g_mem_chunk_destroy has been deprecated since version 2.10 and should not be used in newly-written code. Use the slice allocator instead.

mem_chunk : a GMemChunk.

g_mem_chunk_create()

#define     g_mem_chunk_create(type, pre_alloc, alloc_type)

A convenience macro for creating a new GMemChunk. It calls g_mem_chunk_new(), using the given type to create the GMemChunk name. The atom size is determined using sizeof(), and the area size is calculated by multiplying the pre_alloc parameter with the atom size.

Note

Warning: g_mem_chunk_create has been deprecated since version 2.10 and should not be used in newly-written code. Use the slice allocator instead.

type : | the type of the atoms, typically a structure name.
pre_alloc : | the number of atoms to store in each block of memory.
alloc_type : | the type of the GMemChunk. G_ALLOC_AND_FREE is used if the atoms will be freed individually. G_ALLOC_ONLY should be used if atoms will never be freed individually. G_ALLOC_ONLY is quicker, since it does not need to track free atoms, but it obviously wastes memory if many of the atoms are no longer needed.
Returns : | the new GMemChunk.

g_chunk_new()

#define     g_chunk_new(type, chunk)

A convenience macro to allocate an atom of memory from a GMemChunk. It calls g_mem_chunk_alloc() and casts the returned atom to a pointer to the given type, avoiding a type cast in the source code.

Note

Warning: g_chunk_new has been deprecated since version 2.10 and should not be used in newly-written code. Use g_slice_new() instead.

type : | the type of the GMemChunk atoms, typically a structure name.
chunk : | a GMemChunk.
Returns : | a pointer to the allocated atom, cast to a pointer to type.

g_chunk_new0()

#define     g_chunk_new0(type, chunk)

A convenience macro to allocate an atom of memory from a GMemChunk. It calls g_mem_chunk_alloc0() and casts the returned atom to a pointer to the given type, avoiding a type cast in the source code.

Note

Warning: g_chunk_new0 has been deprecated since version 2.10 and should not be used in newly-written code. Use g_slice_new0() instead.

type : | the type of the GMemChunk atoms, typically a structure name.
chunk : | a GMemChunk.
Returns : | a pointer to the allocated atom, cast to a pointer to type.

g_chunk_free()

#define     g_chunk_free(mem, mem_chunk)

A convenience macro to free an atom of memory from a GMemChunk. It simply switches the arguments and calls g_mem_chunk_free() It is included simply to complement the other convenience macros, g_chunk_new() and g_chunk_new0().

Note

Warning: g_chunk_free has been deprecated since version 2.10 and should not be used in newly-written code. Use g_slice_free() instead.

mem : | a pointer to the atom to be freed.
mem_chunk : | a GMemChunk.

g_mem_chunk_reset ()

void        g_mem_chunk_reset               (GMemChunk *mem_chunk);

Resets a GMemChunk to its initial state. It frees all of the currently allocated blocks of memory.

Note

Warning: g_mem_chunk_reset has been deprecated since version 2.10 and should not be used in newly-written code. Use the slice allocator instead.

mem_chunk : a GMemChunk.

g_mem_chunk_clean ()

void        g_mem_chunk_clean           (GMemChunk *mem_chunk);

Frees any blocks in a GMemChunk which are no longer being used.

Note

Warning: g_mem_chunk_clean has been deprecated since version 2.10 and should not be used in newly-written code. Use the slice allocator instead.

mem_chunk : a GMemChunk.

g_blow_chunks ()

void        g_blow_chunks               (void);
Note

Warning: g_blow_chunks has been deprecated since version 2.10 and should not be used in newly-written code. Use the slice allocator instead.

Calls g_mem_chunk_clean() on all GMemChunk objects.

g_mem_chunk_info ()

void        g_mem_chunk_info          (void);
Note

Warning: g_mem_chunk_info has been deprecated since version 2.10 and should not be used in newly-written code. Use the slice allocator instead.

Outputs debugging information for all GMemChunk objects currently in use. It outputs the number of GMemChunk objects currently allocated, and calls g_mem_chunk_print() to output information on each one.

g_mem_chunk_print ()

void        g_mem_chunk_print        (GMemChunk *mem_chunk);

Outputs debugging information for a GMemChunk. It outputs the name of the GMemChunk (set with g_mem_chunk_new()), the number of bytes used, and the number of blocks of memory allocated.

mem_chunk : a GMemChunk.

Feedback

For additional information or queries on this page send feedback


Memory Slices

Name

Memory Slices — efficient way to allocate groups of equal-sized chunks of memory.

Library

glib.lib

Synopsis

#include <glib.h>

gpointer    g_slice_alloc                   (gsize block_size);
gpointer    g_slice_alloc0                  (gsize block_size);
void        g_slice_free1                   (gsize block_size, gpointer mem_block);
void        g_slice_free_chain_with_offset  (gsize block_size, gpointer mem_chain, gsize next_offset);

#define     g_slice_new                     (type)
#define     g_slice_new0                    (type)
#define     g_slice_free                    (type, mem)
#define     g_slice_free_chain              (type, mem_chain, next)

Description

Memory slices provide a space-efficient and multi-processing scalable way to allocate equal-sized pieces of memory, just like the original GMemChunks (from GLib <= 2.8), while avoiding their excessive memory-waste, scalability and performance problems.

To achieve these goals, the slice allocator uses a sophisticated, layered design that has been inspired by Bonwick's slab allocator [5]. It uses posix_memalign() to optimize allocations of many equally-sized chunks, and has per-thread free lists (the so-called magazine layer) to quickly satisfy allocation requests of already known structure sizes. This is accompanied by extra caching logic to keep freed memory around for some time before returning it to the system. Memory that is unused due to alignment constraints is used for cache colorization (random distribution of chunk addresses) to improve CPU cache utilization. The caching layer of the slice allocator adapts itself to high lock contention to improve scalability.

The slice allocator can allocate blocks as small as two pointers, and unlike malloc(), it does not reserve extra space per block. For large block sizes, g_slice_new() and g_slice_alloc() will automatically delegate to the system malloc() implementation. For newly written code it is recommended to use the new g_slice API instead of g_malloc() and friends, as long as objects are not resized during their lifetime and the object size used at allocation time is still available when freeing.

Example 1. Using the slice allocator

  gchar *mem[10000];
  gint i;

  /* Allocate 10000 blocks. */
  for (i = 0; i < 10000; i++)
    {
      mem[i] = g_slice_alloc (50);

      /* Fill in the memory with some junk. */
      for (j = 0; j < 50; j++)
    mem[i][j] = i * j;
    }

  /* Now free all of the blocks. */
  for (i = 0; i < 10000; i++)
    {
      g_slice_free1 (50, mem[i]);
    }

Example 2. Using the slice allocator with data structures

  GRealArray *array;

  /* Allocate one block, using the g_slice_new() macro. */
  array = g_slice_new (GRealArray);

  /* We can now use array just like a normal pointer to a structure. */
  array->data            = NULL;
  array->len             = 0;
  array->alloc           = 0;
  array->zero_terminated = (zero_terminated ? 1 : 0);
  array->clear           = (clear ? 1 : 0);
  array->elt_size        = elt_size;

  /* We can free the block, so it can be reused. */
  g_slice_free (GRealArray, array);

Details

g_slice_alloc ()

gpointer    g_slice_alloc                   (gsize block_size);

Allocates a block of memory from the slice allocator. The block address handed out is guaranteed to be aligned to at least 2 * sizeof (void*). Note that the underlying slice allocation mechanism can be changed with the G_SLICE=always-malloc environment variable.

block_size : | the number of bytes to allocate
Returns : | a pointer to the allocated memory block

g_slice_alloc0 ()

gpointer    g_slice_alloc0                  (gsize block_size);

Allocates a block of memory via g_slice_alloc() and initialize the returned memory to 0. Note that the underlying slice allocation mechanism can be changed with the G_SLICE=always-malloc environment variable.

block_size : | the number of bytes to allocate
Returns : | a pointer to the allocated block

g_slice_free1 ()

void        g_slice_free1                   (gsize block_size, gpointer mem_block);

Frees a block of memory. The memory must have been allocated via g_slice_alloc() or g_slice_alloc0() and the block_size has to match the size specified upon allocation. Note that the exact release behaviour can be changed with the G_DEBUG=gc-friendly environment variable.

block_size : | the size of the block
mem_block : | a pointer to the block to free

g_slice_free_chain_with_offset ()

void        g_slice_free_chain_with_offset  (gsize block_size, gpointer mem_chain, gsize next_offset);

Frees a linked list of memory blocks of structure type type. The memory blocks must be equal-sized, allocated via g_slice_alloc() or g_slice_alloc0() and linked together by a next pointer (similar to GSList). The offset of the next field in each block is passed as third argument. Note that the exact release behaviour can be changed with the G_DEBUG=gc-friendly environment variable.

block_size : | the size of the blocks
mem_chain : | a pointer to the first block of the chain
next_offset : | the offset of the next field in the blocks

g_slice_new()

#define     g_slice_new(type)

A convenience macro to allocate a block of memory from the slice allocator. It calls g_slice_alloc() with sizeof (type) and casts the returned pointer to a pointer of the given type, avoiding a type cast in the source code. Note that the underlying slice allocation mechanism can be changed with the G_SLICE=always-malloc environment variable.

type : | the type to allocate, typically a structure name
Returns : | a pointer to the allocated block, cast to a pointer to type.

g_slice_new0()

#define     g_slice_new0(type)

A convenience macro to allocate a block of memory from the slice allocator and set the memory to 0. It calls g_slice_alloc0() with sizeof (type) and casts the returned pointer to a pointer of the given type, avoiding a type cast in the source code. Note that the underlying slice allocation mechanism can be changed with the G_SLICE=always-malloc environment variable.

type : | the type to allocate, typically a structure name
Returns : | a pointer to the allocated block, cast to a pointer to type.

g_slice_free()

#define     g_slice_free(type, mem)

A convenience macro to free a block of memory that has been allocated from the slice allocator. It calls g_slice_free1() using sizeof (type) as the block size. Note that the exact release behaviour can be changed with the G_DEBUG=gc-friendly environment variable.

type : | the type of the block to free, typically a structure name
mem : |

g_slice_free_chain()

#define     g_slice_free_chain(type, mem_chain, next)

Frees a linked list of memory blocks of structure type type. The memory blocks must be equal-sized, allocated via g_slice_alloc() or g_slice_alloc0() and linked together by a next pointer (similar to GSList). The name of the next field in type is passed as third argument. Note that the exact release behaviour can be changed with the G_DEBUG=gc-friendly environment variable.

type : | the type of the mem_chain blocks
mem_chain : | a pointer to the first block of the chain
next : | the field name of the next pointer in type

Feedback

For additional information or queries on this page send feedback

[5] [Bonwick94] Jeff Bonwick, The slab allocator: An object-caching kernel memory allocator. USENIX 1994, and [Bonwick01] Bonwick and Jonathan Adams, Magazines and vmem: Extending the slab allocator to many CPU's and arbitrary resources. USENIX 2001


Message Logging

Name

Message Logging — versatile support for logging messages with different levels of importance.

Library

glib.lib

Synopsis

#include <glib.h>

#define     G_LOG_DOMAIN
#define     G_LOG_FATAL_MASK
#define     G_LOG_LEVEL_USER_SHIFT
void        (*GLogFunc)                     (const gchar *log_domain, GLogLevelFlags log_level, const gchar *message, gpointer user_data);
enum        GLogLevelFlags;

void        g_log                           (const gchar *log_domain, GLogLevelFlags log_level, const gchar *format, ...);
void        g_logv                          (const gchar *log_domain, GLogLevelFlags log_level, const gchar *format, va_list args);
#define     g_message                       (...)
#define     g_warning                       (...)
#define     g_critical                      (...)
#define     g_error                         (...)
#define     g_debug                         (...)

guint       g_log_set_handler               (const gchar *log_domain, GLogLevelFlags log_levels, GLogFunc log_func, gpointer user_data);
void        g_log_remove_handler            (const gchar *log_domain, guint handler_id);
GLogLevelFlags g_log_set_always_fatal       (GLogLevelFlags fatal_mask);
GLogLevelFlags g_log_set_fatal_mask         (const gchar *log_domain, GLogLevelFlags fatal_mask);
void        g_log_default_handler           (const gchar *log_domain, GLogLevelFlags log_level, const gchar *message, gpointer unused_data);
GLogFunc    g_log_set_default_handler       (GLogFunc log_func, gpointer user_data);

Detailed Description

These functions provide support for logging error messages or messages used for debugging.

There are several built-in levels of messages, defined in GLogLevelFlags. These can be extended with user-defined levels.

Examples

Adding a log handler for all warning messages in the default (application) domain
g_log_set_handler (NULL, G_LOG_LEVEL_WARNING | G_LOG_FLAG_FATAL | G_LOG_FLAG_RECURSION, my_log_handler, NULL);

Adding a log handler for all critical messages from GTK+
g_log_set_handler ("Gtk", G_LOG_LEVEL_CRITICAL | G_LOG_FLAG_FATAL | G_LOG_FLAG_RECURSION, my_log_handler, NULL);

Example 15. Adding a log handler for all messages from GLib
g_log_set_handler ("GLib", G_LOG_LEVEL_MASK | G_LOG_FLAG_FATAL | G_LOG_FLAG_RECURSION, my_log_handler, NULL);

Details

G_LOG_DOMAIN

#define G_LOG_DOMAIN    ((gchar*) 0)

Defines the log domain. For applications, this is typically left as the default NULL (or "") domain. Libraries should define this so that any messages which they log can be differentiated from messages from other libraries and application code. But be careful not to define it in any public header files.

For example, GTK+ uses this in its Makefile.am:

INCLUDES = -DG_LOG_DOMAIN=\"Gtk\"

G_LOG_FATAL_MASK

#define G_LOG_FATAL_MASK        (G_LOG_FLAG_RECURSION | G_LOG_LEVEL_ERROR)

GLib log levels that are considered fatal by default.

G_LOG_LEVEL_USER_SHIFT

#define G_LOG_LEVEL_USER_SHIFT  (8)

Log level shift offset for user defined log levels (0-7 are used by GLib).

GLogFunc ()

void        (*GLogFunc)             (const gchar *log_domain, GLogLevelFlags log_level, const gchar *message, gpointer user_data);

Specifies the prototype of log handler functions.

log_domain : | the log domain of the message.
log_level : | the log level of the message (including the fatal and recursion flags).
message : | the message to process.
user_data : | user data, set in g_log_set_handler().

enum GLogLevelFlags

typedef enum
{
  /* log flags */
  G_LOG_FLAG_RECURSION          = 1 << 0,
  G_LOG_FLAG_FATAL              = 1 << 1,

  /* GLib log levels */
  G_LOG_LEVEL_ERROR             = 1 << 2,       /* always fatal */
  G_LOG_LEVEL_CRITICAL          = 1 << 3,
  G_LOG_LEVEL_WARNING           = 1 << 4,
  G_LOG_LEVEL_MESSAGE           = 1 << 5,
  G_LOG_LEVEL_INFO              = 1 << 6,
  G_LOG_LEVEL_DEBUG             = 1 << 7,

  G_LOG_LEVEL_MASK              = ~(G_LOG_FLAG_RECURSION | G_LOG_FLAG_FATAL)
} GLogLevelFlags;

Flags specifying the level of log messages.

g_log ()

void        g_log           (const gchar *log_domain, GLogLevelFlags log_level, const gchar *format, ...);

Logs an error or debugging message. If the log level has been set as fatal, the abort() function is called to terminate the program.

log_domain : | the log domain, usually G_LOG_DOMAIN.
log_level : | the log level, either from GLogLevelFlags or a user-defined level.
format : | the message format. See the printf() documentation.
... : | the parameters to insert into the format string.

g_logv ()

void        g_logv            (const gchar *log_domain, GLogLevelFlags log_level, const gchar *format, va_list args);

Logs an error or debugging message. If the log level has been set as fatal, the abort() function is called to terminate the program.

log_domain : | the log domain.
log_level : | the log level.
format : | the message format. See the printf() documentation.
args : | the parameters to insert into the format string.

g_message()

#define     g_message(...)

A convenient function/macro to log a normal message.

... : format string, followed by parameters to insert into the format string (as with printf())

g_warning()

#define     g_warning(...)

A convenience function/macro to log a warning message.

... : format string, followed by parameters to insert into the format string (as with printf())

g_critical()

#define     g_critical(...)

Logs a "critical warning" (G_LOG_LEVEL_CRITICAL). It is more or less application-defined what constitutes a critical vs. a regular warning. Call g_log_set_always_fatal() to make critical warnings exit the program, then use g_critical() for fatal errors, for example.

... : format string, followed by parameters to insert into the format string (as with printf())

g_error()

#define     g_error(...)

A convenience function/macro to log an error message. Error messages are always fatal, resulting in a call to abort() to terminate the application. This function will result in a core dump; do not use it for errors expected. Using this function indicates a bug in the program, i.e. an assertion failure.

... : the parameters to insert into the format string.

g_debug()

#define     g_debug(...)

A convenience function/macro to log a debug message.

... : format string, followed by parameters to insert into the format string (as with printf())

g_log_set_handler ()

guint       g_log_set_handler           (const gchar *log_domain, GLogLevelFlags log_levels, GLogFunc log_func, gpointer user_data);

Sets the log handler for a domain and a set of log levels. To handle fatal and recursive messages the log_levels parameter must be combined with the G_LOG_FLAG_FATAL and G_LOG_FLAG_RECURSION bit flags.

Note that since the G_LOG_LEVEL_ERROR log level is always fatal,to set a handler for this log level combine it with G_LOG_FLAG_FATAL.

Example 13. Adding a log handler for all warning messages in the default (application) domain

  g_log_set_handler (NULL, G_LOG_LEVEL_WARNING | G_LOG_FLAG_FATAL
                     | G_LOG_FLAG_RECURSION, my_log_handler, NULL);

Example 14. Adding a log handler for all critical messages from GTK+

  g_log_set_handler ("Gtk", G_LOG_LEVEL_CRITICAL | G_LOG_FLAG_FATAL
                     | G_LOG_FLAG_RECURSION, my_log_handler, NULL);

Example 15. Adding a log handler for all messages from GLib

  g_log_set_handler ("GLib", G_LOG_LEVEL_MASK | G_LOG_FLAG_FATAL
                     | G_LOG_FLAG_RECURSION, my_log_handler, NULL);

log_domain : | the log domain, or NULL for the default "" application domain.
log_levels : | the log levels to apply the log handler for. To handle fatal and recursive messages as well, combine the log levels with the G_LOG_FLAG_FATAL and G_LOG_FLAG_RECURSION bit flags.
log_func : | the log handler function.
user_data : | data passed to the log handler.
Returns : | the id of the new handler.

g_log_remove_handler ()

void        g_log_remove_handler            (const gchar *log_domain, guint handler_id);

Removes the log handler.

log_domain : | the log domain.
handler_id : | the id of the handler, which was returned in g_log_set_handler().

g_log_set_always_fatal ()

GLogLevelFlags g_log_set_always_fatal       (GLogLevelFlags fatal_mask);

Sets the message levels which are always fatal, in any log domain. When a message with any of these levels is logged the program terminates. Set only the levels defined by GLib to be fatal. G_LOG_LEVEL_ERROR is always fatal.

fatal_mask : | the mask containing bits set for each level of error which is to be fatal.
Returns : | the old fatal mask.

g_log_set_fatal_mask ()

GLogLevelFlags g_log_set_fatal_mask         (const gchar *log_domain, GLogLevelFlags fatal_mask);

Sets the log levels which are fatal in the given domain. G_LOG_LEVEL_ERROR is always fatal.

log_domain : | the log domain.
fatal_mask : | the new fatal mask.
Returns : | the old fatal mask for the log domain.

g_log_default_handler ()

void        g_log_default_handler           (const gchar *log_domain, GLogLevelFlags log_level, const gchar *message, gpointer unused_data);

The default log handler set up by GLib; g_log_set_default_handler() allows to install an alternate default log handler. This is used if no log handler has been set for the particular log domain and log level combination. It outputs the message to stderr or stdout and if the log level is fatal it calls abort().

stderr is used for levels G_LOG_LEVEL_ERROR, G_LOG_LEVEL_CRITICAL, G_LOG_LEVEL_WARNING and G_LOG_LEVEL_MESSAGE. stdout is used for the rest.

log_domain : | the log domain of the message.
log_level : | the level of the message.
message : | the message.
unused_data : | data passed from g_log() which is unused.

g_log_set_default_handler ()

GLogFunc    g_log_set_default_handler       (GLogFunc log_func, gpointer user_data);

Installs a default log handler which is used is used if no log handler has been set for the particular log domain and log level combination. By default, GLib uses g_log_default_handler() as default log handler.

log_func : | the log handler function.
user_data : | data passed to the log handler.
Returns : | the previous default log handler

Feedback

For additional information or queries on this page send feedback


Miscellaneous Macros

Name

Miscellaneous Macros — specialized macros which are not used often.

Library

glib.lib

Synopsis

#include <glib.h>

#define     G_INLINE_FUNC

#define     G_STMT_START
#define     G_STMT_END

#define     G_BEGIN_DECLS
#define     G_END_DECLS

#define     G_N_ELEMENTS                    (arr)

#define     G_VA_COPY                       (ap1,ap2)

#define     G_STRINGIFY                     (macro_or_string)

#define     G_GNUC_EXTENSION
#define     G_GNUC_CONST
#define     G_GNUC_PURE
#define     G_GNUC_MALLOC
#define     G_GNUC_DEPRECATED
#define     G_GNUC_NORETURN
#define     G_GNUC_UNUSED
#define     G_GNUC_PRINTF                   ( format_idx, arg_idx )
#define     G_GNUC_SCANF                    ( format_idx, arg_idx )
#define     G_GNUC_FORMAT                   ( arg_idx )
#define     G_GNUC_NULL_TERMINATED
#define     G_GNUC_WARN_UNUSED_RESULT
#define     G_GNUC_FUNCTION
#define     G_GNUC_PRETTY_FUNCTION
#define     G_GNUC_NO_INSTRUMENT
#define     G_HAVE_GNUC_VISIBILITY
#define     G_GNUC_INTERNAL

#define     G_LIKELY                        (expr)
#define     G_UNLIKELY                      (expr)

#define     G_STRLOC
#define     G_STRFUNC

#define     G_GINT16_MODIFIER
#define     G_GINT16_FORMAT
#define     G_GUINT16_FORMAT
#define     G_GINT32_MODIFIER
#define     G_GINT32_FORMAT
#define     G_GUINT32_FORMAT
#define     G_GINT64_MODIFIER
#define     G_GINT64_FORMAT
#define     G_GUINT64_FORMAT
#define     G_GSIZE_MODIFIER
#define     G_GSIZE_FORMAT
#define     G_GSSIZE_FORMAT

Detailed Description

These macros provide more specialized features which are not needed so often by application programmers.

Details

G_INLINE_FUNC

#define     G_INLINE_FUNC

This macro is used to export function prototypes so they can be linked with an external version when no inlining is performed. The file which implements the functions should define G_IMPLEMENTS_INLINES before including the headers which contain G_INLINE_FUNC declarations. Since inlining is very compiler-dependent using these macros correctly is very difficult. Their use is strongly discouraged.

This macro is often mistaken for a replacement for the inline keyword; inline is already declared in a portable manner in the glib headers and can be used normally.

G_STMT_START

#define     G_STMT_START

Used within multi-statement macros so that they can be used in places where only one statement is expected by the compiler.

G_STMT_END

#define     G_STMT_END

Used within multi-statement macros so that they can be used in places where only one statement is expected by the compiler.

G_BEGIN_DECLS

#define     G_BEGIN_DECLS

Used (along with G_END_DECLS) to bracket header files. If the compiler in use is a C++ compiler, adds extern "C" around the header.

G_END_DECLS

#define     G_END_DECLS

Used (along with G_BEGIN_DECLS) to bracket header files. If the compiler in use is a C++ compiler, adds extern "C" around the header.

G_N_ELEMENTS()

#define G_N_ELEMENTS(arr)		(sizeof (arr) / sizeof ((arr)[0]))

Determines the number of elements in an array. The array must be declared so the compiler knows its size at compile-time; this macro will not work on an array allocated on the heap, only static arrays or arrays on the stack.

arr : the array

G_VA_COPY()

#define     G_VA_COPY(ap1,ap2)

Portable way to copy va_list variables.

In order to use this function, include string.h , because this macro may use memmove() and GLib does not include string.h.

ap1 : | the va_list variable to place a copy of ap2 in.
ap2 : | a va_list.

G_STRINGIFY()

#define G_STRINGIFY(macro_or_string)	G_STRINGIFY_ARG (macro_or_string)

Accepts a macro or a string and converts it into a string.

macro_or_string : a macro or a string.

G_GNUC_EXTENSION

#define     G_GNUC_EXTENSION

Expands to __extension__ when gcc is used as the compiler. This simply tells gcc not to warn about the following non-standard code when compiling with the -pedantic option.

G_GNUC_CONST

#define     G_GNUC_CONST

Expands to the GNU C const function attribute if the compiler is gcc. Declaring a function as const enables better optimization of calls to the function. A const function does not examine any values except its parameters, and has no effects except its return value. See the GNU C documentation for details.

Note

Note: A function that has pointer arguments and examines the data pointed to must not be declared const. Likewise, a function that calls a non-const function usually must not be const. It does not make sense for a const function to return void.

G_GNUC_PURE

#define     G_GNUC_PURE

Expands to the GNU C pure function attribute if the compiler is gcc. Declaring a function as pure enables better optimization of calls to the function. A pure function has no effects except its return value and the return value depends only on the parameters and/or global variables. See the GNU C documentation for details.

G_GNUC_MALLOC

#define     G_GNUC_MALLOC

Expands to the GNU C malloc function attribute if the compiler is gcc. Declaring a function as malloc enables better optimization of the function. A function can have the malloc attribute if it returns a pointer which is guaranteed to not alias with any other pointer when the function returns (in practice, this means newly allocated memory). See the GNU C documentation for details.

G_GNUC_DEPRECATED

#define     G_GNUC_DEPRECATED

Expands to the GNU C deprecated attribute if the compiler is gcc. It can be used to mark typedefs, variables and functions as deprecated. When called with the -Wdeprecated option, the compiler will generate warnings when deprecated interfaces are used. See the GNU C documentation for details.

G_GNUC_NORETURN

#define     G_GNUC_NORETURN

Expands to the GNU C noreturn function attribute if the compiler is gcc. It is used for declaring functions which never return. It enables optimization of the function, and avoids possible compiler warnings. See the GNU C documentation for details.

G_GNUC_UNUSED

#define     G_GNUC_UNUSED

Expands to the GNU C unused function attribute if the compiler is gcc. It is used for declaring functions which may never be used. It avoids possible compiler warnings. See the GNU C documentation for details.

G_GNUC_PRINTF()

#define     G_GNUC_PRINTF( format_idx, arg_idx )

Expands to the GNU C format function attribute if the compiler is gcc. This is used for declaring functions which take a variable number of arguments, with the same syntax as printf(). It allows the compiler to type-check the arguments passed to the function. See the GNU C documentation for details.

gint g_snprintf (gchar  *string, gulong  n, gchar const *format, ...)
G_GNUC_PRINTF (3, 4);
format_idx : | the index of the argument corresponding to the format string. (The arguments are numbered from 1).
arg_idx : | the index of the first of the format arguments.

G_GNUC_SCANF()

#define     G_GNUC_SCANF( format_idx, arg_idx )

Expands to the GNU C format function attribute if the compiler is gcc. This is used for declaring functions which take a variable number of arguments, with the same syntax as scanf(). It allows the compiler to type-check the arguments passed to the function. See the GNU C documentation for details.

format_idx : | the index of the argument corresponding to the format string. (The arguments are numbered from 1).
arg_idx : | the index of the first of the format arguments.

G_GNUC_FORMAT()

#define     G_GNUC_FORMAT( arg_idx )

Expands to the GNU C format_arg function attribute if the compiler is gcc. This function attribute specifies that a function takes a format string for a printf(), scanf(), strftime() or strfmon() style function and modifies it, so that the result can be passed to a printf(), scanf(), strftime() or strfmon() style function (with the remaining arguments to the format function the same as they would have been for the unmodified string). See the GNU C documentation for details.

gchar *g_dgettext (gchar *domain_name, gchar *msgid) G_GNUC_FORMAT (2);
arg_idx : the index of the argument.

G_GNUC_NULL_TERMINATED

#define     G_GNUC_NULL_TERMINATED

Expands to the GNU C sentinel function attribute if the compiler is gcc, or "" if it isn't. This function attribute only applies to variadic functions and instructs the compiler to check that the argument list is terminated with an explicit NULL. See the GNU C documentation for details.

G_GNUC_WARN_UNUSED_RESULT

#define     G_GNUC_WARN_UNUSED_RESULT

Expands to the GNU C warn_unused_ersult function attribute if the compiler is gcc, or "" if it isn't. This function attribute makes the compiler emit a warning if the result of a function call is ignored. See the GNU C documentation for details.

G_GNUC_FUNCTION

#define     G_GNUC_FUNCTION

Expands to the GNU C __FUNCTION__ variable if the compiler is gcc, or "" if it isn't. The GNU C __FUNCTION__ variable contains the name of the current function. See the GNU C documentation for details.

G_GNUC_PRETTY_FUNCTION

#define     G_GNUC_PRETTY_FUNCTION

Expands to the GNU C __PRETTY_FUNCTION__ variable if the compiler is gcc, or "" if it isn't. The GNU C __PRETTY_FUNCTION__ variable contains the name of the current function. For a C program this is the same as the __FUNCTION__ variable but for C++ it also includes extra information such as the class and function prototype. See the GNU C documentation for details.

G_GNUC_NO_INSTRUMENT

#define     G_GNUC_NO_INSTRUMENT

Expands to the GNU C no_instrument_function function attribute if the compiler is gcc. Functions with this attribute will not be instrumented for profiling, when the compiler is called with the -finstrument-functions option. See the GNU C documentation for details.

G_HAVE_GNUC_VISIBILITY

#define G_HAVE_GNUC_VISIBILITY 1

This macro is defined as 1 if the compiler supports ELF visibility attributes (currently only gcc).

G_GNUC_INTERNAL

#define G_GNUC_INTERNAL __attribute__((visibility("hidden")))

Expands to the GNU C visibility(hidden) attribute if the compiler supports it (currently only gcc). This attribute can be used for marking library functions as being used internally to the lib only, to not create inefficient PLT entries. Note that static functions do not need to be marked as internal in this way. See the GNU C documentation for details.

G_LIKELY()

#define     G_LIKELY(expr)

Hints the compiler that the expression is likely to evaluate to a true value. The compiler may use this information for optimizations.

if (G_LIKELY (random() != 1))
  g_print ("not one");
expr : the expression

G_UNLIKELY()

#define     G_UNLIKELY(expr)

Hints the compiler that the expression is unlikely to evaluate to a true value. The compiler may use this information for optimizations.

if (G_UNLIKELY (random() == 1))
  g_print ("a random one");
expr : the expression

G_STRLOC

#define     G_STRLOC

Expands to a string identifying the current code position.

G_STRFUNC

#define     G_STRFUNC

Expands to a string identifying the current function.

G_GINT16_MODIFIER

#define G_GINT16_MODIFIER "h"

The platform dependent length modifier for constructing printf() conversion specifiers for values of type gint16 or guint16. It is a string literal, but does not include the percent-sign, such that precision and length modifiers can be added between percent-sign and conversion specifier and append a conversion specifier.

The following example prints "0x7b";

gint16 value = 123;
g_print ("%#" G_GINT16_MODIFIER "x", value);

G_GINT16_FORMAT

#define G_GINT16_FORMAT "hi"

This is the platform dependent conversion specifier for scanning and printing values of type gint16. It is a string literal, but does not include the percent-sign, such that such that precision and length modifiers can be added between percent-sign and conversion specifier.

gint16 in;
gint32 out;
sscanf ("42", "%" G_GINT16_FORMAT, &in)
out = in * 1000;
g_print ("%" G_GINT32_FORMAT, out);

G_GUINT16_FORMAT

#define G_GUINT16_FORMAT "hu"

This is the platform dependent conversion specifier for scanning and printing values of type guint16. See also G_GINT16_FORMAT.

G_GINT32_MODIFIER

#define G_GINT32_MODIFIER ""

The platform dependent length modifier for constructing printf() conversion specifiers for values of type gint32 or guint32. See also G_GINT16_MODIFIER.

G_GINT32_FORMAT

#define G_GINT32_FORMAT "i"

This is the platform dependent conversion specifier for scanning and printing values of type gint32. See also G_GINT16_FORMAT.

G_GUINT32_FORMAT

#define G_GUINT32_FORMAT "u"

This is the platform dependent conversion specifier for scanning and printing values of type guint32. See also G_GINT16_FORMAT.

G_GINT64_MODIFIER

#define G_GINT64_MODIFIER "ll"

The platform dependent length modifier for constructing printf() conversion specifiers for values of type gint64 or guint64. See also G_GINT16_MODIFIER.

Note

Note: Some platforms do not support printing 64 bit integers, even though the types are supported. On such platforms G_GINT64_MODIFIER is not defined.

G_GINT64_FORMAT

#define G_GINT64_FORMAT "lli"

This is the platform dependent conversion specifier for scanning and printing values of type gint64. See also G_GINT16_FORMAT.

Note

Note: Some platforms do not support scanning and printing 64 bit integers, even though the types are supported. On such platforms G_GINT64_FORMAT is not defined. Note that scanf() may not support 64 bit integers, even if G_GINT64_FORMAT is defined. Due to its weak error handling, scanf() is not recommended for parsing anyway; consider using g_strtoull() instead.

G_GUINT64_FORMAT

#define G_GUINT64_FORMAT "llu"

This is the platform dependent conversion specifier for scanning and printing values of type guint64. See also G_GINT16_FORMAT.

G_GSIZE_MODIFIER

#define G_GSIZE_MODIFIER ""

The platform dependent length modifier for constructing printf() conversion specifiers for values of type gsize or gssize. See also G_GINT16_MODIFIER.

G_GSIZE_FORMAT

#define G_GSIZE_FORMAT "u"

This is the platform dependent conversion specifier for scanning and printing values of type gsize. See also G_GINT16_FORMAT.

G_GSSIZE_FORMAT

#define G_GSSIZE_FORMAT "i"

This is the platform dependent conversion specifier for scanning and printing values of type gssize. See also G_GINT16_FORMAT.

Feedback

For additional information or queries on this page send feedback


Miscellaneous Utility Functions

Name

Miscellaneous Utility Functions — Is a selection of portable utility functions

Library

glib.lib

Synopsis

#include <glib.h>

const gchar* g_get_application_name         (void);
void        g_set_application_name          (const gchar *application_name);
gchar*      g_get_prgname                   (void);
void        g_set_prgname                   (const gchar *prgname);
const gchar* g_getenv                       (const gchar *variable);
gboolean    g_setenv                        (const gchar *variable, const gchar *value, gboolean overwrite);
void        g_unsetenv                      (const gchar *variable);
gchar**     g_listenv                       (void);
const gchar* g_get_user_name                (void);
const gchar* g_get_real_name                (void);
const gchar* g_get_user_cache_dir           (void);
const gchar* g_get_user_data_dir            (void);
const gchar* g_get_user_config_dir          (void);
const gchar* const * g_get_system_data_dirs (void);
const gchar* const * g_get_system_config_dirs
                                            (void);

const gchar* g_get_host_name                (void);
const gchar* g_get_home_dir                 (void);
const gchar* g_get_tmp_dir                  (void);
gchar*      g_get_current_dir               (void);
const gchar* g_basename                     (const gchar *file_name);
#define     g_dirname
gboolean    g_path_is_absolute              (const gchar *file_name);
const gchar* g_path_skip_root               (const gchar *file_name);
gchar*      g_path_get_basename             (const gchar *file_name);
gchar*      g_path_get_dirname              (const gchar *file_name);
gchar*      g_build_filename                (const gchar *first_element, ...);
gchar*      g_build_filenamev               (gchar **args);
gchar*      g_build_path                    (const gchar *separator, const gchar *first_element, ...);
gchar*      g_build_pathv                   (const gchar *separator, gchar **args);

gchar*      g_find_program_in_path          (const gchar *program);

gint        g_bit_nth_lsf                   (gulong mask, gint nth_bit);
gint        g_bit_nth_msf                   (gulong mask, gint nth_bit);
guint       g_bit_storage                   (gulong number);

guint       g_spaced_primes_closest         (guint num);

void        g_atexit                        (GVoidFunc func);

guint       g_parse_debug_string            (const gchar *string, const GDebugKey *keys, guint nkeys);
GDebugKey;

void        (*GVoidFunc)                    (void);
void        (*GFreeFunc)                    (gpointer data);

void        g_qsort_with_data               (gconstpointer pbase, gint total_elems, gsize size, GCompareDataFunc compare_func, gpointer user_data);

void        g_nullify_pointer               (gpointer *nullify_location);

Detailed Description

These are portable utility functions.

Details

g_get_application_name ()

const gchar* g_get_application_name         (void);

Gets a human-readable name for the application, as set by g_set_application_name(). This name should be localized if possible, and is intended for display to the user. Contrast with g_get_prgname(), which gets a non-localized name. If g_set_application_name() has not been called, returns the result of g_get_prgname() (which may be NULL if g_set_prgname() has also not been called).

Returns : human-readable application name. may return NULL

g_set_application_name ()

void        g_set_application_name          (const gchar *application_name);

Sets a human-readable name for the application. This name should be localized if possible, and is intended for display to the user. Contrast with g_set_prgname(), which sets a non-localized name. g_set_prgname() will be called automatically by gtk_init(), but g_set_application_name() will not.

Note that for thread safety reasons, this function can only be called once.

The application name will be used in contexts such as error messages, or when displaying an application's name in the task list.

application_name : localized name of the application

g_get_prgname ()

gchar*      g_get_prgname                   (void);

Gets the name of the program. This name should not be localized, contrast with g_get_application_name(). (If using GDK or GTK+ the program name is set in gdk_init(), which is called by gtk_init(). The program name is found by taking the last component of argv[0].)

Returns : the name of the program. The returned string belongs to GLib and must not be modified or freed.

g_set_prgname ()

void        g_set_prgname                   (const gchar *prgname);

Sets the name of the program. This name should not be localized, contrast with g_set_application_name(). Note that for thread-safety reasons this function can only be called once.

prgname : the name of the program.

g_getenv ()

const gchar* g_getenv               (const gchar *variable);

Returns the value of an environment variable. The name and value are in the GLib file name encoding. On UNIX, this means the actual bytes which might or might not be in some consistent character set and encoding. On Windows, it is in UTF-8. On Windows, in case the environment variable's value contains references to other environment variables, they are expanded.

variable : | the environment variable to get, in the GLib file name encoding.
Returns : | the value of the environment variable, or NULL if the environment variable is not found. The returned string may be overwritten by the next call to g_getenv(), g_setenv() or g_unsetenv().

g_setenv ()

gboolean    g_setenv                 (const gchar *variable, const gchar *value, gboolean overwrite);

Sets an environment variable. Both the variable's name and value should be in the GLib file name encoding. On UNIX, this means that they can be any sequence of bytes. On Windows, they should be in UTF-8.

Note that on some systems, when variables are overwritten, the memory used for the previous variables and its value isn't reclaimed.

variable : | the environment variable to set, must not contain '='.
value : | the value for to set the variable to.
overwrite : | whether to change the variable if it already exists.
Returns : | FALSE if the environment variable couldn't be set.

g_unsetenv ()

void        g_unsetenv                      (const gchar *variable);

Removes an environment variable from the environment.

Note that on some systems, when variables are overwritten, the memory used for the previous variables and its value isn't reclaimed. Furthermore, this function cannot be guaranteed to operate in a threadsafe way.

variable : the environment variable to remove, must not contain '='.

g_listenv ()

gchar**     g_listenv                       (void);

Gets the names of all variables set in the environment.

Returns : a NULL-terminated list of strings which must be freed with g_strfreev().

g_get_user_name ()

const gchar* g_get_user_name                (void);

Gets the user name of the current user. The encoding of the returned string is system-defined. On UNIX, it might be the preferred file name encoding, or something else, and there is no guarantee that it is even consistent on a machine. On Windows, it is always UTF-8.

Returns : the user name of the current user.

g_get_real_name ()

const gchar* g_get_real_name                (void);

Gets the real name of the user. This usually comes from the user's entry in the passwd file. The encoding of the returned string is system-defined. (On Windows, it is, however, always UTF-8.) If the real user name cannot be determined, the string "Unknown" is returned.

Returns : the user's real name.

g_get_user_cache_dir ()

const gchar* g_get_user_cache_dir           (void);

Returns a base directory in which to store non-essential, cached data specific to particular user.

On UNIX platforms this is determined using the mechanisms described in the XDG Base Directory Specification

Returns : a string owned by GLib that must not be modified or freed.

g_get_user_data_dir ()

const gchar* g_get_user_data_dir            (void);

Returns a base directory in which to access application data such as icons that is customized for a particular user.

On UNIX platforms this is determined using the mechanisms described in the XDG Base Directory Specification

Returns : a string owned by GLib that must not be modified or freed.

g_get_user_config_dir ()

const gchar* g_get_user_config_dir          (void);

Returns a base directory in which to store user-specific application configuration information such as user preferences and settings.

On UNIX platforms this is determined using the mechanisms described in the XDG Base Directory Specification

Returns : a string owned by GLib that must not be modified or freed.

g_get_system_data_dirs ()

const gchar* const * g_get_system_data_dirs (void);

Returns an ordered list of base directories in which to access system-wide application data.

On UNIX platforms this is determined using the mechanisms described in the XDG Base Directory Specification

On Windows the first elements in the list are the Application Data and Documents folders for All Users. (These can be determined only on Windows 2000 or later and are not present in the list on other Windows versions.) See documentation for CSIDL_COMMON_APPDATA and CSIDL_COMMON_DOCUMENTS.

Then follows the "share" subfolder in the installation folder for the package containing the DLL that calls this function, if it can be determined.

Finally the list contains the "share" subfolder in the installation folder for GLib, and in the installation folder for the package the application's .exe file belongs to.

The installation folders above are determined by looking up the folder where the module (DLL or EXE) in question is located. If the folder's name is "bin", its parent is used, otherwise the folder itself.

Note that on Windows the returned list can vary depending on where this function is called.

Returns : a NULL-terminated array of strings owned by GLib that must not be modified or freed.

g_get_system_config_dirs ()

const gchar* const * g_get_system_config_dirs
                                            (void);

Returns an ordered list of base directories in which to access system-wide configuration information.

On UNIX platforms this is determined using the mechanisms described in the XDG Base Directory Specification

Returns : a NULL-terminated array of strings owned by GLib that must not be modified or freed.

g_get_host_name ()

const gchar* g_get_host_name                (void);

Return a name for the machine.

The returned name is not necessarily a fully-qualified domain name, or even present in DNS or some other name service at all. It need not even be unique on the local network or site, but usually it is. Callers should not rely on the return value having any specific properties like uniqueness for security purposes. Even if the name of the machine is changed while an application is running, the return value from this function does not change. The returned string is owned by GLib and should not be modified or freed. If no name can be determined, a default fixed string "localhost" is returned.

Returns : the host name of the machine.

g_get_home_dir ()

const gchar* g_get_home_dir                 (void);

Gets the current user's home directory.

Note that in contrast to traditional UNIX tools, this function prefers passwd entries over the HOME environment variable.

Returns : the current user's home directory.

g_get_tmp_dir ()

const gchar* g_get_tmp_dir                  (void);

Gets the directory to use for temporary files. This is found from inspecting the environment variables TMPDIR, TMP, and TEMP in that order. If none of those are defined "/tmp" is returned on UNIX and "C:\" on Windows. The encoding of the returned string is system-defined. On Windows, it is always UTF-8. The return value is never NULL.

Returns : the directory to use for temporary files.

g_get_current_dir ()

gchar*      g_get_current_dir               (void);

Gets the current directory. The returned string should be freed when no longer needed. The encoding of the returned string is system defined. On Windows, it is always UTF-8.

Returns : the current directory.

g_basename ()

const gchar* g_basename                     (const gchar *file_name);

Gets the name of the file without any leading directory components. It returns a pointer into the given file name string.

Note

Warning: g_basename has been deprecated since version 2.2 and should not be used in newly-written code. Use g_path_get_basename() instead, but notice that g_path_get_basename() allocates new memory for the returned string, unlike this function which returns a pointer into the argument.

file_name : | the name of the file.
Returns : | the name of the file without any leading directory components.

g_dirname

#define     g_dirname

This function is deprecated and will be removed in the next major release of GLib. Use g_path_get_dirname() instead.

Gets the directory components of a file name. If the file name has no directory components "." is returned. The returned string should be freed when no longer needed.

Note

Warning: g_dirname is deprecated and should not be used in newly-written code.

Returns : the directory components of the file.

g_path_is_absolute ()

gboolean    g_path_is_absolute              (const gchar *file_name);

Returns TRUE if the given file_name is an absolute file name, i.e. it contains a full path from the root directory such as "/usr/local" on UNIX or "C:\windows" on Windows systems.

file_name : | a file name.
Returns : | TRUE if file_name is an absolute path.

g_path_skip_root ()

const gchar* g_path_skip_root               (const gchar *file_name);

Returns a pointer into file_name after the root component, i.e. after the "/" in UNIX or "C:\" under Windows. If file_name is not an absolute path it returns NULL.

file_name : | a file name.
Returns : | a pointer into file_name after the root component.

g_path_get_basename ()

gchar*      g_path_get_basename             (const gchar *file_name);

Gets the last component of the filename. If file_name ends with a directory separator it gets the component before the last slash. If file_name consists only of directory separators (and on Windows, possibly a drive letter), a single separator is returned. If file_name is empty, it gets ".".

file_name : | the name of the file.
Returns : | a newly allocated string containing the last component of the filename.

g_path_get_dirname ()

gchar*      g_path_get_dirname              (const gchar *file_name);

Gets the directory components of a file name. If the file name has no directory components "." is returned. The returned string should be freed when no longer needed.

file_name : | the name of the file.
Returns : | the directory components of the file.

g_build_filename ()

gchar*      g_build_filename          (const gchar *first_element, ...);

Creates a filename from a series of elements using the correct separator for filenames.

On Unix, this function behaves identically to g_build_path (G_DIR_SEPARATOR_S, first_element, ....).

On Windows, it takes into account that either the backslash (\ or slash (/) can be used as separator in filenames, but otherwise behaves as on Unix. When file pathname separators need to be inserted, the one that last previously occurred in the parameters (reading from left to right) is used.

No attempt is made to force the resulting filename to be an absolute path. If the first element is a relative path, the result will be a relative path.

first_element : | the first element in the path
... : | remaining elements in path, terminated by NULL
Returns : | a newly-allocated string that must be freed with g_free().

g_build_filenamev ()

gchar*      g_build_filenamev               (gchar **args);

Behaves exactly like g_build_filename(), but takes the path elements as a string array, instead of varargs. This function is mainly meant for language bindings.

args : | NULL-terminated array of strings containing the path elements.
Returns : | a newly-allocated string that must be freed with g_free().

g_build_path ()

gchar*      g_build_path                    (const gchar *separator, const gchar *first_element, ...);

Creates a path from a series of elements using separator as the separator between elements. At the boundary between two elements, any trailing occurrences of separator in the first element, or leading occurrences of separator in the second element are removed and exactly one copy of the separator is inserted.

Empty elements are ignored.

The number of leading copies of the separator on the result is the same as the number of leading copies of the separator on the first non-empty element.

The number of trailing copies of the separator on the result is the same as the number of trailing copies of the separator on the last non-empty element. (Determination of the number of trailing copies is done without stripping leading copies, so if the separator is ABA, ABABA has 1 trailing copy.)

However, if there is only a single non-empty element, and there are no characters in that element not part of the leading or trailing separators, then the result is exactly the original value of that element.

Other than for determination of the number of leading and trailing copies of the separator, elements consisting only of copies of the separator are ignored.

separator : | a string used to separator the elements of the path.
first_element : | the first element in the path
... : | remaining elements in path, terminated by NULL
Returns : | a newly-allocated string that must be freed with g_free().

g_build_pathv ()

gchar*      g_build_pathv             (const gchar *separator, gchar **args);

Behaves exactly like g_build_path(), but takes the path elements as a string array, instead of varargs. This function is mainly meant for language bindings.

separator : | a string used to separator the elements of the path.
args : | NULL-terminated array of strings containing the path elements.
Returns : | a newly-allocated string that must be freed with g_free().

g_find_program_in_path ()

gchar*      g_find_program_in_path          (const gchar *program);

Locates the first executable named program in the user's path, in the same way that execvp() would locate it. Returns an allocated string with the absolute path name, or NULL if the program is not found in the path. If program is already an absolute path, returns a copy of program if program exists and is executable, and NULL otherwise. On Windows, if program does not have a file type suffix, tries with the suffixes .exe, .cmd, .bat and .com, and the suffixes in the PATHEXT environment variable.

On Windows, it looks for the file in the same way as CreateProcess() would. This means first in the directory where the executing program was loaded from, then in the current directory, then in the Windows 32-bit system directory, then in the Windows directory, and finally in the directories in the PATH environment variable. If the program is found, the return value contains the full name including the type suffix.

program : | a program name in the GLib file name encoding
Returns : | absolute path, or NULL

g_bit_nth_lsf ()

gint        g_bit_nth_lsf              (gulong mask, gint nth_bit);

Find the position of the first bit set in mask, searching from (but not including) nth_bit upwards. Bits are numbered from 0 (least significant) to sizeof(gulong) * 8 - 1 (31 or 63, usually). To start searching from the 0th bit, set nth_bit to -1.

mask : | a gulong containing flags.
nth_bit : | the index of the bit to start the search from.
Returns : | the index of the first bit set which is higher than nth_bit.

g_bit_nth_msf ()

gint        g_bit_nth_msf             (gulong mask, gint nth_bit);

Find the position of the first bit set in mask, searching from (but not including) nth_bit downwards. Bits are numbered from 0 (least significant) to sizeof(gulong) * 8 - 1 (31 or 63, usually). To start searching from the last bit, set nth_bit to -1 or GLIB_SIZEOF_LONG * 8.

mask : | a gulong containing flags.
nth_bit : | the index of the bit to start the search from.
Returns : | the index of the first bit set which is lower than nth_bit.

g_bit_storage ()

guint       g_bit_storage            (gulong number);

Gets the number of bits used to hold number, e.g. if number is 4, 3 bits are needed.

number : | a guint.
Returns : | the number of bits used to hold number.

g_spaced_primes_closest ()

guint     g_spaced_primes_closest         (guint num);

Gets the smallest prime number from a built-in array of primes which is larger than num. This is used within GLib to calculate the optimum size of a GHashTable.

The built-in array of primes ranges from 11 to 13845163 such that each prime is approximately 1.5-2 times the previous prime.

num : | a guint.
Returns : | the smallest prime number from a built-in array of primes which is larger than num.

g_atexit ()

void        g_atexit                    (GVoidFunc func);

Specifies a function to be called at normal program termination.

Since GLib 2.8.2, on Windows g_atexit() actually is a preprocessor macro that maps to a call to the atexit() function in the C library. This means that in case the code that calls g_atexit(), i.e. atexit(), is in a DLL, the function will be called when the DLL is detached from the program. This typically makes more sense than that the function is called when the GLib DLL is detached, which happened earlier when g_atexit() was a function in the GLib DLL.

The behaviour of atexit() in the context of dynamically loaded modules is not formally specified and varies wildly.

On POSIX systems, calling g_atexit() (or atexit()) in a dynamically loaded module which is unloaded before the program terminates might well cause a crash at program exit.

Some POSIX systems implement atexit() like Windows, and have each dynamically loaded module maintain an own atexit chain that is called when the module is unloaded.

On other POSIX systems, before a dynamically loaded module is unloaded, the registered atexit functions (if any) residing in that module are called, regardless where the code that registered them resided. This is presumably the most robust approach.

As can be seen from the above, for portability it's best to avoid calling g_atexit() (or atexit()) except in the main executable of a program.

func : the function to call on normal program termination.

g_parse_debug_string ()

guint       g_parse_debug_string            (const gchar *string, const GDebugKey *keys, guint nkeys);

Parses a string containing debugging options separated by ':' into a guint containing bit flags. This is used within GDK and GTK+ to parse the debug options passed on the command line or through environment variables.

string : | a list of debug options separated by ':' or "all" to set all flags.
keys : | pointer to an array of GDebugKey which associate strings with bit flags.
nkeys : | the number of GDebugKeys in the array.
Returns : | the combined set of bit flags.

GDebugKey

typedef struct {
  gchar *key;
  guint	 value;
} GDebugKey;

Associates a string with a bit flag. Used in g_parse_debug_string().

gchar *key; | the string
guint value; | the flag

GVoidFunc ()

void        (*GVoidFunc)                (void);

Declares a type of function which takes no arguments and has no return value. It is used to specify the type function passed to g_atexit().

GFreeFunc ()

void        (*GFreeFunc)                (gpointer data);

Declares a type of function which takes an arbitrary data pointer argument and has no return value. It is not currently used in GLib or GTK+.

data : a data pointer.

g_qsort_with_data ()

void       g_qsort_with_data          (gconstpointer pbase, gint total_elems, gsize size, GCompareDataFunc compare_func,
                                       gpointer user_data);

This is just like the standard C qsort() function, but the comparison routine accepts a user data argument.

pbase : | start of array to sort
total_elems : | elements in the array
size : | size of each element
compare_func : | function to compare elements
user_data : | data to pass to compare_func

g_nullify_pointer ()

void        g_nullify_pointer           (gpointer *nullify_location);

Set the pointer at the specified location to NULL.

nullify_location: the memory address of the pointer.

Feedback

For additional information or queries on this page send feedback


glib-mkenums

Name

glib-mkenums — C language enum description generation utility.

Library

gobject.lib

Synopsis

glib-mkenums [options...] [files...]

Detailed Description

glib-mkenums is a small perl-script utility that parses C code to extract enum definitions and produces enum descriptions based on text templates specified by the user. Most frequently this script is used to produce C code that contains enum values as strings so programs can provide value name strings for introspection.

Invocation

glib-mkenums takes a list of valid C code files as input. The options specified control the text that is output, certain substitutions are performed on the text templates for keywords enclosed in @ characters.

Options

--fhead text

Put out text prior to processing input files.

--fprod text

Put out text everytime a new input file is being processed.

--ftail text

Put out text after all input files have been processed.

--eprod text

Put out text everytime an enum is encountered in the input files.

--vhead text

Put out text before iterating over the set of values of an enum.

--vprod text

Put out text for every value of an enum.

--vtail text

Put out text after iterating over all values of an enum.

--comments text

Template for auto-generated comments, the default (for C code generations) is "/* @comment@ */".

--template file

Read templates from the given file. The templates are enclosed in specially-formatted C comments

/*** BEGIN section ***/
/*** END section ***/

where section may be file-header, file-production, file-tail, enumeration-production, value-header, value-production, value-tail or comment.

--help

Print brief help and exit.

--version

Print version and exit.

Production text substitutions

Certain keywords enclosed in @ characters will be substituted in the emitted text. For the substitution examples of the keywords below, the following example enum definition is assumed:

typedef enum
{
  PREFIX_THE_XVALUE    = 1 << 3,
  PREFIX_ANOTHER_VALUE = 1 << 4
} PrefixTheXEnum;

@EnumName@ | The name of the enum currently being processed, enum names are assumed to be properly namespaced and to use mixed capitalization to separate words (e.g. PrefixTheXEnum).
@enum_name@ | The enum name with words lowercase and word-separated by underscores (e.g. prefix_the_xenum).
@ENUMNAME@ | The enum name with words uppercase and word-separated by underscores (e.g. PREFIX_THE_XENUM).
@ENUMSHORT@ | The enum name with words uppercase and word-separated by underscores, prefix stripped (e.g. THE_XENUM).
@VALUENAME@ | The enum value name currently being processed with words uppercase and word-separated by underscores, this is the assumed literal notation of enum values in the C sources (e.g. PREFIX_THE_XVALUE).
@valuenick@ | A nick name for the enum value currently being processed, this is usually generated by stripping common prefix words of all the enum values of the current enum, the words are lowercase and underscores are substituted by a minus (e.g. the-xvalue).
@type@ | This is substituted either by "enum" or "flags", depending on whether the enum value definitions contained bit-shift operators or not (e.g. flags).
@Type@ | The same as @type@ with the first letter capitalized (e.g. Flags).
@TYPE@ | The same as @type@ with all letters uppercased (e.g. FLAGS).
@filename@ | The name of the input file currently being processed (e.g. foo.h).

Trigraph extensions

Some C comments are treated specially in the parsed enum definitions, such comments start out with the trigraph sequence /*< and end with the trigraph sequence >*/. Per enum definition, the options "skip" and "flags" can be specified, to indicate this enum definition to be skipped, or for it to be treated as a flags definition, or to specify the common prefix to be stripped from all values to generate value nicknames, respectively. The "lowercase_name" option can be used to specify the word separation used in the *_get_type() function. For instance, /*< lowercase_name=gnome_vfs_uri_hide_options >*/.

Per value definition, the options "skip" and "nick" are supported. The former causes the value to be skipped, and the latter can be used to specify the otherwise auto-generated nickname. Examples:

typedef enum /*< skip >*/
{
  PREFIX_FOO
} PrefixThisEnumWillBeSkipped;
typedef enum /*< flags,prefix=PREFIX >*/
{
  PREFIX_THE_ZEROTH_VALUE,	/*< skip >*/
  PREFIX_THE_FIRST_VALUE, PREFIX_THE_SECOND_VALUE,
  PREFIX_THE_THIRD_VALUE, /*< nick=the-last-value >*/
} PrefixTheFlagsEnum;

See also

glib-genmarshal( )

Feedback

For additional information or queries on this page send feedback


N-ary Trees

N-ary Trees — trees of data with any number of branches. More...

Synopsis

#include <glib.h>

            GNode;
GNode*      g_node_new                      (gpointer data);
GNode*      g_node_copy                     (GNode *node);
gpointer    (*GCopyFunc)                    (gconstpointer src, gpointer data);
GNode*      g_node_copy_deep                (GNode *node, GCopyFunc copy_func, gpointer data);

GNode*      g_node_insert                   (GNode *parent, gint position, GNode *node);
GNode*      g_node_insert_before            (GNode *parent, GNode *sibling, GNode *node);
GNode*      g_node_insert_after             (GNode *parent, GNode *sibling, GNode *node);
#define     g_node_append                   (parent, node)
GNode*      g_node_prepend                  (GNode *parent, GNode *node);

#define     g_node_insert_data              (parent, position, data)
#define     g_node_insert_data_before       (parent, sibling, data)
#define     g_node_append_data              (parent, data)
#define     g_node_prepend_data             (parent, data)

void        g_node_reverse_children         (GNode *node);
void        g_node_traverse                 (GNode *root, GTraverseType order, GTraverseFlags flags, gint max_depth, GNodeTraverseFunc func, gpointer data);
enum        GTraverseFlags;
gboolean    (*GNodeTraverseFunc)            (GNode *node, gpointer data);
void        g_node_children_foreach         (GNode *node, GTraverseFlags flags, GNodeForeachFunc func, gpointer data);
void        (*GNodeForeachFunc)             (GNode *node, gpointer data);

GNode*      g_node_get_root                 (GNode *node);
GNode*      g_node_find                     (GNode *root, GTraverseType order, GTraverseFlags flags, gpointer data);
GNode*      g_node_find_child               (GNode *node, GTraverseFlags flags, gpointer data);
gint        g_node_child_index              (GNode *node, gpointer data);
gint        g_node_child_position           (GNode *node, GNode *child);
#define     g_node_first_child              (node)
GNode*      g_node_last_child               (GNode *node);
GNode*      g_node_nth_child                (GNode *node, guint n);
GNode*      g_node_first_sibling            (GNode *node);
#define     g_node_next_sibling             (node)
#define     g_node_prev_sibling             (node)
GNode*      g_node_last_sibling             (GNode *node);

#define     G_NODE_IS_LEAF                  (node)
#define     G_NODE_IS_ROOT                  (node)
guint       g_node_depth                    (GNode *node);
guint       g_node_n_nodes                  (GNode *root, GTraverseFlags flags);
guint       g_node_n_children               (GNode *node);
gboolean    g_node_is_ancestor              (GNode *node, GNode *descendant);
guint       g_node_max_height               (GNode *root);

void        g_node_unlink                   (GNode *node);
void        g_node_destroy                  (GNode *root);

void        g_node_push_allocator           (GAllocator *allocator);
void        g_node_pop_allocator            (void);

Detailed Description

The GNode struct and its associated functions provide a N-ary tree data structure, where nodes in the tree can contain arbitrary data.

To create a new tree use g_node_new().

To insert a node into a tree use
g_node_insert(),
g_node_insert_before(),

g_node_append()
and g_node_prepend().

To create a new node and insert it into a tree use
g_node_insert_data(),
g_node_insert_data_before(),
g_node_append_data()
and g_node_prepend_data().

To reverse the children of a node use g_node_reverse_children().

To find a node use g_node_get_root(), g_node_find(),

g_node_find_child(),
g_node_child_index(), g_node_child_position(),
g_node_first_child(),

g_node_last_child(),

g_node_nth_child(),
g_node_first_sibling(),
g_node_prev_sibling(),
g_node_next_sibling() or
g_node_last_sibling().

To get information about a node or tree use
G_NODE_IS_LEAF(),
G_NODE_IS_ROOT(), g_node_depth(),

g_node_n_nodes(),

g_node_n_children(),
g_node_is_ancestor() or
g_node_max_height().

To traverse a tree, calling a function for each node visited in the traversal, use g_node_traverse() or g_node_children_foreach().

To remove a node or sub tree from a tree use g_node_unlink() or g_node_destroy().

Details

GNode

typedef struct {
  gpointer data;
  GNode	  *next;
  GNode	  *prev;
  GNode	  *parent;
  GNode	  *children;
} GNode;

The GNode struct represents one node in a N-ary Tree. The data field contains the actual data of the node. The next and prev fields point to the node's siblings (a sibling is another GNode with the same parent). The parent field points to the parent of the GNode, or is NULL if the GNode is the root of the tree. The children field points to the first child of the GNode. The other children are accessed by using the next pointer of each child.

g_node_new ()

GNode*      g_node_new                      (gpointer data);

Creates a new GNode containing the given data. Used to create the first node in a tree.

data : | the data of the new node.
Returns : | a new GNode.

g_node_copy ()

GNode*      g_node_copy                     (GNode *node);

Recursively copies a GNode (but does not deep-copy the data inside the nodes, see g_node_copy_deep() to do that).

node : | a GNode.
Returns : | a new GNode containing the same data pointers.

GCopyFunc ()

gpointer    (*GCopyFunc)                    (gconstpointer src, gpointer data);

A function of this signature is used to copy the node data when doing a deep-copy of a tree.

src : | A pointer to the data which should be copied.
data : | Additional data.
Returns : | A pointer to the copy.

g_node_copy_deep ()

GNode*      g_node_copy_deep                (GNode *node, GCopyFunc copy_func, gpointer data);

Recursively copies a GNode and its data.

node : | a GNode
copy_func : | the function which is called to copy the data inside each node, or NULL to use the original data.
data : | data to pass to copy_func
Returns : | a new GNode containing copies of the data in node.

g_node_insert ()

GNode*      g_node_insert                   (GNode *parent, gint position, GNode *node);

Inserts a GNode beneath the parent at the given position.

parent : | the GNode to place node under.
position : | the position to place node at, with respect to its siblings. If position is -1, node is inserted as the last child of parent.
node : | the GNode to insert.
Returns : | the inserted GNode.

g_node_insert_before ()

GNode*      g_node_insert_before            (GNode *parent, GNode *sibling, GNode *node);

Inserts a GNode beneath the parent before the given sibling.

parent : | the GNode to place node under.
sibling : | the sibling GNode to place node before. If sibling is NULL, the node is inserted as the last child of parent.
node : | the GNode to insert.
Returns : | the inserted GNode.

g_node_insert_after ()

GNode*      g_node_insert_after             (GNode *parent, GNode *sibling, GNode *node);

Inserts a GNode beneath the parent after the given sibling.

parent : | the GNode to place node under.
sibling : | the sibling GNode to place node after. If sibling is NULL, the node is inserted as the first child of parent.
node : | the GNode to insert.
Returns : | the inserted GNode.

g_node_append()

#define     g_node_append(parent, node)

Inserts a GNode as the last child of the given parent.

parent : | the GNode to place the new GNode under.
node : | the GNode to insert.
Returns : | the inserted GNode.

g_node_prepend ()

GNode*      g_node_prepend              (GNode *parent, GNode *node);

Inserts a GNode as the first child of the given parent.

parent : | the GNode to place the new GNode under.
node : | the GNode to insert.
Returns : | the inserted GNode.

g_node_insert_data()

#define     g_node_insert_data(parent, position, data)

Inserts a new GNode at the given position.

parent : | the GNode to place the new GNode under.
position : | the position to place the new GNode at. If position is -1, the new GNode is inserted as the last child of parent.
data : | the data for the new GNode.
Returns : | the new GNode.

g_node_insert_data_before()

#define     g_node_insert_data_before(parent, sibling, data)

Inserts a new GNode before the given sibling.

parent : | the GNode to place the new GNode under.
sibling : | the sibling GNode to place the new GNode before.
data : | the data for the new GNode.
Returns : | the new GNode.

g_node_append_data()

#define     g_node_append_data(parent, data)

Inserts a new GNode as the last child of the given parent.

parent : | the GNode to place the new GNode under.
data : | the data for the new GNode.
Returns : | the new GNode.

g_node_prepend_data()

#define     g_node_prepend_data(parent, data)

Inserts a new GNode as the first child of the given parent.

parent : | the GNode to place the new GNode under.
data : | the data for the new GNode.
Returns : | the new GNode.

g_node_reverse_children ()

void        g_node_reverse_children         (GNode *node);

Reverses the order of the children of a GNode. (It does not change the order of the grandchildren.)

node : a GNode.

g_node_traverse ()

void        g_node_traverse            (GNode *root, GTraverseType order, GTraverseFlags flags, gint max_depth, GNodeTraverseFunc func, gpointer data);

Traverses a tree starting at the given root GNode. It calls the given function for each node visited. The traversal can be halted at any point by returning TRUE from func.

root : | the root GNode of the tree to traverse.
order : | the order in which nodes are visited - G_IN_ORDER, G_PRE_ORDER, G_POST_ORDER, or G_LEVEL_ORDER.
flags : | which types of children are to be visited, one of G_TRAVERSE_ALL, G_TRAVERSE_LEAVES and G_TRAVERSE_NON_LEAVES.
max_depth : | the maximum depth of the traversal. Nodes below this depth will not be visited. If max_depth is -1 all nodes in the tree are visited. If depth is 1, only the root is visited. If depth is 2, the root and its children are visited. And so on.
func : | the function to call for each visited GNode.
data : | user data to pass to the function.

enum GTraverseFlags

typedef enum
{
  G_TRAVERSE_LEAVES     = 1 << 0,
  G_TRAVERSE_NON_LEAVES = 1 << 1,
  G_TRAVERSE_ALL        = G_TRAVERSE_LEAVES | G_TRAVERSE_NON_LEAVES,
  G_TRAVERSE_MASK       = 0x03,
  G_TRAVERSE_LEAFS      = G_TRAVERSE_LEAVES,
  G_TRAVERSE_NON_LEAFS  = G_TRAVERSE_NON_LEAVES
} GTraverseFlags;

Specifies which nodes are visited during several of the tree functions, including g_node_traverse() and g_node_find().

G_TRAVERSE_LEAVES | only leaf nodes should be visited. This name has been introduced in 2.6, for older version use G_TRAVERSE_LEAFS.
G_TRAVERSE_NON_LEAVES | only non-leaf nodes should be visited. This name has been introduced in 2.6, for older version use G_TRAVERSE_NON_LEAFS.
G_TRAVERSE_ALL | all nodes should be visited.
G_TRAVERSE_MASK |
G_TRAVERSE_LEAFS | identical to G_TRAVERSE_LEAVES
G_TRAVERSE_NON_LEAFS | identical to G_TRAVERSE_NON_LEAVES

GNodeTraverseFunc ()

gboolean    (*GNodeTraverseFunc)            (GNode *node, gpointer data);

Specifies the type of function passed to g_node_traverse(). The function is called with each of the nodes visited, together with the user data passed to g_node_traverse(). If the function returns TRUE, then the traversal is stopped.

node : | a GNode.
data : | user data passed to g_node_traverse().
Returns : | TRUE to stop the traversal.

g_node_children_foreach ()

void        g_node_children_foreach         (GNode *node, GTraverseFlags flags, GNodeForeachFunc func, gpointer data);

Calls a function for each of the children of a GNode. Note that it does not descend beneath the child nodes.

node : | a GNode.
flags : | which types of children are to be visited, one of G_TRAVERSE_ALL, G_TRAVERSE_LEAVES and G_TRAVERSE_NON_LEAVES.
func : | the function to call for each visited node.
data : | user data to pass to the function.

GNodeForeachFunc ()

void        (*GNodeForeachFunc)           (GNode *node, gpointer data);

Specifies the type of function passed to g_node_children_foreach(). The function is called with each child node, together with the user data passed to g_node_children_foreach().

node : | a GNode.
data : | user data passed to g_node_children_foreach().

g_node_get_root ()

GNode*      g_node_get_root             (GNode *node);

Gets the root of a tree.

node : | a GNode.
Returns : | the root of the tree.

g_node_find ()

GNode*      g_node_find                (GNode *root, GTraverseType order, GTraverseFlags flags, gpointer data);

Finds a GNode in a tree.

root : | the root GNode of the tree to search.
order : | the order in which nodes are visited - G_IN_ORDER, G_PRE_ORDER, G_POST_ORDER, or G_LEVEL_ORDER.
flags : | which types of children are to be searched, one of G_TRAVERSE_ALL, G_TRAVERSE_LEAVES and G_TRAVERSE_NON_LEAVES.
data : | the data to find.
Returns : | the found GNode, or NULL if the data is not found.

g_node_find_child ()

GNode*      g_node_find_child         (GNode *node, GTraverseFlags flags, gpointer data);

Finds the first child of a GNode with the given data.

node : | a GNode.
flags : | which types of children are to be searched, one of G_TRAVERSE_ALL, G_TRAVERSE_LEAVES and G_TRAVERSE_NON_LEAVES.
data : | the data to find.
Returns : | the found child GNode, or NULL if the data is not found.

g_node_child_index ()

gint        g_node_child_index        (GNode *node, gpointer data);

Gets the position of the first child of a GNode which contains the given data.

node : | a GNode.
data : | the data to find.
Returns : | the index of the child of node which contains data, or -1 if the data is not found.

g_node_child_position ()

gint        g_node_child_position      (GNode *node, GNode *child);

Gets the position of a GNode with respect to its siblings. child must be a child of node. The first child is numbered 0, the second 1, and so on.

node : | a GNode.
child : | a child of node.
Returns : | the position of child with respect to its siblings.

g_node_first_child()

#define     g_node_first_child(node)

Gets the first child of a GNode.

node : | a GNode.
Returns : | the last child of node, or NULL if node is NULL or has no children.

g_node_last_child ()

GNode*      g_node_last_child       (GNode *node);

Gets the last child of a GNode.

node : | a GNode (must not be NULL).
Returns : | the last child of node, or NULL if node has no children.

g_node_nth_child ()

GNode*      g_node_nth_child        (GNode *node, guint n);

Gets a child of a GNode, using the given index. The first child is at index 0. If the index is too big, NULL is returned.

node : | a GNode.
n : | the index of the desired child.
Returns : | the child of node at index n.

g_node_first_sibling ()

GNode*      g_node_first_sibling    (GNode *node);

Gets the first sibling of a GNode. This could possibly be the node itself.

node : | a GNode.
Returns : | the first sibling of node.

g_node_next_sibling()

#define     g_node_next_sibling(node)

Gets the next sibling of a GNode.

node : | a GNode.
Returns : | the next sibling of node, or NULL if node is NULL.

g_node_prev_sibling()

#define     g_node_prev_sibling(node)

Gets the previous sibling of a GNode.

node : | a GNode.
Returns : | the previous sibling of node, or NULL if node is NULL.

g_node_last_sibling ()

GNode*      g_node_last_sibling             (GNode *node);

Gets the last sibling of a GNode. This could possibly be the node itself.

node : | a GNode.
Returns : | the last sibling of node.

G_NODE_IS_LEAF()

#define	 G_NODE_IS_LEAF(node)	(((GNode*) (node))->children == NULL)

Returns TRUE if a GNode is a leaf node.

node : | a GNode.
Returns : | TRUE if the GNode is a leaf node (i.e. it has no children).

G_NODE_IS_ROOT()

#define     G_NODE_IS_ROOT(node)

Returns TRUE if a GNode is the root of a tree.

node : | a GNode.
Returns : | TRUE if the GNode is the root of a tree (i.e. it has no parent or siblings).

g_node_depth ()

guint       g_node_depth                    (GNode *node);

Gets the depth of a GNode.

If node is NULL the depth is 0. The root node has a depth of 1. For the children of the root node the depth is 2. And so on.

node : | a GNode.
Returns : | the depth of the GNode.

g_node_n_nodes ()

guint       g_node_n_nodes                  (GNode *root, GTraverseFlags flags);

Gets the number of nodes in a tree.

root : | a GNode.
flags : | which types of children are to be counted, one of G_TRAVERSE_ALL, G_TRAVERSE_LEAVES and G_TRAVERSE_NON_LEAVES.
Returns : | the number of nodes in the tree.

g_node_n_children ()

guint       g_node_n_children               (GNode *node);

Gets the number of children of a GNode.

node : | a GNode.
Returns : | the number of children of node.

g_node_is_ancestor ()

gboolean    g_node_is_ancestor              (GNode *node, GNode *descendant);

Returns TRUE if node is an ancestor of descendant. This is true if node is the parent of descendant, or if node is the grandparent of descendant etc.

node : | a GNode.
descendant : | a GNode.
Returns : | TRUE if node is an ancestor of descendant.

g_node_max_height ()

guint       g_node_max_height              (GNode *root);

Gets the maximum height of all branches beneath a GNode. This is the maximum distance from the GNode to all leaf nodes.
If root is NULL, 0 is returned. If root has no children, 1 is returned. If root has children, 2 is returned. And so on.

root : | a GNode.
Returns : | the maximum height of the tree beneath root.

g_node_unlink ()

void        g_node_unlink                  (GNode *node);

Unlinks a GNode from a tree, resulting in two separate trees.

node : the GNode to unlink, which becomes the root of a new tree.

g_node_destroy ()

void        g_node_destroy                  (GNode *root);

Removes the GNode and its children from the tree, freeing any memory allocated.

root : the root of the tree/subtree to destroy.

g_node_push_allocator ()

void        g_node_push_allocator           (GAllocator *allocator);

Sets the allocator to use to allocate GNode elements. Use g_node_pop_allocator() to restore the previous allocator.
Note that this function is not available if GLib has been compiled with --disable-mem-pools

allocator : the GAllocator to use when allocating GNode elements.

g_node_pop_allocator ()

void        g_node_pop_allocator           (void);

Restores the previous GAllocator, used when allocating GNode elements.
Note that this function is not available if GLib has been compiled with --disable-mem-pools

Feedback

For additional information or queries on this page send feedback


Numerical Definitions

Name

Numerical Definitions — mathematical constants, and floating point decomposition.

Library

glib.lib

Synopsis

#include <glib.h>

#define     G_IEEE754_FLOAT_BIAS
#define     G_IEEE754_DOUBLE_BIAS
union       GFloatIEEE754;
union       GDoubleIEEE754;

#define     G_E
#define     G_LN2
#define     G_LN10
#define     G_PI
#define     G_PI_2
#define     G_PI_4
#define     G_SQRT2
#define     G_LOG_2_BASE_10

Detailed Description

GLib offers mathematical constants such as G_PI for the value of pi; many platforms have these in the C library, but some don't, the GLib versions always exist.

The GFloatIEEE754 and GDoubleIEEE754 unions are used to access the sign, mantissa and exponent of IEEE floats and doubles. These unions are defined as appropriate for a given platform. IEEE floats and doubles are supported (used for storage) by at least Intel, PPC and Sparc, for reference: http://cch.loria.fr/documentation/IEEE754/numerical_comp_guide/ncg_math.doc.html

Details

G_IEEE754_FLOAT_BIAS

#define G_IEEE754_FLOAT_BIAS	(127)

See http://cch.loria.fr/documentation/IEEE754/numerical_comp_guide/ncg_math.doc.html

G_IEEE754_DOUBLE_BIAS

#define G_IEEE754_DOUBLE_BIAS	(1023)

See http://cch.loria.fr/documentation/IEEE754/numerical_comp_guide/ncg_math.doc.html

union GFloatIEEE754

union GFloatIEEE754
{
  gfloat v_float;
  struct {
    guint mantissa : 23;
    guint biased_exponent : 8;
    guint sign : 1;
  } mpn;
};

The GFloatIEEE754 and GDoubleIEEE754 unions are used to access the sign, mantissa and exponent of IEEE floats and doubles. These unions are defined as appropriate for a given platform. IEEE floats and doubles are supported (used for storage) by at least Intel, PPC and Sparc, for reference: http://cch.loria.fr/documentation/IEEE754/numerical_comp_guide/ncg_math.doc.html

union GDoubleIEEE754

union GDoubleIEEE754
{
  gdouble v_double;
  struct {
    guint mantissa_low : 32;
    guint mantissa_high : 20;
    guint biased_exponent : 11;
    guint sign : 1;
  } mpn;
};

The GFloatIEEE754 and GDoubleIEEE754 unions are used to access the sign, mantissa and exponent of IEEE floats and doubles. These unions are defined as appropriate for a given platform. IEEE floats and doubles are supported (used for storage) by at least Intel, PPC and Sparc, for reference: http://cch.loria.fr/documentation/IEEE754/numerical_comp_guide/ncg_math.doc.html

G_E

#define G_E     2.7182818284590452353602874713526624977572470937000

The base of natural logarithms.

G_LN2

#define G_LN2   0.69314718055994530941723212145817656807550013436026

The natural logarithm of 2.

G_LN10

#define G_LN10  2.3025850929940456840179914546843642076011014886288

The natural logarithm of 10.

G_PI

#define G_PI    3.1415926535897932384626433832795028841971693993751

The value of pi (ratio of circle's circumference to its diameter).

G_PI_2

#define G_PI_2  1.5707963267948966192313216916397514420985846996876

Pi divided by 2.

G_PI_4

#define G_PI_4  0.78539816339744830961566084581987572104929234984378

Pi divided by 4.

G_SQRT2

#define G_SQRT2 1.4142135623730950488016887242096980785696718753769

The square root of two.

G_LOG_2_BASE_10

#define G_LOG_2_BASE_10		(0.30102999566398119521)

Used for fooling around with float formats, see http://cch.loria.fr/documentation/IEEE754/numerical_comp_guide/ncg_math.doc.html

See Also

http://cch.loria.fr/documentation/IEEE754/numerical_comp_guide/ncg_math.doc.html

Feedback

For additional information or queries on this page send feedback


Pointer Arrays

Name

Pointer Arrays — arrays of pointers to any type of data, which grow automatically as new elements are added.

Library

glib.lib

Synopsis

#include <glib.h>

GPtrArray;
GPtrArray*  g_ptr_array_new                 (void);
GPtrArray*  g_ptr_array_sized_new           (guint reserved_size);
void        g_ptr_array_add                 (GPtrArray *array, gpointer data);
gboolean    g_ptr_array_remove              (GPtrArray *array, gpointer data);
gpointer    g_ptr_array_remove_index        (GPtrArray *array, guint index_);
gboolean    g_ptr_array_remove_fast         (GPtrArray *array, gpointer data);
gpointer    g_ptr_array_remove_index_fast   (GPtrArray *array, guint index_);
void        g_ptr_array_remove_range        (GPtrArray *array, guint index_, guint length);
void        g_ptr_array_sort                (GPtrArray *array, GCompareFunc compare_func);
void        g_ptr_array_sort_with_data      (GPtrArray *array, GCompareDataFunc compare_func, gpointer user_data);
void        g_ptr_array_set_size            (GPtrArray *array, gint length);
#define     g_ptr_array_index               (array,index_)
gpointer*   g_ptr_array_free                (GPtrArray *array, gboolean free_seg);
void        g_ptr_array_foreach             (GPtrArray *array, GFunc func, 99gpointer user_data);

Detailed Description

Pointer Arrays are similar to Arrays but are used only for storing pointers.

To create a pointer array, use g_ptr_array_new().

To add elements to a pointer array, use g_ptr_array_add().

To remove elements from a pointer array, use g_ptr_array_remove(), g_ptr_array_remove_index() or g_ptr_array_remove_index_fast().

To access an element of a pointer array, use g_ptr_array_index().

To set the size of a pointer array, use g_ptr_array_set_size().

To free a pointer array, use g_ptr_array_free().

Example 7. Using a GPtrArray

  GPtrArray *gparray;
  gchar *string1 = "one", *string2 = "two", *string3 = "three";

  gparray = g_ptr_array_new ();
  g_ptr_array_add (gparray, (gpointer) string1);
  g_ptr_array_add (gparray, (gpointer) string2);
  g_ptr_array_add (gparray, (gpointer) string3);

  if (g_ptr_array_index (gparray, 0) != (gpointer) string1)
    g_print ("ERROR: got %p instead of %p\n",
             g_ptr_array_index (gparray, 0), string1);

  g_ptr_array_free (gparray, TRUE);
Note

Note: If elements are removed from the array, elements at the end of the array are moved into the space previously occupied by the removed element. Do not rely on the index of particular elements remaining the same. Also be careful when deleting elements while iterating over the array.

Details

GPtrArray

typedef struct {
  gpointer *pdata;
  guint	    len;
} GPtrArray;

Contains the public fields of a pointer array.

gpointer *pdata; | points to the array of pointers, which may be moved when the array grows.
guint len; | number of pointers in the array.

g_ptr_array_new ()

GPtrArray*  g_ptr_array_new               (void);

Creates a new GPtrArray.

Returns : the new GPtrArray.

g_ptr_array_sized_new ()

GPtrArray*  g_ptr_array_sized_new           (guint reserved_size);

Creates a new GPtrArray with reserved_size pointers preallocated. This avoids frequent reallocation, if many pointers are to be added to the array. Note however that the size of the array is still 0.

reserved_size : | number of pointers preallocated.
Returns : | the new GPtrArray.

g_ptr_array_add ()

void        g_ptr_array_add                 (GPtrArray *array, gpointer data);

Adds a pointer to the end of the pointer array. The array will grow in size automatically if necessary.

array : | a GPtrArray.
data : | the pointer to add.

g_ptr_array_remove ()

gboolean    g_ptr_array_remove              (GPtrArray *array, gpointer data);

Removes the first occurrence of the given pointer from the pointer array. The following elements are moved down one place.

It returns TRUE if the pointer was removed, or FALSE if the pointer was not found.

array : | a GPtrArray.
data : | the pointer to remove.
Returns : | TRUE if the pointer is removed. FALSE if the pointer is not found in the array.

g_ptr_array_remove_index ()

gpointer    g_ptr_array_remove_index        (GPtrArray *array, guint index_);

Removes the pointer at the given index from the pointer array. The following elements are moved down one place.

array : | a GPtrArray.
index_ : | the index of the pointer to remove.
Returns : | the pointer which was removed.

g_ptr_array_remove_fast ()

gboolean    g_ptr_array_remove_fast         (GPtrArray *array, gpointer data);

Removes the first occurrence of the given pointer from the pointer array. The last element in the array is used to fill in the space, so this function does not preserve the order of the array. But it is faster than g_ptr_array_remove().

It returns TRUE if the pointer was removed, or FALSE if the pointer was not found.

array : | a GPtrArray.
data : | the pointer to remove.
Returns : | TRUE if the pointer was found in the array.

g_ptr_array_remove_index_fast ()

gpointer    g_ptr_array_remove_index_fast      (GPtrArray *array, guint index_);

Removes the pointer at the given index from the pointer array. The last element in the array is used to fill in the space, so this function does not preserve the order of the array. But it is faster than g_ptr_array_remove_index().

array : | a GPtrArray.
index_ : | the index of the pointer to remove.
Returns : | the pointer which was removed.

g_ptr_array_remove_range ()

void        g_ptr_array_remove_range        (GPtrArray *array, guint index_, guint length);

Removes the given number of pointers starting at the given index from a GPtrArray. The following elements are moved to close the gap.

array : | a GPtrArray.
index_ : | the index of the first pointer to remove.
length : | the number of pointers to remove.

g_ptr_array_sort ()

void        g_ptr_array_sort            (GPtrArray *array, GCompareFunc compare_func);

Sorts the array, using compare_func which should be a qsort()-style comparison function (returns less than zero for first arg is less than second arg, zero for equal, greater than zero if irst arg is greater than second arg).

If two array elements compare equal, their order in the sorted array is undefined.

Note

Note: The comparison function for g_ptr_array_sort() does not take the pointers from the array as arguments, it takes pointers to the pointers in the array.

array : | a GPtrArray.
compare_func : | comparison function.

g_ptr_array_sort_with_data ()

void        g_ptr_array_sort_with_data      (GPtrArray *array, GCompareDataFunc compare_func, gpointer user_data);

Like g_ptr_array_sort(), but the comparison function has an extra user data argument.

Note

Note: The comparison function for g_ptr_array_sort_with_data() does not take the pointers from the array as arguments, it takes pointers to the pointers in the array.

array : | a GPtrArray.
compare_func : | comparison function.
user_data : | data to pass to compare_func.

g_ptr_array_set_size ()

void        g_ptr_array_set_size            (GPtrArray *array, gint length);

Sets the size of the array, expanding it if necessary. New elements are set to NULL.

array : | a GPtrArray.
length : | the new length of the pointer array.

g_ptr_array_index()

#define     g_ptr_array_index(array,index_)

Returns the pointer at the given index of the pointer array.

array : | a GPtrArray.
index_ : | the index of the pointer to return.
Returns : | the pointer at the given index.

g_ptr_array_free ()

gpointer*   g_ptr_array_free                (GPtrArray *array, gboolean free_seg);

Frees all of the memory allocated for the pointer array.

array : | a GPtrArray.
free_seg : | if TRUE the array of pointers (pdata) is freed.
Returns : | NULL if free_seg is TRUE, otherwise the array of pointers (pdata) is returned.

g_ptr_array_foreach ()

void        g_ptr_array_foreach             (GPtrArray *array, GFunc func, gpointer user_data);

Calls a function for each element of a GPtrArray.

array : | a GPtrArray
func : | the function to call for each array element
user_data : | user data to pass to the function

Feedback

For additional information or queries on this page send feedback


Quarks

Name

Quarks — a 2-way association between a string and a unique integer identifier.

Library

glib.lib

Synopsis

#include <glib.h>

typedef      GQuark;
GQuark       g_quark_from_string             (const gchar *string);
GQuark       g_quark_from_static_string      (const gchar *string);
const gchar* g_quark_to_string               (GQuark quark);
GQuark       g_quark_try_string              (const gchar *string);
const gchar* g_intern_string                 (const gchar *string);
const gchar* g_intern_static_string          (const gchar *string);

Detailed Description

Quarks are associations between strings and integer identifiers. Given either the string or the GQuark identifier it is possible to retrieve the other.

Quarks are used for both Datasets and Keyed Data Lists.

To create a new quark from a string, use g_quark_from_string() or g_quark_from_static_string().

To find the string corresponding to a given GQuark, use g_quark_to_string().

To find the GQuark corresponding to a given string, use g_quark_try_string().

Another use for the string pool maintained for the quark functions is string interning, using g_intern_string() or g_intern_static_string() . An interned string is a canonical representation for a string. One important advantage of interned strings is that they can be compared for equality by a simple pointer comparison, rather than using strcmp().

Details

GQuark

typedef guint32 GQuark;

A GQuark is an integer which uniquely identifies a particular string.

g_quark_from_string ()

GQuark      g_quark_from_string             (const gchar *string);

Gets the GQuark identifying the given string. If the string does not currently have an associated GQuark, a new GQuark is created, using a copy of the string.

string : | a string.
Returns : | the GQuark identifying the string.

g_quark_from_static_string ()

GQuark      g_quark_from_static_string      (const gchar *string);

Gets the GQuark identifying the given (static) string. If the string does not currently have an associated GQuark, a new GQuark is created, linked to the given string.

Note that this function is identical to g_quark_from_string() except that if a new GQuark is created the string itself is used rather than a copy. This saves memory, but can only be used if the string will always exist. It can be used with statically allocated strings in the main program, but not with statically allocated memory in dynamically loaded modules, if expected to ever unload the module again (e.g. do not use this function in GTK+ theme engines).

string : | a string.
Returns : | the GQuark identifying the string.

g_quark_to_string ()

const gchar* g_quark_to_string              (GQuark quark);

Gets the string associated with the given GQuark.

quark : | a GQuark.
Returns : | the string associated with the GQuark.

g_quark_try_string ()

GQuark      g_quark_try_string              (const gchar *string);

Gets the GQuark associated with the given string, or 0 if the string has no associated GQuark.
To create GQuark if it does not already exist, use g_quark_from_string() or g_quark_from_static_string().

string : | a string.
Returns : | the GQuark associated with the string, or 0 if there is no GQuark associated with the string.

g_intern_string ()

const gchar* g_intern_string                (const gchar *string);

Returns a canonical representation for string. Interned strings can be compared for equality by comparing the pointers, instead of using strcmp().

string : | a string
Returns : | a canonical representation for the string

g_intern_static_string ()

const gchar* g_intern_static_string         (const gchar *string);

Returns a canonical representation for string. Interned strings can be compared for equality by comparing the pointers, instead of using strcmp(). g_intern_static_string() does not copy the string, therefore string must not be freed or modified.

string : | a static string
Returns : | a canonical representation for the string

Feedback

For additional information or queries on this page send feedback


Random Numbers

Name

Random Numbers — pseudo-random number generator.

Library

glib.lib

Synopsis

#include <glib.h>

GRand;
GRand*      g_rand_new_with_seed            (guint32 seed);
GRand*      g_rand_new_with_seed_array      (const guint32 *seed, guint seed_length);
GRand*      g_rand_new                      (void);
GRand*      g_rand_copy                     (GRand *rand_);
void        g_rand_free                     (GRand *rand_);
void        g_rand_set_seed                 (GRand *rand_, guint32 seed);
void        g_rand_set_seed_array           (GRand *rand_, const guint32 *seed, guint seed_length);
#define     g_rand_boolean                  (rand_)
guint32     g_rand_int                      (GRand *rand_);
gint32      g_rand_int_range                (GRand *rand_, gint32 begin, gint32 end);
gdouble     g_rand_double                   (GRand *rand_);
gdouble     g_rand_double_range             (GRand *rand_, gdouble begin, gdouble end);
void        g_random_set_seed               (guint32 seed);
#define     g_random_boolean                ()
guint32     g_random_int                    (void);
gint32      g_random_int_range              (gint32 begin, gint32 end);
gdouble     g_random_double                 (void);
gdouble     g_random_double_range           (gdouble begin, gdouble end);

Detailed Description

The following functions allow the use of a portable, fast and good pseudo-random number generator (PRNG). It uses the Mersenne Twister PRNG, which was originally developed by Makoto Matsumoto and Takuji Nishimura.

For a random number, call the g_random_* functions, which will create a globally used GRand and use the according g_rand_* functions internally. Whenever stream of reproducible random numbers are required, create a GRand and use the g_rand_* functions directly, which will also be slightly faster. Initializing a GRand with a certain seed will produce exactly the same series of random numbers on all platforms. This can thus be used as a seed for e.g. games.

The g_rand*_range functions will return high quality equally distributed random numbers, whereas for example the (g_random_int()%max) approach often does not yield equally distributed numbers.

GLib changed the seeding algorithm for the pseudo-random number generator Mersenne Twister, as used by GRand and GRandom. This was necessary, because some seeds would yield very bad pseudo-random streams. Also the pseudo-random integers generated by g_rand*_int_range() will have a slightly better equal distribution with the new version of GLib.

The original seeding and generation algorithms, as found in GLib 2.0.x, can be used instead of the new ones by setting the environment variable G_RANDOM_VERSION to the value of '2.0'. Use the GLib-2.0 algorithms only if the sequences of numbers generated with Glib-2.0 that are required to reproduce exactly.

Details

GRand

typedef struct _GRand GRand;

The GRand struct is an opaque data structure. It should only be accessed through the g_rand_* functions.

g_rand_new_with_seed ()

GRand* g_rand_new_with_seed (guint32 seed);

Creates a new random number generator initialized with seed.

seed : | a value to initialize the random number generator.
Returns : | the new GRand.

g_rand_new_with_seed_array ()

GRand*      g_rand_new_with_seed_array      (const guint32 *seed, guint seed_length);

Creates a new random number generator initialized with seed.

seed : | an array of seeds to initialize the random number generator.
seed_length : | an array of seeds to initialize the random number generator.
Returns : | the new GRand.

g_rand_new ()

GRand*      g_rand_new                      (void);

Creates a new random number generator initialized with a seed taken either from /dev/urandom (if existing) or from the current time (as a fallback).

Returns : the new GRand.

g_rand_copy ()

GRand*      g_rand_copy                     (GRand *rand_);

Copies a GRand into a new one with the same exact state as before. This way a snapshot of the random number generator can be taken for replaying later.

rand_ : | a GRand.
Returns : | the new GRand.

g_rand_free ()

void        g_rand_free                     (GRand *rand_);

Frees the memory allocated for the GRand.

rand_ : a GRand.

g_rand_set_seed ()

void        g_rand_set_seed                 (GRand *rand_, guint32 seed);

Sets the seed for the random number generator GRand to seed.

rand_ : | a GRand.
seed : | a value to reinitialize the random number generator.

g_rand_set_seed_array ()

void        g_rand_set_seed_array           (GRand *rand_, const guint32 *seed, guint seed_length);

Initializes the random number generator by an array of longs. Array can be of arbitrary size, though only the first 624 values are taken. This function is useful if there are many low entropy seeds, or if more than 32bits of actual entropy is required for the application.

rand_ : | a GRand.
seed : | array to initialize with
seed_length : | length of array

g_rand_boolean()

#define     g_rand_boolean(rand_)

Returns a random gboolean from rand_. This corresponds to a unbiased coin toss.

rand_ : | a GRand.
Returns : | a random gboolean.

g_rand_int ()

guint32     g_rand_int                      (GRand *rand_);

Returns the next random guint32 from rand_ equally distributed over the range [0..2^32-1].

rand_ : | a GRand.
Returns : | A random number.

g_rand_int_range ()

gint32      g_rand_int_range                (GRand *rand_, gint32 begin, gint32 end);

Returns the next random gint32 from rand_ equally distributed over the range [begin..end-1].

rand_ : | a GRand.
begin : | lower closed bound of the interval.
end : | upper open bound of the interval.
Returns : | A random number.

g_rand_double ()

gdouble     g_rand_double                   (GRand *rand_);

Returns the next random gdouble from rand_ equally distributed over the range [0..1).

rand_ : | a GRand.
Returns : | A random number.

g_rand_double_range ()

gdouble     g_rand_double_range             (GRand *rand_, gdouble begin, gdouble end);

Returns the next random gdouble from rand_ equally distributed over the range [begin..end).

rand_ : | a GRand.
begin : | lower closed bound of the interval.
end : | upper open bound of the interval.
Returns : | A random number.

g_random_set_seed ()

void        g_random_set_seed               (guint32 seed);

Sets the seed for the global random number generator, which is used by the g_random_* functions, to seed.

seed : a value to reinitialize the global random number generator.

g_random_boolean()

#define     g_random_boolean()

Returns a random gboolean. This corresponds to a unbiased coin toss.

Returns : a random gboolean.

g_random_int ()

guint32     g_random_int                    (void);

Return a random guint32 equally distributed over the range [0..2^32-1].

Returns : A random number.

g_random_int_range ()

gint32      g_random_int_range              (gint32 begin, gint32 end);

Returns a random gint32 equally distributed over the range [begin..end-1].

begin : | lower closed bound of the interval.
end : | upper open bound of the interval.
Returns : | A random number.

g_random_double ()

gdouble     g_random_double                 (void);

Returns a random gdouble equally distributed over the range [0..1).

Returns : A random number.

g_random_double_range ()

gdouble     g_random_double_range           (gdouble begin, gdouble end);

Returns a random gdouble equally distributed over the range [begin..end).

begin : | lower closed bound of the interval.
end : | upper open bound of the interval.
Returns : | A random number.

Feedback

For additional information or queries on this page send feedback


Relations and Tuples

Name

Relations and Tuples — tables of data which can be indexed on any number of fields.

Library

glib.lib

Synopsis

#include <glib.h>

GRelation;
GRelation*  g_relation_new                  (gint fields);
void        g_relation_index                (GRelation *relation, gint field, GHashFunc hash_func, GEqualFunc key_equal_func);
void        g_relation_insert               (GRelation *relation, ...);
gboolean    g_relation_exists               (GRelation *relation, ...);
gint        g_relation_count                (GRelation *relation, gconstpointer key, gint field);
GTuples*    g_relation_select               (GRelation *relation, gconstpointer key, gint field);
gint        g_relation_delete               (GRelation *relation, gconstpointer key, gint field);
void        g_relation_destroy              (GRelation *relation);

void        g_relation_print                (GRelation *relation);

GTuples;
void        g_tuples_destroy                (GTuples *tuples);
gpointer    g_tuples_index                  (GTuples *tuples, gint index_, gint field);

Detailed Description

A GRelation is a table of data which can be indexed on any number of fields, rather like simple database tables. A GRelation contains a number of records, called tuples. Each record contains a number of fields. Records are not ordered, so it is not possible to find the record at a particular index.

Note that GRelation tables are currently limited to 2 fields.

To create a GRelation, use g_relation_new().

To specify which fields should be indexed, use g_relation_index(). Note that this must be called before any tuples are added to the GRelation.

To add records to a GRelation use g_relation_insert().

To determine if a given record appears in a GRelation, use g_relation_exists(). Note that fields are compared directly, so pointers must point to the exact same position (i.e. different copies of the same string will not match.)

To count the number of records which have a particular value in a given field, use g_relation_count().

To get all the records which have a particular value in a given field, use g_relation_select(). To access fields of the resulting records, use g_tuples_index(). To free the resulting records use g_tuples_destroy().

To delete all records which have a particular value in a given field, use g_relation_delete().

To destroy the GRelation, use g_relation_destroy().

To help debug GRelation objects, use g_relation_print().

Details

GRelation

typedef struct _GRelation GRelation;

The GRelation struct is an opaque data structure to represent a Relation. It should only be accessed via the following functions.

g_relation_new ()

GRelation*  g_relation_new                  (gint fields);

Creates a new GRelation with the given number of fields. Note that currently the number of fields must be 2.

fields : | the number of fields.
Returns : | a new GRelation.

g_relation_index ()

void        g_relation_index                (GRelation *relation, gint field, GHashFunc hash_func, GEqualFunc key_equal_func);

Creates an index on the given field. Note that this must be called before any records are added to the GRelation.

relation : | a GRelation.
field : | the field to index, counting from 0.
hash_func : | a function to produce a hash value from the field data.
key_equal_func : | a function to compare two values of the given field.

g_relation_insert ()

void        g_relation_insert               (GRelation *relation, ...);

Inserts a record into a GRelation.

relation : | a GRelation.
... : | the fields of the record to add. These must match the number of fields in the GRelation and of type gpointer or gconstpointer

g_relation_exists ()

gboolean    g_relation_exists               (GRelation *relation, ...);

Returns TRUE if a record with the given values exists in a GRelation. Note that the values are compared directly, so that, for example, two copies of the same string will not match.

relation : | a GRelation.
... : | the fields of the record to compare. The number must match the number of fields in the GRelation.
Returns : | TRUE if a record matches.

g_relation_count ()

gint        g_relation_count                (GRelation *relation, gconstpointer key, gint field);

Returns the number of tuples in a GRelation that have the given value in the given field.

relation : | a GRelation.
key : | the value to compare with.
field : | the field of each record to match.
Returns : | the number of matches.

g_relation_select ()

GTuples*    g_relation_select               (GRelation *relation, gconstpointer key, gint field);

Returns all of the tuples which have the given key in the given field. Use g_tuples_index() to access the returned records. The returned records should be freed with g_tuples_destroy().

relation : | a GRelation.
key : | the value to compare with.
field : | the field of each record to match.
Returns : | the records (tuples) that matched.

g_relation_delete ()

gint        g_relation_delete               (GRelation *relation, gconstpointer key, gint field);

Deletes any records from a GRelation that have the given key value in the given field.

relation : | a GRelation.
key : | the value to compare with.
field : | the field of each record to match.
Returns : | the number of records deleted.

g_relation_destroy ()

void        g_relation_destroy              (GRelation *relation);

Destroys the GRelation, freeing all memory allocated. However, it does not free memory allocated for the tuple data, so free that first if appropriate.

relation : a GRelation.

g_relation_print ()

void        g_relation_print                (GRelation *relation);

Outputs information about all records in a GRelation, as well as the indexes. It is for debugging.

relation : a GRelation.

GTuples

typedef struct {
  guint len;
} GTuples;

The GTuples struct is used to return records (or tuples) from the GRelation by g_relation_select(). It only contains one public member - the number of records that matched. To access the matched records, use g_tuples_index().

guint len; the number of records that matched.

g_tuples_destroy ()

void        g_tuples_destroy                (GTuples *tuples);

Frees the records which were returned by g_relation_select(). This should always be called after g_relation_select() when finished with the records. The records are not removed from the GRelation.

tuples : the tuple data to free.

g_tuples_index ()

gpointer    g_tuples_index                  (GTuples *tuples, gint index_, gint field);

Gets a field from the records returned by g_relation_select(). It returns the given field of the record at the given index. The returned value should not be changed.

tuples : | the tuple data, returned by g_relation_select().
index_ : | the index of the record.
field : | the field to return.
Returns : | the field of the record.

Feedback

For additional information or queries on this page send feedback


Running GLib Applications

Running GLib Applications — How to run and debug your GLib application.

Running and debugging GLib Applications

Environment variables

GLib inspects a few of environment variables in addition to standard variables like LANG, PATH or HOME.

G_FILENAME_ENCODING. This environment variable can be set to a comma-separated list of character set names. GLib assumes that filenames are encoded in the first character set from that list rather than in UTF-8. The special token "@locale" can be used to specify the character set for the current locale.

G_BROKEN_FILENAMES. If this environment variable is set, GLib assumes that filenames are in the locale encoding rather than in UTF-8. G_FILENAME_ENCODING takes priority over G_BROKEN_FILENAMES.

G_MESSAGES_PREFIXED. A list of log levels for which messages should be prefixed by the program name and PID of the application. The default is to prefix everything except G_LOG_LEVEL_MESSAGE and G_LOG_LEVEL_INFO.

G_DEBUG. If GLib has been configured with --enable-debug=yes, this variable can be set to a list of debug options, which cause GLib to print out different types of debugging information.

fatal_warnings | Causes GLib to abort the program at the first call to g_warning() or g_critical(). This option is special in that it doesn't require GLib to be configured with debugging support.
fatal_criticals | Causes GLib to abort the program at the first call to g_critical(). This option is special in that it doesn't require GLib to be configured with debugging support.
gc-friendly | Newly allocated memory that isn't directly initialized, as well as memory being freed will be reset to 0. The point here is to allow memory checkers and similar programs that use bohem GC alike algorithms to produce more accurate results. This option is special in that it doesn't require GLib to be configured with debugging support.

G_SLICE. This environment variable allows reconfiguration of the #GSlice memory allocator.

always-malloc This will cause all slices allocated through g_slice_alloc() and released by g_slice_free1() to be actually allocated via direct calls to g_malloc() and g_free(). This is most useful for memory checkers and similar programs that use bohem GC alike algorithms to produce more accurate results. It can also be in conjunction with debugging features of the system's malloc implementation such as glib's MALLOC_CHECK_=2 to debug erroneous slice allocation code.

G_RANDOM_VERSION. If this environment variable is set to '2.0', the outdated pseudo-random number seeding and generation algorithms from GLib-2.0 are used instead of the new better ones. Use the GLib-2.0 algorithms only if you have sequences of numbers generated with Glib-2.0 that you need to reproduce exactly.

LIBCHARSET_ALIAS_DIR. Allows to specify a nonstandard location for the charset.aliases file that is used by the character set conversion routines. The default location is the libdir specified at compilation time.

G_WIN32_PRETEND_WIN9X. Setting this variable to any value forces g_win32_get_windows_version() to return a version code for Windows 9x. This is mainly an internal debugging aid for GTK+ and GLib developers, to be able to check the code paths for Windows 9x.

Traps and traces

Some code portions contain trap variables that can be set during debugging time if GLib has been configured with --enable-debug=yes. Such traps lead to immediate code halts to examine the current program state and back trace.

Currently, the following trap variables exist:

static volatile gulong g_trap_free_size;
static volatile gulong g_trap_realloc_size;
static volatile gulong g_trap_malloc_size;

If set to a size > 0, g_free(), g_realloc() and g_malloc() will be intercepted if the size matches the size of the corresponding memory block. This will only work with g_mem_set_vtable (glib_mem_profiler_table) upon startup though, because memory profiling is required to match on the memory block sizes.

Note that many modern debuggers support conditional breakpoints, which achieve pretty much the same. E.g. in gdb, you can do

break g_malloc
condition 1 n_bytes == 20

to break only on g_malloc() calls where the size of the allocated memory block is 20.


Shell-related Utilities

Name

Shell-related Utilities — shell-like command line handling.

Library

glib.lib

Synopsis

#include <glib.h>

enum        GShellError;
#define     G_SHELL_ERROR
gboolean    g_shell_parse_argv              (const gchar *command_line, gint *argcp, gchar ***argvp, GError **error);
gchar*      g_shell_quote                   (const gchar *unquoted_string);
gchar*      g_shell_unquote                 (const gchar *quoted_string, GError **error);

Detailed Description

Details

enum GShellError

typedef enum
{
  /* mismatched or otherwise mangled quoting */
  G_SHELL_ERROR_BAD_QUOTING,
  /* string to be parsed was empty */
  G_SHELL_ERROR_EMPTY_STRING,
  G_SHELL_ERROR_FAILED
} GShellError;

Error codes returned by shell functions.

G_SHELL_ERROR_BAD_QUOTING | Mismatched or otherwise mangled quoting.
G_SHELL_ERROR_EMPTY_STRING | String to be parsed was empty.
G_SHELL_ERROR_FAILED | Some other error.

G_SHELL_ERROR

#define G_SHELL_ERROR g_shell_error_quark ()

Error domain for shell functions. Errors in this domain will be from the GShellError enumeration. See GError for information on error domains.

g_shell_parse_argv ()

gboolean    g_shell_parse_argv              (const gchar *command_line, gint *argcp, gchar ***argvp, GError **error);

Parses a command line into an argument vector, in much the same way the shell would, but without many of the expansions the shell would perform (variable expansion, globs, operators, filename expansion, etc. are not supported). The results are defined to be the same as those obtained from a UNIX98 /bin/sh, as long as the input contains none of the unsupported shell expansions. If the input does contain such expansions, they are passed through literally. Possible errors are those from the G_SHELL_ERROR domain. Free the returned vector with g_strfreev().

command_line : | command line to parse
argcp : | return location for number of args
argvp : | return location for array of args
error : | return location for error
Returns : | TRUE on success, FALSE if error set

g_shell_quote ()

gchar*      g_shell_quote              (const gchar *unquoted_string);

Quotes a string so that the shell (/bin/sh) will interpret the quoted string to mean unquoted_string. If a filename is passed to the shell, for example, first quote it with this function. The return value must be freed with g_free(). The quoting style used is undefined (single or double quotes may be used).

unquoted_string : | a literal string
Returns : | quoted string

g_shell_unquote ()

gchar*      g_shell_unquote         (const gchar *quoted_string, GError **error);

Unquotes a string as the shell (/bin/sh) would. Only handles quotes; if a string contains file globs, arithmetic operators, variables, backticks, redirections, or other special-to-the-shell features, the result will be different from the result a real shell would produce (the variables, backticks, etc. will be passed through literally instead of being expanded). This function is guaranteed to succeed if applied to the result of g_shell_quote(). If it fails, it returns NULL and sets the error. The quoted_string need not actually contain quoted or escaped text; g_shell_unquote() simply goes through the string and unquotes/unescapes anything that the shell would. Both single and double quotes are handled, as are escapes including escaped newlines. The return value must be freed with g_free(). Possible errors are in the G_SHELL_ERROR domain.

Shell quoting rules are a bit strange. Single quotes preserve the literal string exactly. escape sequences are not allowed; not even \' - if include a ' in the quoted text, do something like 'foo'\''bar'. Double quotes allow $, `, ", \, and newline to be escaped with backslash. Otherwise double quotes preserve things literally.

quoted_string : | shell-quoted string
error : | error return location or NULL
Returns : | an unquoted string

Feedback

For additional information or queries on this page send feedback


Simple XML Subset Parser

Name

Simple XML Subset Parser — parses a subset of XML.

Library

glib.lib

Synopsis

#include <glib.h>

enum         GMarkupError;
#define      G_MARKUP_ERROR
enum         GMarkupParseFlags;
             GMarkupParseContext;
             GMarkupParser;
gchar*       g_markup_escape_text                       (const gchar *text, gssize length);
gchar*       g_markup_printf_escaped                    (const char *format, ...);
gchar*       g_markup_vprintf_escaped                   (const char *format, va_list args);
gboolean     g_markup_parse_context_end_parse           (GMarkupParseContext *context, GError **error);
void         g_markup_parse_context_free                (GMarkupParseContext *context);
void         g_markup_parse_context_get_position        (GMarkupParseContext *context, gint *line_number, gint *char_number);
const gchar* g_markup_parse_context_get_element         (GMarkupParseContext *context);
GMarkupParseContext* g_markup_parse_context_new         (const GMarkupParser *parser, GMarkupParseFlags flags,
                                                         gpointer user_data, GDestroyNotify user_data_dnotify);
gboolean     g_markup_parse_context_parse               (GMarkupParseContext *context, const gchar *text,
                                                         gssize text_len, GError **error);

Detailed Description

The "GMarkup" parser is intended to parse a simple markup format that is a subset of XML. This is a small, efficient, easy-to-use parser. It should not be used if inter-operatablity with other applications generating full-scale XML is expected. However, it's very useful for application data files, config files, etc. where it is known that the application will be the only one writing the file. Full-scale XML parsers should be able to parse the subset used by GMarkup, enabling the ease to migrate to full-scale XML at a later time if the need arises.

GMarkup is not guaranteed to signal an error on all invalid XML; the parser may accept documents that an XML parser would not. However, XML documents which are not well-formed[4] are not considered valid GMarkup documents.

Simplifications to XML include:

  • Only UTF-8 encoding is allowed.

  • No user-defined entities.

  • Processing instructions, comments and the doc type declaration are "passed through" but are not interpreted in any way.

  • No DTD or validation.

The markup format does support:

  • Elements

  • Attributes

  • 5 standard entities: &amp; &lt; &gt; &quot; &apos;

  • Character references

  • Sections marked as CDATA

Details

enum GMarkupError

typedef enum
{
  G_MARKUP_ERROR_BAD_UTF8, G_MARKUP_ERROR_EMPTY, G_MARKUP_ERROR_PARSE,
  /* These three are primarily intended for specific GMarkupParser
   * implementations to set.
   */
  G_MARKUP_ERROR_UNKNOWN_ELEMENT, G_MARKUP_ERROR_UNKNOWN_ATTRIBUTE, G_MARKUP_ERROR_INVALID_CONTENT
} GMarkupError;

Error codes returned by markup parsing.

G_MARKUP_ERROR_BAD_UTF8 | text being parsed was not valid UTF-8
G_MARKUP_ERROR_EMPTY | document contained nothing, or only white space
G_MARKUP_ERROR_PARSE | document was ill-formed
G_MARKUP_ERROR_UNKNOWN_ELEMENT | error should be set by GMarkupParser functions; element wasn't known
G_MARKUP_ERROR_UNKNOWN_ATTRIBUTE | error should be set by GMarkupParser functions; attribute wasn't known
G_MARKUP_ERROR_INVALID_CONTENT | error should be set by GMarkupParser functions; something was wrong with contents of the document, e.g. invalid attribute value

G_MARKUP_ERROR

#define G_MARKUP_ERROR g_markup_error_quark ()

Error domain for markup parsing. Errors in this domain will be from the GMarkupError enumeration. See GError for information on error domains.

enum GMarkupParseFlags

typedef enum
{
  /* Hmm, cannot think of any at the moment */
  G_MARKUP_DO_NOT_USE_THIS_UNSUPPORTED_FLAG = 1 << 0

} GMarkupParseFlags;

There are no flags right now. Pass "0" for the flags argument to all functions.

G_MARKUP_DO_NOT_USE_THIS_UNSUPPORTED_FLAG flag that should not be used.

GMarkupParseContext

typedef struct _GMarkupParseContext GMarkupParseContext;

A parse context is used to parse a stream of bytes that are expected to contain marked-up text. See g_markup_parse_context_new(), GMarkupParser, and so on for more details.

GMarkupParser

typedef struct {
  /* Called for open tags <foo bar="baz"> */
  void (*start_element)  (GMarkupParseContext *context, const gchar  *element_name, const gchar   **attribute_names,
                          const gchar        **attribute_values, gpointer user_data, GError  **error);

  /* Called for close tags </foo> */
  void (*end_element)    (GMarkupParseContext *context, const gchar  *element_name, gpointer  user_data, GError  **error);

  /* Called for character data */
  /* text is not nul-terminated */
  void (*text)           (GMarkupParseContext *context, const gchar  *text, gsize  text_len, gpointer  user_data, GError  **error);

  /* Called for strings that should be re-saved verbatim in this same
   * position, but are not otherwise interpretable.  At the moment
   * this includes comments and processing instructions.
   */
  /* text is not nul-terminated. */
  void (*passthrough)    (GMarkupParseContext *context, const gchar  *passthrough_text, gsize  text_len, gpointer  user_data, GError **error);

  /* Called on error, including one set by other
   * methods in the vtable. The GError should not be freed.
   */
  void (*error)          (GMarkupParseContext *context, GError  *error, gpointer  user_data);
} GMarkupParser;

Any of the fields in GMarkupParser can be NULL, in which case they will be ignored. Except for the error function, any of these callbacks can set an error; in particular the G_MARKUP_ERROR_UNKNOWN_ELEMENT, G_MARKUP_ERROR_UNKNOWN_ATTRIBUTE, and G_MARKUP_ERROR_INVALID_CONTENT errors are intended to be set from these callbacks. If an error from a callback is set, g_markup_parse_context_parse() will report that error back to its caller.

start_element () | Callback to invoke when the opening tag of an element is seen.
end_element () | Callback to invoke when the closing tag of an element is seen
text () | Callback to invoke when some text is seen (text is always inside an element)
passthrough () | Callback to invoke for comments, processing instructions and doc type declarations; if you're re-writing the parsed document, write the passthrough text back out in the same position
error () | Callback to invoke when an error occurs

g_markup_escape_text ()

gchar*      g_markup_escape_text      (const gchar *text, gssize length);

Escapes text so that the markup parser will parse it verbatim. Less than, greater than, ampersand, etc. are replaced with the corresponding entities. This function would typically be used when writing out a file to be parsed with the markup parser.

Note that this function does not protect white space and line endings from being processed according to the XML rules for normalization of line endings and attribute values.

text : | some valid UTF-8 text
length : | length of text in bytes, or -1 if the text is nul-terminated
Returns : | a newly allocated string with the escaped text

g_markup_printf_escaped ()

gchar*      g_markup_printf_escaped         (const char *format, ...);

Formats arguments according to format, escaping all string and character arguments in the fashion of g_markup_escape_text(). This is useful to insert literal strings into XML-style markup output, without having to worry that the strings might themselves contain markup.

const char *store = "Fortnum & Mason";
const char *item = "Tea";
char *output;

output = g_markup_printf_escaped ("<purchase>"
                                  "<store>%s</store>"
                                  "<item>%s</item>"
                                  "</purchase>",
                                  store, item);

format : | printf() style format string
... : | the arguments to insert in the format string
Returns : | newly allocated result from formatting operation. Free with g_free().

g_markup_vprintf_escaped ()

gchar*      g_markup_vprintf_escaped        (const char *format, va_list args);

Formats the data in args according to format, escaping all string and character arguments in the fashion of g_markup_escape_text(). See g_markup_printf_escaped().

format : | printf() style format string
args : | variable argument list, similar to vprintf()
Returns : | newly allocated result from formatting operation. Free with g_free().

g_markup_parse_context_end_parse ()

gboolean    g_markup_parse_context_end_parse
                                            (GMarkupParseContext *context, GError **error);

Signals to the GMarkupParseContext that all data has been fed into the parse context with g_markup_parse_context_parse(). This function reports an error if the document isn't complete, for example if elements are still open.

context : | a GMarkupParseContext
error : | return location for a GError
Returns : | TRUE on success, FALSE if an error was set

g_markup_parse_context_free ()

void      g_markup_parse_context_free            (GMarkupParseContext *context);

Frees a GMarkupParseContext. cannot be called from inside one of the GMarkupParser functions.

context : a GMarkupParseContext

g_markup_parse_context_get_position ()

void      g_markup_parse_context_get_position     (GMarkupParseContext *context, gint *line_number, gint *char_number);

Retrieves the current line number and the number of the character on that line. Intended for use in error messages; there are no strict semantics for what constitutes the "current" line number other than "the best number we could come up with for error messages."

context : | a GMarkupParseContext
line_number : | return location for a line number, or NULL
char_number : | return location for a char-on-line number, or NULL

g_markup_parse_context_get_element ()

const gchar* g_markup_parse_context_get_element   (GMarkupParseContext *context);

Retrieves the name of the currently open element.

context : | a GMarkupParseContext
Returns : | the name of the currently open element, or NULL

g_markup_parse_context_new ()

GMarkupParseContext* g_markup_parse_context_new     (const GMarkupParser *parser, GMarkupParseFlags flags, gpointer user_data, GDestroyNotify user_data_dnotify);

Creates a new parse context. A parse context is used to parse marked-up documents. Any number of documents can be fed into a context, as long as no errors occur; once an error occurs, the parse context cannot continue to parse text (it has to be freed and a new parse context created).

parser : | a GMarkupParser
flags : | one or more GMarkupParseFlags
user_data : | user data to pass to GMarkupParser functions
user_data_dnotify : | user data destroy notifier called when the parse context is freed
Returns : | a new GMarkupParseContext

g_markup_parse_context_parse ()

gboolean    g_markup_parse_context_parse    (GMarkupParseContext *context, const gchar *text, gssize text_len, GError **error);

Feed some data to the GMarkupParseContext. The data need not be valid UTF-8; an error will be signaled if it is invalid. The data need not be an entire document; a document can be fed into the parser incrementally, via multiple calls to this function. Typically, as the data is received from a network connection or file, feed each received chunk of data into this function, aborting the process if an error occurs. Once an error is reported, no further data may be fed to the GMarkupParseContext; all errors are fatal.

context : | a GMarkupParseContext
text : | chunk of text to parse
text_len : | length of text in bytes
error : | return location for a GError
Returns : | FALSE if an error occurred, TRUE on success

Feedback

For additional information or queries on this page send feedback

[ 4] XML specification


Singly-Linked Lists

Name

Singly-Linked Lists — linked lists containing integer values or pointers to data, limited to iterating over the list in one direction.

Library

glib.lib

Synopsis

#include <glib.h>

            GSList;
GSList*     g_slist_alloc                   (void);
GSList*     g_slist_append                  (GSList *list, gpointer data);
GSList*     g_slist_prepend                 (GSList *list, gpointer data);
GSList*     g_slist_insert                  (GSList *list, gpointer data, gint position);
GSList*     g_slist_insert_before           (GSList *slist, GSList *sibling, gpointer data);
GSList*     g_slist_insert_sorted           (GSList *list, gpointer data, GCompareFunc func);
GSList*     g_slist_remove                  (GSList *list, gconstpointer data);
GSList*     g_slist_remove_link             (GSList *list, GSList *link_);
GSList*     g_slist_delete_link             (GSList *list, GSList *link_);
GSList*     g_slist_remove_all              (GSList *list, gconstpointer data);
void        g_slist_free                    (GSList *list);
void        g_slist_free_1                  (GSList *list);
#define     g_slist_free1

guint       g_slist_length                  (GSList *list);
GSList*     g_slist_copy                    (GSList *list);
GSList*     g_slist_reverse                 (GSList *list);
GSList*     g_slist_insert_sorted_with_data (GSList *list, gpointer data, GCompareDataFunc func, gpointer user_data);

GSList*     g_slist_sort                    (GSList *list, GCompareFunc compare_func);
GSList*     g_slist_sort_with_data          (GSList *list, GCompareDataFunc compare_func, gpointer user_data);
GSList*     g_slist_concat                  (GSList *list1, GSList *list2);
void        g_slist_foreach                 (GSList *list, GFunc func, gpointer user_data);

GSList*     g_slist_last                    (GSList *list);
#define     g_slist_next                    (slist)
GSList*     g_slist_nth                     (GSList *list, guint n);
gpointer    g_slist_nth_data                (GSList *list, guint n);

GSList*     g_slist_find                    (GSList *list, gconstpointer data);
GSList*     g_slist_find_custom             (GSList *list, gconstpointer data, GCompareFunc func);
gint        g_slist_position                (GSList *list, GSList *llink);
gint        g_slist_index                   (GSList *list, gconstpointer data);

void        g_slist_push_allocator          (gpointer dummy);
void        g_slist_pop_allocator           (void);

Detailed Description

The GSList structure and its associated functions provide a standard singly-linked list data structure.

Each element in the list contains a piece of data, together with a pointer which links to the next element in the list. Using this pointer it is possible to move through the list in one direction only (unlike the Doubly-Linked Lists which allow movement in both directions).

The data contained in each element can be either integer values, by using one of the Type Conversion Macros, or simply pointers to any type of data.

List elements are allocated from the slice allocator, which is more efficient than allocating elements individually.

Note that most of the GSList functions expect to be passed a pointer to the first element in the list. The functions which insert elements return the new start of the list, which may have changed.

There is no function to create a GSList. NULL is considered to be the empty list so simply set a GSList* to NULL.

To add elements, use g_slist_append(), g_slist_prepend(), g_slist_insert() and g_slist_insert_sorted().

To remove elements, use g_slist_remove().

To find elements in the list use g_slist_last(), g_slist_next(), g_slist_nth(), g_slist_nth_data(), g_slist_find() and g_slist_find_custom().

To find the index of an element use g_slist_position() and g_slist_index().

To call a function for each element in the list use g_slist_foreach().

To free the entire list, use g_slist_free().

Details

GSList

typedef struct {
  gpointer data;
  GSList *next;
} GSList;

The GSList struct is used for each element in the singly-linked list.

gpointer data; | holds the element's data, which can be a pointer to any kind of data, or any integer value using the Type Conversion Macros.
GSList *next; | contains the link to the next element in the list.

g_slist_alloc ()

GSList*     g_slist_alloc           (void);

Allocates space for one GSList element. It is called by the g_slist_append(), g_slist_prepend(), g_slist_insert() and g_slist_insert_sorted() functions and so is rarely used on its own.

Returns : a pointer to the newly-allocated GSList element.

g_slist_append ()

GSList*     g_slist_append           (GSList *list, gpointer data);

Adds a new element on to the end of the list.

  /* Notice that these are initialized to the empty list. */
  GSList *list = NULL, *number_list = NULL;

  /* This is a list of strings. */
  list = g_slist_append (list, "first");
  list = g_slist_append (list, "second");

  /* This is a list of integers. */
  number_list = g_slist_append (number_list, GINT_TO_POINTER (27));
  number_list = g_slist_append (number_list, GINT_TO_POINTER (14));
Note

Note: The return value is the new start of the list, which may have changed, so make sure to store the new value. g_slist_append() has to traverse the entire list to find the end, which is inefficient when adding multiple elements. A common idiom to avoid the inefficiency is to prepend the elements and reverse the list when all elements have been added.

list : | a GSList.
data : | the data for the new element.
Returns : | the new start of the GSList.

g_slist_prepend ()

GSList*     g_slist_prepend                 (GSList *list, gpointer data);

Adds a new element on to the start of the list.

  /* Notice that it is initialized to the empty list. */
  GSList *list = NULL;
  list = g_slist_prepend (list, "last");
  list = g_slist_prepend (list, "first");
Note

Note: The return value is the new start of the list, which may have changed, so make sure to store the new value.

list : | a GSList.
data : | the data for the new element.
Returns : | the new start of the GSList.

g_slist_insert ()

GSList*     g_slist_insert                  (GSList *list, gpointer data, gint position);

Inserts a new element into the list at the given position.

list : | a GSList.
data : | the data for the new element.
position : | the position to insert the element. If this is negative, or is larger than the number of elements in the list, the new element is added on to the end of the list.
Returns : | the new start of the GSList.

g_slist_insert_before ()

GSList*     g_slist_insert_before           (GSList *slist, GSList *sibling, gpointer data);

Inserts a node before sibling containing data. Returns the new head of the list.

slist : | a GSList.
sibling : | node to insert data before.
data : | data to put in the newly-inserted node.
Returns : | new head of the list.

g_slist_insert_sorted ()

GSList*     g_slist_insert_sorted           (GSList *list, gpointer data, GCompareFunc func);

Inserts a new element into the list, using the given comparison function to determine its position.

list : | a GSList.
data : | the data for the new element.
func : | the function to compare elements in the list. It should return a number > 0 if the first parameter comes after the second parameter in the sort order.
Returns : | the new start of the GSList.

g_slist_remove ()

GSList*     g_slist_remove                  (GSList *list, gconstpointer data);

Removes an element from a GSList. If two elements contain the same data, only the first is removed. If none of the elements contain the data, the GSList is unchanged.

list : | a GSList.
data : | the data of the element to remove.
Returns : | the new start of the GSList.

g_slist_remove_link ()

GSList*     g_slist_remove_link             (GSList *list, GSList *link_);

Removes an element from a GSList, without freeing the element. The removed element's next link is set to NULL, so that it becomes a self-contained list with one element.

list : | a GSList.
link_ : | an element in the GSList.
Returns : | the new start of the GSList, without the element.

g_slist_delete_link ()

GSList*     g_slist_delete_link             (GSList *list, GSList *link_);

Deletes a node of list. Returns the new list head.

list : | a GSList.
link_ : | node to delete.
Returns : | new head of list.

g_slist_remove_all ()

GSList*     g_slist_remove_all              (GSList *list, gconstpointer data);

Removes all list nodes with data equal to data. Returns the new head of the list. Contrast with g_slist_remove() which removes only the first node matching the given data.

list : | a GSList.
data : | data to remove.
Returns : | new head of list.

g_slist_free ()

void        g_slist_free                    (GSList *list);

Frees all of the memory used by a GSList. The freed elements are returned to the slice allocator free list.

list : a GSList.

g_slist_free_1 ()

void        g_slist_free_1                  (GSList *list);

Frees one GSList element. It is usually used after g_slist_remove_link().

list : a GSList element.

g_slist_free1

#define     g_slist_free1

A macro which does the same as g_slist_free_1().

g_slist_length ()

guint       g_slist_length                  (GSList *list);

Gets the number of elements in a GSList.

list : | a GSList.
Returns : | the number of elements in the GSList.

g_slist_copy ()

GSList*     g_slist_copy                    (GSList *list);

Copies a GSList.
Note that this is a "shallow" copy. If the list elements consist of pointers to data, the pointers are copied but the actual data isn't.

list : | a GSList.
Returns : | a copy of list.

g_slist_reverse ()

GSList*     g_slist_reverse              (GSList *list);

Reverses a GSList.

list : | a GSList.
Returns : | the start of the reversed GSList.

g_slist_insert_sorted_with_data ()

GSList*   g_slist_insert_sorted_with_data (GSList *list, gpointer data, GCompareDataFunc func, gpointer user_data);

Inserts a new element into the list, using the given comparison function to determine its position.

list : | a GSList.
data : | the data for the new element.
func : | the function to compare elements in the list. It should return a number > 0 if the first parameter comes after the second parameter in the sort order.
user_data : | data to pass to comparison function.
Returns : | the new start of the GSList. Since 2.10

g_slist_sort ()

GSList*     g_slist_sort                    (GSList *list, GCompareFunc compare_func);

Sorts a GSList using the given comparison function.

list : | a GSList.
compare_func : | the comparison function used to sort the GSList. This function is passed the data from 2 elements of the GSList and should return 0 if they are equal, a negative value if the first element comes before the second, or a positive value if the first element comes after the second.
Returns : | the start of the sorted GSList.

g_slist_sort_with_data ()

GSList*     g_slist_sort_with_data          (GSList *list, GCompareDataFunc compare_func, gpointer user_data);

Like g_slist_sort(), but the sort function accepts a user data argument.

list : | a GSList
compare_func : | comparison function.
user_data : | data to pass to comparison function.
Returns : | new head of the list.

g_slist_concat ()

GSList*     g_slist_concat                  (GSList *list1, GSList *list2);

Adds the second GSList onto the end of the first GSList. Note that the elements of the second GSList are not copied. They are used directly.

list1 : | a GSList.
list2 : | the GSList to add to the end of the first GSList.
Returns : | the start of the new GSList.

g_slist_foreach ()

void        g_slist_foreach                 (GSList *list, GFunc func, gpointer user_data);

Calls a function for each element of a GSList.

list : | a GSList.
func : | the function to call with each element's data.
user_data : | user data to pass to the function.

g_slist_last ()

GSList*     g_slist_last                    (GSList *list);

Gets the last element in a GSList.

list : | a GSList.
Returns : | the last element in the GSList, or NULL if the GSList has no elements.

g_slist_next()

#define     g_slist_next(slist)

A convenience macro to gets the next element in a GSList.

slist : | an element in a GSList.
Returns : | the next element, or NULL if there are no more elements.

g_slist_nth ()

GSList*     g_slist_nth               (GSList *list, guint n);

Gets the element at the given position in a GSList.

list : | a GSList.
n : | the position of the element, counting from 0.
Returns : | the element, or NULL if the position is off the end of the GSList.

g_slist_nth_data ()

gpointer    g_slist_nth_data         (GSList *list, guint n);

Gets the data of the element at the given position.

list : | a GSList.
n : | the position of the element.
Returns : | the element's data, or NULL if the position is off the end of the GSList.

g_slist_find ()

GSList*     g_slist_find            (GSList *list, gconstpointer data);

Finds the element in a GSList which contains the given data.

list : | a GSList.
data : | the element data to find.
Returns : | the found GSList element, or NULL if it is not found.

g_slist_find_custom ()

GSList*   g_slist_find_custom     (GSList *list, gconstpointer data, GCompareFunc func);

Finds an element in a GSList, using a supplied function to find the desired element. It iterates over the list, calling the given function which should return 0 when the desired element is found. The function takes two gconstpointer arguments, the GSList element's data as the first argument and the given user data.

list : | a GSList.
data : | user data passed to the function.
func : | the function to call for each element. It should return 0 when the desired element is found.
Returns : | the found GSList element, or NULL if it is not found.

g_slist_position ()

gint        g_slist_position                (GSList *list, GSList *llink);

Gets the position of the given element in the GSList (starting from 0).

list : | a GSList.
llink : | an element in the GSList.
Returns : | the position of the element in the GSList, or -1 if the element is not found.

g_slist_index ()

gint        g_slist_index                   (GSList *list, gconstpointer data);

Gets the position of the element containing the given data (starting from 0).

list : | a GSList.
data : | the data to find.
Returns : | the index of the element containing the data, or -1 if the data is not found.

g_slist_push_allocator ()

void        g_slist_push_allocator          (gpointer dummy);

Sets the allocator to use to allocate GSList elements. Use g_slist_pop_allocator() to restore the previous allocator.

Note that this function is not available if GLib has been compiled with --disable-mem-pools

dummy : the GAllocator to use when allocating GSList elements.

g_slist_pop_allocator ()

void        g_slist_pop_allocator           (void);
Note

Warning: g_slist_pop_allocator has been deprecated since version 2.10 and should not be used in newly-written code. It does nothing, since GSList has been converted to the slice allocator

Restores the previous GAllocator, used when allocating GSList elements.

Note that this function is not available if GLib has been compiled with --disable-mem-pools

Feedback

For additional information or queries on this page send feedback


Spawning Processes

Name

Spawning Processes — process launching with fork()/exec()

Library

glib.lib

Synopsis

#include <glib.h>

enum        GSpawnError;
#define     G_SPAWN_ERROR
enum        GSpawnFlags;
void        (*GSpawnChildSetupFunc)         (gpointer user_data);
gboolean    g_spawn_async_with_pipes        (const gchar *working_directory, gchar **argv, gchar **envp, GSpawnFlags flags, GSpawnChildSetupFunc child_setup,
                                             gpointer user_data, GPid *child_pid, gint *standard_input, gint *standard_output, gint *standard_error, GError **error);
gboolean    g_spawn_async                   (const gchar *working_directory, gchar **argv, gchar **envp, GSpawnFlags flags, GSpawnChildSetupFunc child_setup,
                                             gpointer user_data, GPid *child_pid, GError **error);
gboolean    g_spawn_sync                    (const gchar *working_directory, gchar **argv, gchar **envp, GSpawnFlags flags, GSpawnChildSetupFunc child_setup,
                                             gpointer user_data, gchar **standard_output, gchar **standard_error, gint *exit_status, GError **error);
gboolean    g_spawn_command_line_async      (const gchar *command_line, GError **error);
gboolean    g_spawn_command_line_sync       (const gchar *command_line, gchar **standard_output, gchar **standard_error,
                                             gint *exit_status, GError **error);
void        g_spawn_close_pid               (GPid pid);

Detailed Description

Details

enum GSpawnError

typedef enum
{
  G_SPAWN_ERROR_FORK,   /* fork failed due to lack of memory */
  G_SPAWN_ERROR_READ,   /* read or select on pipes failed */
  G_SPAWN_ERROR_CHDIR,  /* changing to working dir failed */
  G_SPAWN_ERROR_ACCES,  /* execv() returned EACCES */
  G_SPAWN_ERROR_PERM,   /* execv() returned EPERM */
  G_SPAWN_ERROR_2BIG,   /* execv() returned E2BIG */
  G_SPAWN_ERROR_NOEXEC, /* execv() returned ENOEXEC */
  G_SPAWN_ERROR_NAMETOOLONG, /* ""  "" ENAMETOOLONG */
  G_SPAWN_ERROR_NOENT,       /* ""  "" ENOENT */
  G_SPAWN_ERROR_NOMEM,       /* ""  "" ENOMEM */
  G_SPAWN_ERROR_NOTDIR,      /* ""  "" ENOTDIR */
  G_SPAWN_ERROR_LOOP,        /* ""  "" ELOOP   */
  G_SPAWN_ERROR_TXTBUSY,     /* ""  "" ETXTBUSY */
  G_SPAWN_ERROR_IO,          /* ""  "" EIO */
  G_SPAWN_ERROR_NFILE,       /* ""  "" ENFILE */
  G_SPAWN_ERROR_MFILE,       /* ""  "" EMFLE */
  G_SPAWN_ERROR_INVAL,       /* ""  "" EINVAL */
  G_SPAWN_ERROR_ISDIR,       /* ""  "" EISDIR */
  G_SPAWN_ERROR_LIBBAD,      /* ""  "" ELIBBAD */
  G_SPAWN_ERROR_FAILED       /* other fatal failure, error->message
                              * should explain
                              */
} GSpawnError;

Error codes returned by spawning processes.

G_SPAWN_ERROR_FORK | Fork failed due to lack of memory.
G_SPAWN_ERROR_READ | Read or select on pipes failed.
G_SPAWN_ERROR_CHDIR | Changing to working directory failed.
G_SPAWN_ERROR_ACCES | execv() returned EACCES.
G_SPAWN_ERROR_PERM | execv() returned EPERM.
G_SPAWN_ERROR_2BIG | execv() returned E2BIG.
G_SPAWN_ERROR_NOEXEC | execv() returned ENOEXEC.
G_SPAWN_ERROR_NAMETOOLONG | execv() returned ENAMETOOLONG.
G_SPAWN_ERROR_NOENT | execv() returned ENOENT.
G_SPAWN_ERROR_NOMEM | execv() returned ENOMEM.
G_SPAWN_ERROR_NOTDIR | execv() returned ENOTDIR.
G_SPAWN_ERROR_LOOP | execv() returned ELOOP.
G_SPAWN_ERROR_TXTBUSY | execv() returned ETXTBUSY.
G_SPAWN_ERROR_IO | execv() returned EIO.
G_SPAWN_ERROR_NFILE | execv() returned ENFILE.
G_SPAWN_ERROR_MFILE | execv() returned EMFILE.
G_SPAWN_ERROR_INVAL | execv() returned EINVAL.
G_SPAWN_ERROR_ISDIR | execv() returned EISDIR.
G_SPAWN_ERROR_LIBBAD | execv() returned ELIBBAD.
G_SPAWN_ERROR_FAILED | Some other fatal failure, error->message should explain.

G_SPAWN_ERROR

#define G_SPAWN_ERROR g_spawn_error_quark ()

Error domain for spawning processes. Errors in this domain will be from the GSpawnError enumeration. See GError for information on error domains.

enum GSpawnFlags

typedef enum
{
  G_SPAWN_LEAVE_DESCRIPTORS_OPEN = 1 << 0,
  G_SPAWN_DO_NOT_REAP_CHILD      = 1 << 1,
  /* look for argv[0] in the path i.e. use execvp() */
  G_SPAWN_SEARCH_PATH            = 1 << 2,
  /* Dump output to /dev/null */
  G_SPAWN_STDOUT_TO_DEV_NULL     = 1 << 3,
  G_SPAWN_STDERR_TO_DEV_NULL     = 1 << 4,
  G_SPAWN_CHILD_INHERITS_STDIN   = 1 << 5,
  G_SPAWN_FILE_AND_ARGV_ZERO     = 1 << 6
} GSpawnFlags;

Flags passed to g_spawn_sync(), g_spawn_async() and g_spawn_async_with_pipes().

G_SPAWN_LEAVE_DESCRIPTORS_OPEN | the parent's open file descriptors will be inherited by the child; otherwise all descriptors except stdin/stdout/stderr will be closed before calling exec() in the child.
G_SPAWN_DO_NOT_REAP_CHILD | the child will not be automatically reaped; call waitpid() or handle SIGCHLD, or the child will become a zombie.
G_SPAWN_SEARCH_PATH | argv[0] need not be an absolute path, it will be looked for in the user's PATH.
G_SPAWN_STDOUT_TO_DEV_NULL | the child's standad output will be discarded, instead of going to the same location as the parent's standard output.
G_SPAWN_STDERR_TO_DEV_NULL | the child's standard error will be discarded.
G_SPAWN_CHILD_INHERITS_STDIN | the child will inherit the parent's standard input (by default, the child's standard input is attached to /dev/null).
G_SPAWN_FILE_AND_ARGV_ZERO | the first element of argv is the file to execute, while the remaining elements are the actual argument vector to pass to the file. Normally g_spawn_async_with_pipes() uses argv[0] as the file to execute, and passes all of argv to the child.

The following flags are not supported for Symbian implementaion.

G_SPAWN_LEAVE_DESCRIPTORS_OPEN
 G_SPAWN_STDOUT_TO_DEV_NULL
G_SPAWN_STDERR_TO_DEV_NULL
 G_SPAWN_CHILD_INHERITS_STDIN

GSpawnChildSetupFunc ()

void        (*GSpawnChildSetupFunc)         (gpointer user_data);

Specifies the type of the setup function passed to g_spawn_async(), g_spawn_sync() and g_spawn_async_with_pipes(). On POSIX platforms it is called in the child after GLib has performed all the setup it plans to perform but before calling exec(). On POSIX actions taken in this function will thus only affect the child, not the parent.

On Windows and Symbian the function is called in the parent. Its usefulness on Windows and Symbian is thus questionable. In many cases executing the child setup function in the parent can have ill effects, the user should be very careful when porting software to Windows and Symbian that uses child setup functions.

user_data : user data to pass to the function.

g_spawn_async_with_pipes ()

gboolean    g_spawn_async_with_pipes     (const gchar *working_directory, gchar **argv, gchar **envp, GSpawnFlags flags,
                                          GSpawnChildSetupFunc child_setup, gpointer user_data, GPid *child_pid,
                                          gint *standard_input, gint *standard_output, gint *standard_error, GError **error);

Executes a child program asynchronously (the program will not block waiting for the child to exit). The child program is specified by the only argument that must be provided, argv. argv should be a NULL-terminated array of strings, to be passed as the argument vector for the child. The first string in argv is of course the name of the program to execute. By default, the name of the program must be a full path; the PATH shell variable will only be searched if the G_SPAWN_SEARCH_PATH flag is passed. In the Symbian case if only the name of the program is specified, the program is searched in the default order as defined by Symbian OS.

On Windows, note that all the string or string vector arguments to this function and the other g_spawn*() functions are in UTF-8, the GLib file name encoding. Unicode characters that are not part of the system codepage passed in argument vectors will be correctly available in the spawned program only if it uses wide character API to retrieve its command line. For C programs built with Microsoft's tools it is enough to make the program have a wmain() instead of main(). wmain() has a wide character argument vector as parameter.

At least currently, mingw does not support wmain(), so if mingw is used to develop the spawned program, it will have to call the undocumented function __wgetmainargs() to get the wide character argument vector and environment. See gspawn-win32-helper.c in the GLib sources or init.c in the mingw runtime sources for a prototype for that function. Alternatively, the Win32 system level wide character command line passed to the spawned program can be retrieved using the GetCommandLineW() function.

On Windows the low-level child process creation API CreateProcess() does not use argument vectors, but a command line. The C runtime library's spawn*() family of functions (which g_spawn_async_with_pipes() eventually calls) paste the argument vector elements together into a command line, and the C runtime startup code does a corresponding reconstruction of an argument vector from the command line, to be passed to main(). Complications arise when there are argument vector elements that contain spaces of double quotes. The spawn*() functions do not do any quoting or escaping, but on the other hand the startup code does do unquoting and unescaping in order to enable receiving arguments with embedded spaces or double quotes. To work around this asymmetry, g_spawn_async_with_pipes() will do quoting and escaping on argument vector elements that need it before calling the C runtime spawn() function.

envp is a NULL-terminated array of strings, where each string has the form KEY=VALUE. This will become the child's environment. If envp is NULL, the child inherits its parent's environment. On Symbain no environment setting is done for the child.

flags should be the bitwise OR of any flags that affect the function's behaviour. The G_SPAWN_DO_NOT_REAP_CHILD means that the child will not automatically be reaped; a GChildWatch source should be used to be notified about the death of the child process. Eventually a call to g_spawn_close_pid() on the child_pid  should be made, in order to free resources which may be associated with the child process. (On Unix, using a GChildWatch source is equivalent to calling waitpid() or handling the SIGCHLD signal manually. On Windows, calling g_spawn_close_pid() is equivalent to calling CloseHandle() on the process handle returned in child_pid).

G_SPAWN_LEAVE_DESCRIPTORS_OPEN means that the parent's open file descriptors will be inherited by the child; otherwise all descriptors except stdin/stdout/stderr will be closed before calling exec() in the child. On Symbian this is not supported. G_SPAWN_SEARCH_PATH means that argv[0] need not be an absolute path, it will be looked for in the user's PATH. G_SPAWN_STDOUT_TO_DEV_NULL means that the child's standard output will be discarded, instead of going to the same location as the parent's standard output. If this flag is used, standard_output must be NULL. On Symbian this is not supported. G_SPAWN_STDERR_TO_DEV_NULL means that the child's standard error will be discarded, instead of going to the same location as the parent's standard error. If this flag is used, standard_error must be NULL. On Symbian this is not supported. G_SPAWN_CHILD_INHERITS_STDIN means that the child will inherit the parent's standard input (by default, the child's standard input is attached to /dev/null). If this flag is used, standard_input must be NULL. On Symbian this is not supported. G_SPAWN_FILE_AND_ARGV_ZERO means that the first element of argv is the file to execute, while the remaining elements are the actual argument vector to pass to the file. Normally g_spawn_async_with_pipes() uses argv[0] as the file to execute, and passes all of argv to the child.

child_setup and user_data are a function and user data. On POSIX platforms, the function is called in the child after GLib has performed all the setup it plans to perform (including creating pipes, closing file descriptors, etc.) but before calling exec(). That is, child_setup is called just before calling exec() in the child. Obviously actions taken in this function will only affect the child, not the parent. On Windows, there is no separate fork() and exec() functionality. Child processes are created and run with a single API call, CreateProcess(). child_setup is called in the parent process just before creating the child process. Concider carefully what is done in child_setup if the software is intended to be portable to Windows. The behaviour of child_setup on Symbian is similar to that in WIndows.

If non-NULL, child_pid will on Unix be filled with the child's process ID. The process ID can be used to send signals to the child, or to waitpid() if the G_SPAWN_DO_NOT_REAP_CHILD flag is specified. On Windows, child_pid will be filled with a handle to the child process only if the G_SPAWN_DO_NOT_REAP_CHILD flag i spsecified. The child process can be accessed using the Win32 API, for example wait for its termination with the WaitFor*() functions, or examine its exit code with GetExitCodeProcess(). Close the handle with CloseHandle() or g_spawn_close_pid() when it is no longer needed . On Symbian child_pid will be filled with the process handle and the handle can be closed using g_spawn_close_pid() .

If non-NULL, the standard_input, standard_output, standard_error locations will be filled with file descriptors for writing to the child's standard input or reading from its standard output or standard error. The caller of g_spawn_async_with_pipes() must close these file descriptors when they are no longer in use. If these parameters are NULL, the corresponding pipe will not be created.In Symbian if non-NULL, standard_input, standard_output, standard_error are filled with -1. The default UNIX behaviour is not supported.

If standard_input is NULL, the child's standard input is attached to /dev/null unless G_SPAWN_CHILD_INHERITS_STDIN is set. On Symbian this is not supported.

If standard_error is NULL, the child's standard error goes to the same location as the parent's standard error unless G_SPAWN_STDERR_TO_DEV_NULL is set. On Symbian this is not supported.

If standard_output is NULL, the child's standard output goes to the same location as the parent's standard output unless G_SPAWN_STDOUT_TO_DEV_NULL is set. On Symbian this is not supported.

error can be NULL to ignore errors, or non-NULL to report errors. If an error is set, the function returns FALSE. Errors are reported even if they occur in the child (for example if the executable in argv[0] is not found). Typically the message field of returned errors should be displayed to users. Possible errors are those from the G_SPAWN_ERROR domain.

If an error occurs, child_pid, standard_input, standard_output, and standard_error will not be filled with valid values.

If child_pid is not NULL and an error does not occur then the returned pid must be closed using g_spawn_close_pid().

working_directory : | child's current working directory, or NULL to inherit parent's, in the GLib file name encoding. On Symbian this is not supported.
argv : | child's argument vector, in the GLib file name encoding
envp : | child's environment, or NULL to inherit parent's, in the GLib file name encoding. On Symbian this is not supported.
flags : | flags from GSpawnFlags
child_setup : | function to run in the child just before exec()
user_data : | user data for child_setup
child_pid : | return location for child process ID, or NULL
standard_input : | return location for file descriptor to write to child's stdin, or NULL. On Symbian returns -1.
standard_output : | return location for file descriptor to read child's stdout, or NULL. On Symbian returns -1.
standard_error : | return location for file descriptor to read child's stderr, or NULL. On Symbian returns -1.
error : | return location for error
Returns : | TRUE on success, FALSE if an error was set

g_spawn_async ()

gboolean    g_spawn_async       (const gchar *working_directory, gchar **argv, gchar **envp, GSpawnFlags flags,
                                 GSpawnChildSetupFunc child_setup, gpointer user_data, GPid *child_pid, GError **error);

See g_spawn_async_with_pipes() for a full description; this function simply calls the g_spawn_async_with_pipes() without any pipes.

working_directory : | child's current working directory, or NULL to inherit parent's. On Symbian this is not supported.
argv : | child's argument vector
envp : | child's environment, or NULL to inherit parent's. On Symbian this is not supported.,
flags : | flags from GSpawnFlags
child_setup : | function to run in the child just before exec()
user_data : | user data for child_setup
child_pid : | return location for child process ID, or NULL
error : | return location for error
Returns : | TRUE on success, FALSE if error is set

g_spawn_sync ()

gboolean    g_spawn_sync      (const gchar *working_directory, gchar **argv, gchar **envp, GSpawnFlags flags, GSpawnChildSetupFunc child_setup,
                               gpointer user_data, gchar **standard_output, gchar **standard_error, gint *exit_status, GError **error);

Executes a child synchronously (waits for the child to exit before returning). All output from the child is stored in standard_output and standard_error, if those parameters are non-NULL. On Symbian this is not supported. If exit_status is non-NULL, the exit status of the child is stored there as it would be returned by waitpid(); standard UNIX macros such as WIFEXITED() and WEXITSTATUS() must be used to evaluate the exit status. If an error occurs, no data is returned in standard_output, standard_error, or exit_status.

This function calls g_spawn_async_with_pipes() internally; see that function for full details on the other parameters and details on how these functions work on Windows.

working_directory : | child's current working directory, or NULL to inherit parent's. On Symbian this is not supported.
argv : | child's argument vector
envp : | child's environment, or NULL to inherit parent's. On Symbian this is not supported.
flags : | flags from GSpawnFlags
child_setup : | function to run in the child just before exec()
user_data : | user data for child_setup
standard_output : | return location for child output. On Symbian returns -1.
standard_error : | return location for child error messages On Symbian returns -1.
exit_status : | return location for child exit status, as returned by waitpid()
error : | return location for error
Returns : | TRUE on success, FALSE if an error was set.

g_spawn_command_line_async ()

gboolean    g_spawn_command_line_async      (const gchar *command_line, GError **error);

A simple version of g_spawn_async() that parses a command line with g_shell_parse_argv() and passes it to g_spawn_async(). Runs a command line in the background. Unlike g_spawn_async(), the G_SPAWN_SEARCH_PATH flag is enabled, other flags are not. Note that G_SPAWN_SEARCH_PATH can have security implications, so consider using g_spawn_async() directly if appropriate. Possible errors are those from g_shell_parse_argv() and g_spawn_async().

The same concerns on Windows apply as for g_spawn_command_line_sync().

command_line : | a command line
error : | return location for errors
Returns : | TRUE on success, FALSE if error is set.

g_spawn_command_line_sync ()

gboolean    g_spawn_command_line_sync     (const gchar *command_line, gchar **standard_output, gchar **standard_error, gint *exit_status, GError **error);

A simple version of g_spawn_sync() with little-used parameters removed, taking a command line instead of an argument vector. See g_spawn_sync() for full details. command_line will be parsed by g_shell_parse_argv(). Unlike g_spawn_sync(), the G_SPAWN_SEARCH_PATH flag is enabled. Note that G_SPAWN_SEARCH_PATH can have security implications, so consider using g_spawn_sync() directly if appropriate. Possible errors are those from g_spawn_sync() and those from g_shell_parse_argv().

If exit_status is non-NULL, the exit status of the child is stored there as it would be returned by waitpid(); standard UNIX macros such as WIFEXITED() and WEXITSTATUS() must be used to evaluate the exit status.

On Windows, please note the implications of g_shell_parse_argv() parsing command_line. Parsing is done according to Unix shell rules, not Windows command interpreter rules. Space is a separator, and backslashes are special. Thus a command_line containing canonical Windows paths , like "c:\\program files\\app\\app.exe" cannot be passed, as the backslashes will be eaten, and the space will act as a separator. Such paths need to be enclosed within single quotes, like " 'c:\\program files\\app\\app.exe' 'e:\\folder\\argument.txt' ".

command_line : | a command line
standard_output : | return location for child output
standard_error : | return location for child errors
exit_status : | return location for child exit status, as returned by waitpid()
error : | return location for errors
Returns : | TRUE on success, FALSE if an error was set.

g_spawn_close_pid ()

void        g_spawn_close_pid       (GPid pid);

On some platforms, notably WIN32, the GPid type represents a resource which must be closed to prevent resource leaking. g_spawn_close_pid() is provided for this purpose. It should be used on all platforms, even though it does not do anything under UNIX.

pid : The process identifier to close

Feedback

For additional information or queries on this page send feedback


Standard Macros

Name

Standard Macros — commonly-used macros.

Library

glib.lib

Synopsis

#include <glib.h>

#define     G_OS_WIN32
#define     G_OS_BEOS
#define     G_OS_UNIX

#define     G_DIR_SEPARATOR
#define     G_DIR_SEPARATOR_S
#define     G_IS_DIR_SEPARATOR              (c)
#define     G_SEARCHPATH_SEPARATOR
#define     G_SEARCHPATH_SEPARATOR_S

#define     TRUE
#define     FALSE

#define     NULL

#define     MIN                             (a, b)
#define     MAX                             (a, b)

#define     ABS                             (a)
#define     CLAMP                           (x, low, high)

#define     G_STRUCT_MEMBER                 (member_type, struct_p, struct_offset)
#define     G_STRUCT_MEMBER_P               (struct_p, struct_offset)
#define     G_STRUCT_OFFSET                 (struct_type, member)

#define     G_MEM_ALIGN

#define     G_CONST_RETURN

Detailed Description

These macros provide a few commonly-used features.

Details

G_OS_WIN32

#define G_OS_WIN32

This macro is defined only on Windows. So bracket Windows-specific code in "#ifdef G_OS_WIN32".

G_OS_BEOS

#define G_OS_BEOS

This macro is defined only on BeOS. So bracket BeOS-specific code in "#ifdef G_OS_BEOS".

G_OS_UNIX

#define G_OS_UNIX

This macro is defined only on UNIX. So bracket UNIX-specific code in "#ifdef G_OS_UNIX".

G_DIR_SEPARATOR

#define     G_DIR_SEPARATOR

The directory separator character. This is '/' on UNIX machines and '\' under Windows.

G_DIR_SEPARATOR_S

#define     G_DIR_SEPARATOR_S

The directory separator as a string. This is "/" on UNIX machines and "\" under Windows.

G_IS_DIR_SEPARATOR()

#define     G_IS_DIR_SEPARATOR(c)

Checks whether a character is a directory separator. It returns TRUE for '/' on UNIX machines and for '\' or '/' under Windows.

c : a character

G_SEARCHPATH_SEPARATOR

#define     G_SEARCHPATH_SEPARATOR

The search path separator character. This is ':' on UNIX machines and ';' under Windows.

G_SEARCHPATH_SEPARATOR_S

#define     G_SEARCHPATH_SEPARATOR_S

The search path separator as a string. This is ":" on UNIX machines and ";" under Windows.

TRUE

#define	TRUE	(!FALSE)

Defines the TRUE value for the gboolean type.

FALSE

#define	FALSE	(0)

Defines the FALSE value for the gboolean type.

NULL

#define     NULL

Defines the standard NULL pointer.

MIN()

#define MIN(a, b)  (((a) < (b)) ? (a) : (b))

Calculates the minimum of a and b.

a : | a numeric value.
b : | a numeric value.
Returns : | the minimum of a and b.

MAX()

#define MAX(a, b)  (((a) > (b)) ? (a) : (b))

Calculates the maximum of a and b.

a : | a numeric value.
b : | a numeric value.
Returns : | the maximum of a and b.

ABS()

#define ABS(a)	   (((a) < 0) ? -(a) : (a))

Calculates the absolute value of a. The absolute value is simply the number with any negative sign taken away.

For example,

  • ABS(-10) is 10.

  • ABS(10) is also 10.

a : | a numeric value.
Returns : | the absolute value of a.

CLAMP()

#define CLAMP(x, low, high)  (((x) > (high)) ? (high) : (((x) < (low)) ? (low) : (x)))

Ensures that x is between the limits set by low and high.

For example,

  • CLAMP(5, 10, 15) is 10.

  • CLAMP(15, 5, 10) is 10.

  • CLAMP(20, 15, 25) is 20.

x : | the value to clamp.
low : | the minimum value allowed.
high : | the maximum value allowed.
Returns : | the value of x clamped to the range between low and high.

G_STRUCT_MEMBER()

#define     G_STRUCT_MEMBER(member_type, struct_p, struct_offset)

Returns a member of a structure at a given offset, using the given type.

member_type : | the type of the struct field.
struct_p : | a pointer to a struct.
struct_offset : | the offset of the field from the start of the struct, in bytes.
Returns : | the struct member.

G_STRUCT_MEMBER_P()

#define     G_STRUCT_MEMBER_P(struct_p, struct_offset)

Returns an untyped pointer to a given offset of a struct.

struct_p : | a pointer to a struct.
struct_offset : | the offset from the start of the struct, in bytes.
Returns : | an untyped pointer to struct_p plus struct_offset bytes.

G_STRUCT_OFFSET()

#define     G_STRUCT_OFFSET(struct_type, member)

Returns the offset, in bytes, of a member of a struct.

struct_type : | a structure type, e.g. GtkWidget.
member : | a field in the structure, e.g. window.
Returns : | the offset of member from the start of struct_type.

G_MEM_ALIGN

#define     G_MEM_ALIGN

Indicates the number of bytes to which memory will be aligned on the current platform.

G_CONST_RETURN

#define     G_CONST_RETURN

If G_DISABLE_CONST_RETURNS is defined, this macro expands to nothing. By default, the macro expands to const. The macro should be used in place of const for functions that return a value that should not be modified. The purpose of this macro is to allow us to turn on const for returned constant strings by default, while allowing programmers who find that annoying to turn it off. This macro should only be used for return values and for out parameters, it doesn't make sense for in parameters.

Feedback

For additional information or queries on this page send feedback


String Chunks

Name

String Chunks — efficient storage of groups of strings.

Library

glib.lib

Synopsis

#include <glib.h>

              GStringChunk;
GStringChunk* g_string_chunk_new              (gsize size);
gchar*        g_string_chunk_insert           (GStringChunk *chunk, const gchar *string);
gchar*        g_string_chunk_insert_const     (GStringChunk *chunk, const gchar *string);
gchar*        g_string_chunk_insert_len       (GStringChunk *chunk, const gchar *string, gssize len);
void          g_string_chunk_free             (GStringChunk *chunk);

Detailed Description

String chunks are used to store groups of strings. Memory is allocated in blocks, and as strings are added to the GStringChunk they are copied into the next free position in a block. When a block is full a new block is allocated.

When storing a large number of strings, string chunks are more efficient than using g_strdup() since fewer calls to malloc() are needed, and less memory is wasted in memory allocation overheads.

By adding strings with g_string_chunk_insert_const() it is also possible to remove duplicates.

To create a new GStringChunk use g_string_chunk_new().

To add strings to a GStringChunk use g_string_chunk_insert().

To add strings to a GStringChunk, but without duplicating strings which are already in the GStringChunk, use g_string_chunk_insert_const().

To free the entire GStringChunk use g_string_chunk_free(). It is not possible to free individual strings.

Details

GStringChunk

typedef struct _GStringChunk GStringChunk;

An opaque data structure representing String Chunks. It should only be accessed by using the following functions.

g_string_chunk_new ()

GStringChunk* g_string_chunk_new      (gsize size);

Creates a new GStringChunk.

size : | the default size of the blocks of memory which are allocated to store the strings. If a particular string is larger than this default size, a larger block of memory will be allocated for it.
Returns : | a new GStringChunk.

g_string_chunk_insert ()

gchar*      g_string_chunk_insert      (GStringChunk *chunk, const gchar *string);

Adds a copy of string to the GStringChunk. It returns a pointer to the new copy of the string in the GStringChunk. The characters in the string can be changed, if necessary, though nothing should be changed after the end of the string.

Unlike g_string_chunk_insert_const(), this function does not check for duplicates. Also strings added with g_string_chunk_insert() will not be searched by g_string_chunk_insert_const() when looking for duplicates.

chunk : | a GStringChunk.
string : | the string to add.
Returns : | a pointer to the copy of string within the GStringChunk.

g_string_chunk_insert_const ()

gchar*      g_string_chunk_insert_const     (GStringChunk *chunk, const gchar *string);

Adds a copy of string to the GStringChunk, unless the same string has already been added to the GStringChunk with g_string_chunk_insert_const().

This function is useful to copy a large number of strings and not wasting space storing duplicates. But, do remember that there may be several pointers to the same string, and so any changes made to the strings should be done very carefully.

Note that g_string_chunk_insert_const() will not return a pointer to a string added with g_string_chunk_insert(), even if they do match.

chunk : | a GStringChunk.
string : | the string to add.
Returns : | a pointer to the new or existing copy of string within the GStringChunk.

g_string_chunk_insert_len ()

gchar*      g_string_chunk_insert_len       (GStringChunk *chunk, const gchar *string, gssize len);

Adds a copy of the first len bytes of string to the GStringChunk. The copy is nul-terminated.

The characters in the string can be changed, if necessary, though nothing should be changed after the end of the string.

chunk : | a GStringChunk
string : | bytes to insert
len : | number of bytes of string to insert, or -1 to insert a nul-terminated string.
Returns : | a pointer to the copy of string within the GStringChunk

g_string_chunk_free ()

void        g_string_chunk_free             (GStringChunk *chunk);

Frees all memory allocated by the GStringChunk. After calling g_string_chunk_free() it is not safe to access any of the strings which were contained within it.

chunk : a GStringChunk

Feedback

For additional information or queries on this page send feedback


String Utility Functions

Name

String Utility Functions — various string-related functions.

Library

glib.lib

Synopsis

#include <glib.h>
#include <glib/gprintf.h>

gchar*      g_strdup                        (const gchar *str);
gchar*      g_strndup                       (const gchar *str, gsize n);
gchar**     g_strdupv                       (gchar **str_array);
gchar*      g_strnfill                      (gsize length, gchar fill_char);
gchar*      g_stpcpy                        (gchar *dest, const char *src);
gchar*      g_strstr_len                    (const gchar *haystack, gssize haystack_len, const gchar *needle);
gchar*      g_strrstr                       (const gchar *haystack, const gchar *needle);
gchar*      g_strrstr_len                   (const gchar *haystack, gssize haystack_len, const gchar *needle);
gboolean    g_str_has_prefix                (const gchar *str, const gchar *prefix);
gboolean    g_str_has_suffix                (const gchar *str, const gchar *suffix);

gsize       g_strlcpy                       (gchar *dest, const gchar *src, gsize dest_size);
gsize       g_strlcat                       (gchar *dest, const gchar *src, gsize dest_size);

gchar*      g_strdup_printf                 (const gchar *format, ...);
gchar*      g_strdup_vprintf                (const gchar *format, va_list args);
gint        g_printf                        (gchar const *format, ...);
gint        g_vprintf                       (gchar const *format, va_list args);
gint        g_fprintf                       (FILE *file, gchar const *format, ...);
gint        g_vfprintf                      (FILE *file, gchar const *format, va_list args);
gint        g_sprintf                       (gchar *string, gchar const *format, ...);
gint        g_vsprintf                      (gchar *string, gchar const *format, va_list args);
gint        g_snprintf                      (gchar *string, gulong n, gchar const *format, ...);
gint        g_vsnprintf                     (gchar *string, gulong n, gchar const *format, va_list args);
gint        g_vasprintf                     (gchar **string, gchar const *format, va_list args);
gsize       g_printf_string_upper_bound     (const gchar *format, va_list args);

gboolean    g_ascii_isalnum                 (gchar c);
gboolean    g_ascii_isalpha                 (gchar c);
gboolean    g_ascii_iscntrl                 (gchar c);
gboolean    g_ascii_isdigit                 (gchar c);
gboolean    g_ascii_isgraph                 (gchar c);
gboolean    g_ascii_islower                 (gchar c);
gboolean    g_ascii_isprint                 (gchar c);
gboolean    g_ascii_ispunct                 (gchar c);
gboolean    g_ascii_isspace                 (gchar c);
gboolean    g_ascii_isupper                 (gchar c);
gboolean    g_ascii_isxdigit                (gchar c);

gint        g_ascii_digit_value             (gchar c);
gint        g_ascii_xdigit_value            (gchar c);

gint        g_ascii_strcasecmp              (const gchar *s1, const gchar *s2);
gint        g_ascii_strncasecmp             (const gchar *s1, const gchar *s2, gsize n);

gchar*      g_ascii_strup                   (const gchar *str, gssize len);
gchar*      g_ascii_strdown                 (const gchar *str, gssize len);

gchar       g_ascii_tolower                 (gchar c);
gchar       g_ascii_toupper                 (gchar c);

GString*    g_string_ascii_up               (GString *string);
GString*    g_string_ascii_down             (GString *string);

gchar*      g_strup                         (gchar *string);
gchar*      g_strdown                       (gchar *string);

gint        g_strcasecmp                    (const gchar *s1, const gchar *s2);
gint        g_strncasecmp                   (const gchar *s1, const gchar *s2, guint n);

gchar*      g_strreverse                    (gchar *string);

guint64     g_ascii_strtoull                (const gchar *nptr, gchar **endptr, guint base);
#define     G_ASCII_DTOSTR_BUF_SIZE
gdouble     g_ascii_strtod                  (const gchar *nptr, gchar **endptr);
gchar*      g_ascii_dtostr                  (gchar *buffer, gint buf_len, gdouble d);
gchar*      g_ascii_formatd                 (gchar *buffer, gint buf_len, const gchar *format, gdouble d);
gdouble     g_strtod                        (const gchar *nptr, gchar **endptr);

gchar*      g_strchug                       (gchar *string);
gchar*      g_strchomp                      (gchar *string);
#define     g_strstrip                      ( string )

gchar*      g_strdelimit                    (gchar *string, const gchar *delimiters, gchar new_delimiter);
#define     G_STR_DELIMITERS
gchar*      g_strescape                     (const gchar *source, const gchar *exceptions);
gchar*      g_strcompress                   (const gchar *source);
gchar*      g_strcanon                      (gchar *string, const gchar *valid_chars, gchar substitutor);
gchar**     g_strsplit                      (const gchar *string, const gchar *delimiter, gint max_tokens);
gchar**     g_strsplit_set                  (const gchar *string, const gchar *delimiters, gint max_tokens);
void        g_strfreev                      (gchar **str_array);
gchar*      g_strconcat                     (const gchar *string1, ...);
gchar*      g_strjoin                       (const gchar *separator, ...);
gchar*      g_strjoinv                      (const gchar *separator, gchar **str_array);
guint       g_strv_length                   (gchar **str_array);

const gchar* g_strerror                     (gint errnum);
const gchar* g_strsignal                    (gint signum);

Detailed Description

This section describes a number of utility functions for creating, duplicating, and manipulating strings.

Note that the functions g_printf(), g_fprintf(), g_sprintf(), g_snprintf(), g_vprintf(), g_vfprintf(), g_vsprintf() and g_vsnprintf() are declared in the header gprintf.h which is not included in glib.h (otherwise using glib.h would drag in stdio.h), explicitly include <glib/gprintf.h> in order to use the GLib printf() functions.

While the printf() functions may be used to format UTF-8 strings, notice that the precision of a %Ns parameter is interpreted as the number of bytes, not characters to print. On top of that, the GNU libc implementation of the printf() functions has the "feature" that it checks that the string given for the %Ns parameter consists of a whole number of characters in the current encoding. Avoid using %Ns unless the text is always going to be in an UTF-8 locale or, restricted to ASCII. If intent is to format strings for a certain number of columns, then %Ns is not a correct solution anyway, since it fails to take wide characters (see g_unichar_iswide()) into account.

Details

g_strdup ()

gchar*      g_strdup           (const gchar *str);

Duplicates a string. If str is NULL it returns NULL. The returned string should be freed when no longer needed.

str : | the string to duplicate.
Returns : | a newly-allocated copy of str.

g_strndup ()

gchar*      g_strndup         (const gchar *str, gsize n);

Duplicates the first n characters of a string, returning a newly-allocated buffer n + 1 characters long which will always be null-terminated. If str is less than n characters long the buffer is padded with nulls. If str is NULL it returns NULL. The returned value should be freed when no longer needed.

str : | the string to duplicate part of.
n : | the maximum number of characters to copy from str.
Returns : | a newly-allocated buffer containing the first n characters of str, null-terminated.

g_strdupv ()

gchar**     g_strdupv        (gchar **str_array);

Copies NULL-terminated array of strings. The copy is a deep copy; the new array should be freed by first freeing each string, then the array itself. g_strfreev() does this. If called on a NULL value, g_strdupv() simply returns NULL.

str_array : | NULL-terminated array of strings.
Returns : | a new NULL-terminated array of strings.

g_strnfill ()

gchar*      g_strnfill        (gsize length, gchar fill_char);

Creates a new string length characters long filled with fill_char. The returned string should be freed when no longer needed.

length : | the length of the new string.
fill_char : | the character to fill the string with.
Returns : | a newly-allocated string filled the fill_char.

g_stpcpy ()

gchar*      g_stpcpy          (gchar *dest, const char *src);

Copies a null-terminated string into the dest buffer, include the trailing null, and return a pointer to the trailing null byte. This is useful for concatenating multiple strings together without having to repeatedly scan for the end.

dest : | destination buffer.
src : | source string.
Returns : | a pointer to trailing null byte.

g_strstr_len ()

gchar*      g_strstr_len        (const gchar *haystack, gssize haystack_len, const gchar *needle);

Searches the string haystack for the first occurrence of the string needle, limiting the length of the search to haystack_len.

haystack : | a string.
haystack_len : | the maximum length of haystack.
needle : | the string to search for.
Returns : | a pointer to the found occurrence, or NULL if not found.

g_strrstr ()

gchar*      g_strrstr        (const gchar *haystack, const gchar *needle);

Searches the string haystack for the last occurrence of the string needle.

haystack : | a null-terminated string.
needle : | the null-terminated string to search for.
Returns : | a pointer to the found occurrence, or NULL if not found.

g_strrstr_len ()

gchar*      g_strrstr_len        (const gchar *haystack, gssize haystack_len, const gchar *needle);

Searches the string haystack for the last occurrence of the string needle, limiting the length of the search to haystack_len.

haystack : | a null-terminated string.
haystack_len : | the maximum length of haystack.
needle : | the null-terminated string to search for.
Returns : | a pointer to the found occurrence, or NULL if not found.

g_str_has_prefix ()

gboolean    g_str_has_prefix       (const gchar *str, const gchar *prefix);

Looks whether the string str begins with prefix.

str : | a null-terminated string.
prefix : | the null-terminated prefix to look for.
Returns : | TRUE if str begins with prefix, FALSE otherwise.

g_str_has_suffix ()

gboolean    g_str_has_suffix      (const gchar *str, const gchar *suffix);

Looks whether the string str ends with suffix.

str : | a null-terminated string.
suffix : | the null-terminated suffix to look for.
Returns : | TRUE if str end with suffix, FALSE otherwise.

g_strlcpy ()

gsize       g_strlcpy       (gchar *dest, const gchar *src, gsize dest_size);

Portability wrapper that calls strlcpy() on systems which have it, and emulates strlcpy() otherwise. Copies src to dest; dest is guaranteed to be null-terminated; src must be null-terminated; dest_size is the buffer size, not the number of chars to copy. Caveat: strlcpy() is supposedly more secure than strcpy() or strncpy(), but using, g_strdup() is an even better idea.

dest : | destination buffer
src : | source buffer
dest_size : | length of dest in bytes
Returns : | length of src

g_strlcat ()

gsize       g_strlcat       (gchar *dest, const gchar *src, gsize dest_size);

Portability wrapper that calls strlcat() on systems which have it, and emulates it otherwise. Appends null-terminated src string to dest, guaranteeing null-termination for dest. The total size of dest won't exceed dest_size. Caveat: this is supposedly a more secure alternative to strcat() or strncat(), but for real security g_strconcat() is harder to mess up.

dest : | destination buffer, already containing one null-terminated string
src : | source buffer
dest_size : | length of dest buffer in bytes (not length of existing string inside dest)
Returns : | length of src plus initial length of string in dest

g_strdup_printf ()

gchar*      g_strdup_printf      (const gchar *format, ...);

Similar to the standard C sprintf() function but safer, since it calculates the maximum space required and allocates memory to hold the result. The returned string should be freed when no longer needed.

format : | a standard printf() format string, but notice string precision pitfalls.
... : | the parameters to insert into the format string.
Returns : | a newly-allocated string holding the result.

g_strdup_vprintf ()

gchar*      g_strdup_vprintf      (const gchar *format, va_list args);

Similar to the standard C vsprintf() function but safer, since it calculates the maximum space required and allocates memory to hold the result. The returned string should be freed when no longer needed.

See also g_vasprintf(), which offers the same functionality, but additionally returns the length of the allocated string.

format : | a standard printf() format string, but notice string precision pitfalls.
args : | the list of parameters to insert into the format string.
Returns : | a newly-allocated string holding the result.

g_printf ()

gint        g_printf        (gchar const *format, ...);

An implementation of the standard printf() function which supports positional parameters, as specified in the Single Unix Specification.

format : | a standard printf() format string, but notice string precision pitfalls.
... : | the arguments to insert in the output.
Returns : | the number of characters printed.

g_vprintf ()

gint        g_vprintf       (gchar const *format, va_list args);

An implementation of the standard vprintf() function which supports positional parameters, as specified in the Single Unix Specification.

format : | a standard printf() format string, but notice string precision pitfalls.
args : | the list of arguments to insert in the output.
Returns : | the number of characters printed.

g_fprintf ()

gint        g_fprintf     (FILE *file, gchar const *format, ...);

An implementation of the standard fprintf() function which supports positional parameters, as specified in the Single Unix Specification.

file : | the stream to write to.
format : | a standard printf() format string, but notice string precision pitfalls.
... : | the arguments to insert in the output.
Returns : | the number of characters printed.

g_vfprintf ()

gint        g_vfprintf      (FILE *file, gchar const *format, va_list args);

An implementation of the standard fprintf() function which supports positional parameters, as specified in the Single Unix Specification.

file : | the stream to write to.
format : | a standard printf() format string, but notice string precision pitfalls.
args : | the list of arguments to insert in the output.
Returns : | the number of characters printed.

g_sprintf ()

gint        g_sprintf         (gchar *string, gchar const *format, ...);

An implementation of the standard sprintf() function which supports positional parameters, as specified in the Single Unix Specification.

string : | the buffer to hold the output.
format : | a standard printf() format string, but notice string precision pitfalls.
... : | the arguments to insert in the output.
Returns : | the number of characters printed.

g_vsprintf ()

gint        g_vsprintf        (gchar *string, gchar const *format, va_list args);

An implementation of the standard vsprintf() function which supports positional parameters, as specified in the Single Unix Specification.

string : | the buffer to hold the output.
format : | a standard printf() format string, but notice string precision pitfalls.
args : | the list of arguments to insert in the output.
Returns : | the number of characters printed.

g_snprintf ()

gint        g_snprintf       (gchar *string, gulong n, gchar const *format, ...);

A safer form of the standard sprintf() function. The output is guaranteed to not exceed n characters (including the terminating null character), so it is easy to ensure that a buffer overflow cannot occur.

See also g_strdup_printf().

In versions of GLib prior to 1.2.3, this function may return -1 if the output was truncated, and the truncated string may not be null-terminated. In versions prior to 1.3.12, this function returns the length of the output string.

The return value of g_snprintf() conforms to the snprintf() function as standardized in ISO C99. Note that this is different from traditional snprintf(), which returns the length of the output string.

The format string may contain positional parameters, as specified in the Single Unix Specification.

string : | the buffer to hold the output.
n : | the maximum number of characters to produce (including the terminating null character).
format : | a standard printf() format string, but notice string precision pitfalls.
... : | the arguments to insert in the output.
Returns : | the number of characters which would be produced if the buffer was large enough.

g_vsnprintf ()

gint        g_vsnprintf          (gchar *string, gulong n, gchar const *format, va_list args);

A safer form of the standard vsprintf() function. The output is guaranteed to not exceed n characters (including the terminating null character), so it is easy to ensure that a buffer overflow cannot occur.

See also g_strdup_vprintf().

In versions of GLib prior to 1.2.3, this function may return -1 if the output was truncated, and the truncated string may not be null-terminated. In versions prior to 1.3.12, this function returns the length of the output string.

The return value of g_vsnprintf() conforms to the vsnprintf() function as standardized in ISO C99. Note that this is different from traditional vsnprintf(), which returns the length of the output string.

The format string may contain positional parameters, as specified in the Single Unix Specification.

string : | the buffer to hold the output.
n : | the maximum number of characters to produce (including the terminating null character).
format : | a standard printf() format string, but notice string precision pitfalls.
args : | the list of arguments to insert in the output.
Returns : | the number of characters which would be produced if the buffer was large enough.

g_vasprintf ()

gint        g_vasprintf         (gchar **string, gchar const *format, va_list args);

An implementation of the GNU vasprintf() function which supports positional parameters, as specified in the Single Unix Specification. This function is similar to g_vsprintf(), except that it allocates a string to hold the output, instead of putting the output in a buffer allocate in advance.

string : | the return location for the newly-allocated string.
format : | a standard printf() format string, but notice string precision pitfalls.
args : | the list of arguments to insert in the output.
Returns : | the number of characters printed.

g_printf_string_upper_bound ()

gsize       g_printf_string_upper_bound     (const gchar *format, va_list args);

Calculates the maximum space needed to store the output of the sprintf() function.

format : | the format string. See the printf() documentation.
args : | the parameters to be inserted into the format string.
Returns : | the maximum space needed to store the formatted string.

g_ascii_isalnum ()

gboolean    g_ascii_isalnum           (gchar c);

Determines whether a character is alphanumeric.

Unlike the standard C library isalnum() function, this only recognizes standard ASCII letters and ignores the locale, returning FALSE for all non-ASCII characters. Also unlike the standard library function, this takes a char, not an int, so don't call it on EOF but no need to cast to guchar before passing a possibly non-ASCII character in.

c : | any character
Returns : | TRUE if c is an ASCII alphanumeric character

g_ascii_isalpha ()

gboolean    g_ascii_isalpha          (gchar c);

Determines whether a character is alphabetic (i.e. a letter).

Unlike the standard C library isalpha() function, this only recognizes standard ASCII letters and ignores the locale, returning FALSE for all non-ASCII characters. Also unlike the standard library function, this takes a char, not an int, so don't call it on EOF but no need to cast to guchar before passing a possibly non-ASCII character in.

c : | any character
Returns : | TRUE if c is an ASCII alphabetic character

g_ascii_iscntrl ()

gboolean    g_ascii_iscntrl        (gchar c);

Determines whether a character is a control character.

Unlike the standard C library iscntrl() function, this only recognizes standard ASCII control characters and ignores the locale, returning FALSE for all non-ASCII characters. Also unlike the standard library function, this takes a char, not an int, so don't call it on EOF but no need to cast to guchar before passing a possibly non-ASCII character in.

c : | any character
Returns : | TRUE if c is an ASCII control character.

g_ascii_isdigit ()

gboolean    g_ascii_isdigit        (gchar c);

Determines whether a character is digit (0-9).

Unlike the standard C library isdigit() function, this takes a char, not an int, so don't call it on EOF but no need to cast to guchar before passing a possibly non-ASCII character in.

c : | any character
Returns : | TRUE if c is an ASCII digit.

g_ascii_isgraph ()

gboolean    g_ascii_isgraph         (gchar c);

Determines whether a character is a printing character and not a space.

Unlike the standard C library isgraph() function, this only recognizes standard ASCII characters and ignores the locale, returning FALSE for all non-ASCII characters. Also unlike the standard library function, this takes a char, not an int, so don't call it on EOF but no need to cast to guchar before passing a possibly non-ASCII character in.

c : | any character
Returns : | TRUE if c is an ASCII printing character other than space.

g_ascii_islower ()

gboolean    g_ascii_islower        (gchar c);

Determines whether a character is an ASCII lower case letter.

Unlike the standard C library islower() function, this only recognizes standard ASCII letters and ignores the locale, returning FALSE for all non-ASCII characters. Also unlike the standard library function, this takes a char, not an int, so don't call it on EOF but no need to worry about casting to guchar before passing a possibly non-ASCII character in.

c : | any character
Returns : | TRUE if c is an ASCII lower case letter

g_ascii_isprint ()

gboolean    g_ascii_isprint        (gchar c);

Determines whether a character is a printing character.

Unlike the standard C library isprint() function, this only recognizes standard ASCII characters and ignores the locale, returning FALSE for all non-ASCII characters. Also unlike the standard library function, this takes a char, not an int, so don't call it on EOF but no need to cast to guchar before passing a possibly non-ASCII character in.

c : | any character
Returns : | TRUE if c is an ASCII printing character.

g_ascii_ispunct ()

gboolean    g_ascii_ispunct          (gchar c);

Determines whether a character is a punctuation character.

Unlike the standard C library ispunct() function, this only recognizes standard ASCII letters and ignores the locale, returning FALSE for all non-ASCII characters. Also unlike the standard library function, this takes a char, not an int, so don't call it on EOF but no need to cast to guchar before passing a possibly non-ASCII character in.

c : | any character
Returns : | TRUE if c is an ASCII punctuation character.

g_ascii_isspace ()

gboolean    g_ascii_isspace          (gchar c);

Determines whether a character is a white-space character.

Unlike the standard C library isspace() function, this only recognizes standard ASCII white-space and ignores the locale, returning FALSE for all non-ASCII characters. Also unlike the standard library function, this takes a char, not an int, so don't call it on EOF but no need to cast to guchar before passing a possibly non-ASCII character in.

c : | any character
Returns : | TRUE if c is an ASCII white-space character

g_ascii_isupper ()

gboolean    g_ascii_isupper        (gchar c);

Determines whether a character is an ASCII upper case letter.

Unlike the standard C library isupper() function, this only recognizes standard ASCII letters and ignores the locale, returning FALSE for all non-ASCII characters. Also unlike the standard library function, this takes a char, not an int, so don't call it on EOF but no need to worry about casting to guchar before passing a possibly non-ASCII character in.

c : | any character
Returns : | TRUE if c is an ASCII upper case letter

g_ascii_isxdigit ()

gboolean    g_ascii_isxdigit        (gchar c);

Determines whether a character is a hexadecimal-digit character.

Unlike the standard C library isxdigit() function, this takes a char, not an int, so don't call it on EOF but no need to cast to guchar before passing a possibly non-ASCII character in.

c : | any character
Returns : | TRUE if c is an ASCII hexadecimal-digit character.

g_ascii_digit_value ()

gint        g_ascii_digit_value     (gchar c);

Determines the numeric value of a character as a decimal digit. Differs from g_unichar_digit_value() because it takes a char, so there's no worry about sign extension if characters are signed.

c : | an ASCII character.
Returns : | If c is a decimal digit (according to g_ascii_isdigit()), its numeric value. Otherwise, -1.

g_ascii_xdigit_value ()

gint        g_ascii_xdigit_value     (gchar c);

Determines the numeric value of a character as a hexadecimal digit. Differs from g_unichar_xdigit_value() because it takes a char, so there's no worry about sign extension if characters are signed.

c : | an ASCII character.
Returns : | If c is a hex digit (according to g_ascii_isxdigit()), its numeric value. Otherwise, -1.

g_ascii_strcasecmp ()

gint        g_ascii_strcasecmp              (const gchar *s1, const gchar *s2);

Compare two strings, ignoring the case of ASCII characters.

Unlike the BSD strcasecmp() function, this only recognizes standard ASCII letters and ignores the locale, treating all non-ASCII bytes as if they are not letters.

This function should be used only on strings that are known to be in encodings where the bytes corresponding to ASCII letters always represent themselves. This includes UTF-8 and the ISO-8859-* char sets, but not for instance double-byte encodings like the Windows Codepage 932, where the trailing bytes of double-byte characters include all ASCII letters. If two CP932 strings are compared using this function, false matches are obtained.

s1 : | string to compare with s2.
s2 : | string to compare with s1.
Returns : | 0 if the strings match, a negative value if s1 < s2, or a positive value if s1 > s2. .

g_ascii_strncasecmp ()

gint        g_ascii_strncasecmp             (const gchar *s1, const gchar *s2, gsize n);

Compare s1 and s2, ignoring the case of ASCII characters and any characters after the first n in each string.

Unlike the BSD strcasecmp() function, this only recognizes standard ASCII letters and ignores the locale, treating all non-ASCII characters as if they are not letters.

The same warning as in g_ascii_strcasecmp() applies: Use this function only on strings known to be in encodings where bytes corresponding to ASCII letters always represent themselves.

s1 : | string to compare with s2.
s2 : | string to compare with s1.
n : | number of characters to compare.
Returns : | 0 if the strings match, a negative value if s1 < s2, or a positive value if s1 > s2.

g_ascii_strup ()

gchar*      g_ascii_strup              (const gchar *str, gssize len);

Converts all lower case ASCII letters to upper case ASCII letters.

str : | a string.
len : | length of str in bytes, or -1 if str is null-terminated.
Returns : | a newly allocated string, with all the lower case characters in str converted to upper case, with semantics that exactly match g_ascii_toupper(). (Note that this is unlike the old g_strup(), which modified the string in place.)

g_ascii_strdown ()

gchar*      g_ascii_strdown            (const gchar *str, gssize len);

Converts all upper case ASCII letters to lower case ASCII letters.

str : | a string.
len : | length of str in bytes, or -1 if str is null-terminated.
Returns : | a newly-allocated string, with all the upper case characters in str converted to lower case, with semantics that exactly match g_ascii_tolower(). (Note that this is unlike the old g_strdown(), which modified the string in place.)

g_ascii_tolower ()

gchar       g_ascii_tolower          (gchar c);

Convert a character to ASCII lower case.

Unlike the standard C library tolower() function, this only recognizes standard ASCII letters and ignores the locale, returning all non-ASCII characters unchanged, even if they are lower case letters in a particular character set. Also unlike the standard library function, this takes and returns a char, not an int, so don't call it on EOF but no need to worry about casting to guchar before passing a possibly non-ASCII character in.

c : | any character.
Returns : | the result of converting c to lower case. If c is not an ASCII upper case letter, c is returned unchanged.

g_ascii_toupper ()

gchar       g_ascii_toupper           (gchar c);

Convert a character to ASCII upper case.

Unlike the standard C library toupper() function, this only recognizes standard ASCII letters and ignores the locale, returning all non-ASCII characters unchanged, even if they are upper case letters in a particular character set. Also unlike the standard library function, this takes and returns a char, not an int, so don't call it on EOF but no need to worry about casting to guchar before passing a possibly non-ASCII character in.

c : | any character.
Returns : | the result of converting c to upper case. If c is not an ASCII lower case letter, c is returned unchanged.

g_string_ascii_up ()

GString*    g_string_ascii_up         (GString *string);

Converts all lower case ASCII letters to upper case ASCII letters.

string : | a GString
Returns : | passed-in string pointer, with all the lower case characters converted to upper case in place, with semantics that exactly match g_ascii_toupper.

g_string_ascii_down ()

GString*    g_string_ascii_down             (GString *string);

Converts all upper case ASCII letters to lower case ASCII letters.

string : | a GString
Returns : | passed-in string pointer, with all the upper case characters converted to lower case in place, with semantics that exactly match g_ascii_tolower.

g_strup ()

gchar*      g_strup                         (gchar *string);

Converts a string to upper case.

Note

Warning: g_strup has been deprecated since version 2.2 and should not be used in newly-written code. This function is totally broken for the reasons discussed in the g_strncasecmp() docs - use g_ascii_strup() or g_utf8_strup() instead.

string : | the string to convert.
Returns : | the string

g_strdown ()

gchar*      g_strdown                       (gchar *string);

Converts a string to lower case.

Note

Warning: g_strdown has been deprecated since version 2.2 and should not be used in newly-written code. This function is totally broken for the reasons discussed in the g_strncasecmp() docs - use g_ascii_strdown() or g_utf8_strdown() instead.

string : | the string to convert.
Returns : | the string

g_strcasecmp ()

gint        g_strcasecmp                    (const gchar *s1, const gchar *s2);

A case-insensitive string comparison, corresponding to the standard strcasecmp() function on platforms which support it.

Note

Warning: g_strcasecmp has been deprecated since version 2.2 and should not be used in newly-written code. See g_strncasecmp() for a discussion of why this function is deprecated and how to replace it.

s1 : | a string.
s2 : | a string to compare with s1.
Returns : | 0 if the strings match, a negative value if s1 < s2, or a positive value if s1 > s2.

g_strncasecmp ()

gint        g_strncasecmp           (const gchar *s1, const gchar *s2, guint n);

A case-insensitive string comparison, corresponding to the standard strncasecmp() function on platforms which support it. It is similar to g_strcasecmp() except it only compares the first n characters of the strings.

Note

Warning: g_strncasecmp has been deprecated since version 2.2 and should not be used in newly-written code. The problem with g_strncasecmp() is that it does the comparison by calling toupper()/tolower(). These functions are locale-specific and operate on single bytes. However, it is impossible to handle things correctly from an I18N standpoint by operating on bytes, since characters may be multi byte. Thus g_strncasecmp() is broken if the string is guaranteed to be ASCII, since it's locale-sensitive, and it's broken if the string is localized, since it does not work on many encodings at all, including UTF-8, EUC-JP, etc.

There are therefore two replacement functions: g_ascii_strncasecmp(), which only works on ASCII and is not locale-sensitive, and g_utf8_casefold(), which is good for case-insensitive sorting of UTF-8.

s1 : | a string.
s2 : | a string to compare with s1.
n : | the maximum number of characters to compare.
Returns : | 0 if the strings match, a negative value if s1 < s2, or a positive value if s1 > s2.

g_strreverse ()

gchar*      g_strreverse           (gchar *string);

Reverses all of the bytes in a string. For example, g_strreverse ("abcdef") will result in "fedcba".

Note that g_strreverse() does not work on UTF-8 strings containing multi byte characters. For that purpose, use g_utf8_strreverse().

string : | the string to reverse.
Returns : | the same pointer passed in as string.

g_ascii_strtoull ()

guint64     g_ascii_strtoull       (const gchar *nptr, gchar **endptr, guint base);

Converts a string to a guint64 value. This function behaves like the standard strtoull() function does in the C locale. It does this without actually changing the current locale, since that would not be thread-safe.

This function is typically used when reading configuration files or other non-user input that should be locale independent. To handle input from the user, the locale-sensitive system strtoull() function is used.

If the correct value would cause overflow, G_MAXUINT64 is returned, and ERANGE is stored in errno. If the base is outside the valid range, zero is returned, and EINVAL is stored in errno. If the string conversion fails, zero is returned, and endptr returns nptr (if endptr is non-NULL).

nptr : | the string to convert to a numeric value.
endptr : | if non-NULL, it returns the character after the last character used in the conversion.
base : | to be used for the conversion, 2..36 or 0
Returns : | the guint64 value or zero on error.

G_ASCII_DTOSTR_BUF_SIZE

#define G_ASCII_DTOSTR_BUF_SIZE (29 + 10)

A good size for a buffer to be passed into g_ascii_dtostr(). It is guaranteed to be enough for all output of that function on systems with 64bit IEEE-compatible doubles.

The typical usage would be something like:

  char buf[G_ASCII_DTOSTR_BUF_SIZE];

  fprintf (out, "value=%s\n", g_ascii_dtostr (buf, sizeof (buf), value));

g_ascii_strtod ()

gdouble     g_ascii_strtod          (const gchar *nptr, gchar **endptr);

Converts a string to a gdouble value. This function behaves like the standard strtod() function does in the C locale. It does this without actually changing the current locale, since that would not be thread-safe.

This function is typically used when reading configuration files or other non-user input that should be locale independent. To handle input from the user, the locale-sensitive system strtod() function is used.

To convert from a gdouble to a string in a locale-insensitive way, use g_ascii_dtostr().

If the correct value would cause overflow, plus or minus HUGE_VAL is returned (according to the sign of the value), and ERANGE is stored in errno. If the correct value would cause underflow, zero is returned and ERANGE is stored in errno.

This function resets errno before calling strtod() so that overflow and underflow can be detected reliably.

nptr : | the string to convert to a numeric value.
endptr : | if non-NULL, it returns the character after the last character used in the conversion.
Returns : | the gdouble value.

g_ascii_dtostr ()

gchar*      g_ascii_dtostr          (gchar *buffer, gint buf_len, gdouble d);

Converts a gdouble to a string, using the '.' as decimal point.

This functions generates enough precision that converting the string back using g_ascii_strtod() gives the same machine-number (on machines with IEEE compatible 64bit doubles). It is guaranteed that the size of the resulting string will never be larger than G_ASCII_DTOSTR_BUF_SIZE bytes.

buffer : | A buffer to place the resulting string in
buf_len : | The length of the buffer.
d : | The gdouble to convert
Returns : | The pointer to the buffer with the converted string.

g_ascii_formatd ()

gchar*      g_ascii_formatd       (gchar *buffer, gint buf_len, const gchar *format, gdouble d);

Converts a gdouble to a string, using the '.' as decimal point. To format the number passed in a printf()-style format string. Allowed conversion specifiers are 'e', 'E', 'f', 'F', 'g' and 'G'.

To serialize the value into a string, use g_ascii_dtostr().

buffer : | A buffer to place the resulting string in
buf_len : | The length of the buffer.
format : | The printf()-style format to use for the code to use for converting.
d : | The gdouble to convert
Returns : | The pointer to the buffer with the converted string.

g_strtod ()

gdouble     g_strtod       (const gchar *nptr, gchar **endptr);

Converts a string to a gdouble value. It calls the standard strtod() function to handle the conversion, but if the string is not completely converted it attempts the conversion again with g_ascii_strtod(), and returns the best match.

This function should seldomly be used. The normal situation when reading numbers not for human consumption is to use g_ascii_strtod().This function must be used only when the expected locale formatted and C formatted numbers are known. Make sure that not to pass strings such as comma separated lists of values, since the commas may be interpreted as a decimal point in some locales, causing unexpected results.

nptr : | the string to convert to a numeric value.
endptr : | if non-NULL, it returns the character after the last character used in the conversion.
Returns : | the gdouble value.

g_strchug ()

gchar*      g_strchug         (gchar *string);

Removes leading white space from a string, by moving the rest of the characters forward.

This function does not allocate or reallocate any memory; it modifies string in place. The pointer to string is returned to allow the nesting of functions.

Also see g_strchomp() and g_strstrip().

string : | a string to remove the leading white space from.
Returns : | string.

g_strchomp ()

gchar*      g_strchomp         (gchar *string);

Removes trailing white space from a string.

This function does not allocate or reallocate any memory; it modifies string in place. The pointer to string is returned to allow the nesting of functions.

Also see g_strchug() and g_strstrip().

string : | a string to remove the trailing white space from.
Returns : | string.

g_strstrip()

#define     g_strstrip( string )

Removes leading and trailing white space from a string. See g_strchomp() and g_strchug().

string : a string to remove the leading and trailing white space from.

g_strdelimit ()

gchar*      g_strdelimit          (gchar *string, const gchar *delimiters, gchar new_delimiter);

Converts any delimiter characters in string to new_delimiter. Any characters in string which are found in delimiters are changed to the new_delimiter character. Modifies string in place, and returns string itself, not a copy. The return value is to allow nesting such as g_ascii_strup (g_strdelimit (str, "abc", '?')).

string : | the string to convert.
delimiters : | a string containing the current delimiters, or NULL to use the standard delimiters defined in G_STR_DELIMITERS.
new_delimiter : | the new delimiter character.
Returns : | string.

G_STR_DELIMITERS

#define	 G_STR_DELIMITERS	"_-|> <."

The standard delimiters, used in g_strdelimit().

g_strescape ()

gchar*      g_strescape          (const gchar *source, const gchar *exceptions);

Escapes the special characters '\b', '\f', '\n', '\r', '\t', '\' and '"' in the string source by inserting a '\' before them. Additionally all characters in the range 0x01-0x1F (everything below SPACE) and in the range 0x7F-0xFF (all non-ASCII chars) are replaced with a '\' followed by their octal representation. Characters supplied in exceptions are not escaped.

g_strcompress() does the reverse conversion.

source : | a string to escape.
exceptions : | a string of characters not to escape in source.
Returns : | a newly-allocated copy of source with certain characters escaped. See above.

g_strcompress ()

gchar*      g_strcompress        (const gchar *source);

Replaces all escaped characters with their one byte equivalent. It does the reverse conversion of g_strescape().

source : | a string to compress.
Returns : | a newly-allocated copy of source with all escaped character compressed.

g_strcanon ()

gchar*      g_strcanon       (gchar *string, const gchar *valid_chars, gchar substitutor);

For each character in string, if the character is not in valid_chars, replaces the character with substitutor. Modifies string in place, and return string itself, not a copy. The return value is to allow nesting such as g_ascii_strup (g_strcanon (str, "abc", '?')).

string : | a null-terminated array of bytes.
valid_chars : | bytes permitted in string.
substitutor : | replacement character for disallowed bytes.
Returns : | string.

g_strsplit ()

gchar**     g_strsplit       (const gchar *string, const gchar *delimiter, gint max_tokens);

Splits a string into a maximum of max_tokens pieces, using the given delimiter. If max_tokens is reached, the remainder of string is appended to the last token.

As a special case, the result of splitting the empty string "" is an empty vector, not a vector containing a single string. The reason for this special case is that being able to represent a empty vector is typically more useful than consistent handling of empty elements. If there is no need to represent empty elements, check for the empty string before calling g_strsplit().

string : | a string to split.
delimiter : | a string which specifies the places at which to split the string. The delimiter is not included in any of the resulting strings, unless max_tokens is reached.
max_tokens : | the maximum number of pieces to split string into. If this is less than 1, the string is split completely.
Returns : | a newly-allocated NULL-terminated array of strings. Use g_strfreev() to free it.

g_strsplit_set ()

gchar**     g_strsplit_set       (const gchar *string, const gchar *delimiters, gint max_tokens);

Splits string into a number of tokens not containing any of the characters in delimiter. A token is the (possibly empty) longest string that does not contain any of the characters in delimiters. If max_tokens is reached, the remainder is appended to the last token.

For example the result of g_strsplit_set ("abc:def/ghi", ":/", -1) is a NULL-terminated vector containing the three strings "abc", "def", and "ghi".

The result if g_strsplit_set (":def/ghi:", ":/", -1) is a NULL-terminated vector containing the four strings "", "def", "ghi", and "".

As a special case, the result of splitting the empty string "" is an empty vector, not a vector containing a single string. The reason for this special case is that being able to represent a empty vector is typically more useful than consistent handling of empty elements. If there is no need to represent empty elements, check for the empty string before calling g_strsplit_set().

Note that this function works on bytes not characters, so it cannot be used to delimit UTF-8 strings for anything but ASCII characters.

string : | The string to be tokenized
delimiters : | A null-terminated string containing bytes that are used to split the string.
max_tokens : | The maximum number of tokens to split string into. If this is less than 1, the string is split completely
Returns : | a newly-allocated NULL-terminated array of strings. Use g_strfreev() to free it.

g_strfreev ()

void        g_strfreev       (gchar **str_array);

Frees a NULL-terminated array of strings, and the array itself. If called on a NULL value, g_strfreev() simply returns.

str_array : a NULL-terminated array of strings to free.

g_strconcat ()

gchar*      g_strconcat         (const gchar *string1, ...);

Concatenates all of the given strings into one long string. The returned string should be freed when no longer needed.

Note

Warning: The variable argument list must end with NULL. If NULL is forgotten, g_strconcat() will start appending random memory junk to the string.

string1 : | The first string to add, which must not be NULL.
... : | a NULL-terminated list of strings to append to the string.
Returns : | a newly-allocated string containing all the string arguments.

g_strjoin ()

gchar*      g_strjoin         (const gchar *separator, ...);

Joins a number of strings together to form one long string, with the optional separator inserted between each of them.

separator : | a string to insert between each of the strings, or NULL.
... : | a NULL-terminated list of strings to join.
Returns : | a newly-allocated string containing all of the strings joined together, with separator between them.

g_strjoinv ()

gchar*      g_strjoinv         (const gchar *separator, gchar **str_array);

Joins a number of strings together to form one long string, with the optional separator inserted between each of them.

separator : | a string to insert between each of the strings, or NULL.
str_array : | a NULL-terminated array of strings to join.
Returns : | a newly-allocated string containing all of the strings joined together, with separator between them.

g_strv_length ()

guint       g_strv_length          (gchar **str_array);

Returns the length of the given NULL-terminated string array str_array.

str_array : | a NULL-terminated array of strings.
Returns : | length of str_array.

g_strerror ()

const gchar* g_strerror        (gint errnum);

Returns a string corresponding to the given error code, e.g. "no such process". This function is included since not all platforms support the strerror() function.

errnum : | the system error number. See the standard C errno documentation.
Returns : | a string describing the error code. If the error code is unknown, it returns "unknown error (<code>)". The string can only be used until the next call to g_strerror().

g_strsignal ()

const gchar* g_strsignal       (gint signum);

Returns a string describing the given signal, e.g. "Segmentation fault". This function is included since not all platforms support the strsignal() function.

signum : | the signal number. See the signal documentation.
Returns : | a string describing the signal. If the signal is unknown, it returns "unknown signal (<signum>)". The string can only be used until the next call to g_strsignal().

Feedback

For additional information or queries on this page send feedback


Strings

Name

Strings — text buffers which grow automatically as text is added.

Library

glib.lib

Synopsis

#include <glib.h>

            GString;
GString*    g_string_new                    (const gchar *init);
GString*    g_string_new_len                (const gchar *init, gssize len);
GString*    g_string_sized_new              (gsize dfl_size);
GString*    g_string_assign                 (GString *string, const gchar *rval);
#define     g_string_sprintf
#define     g_string_sprintfa
void        g_string_printf                 (GString *string, const gchar *format, ...);
void        g_string_append_printf          (GString *string, const gchar *format, ...);
GString*    g_string_append                 (GString *string, const gchar *val);
GString*    g_string_append_c               (GString *string, gchar c);
GString*    g_string_append_unichar         (GString *string, gunichar wc);
GString*    g_string_append_len             (GString *string, const gchar *val, gssize len);
GString*    g_string_prepend                (GString *string, const gchar *val);
GString*    g_string_prepend_c              (GString *string, gchar c);
GString*    g_string_prepend_unichar        (GString *string, gunichar wc);
GString*    g_string_prepend_len            (GString *string, const gchar *val, gssize len);
GString*    g_string_insert                 (GString *string, gssize pos, const gchar *val);
GString*    g_string_insert_c               (GString *string, gssize pos, gchar c);
GString*    g_string_insert_unichar         (GString *string, gssize pos, gunichar wc);
GString*    g_string_insert_len             (GString *string, gssize pos, const gchar *val, gssize len);
GString*    g_string_erase                  (GString *string, gssize pos, gssize len);
GString*    g_string_truncate               (GString *string, gsize len);
GString*    g_string_set_size               (GString *string, gsize len);
gchar*      g_string_free                   (GString *string, gboolean free_segment);

GString*    g_string_up                     (GString *string);
GString*    g_string_down                   (GString *string);

guint       g_string_hash                   (const GString *str);
gboolean    g_string_equal                  (const GString *v, const GString *v2);

Detailed Description

A GString is similar to a standard C string, except that it grows automatically as text is appended or inserted. Also, it stores the length of the string, so can be used for binary data with embedded nul bytes.

Details

GString

typedef struct {
  gchar  *str;
  gsize len;
  gsize allocated_len;
} GString;

The GString struct contains the public fields of a GString. The str field points to the character data. It may move as text is added. The len field contains the length of the string, not including the terminating nul byte.

The str field is nul-terminated and so can be used as an ordinary C string. But it may be moved when text is appended or inserted into the string.

g_string_new ()

GString*    g_string_new                    (const gchar *init);

Creates a new GString, initialized with the given string.

init : | the initial text to copy into the string.
Returns : | the new GString.

g_string_new_len ()

GString*    g_string_new_len                (const gchar *init, gssize len);

Creates a new GString with len bytes of the init buffer. Because a length is provided, init need not be nul-terminated, and can contain embedded nul bytes.

init : | initial contents of string.
len : | length of init to use.
Returns : | a new GString.

g_string_sized_new ()

GString*    g_string_sized_new              (gsize dfl_size);

Creates a new GString, with enough space for dfl_size bytes. This is useful to add a lot of text to the string and do not want it to be reallocated too often.

dfl_size : | the default size of the space allocated to hold the string.
Returns : | the new GString.

g_string_assign ()

GString*    g_string_assign                 (GString *string, const gchar *rval);

Copies the bytes from a string into a GString, destroying any previous contents. It is rather like the standard strcpy() function, except that there is no need to worry about having enough space to copy the string.

string : | the destination GString. Its current contents are destroyed.
rval : | the string to copy into string
Returns : | the destination GString.

g_string_sprintf

#define     g_string_sprintf

Writes a formatted string into a GString. This is similar to the standard sprintf() function, except that the GString buffer automatically expands to contain the results. The previous contents of the GString are destroyed.

Note

Warning: g_string_sprintf is deprecated and should not be used in newly-written code. This function has been renamed to g_string_printf().

g_string_sprintfa

#define     g_string_sprintfa

Appends a formatted string onto the end of a GString. This function is similar to g_string_sprintf() except that the text is appended to the GString.

Note

Warning: g_string_sprintfa is deprecated and should not be used in newly-written code. This function has been renamed to g_string_append_printf().

g_string_printf ()

void        g_string_printf                 (GString *string, const gchar *format, ...);

Writes a formatted string into a GString. This is similar to the standard sprintf() function, except that the GString buffer automatically expands to contain the results. The previous contents of the GString are destroyed.

string : | a GString.
format : | the string format. See the printf() documentation.
... : | the parameters to insert into the format string.

g_string_append_printf ()

void        g_string_append_printf          (GString *string, const gchar *format, ...);

Appends a formatted string onto the end of a GString. This function is similar to g_string_printf() except that the text is appended to the GString.

string : | a GString.
format : | the string format. See the printf() documentation.
... : | the parameters to insert into the format string.

g_string_append ()

GString*    g_string_append                 (GString *string, const gchar *val);

Adds a string onto the end of a GString, expanding it if necessary.

string : | a GString.
val : | the string to append onto the end of the GString.
Returns : | the GString.

g_string_append_c ()

GString*    g_string_append_c               (GString *string, gchar c);

Adds a byte onto the end of a GString, expanding it if necessary.

string : | a GString.
c : | the byte to append onto the end of the GString.
Returns : | the GString.

g_string_append_unichar ()

GString*    g_string_append_unichar         (GString *string, gunichar wc);

Converts a Unicode character into UTF-8, and appends it to the string.

string : | a GString
wc : | a Unicode character
Returns : | string

g_string_append_len ()

GString*    g_string_append_len             (GString *string, const gchar *val, gssize len);

Appends len bytes of val to string. Because len is provided, val may contain embedded nulls and need not be nul-terminated.

string : | a GString.
val : | bytes to append.
len : | number of bytes of val to use.
Returns : | the GString.

g_string_prepend ()

GString*    g_string_prepend                (GString *string, const gchar *val);

Adds a string on to the start of a GString, expanding it if necessary.

string : | a GString.
val : | the string to prepend on the start of the GString.
Returns : | the GString.

g_string_prepend_c ()

GString*    g_string_prepend_c              (GString *string, gchar c);

Adds a byte onto the start of a GString, expanding it if necessary.

string : | a GString.
c : | the byte to prepend on the start of the GString.
Returns : | the GString.

g_string_prepend_unichar ()

GString*    g_string_prepend_unichar        (GString *string, gunichar wc);

Converts a Unicode character into UTF-8, and prepends it to the string.

string : | a GString.
wc : | a Unicode character.
Returns : | string.

g_string_prepend_len ()

GString*    g_string_prepend_len            (GString *string,  const gchar *val, gssize len);

Prepends len bytes of val to string. Because len is provided, val may contain embedded nulls and need not be nul-terminated.

string : | a GString.
val : | bytes to prepend.
len : | number of bytes in val to prepend.
Returns : | the GString passed in.

g_string_insert ()

GString*    g_string_insert        (GString *string, gssize pos, const gchar *val);

Inserts a copy of a string into a GString, expanding it if necessary.

string : | a GString.
pos : | the position to insert the copy of the string.
val : | the string to insert.
Returns : | the GString.

g_string_insert_c ()

GString*    g_string_insert_c       (GString *string, gssize pos, gchar c);

Inserts a byte into a GString, expanding it if necessary.

string : | a GString.
pos : | the position to insert the byte.
c : | the byte to insert.
Returns : | the GString.

g_string_insert_unichar ()

GString*    g_string_insert_unichar         (GString *string, gssize pos, gunichar wc);

Converts a Unicode character into UTF-8, and insert it into the string at the given position.

string : | a GString
pos : | the position at which to insert character, or -1 to append at the end of the string.
wc : | a Unicode character
Returns : | string

g_string_insert_len ()

GString*    g_string_insert_len             (GString *string, gssize pos, const gchar *val, gssize len);

Inserts len bytes of val into string at pos. Because len is provided, val may contain embedded nulls and need not be nul-terminated. If pos is -1, bytes are inserted at the end of the string.

string : | a GString.
pos : | position in string where insertion should happen, or -1 for at the end.
val : | bytes to insert.
len : | number of bytes of val to insert.
Returns : | the GString.

g_string_erase ()

GString*    g_string_erase          (GString *string, gssize pos, gssize len);

Removes len bytes from a GString, starting at position pos. The rest of the GString is shifted down to fill the gap.

string : | a GString.
pos : | the position of the content to remove.
len : | the number of bytes to remove, or -1 to remove all following bytes.
Returns : | the GString.

g_string_truncate ()

GString*    g_string_truncate          (GString *string, gsize len);

Cuts off the end of the GString, leaving the first len bytes.

string : | a GString.
len : | the new size of the GString.
Returns : | the GString.

g_string_set_size ()

GString*    g_string_set_size        (GString *string, gsize len);

Sets the length of a GString. If the length is less than the current length, the string will be truncated. If the length is greater than the current length, the contents of the newly added area are undefined. (However, as always, string->str[string->len] will be a nul byte.)

string : | a GString
len : | the new length
Returns : | string

g_string_free ()

gchar*      g_string_free        (GString *string, gboolean free_segment);

Frees the memory allocated for the GString. If free_segment is TRUE it also frees the character data.

string : | a GString.
free_segment : | if TRUE the actual character data is freed as well.
Returns : | the character data of string (i.e. NULL if free_segment is TRUE)

g_string_up ()

GString*    g_string_up           (GString *string);

Converts a GString to uppercase.

Note

Warning: g_string_up has been deprecated since version 2.2 and should not be used in newly-written code. This function uses the locale-specific toupper() function, which is almost never the right thing. Use g_string_ascii_up() or g_utf8_strup() instead.

string : | a GString
Returns : | the GString

g_string_down ()

GString*    g_string_down          (GString *string);

Converts a GString to lowercase.

Note

Warning: g_string_down has been deprecated since version 2.2 and should not be used in newly-written code. This function uses the locale-specific tolower() function, which is almost never the right thing. Use g_string_ascii_down() or g_utf8_strdown() instead.

string : | a GString
Returns : | the GString.

g_string_hash ()

guint       g_string_hash        (const GString *str);

Creates a hash code for str; for use with GHashTable.

str : | a string to hash.
Returns : | hash code for str.

g_string_equal ()

gboolean    g_string_equal           (const GString *v, const GString *v2);

Compares two strings for equality, returning TRUE if they are equal. For use with GHashTable.

v : | a GString.
v2 : | another GString.
Returns : | TRUE if they strings are the same length and contain the same bytes.

Feedback

For additional information or queries on this page send feedback


The Main Event Loop

Name

The Main Event Loop — manages all available sources of events.

Library

glib.lib

Synopsis

#include <glib.h>

GMainLoop;
GMainLoop*  g_main_loop_new                    (GMainContext *context, gboolean is_running);
GMainLoop*  g_main_loop_ref                    (GMainLoop *loop);
void        g_main_loop_unref                  (GMainLoop *loop);
void        g_main_loop_run                    (GMainLoop *loop);
void        g_main_loop_quit                   (GMainLoop *loop);
gboolean    g_main_loop_is_running             (GMainLoop *loop);
GMainContext* g_main_loop_get_context          (GMainLoop *loop);
#define     g_main_new                         (is_running)
#define     g_main_destroy                     (loop)
#define     g_main_run                         (loop)
#define     g_main_quit                        (loop)
#define     g_main_is_running                  (loop)

#define     G_PRIORITY_HIGH
#define     G_PRIORITY_DEFAULT
#define     G_PRIORITY_HIGH_IDLE
#define     G_PRIORITY_DEFAULT_IDLE
#define     G_PRIORITY_LOW

GMainContext;
GMainContext* g_main_context_new               (void);
GMainContext* g_main_context_ref               (GMainContext *context);
void        g_main_context_unref               (GMainContext *context);
GMainContext* g_main_context_default           (void);
gboolean    g_main_context_iteration           (GMainContext *context, gboolean may_block);
#define     g_main_iteration                   (may_block)
gboolean    g_main_context_pending             (GMainContext *context);
#define     g_main_pending                     ()

GSource*    g_main_context_find_source_by_id               (GMainContext *context, guint source_id);
GSource*    g_main_context_find_source_by_user_data        (GMainContext *context, gpointer user_data);
GSource*    g_main_context_find_source_by_funcs_user_data  (GMainContext *context, GSourceFuncs *funcs, gpointer user_data);

void        g_main_context_wakeup              (GMainContext *context);
gboolean    g_main_context_acquire             (GMainContext *context);
void        g_main_context_release             (GMainContext *context);
gboolean    g_main_context_is_owner            (GMainContext *context);

gboolean    g_main_context_wait                (GMainContext *context, GCond *cond, GMutex *mutex);
gboolean    g_main_context_prepare             (GMainContext *context, gint *priority);
gint        g_main_context_query               (GMainContext *context, gint max_priority, gint *timeout_, GPollFD *fds, gint n_fds);
gint        g_main_context_check               (GMainContext *context, gint max_priority, GPollFD *fds, gint n_fds);
void        g_main_context_dispatch            (GMainContext *context);
void        g_main_context_set_poll_func       (GMainContext *context, GPollFunc func);
GPollFunc   g_main_context_get_poll_func       (GMainContext *context);
gint        (*GPollFunc)                       (GPollFD *ufds, guint nfsd, gint timeout_);
void        g_main_context_add_poll            (GMainContext *context, GPollFD *fd, gint priority);
void        g_main_context_remove_poll         (GMainContext *context, GPollFD *fd);
int         g_main_depth                       (void);
#define     g_main_set_poll_func               (func)

GSource*    g_timeout_source_new               (guint interval);
guint       g_timeout_add                      (guint interval, GSourceFunc function, gpointer data);
guint       g_timeout_add_full                 (gint priority, guint interval, GSourceFunc function, gpointer data, GDestroyNotify notify);

GSource*    g_idle_source_new                  (void);
guint       g_idle_add                         (GSourceFunc function, gpointer data);
guint       g_idle_add_full                    (gint priority, GSourceFunc function, gpointer data, GDestroyNotify notify);
gboolean    g_idle_remove_by_data              (gpointer data);

typedef     GPid;
void        (*GChildWatchFunc)                 (GPid pid, gint status, gpointer data);
GSource*    g_child_watch_source_new           (GPid pid);
guint       g_child_watch_add                  (GPid pid, GChildWatchFunc function, gpointer data);
guint       g_child_watch_add_full             (gint priority, GPid pid, GChildWatchFunc function, gpointer data,
                                                GDestroyNotify notify);

            GPollFD;

            GSource;
void        (*GSourceDummyMarshal)             (void);
            GSourceFuncs;
            GSourceCallbackFuncs;
GSource*    g_source_new                       (GSourceFuncs *source_funcs, guint struct_size);
GSource*    g_source_ref                       (GSource *source);
void        g_source_unref                     (GSource *source);
guint       g_source_attach                    (GSource *source, GMainContext *context);
void        g_source_destroy                   (GSource *source);
void        g_source_set_priority              (GSource *source, gint priority);
gint        g_source_get_priority              (GSource *source);
void        g_source_set_can_recurse           (GSource *source, gboolean can_recurse);
gboolean    g_source_get_can_recurse           (GSource *source);
guint       g_source_get_id                    (GSource *source);
GMainContext* g_source_get_context             (GSource *source);
void        g_source_set_callback              (GSource *source, GSourceFunc func, gpointer data, GDestroyNotify notify);
gboolean    (*GSourceFunc)                     (gpointer data);
void        g_source_set_callback_indirect     (GSource *source, gpointer callback_data, GSourceCallbackFuncs *callback_funcs);
void        g_source_add_poll                  (GSource *source, GPollFD *fd);
void        g_source_remove_poll               (GSource *source, GPollFD *fd);
void        g_source_get_current_time          (GSource *source, GTimeVal *timeval);
gboolean    g_source_remove                    (guint tag);
gboolean    g_source_remove_by_funcs_user_data (GSourceFuncs *funcs, gpointer user_data);
gboolean    g_source_remove_by_user_data       (gpointer user_data);

Detailed Description

The main event loop manages all the available sources of events for GLib and GTK+ applications. These events can come from any number of different types of sources such as file descriptors (plain files, pipes or sockets) and timeouts. New types of event sources can also be added using g_source_attach().

To allow multiple independent sets of sources to be handled in different threads, each source is associated with a GMainContext. A GMainContext can only be running in a single thread, but sources can be added to it and removed from it from other threads.

Each event source is assigned a priority. The default priority, G_PRIORITY_DEFAULT, is 0. Values less than 0 denote higher priorities. Values greater than 0 denote lower priorities. Events from high priority sources are always processed before events from lower priority sources.

Idle functions can also be added, and assigned a priority. These will be run whenever no events with a higher priority are ready to be processed.

The GMainLoop data type represents a main event loop. A GMainLoop is created with g_main_loop_new(). After adding the initial event sources, g_main_loop_run() is called. This continuously checks for new events from each of the event sources and dispatches them. Finally, the processing of an event from one of the sources leads to a call to g_main_loop_quit() to exit the main loop, and g_main_loop_run() returns.

It is possible to create new instances of GMainLoop recursively. This is often used in GTK+ applications when showing modal dialog boxes. Note that event sources are associated with a particular GMainContext, and will be checked and dispatched for all main loops associated with that GMainContext.

 GTK+ contains wrappers of some of these functions, e.g.
gtk_main(),

gtk_main_quit()
and gtk_events_pending().

Creating new sources types

One of the unusual features of the GTK+ main loop functionality is that new types of event source can be created and used in addition to the builtin type of event source. A new event source type is used for handling GDK events. A new source type is created by deriving from the GSource structure. The derived type of source is represented by a structure that has the GSource structure as a first element, and other elements specific to the new source type. To create an instance of the new source type, call g_source_new() passing in the size of the derived structure and a table of functions. These GSourceFuncs determine the behavior of the new source types.

New source types basically interact with with the main context in two ways. Their prepare function in GSourceFuncs can set a timeout to determine the maximum amount of time that the main loop will sleep before checking the source again. In addition, or as well, the source can add file descriptors to the set that the main context checks using g_source_add_poll().

Customizing the main loop iteration

Single iterations of a GMainContext can be run with g_main_context_iteration(). In some cases, more detailed control of exactly how the details of the main loop work is desired, for instance, when integrating the GMainLoop with an external main loop. In such cases, call the component functions of g_main_context_iteration() directly. These functions are g_main_context_prepare(), g_main_context_query(), g_main_context_check() and g_main_context_dispatch().

The operation of these functions can best be seen in terms of a state diagram, as shown in Figure 1, “States of a Main Context”.

Figure 1. States of a Main Context

States of a Main Context

Details

GMainLoop

typedef struct _GMainLoop GMainLoop;

The GMainLoop struct is an opaque data type representing the main event loop of a GLib or GTK+ application.

g_main_loop_new ()

GMainLoop*  g_main_loop_new          GMainContext *context, gboolean is_running);

Creates a new GMainLoop structure.

context : | a GMainContext (if NULL, the default context will be used).
is_running : | set to TRUE to indicate that the loop is running. This is not very important since calling g_main_loop_run() will set this to TRUE anyway.
Returns : | a new GMainLoop.

g_main_loop_ref ()

GMainLoop*  g_main_loop_ref        (GMainLoop *loop);

Increases the reference count on a GMainLoop object by one.

loop : | a GMainLoop
Returns : | loop

g_main_loop_unref ()

void        g_main_loop_unref          (GMainLoop *loop);

Decreases the reference count on a GMainLoop object by one. If the result is zero, free the loop and free all associated memory.

loop : a GMainLoop

g_main_loop_run ()

void        g_main_loop_run            (GMainLoop *loop);

Runs a main loop until g_main_loop_quit() is called on the loop. If this is called for the thread of the loop's GMainContext, it will process events from the loop, otherwise it will simply wait.

loop : a GMainLoop

g_main_loop_quit ()

void        g_main_loop_quit          (GMainLoop *loop);

Stops a GMainLoop from running. Any calls to g_main_loop_run() for the loop will return.

loop : a GMainLoop

g_main_loop_is_running ()

gboolean    g_main_loop_is_running          (GMainLoop *loop);

Checks to see if the main loop is currently being run via g_main_loop_run().

loop : | a GMainLoop.
Returns : | TRUE if the mainloop is currently being run.

g_main_loop_get_context ()

GMainContext* g_main_loop_get_context       (GMainLoop *loop);

Returns the GMainContext of loop.

loop : | a GMainLoop.
Returns : | the GMainContext of loop

g_main_new()

#define     g_main_new(is_running)

Creates a new GMainLoop for the default main loop.

Note

Warning: g_main_new has been deprecated since version 2.2 and should not be used in newly-written code. Use g_main_loop_new() instead.

is_running : | set to TRUE to indicate that the loop is running. This is not very important since calling g_main_run() will set this to TRUE anyway.
Returns : | a new GMainLoop.

g_main_destroy()

#define     g_main_destroy(loop)

Frees the memory allocated for the GMainLoop.

Note

Warning: g_main_destroy has been deprecated since version 2.2 and should not be used in newly-written code. Use g_main_loop_unref() instead.

loop : a GMainLoop.

g_main_run()

#define     g_main_run(loop)

Runs a main loop until it stops running.

Note

Warning: g_main_run has been deprecated since version 2.2 and should not be used in newly-written code. Use g_main_loop_run() instead.

loop : a GMainLoop.

g_main_quit()

#define     g_main_quit(loop)

Stops the GMainLoop. If g_main_run() was called to run the GMainLoop, it will now return.

Note

Warning: g_main_quit has been deprecated since version 2.2 and should not be used in newly-written code. Use g_main_loop_quit() instead.

loop : a GMainLoop.

g_main_is_running()

#define     g_main_is_running(loop)

Checks if the main loop is running.

Note

Warning: g_main_is_running has been deprecated since version 2.2 and should not be used in newly-written code. USe g_main_loop_is_running() instead.

loop : | a GMainLoop.
Returns : | TRUE if the main loop is running.

G_PRIORITY_HIGH

#define G_PRIORITY_HIGH            -100

Use this for high priority event sources. It is not used within GLib or GTK+.

G_PRIORITY_DEFAULT

#define G_PRIORITY_DEFAULT          0

Use this for default priority event sources. In GLib this priority is used when adding timeout functions with g_timeout_add(). In GDK this priority is used for events from the X server.

G_PRIORITY_HIGH_IDLE

#define G_PRIORITY_HIGH_IDLE        100

Use this for high priority idle functions. GTK+ uses G_PRIORITY_HIGH_IDLE + 10 for resizing operations, and G_PRIORITY_HIGH_IDLE + 20 for redrawing operations. (This is done to ensure that any pending resizes are processed before any pending redraws, so that widgets are not redrawn twice unnecessarily.)

G_PRIORITY_DEFAULT_IDLE

#define G_PRIORITY_DEFAULT_IDLE     200

Use this for default priority idle functions. In GLib this priority is used when adding idle functions with g_idle_add().

G_PRIORITY_LOW

#define G_PRIORITY_LOW	            300

Use this for very low priority background tasks. It is not used within GLib or GTK+.

GMainContext

typedef struct _GMainContext GMainContext;

The GMainContext struct is an opaque data type representing a set of sources to be handled in a main loop.

g_main_context_new ()

GMainContext* g_main_context_new            (void);

Creates a new GMainContext strcuture

Returns : the new GMainContext

g_main_context_ref ()

GMainContext* g_main_context_ref            (GMainContext *context);

Increases the reference count on a GMainContext object by one.

context : | a GMainContext
Returns : | the context that was passed in (since 2.6)

g_main_context_unref ()

void        g_main_context_unref            (GMainContext *context);

Decreases the reference count on a GMainContext object by one. If the result is zero, free the context and free all associated memory.

context : a GMainContext

g_main_context_default ()

GMainContext* g_main_context_default        (void);

Returns the default main context. This is the main context used for main loop functions when a main loop is not explicitly specified.

Returns : the default main context.

g_main_context_iteration ()

gboolean    g_main_context_iteration        (GMainContext *context, gboolean may_block);

Runs a single iteration for the given main loop. This involves checking to see if any event sources are ready to be processed, then if no events sources are ready and may_block is TRUE, waiting for a source to become ready, then dispatching the highest priority events sources that are ready. Note that even when may_block is TRUE, it is still possible for g_main_context_iteration() to return FALSE, since the the wait may be interrupted for other reasons than an event source becoming ready.

context : | a GMainContext (if NULL, the default context will be used)
may_block : | whether the call may block.
Returns : | TRUE if events were dispatched.

g_main_iteration()

#define     g_main_iteration(may_block)

Runs a single iteration for the default GMainContext.

Note

Warning: g_main_iteration has been deprecated since version 2.2 and should not be used in newly-written code. Use g_main_context_iteration()

may_block : | set to TRUE if it should block (i.e. wait) until an event source becomes ready. It will return after an event source has been processed. If set to FALSE it will return immediately if no event source is ready to be processed.
Returns : | TRUE if more events are pending.

g_main_context_pending ()

gboolean    g_main_context_pending          (GMainContext *context);

Checks if any sources have pending events for the given context.

context : | a GMainContext (if NULL, the default context will be used)
Returns : | TRUE if events are pending.

g_main_pending()

#define     g_main_pending()

Checks if any events are pending for the default GMainContext (i.e. ready to be processed).

Note

Warning: g_main_pending has been deprecated since version 2.2 and should not be used in newly-written code. Use g_main_context_pending().

Returns : TRUE if any events are pending.

g_main_context_find_source_by_id ()

GSource*    g_main_context_find_source_by_id           (GMainContext *context, guint source_id);

Finds a GSource given a pair of context and ID.

context : | a GMainContext (if NULL, the default context will be used)
source_id : | the source ID, as returned by g_source_get_id()
Returns : | the GSource if found, otherwise, NULL

g_main_context_find_source_by_user_data ()

GSource*    g_main_context_find_source_by_user_data      (GMainContext *context, gpointer user_data);

Finds a source with the given user data for the callback. If multiple sources exist with the same user data, the first one found will be returned.

context : | a GMainContext
user_data : | the user_data for the callback.
Returns : | the source, if one was found, otherwise NULL

g_main_context_find_source_by_funcs_user_data ()

GSource*    g_main_context_find_source_by_funcs_user_data      (GMainContext *context, GSourceFuncs *funcs, gpointer user_data);

Finds a source with the given source functions and user data. If multiple sources exist with the same source function and user data, the first one found will be returned.

context : | a GMainContext (if NULL, the default context will be used).
funcs : | the source_funcs passed to g_source_new().
user_data : | the user data from the callback.
Returns : | the source, if one was found, otherwise NULL

g_main_context_wakeup ()

void        g_main_context_wakeup        (GMainContext *context);

If context is currently waiting in a poll(), interrupt the poll(), and continue the iteration process.

context : a GMainContext

g_main_context_acquire ()

gboolean    g_main_context_acquire      (GMainContext *context);

Tries to become the owner of the specified context. If some other context is the owner of the context, returns FALSE immediately. Ownership is properly recursive: the owner can require ownership again and will release ownership when g_main_context_release() is called as many times as g_main_context_acquire().

Ownership of a context is a pre-requisite before a call to g_main_context_prepare(), g_main_context_query(), g_main_context_check(), g_main_context_dispatch().

context : | a GMainContext
Returns : | TRUE if the operation succeeded, and this thread is now the owner of context.

g_main_context_release ()

void        g_main_context_release       (GMainContext *context);

Releases ownership of a context previously acquired by this thread with g_main_context_acquire(). If the context was acquired multiple times, the only release ownership when g_main_context_release() is called as many times as it was acquired.

context : a GMainContext

g_main_context_is_owner ()

gboolean    g_main_context_is_owner         (GMainContext *context);

Determines whether this thread holds the (recursive) ownership of this GMaincontext. This is useful to know before waiting on another thread that may be blocking to get ownership of context.

context : | a GMainContext
Returns : | TRUE if current thread is owner of context.

g_main_context_wait ()

gboolean    g_main_context_wait        (GMainContext *context, GCond *cond, GMutex *mutex);

Tries to become the owner of the specified context, as with g_main_context_acquire(). But if another thread is the owner, atomically drop mutex and wait on cond until that owner releases ownership or until cond is signaled, then try again (once) to become the owner.

context : | a GMainContext
cond : | a condition variable
mutex : | a mutex, currently held
Returns : | TRUE if the operation succeeded, and this thread is now the owner of context.

g_main_context_prepare ()

gboolean    g_main_context_prepare      (GMainContext *context, gint *priority);

Prepares to poll sources within a main loop. The resulting information for polling is determined by calling g_main_context_query().

context : | a GMainContext
priority : | location to store priority of highest priority source already ready.
Returns : | TRUE if some source is ready to be dispatched prior to polling.

g_main_context_query ()

gint        g_main_context_query        (GMainContext *context, gint max_priority, gint *timeout_, GPollFD *fds, gint n_fds);

Determines information necessary to poll this main loop.

context : | a GMainContext
max_priority : | maximum priority source to check
timeout_ : | location to store timeout to be used in polling
fds : | location to store GPollFD records that need to be polled.
n_fds : | length of fds.
Returns : | the number of records actually stored in fds, or, if more than n_fds records need to be stored, the number of records that need to be stored.

g_main_context_check ()

gint        g_main_context_check           (GMainContext *context, gint max_priority, GPollFD *fds, gint n_fds);

Passes the results of polling back to the main loop.

context : | a GMainContext
max_priority : | the maximum numerical priority of sources to check
fds : | array of GPollFD's that was passed to the last call to g_main_context_query()
n_fds : | return value of g_main_context_query()
Returns : | TRUE if some sources are ready to be dispatched.

g_main_context_dispatch ()

void        g_main_context_dispatch         (GMainContext *context);

Dispatches all pending sources.

context : a GMainContext

g_main_context_set_poll_func ()

void        g_main_context_set_poll_func    (GMainContext *context, GPollFunc func);

Sets the function to use to handle polling of file descriptors. It will be used instead of the poll() system call (or GLib's replacement function, which is used where poll() isn't available).

This function could possibly be used to integrate the GLib event loop with an external event loop.

context : | a GMainContext
func : | the function to call to poll all file descriptors

g_main_context_get_poll_func ()

GPollFunc   g_main_context_get_poll_func    (GMainContext *context);

Gets the poll function set by g_main_context_set_poll_func().

context : | a GMainContext
Returns : | the poll function

GPollFunc ()

gint        (*GPollFunc)           (GPollFD *ufds, guint nfsd, gint timeout_);

Specifies the type of function passed to g_main_context_set_poll_func(). The semantics of the function should match those of the poll() system call.

ufds : | an array of GPollFD elements.
nfsd : | the number of elements in ufds.
timeout_ : | the maximum time to wait for an event of the file descriptors. A negative value indicates an infinite timeout.
Returns : | the number of GPollFD elements which have events or errors reported, or -1 if an error occurred.

g_main_context_add_poll ()

void        g_main_context_add_poll       (GMainContext *context, GPollFD *fd, gint priority);

Adds a file descriptor to the set of file descriptors polled for this context. This will very seldomly be used directly. Instead a typical event source will use g_source_add_poll() instead.

context : | a GMainContext (or NULL for the default context)
fd : | a GPollFD structure holding information about a file descriptor to watch.
priority : | the priority for this file descriptor which should be the same as the priority used for g_source_attach() to ensure that the file descriptor is polled whenever the results may be needed.

g_main_context_remove_poll ()

void        g_main_context_remove_poll     (GMainContext *context, GPollFD *fd);

Removes file descriptor from the set of file descriptors to be polled for a particular context.

context : | a GMainContext
fd : | a GPollFD descriptor previously added with g_main_context_add_poll()

g_main_depth ()

int         g_main_depth                    (void);

Return value: The main loop recursion level in the current thread

Returns : the depth of the stack of calls to g_main_context_dispatch() on any GMainContext in the current thread. That is, when called from the toplevel, it gives 0. When called from within a callback from g_main_context_iteration() (or g_main_loop_run(), etc.) it returns 1. When called from within a callback to a recursive call to g_main_context_iterate(), it returns 2. And so forth. This function is useful in a situation like the following: Imagine an extremely simple "garbage collected" system.

Example 1.

static GList *free_list; gpointer allocate_memory (gsize size) { gpointer result = g_malloc (size); free_list = g_list_prepend (free_list, result); return result; } void free_allocated_memory (void) { GList *l; for (l = free_list; l; l = l->next); g_free (l->data); g_list_free (free_list); free_list = NULL; } [...] while (TRUE); { g_main_context_iteration (NULL, TRUE); free_allocated_memory(); }
This works from an application, however, to do the same thing from a library, it gets more difficult, since there is no longer control over the main loop. The use an idle function to make the call to free_allocated_memory() does not work, since the idle function could be called from a recursive callback. This can be fixed by using g_main_depth()

Example 2.

gpointer allocate_memory (gsize size) { FreeListBlock *block = g_new (FreeListBlock, 1);\ block->mem = g_malloc (size); block->depth = g_main_depth(); free_list = g_list_prepend (free_list, block); return block->mem; } void free_allocated_memory (void) { GList *l; int depth = g_main_depth(); for (l = free_list; l; ); { GList *next = l->next; FreeListBlock *block = l->data; if (block->depth > depth) { g_free (block->mem); g_free (block); free_list = g_list_delete_link (free_list, l); } l = next; } }
There is a temptation to use g_main_depth() to solve problems with re-entrancy. For instance, while waiting for data to be received from the network in response to a menu item, the menu item might be selected again. It might seem that one could make the menu item's callback return immediately and do nothing if g_main_depth() returns a value greater than 1. However, this should be avoided since the user then sees selecting the menu item do nothing. Furthermore, adding these checks all over the code, since there are many things that the user could do. Instead, use the following techniques:

  1. Use gtk_widget_set_sensitive() or modal dialogs to prevent the user from interacting with elements while the main loop is recursing.

  2. Avoid main loop recursion in situations where arbitrary callbacks cannot be handled. Instead, structure the code so that it simply returns to the main loop and then get called again when there is more work to do.

g_main_set_poll_func()

#define     g_main_set_poll_func(func)
Note

Warning: g_main_set_poll_func has been deprecated since version 2.2 and should not be used in newly-written code. Use g_main_context_set_poll_func() instead.

Sets the function to use for the handle polling of file descriptors for the default main context.

func : the function to call to poll all file descriptors.

g_timeout_source_new ()

GSource*    g_timeout_source_new     (guint interval);

Creates a new timeout source.

The source will not initially be associated with any GMainContext and must be added to one with g_source_attach() before it will be executed.

interval : | the timeout interval in milliseconds.
Returns : | the newly-created timeout source

g_timeout_add ()

guint       g_timeout_add            (guint interval, GSourceFunc function, gpointer data);

Sets a function to be called at regular intervals, with the default priority, G_PRIORITY_DEFAULT. The function is called repeatedly until it returns FALSE, at which point the timeout is automatically destroyed and the function will not be called again. The first call to the function will be at the end of the first interval.

Note that timeout functions may be delayed, due to the processing of other event sources. Thus they should not be relied on for precise timing. After each call to the timeout function, the time of the next timeout is recalculated based on the current time and the given interval (it does not try to 'catch up' time lost in delays).

interval : | the time between calls to the function, in milliseconds (1/1000ths of a second)
function : | function to call
data : | data to pass to function
Returns : | the ID (greater than 0) of the event source.

g_timeout_add_full ()

guint       g_timeout_add_full       (gint priority, guint interval, GSourceFunc function, gpointer data, GDestroyNotify notify);

Sets a function to be called at regular intervals, with the given priority. The function is called repeatedly until it returns FALSE, at which point the timeout is automatically destroyed and the function will not be called again. The notify function is called when the timeout is destroyed. The first call to the function will be at the end of the first interval.

Note that timeout functions may be delayed, due to the processing of other event sources. Thus they should not be relied on for precise timing. After each call to the timeout function, the time of the next timeout is recalculated based on the current time and the given interval (it does not try to 'catch up' time lost in delays).

priority : | the priority of the idle source. Typically this will be in the range between G_PRIORITY_DEFAULT_IDLE and G_PRIORITY_HIGH_IDLE.
interval : | the time between calls to the function, in milliseconds (1/1000ths of a second)
function : | function to call
data : | data to pass to function
notify : | function to call when the idle is removed, or NULL
Returns : | the ID (greater than 0) of the event source.

g_idle_source_new ()

GSource*    g_idle_source_new       (void);

Creates a new idle source.

The source will not initially be associated with any GMainContext and must be added to one with g_source_attach() before it will be executed. Note that the default priority for idle sources is G_PRIORITY_DEFAULT_IDLE, as compared to other sources which have a default priority of G_PRIORITY_DEFAULT.

Returns : the newly-created idle source

g_idle_add ()

guint       g_idle_add              (GSourceFunc function, gpointer data);

Adds a function to be called whenever there are no higher priority events pending to the default main loop. The function is given the default idle priority, G_PRIORITY_DEFAULT_IDLE. If the function returns FALSE it is automatically removed from the list of event sources and will not be called again.

function : | function to call
data : | data to pass to function.
Returns : | the ID (greater than 0) of the event source.

g_idle_add_full ()

guint       g_idle_add_full           (gint priority, GSourceFunc function, gpointer data, GDestroyNotify notify);

Adds a function to be called whenever there are no higher priority events pending. If the function returns FALSE it is automatically removed from the list of event sources and will not be called again.

priority : | the priority of the idle source. Typically this will be in the range btweeen G_PRIORITY_DEFAULT_IDLE and G_PRIORITY_HIGH_IDLE.
function : | function to call
data : | data to pass to function
notify : | function to call when the idle is removed, or NULL
Returns : | the ID (greater than 0) of the event source.

g_idle_remove_by_data ()

gboolean    g_idle_remove_by_data       (gpointer data);

Removes the idle function with the given data.

data : | the data for the idle source's callback.
Returns : | TRUE if an idle source was found and removed.

GPid

typedef int GPid;

A type which is used to hold a process identification. On Unix, processes are identified by a process id (an integer), while Windows uses process handles (which are pointers).

GChildWatchFunc ()

void        (*GChildWatchFunc)          (GPid pid, gint status, gpointer data);

The type of functions to be called when a child exists.

pid : | the process id of the child process
status : | Status information about the child process, see waitpid(2) for more information about this field
data : | user data passed to g_child_watch_add()

g_child_watch_source_new ()

GSource*    g_child_watch_source_new    (GPid pid);

Creates a new child_watch source.

The source will not initially be associated with any GMainContext and must be added to one with g_source_attach() before it will be executed.

Note that child watch sources can only be used in conjunction with g_spawn... when the G_SPAWN_DO_NOT_REAP_CHILD flag is used.

Note that on platforms where GPid must be explicitely closed (see g_spawn_close_pid()) pid must not be closed while the source is still active. Typically, a want to call g_spawn_close_pid() in the callback function for the source.

Note further that using g_child_watch_source_new() is not compatible with calling waitpid(-1) in the application. Calling waitpid() for individual pids will still work fine.

pid : | process id of a child process to watch. On Windows, a HANDLE for the process to watch (which actually doesn't have to be a child).
Returns : | the newly-created child watch source

g_child_watch_add ()

guint       g_child_watch_add           (GPid pid, GChildWatchFunc function, gpointer data);

Sets a function to be called when the child indicated by pid exits, at a default priority, G_PRIORITY_DEFAULT.

Note that on platforms where GPid must be explicitely closed (see g_spawn_close_pid()) pid must not be closed while the source is still active. Typically, a want to call g_spawn_close_pid() in the callback function for the source.

GLib supports only a single callback per process id.

pid : | process id of a child process to watch
function : | function to call
data : | data to pass to function
Returns : | the ID (greater than 0) of the event source.

g_child_watch_add_full ()

guint       g_child_watch_add_full       (gint priority, GPid pid, GChildWatchFunc function, gpointer data, GDestroyNotify notify);

Sets a function to be called when the child indicated by pid exits, at a default priority, G_PRIORITY_DEFAULT.

Note that on platforms where GPid must be explicitely closed (see g_spawn_close_pid()) pid must not be closed while the source is still active. Typically, a want to call g_spawn_close_pid() in the callback function for the source.

GLib supports only a single callback per process id.

priority : | the priority of the idle source. Typically this will be in the range between G_PRIORITY_DEFAULT_IDLE and G_PRIORITY_HIGH_IDLE.
pid : | process id of a child process to watch
function : | function to call
data : | data to pass to function
notify : | function to call when the idle is removed, or NULL
Returns : | the ID (greater than 0) of the event source.

GPollFD

typedef struct {
  gint		fd;
  gushort 	events;
  gushort 	revents;
} GPollFD;

gint fd; | the file descriptor to poll (or a HANDLE on Win32 platforms).
gushort events; | a bitwise combination of flags from GIOCondition, specifying which events should be polled for. Typically for reading from a file descriptor use G_IO_IN | G_IO_HUP | G_IO_ERR, and for writing use G_IO_OUT | G_IO_ERR.
gushort revents; | a bitwise combination of flags from GIOCondition, returned from the poll() function to indicate which events occurred.

GSource

typedef struct {
} GSource;

The GSource struct is an opaque data type representing an event source.

GSourceDummyMarshal ()

void        (*GSourceDummyMarshal)          (void);

This is just a placeholder for GClosureMarshal, which cannot be used here for dependency reasons.

GSourceFuncs

typedef struct {
  gboolean (*prepare)  (GSource  *source, gint  *timeout_);
  gboolean (*check)    (GSource  *source);
  gboolean (*dispatch) (GSource  *source, GSourceFunc callback, gpointer    user_data);
  void     (*finalize) (GSource  *source); /* Can be NULL */

  /* For use by g_source_set_closure */
  GSourceFunc     closure_callback;
  GSourceDummyMarshal closure_marshal; /* Really is of type GClosureMarshal */
} GSourceFuncs;

The GSourceFuncs struct contains a table of functions used to handle event sources in a generic manner.

prepare | Called before all the file descriptors are polled. If the source can determine that it is ready here (without waiting for the results of the poll() call) it should return TRUE. It can also return a timeout_ value which should be the maximum timeout (in milliseconds) which should be passed to the poll() call. The actual timeout used will be -1 if all sources returned -1, or it will be the minimum of all the timeout_ values returned which were >= 0.
check | Called after all the file descriptors are polled. The source should return TRUE if it is ready to be dispatched. Note that some time may have passed since the previous prepare function was called, so the source should be checked again here.
dispatch | Called to dispatch the event source, after it has returned TRUE in either its prepare or its check function. The dispatch function is passed in a callback function and data. The callback function may be NULL if the source was never connected to a callback using g_source_set_callback(). The dispatch function should call the callback function with user_data and whatever additional parameters are needed for this type of event source.
finalize | Called when the source is finalized.

For idle sources, the prepare and check functions always return TRUE to indicate that the source is always ready to be processed. The prepare function also returns a timeout value of 0 to ensure that the poll() call doesn't block (since that would be time wasted which could have been spent running the idle function).

For timeout sources, the prepare and check functions both return TRUE if the timeout interval has expired. The prepare function also returns a timeout value to ensure that the poll() call doesn't block too long and miss the next timeout.

For file descriptor sources, the prepare function typically returns FALSE, since it must wait until poll() has been called before it knows whether any events need to be processed. It sets the returned timeout to -1 to indicate that it doesn't mind how long the poll() call blocks. In the check function, it tests the results of the poll() call to see if the required condition has been met, and returns TRUE if so.

GSourceCallbackFuncs

typedef struct {
  void (*ref)   (gpointer   cb_data);
  void (*unref) (gpointer   cb_data);
  void (*get)   (gpointer   cb_data, GSource  *source, GSourceFunc *func, gpointer *data);
} GSourceCallbackFuncs;

The GSourceCallbackFuncs struct contains functions for managing callback objects.

ref () | Called when a reference is added to the callback object.
unref () | Called when a reference to the callback object is dropped.
get () | Called to extract the callback function and data from the callback object.

g_source_new ()

GSource*    g_source_new                (GSourceFuncs *source_funcs, guint struct_size);

Creates a new GSource structure. The size is specified to allow creating structures derived from GSource that contain additional data. The size passed in must be at least sizeof (GSource).

The source will not initially be associated with any GMainContext and must be added to one with g_source_attach() before it will be executed.

source_funcs : | structure containing functions that implement the sources behavior.
struct_size : | size of the GSource structure to create.
Returns : | the newly-created GSource.

g_source_ref ()

GSource*    g_source_ref                 (GSource *source);

Increases the reference count on a source by one.

source : | a GSource
Returns : | source

g_source_unref ()

void        g_source_unref               (GSource *source);

Decreases the reference count of a source by one. If the resulting reference count is zero the source and associated memory will be destroyed.

source : a GSource

g_source_attach ()

guint       g_source_attach              (GSource *source, GMainContext *context);

Adds a GSource to a context so that it will be executed within that context.

source : | a GSource
context : | a GMainContext (if NULL, the default context will be used)
Returns : | the ID (greater than 0) for the source within the GMainContext

g_source_destroy ()

void        g_source_destroy             (GSource *source);

Removes a source from its GMainContext, if any, and mark it as destroyed. The source cannot be subsequently added to another context.

source : a GSource

g_source_set_priority ()

void        g_source_set_priority        (GSource *source, gint priority);

Sets the priority of a source. While the main loop is being run, a source will be dispatched if it is ready to be dispatched and no sources at a higher (numerically smaller) priority are ready to be dispatched.

source : | a GSource
priority : | the new priority.

g_source_get_priority ()

gint     g_source_get_priority           (GSource *source);

Gets the priority of a source.

source : | a GSource
Returns : | the priority of the source

g_source_set_can_recurse ()

void   g_source_set_can_recurse         (GSource *source, gboolean can_recurse);

Sets whether a source can be called recursively. If can_recurse is TRUE, then while the source is being dispatched then this source will be processed normally. Otherwise, all processing of this source is blocked until the dispatch function returns.

source : | a GSource
can_recurse : | whether recursion is allowed for this source

g_source_get_can_recurse ()

gboolean    g_source_get_can_recurse    (GSource *source);

Checks whether a source is allowed to be called recursively. see g_source_set_can_recurse().

source : | a GSource
Returns : | whether recursion is allowed.

g_source_get_id ()

guint       g_source_get_id            (GSource *source);

Returns the numeric ID for a particular source. The ID of a source is a positive integer which is unique within a particular main loop context. The reverse mapping from ID to source is done by g_main_context_find_source_by_id().

source : | a GSource
Returns : | the ID (greater than 0) for the source

g_source_get_context ()

GMainContext* g_source_get_context    (GSource *source);

Gets the GMainContext with which the source is associated. Calling this function on a destroyed source is an error.

source : | a GSource
Returns : | the GMainContext with which the source is associated, or NULL if the context has not yet been added to a source.

g_source_set_callback ()

void        g_source_set_callback    (GSource *source, GSourceFunc func, gpointer data, GDestroyNotify notify);

Sets the callback function for a source. The callback for a source is called from the source's dispatch function.

The exact type of func depends on the type of source; ie. do not count on func being called with data as its first parameter.

Typically, do not use this function. Instead use functions specific to the type of source being used.

source : | the source
func : | a callback function
data : | the data to pass to callback function
notify : | a function to call when data is no longer in use, or NULL.

GSourceFunc ()

gboolean    (*GSourceFunc)          (gpointer data);

Specifies the type of function passed to g_timeout_add(), g_timeout_add_full(), g_idle_add(), and g_idle_add_full().

data : | data passed to the function, set when the source was created with one of the above functions.
Returns : | it should return FALSE if the source should be removed.

g_source_set_callback_indirect ()

void     g_source_set_callback_indirect  (GSource *source, gpointer callback_data, GSourceCallbackFuncs *callback_funcs);

Sets the callback function storing the data as a refcounted callback "object". This is used internally. Note that calling g_source_set_callback_indirect() assumes an initial reference count on callback_data, and thus callback_funcs->unref will eventually be called once more than callback_funcs->ref.

source : | the source
callback_data : | pointer to callback data "object"
callback_funcs : | functions for reference counting callback_data and getting the callback and data

g_source_add_poll ()

void     g_source_add_poll          (GSource *source, GPollFD *fd);

Adds a file descriptor to the set of file descriptors polled for this source. This is usually combined with g_source_new() to add an event source. The event source's check function will typically test the revents field in the GPollFD struct and return TRUE if events need to be processed.

source : | a GSource
fd : | a GPollFD structure holding information about a file descriptor to watch.

g_source_remove_poll ()

void    g_source_remove_poll       (GSource *source, GPollFD *fd);

Removes a file descriptor from the set of file descriptors polled for this source.

source : | a GSource
fd : | a GPollFD structure previously passed to g_source_add_poll().

g_source_get_current_time ()

void    g_source_get_current_time  (GSource *source, GTimeVal *timeval);

Gets the "current time" to be used when checking this source. The advantage of calling this function over calling g_get_current_time() directly is that when checking multiple sources, GLib can cache a single value instead of having to repeatedly get the system time.

source : | a GSource
timeval : | GTimeVal structure in which to store current time.

g_source_remove ()

gboolean  g_source_remove              (guint tag);

Removes the source with the given id from the default main context. The id of a
GSource
is given by g_source_get_id(), or will be returned by the
functions g_source_attach(),
g_idle_add(),
g_idle_add_full(),
g_timeout_add(), g_timeout_add_full(), g_child_watch_add(),
g_child_watch_add_full(),
g_io_add_watch(), and g_io_add_watch_full().

See also g_source_destroy().

tag : | the id of the source to remove.
Returns : | TRUE if the source was found and removed.

g_source_remove_by_funcs_user_data ()

gboolean    g_source_remove_by_funcs_user_data      (GSourceFuncs *funcs, gpointer user_data);

Removes a source from the default main loop context given the source functions and user data. If multiple sources exist with the same source functions and user data, only one will be destroyed.

funcs : | The source_funcs passed to g_source_new()
user_data : | the user data for the callback
Returns : | TRUE if a source was found and removed.

g_source_remove_by_user_data ()

gboolean    g_source_remove_by_user_data    (gpointer user_data);

Removes a source from the default main loop context given the user data for the callback. If multiple sources exist with the same user data, only one will be destroyed.

user_data : | the user_data for the callback.
Returns : | TRUE if a source was found and removed.

Feedback

For additional information or queries on this page send feedback


Thread Pools

Name

Thread Pools — pools of threads to execute work concurrently.

Library

glib.lib

Synopsis

#include <glib.h>

GThreadPool;
GThreadPool* g_thread_pool_new                   (GFunc func, gpointer user_data, gint max_threads, gboolean exclusive,
                                                  GError **error);
void        g_thread_pool_push                   (GThreadPool *pool, gpointer data, GError **error);
void        g_thread_pool_set_max_threads        (GThreadPool *pool, gint max_threads, GError **error);
gint        g_thread_pool_get_max_threads        (GThreadPool *pool);
guint       g_thread_pool_get_num_threads        (GThreadPool *pool);
guint       g_thread_pool_unprocessed            (GThreadPool *pool);
void        g_thread_pool_free                   (GThreadPool *pool, gboolean immediate, gboolean wait);

void        g_thread_pool_set_max_unused_threads (gint max_threads);
gint        g_thread_pool_get_max_unused_threads (void);
guint       g_thread_pool_get_num_unused_threads (void);
void        g_thread_pool_stop_unused_threads    (void);
void        g_thread_pool_set_sort_function (GThreadPool *pool, GCompareDataFunc func, gpointer user_data);
void        g_thread_pool_set_max_idle_time (guint  interval);
guint       g_thread_pool_get_max_idle_time (void);

Detailed Description

If the need to asynchronously fork out the execution of work and continue working within the own thread happens often, the overhead of starting and destroying a thread each time might be too high. In such cases reusing already started threads seems like a good idea. And it indeed is, but implementing this can be tedious and error-prone.

Therefore GLib provides thread pools for convenience. An added advantage is, that the threads can be shared between the different subsystems of the program, when they are using GLib.

To create a new thread pool, use g_thread_pool_new(). It is destroyed by g_thread_pool_free().

To execute a certain task within a thread pool, call g_thread_pool_push().

To get the current number of running threads call g_thread_pool_get_num_threads(). To get the number of still unprocessed tasks call g_thread_pool_unprocessed(). To control the maximal number of threads for a thread pool, use g_thread_pool_get_max_threads() and g_thread_pool_set_max_threads().

The number of unused threads, that are kept alive by GLib for future use can be controlled. The current number can be fetched with g_thread_pool_get_num_unused_threads(). The maximal number can be controlled by g_thread_pool_get_max_unused_threads() and g_thread_pool_set_max_unused_threads(). All currently unused threads can be stopped by calling g_thread_pool_stop_unused_threads().

Details

GThreadPool

typedef struct {
  GFunc func;
  gpointer user_data;
  gboolean exclusive;
} GThreadPool;

The GThreadPool struct represents a thread pool. It has six public read-only members, but the underlying struct is bigger, so do not copy this struct.

GFunc func; | the function to execute in the threads of this pool
gpointer user_data; | the user data for the threads of this pool
gboolean exclusive; | are all threads exclusive to this pool

g_thread_pool_new ()

GThreadPool* g_thread_pool_new   (GFunc func, gpointer user_data, gint max_threads, gboolean exclusive, GError **error);

This function creates a new thread pool.

Whenever the function g_thread_pool_push() is called, either a new thread is created or an unused one is reused. At most, max_threads threads are running concurrently for this thread pool. max_threads = -1 allows unlimited threads to be created for this thread pool. The newly created or reused thread now executes the function func with the two arguments. The first one is the parameter to g_thread_pool_push() and the second one is user_data.

The parameter exclusive determines, whether the thread pool owns all threads exclusive or whether the threads are shared globally. If exclusive is TRUE, max_threads threads are started immediately and they will run exclusively for this thread pool until it is destroyed by g_thread_pool_free(). If exclusive is FALSE, threads are created, when needed and shared between all non-exclusive thread pools. This implies that max_threads may not be -1 for exclusive thread pools.

error can be NULL to ignore errors, or non-NULL to report errors. An error can only occur when exclusive is set to TRUE and not all max_threads threads could be created.

func : | a function to execute in the threads of the new thread pool
user_data : | user data that is handed over to func every time it is called
max_threads : | the maximal number of threads to execute concurrently in the new thread pool, -1 means no limit
exclusive : | should this thread pool be exclusive?
error : | return location for error
Returns : | the new GThreadPool

g_thread_pool_push ()

void     g_thread_pool_push      (GThreadPool *pool, gpointer data, GError **error);

Inserts data into the list of tasks to be executed by pool. When the number of currently running threads is lower than the maximal allowed number of threads, a new thread is started (or reused) with the properties given to g_thread_pool_new(). Otherwise data stays in the queue until a thread in this pool finishes its previous task and processes data.

error can be NULL to ignore errors, or non-NULL to report errors. An error can only occur when a new thread could no t be created. In that case data is simply appended to the queue of work to do.

pool : | a GThreadPool
data : | a new task for pool
error : | return location for error

g_thread_pool_set_max_threads ()

void    g_thread_pool_set_max_threads   (GThreadPool *pool, gint max_threads, GError **error);

Sets the maximal allowed number of threads for pool. A value of -1 means, that the maximal number of threads is unlimited.

Setting max_threads to 0 means stopping all work for pool. It is effectively frozen until max_threads is set to a non-zero value again.

A thread is never terminated while calling func, as supplied by g_thread_pool_new(). Instead the maximal number of threads only has effect for the allocation of new threads in g_thread_pool_push(). A new thread is allocated, whenever the number of currently running threads in pool is smaller than the maximal number.

error can be NULL to ignore errors, or non-NULL to report errors. An error can only occur when a new thread could not be created.

pool : | a GThreadPool
max_threads : | a new maximal number of threads for pool
error : | return location for error

g_thread_pool_get_max_threads ()

gint   g_thread_pool_get_max_threads   (GThreadPool *pool);

Returns the maximal number of threads for pool.

pool : | a GThreadPool
Returns : | the maximal number of threads

g_thread_pool_get_num_threads ()

guint   g_thread_pool_get_num_threads   (GThreadPool *pool);

Returns the number of threads currently running in pool.

pool : | a GThreadPool
Returns : | the number of threads currently running

g_thread_pool_unprocessed ()

guint    g_thread_pool_unprocessed       (GThreadPool *pool);

Returns the number of tasks still unprocessed in pool.

pool : | a GThreadPool
Returns : | the number of unprocessed tasks

g_thread_pool_free ()

void   g_thread_pool_free         (GThreadPool *pool, gboolean immediate, gboolean wait);

Frees all resources allocated for pool.

If immediate is TRUE, no new task is processed for pool. Otherwise pool is not freed before the last task is processed. Note however, that no thread of this pool is interrupted, while processing a task. Instead at least all still running threads can finish their tasks before the pool is freed.

If wait is TRUE, the functions does not return before all tasks to be processed (dependent on immediate, whether all or only the currently running) are ready. Otherwise the function returns immediately.

After calling this function pool must not be used anymore.

pool : | a GThreadPool
immediate : | should pool shut down immediately?
wait : | should the function wait for all tasks to be finished?

g_thread_pool_set_max_unused_threads ()

void   g_thread_pool_set_max_unused_threads      (gint max_threads);

Sets the maximal number of unused threads to max_threads. If max_threads is -1, no limit is imposed on the number of unused threads.

max_threads : maximal number of unused threads

g_thread_pool_get_max_unused_threads ()

gint    g_thread_pool_get_max_unused_threads   (void);

Returns the maximal allowed number of unused threads.

Returns : the maximal number of unused threads

g_thread_pool_get_num_unused_threads ()

guint   g_thread_pool_get_num_unused_threads   (void);

Returns the number of currently unused threads.

Returns : the number of currently unused threads

g_thread_pool_stop_unused_threads ()

void   g_thread_pool_stop_unused_threads   (void);

Stops all currently unused threads. This does not change the maximal number of unused threads. This function can be used to regularly stop all unused threads e.g. from g_timeout_add().

g_thread_pool_set_sort_function ()

void    g_thread_pool_set_sort_function (GThreadPool *pool, GCompareDataFunc func, gpointer user_data);

Sets the function used to sort the list of tasks. This allows the tasks to be processed by a priority determined by func, and not just in the order in which they were added to the pool.

Note, if the maximum number of threads is more than 1, the order that threads are executed can not be guaranteed 100%. Threads are scheduled by the operating system and are executed at random. It cannot be assumed that threads are executed in the order they are created.

pool : | a GThreadPool
func : | the GCompareDataFunc used to sort the list of tasks. This function is passed two tasks. It should return 0 if the order in which they are handled does not matter, a negative value if the first task should be processed before the second or a positive value if the second task should be processed first.
user_data : | user data passed to func.

g_thread_pool_set_max_idle_time ()

void        g_thread_pool_set_max_idle_time (guint interval);

This function will set the maximum interval that a thread waiting in the pool for new tasks can be idle for before being stopped. This function is similar to calling g_thread_pool_stop_unused_threads() on a regular timeout, except, this is done on a per thread basis.

By setting interval to 0, idle threads will not be stopped. This function makes use of g_async_queue_timed_pop() using interval.

interval : the maximum interval (1/1000ths of a second) a thread can be idle.

g_thread_pool_get_max_idle_time ()

guint       g_thread_pool_get_max_idle_time (void);

This function will return the maximum interval that a thread will wait in the thread pool for new tasks before being stopped.

If this function returns 0, threads waiting in the thread pool for new work are not stopped.

Returns : the maximum interval to wait for new tasks in the thread pool before stopping the thread (1/1000ths of a second).

See Also

GThread : Glib thread system

Feedback

For additional information or queries on this page send feedback


Threads

Name

Threads — thread abstraction; including threads, different mutexes, conditions and thread private data.

Library

glib.lib

Synopsis

#include <glib.h>

#define     G_THREADS_ENABLED
#define     G_THREADS_IMPL_POSIX
#define     G_THREADS_IMPL_NONE

#define     G_THREAD_ERROR
enum        GThreadError;

            GThreadFunctions;
void        g_thread_init            (GThreadFunctions *vtable);
gboolean    g_thread_supported       ();

gpointer    (*GThreadFunc)           (gpointer data);
enum        GThreadPriority;
            GThread;
GThread*    g_thread_create          (GThreadFunc func, gpointer data, gboolean joinable, GError **error);
GThread*    g_thread_create_full     (GThreadFunc func, gpointer data, gulong stack_size, gboolean joinable, gboolean bound, GThreadPriority priority, GError **error);
GThread*    g_thread_self            (void);
gpointer    g_thread_join            (GThread *thread);
void        g_thread_set_priority    (GThread *thread, GThreadPriority priority);
void        g_thread_yield           ();
void        g_thread_exit            (gpointer retval);
void        g_thread_foreach         (GFunc thread_func, gpointer user_data);

            GMutex;
GMutex*     g_mutex_new              ();
void        g_mutex_lock             (GMutex *mutex);
gboolean    g_mutex_trylock          (GMutex *mutex);
void        g_mutex_unlock           (GMutex *mutex);
void        g_mutex_free             (GMutex *mutex);

            GStaticMutex;
#define     G_STATIC_MUTEX_INIT
void        g_static_mutex_init      (GStaticMutex *mutex);
void        g_static_mutex_lock      (GStaticMutex *mutex);
gboolean    g_static_mutex_trylock   (GStaticMutex *mutex);
void        g_static_mutex_unlock    (GStaticMutex *mutex);
GMutex*     g_static_mutex_get_mutex (GStaticMutex *mutex);
void        g_static_mutex_free      (GStaticMutex *mutex);

#define     G_LOCK_DEFINE            (name)
#define     G_LOCK_DEFINE_STATIC     (name)
#define     G_LOCK_EXTERN            (name)
#define     G_LOCK                   (name)
#define     G_TRYLOCK                (name)
#define     G_UNLOCK                 (name)

            GStaticRecMutex;
#define     G_STATIC_REC_MUTEX_INIT
void        g_static_rec_mutex_init         (GStaticRecMutex *mutex);
void        g_static_rec_mutex_lock         (GStaticRecMutex *mutex);
gboolean    g_static_rec_mutex_trylock      (GStaticRecMutex *mutex);
void        g_static_rec_mutex_unlock       (GStaticRecMutex *mutex);
void        g_static_rec_mutex_lock_full    (GStaticRecMutex *mutex, guint depth);
guint       g_static_rec_mutex_unlock_full  (GStaticRecMutex *mutex);
void        g_static_rec_mutex_free         (GStaticRecMutex *mutex);

            GStaticRWLock;
#define     G_STATIC_RW_LOCK_INIT
void        g_static_rw_lock_init           (GStaticRWLock *lock);
void        g_static_rw_lock_reader_lock    (GStaticRWLock *lock);
gboolean    g_static_rw_lock_reader_trylock (GStaticRWLock *lock);
void        g_static_rw_lock_reader_unlock  (GStaticRWLock *lock);
void        g_static_rw_lock_writer_lock    (GStaticRWLock *lock);
gboolean    g_static_rw_lock_writer_trylock (GStaticRWLock *lock);
void        g_static_rw_lock_writer_unlock  (GStaticRWLock *lock);
void        g_static_rw_lock_free           (GStaticRWLock *lock);

            GCond;
GCond*      g_cond_new                      ();
void        g_cond_signal                   (GCond *cond);
void        g_cond_broadcast                (GCond *cond);
void        g_cond_wait                     (GCond *cond, GMutex *mutex);
gboolean    g_cond_timed_wait               (GCond *cond, GMutex *mutex, GTimeVal *abs_time);
void        g_cond_free                     (GCond *cond);

            GPrivate;
GPrivate*   g_private_new                   (GDestroyNotify destructor);
gpointer    g_private_get                   (GPrivate *private_key);
void        g_private_set                   (GPrivate *private_key, gpointer data);

            GStaticPrivate;
#define     G_STATIC_PRIVATE_INIT
void        g_static_private_init           (GStaticPrivate *private_key);
gpointer    g_static_private_get            (GStaticPrivate *private_key);
void        g_static_private_set            (GStaticPrivate *private_key, gpointer data, GDestroyNotify notify);
void        g_static_private_free           (GStaticPrivate *private_key);

            GOnce;
enum        GOnceStatus;
#define     G_ONCE_INIT
#define     g_once                          (once, func, arg)

Detailed Description

Threads act almost like processes, but unlike processes all threads of one process share the same memory. This provides easy communication between the involved threads via this shared memory, but it also causes strange things to happen, when the program is not carefully designed. Especially, because of the concurrent nature of threads no assumptions on the order of execution of different threads can be done unless explicitly forced by the programmer through synchronization primitives.

The aim of the thread related functions in GLib is to provide a portable means for writing multi-threaded software. There are primitives for mutexes to protect the access to portions of memory (GMutex, GStaticMutex, G_LOCK_DEFINE, GStaticRecMutex and GStaticRWLock), there are primitives for condition variables to allow synchronization of threads (GCond) and finally there are primitives for thread-private data, that every thread has a private instance of (GPrivate, GStaticPrivate). Last but not least there are primitives to portably create and manage threads (GThread).

A call to g_thread_init() must be made before executing any other GLib functions in a threaded GLib program. After that, GLib is completely thread safe (all global data is automatically locked). But individual data structure instances are not automatically locked for performance reasons. For example, accesses to the same GHashTable from multiple threads must be coordinated by the user. The two notable exceptions from this rule are GMainLoop and GAsyncQueue, which are threadsafe and needs no further application-level locking to be accessed from multiple threads.

Details

G_THREADS_ENABLED

#define G_THREADS_ENABLED

This macro is defined, if GLib was compiled with thread support. This does not necessarily mean, that there is a thread implementation available, but the infrastructure is in place and once a thread implementation to g_thread_init() is provided, GLib will be multi-thread safe. It is not and cannot be, if G_THREADS_ENABLED is not defined.

G_THREADS_IMPL_POSIX

#define G_THREADS_IMPL_POSIX

This macro is defined, if POSIX style threads are used.

G_THREADS_IMPL_NONE

#define G_THREADS_IMPL_NONE

This macro is defined, if no thread implementation is used. The user can however, provide one to g_thread_init() to make GLib multi-thread safe.

G_THREAD_ERROR

#define G_THREAD_ERROR g_thread_error_quark ()

The error domain of the GLib thread subsystem.

enum GThreadError

typedef enum
{
  G_THREAD_ERROR_AGAIN /* Resource temporarily unavailable */
} GThreadError;

Possible errors of thread related functions.

G_THREAD_ERROR_AGAIN a thread couldn't be created due to resource shortage. Try again later.

GThreadFunctions

typedef struct {
  GMutex*  (*mutex_new)           (void);
  void     (*mutex_lock)          (GMutex *mutex);
  gboolean (*mutex_trylock)       (GMutex *mutex);
  void     (*mutex_unlock)        (GMutex *mutex);
  void     (*mutex_free)          (GMutex *mutex);
  GCond*   (*cond_new)            (void);
  void     (*cond_signal)         (GCond  *cond);
  void     (*cond_broadcast)      (GCond  *cond);
  void     (*cond_wait)           (GCond  *cond, GMutex *mutex);
  gboolean (*cond_timed_wait)     (GCond  *cond, GMutex *mutex, GTimeVal *end_time);
  void      (*cond_free)          (GCond  *cond);
  GPrivate* (*private_new)        (GDestroyNotify destructor);
  gpointer  (*private_get)        (GPrivate *private_key);
  void      (*private_set)        (GPrivate *private_key, gpointer data);
  void      (*thread_create)      (GThreadFunc func, gpointer data, gulong stack_size, gboolean joinable, gboolean bound, GThreadPriority priority, gpointer thread,
                                   GError **error);
  void      (*thread_yield)       (void);
  void      (*thread_join)        (gpointer thread);
  void      (*thread_exit)        (void);
  void      (*thread_set_priority)(gpointer thread, GThreadPriority priority);
  void      (*thread_self)        (gpointer thread);
  gboolean  (*thread_equal)       (gpointer thread1, gpointer thread2);
} GThreadFunctions;

This function table is used by g_thread_init() to initialize the thread system. The functions in that table are directly used by their g_* prepended counterparts, that are described here, e.g. if the user calls g_mutex_new() then, mutex_new() from the table provided to g_thread_init() will be called.

Note

Note: This struct should only be used, if the users know, what they are doing.

g_thread_init ()

void   g_thread_init   (GThreadFunctions *vtable);

The use of GLib from more than one thread, must be followed by an initialization to the thread system by calling g_thread_init(). Most of the time only a to call g_thread_init (NULL).

Note

Note: The user should call only g_thread_init() with a non-NULL parameter.

Note Note: g_thread_init() must not be called directly or indirectly as a callback from GLib. Also no mutexes may be currently locked, while calling g_thread_init().

g_thread_init() might only be called once. On the second call it will abort with an error. To make sure, that the thread system is initialized, use the following:

    if (!g_thread_supported ()) g_thread_init (NULL);

After that line either the thread system is initialized or the program will abort, if no thread system is available in GLib, i.e. either G_THREADS_ENABLED is not defined or G_THREADS_IMPL_NONE is defined.

If no thread system is available and vtable is NULL or if not all elements of vtable are non-NULL, then g_thread_init() will abort.

Note Note: To use g_thread_init() in the program, the user has to link with the libraries that the command pkg-config --libs gthread-2.0 outputs. This is not the case for all the other thread related functions of GLib. Those can be used without having to link with the thread libraries.
vtable : a function table of type GThreadFunctions, that provides the entry points to the thread system to be used.

g_thread_supported ()

gboolean    g_thread_supported     ();

This function returns, whether the thread system is initialized or not.

Note

Note: This function is actually a macro. Apart from taking its address it can however be used as if it was a function.

Returns : TRUE, if the thread system is initialized.

GThreadFunc ()

gpointer    (*GThreadFunc)       (gpointer data);

Specifies the type of the func functions passed to g_thread_create() or g_thread_create_full().

data : | data passed to the thread.
Returns : | the return value of the thread, which will be returned by g_thread_join().

enum GThreadPriority

typedef enum
{
  G_THREAD_PRIORITY_LOW, G_THREAD_PRIORITY_NORMAL, G_THREAD_PRIORITY_HIGH, G_THREAD_PRIORITY_URGENT
} GThreadPriority;

Specifies the priority of a thread.

Note

Note: It is not guaranteed, that threads with different priorities really behave accordingly. On some systems (e.g. Linux) there are no thread priorities. On other systems (e.g. Solaris) there does not seem to be different scheduling for different priorities. All in all try to avoid being dependent on priorities.

G_THREAD_PRIORITY_LOW | a priority lower than normal
G_THREAD_PRIORITY_NORMAL | the default priority
G_THREAD_PRIORITY_HIGH | a priority higher than normal
G_THREAD_PRIORITY_URGENT | the highest priority

GThread

typedef struct {
} GThread;

The GThread struct represents a running thread. It has three public read-only members, but the underlying struct is bigger, so do not copy this struct.

Note

Note: Resources for a joinable thread are not fully released until g_thread_join() is called for that thread.

g_thread_create ()

GThread*    g_thread_create       (GThreadFunc func,  gpointer data,  gboolean joinable, GError **error);

This function creates a new thread with the default priority.

If joinable is TRUE, the user can wait for this threads termination calling g_thread_join(). Otherwise the thread will just disappear, when ready.

The new thread executes the function func with the argument data. If the thread was created successfully, it is returned.

error can be NULL to ignore errors, or non-NULL to report errors. The error is set, if and only if the function returns NULL.

func : | a function to execute in the new thread.
data : | an argument to supply to the new thread.
joinable : | should this thread be joinable?
error : | return location for error.
Returns : | the new GThread on success.

g_thread_create_full ()

GThread*    g_thread_create_full       (GThreadFunc func, gpointer data, gulong stack_size, gboolean joinable,  gboolean bound,
                                        GThreadPriority priority, GError **error);

This function creates a new thread with the priority priority. If the underlying thread implementation supports it, the thread gets a stack size of stack_size or the default value for the current platform, if stack_size is 0.

If joinable is TRUE, the user can wait for this threads termination calling g_thread_join(). Otherwise the thread will just disappear, when ready. If bound is TRUE, this thread will be scheduled in the system scope, otherwise the implementation is free to do scheduling in the process scope. The first variant is more expensive resource-wise, but generally faster. On some systems (e.g. Linux) all threads are bound.

The new thread executes the function func with the argument data. If the thread was created successfully, it is returned.

error can be NULL to ignore errors, or non-NULL to report errors. The error is set, if and only if the function returns NULL.

Note

Note: It is not guaranteed, that threads with different priorities really behave accordingly. On some systems (e.g. Linux) there are no thread priorities. On other systems (e.g. Solaris) there does not seem to be different scheduling for different priorities. All in all try to avoid being dependent on priorities. Use G_THREAD_PRIORITY_NORMAL here as a default.

Note

Note: Only use g_thread_create_full(), when g_thread_create() cannot be used instead. g_thread_create() does not take stack_size, bound and priority as arguments, as they should only be used for cases, where it is inevitable.

func : | a function to execute in the new thread.
data : | an argument to supply to the new thread.
stack_size : | a stack size for the new thread.
joinable : | should this thread be joinable?
bound : | should this thread be bound to a system thread?
priority : | a priority for the thread.
error : | return location for error.
Returns : | the new GThread on success.

g_thread_self ()

GThread*    g_thread_self       (void);

This functions returns the GThread corresponding to the calling thread.

Returns : the current thread.

g_thread_join ()

gpointer    g_thread_join       (GThread *thread);

Waits until thread finishes, i.e. the function func, as given to g_thread_create(), returns or g_thread_exit() is called by thread. All resources of thread including the GThread struct are released. thread must have been created with joinable=TRUE in g_thread_create(). The value returned by func or given to g_thread_exit() by thread is returned by this function.

thread : | a GThread to be waited for.
Returns : | the return value of the thread.

g_thread_set_priority ()

void     g_thread_set_priority       (GThread *thread, GThreadPriority priority);

Changes the priority of thread to priority.

Note

Note: It is not guaranteed, that threads with different priorities really behave accordingly. On some systems (e.g. Linux) there are no thread priorities. On other systems (e.g. Solaris) there does not seem to be different scheduling for different priorities. All in all try to avoid being dependent on priorities.

thread : | a GThread.
priority : | a new priority for thread.

g_thread_yield ()

void   g_thread_yield    ();

Gives way to other threads waiting to be scheduled.

This function is often used as a method to make busy wait less evil. But in most cases, the user will encounter better methods to do that. So in general this function should not be used.

g_thread_exit ()

void    g_thread_exit   (gpointer retval);

Exits the current thread. If another thread is waiting for that thread using g_thread_join() and the current thread is joinable, the waiting thread will be woken up and getting retval as the return value of g_thread_join(). If the current thread is not joinable, retval is ignored. Calling

g_thread_exit (retval);

is equivalent to calling

return retval;

in the function func, as given to g_thread_create().

Note

Note: Never call g_thread_exit() from within a thread of a GThreadPool, as that will mess up the bookkeeping and lead to funny and unwanted results.

retval : the return value of this thread.

g_thread_foreach ()

void      g_thread_foreach           (GFunc thread_func, gpointer user_data);

Call thread_func on all existing GThread structures. Note that threads may decide to exit while thread_func is running, so without intimate knowledge about the lifetime of foreign threads, thread_func shouldn't access the GThread* pointer passed in as first argument. However, thread_func will not be called for threads which are known to have exited already.

Due to thread lifetime checks, this function has an execution complexity which is quadratic in the number of existing threads.

thread_func : | function to call for all GThread structures
user_data : | second argument to thread_func

GMutex

typedef struct _GMutex GMutex;

The GMutex struct is an opaque data structure to represent a mutex (mutual exclusion). It can be used to protect data against shared access. Take for example the following function:

Example 3. A function which will not work in a threaded environment

  int give_me_next_number ()
  {
    static int current_number = 0;

    /* now do a very complicated calculation to calculate the new number,
       this might for example be a random number generator */
    current_number = calc_next_number (current_number);
    return current_number;
  }

It is easy to see, that this will not work in a multi-threaded application. There current_number must be protected against shared access. A first naive implementation would be:

Example 4. The wrong way to write a thread-safe function

  int give_me_next_number ()
  {
    static int current_number = 0;
    int ret_val;
    static GMutex * mutex = NULL;

    if (!mutex)
      mutex = g_mutex_new ();
    g_mutex_lock (mutex);
    ret_val = current_number = calc_next_number (current_number);
    g_mutex_unlock (mutex);
    return ret_val;
  }

This looks like it would work, but there is a race condition while constructing the mutex and this code cannot work reliable. So please do not use such constructs in own programs. One working solution is:

Example 5. A correct thread-safe function

  static GMutex *give_me_next_number_mutex = NULL;

  /* this function must be called before any call to give_me_next_number ()
     it must be called exactly once. */
  void init_give_me_next_number ()
  {
    g_assert (give_me_next_number_mutex == NULL);
    give_me_next_number_mutex = g_mutex_new ();
  }

  int give_me_next_number ()
  {
    static int current_number = 0;
    int ret_val;

    g_mutex_lock (give_me_next_number_mutex);
    ret_val = current_number = calc_next_number (current_number);
    g_mutex_unlock (give_me_next_number_mutex);
    return ret_val;
  }

GStaticMutex provides a simpler and safer way of doing this.

If the user wants to use a mutex, the code should also work without calling g_thread_init() first, the user cannot use a GMutex, as g_mutex_new() requires that. Use a GStaticMutex instead.

A GMutex should only be accessed via the following functions.

Note

Note: All of the g_mutex_* functions are actually macros. Apart from taking their addresses, they can be used as if they were functions.

g_mutex_new ()

GMutex*     g_mutex_new         ();

Creates a new GMutex.

Note

Note: This function will abort, if g_thread_init() has not been called yet.

Returns : a new GMutex.

g_mutex_lock ()

void     g_mutex_lock        (GMutex *mutex);

Locks mutex. If mutex is already locked by another thread, the current thread will block until mutex is unlocked by the other thread.

This function can also be used, if g_thread_init() has not yet been called and will do nothing then.

Note

Note: GMutex is neither guaranteed to be recursive nor to be non-recursive, i.e. a thread could deadlock while calling g_mutex_lock(), if it already has locked mutex. Use GStaticRecMutex, if recursive mutexes are needed.

mutex : a GMutex.

g_mutex_trylock ()

gboolean    g_mutex_trylock       (GMutex *mutex);

Tries to lock mutex. If mutex is already locked by another thread, it immediately returns FALSE. Otherwise it locks mutex and returns TRUE.

This function can also be used, if g_thread_init() has not yet been called and will immediately return TRUE then.

Note

Note: GMutex is neither guaranteed to be recursive nor to be non-recursive, i.e. the return value of g_mutex_trylock() could be both FALSE or TRUE, if the current thread already has locked mutex. Use GStaticRecMutex, if recursive mutexes are needed.

mutex : | a GMutex.
Returns : | TRUE, if mutex could be locked.

g_mutex_unlock ()

void   g_mutex_unlock       (GMutex *mutex);

Unlocks mutex. If another thread is blocked in a g_mutex_lock() call for mutex, it will be woken and can lock mutex itself.

This function can also be used, if g_thread_init() has not yet been called and will do nothing then.

mutex : a GMutex.

g_mutex_free ()

void    g_mutex_free      (GMutex *mutex);

Destroys mutex.

mutex : a GMutex.

GStaticMutex

typedef struct _GStaticMutex GStaticMutex;

A GStaticMutex works like a GMutex, but it has one significant advantage. It does not need to be created at run-time like a GMutex, but can be defined at compile-time. Here is a shorter, easier and safer version of the give_me_next_number() example:

Example 6. Using GStaticMutex to simplify thread-safe programming

  int give_me_next_number ()
  {
    static int current_number = 0;
    int ret_val;
    static GStaticMutex mutex = G_STATIC_MUTEX_INIT;

    g_static_mutex_lock (&mutex);
    ret_val = current_number = calc_next_number (current_number);
    g_static_mutex_unlock (&mutex);
    return ret_val;
  }

When the user would like to dynamically create a mutex without a prior call to g_thread_init() as, the code must be usable in non-threaded programs. The function g_mutex_new() cannot be used and thus GMutex also cannot be used as it requires a prior call to g_thread_init() . In such cases, the function GStaticMutex can be used.It must be initialized with g_static_mutex_init() before using it and freed with g_static_mutex_free() when not needed anymore to free up any allocated resources.

Even though GStaticMutex is not opaque, it should only be used with the following functions, as it is defined differently on different platforms.

All of the g_static_mutex_* functions can also be used, if g_thread_init() has not yet been called.

Note

Note: All of the g_static_mutex_* functions are actually macros. Apart from taking their addresses, they can be used as if they were functions.

G_STATIC_MUTEX_INIT

#define G_STATIC_MUTEX_INIT

A GStaticMutex must be initialized with this macro, before it can be used. This macro can used be to initialize a variable, but it cannot be assigned to a variable. In that case g_static_mutex_init() must be used.

GStaticMutex my_mutex = G_STATIC_MUTEX_INIT;

g_static_mutex_init ()

void        g_static_mutex_init             (GStaticMutex *mutex);

Initializes mutex. Alternatively, it can be initialized by G_STATIC_MUTEX_INIT.

mutex : a GStaticMutex to be initialized.

g_static_mutex_lock ()

void        g_static_mutex_lock             (GStaticMutex *mutex);

Works like g_mutex_lock(), but for a GStaticMutex.

mutex : a GStaticMutex.

g_static_mutex_trylock ()

gboolean    g_static_mutex_trylock          (GStaticMutex *mutex);

Works like g_mutex_trylock(), but for a GStaticMutex.

mutex : | a GStaticMutex.
Returns : | TRUE, if the GStaticMutex could be locked.

g_static_mutex_unlock ()

void        g_static_mutex_unlock           (GStaticMutex *mutex);

Works like g_mutex_unlock(), but for a GStaticMutex.

mutex : a GStaticMutex.

g_static_mutex_get_mutex ()

GMutex*     g_static_mutex_get_mutex        (GStaticMutex *mutex);

For some operations (like g_cond_wait()) the user must have a GMutex instead of a GStaticMutex. This function will return the corresponding GMutex for mutex.

mutex : | a GStaticMutex.
Returns : | the GMutex corresponding to mutex.

g_static_mutex_free ()

void        g_static_mutex_free             (GStaticMutex *mutex);

Releases all resources allocated to mutex.

This function does not have to be called for a GStaticMutex with an unbounded lifetime, i.e. objects declared 'static', but if GStaticMutex is a member of a structure and the structure is freed, GStaticMutex must also be freed.

mutex : a GStaticMutex to be freed.

G_LOCK_DEFINE()

#define     G_LOCK_DEFINE(name)

The G_LOCK_* macros provide a convenient interface to GStaticMutex with the advantage that they will expand to nothing in programs compiled against a thread-disabled GLib, saving code and memory there. G_LOCK_DEFINE defines a lock. It can appear, where variable definitions may appear in programs, i.e. in the first block of a function or outside of functions. The name parameter will be mangled to get the name of the GStaticMutex. This means, that names of existing variables as the parameter can be used, e.g. the name of the variable that the user intents to protect with the lock. Look at the give_me_next_number() example using the G_LOCK_* macros:

Example 7. Using the G_LOCK_* convenience macros

G_LOCK_DEFINE (current_number);

int give_me_next_number ()
  {
    static int current_number = 0;
    int ret_val;

    G_LOCK (current_number);
    ret_val = current_number = calc_next_number (current_number);
    G_UNLOCK (current_number);
    return ret_val;
  }

name : the name of the lock.

G_LOCK_DEFINE_STATIC()

#define     G_LOCK_DEFINE_STATIC(name)

This works like G_LOCK_DEFINE, but it creates a static object.

name : the name of the lock.

G_LOCK_EXTERN()

#define     G_LOCK_EXTERN(name)

This declares a lock, that is defined with G_LOCK_DEFINE in another module.

name : the name of the lock.

G_LOCK()

#define     G_LOCK(name)

Works like g_mutex_lock(), but for a lock defined with G_LOCK_DEFINE.

name : the name of the lock.

G_TRYLOCK()

#define     G_TRYLOCK(name)

Works like g_mutex_trylock(), but for a lock defined with G_LOCK_DEFINE.

name : | the name of the lock.
Returns : | TRUE, if the lock could be locked.

G_UNLOCK()

#define     G_UNLOCK(name)

Works like g_mutex_unlock(), but for a lock defined with G_LOCK_DEFINE.

name : the name of the lock.

GStaticRecMutex

typedef struct {
} GStaticRecMutex;

A GStaticRecMutex works like a GStaticMutex, but it can be locked multiple times by one thread. If entered n times, however, it must be unlocked n times again to let other threads lock it. An exception is the function g_static_rec_mutex_unlock_full(), that allows to unlock a GStaticRecMutex completely returning the depth, i.e. the number of times this mutex was locked. The depth can later be used to restore the state by calling g_static_rec_mutex_lock_full().

Even though GStaticRecMutex is not opaque, it should only be used with the following functions.

All of the g_static_rec_mutex_* functions can also be used, if g_thread_init() has not been called.

G_STATIC_REC_MUTEX_INIT

#define G_STATIC_REC_MUTEX_INIT { G_STATIC_MUTEX_INIT }

A GStaticRecMutex must be initialized with this macro, before it can be used. This macro can used be to initialize a variable, but it cannot be assigned to a variable. In that case use g_static_rec_mutex_init().

GStaticRecMutex my_mutex = G_STATIC_REC_MUTEX_INIT;

g_static_rec_mutex_init ()

void        g_static_rec_mutex_init         (GStaticRecMutex *mutex);

A GStaticRecMutex must be initialized with this function, before it can be used. Alternatively, it can be initialized by G_STATIC_REC_MUTEX_INIT.

mutex : a GStaticRecMutex to be initialized.

g_static_rec_mutex_lock ()

void        g_static_rec_mutex_lock         (GStaticRecMutex *mutex);

Locks mutex. If mutex is already locked by another thread, the current thread will block until mutex is unlocked by the other thread. If mutex is already locked by the calling thread, this functions increases the depth of mutex and returns immediately.

mutex : a GStaticRecMutex to lock.

g_static_rec_mutex_trylock ()

gboolean    g_static_rec_mutex_trylock      (GStaticRecMutex *mutex);

Tries to lock mutex. If mutex is already locked by another thread, it immediately returns FALSE. Otherwise it locks mutex and returns TRUE. If mutex is already locked by the calling thread, this functions increases the depth of mutex and immediately returns TRUE.

mutex : | a GStaticRecMutex to lock.
Returns : | TRUE, if mutex could be locked.

g_static_rec_mutex_unlock ()

void        g_static_rec_mutex_unlock       (GStaticRecMutex *mutex);

Unlocks mutex. Another threads can, however, only lock mutex when it has been unlocked as many times, as it had been locked before. If mutex is completely unlocked and another thread is blocked in a g_static_rec_mutex_lock() call for mutex, it will be woken and can lock mutex itself.

mutex : a GStaticRecMutex to unlock.

g_static_rec_mutex_lock_full ()

void        g_static_rec_mutex_lock_full    (GStaticRecMutex *mutex,
                                             guint depth);

Works like calling g_static_rec_mutex_lock() for mutex depth times.

mutex : | a GStaticRecMutex to lock.
depth : | number of times this mutex has to be unlocked to be completely unlocked.

g_static_rec_mutex_unlock_full ()

guint       g_static_rec_mutex_unlock_full  (GStaticRecMutex *mutex);

Completely unlocks mutex. If another thread is blocked in a g_static_rec_mutex_lock() call for mutex, it will be woken and can lock mutex itself. This function returns the number of times, that mutex has been locked by the current thread. To restore the state before the call to g_static_rec_mutex_unlock_full(), a call to g_static_rec_mutex_lock_full() with the depth returned by this function ca be done.

mutex : | a GStaticRecMutex to completely unlock.
Returns : | number of times mutex has been locked by the current thread.

g_static_rec_mutex_free ()

void        g_static_rec_mutex_free         (GStaticRecMutex *mutex);

Releases all resources allocated to a GStaticRecMutex.

A call to this function is not needed for a GStaticRecMutex with an unbounded lifetime, i.e. objects declared 'static', but if GStaticRecMutex is a member of a structure and the structure is freed, then GStaticRecMutex also needs to be freed.

mutex : a GStaticRecMutex to be freed.

GStaticRWLock

typedef struct {
} GStaticRWLock;

The GStaticRWLock struct represents a read-write lock. A read-write lock can be used for protecting data, that some portions of code only read from, while others also write. In such situations it is desirable, that several readers can read at once, whereas of course only one writer may write at a time. Take a look at the following example:

Example 8. An array with access functions

  GStaticRWLock rwlock = G_STATIC_RW_LOCK_INIT;

  GPtrArray *array;

  gpointer my_array_get (guint index)
  {
    gpointer retval = NULL;

    if (!array)
      return NULL;

    g_static_rw_lock_reader_lock (&rwlock);

    if (index < array->len)
      retval = g_ptr_array_index (array, index);

    g_static_rw_lock_reader_unlock (&rwlock);

    return retval;
  }

  void my_array_set (guint index, gpointer data)
  {
    g_static_rw_lock_writer_lock (&rwlock);

    if (!array)
      array = g_ptr_array_new ();

    if (index >= array->len)
      g_ptr_array_set_size (array, index+1);

    g_ptr_array_index (array, index) = data;

    g_static_rw_lock_writer_unlock (&rwlock);
  }

This example shows an array, which can be accessed by many readers (the my_array_get() function) simultaneously, whereas the writers (the my_array_set() function) will only be allowed one at a time and only if no readers are currently accessing the array. This is because of the potentially dangerous resizing of the array. Using these functions is fully multi-thread safe now.

Most of the time the writers should have precedence of readers. That means for this implementation, that as soon as a writer wants to lock the data, no other reader is allowed to lock the data, whereas of course the readers, that already have locked the data are allowed to finish their operation. As soon as the last reader unlocks the data, the writer will lock it.

Even though GStaticRWLock is not opaque, it should only be used with the following functions.

All of the g_static_rw_lock_* functions can also be used, if g_thread_init() has not been called.

Note

Note: A read-write lock has a higher overhead as a mutex. For example both g_static_rw_lock_reader_lock() and g_static_rw_lock_reader_unlock() have to lock and unlock a GStaticMutex, so it takes at least twice the time to lock and unlock a GStaticRWLock than to lock and unlock a GStaticMutex. So only data structures, that are accessed by multiple readers, which keep the lock for a considerable time justify a GStaticRWLock. The above example most probably would fare better with a GStaticMutex.

G_STATIC_RW_LOCK_INIT

#define G_STATIC_RW_LOCK_INIT { G_STATIC_MUTEX_INIT, NULL, NULL, 0, FALSE, 0, 0 }

A GStaticRWLock must be initialized with this macro, before it can be used. This macro can used be to initialize a variable, but it cannot be assigned to a variable. In that case use g_static_rw_lock_init().

GStaticRWLock my_lock = G_STATIC_RW_LOCK_INIT;

g_static_rw_lock_init ()

void        g_static_rw_lock_init           (GStaticRWLock *lock);

A GStaticRWLock must be initialized with this function, before it can be used. Alternatively,it can be initialized by G_STATIC_RW_LOCK_INIT.

lock : a GStaticRWLock to be initialized.

g_static_rw_lock_reader_lock ()

void        g_static_rw_lock_reader_lock    (GStaticRWLock *lock);

Locks lock for reading. There may be unlimited concurrent locks for reading of a GStaticRWLock at the same time. If lock is already locked for writing by another thread or if another thread is already waiting to lock lock for writing, this function will block until lock is unlocked by the other writing thread and no other writing threads want to lock lock. This lock has to be unlocked by g_static_rw_lock_reader_unlock().

GStaticRWLock is not recursive. It might seem to be possible to recursively lock for reading, but that can result in a deadlock as well, due to writer preference.

lock : a GStaticRWLock to lock for reading.

g_static_rw_lock_reader_trylock ()

gboolean    g_static_rw_lock_reader_trylock (GStaticRWLock *lock);

Tries to lock lock for reading. If lock is already locked for writing by another thread or if another thread is already waiting to lock lock for writing, it immediately returns FALSE. Otherwise it locks lock for reading and returns TRUE. This lock has to be unlocked by g_static_rw_lock_reader_unlock().

lock : | a GStaticRWLock to lock for reading.
Returns : | TRUE, if lock could be locked for reading.

g_static_rw_lock_reader_unlock ()

void        g_static_rw_lock_reader_unlock  (GStaticRWLock *lock);

Unlocks lock. If a thread waits to lock lock for writing and all locks for reading have been unlocked, the waiting thread is woken up and can lock lock for writing.

lock : a GStaticRWLock to unlock after reading.

g_static_rw_lock_writer_lock ()

void        g_static_rw_lock_writer_lock    (GStaticRWLock *lock);

Locks lock for writing. If lock is already locked for writing or reading by other threads, this function will block until lock is completely unlocked and then lock lock for writing. While this functions waits to lock lock, no other thread can lock lock for reading. When lock is locked for writing, no other thread can lock lock (neither for reading nor writing). This lock has to be unlocked by g_static_rw_lock_writer_unlock().

lock : a GStaticRWLock to lock for writing.

g_static_rw_lock_writer_trylock ()

gboolean    g_static_rw_lock_writer_trylock (GStaticRWLock *lock);

Tries to lock lock for writing. If lock is already locked (for either reading or writing) by another thread, it immediately returns FALSE. Otherwise it locks lock for writing and returns TRUE. This lock has to be unlocked by g_static_rw_lock_writer_unlock().

lock : | a GStaticRWLock to lock for writing.
Returns : | TRUE, if lock could be locked for writing.

g_static_rw_lock_writer_unlock ()

void        g_static_rw_lock_writer_unlock  (GStaticRWLock *lock);

Unlocks lock. If a thread waits to lock lock for writing and all locks for reading have been unlocked, the waiting thread is woken up and can lock lock for writing. If no thread waits to lock lock for writing and threads wait to lock lock for reading, the waiting threads are woken up and can lock lock for reading.

lock : a GStaticRWLock to unlock after writing.

g_static_rw_lock_free ()

void        g_static_rw_lock_free           (GStaticRWLock *lock);

Releases all resources allocated to lock.

A call to this function is not needed for a GStaticRWLock with an unbounded lifetime, i.e. objects declared 'static', but if GStaticRWLock is a member of a structure and the structure is freed, then GStaticRWLock must also be freed.

lock : a GStaticRWLock to be freed.

GCond

typedef struct _GCond GCond;

The GCond struct is an opaque data structure to represent a condition. A GCond is an object, that threads can block on, if they find a certain condition to be false. If other threads change the state of this condition they can signal the GCond, such that the waiting thread is woken up.

Example 9. Using GCond to block a thread until a condition is satisfied

GCond* data_cond = NULL;   /* Must be initialized somewhere */
GMutex* data_mutex = NULL; /* Must be initialized somewhere */
gpointer current_data = NULL;

void push_data (gpointer data)
{
  g_mutex_lock (data_mutex);
  current_data = data;
  g_cond_signal (data_cond);
  g_mutex_unlock (data_mutex);
}

gpointer pop_data ()
{
  gpointer data;

  g_mutex_lock (data_mutex);
  while (!current_data)
      g_cond_wait (data_cond, data_mutex);
  data = current_data;
  current_data = NULL;
  g_mutex_unlock (data_mutex);
  return data;
}

Whenever a thread calls pop_data() now, it will wait until current_data is non-NULL, i.e. until some other thread has called push_data().

Note

Note: It is important to use the g_cond_wait() and g_cond_timed_wait() functions only inside a loop, which checks for the condition to be true as it is not guaranteed that the waiting thread will find it fulfilled, even if the signaling thread left the condition in that state. This is because another thread can have altered the condition, before the waiting thread got the chance to be woken up, even if the condition itself is protected by a GMutex, like above.

A GCond should only be accessed via the following functions.

Note

Note: All of the g_cond_* functions are actually macros. Apart from taking their addresses, they can be used as if they were functions.

g_cond_new ()

GCond*      g_cond_new                      ();

Creates a new GCond. This function will abort, if g_thread_init() has not been called yet.

Returns : a new GCond.

g_cond_signal ()

void        g_cond_signal                   (GCond *cond);

If threads are waiting for cond, exactly one of them is woken up. It is good practice to hold the same lock as the waiting thread, while calling this function, though not required.

This function can also be used, if g_thread_init() has not yet been called and will do nothing then.

cond : a GCond.

g_cond_broadcast ()

void        g_cond_broadcast                (GCond *cond);

If threads are waiting for cond, all of them are woken up. It is good practice to lock the same mutex as the waiting threads, while calling this function, though not required.

This function can also be used, if g_thread_init() has not yet been called and will do nothing then.

cond : a GCond.

g_cond_wait ()

void        g_cond_wait                     (GCond *cond, GMutex *mutex);

Waits until this thread is woken up on cond. The mutex is unlocked before falling asleep and locked again before resuming.

This function can also be used, if g_thread_init() has not yet been called and will immediately return then.

cond : | a GCond.
mutex : | a GMutex, that is currently locked.

g_cond_timed_wait ()

gboolean    g_cond_timed_wait               (GCond *cond, GMutex *mutex, GTimeVal *abs_time);

Waits until this thread is woken up on cond, but not longer than until the time, that is specified by abs_time. The mutex is unlocked before falling asleep and locked again before resuming.

If abs_time is NULL, g_cond_timed_wait() acts like g_cond_wait().

This function can also be used, if g_thread_init() has not yet been called and will immediately return TRUE then.

To easily calculate abs_time a combination of g_get_current_time() and g_time_val_add() can be used.

cond : | a GCond.
mutex : | a GMutex, that is currently locked.
abs_time : | a GTimeVal, determining the final time.
Returns : | TRUE, if the thread is woken up in time.

g_cond_free ()

void        g_cond_free                     (GCond *cond);

Destroys the GCond.

cond : a GCond.

GPrivate

typedef struct _GPrivate GPrivate;

The GPrivate struct is an opaque data structure to represent a thread private data key. Threads can thereby obtain and set a pointer, which is private to the current thread. Use the give_me_next_number() example from above. If the user does not want current_number to be shared between the threads, but to be private to each thread. This can be done as follows:

Example 10. Using GPrivate for per-thread data

  GPrivate* current_number_key = NULL; /* Must be initialized somewhere */
                                       /* with g_private_new (g_free); */

  int give_me_next_number ()
  {
    int *current_number = g_private_get (current_number_key);

    if (!current_number)
    {
      current_number = g_new (int,1);
      *current_number = 0;
      g_private_set (current_number_key, current_number);
    }
    *current_number = calc_next_number (*current_number);
    return *current_number;
  }

Here the pointer belonging to the key current_number_key is read. If it is NULL, it has not been set yet. Then get memory for an integer value, assign this memory to the pointer and write the pointer back. The integer value thus obtained, is private to the current thread.

The GPrivate struct should only be accessed via the following functions.

Note

Note: All of the g_private_* functions are actually macros. Apart from taking their addresses, they can be used as if they were functions.

g_private_new ()

GPrivate*   g_private_new        (GDestroyNotify destructor);

Creates a new GPrivate. If destructor is non-NULL, it is a pointer to a destructor function. Whenever a thread ends and the corresponding pointer keyed to this instance of GPrivate is non-NULL, the destructor is called with this pointer as the argument.

Note

Note: A GPrivate can not be freed. Reuse it instead, to avoid shortage or use GStaticPrivate. This function will abort, if g_thread_init() has not been called yet.

destructor : | a function to handle the data keyed to GPrivate, when a thread ends.
Returns : | a new GPrivate.

g_private_get ()

gpointer    g_private_get         (GPrivate *private_key);

Returns the pointer keyed to private_key for the current thread. This pointer is NULL, when g_private_set() has not been called for the current private_key and thread yet.

This function can also be used, if g_thread_init() has not yet been called and will return the value of private_key casted to gpointer then.

private_key : | a GPrivate.
Returns : | the corresponding pointer.

g_private_set ()

void        g_private_set          (GPrivate *private_key, gpointer data);

Sets the pointer keyed to private_key for the current thread.

This function can also be used, if g_thread_init() has not yet been called and will set private_key to data casted to GPrivate* then.

private_key : | a GPrivate.
data : | the new pointer.

GStaticPrivate

typedef struct {
} GStaticPrivate;

A GStaticPrivate works almost like a GPrivate, but it has one significant advantage. It does not need to be created at run-time like a GPrivate, but can be defined at compile-time. This is similar to the difference between GMutex and GStaticMutex. Now look at the give_me_next_number() example with GStaticPrivate:

Example 11. Using GStaticPrivate for per-thread data

  int give_me_next_number ()
  {
    static GStaticPrivate current_number_key = G_STATIC_PRIVATE_INIT;
    int *current_number = g_static_private_get (&current_number_key);

    if (!current_number)
    {
      current_number = g_new (int,1);
      *current_number = 0;
      g_static_private_set (&current_number_key, current_number, g_free);
    }
    *current_number = calc_next_number (*current_number);
    return *current_number;
  }

G_STATIC_PRIVATE_INIT

#define G_STATIC_PRIVATE_INIT

Every GStaticPrivate must be initialized with this macro, before it can be used.

GStaticPrivate my_private = G_STATIC_PRIVATE_INIT;

g_static_private_init ()

void        g_static_private_init           (GStaticPrivate *private_key);

Initializes private_key. Alternatively, it can be initialized by G_STATIC_PRIVATE_INIT.

private_key : a GStaticPrivate to be initialized.

g_static_private_get ()

gpointer    g_static_private_get            (GStaticPrivate *private_key);

Works like g_private_get() only for a GStaticPrivate.

This function also works, if g_thread_init() has not yet been called.

private_key : | a GStaticPrivate.
Returns : | the corresponding pointer.

g_static_private_set ()

void        g_static_private_set            (GStaticPrivate *private_key, gpointer data, GDestroyNotify notify);

Sets the pointer keyed to private_key for the current thread and the function notify to be called with that pointer (NULL or non-NULL), whenever the pointer is set again or whenever the current thread ends.

This function also works, if g_thread_init() has not yet been called. If g_thread_init() is called later, the data keyed to private_key will be inherited only by the main thread, i.e. the one that called g_thread_init().

Note

Note: notify is working quite differently from destructor in g_private_new().

private_key : | a GStaticPrivate.
data : | the new pointer.
notify : | a function to be called with the pointer, whenever the current thread ends or sets this pointer again.

g_static_private_free ()

void        g_static_private_free           (GStaticPrivate *private_key);

Releases all resources allocated to private_key.

A call to this function is not needed for a GStaticPrivate with an unbounded lifetime, i.e. objects declared 'static', but if GStaticPrivate is a member of a structure and the structure is freed, then GStaticPrivate must be freed.

private_key : a GStaticPrivate to be freed.

GOnce

typedef struct {
  volatile GOnceStatus status;
  volatile gpointer retval;
} GOnce;

A GOnce struct controls a one-time initialization function. Any one-time initialization function must have its own unique GOnce struct.

volatile GOnceStatus status; | the status of the GOnce
volatile gpointer retval; | the value returned by the call to the function, if status is G_ONCE_STATUS_READY

enum GOnceStatus

typedef enum
{
  G_ONCE_STATUS_NOTCALLED,
  G_ONCE_STATUS_PROGRESS,
  G_ONCE_STATUS_READY
} GOnceStatus;

The possible stati of a one-time initialization function controlled by a GOnce struct.

G_ONCE_STATUS_NOTCALLED | the function has not been called yet.
G_ONCE_STATUS_PROGRESS | the function call is currently in progress.
G_ONCE_STATUS_READY | the function has been called.

G_ONCE_INIT

#define G_ONCE_INIT { G_ONCE_STATUS_NOTCALLED, NULL }

A GOnce must be initialized with this macro, before it can be used.

GOnce my_once = G_ONCE_INIT;

g_once()

#define     g_once(once, func, arg)

The first call to this routine by a process with a given GOnce struct calls func with the given argument. Thereafter, subsequent calls to g_once() with the same GOnce struct do not call func again, but return the stored result of the first call. On return from g_once(), the status of once will be G_ONCE_STATUS_READY.

For example, a mutex or a thread-specific data key must be created exactly once. In a threaded environment, calling g_once() ensures that the initialization is serialized across multiple threads.

Note

Note: Calling g_once() recursively on the same GOnce struct in func will lead to a deadlock.

gpointer
get_debug_flags()
{
  static GOnce my_once = G_ONCE_INIT;

  g_once (&my_once, parse_debug_flags, NULL);

  return my_once.retval;
}

once : | a GOnce structure
func : | the GTreadFunc function associated to once. This function is called only once, regardless of the number of times it and its associated GOnce struct are passed to g_once() .
arg : | data to be passed to func

See Also

GThreadPool | Thread pools.
GAsyncQueue | Send asynchronous messages between threads.

Feedback

For additional information or queries on this page send feedback


Timers

Name

Timers — keep track of elapsed time.

Library

glib.lib

Synopsis

#include <glib.h>

            GTimer;
GTimer*     g_timer_new         (void);
void        g_timer_start       (GTimer *timer);
void        g_timer_stop        (GTimer *timer);
void        g_timer_continue    (GTimer *timer);
gdouble     g_timer_elapsed     (GTimer *timer, gulong *microseconds);
void        g_timer_reset       (GTimer *timer);
void        g_timer_destroy     (GTimer *timer);

Detailed Description

GTimer records a start time, and counts microseconds elapsed since that time. This is done somewhat differently on different platforms, and can be tricky to get exactly right, so GTimer provides a portable/convenient interface.

Details

GTimer

typedef struct _GTimer GTimer;

Opaque datatype that records a start time.

g_timer_new ()

GTimer*   g_timer_new      (void);

Creates a new timer, and starts timing (i.e. g_timer_start() is called implicitly).

Returns : a new GTimer.

g_timer_start ()

void    g_timer_start     (GTimer *timer);

Marks a start time, so that future calls to g_timer_elapsed() will report the time since g_timer_start() was called. g_timer_new() automatically marks the start time, so no need to call g_timer_start() immediately after creating the timer.

timer : a GTimer.

g_timer_stop ()

void    g_timer_stop      (GTimer *timer);

Marks an end time, so calls to g_timer_elapsed() will return the difference between this end time and the start time.

timer : a GTimer.

g_timer_continue ()

void   g_timer_continue   (GTimer *timer);

Resumes a timer that has previously been stopped with g_timer_stop(). g_timer_stop() must be called before using this function.

timer : a GTimer.

g_timer_elapsed ()

gdouble  g_timer_elapsed  (GTimer *timer, gulong *microseconds);

If timer has been started but not stopped, obtains the time since the timer was started. If timer has been stopped, obtains the elapsed time between the time it was started and the time it was stopped. The return value is the number of seconds elapsed, including any fractional part. The microseconds out parameter is essentially useless.

timer : | a GTimer.
microseconds : | return location for the fractional part of seconds elapsed, in microseconds (that is, the total number of microseconds elapsed, modulo 1000000), or NULL )
Returns : | seconds elapsed as a floating point value, including any fractional part.

g_timer_reset ()

void    g_timer_reset    (GTimer *timer);

This function is useless; it's fine to call g_timer_start() on an already-started timer to reset the start time, so g_timer_reset() serves no purpose.

timer : a GTimer.

g_timer_destroy ()

void   g_timer_destroy   (GTimer *timer);

Destroys a timer, freeing associated resources.

timer : a GTimer.

Feedback

For additional information or queries on this page send feedback


Trash Stacks

Name

Trash Stacks — maintain a stack of unused allocated memory chunks.

Library

glib.lib

Synopsis

#include <glib.h>

          GTrashStack;
void      g_trash_stack_push    (GTrashStack **stack_p, gpointer data_p);
gpointer  g_trash_stack_pop     (GTrashStack **stack_p);
gpointer  g_trash_stack_peek    (GTrashStack **stack_p);
guint     g_trash_stack_height  (GTrashStack **stack_p);

Detailed Description

A GTrashStack is an efficient way to keep a stack of unused allocated memory chunks. Each memory chunk is required to be large enough to hold a gpointer. This allows the stack to be maintained without any space overhead, since the stack pointers can be stored inside the memory chunks.

There is no function to create a GTrashStack. A NULL GTrashStack* is a perfectly valid empty stack.

Details

GTrashStack

typedef struct {
  GTrashStack *next;
} GTrashStack;

Each piece of memory that is pushed onto the stack is cast to a GTrashStack*.

GTrashStack *next; pointer to the previous element of the stack, gets stored in the first sizeof (gpointer) bytes of the element.

g_trash_stack_push ()

void  g_trash_stack_push    (GTrashStack **stack_p, gpointer data_p);

Pushes a piece of memory onto a GTrashStack.

stack_p : | a pointer to a GTrashStack.
data_p : | the piece of memory to push on the stack.

g_trash_stack_pop ()

gpointer  g_trash_stack_pop  (GTrashStack **stack_p);

Pops a piece of memory off a GTrashStack.

stack_p : | a pointer to a GTrashStack.
Returns : | the element at the top of the stack.

g_trash_stack_peek ()

gpointer  g_trash_stack_peek   (GTrashStack **stack_p);

Returns the element at the top of a GTrashStack.

stack_p : | a pointer to a GTrashStack.
Returns : | the element at the top of the stack.

g_trash_stack_height ()

guint  g_trash_stack_height   (GTrashStack **stack_p);

Returns the height of a GTrashStack.

stack_p : | a pointer to a GTrashStack.
Returns : | the height of the stack.

Feedback

For additional information or queries on this page send feedback


Type Conversion Macros

Name

Type Conversion Macros — portably storing integers in pointer variables.

Library

glib.lib

Synopsis

#include <glib.h>

#define  GINT_TO_POINTER   (i)
#define  GPOINTER_TO_INT   (p)

#define  GUINT_TO_POINTER  (u)
#define  GPOINTER_TO_UINT  (p)
#define  GSIZE_TO_POINTER  (s)
#define  GPOINTER_TO_SIZE  (p)

Detailed Description

Many times GLib, GTK+, and other libraries allow to pass "user data" to a callback, in the form of a void pointer. From time to time, to pass an integer instead of a pointer. Allocate an integer, with something like:

 int *ip = g_new (int, 1);
 *ip = 42;

This is inconvenient, but annoying to have to free the memory some later time.

Pointers are always at least 32 bits in size (on all platforms GLib intends to support). Thus, at least 32-bit integer values can be stored in a pointer value. Do not do the this as, it is incorrect:

 gpointer p;
 int i;
 p = (void*) 42;
 i = (int) p;

Again, that example was not correct, do not copy it. The problem is that on some systems this should be done:

 gpointer p;
 int i;
 p = (void*) (long) 42;
 i = (int) (long) p;

So GPOINTER_TO_INT(), GINT_TO_POINTER(), etc. do the right thing on the current platform.

WARNING

Warning: DO NOT STORE POINTERS IN INTEGERS. THIS IS NOT PORTABLE IN ANY WAY, SHAPE OR FORM. These macros ONLY allow storing integers in pointers, and only preserve 32 bits of the integer; values outside the range of a 32-bit integer will be mangled.

Details

GINT_TO_POINTER()

#define GINT_TO_POINTER(i)	((gpointer)  (i))

Stuffs an integer into a pointer type.

Remember, DO NOT STORE POINTERS IN INTEGERS. THIS IS NOT PORTABLE IN ANY WAY, SHAPE OR FORM. These macros ONLY allow storing integers in pointers, and only preserve 32 bits of the integer; values outside the range of a 32-bit integer will be mangled.

i : integer to stuff into a pointer.

GPOINTER_TO_INT()

#define GPOINTER_TO_INT(p)	((gint)   (p))

Extracts an integer from a pointer. The integer must have been stored in the pointer with GINT_TO_POINTER().

Remember,DO NOT STORE POINTERS IN INTEGERS. THIS IS NOT PORTABLE IN ANY WAY, SHAPE OR FORM. These macros ONLY allow storing integers in pointers, and only preserve 32 bits of the integer; values outside the range of a 32-bit integer will be mangled.

p : pointer containing an integer.

GUINT_TO_POINTER()

#define GUINT_TO_POINTER(u)	((gpointer)  (u))

Stuffs an unsigned integer into a pointer type.

u : unsigned integer to stuff into the pointer.

GPOINTER_TO_UINT()

#define GPOINTER_TO_UINT(p)	((guint)  (p))

Extracts an unsigned integer from a pointer. The integer must have been stored in the pointer with GUINT_TO_POINTER().

p : pointer to extract an unsigned integer from.

GSIZE_TO_POINTER()

#define GSIZE_TO_POINTER(s)	((gpointer) (gsize) (s))

Stuffs a gsize into a pointer type.

s : gsize to stuff into the pointer.

GPOINTER_TO_SIZE()

#define GPOINTER_TO_SIZE(p)	((gsize) (p))

Extracts a gsize from a pointer. The gsize must have been stored in the pointer with GSIZE_TO_POINTER().

p : pointer to extract a gsize from.

Feedback

For additional information or queries on this page send feedback


Unicode Manipulation

Name

Unicode Manipulation — functions operating on Unicode characters and UTF-8 strings.

Library

glib.lib

Synopsis

#include <glib.h>

typedef     gunichar;
typedef     gunichar2;

gboolean    g_unichar_validate              (gunichar ch);
gboolean    g_unichar_isalnum               (gunichar c);
gboolean    g_unichar_isalpha               (gunichar c);
gboolean    g_unichar_iscntrl               (gunichar c);
gboolean    g_unichar_isdigit               (gunichar c);
gboolean    g_unichar_isgraph               (gunichar c);
gboolean    g_unichar_islower               (gunichar c);
gboolean    g_unichar_isprint               (gunichar c);
gboolean    g_unichar_ispunct               (gunichar c);
gboolean    g_unichar_isspace               (gunichar c);
gboolean    g_unichar_isupper               (gunichar c);
gboolean    g_unichar_isxdigit              (gunichar c);
gboolean    g_unichar_istitle               (gunichar c);
gboolean    g_unichar_isdefined             (gunichar c);
gboolean    g_unichar_iswide                (gunichar c);
gunichar    g_unichar_toupper               (gunichar c);
gunichar    g_unichar_tolower               (gunichar c);
gunichar    g_unichar_totitle               (gunichar c);
gint        g_unichar_digit_value           (gunichar c);
gint        g_unichar_xdigit_value          (gunichar c);
enum        GUnicodeType;
GUnicodeType g_unichar_type                 (gunichar c);
enum         GUnicodeBreakType;
GUnicodeBreakType g_unichar_break_type      (gunichar c);
void        g_unicode_canonical_ordering    (gunichar *string, gsize len);
gunichar*   g_unicode_canonical_decomposition (gunichar ch, gsize *result_len);
gboolean    g_unichar_get_mirror_char         (gunichar ch, gunichar *mirrored_ch);

#define     g_utf8_next_char                (p)
gunichar    g_utf8_get_char                 (const gchar *p);
gunichar    g_utf8_get_char_validated       (const  gchar *p, gssize max_len);
gchar*      g_utf8_offset_to_pointer        (const gchar *str, glong offset);
glong       g_utf8_pointer_to_offset        (const gchar *str, const gchar *pos);
gchar*      g_utf8_prev_char                (const gchar *p);
gchar*      g_utf8_find_next_char           (const gchar *p, const gchar *end);
gchar*      g_utf8_find_prev_char           (const gchar *str, const gchar *p);
glong       g_utf8_strlen                   (const gchar *p, gssize max);
gchar*      g_utf8_strncpy                  (gchar *dest, const gchar *src,
                                             gsize n);
gchar*      g_utf8_strchr                   (const gchar *p, gssize len, gunichar c);
gchar*      g_utf8_strrchr                  (const gchar *p, gssize len, gunichar c);
gchar*      g_utf8_strreverse               (const gchar *str, gssize len);
gboolean    g_utf8_validate                 (const gchar *str, gssize max_len, const gchar **end);

gchar*      g_utf8_strup                    (const gchar *str, gssize len);
gchar*      g_utf8_strdown                  (const gchar *str, gssize len);
gchar*      g_utf8_casefold                 (const gchar *str, gssize len);
gchar*      g_utf8_normalize                (const gchar *str, gssize len, GNormalizeMode mode);
enum        GNormalizeMode;
gint        g_utf8_collate                  (const gchar *str1, const gchar *str2);
gchar*      g_utf8_collate_key              (const gchar *str, gssize len);
gchar*      g_utf8_collate_key_for_filename (const gchar *str, gssize len);

gunichar2*  g_utf8_to_utf16                 (const gchar *str, glong len, glong *items_read, glong
                                            *items_written, GError **error);
gunichar*   g_utf8_to_ucs4                  (const gchar *str, glong len, glong *items_read, glong *items_written, GError **error);
gunichar*   g_utf8_to_ucs4_fast             (const gchar *str, glong len, glong *items_written);
gunichar*   g_utf16_to_ucs4                 (const gunichar2 *str, glong len, glong *items_read, glong *items_written, GError **error);
gchar*      g_utf16_to_utf8                 (const gunichar2 *str, glong len, glong *items_read, glong *items_written, GError **error);
gunichar2*  g_ucs4_to_utf16                 (const gunichar *str, glong len, glong *items_read, glong *items_written, GError **error);
gchar*      g_ucs4_to_utf8                  (const gunichar *str, glong len, glong *items_read, glong *items_written, GError **error);
gint        g_unichar_to_utf8               (gunichar c, gchar *outbuf);

Detailed Description

This section describes a number of functions for dealing with Unicode characters and strings. There are analogues of the traditional ctype.h character classification and case conversion functions, UTF-8 analogues of some string utility functions, functions to perform normalization, case conversion and collation on UTF-8 strings and finally functions to convert between the UTF-8, UTF-16 and UCS-4 encodings of Unicode.

Details

gunichar

typedef guint32 gunichar;

A type which can hold any UCS-4 character code.

gunichar2

typedef guint16 gunichar2;

A type which can hold any UTF-16 code point[3].

g_unichar_validate ()

gboolean    g_unichar_validate          (gunichar ch);

Checks whether ch is a valid Unicode character. Some possible integer values of ch will not be valid. 0 is considered a valid character, though it's normally a string terminator.

ch : | a Unicode character
Returns : | TRUE if ch is a valid Unicode character

g_unichar_isalnum ()

gboolean    g_unichar_isalnum           (gunichar c);

Determines whether a character is alphanumeric. Given some UTF-8 text, obtain a character value with g_utf8_get_char().

c : | a Unicode character
Returns : | TRUE if c is an alphanumeric character

g_unichar_isalpha ()

gboolean    g_unichar_isalpha       (gunichar c);

Determines whether a character is alphabetic (i.e. a letter). Given some UTF-8 text, obtain a character value with g_utf8_get_char().

c : | a Unicode character
Returns : | TRUE if c is an alphabetic character

g_unichar_iscntrl ()

gboolean    g_unichar_iscntrl        (gunichar c);

Determines whether a character is a control character. Given some UTF-8 text, obtain a character value with g_utf8_get_char().

c : | a Unicode character
Returns : | TRUE if c is a control character

g_unichar_isdigit ()

gboolean    g_unichar_isdigit         (gunichar c);

Determines whether a character is numeric (i.e. a digit). This covers ASCII 0-9 and also digits in other languages/scripts. Given some UTF-8 text, obtain a character value with g_utf8_get_char().

c : | a Unicode character
Returns : | TRUE if c is a digit

g_unichar_isgraph ()

gboolean    g_unichar_isgraph          (gunichar c);

Determines whether a character is printable and not a space (returns FALSE for control characters, format characters, and spaces). g_unichar_isprint() is similar, but returns TRUE for spaces. Given some UTF-8 text, obtain a character value with g_utf8_get_char().

c : | a Unicode character
Returns : | TRUE if c is printable unless it's a space

g_unichar_islower ()

gboolean    g_unichar_islower               (gunichar c);

Determines whether a character is a lowercase letter. Given some UTF-8 text, obtain a character value with g_utf8_get_char().

c : | a Unicode character
Returns : | TRUE if c is a lowercase letter

g_unichar_isprint ()

gboolean    g_unichar_isprint               (gunichar c);

Determines whether a character is printable. Unlike g_unichar_isgraph(), returns TRUE for spaces. Given some UTF-8 text, obtain a character value with g_utf8_get_char().

c : | a Unicode character
Returns : | TRUE if c is printable

g_unichar_ispunct ()

gboolean    g_unichar_ispunct               (gunichar c);

Determines whether a character is punctuation or a symbol. Given some UTF-8 text, obtain a character value with g_utf8_get_char().

c : | a Unicode character
Returns : | TRUE if c is a punctuation or symbol character

g_unichar_isspace ()

gboolean    g_unichar_isspace               (gunichar c);

Determines whether a character is a space, tab, or line separator (new line, carriage return, etc.). Given some UTF-8 text, obtain a character value with g_utf8_get_char().

(Note: Do not use this to do word breaking; use Pango or equivalent to get word breaking right, the algorithm is fairly complex.)

c : | a Unicode character
Returns : | TRUE if c is a space character

g_unichar_isupper ()

gboolean    g_unichar_isupper               (gunichar c);

Determines if a character is uppercase.

c : | a Unicode character
Returns : | TRUE if c is an uppercase character

g_unichar_isxdigit ()

gboolean    g_unichar_isxdigit              (gunichar c);

Determines if a character is a hexadecimal digit.

c : | a Unicode character.
Returns : | TRUE if the character is a hexadecimal digit

g_unichar_istitle ()

gboolean    g_unichar_istitle               (gunichar c);

Determines if a character is titlecase. Some characters in Unicode which are composites, such as the DZ digraph have three case variants instead of just two. The titlecase form is used at the beginning of a word where only the first letter is capitalized. The titlecase form of the DZ digraph is U+01F2 LATIN CAPITAL LETTTER D WITH SMALL LETTER Z.

c : | a Unicode character
Returns : | TRUE if the character is titlecase

g_unichar_isdefined ()

gboolean    g_unichar_isdefined             (gunichar c);

Determines if a given character is assigned in the Unicode standard.

c : | a Unicode character
Returns : | TRUE if the character has an assigned value

g_unichar_iswide ()

gboolean    g_unichar_iswide                (gunichar c);

Determines if a character is typically rendered in a double-width cell.

c : | a Unicode character
Returns : | TRUE if the character is wide

g_unichar_toupper ()

gunichar    g_unichar_toupper         (gunichar c);

Converts a character to uppercase.

c : | a Unicode character
Returns : | the result of converting c to uppercase. If c is not an lowercase or titlecase character, or has no upper case equivalent c is returned unchanged.

g_unichar_tolower ()

gunichar    g_unichar_tolower        (gunichar c);

Converts a character to lower case.

c : | a Unicode character.
Returns : | the result of converting c to lower case. If c is not an upper lower or titlecase character, or has no lowercase equivalent c is returned unchanged.

g_unichar_totitle ()

gunichar    g_unichar_totitle               (gunichar c);

Converts a character to the titlecase.

c : | a Unicode character
Returns : | the result of converting c to titlecase. If c is not an uppercase or lowercase character, c is returned unchanged.

g_unichar_digit_value ()

gint        g_unichar_digit_value           (gunichar c);

Determines the numeric value of a character as a decimal digit.

c : | a Unicode character
Returns : | If c is a decimal digit (according to g_unichar_isdigit()), its numeric value. Otherwise, -1.

g_unichar_xdigit_value ()

gint        g_unichar_xdigit_value         (gunichar c);

Determines the numeric value of a character as a hexadecimal digit.

c : | a Unicode character
Returns : | If c is a hex digit (according to g_unichar_isxdigit()), its numeric value. Otherwise, -1.

enum GUnicodeType

typedef enum
{
  G_UNICODE_CONTROL,
  G_UNICODE_FORMAT,
  G_UNICODE_UNASSIGNED,
  G_UNICODE_PRIVATE_USE,
  G_UNICODE_SURROGATE,
  G_UNICODE_LOWERCASE_LETTER,
  G_UNICODE_MODIFIER_LETTER,
  G_UNICODE_OTHER_LETTER,
  G_UNICODE_TITLECASE_LETTER,
  G_UNICODE_UPPERCASE_LETTER,
  G_UNICODE_COMBINING_MARK,
  G_UNICODE_ENCLOSING_MARK,
  G_UNICODE_NON_SPACING_MARK,
  G_UNICODE_DECIMAL_NUMBER,
  G_UNICODE_LETTER_NUMBER,
  G_UNICODE_OTHER_NUMBER,
  G_UNICODE_CONNECT_PUNCTUATION,
  G_UNICODE_DASH_PUNCTUATION,
  G_UNICODE_CLOSE_PUNCTUATION,
  G_UNICODE_FINAL_PUNCTUATION,
  G_UNICODE_INITIAL_PUNCTUATION,
  G_UNICODE_OTHER_PUNCTUATION,
  G_UNICODE_OPEN_PUNCTUATION,
  G_UNICODE_CURRENCY_SYMBOL,
  G_UNICODE_MODIFIER_SYMBOL,
  G_UNICODE_MATH_SYMBOL,
  G_UNICODE_OTHER_SYMBOL,
  G_UNICODE_LINE_SEPARATOR,
  G_UNICODE_PARAGRAPH_SEPARATOR,
  G_UNICODE_SPACE_SEPARATOR
} GUnicodeType;

These are the possible character classifications. See http://www.unicode.org/Public/UNIDATA/UnicodeData.txt.

g_unichar_type ()

GUnicodeType g_unichar_type              (gunichar c);

Classifies a Unicode character by type.

c : | a Unicode character
Returns : | the type of the character.

enum GUnicodeBreakType

typedef enum
{
  G_UNICODE_BREAK_MANDATORY,
  G_UNICODE_BREAK_CARRIAGE_RETURN,
  G_UNICODE_BREAK_LINE_FEED,
  G_UNICODE_BREAK_COMBINING_MARK,
  G_UNICODE_BREAK_SURROGATE,
  G_UNICODE_BREAK_ZERO_WIDTH_SPACE,
  G_UNICODE_BREAK_INSEPARABLE,
  G_UNICODE_BREAK_NON_BREAKING_GLUE,
  G_UNICODE_BREAK_CONTINGENT,
  G_UNICODE_BREAK_SPACE,
  G_UNICODE_BREAK_AFTER,
  G_UNICODE_BREAK_BEFORE,
  G_UNICODE_BREAK_BEFORE_AND_AFTER,
  G_UNICODE_BREAK_HYPHEN,
  G_UNICODE_BREAK_NON_STARTER,
  G_UNICODE_BREAK_OPEN_PUNCTUATION,
  G_UNICODE_BREAK_CLOSE_PUNCTUATION,
  G_UNICODE_BREAK_QUOTATION,
  G_UNICODE_BREAK_EXCLAMATION,
  G_UNICODE_BREAK_IDEOGRAPHIC,
  G_UNICODE_BREAK_NUMERIC,
  G_UNICODE_BREAK_INFIX_SEPARATOR,
  G_UNICODE_BREAK_SYMBOL,
  G_UNICODE_BREAK_ALPHABETIC,
  G_UNICODE_BREAK_PREFIX,
  G_UNICODE_BREAK_POSTFIX,
  G_UNICODE_BREAK_COMPLEX_CONTEXT,
  G_UNICODE_BREAK_AMBIGUOUS,
  G_UNICODE_BREAK_UNKNOWN,
  G_UNICODE_BREAK_NEXT_LINE,
  G_UNICODE_BREAK_WORD_JOINER,
  G_UNICODE_BREAK_HANGUL_L_JAMO,
  G_UNICODE_BREAK_HANGUL_V_JAMO,
  G_UNICODE_BREAK_HANGUL_T_JAMO,
  G_UNICODE_BREAK_HANGUL_LV_SYLLABLE,
  G_UNICODE_BREAK_HANGUL_LVT_SYLLABLE
} GUnicodeBreakType;

These are the possible line break classifications. GLib 2.8 supports Unicode 4.0, GLib 2.10 supports Unicode 4.1. The five Hangul types were added in Unicode 4.1, so, has been introduced in GLib 2.10. Note that new types may be added in the future. Applications should be ready to handle unknown values. They may be regarded as G_UNICODE_BREAK_UNKNOWN See http://www.unicode.org/unicode/reports/tr14/.

g_unichar_break_type ()

GUnicodeBreakType g_unichar_break_type      (gunichar c);

Determines the break type of c. c should be a Unicode character (to derive a character from UTF-8 encoded text, use g_utf8_get_char()). The break type is used to find word and line breaks ("text boundaries"), Pango implements the Unicode boundary resolution algorithms and normally uses a function such as pango_break() instead of caring about break types.

c : | a Unicode character
Returns : | the break type of c

g_unicode_canonical_ordering ()

void        g_unicode_canonical_ordering    (gunichar *string, gsize len);

Computes the canonical ordering of a string in-place. This rearranges decomposed characters in the string according to their combining classes. See the Unicode manual for more information.

string : | a UCS-4 encoded string.
len : | the maximum length of string to use.

g_unicode_canonical_decomposition ()

gunichar*   g_unicode_canonical_decomposition     (gunichar ch, gsize *result_len);

Computes the canonical decomposition of a Unicode character.

ch : | a Unicode character.
result_len : | location to store the length of the return value.
Returns : | a newly allocated string of Unicode characters. result_len is set to the resulting length of the string.

g_unichar_get_mirror_char ()

gboolean    g_unichar_get_mirror_char            (gunichar ch, gunichar *mirrored_ch);

In Unicode, some characters are mirrored. This means that their images are mirrored horizontally in text that is laid out from right to left. For instance, "(" would become its mirror image, ")", in right-to-left text.

If ch has the Unicode mirrored property and there is another unicode character that typically has a glyph that is the mirror image of ch's glyph and mirrored_ch is set, it puts that character in the address pointed to by mirrored_ch. Otherwise the original character is put.

ch : | a unicode character
mirrored_ch : | location to store the mirrored character
Returns : | TRUE if ch has a mirrored character, FALSE otherwise

g_utf8_next_char()

#define     g_utf8_next_char(p)

Skips to the next character in a UTF-8 string. The string must be valid; this macro is as fast as possible, and has no error-checking.Use this macro to iterate over a string character by character. The macro returns the start of the next UTF-8 character. Before using this macro, use g_utf8_validate() to validate strings that may contain invalid UTF-8.

p : Pointer to the start of a valid UTF-8 character.

g_utf8_get_char ()

gunichar    g_utf8_get_char       (const gchar *p);

Converts a sequence of bytes encoded as UTF-8 to a Unicode character. If p does not point to a valid UTF-8 encoded character, results are undefined. When unsure that the bytes are complete valid Unicode characters, use g_utf8_get_char_validated() instead.

p : | a pointer to Unicode character encoded as UTF-8
Returns : | the resulting character

g_utf8_get_char_validated ()

gunichar    g_utf8_get_char_validated       (const  gchar *p, gssize max_len);

Convert a sequence of bytes encoded as UTF-8 to a Unicode character. This function checks for incomplete characters, for invalid characters such as characters that are out of the range of Unicode, and for overlong encodings of valid characters.

p : | a pointer to Unicode character encoded as UTF-8
max_len : | the maximum number of bytes to read, or -1, for no maximum.
Returns : | the resulting character. If p points to a partial sequence at the end of a string that could begin a valid character, returns (gunichar)-2; otherwise, if p does not point to a valid UTF-8 encoded Unicode character, returns (gunichar)-1.

g_utf8_offset_to_pointer ()

gchar*      g_utf8_offset_to_pointer    (const gchar *str, glong offset);

Converts from an integer character offset to a pointer to a position within the string.

Since 2.10, this function allows to pass a negative offset to step backwards. It is usually worth stepping backwards from the end instead of forwards if offset is in the last fourth of the string, since moving forward is about 3 times faster than moving backward.

str : | a UTF-8 encoded string
offset : | a character offset within str
Returns : | the resulting pointer

g_utf8_pointer_to_offset ()

glong       g_utf8_pointer_to_offset    (const gchar *str, const gchar *pos);

Converts from a pointer to position within a string to a integer character offset.

Since 2.10, this function allows pos to be before str, and returns a negative offset in this case.

str : | a UTF-8 encoded string
pos : | a pointer to a position within str
Returns : | the resulting character offset

g_utf8_prev_char ()

gchar*      g_utf8_prev_char             (const gchar *p);

Finds the previous UTF-8 character in the string before p.

p does not have to be at the beginning of a UTF-8 character. No check is made to see if the character found is actually valid other than it starts with an appropriate byte. If p might be the first character of the string, use g_utf8_find_prev_char() instead.

p : | a pointer to a position within a UTF-8 encoded string
Returns : | a pointer to the found character.

g_utf8_find_next_char ()

gchar*      g_utf8_find_next_char       (const gchar *p, const gchar *end);

Finds the start of the next UTF-8 character in the string after p.

p does not have to be at the beginning of a UTF-8 character. No check is made to see if the character found is actually valid other than it starts with an appropriate byte.

p : | a pointer to a position within a UTF-8 encoded string
end : | a pointer to the end of the string, or NULL to indicate that the string is null-terminated, in which case the returned value will be
Returns : | a pointer to the found character or NULL

g_utf8_find_prev_char ()

gchar*      g_utf8_find_prev_char       (const gchar *str, const gchar *p);

Given a position p with a UTF-8 encoded string str, find the start of the previous UTF-8 character starting before p. Returns NULL if no UTF-8 characters are present in str before p .

p does not have to be at the beginning of a UTF-8 character. No check is made to see if the character found is actually valid other than it starts with an appropriate byte.

str : | pointer to the beginning of a UTF-8 encoded string
p : | pointer to some position within str
Returns : | a pointer to the found character or NULL.

g_utf8_strlen ()

glong       g_utf8_strlen            (const gchar *p, gssize max);

Returns the length of the string in characters.

p : | pointer to the start of a UTF-8 encoded string.
max : | the maximum number of bytes to examine. If max is less than 0, then the string is assumed to be null-terminated. If max is 0, p will not be examined and may be NULL.
Returns : | the length of the string in characters

g_utf8_strncpy ()

gchar*      g_utf8_strncpy           (gchar *dest, const gchar *src, gsize n);

Like the standard C strncpy() function, but copies a given number of characters instead of a given number of bytes. The src string must be valid UTF-8 encoded text. (Use g_utf8_validate() on all text before trying to use UTF-8 utility functions with it.)

dest : | buffer to fill with characters from src
src : | UTF-8 encoded string
n : | character count
Returns : | dest

g_utf8_strchr ()

gchar*      g_utf8_strchr           (const gchar *p, gssize len, gunichar c);

Finds the leftmost occurrence of the given Unicode character in a UTF-8 encoded string, while limiting the search to len bytes. If len is -1, allow unbounded search.

p : | a null-terminated UTF-8 encoded string
len : | the maximum length of p
c : | a Unicode character
Returns : | NULL if the string does not contain the character, otherwise, a pointer to the start of the leftmost occurrence of the character in the string.

g_utf8_strrchr ()

gchar*      g_utf8_strrchr          (const gchar *p, gssize len, gunichar c);

Find the rightmost occurrence of the given Unicode character in a UTF-8 encoded string, while limiting the search to len bytes. If len is -1, allow unbounded search.

p : | a null-terminated UTF-8 encoded string
len : | the maximum length of p
c : | a Unicode character
Returns : | NULL if the string does not contain the character, otherwise, a pointer to the start of the rightmost occurrence of the character in the string.

g_utf8_strreverse ()

gchar*      g_utf8_strreverse       (const gchar *str, gssize len);

Reverses a UTF-8 string. str must be valid UTF-8 encoded text. (Use g_utf8_validate() on all text before trying to use UTF-8 utility functions with it.)

Note that unlike g_strreverse(), this function returns newly-allocated memory, which should be freed with g_free() when no longer needed.

str : | a UTF-8 encoded string
len : | the maximum length of str to use. If len < 0, then the string is null-terminated.
Returns : | a newly-allocated string which is the reverse of str.

g_utf8_validate ()

gboolean    g_utf8_validate           (const gchar *str, gssize max_len, const gchar **end);

Validates UTF-8 encoded text. str is the text to validate; if str is null-terminated, then max_len can be -1, otherwise max_len should be the number of bytes to validate. If end is non-NULL, then the end of the valid range will be stored there (i.e. the start of the first invalid character if some bytes were invalid, or the end of the text being validated otherwise).

Note that g_utf8_validate() returns FALSE if max_len is positive and NULL is met before max_len bytes have been read.

Returns TRUE if all of str was valid. Many GLib and GTK+ routines require valid UTF-8 as input; so data read from a file or the network should be checked with g_utf8_validate() before doing anything else with it.

str : | a pointer to character data
max_len : | max bytes to validate, or -1 to go until NULL
end : | return location for end of valid data
Returns : | TRUE if the text was valid UTF-8

g_utf8_strup ()

gchar*      g_utf8_strup              (const gchar *str, gssize len);

Converts all Unicode characters in the string that have a case to uppercase. The exact manner that this is done depends on the current locale, and may result in the number of characters in the string increasing. (For instance, the German ess-zet will be changed to SS.)

str : | a UTF-8 encoded string
len : | length of str, in bytes, or -1 if str is null-terminated.
Returns : | a newly allocated string, with all characters converted to uppercase.

g_utf8_strdown ()

gchar*      g_utf8_strdown           (const gchar *str, gssize len);

Converts all Unicode characters in the string that have a case to lowercase. The exact manner that this is done depends on the current locale, and may result in the number of characters in the string changing.

str : | a UTF-8 encoded string
len : | length of str, in bytes, or -1 if str is null-terminated.
Returns : | a newly allocated string, with all characters converted to lowercase.

g_utf8_casefold ()

gchar*      g_utf8_casefold          (const gchar *str, gssize len);

Converts a string into a form that is independent of case. The result will not correspond to any particular case, but can be compared for equality or ordered with the results of calling g_utf8_casefold() on other strings.

Note that calling g_utf8_casefold() followed by g_utf8_collate() is only an approximation to the correct linguistic case insensitive ordering, though it is a fairly good one. Getting this exactly right would require a more sophisticated collation function that takes case sensitivity into account. GLib does not currently provide such a function.

str : | a UTF-8 encoded string
len : | length of str, in bytes, or -1 if str is null-terminated.
Returns : | a newly allocated string, that is a case independent form of str.

g_utf8_normalize ()

gchar*      g_utf8_normalize         (const gchar *str, gssize len, GNormalizeMode mode);

Converts a string into canonical form, standardizing such issues as whether a character with an accent is represented as a base character and combining accent or as a single precomposed character. Call g_utf8_normalize() before comparing two Unicode strings.

The normalization mode G_NORMALIZE_DEFAULT only standardizes differences that do not affect the text content, such as the above-mentioned accent representation. G_NORMALIZE_ALL also standardizes the "compatibility" characters in Unicode, such as SUPERSCRIPT THREE to the standard forms (in this case DIGIT THREE). Formatting information may be lost but for most text operations such characters should be considered the same. For example, g_utf8_collate() normalizes with G_NORMALIZE_ALL as its first step.

G_NORMALIZE_DEFAULT_COMPOSE and G_NORMALIZE_ALL_COMPOSE are like G_NORMALIZE_DEFAULT and G_NORMALIZE_ALL, but returned a result with composed forms rather than a maximally decomposed form. This is often useful to convert the string to a legacy encoding or pass it to a system with less capable Unicode handling.

str : | a UTF-8 encoded string.
len : | length of str, in bytes, or -1 if str is null-terminated.
mode : | the type of normalization to perform.
Returns : | a newly allocated string, that is the normalized form of str.

enum GNormalizeMode

typedef enum {
  G_NORMALIZE_DEFAULT,
  G_NORMALIZE_NFD = G_NORMALIZE_DEFAULT,
  G_NORMALIZE_DEFAULT_COMPOSE,
  G_NORMALIZE_NFC = G_NORMALIZE_DEFAULT_COMPOSE,
  G_NORMALIZE_ALL,
  G_NORMALIZE_NFKD = G_NORMALIZE_ALL,
  G_NORMALIZE_ALL_COMPOSE,
  G_NORMALIZE_NFKC = G_NORMALIZE_ALL_COMPOSE
} GNormalizeMode;

Defines how a Unicode string is transformed in a canonical form, standardizing such issues as whether a character with an accent is represented as a base character and combining accent or as a single precomposed character. Unicode strings should generally be normalized before comparing them.

G_NORMALIZE_DEFAULT | standardize differences that do not affect the text content, such as the above-mentioned accent representation.
G_NORMALIZE_NFD | another name for G_NORMALIZE_DEFAULT.
G_NORMALIZE_DEFAULT_COMPOSE | like G_NORMALIZE_DEFAULT, but with composed forms rather than a maximally decomposed form.
G_NORMALIZE_NFC | another name for G_NORMALIZE_DEFAULT_COMPOSE.
G_NORMALIZE_ALL | beyond G_NORMALIZE_DEFAULT also standardize the "compatibility" characters in Unicode, such as SUPERSCRIPT THREE to the standard forms (in this case DIGIT THREE). Formatting information may be lost but for most text operations such characters should be considered the same.
G_NORMALIZE_NFKD | another name for G_NORMALIZE_ALL.
G_NORMALIZE_ALL_COMPOSE | like G_NORMALIZE_ALL, but with composed forms rather than a maximally decomposed form.
G_NORMALIZE_NFKC | another name for G_NORMALIZE_ALL_COMPOSE.

g_utf8_collate ()

gint        g_utf8_collate        (const gchar *str1, const gchar *str2);

Compares two strings for ordering using the linguistically correct rules for the current locale. When sorting a large number of strings, it will be significantly faster to obtain collation keys with g_utf8_collate_key() and compare the keys with strcmp() when sorting instead of sorting the original strings.

str1 : | a UTF-8 encoded string
str2 : | a UTF-8 encoded string
Returns : | < 0 if str1 compares before str2, 0 if they compare equal, > 0 if str1 compares after str2.

g_utf8_collate_key ()

gchar*      g_utf8_collate_key    (const gchar *str, gssize len);

Converts a string into a collation key that can be compared with other collation keys produced by the same function using strcmp(). The results of comparing the collation keys of two strings with strcmp() will always be the same as comparing the two original keys with g_utf8_collate().

str : | a UTF-8 encoded string.
len : | length of str, in bytes, or -1 if str is null-terminated.
Returns : | a newly allocated string. This string should be freed with g_free() when done with it.

g_utf8_collate_key_for_filename ()

gchar*      g_utf8_collate_key_for_filename     (const gchar *str, gssize len);

Converts a string into a collation key that can be compared with other collation keys produced by the same function using strcmp().

In order to sort filenames correctly, this function treats the dot '.' as a special case. Most dictionary orderings seem to consider it insignificant, thus producing the ordering "event.c" "eventgenerator.c" "event.h" instead of "event.c" "event.h" "eventgenerator.c". Also, we would like to treat numbers intelligently so that "file1" "file10" "file5" is sorted as "file1" "file5" "file10".

str : | a UTF-8 encoded string.
len : | length of str, in bytes, or -1 if str is null-terminated.
Returns : | a newly allocated string. This string should be freed with g_free() when done with it.

g_utf8_to_utf16 ()

gunichar2*  g_utf8_to_utf16        (const gchar *str, glong len, glong *items_read, glong *items_written, GError **error);

Convert a string from UTF-8 to UTF-16. A 0 word will be added to the result after the converted text.

str : | a UTF-8 encoded string
len : | the maximum length (number of characters) of str to use. If len < 0, then the string is null-terminated.
items_read : | location to store number of bytes read, or NULL. If NULL, then G_CONVERT_ERROR_PARTIAL_INPUT will be returned in case str contains a trailing partial character. If an error occurs then the index of the invalid input is stored here.
items_written : | location to store number of gunichar2 written, or NULL. The value stored here does not include the trailing 0 word.
error : | location to store the error occurring, or NULL to ignore errors. Any of the errors in GConvertError other than G_CONVERT_ERROR_NO_CONVERSION may occur.
Returns : | a pointer to a newly allocated UTF-16 string. This value must be freed with g_free(). If an error occurs, NULL will be returned and error set.

g_utf8_to_ucs4 ()

gunichar*   g_utf8_to_ucs4         (const gchar *str, glong len, glong *items_read, glong *items_written, GError **error);

Convert a string from UTF-8 to a 32-bit fixed width representation as UCS-4. A trailing 0 will be added to the string after the converted text.

str : | a UTF-8 encoded string
len : | the maximum length (number of gunichar2) of str to use. If len < 0, then the string is null-terminated.
items_read : | location to store number of bytes read, or NULL. If NULL, then G_CONVERT_ERROR_PARTIAL_INPUT will be returned in case str contains a trailing partial character. If an error occurs then the index of the invalid input is stored here.
items_written : | location to store number of characters written or NULL. The value here stored does not include the trailing 0 character.
error : | location to store the error occurring, or NULL to ignore errors. Any of the errors in GConvertError other than G_CONVERT_ERROR_NO_CONVERSION may occur.
Returns : | a pointer to a newly allocated UCS-4 string. This value must be freed with g_free(). If an error occurs, NULL will be returned and error set.

g_utf8_to_ucs4_fast ()

gunichar*   g_utf8_to_ucs4_fast   (const gchar *str, glong len, glong *items_written);

Convert a string from UTF-8 to a 32-bit fixed width representation as UCS-4, assuming valid UTF-8 input. This function is roughly twice as fast as g_utf8_to_ucs4() but does no error checking on the input.

str : | a UTF-8 encoded string
len : | the maximum length (number of gunichar2) of str to use. If len < 0, then the string is null-terminated.
items_written : | location to store the number of characters in the result, or NULL.
Returns : | a pointer to a newly allocated UCS-4 string. This value must be freed with g_free().

g_utf16_to_ucs4 ()

gunichar*   g_utf16_to_ucs4      (const gunichar2 *str, glong len, glong *items_read, glong *items_written, GError **error);

Convert a string from UTF-16 to UCS-4. The result will be terminated with a 0 character.

str : | a UTF-16 encoded string
len : | the maximum length of str to use. If len < 0, then the string is terminated with a 0 character.
items_read : | location to store number of words read, or NULL. If NULL, then G_CONVERT_ERROR_PARTIAL_INPUT will be returned in case str contains a trailing partial character. If an error occurs then the index of the invalid input is stored here.
items_written : | location to store number of characters written, or NULL. The value stored here does not include the trailing 0 character.
error : | location to store the error occurring, or NULL to ignore errors. Any of the errors in GConvertError other than G_CONVERT_ERROR_NO_CONVERSION may occur.
Returns : | a pointer to a newly allocated UCS-4 string. This value must be freed with g_free(). If an error occurs, NULL will be returned and error set.

g_utf16_to_utf8 ()

gchar*      g_utf16_to_utf8     (const gunichar2 *str, glong len, glong *items_read, glong *items_written, GError **error);

Convert a string from UTF-16 to UTF-8. The result will be terminated with a 0 byte.

Note that the input is expected to be already in native endianness, an initial byte-order-mark character is not handled specially. g_convert() can be used to convert a byte buffer of UTF-16 data of ambiguous endianess.

str : | a UTF-16 encoded string
len : | the maximum length of str to use. If len < 0, then the string is terminated with a 0 character.
items_read : | location to store number of words read, or NULL. If NULL, then G_CONVERT_ERROR_PARTIAL_INPUT will be returned in case str contains a trailing partial character. If an error occurs then the index of the invalid input is stored here.
items_written : | location to store number of bytes written, or NULL. The value stored here does not include the trailing 0 byte.
error : | location to store the error occurring, or NULL to ignore errors. Any of the errors in GConvertError other than G_CONVERT_ERROR_NO_CONVERSION may occur.
Returns : | a pointer to a newly allocated UTF-8 string. This value must be freed with g_free(). If an error occurs, NULL will be returned and error set.

g_ucs4_to_utf16 ()

gunichar2*  g_ucs4_to_utf16    (const gunichar *str, glong len, glong *items_read, glong *items_written, GError **error);

Convert a string from UCS-4 to UTF-16. A 0 character will be added to the result after the converted text.

str : | a UCS-4 encoded string
len : | the maximum length (number of characters) of str to use. If len < 0, then the string is terminated with a 0 character.
items_read : | location to store number of bytes read, or NULL. If an error occurs then the index of the invalid input is stored here.
items_written : | location to store number of gunichar2 written, or NULL. The value stored here does not include the trailing 0 word.
error : | location to store the error occurring, or NULL to ignore errors. Any of the errors in GConvertError other than G_CONVERT_ERROR_NO_CONVERSION may occur.
Returns : | a pointer to a newly allocated UTF-16 string. This value must be freed with g_free(). If an error occurs, NULL will be returned and error set.

g_ucs4_to_utf8 ()

gchar*   g_ucs4_to_utf8       (const gunichar *str, glong len, glong *items_read, glong *items_written, GError **error);

Convert a string from a 32-bit fixed width representation as UCS-4. to UTF-8. The result will be terminated with a 0 byte.

str : | a UCS-4 encoded string
len : | the maximum length (number of characters) of str to use. If len < 0, then the string is terminated with a 0 character.
items_read : | location to store number of characters read, or NULL.
items_written : | location to store number of bytes written or NULL. The value here stored does not include the trailing 0 byte.
error : | location to store the error occurring, or NULL to ignore errors. Any of the errors in GConvertError other than G_CONVERT_ERROR_NO_CONVERSION may occur.
Returns : | a pointer to a newly allocated UTF-8 string. This value must be freed with g_free(). If an error occurs, NULL will be returned and error set. In that case, items_read will be set to the position of the first invalid input character.

g_unichar_to_utf8 ()

gint    g_unichar_to_utf8     (gunichar c, gchar *outbuf);

Converts a single character to UTF-8.

c : | a Unicode character code
outbuf : | output buffer, must have at least 6 bytes of space. If NULL, the length will be computed and returned and nothing will be written to outbuf.
Returns : | number of bytes written

See Also

g_locale_to_utf8(), g_locale_from_utf8()

Convenience functions for converting between UTF-8 and the locale encoding.

Feedback

For additional information or queries on this page send feedback

[3] surrogate pairs


GLib Utilities

String Utility Functions - various string-related functions.
Character Set Conversion - convert strings between different character sets using iconv().
Unicode Manipulation - functions operating on Unicode characters and UTF-8 strings.
Internationalization - gettext support macros.
Date and Time Functions - calendrical calculations and miscellaneous time stuff.
Random Numbers - pseudo-random number generator.
Hook Functions - support for manipulating lists of hook functions.
Miscellaneous Utility Functions - a selection of portable utility functions.
Lexical Scanner - a general purpose lexical scanner.
Automatic String Completion - support for automatic completion using a group of target strings.
Timers - keep track of elapsed time.
Spawning Processes - process launching with fork()/exec().
File Utilities - various file-related functions.
Shell-related Utilities - shell-like command line handling.
Commandline option parser - parses command line options
Glob-style pattern matching - matches strings against patterns containing '*' (wildcard) and '?' (joker).
Simple XML Subset Parser - parses a subset of XML.
Key-value file parser - parses .ini-like config files
Windows Compatibility Functions - UNIX emulation on Windows.


Version information

Name

Version Information — Variables and functions to check the GLib version.

Library

glib.lib

Synopsis

#include <glib.h>

extern  const guint glib_major_version;
extern  const guint glib_minor_version;
extern  const guint glib_micro_version;
extern  const guint glib_binary_age;
extern  const guint glib_interface_age;

const   gchar* glib_check_version      (guint required_major, guint required_minor, guint required_micro);

#define GLIB_MAJOR_VERSION
#define GLIB_MINOR_VERSION
#define GLIB_MICRO_VERSION
#define GLIB_CHECK_VERSION             (major,minor,micro)

Detailed Description

GLib provides version information, primarily useful in configure checks for builds that have a configure script. Applications will not typically use the features described here.

Details

glib_major_version

extern const guint glib_major_version;

The major version number of the GLib library. (e.g. in GLib version 1.2.5 this is 1.)

This variable is in the library, so represents the GLib library linked against. Contrast with the GLIB_MAJOR_VERSION macro, which represents the major version of the GLib headers included. In Symbian case application will have to include glib_global.h to access this variable.

glib_minor_version

extern const guint glib_minor_version;

The minor version number of the GLib library. (e.g. in GLib version 1.2.5 this is 2.)

This variable is in the library, so represents the GLib library linked against. Contrast with the GLIB_MINOR_VERSION macro, which represents the minor version of the GLib headers included. In Symbian case application will have to include glib_global.h to access this variable.

glib_micro_version

extern const guint glib_micro_version;

The micro version number of the GLib library. (e.g. in GLib version 1.2.5 this is 5.)

This variable is in the library, so represents the GLib library linked against. Contrast with the GLIB_MICRO_VERSION macro, which represents the micro version of the GLib headers included. In Symbian case application will have to include glib_global.h to access this variable.

glib_binary_age

extern const guint glib_binary_age;

This is the binary age passed to libtool. In Symbian case application will have to include glib_global.h to access this variable.

glib_interface_age

extern const guint glib_interface_age;

This is the interface age passed to libtool. If libtool means nothing, do not worry about it. In Symbian case application will have to include glib_global.h to access this variable.

glib_check_version ()

const gchar* glib_check_version        (guint required_major, guint required_minor, guint required_micro);

Checks that the GLib library in use is compatible with the given version. Generally the constants GLIB_MAJOR_VERSION, GLIB_MINOR_VERSION, GLIB_MICRO_VERSION are passed as the three arguments to this function; that produces a check that the library in use is compatible with the version of GLib the application or module was compiled against.

Compatibility is defined by two things: first the version of the running library is newer than the version required_major.required_minor.required_micro. Second the running library must be binary compatible with the version required_major.required_minor.required_micro (same major version.)

required_major : | the required major version.
required_minor : | the required minor version.
required_micro : | the required micro version.
Returns : | NULL if the GLib library is compatible with the given version, or a string describing the version mismatch. The returned string is owned by GLib and must not be modified or freed.

GLIB_MAJOR_VERSION

#define GLIB_MAJOR_VERSION 2

The major version number of the GLib library. Like glib_major_version, but from the headers used at application compile time, rather than from the library linked against at application run time.

GLIB_MINOR_VERSION

#define GLIB_MINOR_VERSION 10

The minor version number of the GLib library. Like gtk_minor_version, but from the headers used at application compile time, rather than from the library linked against at application run time.

GLIB_MICRO_VERSION

#define GLIB_MICRO_VERSION 3

The micro version number of the GLib library. Like gtk_micro_version, but from the headers used at application compile time, rather than from the library linked against at application run time.

GLIB_CHECK_VERSION()

#define     GLIB_CHECK_VERSION(major,minor,micro)

Checks the version of the GLib library. Returns TRUE if the version of the GLib header files is the same as or newer than the passed-in version.

Example 1. Checking the version of the GLib library

  if (!GLIB_CHECK_VERSION (1, 2, 0))
    g_error ("GLib version 1.2.0 or above is needed");
major : | the major version number.
minor : | the minor version number.
micro : | the micro version number.

Feedback

For additional information or queries on this page send feedback


Message Output and Debugging Functions

Name

Message Output and Debugging Functions — functions to output messages and help debug applications.

Library

glib.lib

Synopsis

#include <glib.h>

void        g_print                         (const gchar *format, ...);
GPrintFunc  g_set_print_handler             (GPrintFunc func);
void        (*GPrintFunc)                   (const gchar *string);
void        g_printerr                      (const gchar *format, ...);
GPrintFunc  g_set_printerr_handler          (GPrintFunc func);

#define     g_return_if_fail                (expr)
#define     g_return_val_if_fail            (expr,val)
#define     g_return_if_reached             ()
#define     g_return_val_if_reached         (val)
#define     g_assert                        (expr)
#define     g_assert_not_reached            ()
void        g_on_error_query                (const gchar *prg_name);
void        g_on_error_stack_trace          (const gchar *prg_name);
#define     G_BREAKPOINT                    ()

Detailed Description

These functions provide support for outputting messages.

Details

g_print ()

void        g_print        (const gchar *format, ...);

Outputs a formatted message via the print handler. The default print handler simply outputs the message to stdout.

g_print() should not be used from within libraries for debugging messages, since it may be redirected by applications to special purpose message windows or even files. Instead, libraries should use g_log(), or the convenience functions g_message(), g_warning() and g_error().

format : | the message format. See the printf() documentation.
... : | the parameters to insert into the format string.

g_set_print_handler ()

GPrintFunc  g_set_print_handler      (GPrintFunc func);

Sets the print handler. Any messages passed to g_print() will be output via the new handler.

The default handler simply outputs the message to stdout. By providing an own handler redirect the output, to a GTK+ widget or a log file for example.

func : | the new print handler.
Returns : | the old print handler.

GPrintFunc ()

void        (*GPrintFunc)    (const gchar *string);

Specifies the type of the print handler functions. These are called with the complete formatted string to output.

string : the message to be output.

g_printerr ()

void        g_printerr      (const gchar *format, ...);

Outputs a formatted message via the error message handler. The default handler simply outputs the message to stderr.

g_printerr() should not be used from within
libraries. Instead g_log() should be used, or the convenience
functions g_message(),
g_warning()
and g_error().

format : | the message format. See the printf() documentation.
... : | the parameters to insert into the format string.

g_set_printerr_handler ()

GPrintFunc  g_set_printerr_handler       (GPrintFunc func);

Sets the handler for printing error messages. Any messages passed to g_printerr() will be output via the new handler. The default handler simply outputs the message to stderr. By providing an own handler redirect the output, to a GTK+ widget or a log file for example.

func : | the new error message handler.
Returns : | the old error message handler.

g_return_if_fail()

#define     g_return_if_fail(expr)

Returns from the current function if the expression is not true.

If the expression evaluates to FALSE, a critical message is logged and the function returns. This can only be used in functions which do not return a value.

expr : the expression to check.

g_return_val_if_fail()

#define     g_return_val_if_fail(expr,val)

Returns from the current function, returning the value val, if the expression is not true. If the expression evaluates to FALSE, a critical message is logged and val is returned.

expr : | the expression to check.
val : | the value to return from the current function if the expression is not true.

g_return_if_reached()

#define     g_return_if_reached()

Logs a critical message and returns from the current function. This can only be used in functions which do not return a value.

g_return_val_if_reached()

#define     g_return_val_if_reached(val)

Logs a critical message and returns val.

val : the value to return from the current function.

g_assert()

#define     g_assert(expr)

Debugging macro to terminate the application if the assertion fails. If the assertion fails (i.e. the expression is not true), an error message is logged and the application is terminated.

The macro can be turned off in final releases of code by defining G_DISABLE_ASSERT when compiling the application.

expr : the expression to check.

g_assert_not_reached()

#define     g_assert_not_reached()

Debugging macro to terminate the application if it is ever reached. If it is reached, an error message is logged and the application is terminated.

The macro can be turned off in final releases of code by defining G_DISABLE_ASSERT when compiling the application.

g_on_error_query ()

void     g_on_error_query      (const gchar *prg_name);

Prompts the user with [E]xit, [H]alt, show [S]tack trace or [P]roceed. This function is intended to be used for debugging use only. The following example shows how it can be used together with the g_log() functions.

#include <glib.h>

static void
log_handler (const gchar *log_domain, 3.GLogLevelFlags log_level, const gchar *message, gpointer user_data)
{

   g_log_default_handler (log_domain, log_level, message, user_data);

   g_on_error_query (MY_PROGRAM_NAME);
}

int main (int argc, char *argv[])
{
  g_log_set_handler (MY_LOG_DOMAIN, G_LOG_LEVEL_WARNING | G_LOG_LEVEL_ERROR | G_LOG_LEVEL_CRITICAL, log_handler, NULL);

 /* ... */

If [E]xit is selected, the application terminates with a call to _exit(0).

If [H]alt is selected, the application enters an infinite loop. The infinite loop can only be stopped by killing the application, or by setting glib_on_error_halt to FALSE (possibly via a debugger).

If [S]tack trace is selected, g_on_error_stack_trace() is called. This invokes gdb, which attaches to the current process and shows a stack trace. The prompt is then shown again.

If [P]roceed is selected, the function returns.

This function may cause different actions on non-UNIX platforms.

prg_name : the program name, needed by gdb for the [S]tack trace option. If prg_name is NULL, g_get_prgname() is called to get the program name (which will work correctly if gdk_init() or gtk_init() has been called).

g_on_error_stack_trace ()

void      g_on_error_stack_trace      (const gchar *prg_name);

Invokes gdb, which attaches to the current process and shows a stack trace. Called by g_on_error_query() when the [S]tack trace option is selected.

This function may cause different actions on non-UNIX platforms.

prg_name : the program name, needed by gdb for the [S]tack trace option. If prg_name is NULL, g_get_prgname() is called to get the program name (which will work correctly if gdk_init() or gtk_init() has been called).

G_BREAKPOINT()

#define     G_BREAKPOINT()

Inserts a breakpoint instruction into the code (on x86 machines only).

Feedback

For additional information or queries on this page send feedback


glob

Name

glob, globfree - generates pathnames matching a pattern.

Library

libc.lib

Synopsis

#include <glob.h>

int glob(const char *pattern, int flags,int(*errfunc)(const char *epath, int eerrno),glob_t *pglob);
void globfree(glob_t *pglob);

Detailed Description

The glob() is a pathname generator function.

The structure type glob_t is defined in the header <glob.h>.

struct glob_t
{
size_t gl_pathc, /* number of paths matched by pattern */
char ** gl_pathv, /* pointer to a list of matched patterns */
size_t gl_offs /* Slots to reserve at the beginning of gl_pathv */
};

The argument pattern is a pointer to a pathname pattern to be expanded. glob() will match all accessible pathnames with the pattern and generates a list of pathnames that match. glob() requires search permission on every component of a path except the last, and read permission on each directory of any filename component of pattern that contains any of the following special characters: '*', '?', and '['.

glob() function will store the number of pathnames that matched in pglob->gl_pathc and a pointer to the matched pathnames in pglob->gl_pathv. The pathnames will be sorted in the order defined by the current setting of LC_COLLATE category.

It is the caller's responsibility to create the structure pointed to by pglob. The glob() function allocates other space as needed, including the memory pointed to by gl_pathv.

The globfree() function shall free any space associated with pglob from a previous call to glob().

Return Values

glob() returns 0 on success. The argument pglob->gl_pathc returns the number of matched pathnames and the argument pglob->gl_pathv contains a pointer to a NULL-terminated list of matched and sorted pathnames. If pglob->gl_pathc is 0, the content of pglob->gl_pathv is undefined.

If glob() terminates because of an error, it returns one of the non-zero constants defined in <glob.h>. The arguments pglob->gl_pathc and pglob->gl_pathv are set as defined above.

Feedback

For additional information or queries on this page send feedback

© 2005-2007 Nokia


GBoxed

Name

GBoxed — A mechanism to wrap opaque C structures registered by the type system.

Library

gobject.lib

Synopsis

#include <glib-object.h>

gpointer    (*GBoxedCopyFunc)               (gpointer boxed);
void        (*GBoxedFreeFunc)               (gpointer boxed);
gpointer    g_boxed_copy                    (GType boxed_type, gconstpointer src_boxed);
void        g_boxed_free                    (GType boxed_type, gpointer boxed);
GType       g_boxed_type_register_static    (const gchar *name, GBoxedCopyFunc boxed_copy, GBoxedFreeFunc boxed_free);
GType       g_pointer_type_register_static  (const gchar *name);

#define     G_TYPE_HASH_TABLE
#define     G_TYPE_DATE
#define     G_TYPE_GSTRING
#define     G_TYPE_STRV
typedef     GStrv;

Detailed Description

GBoxed is a generic wrapper mechanism for arbitrary C structures. The only thing the type system needs to know about the structures is how to copy and free them, beyond that they are treated as opaque chunks of memory.

Boxed types are useful for simple value-holder structures like rectangles or points. They can also be used for wrapping structures defined in non-GObject based libraries.

Details

GBoxedCopyFunc ()

gpointer    (*GBoxedCopyFunc)               (gpointer boxed);

This function is provided by the user and should produce a copy of the passed in boxed structure.

boxed : | The boxed structure to be copied.
Returns : | The newly created copy of the boxed structure.

GBoxedFreeFunc ()

void        (*GBoxedFreeFunc)               (gpointer boxed);

This function is provided by the user and should free the boxed structure passed.

boxed : The boxed structure to be freed.

g_boxed_copy ()

gpointer    g_boxed_copy                    (GType boxed_type, gconstpointer src_boxed);

Provide a copy of a boxed structure src_boxed which is of type boxed_type.

boxed_type : | The type of src_boxed.
src_boxed : | The boxed structure to be copied.
Returns : | The newly created copy of the boxed structure.

g_boxed_free ()

void        g_boxed_free                    (GType boxed_type, gpointer boxed);

Free the boxed structure boxed which is of type boxed_type.

boxed_type : | The type of boxed.
boxed : | The boxed structure to be freed.

g_boxed_type_register_static ()

GType      g_boxed_type_register_static    (const gchar *name, GBoxedCopyFunc boxed_copy, GBoxedFreeFunc boxed_free);

This function creates a new G_TYPE_BOXED derived type id for a new boxed type with name name. Boxed type handling functions have to be provided to copy and free opaque boxed structures of this type.

name : | Name of the new boxed type.
boxed_copy : | Boxed structure copy function.
boxed_free : | Boxed structure free function.
Returns : | New G_TYPE_BOXED derived type id for name.

g_pointer_type_register_static ()

GType       g_pointer_type_register_static  (const gchar *name);

Creates a new G_TYPE_POINTER derived type id for a new pointer type with name name.

name : | the name of the new pointer type.
Returns : | a new G_TYPE_POINTER derived type id for name.

G_TYPE_HASH_TABLE

#define	G_TYPE_HASH_TABLE	(g_hash_table_get_type ())

The GType for a boxed type holding a GHashTable reference.

G_TYPE_DATE

#define	G_TYPE_DATE	        (g_date_get_type ())

The GType for GDate.

G_TYPE_GSTRING

#define	G_TYPE_GSTRING		(g_gstring_get_type ())

The GType for GString.

G_TYPE_STRV

#define	G_TYPE_STRV	        (g_strv_get_type ())

The GType for a boxed type holding a NULL-terminated array of strings.

The code fragments in the following example show the use of a property of type G_TYPE_STRV with g_object_class_install_property(), g_object_set() and g_object_get().

g_object_class_install_property (object_class,
PROP_AUTHORS,
g_param_spec_boxed ("authors", _("Authors"), _("List of authors"), G_TYPE_STRV, G_PARAM_READWRITE));

gchar *authors[] = { "Owen", "Tim", NULL };
g_object_set (obj, "authors", authors, NULL);

gchar *writers[];
g_object_get (obj, "authors", &writers, NULL);
/* do something with writers */
g_strfreev (writers);

GStrv

typedef gchar** GStrv;

A C representable type name for G_TYPE_STRV.

See Also

GParamSpecBoxed, g_param_spec_boxed( ).

Feedback

For additional information or queries on this page send feedback


Closures

Name

Closures — Functions as first-class objects.

Library

gobject.lib

Synopsis

#include <glib-object.h>

#define     G_CLOSURE_NEEDS_MARSHAL         (closure)
#define     G_CLOSURE_N_NOTIFIERS           (cl)
#define     G_CCLOSURE_SWAP_DATA            (cclosure)
#define     G_CALLBACK                      (f)
void        (*GCallback)                    (void);
            GClosure;
#define     G_TYPE_CLOSURE                   GCClosure;
void        (*GClosureMarshal)              (GClosure *closure, GValue *return_value, guint n_param_values,
                                             const GValue *param_values, gpointer invocation_hint, gpointer marshal_data);
void        (*GClosureNotify)               (gpointer data, GClosure *closure);
GClosure*   g_cclosure_new                  (GCallback callback_func, gpointer user_data, GClosureNotify destroy_data);
GClosure*   g_cclosure_new_swap             (GCallback callback_func, gpointer user_data, GClosureNotify destroy_data);
GClosure*   g_cclosure_new_object           (GCallback callback_func, GObject *object);
GClosure*   g_cclosure_new_object_swap      (GCallback callback_func, GObject *object);
GClosure*   g_closure_new_object            (guint sizeof_closure, GObject *object);
GClosure*   g_closure_ref                   (GClosure *closure);
void        g_closure_sink                  (GClosure *closure);
void        g_closure_unref                 (GClosure *closure);
void        g_closure_invoke                (GClosure *closure, GValue *return_value, guint n_param_values,
                                             const GValue *param_values, gpointer invocation_hint);
void        g_closure_invalidate            (GClosure *closure);
void        g_closure_add_finalize_notifier (GClosure *closure, gpointer notify_data, GClosureNotify notify_func);

void        g_closure_add_invalidate_notifier    (GClosure *closure, gpointer notify_data, GClosureNotify notify_func);
void        g_closure_remove_finalize_notifier   (GClosure *closure, gpointer notify_data, GClosureNotify notify_func);
void        g_closure_remove_invalidate_notifier (GClosure *closure, gpointer notify_data, GClosureNotify notify_func);
GClosure*   g_closure_new_simple                 (guint sizeof_closure, gpointer data);
void        g_closure_set_marshal                (GClosure *closure, GClosureMarshal marshal);
void        g_closure_add_marshal_guards         (GClosure *closure, gpointer pre_marshal_data, ClosureNotify pre_marshal_notify,
                                                  gpointer post_marshal_data, GClosureNotify post_marshal_notify);
void        g_closure_set_meta_marshal           (GClosure *closure, gpointer marshal_data, GClosureMarshal meta_marshal);
void        g_source_set_closure                 (GSource *source, GClosure *closure);
#define     G_TYPE_IO_CHANNEL
#define     G_TYPE_IO_CONDITION

void        g_cclosure_marshal_VOID__VOID        (GClosure *closure, GValue *return_value, guint n_param_values,
                                                  const GValue *param_values, gpointer invocation_hint, gpointer marshal_data);
void        g_cclosure_marshal_VOID__BOOLEAN     (GClosure *closure, GValue *return_value, guint n_param_values,
                                                  const GValue *param_values, gpointer invocation_hint, gpointer marshal_data);
void        g_cclosure_marshal_VOID__CHAR        (GClosure *closure, GValue *return_value, guint n_param_values,
                                                  const GValue *param_values, gpointer invocation_hint, gpointer marshal_data);
void        g_cclosure_marshal_VOID__UCHAR       (GClosure *closure, GValue *return_value, guint n_param_values,
                                                  const GValue *param_values, gpointer invocation_hint, gpointer marshal_data);
void        g_cclosure_marshal_VOID__INT         (GClosure *closure, GValue *return_value, guint n_param_values,
                                                  const GValue *param_values, gpointer invocation_hint, gpointer marshal_data);
void        g_cclosure_marshal_VOID__UINT        (GClosure *closure, GValue *return_value, guint n_param_values,
                                                  const GValue *param_values, gpointer invocation_hint, gpointer marshal_data);
void        g_cclosure_marshal_VOID__LONG        (GClosure *closure, GValue *return_value, guint n_param_values,
                                                  const GValue *param_values, gpointer invocation_hint, gpointer marshal_data);
void        g_cclosure_marshal_VOID__ULONG       (GClosure *closure, GValue *return_value, guint n_param_values,
                                                  const GValue *param_values, gpointer invocation_hint, gpointer marshal_data);
void        g_cclosure_marshal_VOID__ENUM        (GClosure *closure, GValue *return_value, guint n_param_values,
                                                  const GValue *param_values, gpointer invocation_hint, gpointer marshal_data);
void        g_cclosure_marshal_VOID__FLAGS       (GClosure *closure, GValue *return_value, guint n_param_values,
                                                  const GValue *param_values, gpointer invocation_hint, gpointer marshal_data);
void        g_cclosure_marshal_VOID__FLOAT       (GClosure *closure, GValue *return_value, guint n_param_values,
                                                  const GValue *param_values, gpointer invocation_hint, gpointer marshal_data);
void        g_cclosure_marshal_VOID__DOUBLE      (GClosure *closure, GValue *return_value, guint n_param_values,
                                                  const GValue *param_values, gpointer invocation_hint, gpointer marshal_data);
void        g_cclosure_marshal_VOID__STRING      (GClosure *closure, GValue *return_value, guint n_param_values,
                                                  const GValue *param_values, gpointer invocation_hint, gpointer marshal_data);
void        g_cclosure_marshal_VOID__PARAM       (GClosure *closure, GValue *return_value, guint n_param_values,
                                                  const GValue *param_values, gpointer invocation_hint, gpointer marshal_data);
void        g_cclosure_marshal_VOID__BOXED       (GClosure *closure, GValue *return_value, guint n_param_values,
                                                  const GValue *param_values, gpointer invocation_hint, gpointer marshal_data);
void        g_cclosure_marshal_VOID__POINTER     (GClosure *closure, GValue *return_value, guint n_param_values,
                                                  const GValue *param_values, gpointer invocation_hint, gpointer marshal_data);
void        g_cclosure_marshal_VOID__OBJECT      (GClosure *closure, GValue *return_value, guint n_param_values,
                                                  const GValue *param_values, gpointer invocation_hint, gpointer marshal_data);
void        g_cclosure_marshal_STRING__OBJECT_POINTER (GClosure *closure, GValue *return_value, guint n_param_values,
                                                        const GValue *param_values, gpointer invocation_hint, gpointer marshal_data);
void        g_cclosure_marshal_VOID__UINT_POINTER     (GClosure *closure, GValue *return_value, guint n_param_values,
                                                       const GValue *param_values, gpointer invocation_hint, gpointer marshal_data);
void        g_cclosure_marshal_BOOLEAN__FLAGS   (GClosure *closure, GValue *return_value, guint n_param_values,
                                                 const GValue *param_values, gpointer invocation_hint, gpointer marshal_data);
#define     g_cclosure_marshal_BOOL__FLAGS

Detailed Description

A GClosure represents a callback supplied by the programmer. It will generally comprise a function of some kind and a marshaller used to call it. It is the reponsibility of the marshaller to convert the arguments for the invocation from GValues into a suitable form, perform the callback on the converted arguments, and transform the return value back into a GValue.

In the case of C programs, a closure usually just holds a pointer to a function and maybe a data argument, and the marshaller converts between GValue and native C types. The GObject library provides the GCClosure type for this purpose. Bindings for other languages need marshallers which convert between GValues and suitable representations in the runtime of the language in order to use functions written in that languages as callbacks.

Within GObject, closures play an important role in the implementation of signals. When a signal is registered, the c_marshaller argument to g_signal_new() specifies the default C marshaller for any closure which is connected to this signal. GObject provides a number of C marshallers for this purpose, see the g_cclosure_marshal_*() functions. Additional C marshallers can be generated with the glib-genmarshal utility. Closures can be explicitly connected to signals with g_signal_connect_closure(), but it usually more convenient to let GObject create a closure automatically by using one of the g_signal_connect_*() functions which take a callback function/user data pair.

Using closures has a number of important advantages over a simple callback function/data pointer combination:

  • Closures allow the callee to get the types of the callback parameters, which means that language bindings don't have to write individual glue for each callback type.

  • The reference counting of GClosure makes it easy to handle reentrancy right; if a callback is removed while it is being invoked, the closure and it's parameters won't be freed until the invocation finishes.

  • g_closure_invalidate() and invalidation notifiers allow callbacks to be automatically removed when the objects they point to go away.

Details

G_CLOSURE_NEEDS_MARSHAL()

#define	G_CLOSURE_NEEDS_MARSHAL(closure) (((GClosure*) (closure))->marshal == NULL)

Returns TRUE if a GClosureMarshal marshaller has not yet been set on closure. See g_closure_set_marshal().

closure : a GClosure

G_CLOSURE_N_NOTIFIERS()

#define     G_CLOSURE_N_NOTIFIERS(cl)

Returns the total number of notifiers connected with the closure cl. The count includes the meta marshaller, the finalize and invalidate notifiers and the marshal guards. Note that each guard counts as two notifiers. See g_closure_set_meta_marshal(), g_closure_add_finalize_notifier(), g_closure_add_invalidate_notifier() and g_closure_add_marshal_guards().

cl : a GClosure

G_CCLOSURE_SWAP_DATA()

#define	G_CCLOSURE_SWAP_DATA(cclosure)	 (((GClosure*) (closure))->derivative_flag)

Returns whether the user data of the GCClosure should be passed as the first parameter to the callback. See g_cclosure_new_swap().

cclosure : a GCClosure

G_CALLBACK()

#define	G_CALLBACK(f)			 ((GCallback) (f))

Casts a function pointer to a GCallback.

f : a function pointer.

GCallback ()

void        (*GCallback)                (void);

The type used for callback functions in structure definitions and function signatures. This doesn't mean that all callback functions must take no parameters and return void. The required signature of a callback function is determined by the context in which is used (e.g. the signal to which it is connected). Use G_CALLBACK() to cast the callback function to a GCallback.

GClosure

typedef struct {
  volatile       	guint	 in_marshal : 1;
  volatile       	guint	 is_invalid : 1;
} GClosure;

A GClosure represents a callback supplied by the programmer.

volatile guint in_marshal : 1; | Indicates whether the closure is currently being invoked with g_closure_invoke()
volatile guint is_invalid : 1; | Indicates whether the closure has been invalidated by g_closure_invalidate()

G_TYPE_CLOSURE

#define	G_TYPE_CLOSURE		(g_closure_get_type ())

The GType for GClosure.

GCClosure

typedef struct {
  GClosure	closure;
  gpointer	callback;
} GCClosure;

A GCClosure is a specialization of GClosure for C function callbacks.

GClosure closure; | the GClosure
gpointer callback; | the callback function

GClosureMarshal ()

void        (*GClosureMarshal)              (GClosure *closure, GValue *return_value, guint n_param_values,
                                             const GValue *param_values, gpointer invocation_hint, gpointer marshal_data);

The type used for marshaller functions.

closure : | the GClosure to which the marshaller belongs
return_value : | a GValue to store the return value. May be NULL if the callback of closure doesn't return a value.
n_param_values : | the length of the param_values array
param_values : | an array of GValues holding the arguments on which to invoke the callback of closure
invocation_hint : | the invocation hint given as the the last argument to g_closure_invoke()
marshal_data : | additional data specified when registering the marshaller, see g_closure_set_marshal() and g_closure_set_meta_marshal()

GClosureNotify ()

void        (*GClosureNotify)               (gpointer data, GClosure *closure);

The type used for the various notification callbacks which can be registered on closures.

data : | data specified when registering the notification callback
closure : | the GClosure on which the notification is emitted

g_cclosure_new ()

GClosure*   g_cclosure_new                (GCallback callback_func, gpointer user_data, GClosureNotify destroy_data);

Creates a new closure which invokes callback_func with user_data as the last parameter.

callback_func : | the function to invoke
user_data : | user data to pass to callback_func
destroy_data : | destroy notify to be called when user_data is no longer used
Returns : | a new GCClosure

g_cclosure_new_swap ()

GClosure*   g_cclosure_new_swap             (GCallback callback_func, gpointer user_data, GClosureNotify destroy_data);

Creates a new closure which invokes callback_func with user_data as the first parameter.

callback_func : | the function to invoke
user_data : | user data to pass to callback_func
destroy_data : | destroy notify to be called when user_data is no longer used
Returns : | a new GCClosure

g_cclosure_new_object ()

GClosure*   g_cclosure_new_object           (GCallback callback_func, GObject *object);

A variant of g_cclosure_new() which uses object as user_data and calls g_object_watch_closure() on object and the created closure. This function is useful when there is a callback closely associated with a GObject, and want the callback to no longer run after the object is freed.

callback_func : | the function to invoke
object : | a GObject pointer to pass to callback_func
Returns : | a new GCClosure

g_cclosure_new_object_swap ()

GClosure*   g_cclosure_new_object_swap      (GCallback callback_func, GObject *object);

A variant of g_cclosure_new_swap() which uses object as user_data and calls g_object_watch_closure() on object and the created closure. This function is useful when there is a callback closely associated with a GObject, and want the callback to no longer run after the object is freed.

callback_func : | the function to invoke
object : | a GObject pointer to pass to callback_func
Returns : | a new GCClosure

g_closure_new_object ()

GClosure*   g_closure_new_object            (guint sizeof_closure, GObject *object);

A variant of g_closure_new_simple() which stores object in the data field of the closure and calls g_object_watch_closure() on object and the created closure. This function is mainly useful when implementing new types of closures.

sizeof_closure : | the size of the structure to allocate, must be at least sizeof (GClosure)
object : | a GObject pointer to store in the data field of the newly allocated GClosure
Returns : | a newly allocated GClosure

g_closure_ref ()

GClosure*   g_closure_ref                   (GClosure *closure);

Increments the reference count on a closure to force it staying alive while the caller holds a pointer to it.

closure : | GClosure to increment the reference count on
Returns : | The closure passed in, for convenience

g_closure_sink ()

void        g_closure_sink                  (GClosure *closure);

Takes over the initial ownership of a closure. Each closure is initially created in afloating state, which means that the initial reference count is not owned by any caller. g_closure_sink() checks to see if the object is still floating, and if so, unsets the floating state and decreases the reference count. If the closure is not floating, g_closure_sink() does nothing. The reason for the existance of the floating state is to prevent cumbersome code sequences like:

closure = g_cclosure_new (cb_func, cb_data);
g_source_set_closure (source, closure);
g_closure_unref (closure); /* XXX GObject doesn't really need this */

Because g_source_set_closure() (and similar functions) take ownership of the initial reference count, if it is unowned, we instead can write:

g_source_set_closure (source, g_cclosure_new (cb_func, cb_data));

Generally, this function is used together with g_closure_ref(). Ane example of storing a closure for later notification looks like:

static GClosure *notify_closure = NULL;
void
foo_notify_set_closure (GClosure *closure)
{
  if (notify_closure)
    g_closure_unref (notify_closure);
  notify_closure = closure;
  if (notify_closure)
    {
      g_closure_ref (notify_closure);
      g_closure_sink (notify_closure);
    }
}

Because g_closure_sink() may decrement the reference count of a closure (if it hasn't been called on closure yet) just like g_closure_unref(), g_closure_ref() should be called prior to this function.

closure : GClosure to decrement the initial reference count on, if it's still being held

g_closure_unref ()

void        g_closure_unref          (GClosure *closure);

Decrements the reference count of a closure after it was previously incremented by the same caller. If no other callers are using the closure, then the closure will be destroyed and freed.

closure : GClosure to decrement the reference count on

g_closure_invoke ()

void        g_closure_invoke        (GClosure *closure, GValue *return_value, guint n_param_values, const GValue *param_values,
                                     gpointer invocation_hint);

Invokes the closure, i.e. executes the callback represented by the closure.

closure : | a GClosure
return_value : | a GValue to store the return value. May be NULL if the callback of closure doesn't return a value.
n_param_values : | the length of the param_values array
param_values : | an array of GValues holding the arguments on which to invoke the callback of closure
invocation_hint : | a context-dependent invocation hint

g_closure_invalidate ()

void        g_closure_invalidate        (GClosure *closure);

Sets a flag on the closure to indicate that it is calling environment has become invalid, and thus causes any future invocations of g_closure_invoke() on this closure to be ignored. Also, invalidation notifiers installed on the closure will be called at this point. Note that unless a reference to the closure is held, the invalidation notifiers may unref the closure and cause it to be destroyed, so to access the closure after calling g_closure_invalidate(), make sure that the function g_closure_ref() was called previously.

Note that g_closure_invalidate() will also be called when the reference count of a closure drops to zero (unless it has already been invalidated before).

closure : GClosure to invalidate

g_closure_add_finalize_notifier ()

void     g_closure_add_finalize_notifier     (GClosure *closure, gpointer notify_data, GClosureNotify notify_func);

Registers a finalization notifier which will be called when the reference count of closure goes down to 0. Multiple finalization notifiers on a single closure are invoked in unspecified order. If a single call to g_closure_unref() results in the closure being both invalidated and finalized, then the invalidate notifiers will be run before the finalize notifiers.

closure : | a GClosure
notify_data : | data to pass to notify_func
notify_func : | the callback function to register

g_closure_add_invalidate_notifier ()

void    g_closure_add_invalidate_notifier    (GClosure *closure, gpointer notify_data, GClosureNotify notify_func);

Registers an invalidation notifier which will be called when the closure is invalidated with g_closure_invalidate(). Invalidation notifiers are invoked before finalization notifiers, in an unspecified order.

closure : | a GClosure
notify_data : | data to pass to notify_func
notify_func : | the callback function to register

g_closure_remove_finalize_notifier ()

void      g_closure_remove_finalize_notifier    (GClosure *closure, gpointer notify_data, GClosureNotify notify_func);

Removes a finalization notifier. Notifiers are automatically removed after they are run.

closure : | a GClosure
notify_data : | data which was passed to g_closure_add_finalize_notifier() when registering notify_func
notify_func : | the callback function to remove

g_closure_remove_invalidate_notifier ()

void     g_closure_remove_invalidate_notifier     (GClosure *closure, gpointer notify_data, GClosureNotify notify_func);

Removes a invalidation notifier. Notifiers are automatically removed after they are run.

closure : | a GClosure
notify_data : | data which was passed to g_closure_add_invalidate_notifier() when registering notify_func
notify_func : | the callback function to remove

g_closure_new_simple ()

GClosure*   g_closure_new_simple        (guint sizeof_closure, gpointer data);

Allocates a struct of the given size and initializes the initial part as a GClosure. This function is mainly useful when implementing new types of closures.

typedef struct _MyClosure MyClosure;
struct _MyClosure
{
  GClosure closure;
  /* extra data goes here */
};

static void
my_closure_finalize (gpointer  notify_data,
                     GClosure *closure)
{
  MyClosure *my_closure = (MyClosure *)closure;

  /* free extra data here */
}

MyClosure *my_closure_new (gpointer data)
{
  GClosure *closure;
  MyClosure *my_closure;

  closure = g_closure_new_simple (sizeof (MyClosure), data);
  my_closure = (MyClosure *) closure;

  / initialize extra data here */

  g_closure_add_finalize_notifier (closure, notify_data,
                                   my_closure_finalize);
  return my_closure;
}
sizeof_closure : | the size of the structure to allocate, must be at least sizeof (GClosure)
data : | data to store in the data field of the newly allocated GClosure
Returns : | a newly allocated GClosure

g_closure_set_marshal ()

void        g_closure_set_marshal        (GClosure *closure, GClosureMarshal marshal);

Sets the marshaller of closure. The marshal_data provides a way for a meta marshaller to provide additional information to the marshaller. (See g_closure_set_meta_marshal().) For GObject's C predefined marshallers (the g_cclosure_marshal_*() functions), what it provides is a callback function to use instead of closure->callback.

closure : | a GClosure
marshal : | a GClosureMarshal function

g_closure_add_marshal_guards ()

void     g_closure_add_marshal_guards    (GClosure *closure, gpointer pre_marshal_data, GClosureNotify pre_marshal_notify,
                                          gpointer post_marshal_data, GClosureNotify post_marshal_notify);

Adds a pair of notifiers which get invoked before and after the closure callback, respectively. This is typically used to protect the extra arguments for the duration of the callback. See g_object_watch_closure() for an example of marshal guards.

closure : | a GClosure
pre_marshal_data : | data to pass to pre_marshal_notify
pre_marshal_notify : | a function to call before the closure callback
post_marshal_data : | data to pass to post_marshal_notify
post_marshal_notify : | a function to call after the closure callback

g_closure_set_meta_marshal ()

void      g_closure_set_meta_marshal      (GClosure *closure, gpointer marshal_data, GClosureMarshal meta_marshal);

Sets the meta marshaller of closure. A meta marshaller wraps closure->marshal and modifies the way it is called in some fashion. The most common use of this facility is for C callbacks. The same marshallers (generated by glib-genmarshal) are used everywhere, but the way that we get the callback function differs. In most cases we want to use closure->callback, but in other cases we want to use use some different technique to retrieve the callbakc function.

For example, class closures for signals (see g_signal_type_cclosure_new()) retrieve the callback function from a fixed offset in the class structure. The meta marshaller retrieves the right callback and passes it to the marshaller as the marshal_data argument.

closure : | a GClosure
marshal_data : | context-dependent data to pass to meta_marshal
meta_marshal : | a GClosureMarshal function

g_source_set_closure ()

void        g_source_set_closure         (GSource *source, GClosure *closure);

Sets the callback for a source as a GClosure.
If the source is not one of the standard GLib types, the closure_callback and closure_marshal fields of the GSourceFuncs structure must have been filled in with pointers to appropriate functions.

source : | the source
closure : | a GClosure

G_TYPE_IO_CHANNEL

#define G_TYPE_IO_CHANNEL (g_io_channel_get_type ())

The GType for GIOChannel.

G_TYPE_IO_CONDITION

#define G_TYPE_IO_CONDITION (g_io_condition_get_type ())

The GType for GIOCondition.

g_cclosure_marshal_VOID__VOID ()

void    g_cclosure_marshal_VOID__VOID    (GClosure *closure, GValue *return_value, guint n_param_values,
                                          const GValue *param_values, gpointer invocation_hint, gpointer marshal_data);

A marshaller for a GCClosure with a callback of type void (*callback) (gpointer instance, gpointer user_data).

closure : | the GClosure to which the marshaller belongs
return_value : | ignored
n_param_values : | 1
param_values : | a GValue array holding only the instance
invocation_hint : | the invocation hint given as the the last argument to g_closure_invoke()
marshal_data : | additional data specified when registering the marshaller

g_cclosure_marshal_VOID__BOOLEAN ()

void     g_cclosure_marshal_VOID__BOOLEAN   (GClosure *closure, GValue *return_value, guint n_param_values, const GValue *param_values,
                                             gpointer invocation_hint, gpointer marshal_data);

A marshaller for a GCClosure with a callback of type void (*callback) (gpointer instance, gboolean arg1, gpointer user_data).

closure : | the GClosure to which the marshaller belongs
return_value : | ignored
n_param_values : | 2
param_values : | a GValue array holding the instance and the gboolean parameter
invocation_hint : | the invocation hint given as the the last argument to g_closure_invoke()
marshal_data : | additional data specified when registering the marshaller

g_cclosure_marshal_VOID__CHAR ()

void        g_cclosure_marshal_VOID__CHAR   (GClosure *closure, GValue *return_value, guint n_param_values, const GValue *param_values,
                                             gpointer invocation_hint, gpointer marshal_data);

A marshaller for a GCClosure with a callback of type void (*callback) (gpointer instance, gchar arg1, gpointer user_data).

closure : | the GClosure to which the marshaller belongs
return_value : | ignored
n_param_values : | 2
param_values : | a GValue array holding the instance and the gchar parameter
invocation_hint : | the invocation hint given as the the last argument to g_closure_invoke()
marshal_data : | additional data specified when registering the marshaller

g_cclosure_marshal_VOID__UCHAR ()

void     g_cclosure_marshal_VOID__UCHAR  (GClosure *closure, GValue *return_value, guint n_param_values, const GValue *param_values,
                                          gpointer invocation_hint, gpointer marshal_data);

A marshaller for a GCClosure with a callback of type void (*callback) (gpointer instance, guchar arg1, gpointer user_data).

closure : | the GClosure to which the marshaller belongs
return_value : | ignored
n_param_values : | 2
param_values : | a GValue array holding the instance and the guchar parameter
invocation_hint : | the invocation hint given as the the last argument to g_closure_invoke()
marshal_data : | additional data specified when registering the marshaller

g_cclosure_marshal_VOID__INT ()

void    g_cclosure_marshal_VOID__INT      (GClosure *closure, GValue *return_value, guint n_param_values, const GValue *param_values,
                                           gpointer invocation_hint, gpointer marshal_data);

A marshaller for a GCClosure with a callback of type void (*callback) (gpointer instance, gint arg1, gpointer user_data).

closure : | the GClosure to which the marshaller belongs
return_value : | ignored
n_param_values : | 2
param_values : | a GValue array holding the instance and the gint parameter
invocation_hint : | the invocation hint given as the the last argument to g_closure_invoke()
marshal_data : | additional data specified when registering the marshaller

g_cclosure_marshal_VOID__UINT ()

void     g_cclosure_marshal_VOID__UINT    (GClosure *closure, GValue *return_value, guint n_param_values, const GValue *param_values,
                                           gpointer invocation_hint, gpointer marshal_data);

A marshaller for a GCClosure with a callback of type void (*callback) (gpointer instance, guint arg1, gpointer user_data).

closure : | the GClosure to which the marshaller belongs
return_value : | ignored
n_param_values : | 2
param_values : | a GValue array holding the instance and the guint parameter
invocation_hint : | the invocation hint given as the the last argument to g_closure_invoke()
marshal_data : | additional data specified when registering the marshaller

g_cclosure_marshal_VOID__LONG ()

void      g_cclosure_marshal_VOID__LONG     (GClosure *closure, GValue *return_value, guint n_param_values, const GValue *param_values,
                                             gpointer invocation_hint, gpointer marshal_data);

A marshaller for a GCClosure with a callback of type void (*callback) (gpointer instance, glong arg1, gpointer user_data).

closure : | the GClosure to which the marshaller belongs
return_value : | ignored
n_param_values : | 2
param_values : | a GValue array holding the instance and the glong parameter
invocation_hint : | the invocation hint given as the the last argument to g_closure_invoke()
marshal_data : | additional data specified when registering the marshaller

g_cclosure_marshal_VOID__ULONG ()

void     g_cclosure_marshal_VOID__ULONG    (GClosure *closure, GValue *return_value, guint n_param_values, const GValue *param_values,
                                            gpointer invocation_hint, gpointer marshal_data);

A marshaller for a GCClosure with a callback of type void (*callback) (gpointer instance, gulong arg1, gpointer user_data).

closure : | the GClosure to which the marshaller belongs
return_value : | ignored
n_param_values : | 2
param_values : | a GValue array holding the instance and the gulong parameter
invocation_hint : | the invocation hint given as the the last argument to g_closure_invoke()
marshal_data : | additional data specified when registering the marshaller

g_cclosure_marshal_VOID__ENUM ()

void      g_cclosure_marshal_VOID__ENUM     (GClosure *closure, GValue *return_value, guint n_param_values, const GValue *param_values,
                                             gpointer invocation_hint, gpointer marshal_data);

A marshaller for a GCClosure with a callback of type void (*callback) (gpointer instance, gint arg1, gpointer user_data) where the gint parameter denotes an enumeration type..

closure : | the GClosure to which the marshaller belongs
return_value : | ignored
n_param_values : | 2
param_values : | a GValue array holding the instance and the enumeration parameter
invocation_hint : | the invocation hint given as the the last argument to g_closure_invoke()
marshal_data : | additional data specified when registering the marshaller

g_cclosure_marshal_VOID__FLAGS ()

void    g_cclosure_marshal_VOID__FLAGS    (GClosure *closure, GValue *return_value, guint n_param_values, const GValue *param_values,
                                           gpointer invocation_hint, gpointer marshal_data);

A marshaller for a GCClosure with a callback of type void (*callback) (gpointer instance, gint arg1, gpointer user_data) where the gint parameter denotes a flags type denotes a flags type.

closure : | the GClosure to which the marshaller belongs
return_value : | ignored
n_param_values : | 2
param_values : | a GValue array holding the instance and the flags parameter
invocation_hint : | the invocation hint given as the the last argument to g_closure_invoke()
marshal_data : | additional data specified when registering the marshaller

g_cclosure_marshal_VOID__FLOAT ()

void     g_cclosure_marshal_VOID__FLOAT    (GClosure *closure, GValue *return_value, guint n_param_values, const GValue *param_values,
                                            gpointer invocation_hint, gpointer marshal_data);

A marshaller for a GCClosure with a callback of type void (*callback) (gpointer instance, gfloat arg1, gpointer user_data).

closure : | the GClosure to which the marshaller belongs
return_value : | ignored
n_param_values : | 2
param_values : | a GValue array holding the instance and the gfloat parameter
invocation_hint : | the invocation hint given as the the last argument to g_closure_invoke()
marshal_data : | additional data specified when registering the marshaller

g_cclosure_marshal_VOID__DOUBLE ()

void    g_cclosure_marshal_VOID__DOUBLE    (GClosure *closure, GValue *return_value, guint n_param_values, const GValue *param_values,
                                            gpointer invocation_hint, gpointer marshal_data);

A marshaller for a GCClosure with a callback of type void (*callback) (gpointer instance, gdouble arg1, gpointer user_data).

closure : | the GClosure to which the marshaller belongs
return_value : | ignored
n_param_values : | 2
param_values : | a GValue array holding the instance and the gdouble parameter
invocation_hint : | the invocation hint given as the the last argument to g_closure_invoke()
marshal_data : | additional data specified when registering the marshaller

g_cclosure_marshal_VOID__STRING ()

void    g_cclosure_marshal_VOID__STRING    (GClosure *closure, GValue *return_value, guint n_param_values, const GValue *param_values,
                                            gpointer invocation_hint, gpointer marshal_data);

A marshaller for a GCClosure with a callback of type void (*callback) (gpointer instance, const gchar *arg1, gpointer user_data).

closure : | the GClosure to which the marshaller belongs
return_value : | ignored
n_param_values : | 2
param_values : | a GValue array holding the instance and the gchar* parameter
invocation_hint : | the invocation hint given as the the last argument to g_closure_invoke()
marshal_data : | additional data specified when registering the marshaller

g_cclosure_marshal_VOID__PARAM ()

void    g_cclosure_marshal_VOID__PARAM  (GClosure *closure, GValue *return_value, guint n_param_values, const GValue *param_values,
                                         gpointer invocation_hint, gpointer marshal_data);

A marshaller for a GCClosure with a callback of type void (*callback) (gpointer instance, GParamSpec *arg1, gpointer user_data).

closure : | the GClosure to which the marshaller belongs
return_value : | ignored
n_param_values : | 2
param_values : | a GValue array holding the instance and the GParamSpec* parameter
invocation_hint : | the invocation hint given as the the last argument to g_closure_invoke()
marshal_data : | additional data specified when registering the marshaller

g_cclosure_marshal_VOID__BOXED ()

void     g_cclosure_marshal_VOID__BOXED  (GClosure *closure, GValue *return_value, guint n_param_values, const GValue *param_values,
                                             gpointer invocation_hint, gpointer marshal_data);

A marshaller for a GCClosure with a callback of type void (*callback) (gpointer instance, GBoxed *arg1, gpointer user_data).

closure : | the GClosure to which the marshaller belongs
return_value : | ignored
n_param_values : | 2
param_values : | a GValue array holding the instance and the GBoxed* parameter
invocation_hint : | the invocation hint given as the the last argument to g_closure_invoke()
marshal_data : | additional data specified when registering the marshaller

g_cclosure_marshal_VOID__POINTER ()

void     g_cclosure_marshal_VOID__POINTER   (GClosure *closure, GValue *return_value, guint n_param_values, const GValue *param_values,
                                             gpointer invocation_hint, gpointer marshal_data);

A marshaller for a GCClosure with a callback of type void (*callback) (gpointer instance, gpointer arg1, gpointer user_data).

closure : | the GClosure to which the marshaller belongs
return_value : | ignored
n_param_values : | 2
param_values : | a GValue array holding the instance and the gpointer parameter
invocation_hint : | the invocation hint given as the the last argument to g_closure_invoke()
marshal_data : | additional data specified when registering the marshaller

g_cclosure_marshal_VOID__OBJECT ()

void    g_cclosure_marshal_VOID__OBJECT    (GClosure *closure, GValue *return_value, guint n_param_values, const GValue *param_values,
                                            gpointer invocation_hint, gpointer marshal_data);

A marshaller for a GCClosure with a callback of type void (*callback) (gpointer instance, GOBject *arg1, gpointer user_data).

closure : | the GClosure to which the marshaller belongs
return_value : | ignored
n_param_values : | 2
param_values : | a GValue array holding the instance and the GObject* parameter
invocation_hint : | the invocation hint given as the the last argument to g_closure_invoke()
marshal_data : | additional data specified when registering the marshaller

g_cclosure_marshal_STRING__OBJECT_POINTER ()

void    g_cclosure_marshal_STRING__OBJECT_POINTER   (GClosure *closure, GValue *return_value, guint n_param_values, const GValue *param_values,
                                                     gpointer invocation_hint, gpointer marshal_data);

A marshaller for a GCClosure with a callback of type void (*callback) (gpointer instance, GObject *arg1, gpointer arg2, gpointer user_data).

closure : | the GClosure to which the marshaller belongs
return_value : | ignored
n_param_values : | 3
param_values : | a GValue array holding instance, arg1 and arg2
invocation_hint : | the invocation hint given as the the last argument to g_closure_invoke()
marshal_data : | additional data specified when registering the marshaller

g_cclosure_marshal_VOID__UINT_POINTER ()

void     g_cclosure_marshal_VOID__UINT_POINTER   (GClosure *closure, GValue *return_value, guint n_param_values, const GValue *param_values,
                                                  gpointer invocation_hint, gpointer marshal_data);

A marshaller for a GCClosure with a callback of type void (*callback) (gpointer instance, guint arg1, gpointer arg2, gpointer user_data).

closure : | the GClosure to which the marshaller belongs
return_value : | ignored
n_param_values : | 3
param_values : | a GValue array holding instance, arg1 and arg2
invocation_hint : | the invocation hint given as the the last argument to g_closure_invoke()
marshal_data : | additional data specified when registering the marshaller

g_cclosure_marshal_BOOLEAN__FLAGS ()

void    g_cclosure_marshal_BOOLEAN__FLAGS  (GClosure *closure, GValue *return_value, guint n_param_values, const GValue *param_values,
                                            gpointer invocation_hint, gpointer marshal_data);

A marshaller for a GCClosure with a callback of type gboolean (*callback) (gpointer instance, gint arg1, gpointer user_data) where the gint parameter denotes a flags type.

closure : | the GClosure to which the marshaller belongs
return_value : | a GValue which can store the returned gboolean
n_param_values : | 2
param_values : | a GValue array holding instance and arg1
invocation_hint : | the invocation hint given as the the last argument to g_closure_invoke()
marshal_data : | additional data specified when registering the marshaller

g_cclosure_marshal_BOOL__FLAGS

#define     g_cclosure_marshal_BOOL__FLAGS

Another name for g_cclosure_marshal_BOOLEAN__FLAGS().

Feedback

For additional information or queries on this page send feedback


Enums and Flags

Name

Enums and Flags — Enumeration and flags types.

Library

gobject.lib

Synopsis

#include <glib-object.h>

GEnumClass;
GFlagsClass;
#define     G_ENUM_CLASS_TYPE               (class)
#define     G_ENUM_CLASS_TYPE_NAME          (class)
#define     G_TYPE_IS_ENUM                  (type)
#define     G_ENUM_CLASS                    (class)
#define     G_IS_ENUM_CLASS                 (class)
#define     G_TYPE_IS_FLAGS                 (type)
#define     G_FLAGS_CLASS                   (class)
#define     G_IS_FLAGS_CLASS                (class)
#define     G_FLAGS_CLASS_TYPE              (class)
#define     G_FLAGS_CLASS_TYPE_NAME         (class)
            GEnumValue;
            GFlagsValue;
GEnumValue* g_enum_get_value                (GEnumClass *enum_class, gint value);
GEnumValue* g_enum_get_value_by_name        (GEnumClass *enum_class, const gchar *name);
GEnumValue* g_enum_get_value_by_nick        (GEnumClass *enum_class, const gchar *nick);
GFlagsValue* g_flags_get_first_value        (GFlagsClass *flags_class, guint value);
GFlagsValue* g_flags_get_value_by_name      (GFlagsClass *flags_class, const gchar *name);
GFlagsValue* g_flags_get_value_by_nick      (GFlagsClass *flags_class, const gchar *nick);
GType       g_enum_register_static          (const gchar *name, const GEnumValue *const_static_values);
GType       g_flags_register_static         (const gchar *name, const GFlagsValue *const_static_values);
void        g_enum_complete_type_info       (GType g_enum_type, GTypeInfo *info, const GEnumValue *const_values);
void        g_flags_complete_type_info      (GType g_flags_type, GTypeInfo *info, const GFlagsValue *const_values);

Detailed Description

The GLib type system provides fundamental types for enumeration and flags types. (Flags types are like enumerations,
but allow their values to be combined by bitwise or). A registered enumeration or flags type associates a name and a nickname with each allowed value, and the methods g_enum_get_value_by_name(), g_enum_get_value_by_nick(), g_flags_get_value_by_name() and g_flags_get_value_by_nick() can look up values by their name or nickname. When an enumeration or flags type is registered with the GLib type system, it can be used as value type for object properties, using g_param_spec_enum() or g_param_spec_flags().

GObject ships with a utility called glib-mkenums that can construct suitable type registration functions from C enumeration definitions.

Details

GEnumClass

typedef struct {
  GTypeClass  g_type_class;

  gint	      minimum;
  gint	      maximum;
  guint	      n_values;
  GEnumValue *values;
} GEnumClass;

The class of an enumeration type holds information about its possible values.

GTypeClass g_type_class; | the parent class
gint minimum; | the smallest possible value.
gint maximum; | the largest possible value.
guint n_values; | the number of possible values.
GEnumValue *values; | an array of GEnumValue structs describing the individual values.

GFlagsClass

typedef struct {
  GTypeClass   g_type_class;

  guint	 mask;
  guint	 n_values;
  GFlagsValue *values;
} GFlagsClass;

The class of a flags type holds information about its possible values.

GTypeClass g_type_class; | the parent class
guint mask; | a mask covering all possible values.
guint n_values; | the number of possible values.
GFlagsValue *values; | an array of GFlagsValue structs describing the individual values.

G_ENUM_CLASS_TYPE()

#define G_ENUM_CLASS_TYPE(class)       (G_TYPE_FROM_CLASS (class))

Returns the type identifier from a given GEnumClass structure.

class : a GEnumClass

G_ENUM_CLASS_TYPE_NAME()

#define G_ENUM_CLASS_TYPE_NAME(class)  (g_type_name (G_ENUM_CLASS_TYPE (class)))

Returns the static type name from a given GEnumClass structure.

class : a GEnumClass

G_TYPE_IS_ENUM()

#define G_TYPE_IS_ENUM(type)	       (G_TYPE_FUNDAMENTAL (type) == G_TYPE_ENUM)

Returns whether type "is a" G_TYPE_ENUM.

type : a GType ID.

G_ENUM_CLASS()

#define G_ENUM_CLASS(class)	       (G_TYPE_CHECK_CLASS_CAST ((class), G_TYPE_ENUM, GEnumClass))

Casts a derived GEnumClass structure into a GEnumClass structure.

class : a valid GEnumClass

G_IS_ENUM_CLASS()

#define G_IS_ENUM_CLASS(class)	       (G_TYPE_CHECK_CLASS_TYPE ((class), G_TYPE_ENUM))

Checks whether class "is a" valid GEnumClass structure of type G_TYPE_ENUM or derived.

class : a GEnumClass

G_TYPE_IS_FLAGS()

#define G_TYPE_IS_FLAGS(type)	       (G_TYPE_FUNDAMENTAL (type) == G_TYPE_FLAGS)

Returns whether type "is a" G_TYPE_FLAGS.

type : a GType ID.

G_FLAGS_CLASS()

#define G_FLAGS_CLASS(class)	       (G_TYPE_CHECK_CLASS_CAST ((class), G_TYPE_FLAGS, GFlagsClass))

Casts a derived GFlagsClass structure into a GFlagsClass structure.

class : a valid GFlagsClass

G_IS_FLAGS_CLASS()

#define G_IS_FLAGS_CLASS(class)        (G_TYPE_CHECK_CLASS_TYPE ((class), G_TYPE_FLAGS))

Checks whether class "is a" valid GFlagsClass structure of type G_TYPE_FLAGS or derived.

class : a GFlagsClass

G_FLAGS_CLASS_TYPE()

#define G_FLAGS_CLASS_TYPE(class)      (G_TYPE_FROM_CLASS (class))

Returns the type identifier from a given GFlagsClass structure.

class : a GFlagsClass

G_FLAGS_CLASS_TYPE_NAME()

#define G_FLAGS_CLASS_TYPE_NAME(class) (g_type_name (G_FLAGS_TYPE (class)))

Returns the static type name from a given GFlagsClass structure.

class : a GFlagsClass

GEnumValue

typedef struct {
  gint	 value;
  gchar *value_name;
  gchar *value_nick;
} GEnumValue;

A structure which contains a single enum value, it's name, and it's nickname.

gint value; | the enum value
gchar *value_name; | the name of the value
gchar *value_nick; | the nickname of the value

GFlagsValue

typedef struct {
  guint	 value;
  gchar *value_name;
  gchar *value_nick;
} GFlagsValue;

A structure which contains a single flags value, it's name, and it's nickname.

guint value; | the flags value
gchar *value_name; | the name of the value
gchar *value_nick; | the nickname of the value

g_enum_get_value ()

GEnumValue* g_enum_get_value                (GEnumClass *enum_class, gint value);

Returns the GEnumValue for a value.

enum_class : | a GEnumClass
value : | the value to look up
Returns : | the GEnumValue for value, or NULL if value is not a member of the enumeration

g_enum_get_value_by_name ()

GEnumValue* g_enum_get_value_by_name        (GEnumClass *enum_class, const gchar *name);

Looks up a GEnumValue by name.

enum_class : | a GEnumClass
name : | the name to look up
Returns : | the GEnumValue with name name, or NULL if the enumeration doesn' t have a member with that name

g_enum_get_value_by_nick ()

GEnumValue* g_enum_get_value_by_nick        (GEnumClass *enum_class, const gchar *nick);

Looks up a GEnumValue by nickname.

enum_class : | a GEnumClass
nick : | the nickname to look up
Returns : | the GEnumValue with nickname nick, or NULL if the enumeration doesn' t have a member with that nickname

g_flags_get_first_value ()

GFlagsValue* g_flags_get_first_value        (GFlagsClass *flags_class, guint value);

Returns the first GFlagsValue which is set in value.

flags_class : | a GFlagsClass
value : | the value
Returns : | the first GFlagsValue which is set in value, or NULL if none is set

g_flags_get_value_by_name ()

GFlagsValue* g_flags_get_value_by_name      (GFlagsClass *flags_class, const gchar *name);

Looks up a GFlagsValue by name.

flags_class : | a GFlagsClass
name : | the name to look up
Returns : | the GFlagsValue with name name, or NULL if there is no flag with that name

g_flags_get_value_by_nick ()

GFlagsValue* g_flags_get_value_by_nick      (GFlagsClass *flags_class, const gchar *nick);

Looks up a GFlagsValue by nickname.

flags_class : | a GFlagsClass
nick : | the nickname to look up
Returns : | the GFlagsValue with nickname nick, or NULL if there is no flag with that nickname

g_enum_register_static ()

GType       g_enum_register_static         (const gchar *name, const GEnumValue *const_static_values);

Registers a new static enumeration type with the name name.

It is normally more convenient to let glib-mkenums generate a my_enum_get_type() function from a usual C enumeration definition than to write one yourself using g_enum_register_static().

name : | A nul-terminated string used as the name of the new type.
const_static_values : | An array of GEnumValue structs for the possible enumeration values. The array is terminated by a struct with all members being 0.
Returns : | The new type identifier.

g_flags_register_static ()

GType       g_flags_register_static         (const gchar *name, const GFlagsValue *const_static_values);

Registers a new static flags type with the name name.

It is normally more convenient to let glib-mkenums generate a my_flags_get_type() function from a usual C enumeration definition than to write one yourself using g_flags_register_static().

name : | A nul-terminated string used as the name of the new type.
const_static_values : | An array of GFlagsValue structs for the possible flags values. The array is terminated by a struct with all members being 0.
Returns : | The new type identifier.

g_enum_complete_type_info ()

void        g_enum_complete_type_info       (GType g_enum_type, GTypeInfo *info, const GEnumValue *const_values);

This function is meant to be called from the complete_type_info() function of a GTypePlugin implementation, as in the following example:

static void
my_enum_complete_type_info (GTypePlugin  *plugin, GType  g_type, GTypeInfo  *info, GTypeValueTable *value_table)
{
  static const GEnumValue values[] = {
    { MY_ENUM_FOO, "MY_ENUM_FOO", "foo" },
    { MY_ENUM_BAR, "MY_ENUM_BAR", "bar" },
    { 0, NULL, NULL }
  };

  g_enum_complete_type_info (type, info, values);
}

g_enum_type : | the type identifier of the type being completed
info : | the GTypeInfo struct to be filled in
const_values : | An array of GEnumValue structs for the possible enumeration values. The array is terminated by a struct with all members being 0.

g_flags_complete_type_info ()

void        g_flags_complete_type_info      (GType g_flags_type, GTypeInfo *info, const GFlagsValue *const_values);

This function is meant to be called from the complete_type_info() function of a GTypePlugin implementation, see the example for g_enumeration_complete_type_info() above.

g_flags_type : | the type identifier of the type being completed
info : | the GTypeInfo struct to be filled in
const_values : | An array of GFlagsValue structs for the possible enumeration values. The array is terminated by a struct with all members being 0.

See Also

GParamSpecEnum, GParamSpecFlags, g_param_spec_enum(), g_param_spec_flags(), glib-mkenums.

Feedback

For additional information or queries on this page send feedback


Generic Values

Name

Generic Values — A polymorphic type that can hold values of any other type.

Library

gobject.lib

Synopsis

#include <glib-object.h>
#define     G_VALUE_HOLDS                   (value,type)
#define     G_VALUE_TYPE                    (value)
#define     G_VALUE_TYPE_NAME               (value)
#define     G_TYPE_IS_VALUE                 (type)
#define     G_TYPE_IS_VALUE_ABSTRACT        (type)
#define     G_IS_VALUE                      (value)
            GValue;
#define     G_TYPE_VALUE
#define     G_TYPE_VALUE_ARRAY
GValue*     g_value_init                    (GValue *value, GType g_type);
void        g_value_copy                    (const GValue *src_value, GValue *dest_value);
GValue*     g_value_reset                   (GValue *value);
void        g_value_unset                   (GValue *value);
void        g_value_set_instance            (GValue *value, gpointer instance);

gboolean    g_value_fits_pointer            (const GValue *value);
gpointer    g_value_peek_pointer            (const GValue *value);
gboolean    g_value_type_compatible         (GType src_type, GType dest_type);
gboolean    g_value_type_transformable      (GType src_type, GType dest_type);
gboolean    g_value_transform               (const GValue *src_value, GValue *dest_value);
void        (*GValueTransform)              (const GValue *src_value, GValue *dest_value);
void        g_value_register_transform_func (GType src_type, GType dest_type, GValueTransform transform_func);
gchar*      g_strdup_value_contents         (const GValue *value);

Detailed Description

The GValue structure is basically a variable container that consists of a type identifier and a specific value of that type. The type identifier within a GValue structure always determines the type of the associated value. To create a undefined GValue structure, simply create a zero-filled GValue structure. To initialize the GValue, use the g_value_init() function. A GValue cannot be used until it is initialized. The basic type operations (such as freeing and copying) are determined by the GTypeValueTable associated with the type ID stored in the GValue. Other GValue operations (such as converting values between types) are provided by this interface.

Details

G_VALUE_HOLDS()

#define G_VALUE_HOLDS(value,type)	(G_TYPE_CHECK_VALUE_TYPE ((value), (type)))

Returns TRUE if value holds (or contains) a value of type. This macro will also check for value != NULL and issue a warning if the check fails.

value : | A GValue structure.
type : | A GType value.

G_VALUE_TYPE()

#define	G_VALUE_TYPE(value)		(((GValue*) (value))->g_type)

Returns the type identifier of value.

value : A GValue structure.

G_VALUE_TYPE_NAME()

#define	G_VALUE_TYPE_NAME(value)	(g_type_name (G_VALUE_TYPE (value)))

Returns the type name of value.

value : A GValue structure.

G_TYPE_IS_VALUE()

#define	G_TYPE_IS_VALUE(type)		(g_type_check_is_value_type (type))

Returns whether the passed in type ID can be used for g_value_init(). That is, this macro checks whether this type provides an implementation of the GTypeValueTable functions required for a type to create a GValue of.

type : | A GType value.
Returns : | Whether type is suitable as a GValue type.

G_TYPE_IS_VALUE_ABSTRACT()

#define G_TYPE_IS_VALUE_ABSTRACT(type)          (g_type_test_flags ((type), G_TYPE_FLAG_VALUE_ABSTRACT))

Returns TRUE if type is an abstract value type. An abstract value type introduces a value table, but can't be used for g_value_init() and is normally used as an abstract base type for derived value types.

type : A GType value.

G_IS_VALUE()

#define	G_IS_VALUE(value)		(G_TYPE_CHECK_VALUE (value))

Returns TRUE if value is a valid and initialized GValue structure.

value : A GValue structure.

GValue

typedef struct {
} GValue;

An opaque structure used to hold different types of values. The data within the structure has protected scope: it is accessible only to functions within a GTypeValueTable structure, or implementations of the g_value_*() API. That is, code portions which implement new fundamental types. GValue users can not make any assumptions about how data is stored within the 2 element data union, and the g_type member should only be accessed through the G_VALUE_TYPE() macro.

G_TYPE_VALUE

#define	G_TYPE_VALUE		(g_value_get_type ())

Returns the type ID of the "GValue" type which is a boxed type, used to pass around pointers to GValues.

G_TYPE_VALUE_ARRAY

#define	G_TYPE_VALUE_ARRAY	(g_value_array_get_type ())

Returns the type ID of the "GValueArray" type which is a boxed type, used to pass around pointers to GValueArrays.

g_value_init ()

GValue*     g_value_init          (GValue *value, GType g_type);

Initializes value with the default value of type.

value : | A zero-filled (uninitialized) GValue structure.
g_type : | Type the GValue should hold values of.
Returns : | the GValue structure that has been passed in

g_value_copy ()

void        g_value_copy                    (const GValue *src_value, GValue *dest_value);

Copies the value of src_value into dest_value.

src_value : | An initialized GValue structure.
dest_value : | An initialized GValue structure of the same type as src_value.

g_value_reset ()

GValue*     g_value_reset                   (GValue *value);

Clears the current value in value and resets it to the default value (as if the value had just been initialized).

value : | An initialized GValue structure.
Returns : | the GValue structure that has been passed in

g_value_unset ()

void        g_value_unset                   (GValue *value);

Clears the current value in value and "unsets" the type, this releases all resources associated with this GValue. An unset value is the same as an uninitialized (zero-filled) GValue structure.

value : An initialized GValue structure.

g_value_set_instance ()

void        g_value_set_instance            (GValue *value, gpointer instance);

Sets value from an instantiatable type via the value_table's collect_value() function.

value : | An initialized GValue structure.
instance : | the instance

g_value_fits_pointer ()

gboolean    g_value_fits_pointer            (const GValue *value);

Determines if value will fit inside the size of a pointer value. This is an internal function introduced mainly for C marshallers.

value : | An initialized GValue structure.
Returns : | TRUE if value will fit inside a pointer value.

g_value_peek_pointer ()

gpointer    g_value_peek_pointer            (const GValue *value);

Returns the value contents as pointer. This function asserts that g_value_fits_pointer() returned TRUE for the passed in value. This is an internal function introduced mainly for C marshallers.

value : | An initialized GValue structure.
Returns : | TRUE if value will fit inside a pointer value.

g_value_type_compatible ()

gboolean    g_value_type_compatible         (GType src_type, GType dest_type);

Returns whether a GValue of type src_type can be copied into a GValue of type dest_type.

src_type : | source type to be copied.
dest_type : | destination type for copying.
Returns : | TRUE if g_value_copy() is possible with src_type and dest_type.

g_value_type_transformable ()

gboolean    g_value_type_transformable      (GType src_type, GType dest_type);

Checks whether g_value_transform() is able to transform values of type src_type into values of type dest_type.

src_type : | Source type.
dest_type : | Target type.
Returns : | TRUE if the transformation is possible, FALSE otherwise.

g_value_transform ()

gboolean    g_value_transform               (const GValue *src_value, GValue *dest_value);

Tries to cast the contents of src_value into a type appropriate to store in dest_value, e.g. to transform a G_TYPE_INT value into a G_TYPE_FLOAT value. Performing transformations between value types might incur precision lossage. Especially transformations into strings might reveal seemingly arbitrary results and shouldn't be relied upon for production code (such as rcfile value or object property serialization).

src_value : | Source value.
dest_value : | Target value.
Returns : | Whether a transformation rule was found and could be applied. Upon failing transformations, dest_value is left untouched.

GValueTransform ()

void        (*GValueTransform)              (const GValue *src_value, GValue *dest_value);

The type of value transformation functions which can be registered with g_value_register_transform_func().

src_value : | Source value.
dest_value : | Target value.

g_value_register_transform_func ()

void        g_value_register_transform_func  (GType src_type, GType dest_type, GValueTransform transform_func);

Registers a value transformation function for use in g_value_transform(). A previously registered transformation function for src_type and dest_type will be replaced.

src_type : | Source type.
dest_type : | Target type.
transform_func : | a function which transforms values of type src_type into value of type dest_type

g_strdup_value_contents ()

gchar*      g_strdup_value_contents         (const GValue *value);

Return a newly allocated string, which describes the contents of a GValue. The main purpose of this function is to describe GValue contents for debugging output, the way in which the contents are described may change between different GLib versions.

value : | GValue which contents are to be described.
Returns : | Newly allocated string.

See Also

The fundamental types which all support GValue operations and thus can be used as a type initializer for g_value_init() are defined by a separate interface. See the Standard Values API for details.


GParamSpec

Name

GParamSpec — Metadata for parameter specifications.

Library

gobject.lib

Synopsis

#include <glib-object.h>

#define     G_TYPE_IS_PARAM                 (type)
#define     G_PARAM_SPEC                    (pspec)
#define     G_IS_PARAM_SPEC                 (pspec)
#define     G_PARAM_SPEC_CLASS              (pclass)
#define     G_IS_PARAM_SPEC_CLASS           (pclass)
#define     G_PARAM_SPEC_GET_CLASS          (pspec)
#define     G_PARAM_SPEC_TYPE               (pspec)
#define     G_PARAM_SPEC_TYPE_NAME          (pspec)
#define     G_PARAM_SPEC_VALUE_TYPE         (pspec)
            GParamSpec;
            GParamSpecClass;
enum        GParamFlags;
#define     G_PARAM_READWRITE
#define     G_PARAM_MASK
#define     G_PARAM_USER_SHIFT
GParamSpec* g_param_spec_ref                (GParamSpec *pspec);
void        g_param_spec_unref              (GParamSpec *pspec);
void        g_param_spec_sink               (GParamSpec *pspec);
GParamSpec* g_param_spec_ref_sink           (GParamSpec *pspec);

void        g_param_value_set_default       (GParamSpec *pspec, GValue *value);
gboolean    g_param_value_defaults          (GParamSpec *pspec, GValue *value);
gboolean    g_param_value_validate          (GParamSpec *pspec, GValue *value);
gboolean    g_param_value_convert           (GParamSpec *pspec, const GValue *src_value, GValue *dest_value,
                                             gboolean strict_validation);
gint        g_param_values_cmp              (GParamSpec *pspec, const GValue *value1, const GValue *value2);
const gchar* g_param_spec_get_name          (GParamSpec *pspec);
const gchar* g_param_spec_get_nick          (GParamSpec *pspec);
const gchar* g_param_spec_get_blurb         (GParamSpec *pspec);
gpointer    g_param_spec_get_qdata          (GParamSpec *pspec, GQuark quark);
void        g_param_spec_set_qdata          (GParamSpec *pspec, GQuark quark, gpointer data);
void        g_param_spec_set_qdata_full     (GParamSpec *pspec, GQuark quark, gpointer data, GDestroyNotify destroy);
gpointer    g_param_spec_steal_qdata        (GParamSpec *pspec, GQuark quark);
GParamSpec* g_param_spec_get_redirect_target  (GParamSpec *pspec);
gpointer    g_param_spec_internal           (GType param_type, const gchar *name, const gchar *nick, const gchar *blurb,
                                             GParamFlags flags);
            GParamSpecTypeInfo;
GType       g_param_type_register_static    (const gchar *name, const GParamSpecTypeInfo *pspec_info);
            GParamSpecPool;
GParamSpecPool* g_param_spec_pool_new       (gboolean type_prefixing);
void        g_param_spec_pool_insert        (GParamSpecPool *pool, GParamSpec *pspec, GType owner_type);
void        g_param_spec_pool_remove        (GParamSpecPool *pool, GParamSpec *pspec);
GParamSpec* g_param_spec_pool_lookup        (GParamSpecPool *pool, const gchar *param_name, GType owner_type,
                                             gboolean walk_ancestors);
GParamSpec** g_param_spec_pool_list         (GParamSpecPool *pool, GType owner_type, guint *n_pspecs_p);
GList*      g_param_spec_pool_list_owned    (GParamSpecPool *pool, GType owner_type);

Detailed Description

GParamSpec is an object structure that encapsulates the metadata required to specify parameters, such as e.g. GObject properties.

Parameter names need to start with a letter (a-z or A-Z). Subsequent characters can be letters, numbers or a '-'. All other characters are replaced by a '-' during construction.

Details

G_TYPE_IS_PARAM()

#define G_TYPE_IS_PARAM(type)		(G_TYPE_FUNDAMENTAL (type) == G_TYPE_PARAM)

Returns whether type "is a" G_TYPE_PARAM.

type : a GType ID

G_PARAM_SPEC()

#define G_PARAM_SPEC(pspec)		(G_TYPE_CHECK_INSTANCE_CAST ((pspec), G_TYPE_PARAM, GParamSpec))

Casts a derived GParamSpec object (e.g. of type GParamSpecInt) into a GParamSpec object.

pspec : a valid GParamSpec

G_IS_PARAM_SPEC()

#define G_IS_PARAM_SPEC(pspec)		(G_TYPE_CHECK_INSTANCE_TYPE ((pspec), G_TYPE_PARAM))

Checks whether pspec "is a" valid GParamSpec structure of type G_TYPE_PARAM or derived.

pspec : a GParamSpec

G_PARAM_SPEC_CLASS()

#define G_PARAM_SPEC_CLASS(pclass)      (G_TYPE_CHECK_CLASS_CAST ((pclass), G_TYPE_PARAM, GParamSpecClass))

Casts a derived GParamSpecClass structure into a GParamSpecClass structure.

pclass : a valid GParamSpecClass

G_IS_PARAM_SPEC_CLASS()

#define G_IS_PARAM_SPEC_CLASS(pclass)   (G_TYPE_CHECK_CLASS_TYPE ((pclass), G_TYPE_PARAM))

Checks whether pclass "is a" valid GParamSpecClass structure of type G_TYPE_PARAM or derived.

pclass : a GParamSpecClass

G_PARAM_SPEC_GET_CLASS()

#define G_PARAM_SPEC_GET_CLASS(pspec)	(G_TYPE_INSTANCE_GET_CLASS ((pspec), G_TYPE_PARAM, GParamSpecClass))

Retrieves the GParamSpecClass of a GParamSpec.

pspec : a valid GParamSpec

G_PARAM_SPEC_TYPE()

#define G_PARAM_SPEC_TYPE(pspec)	(G_TYPE_FROM_INSTANCE (pspec))

Retrieves the GType of this pspec.

pspec : a valid GParamSpec

G_PARAM_SPEC_TYPE_NAME()

#define G_PARAM_SPEC_TYPE_NAME(pspec)	(g_type_name (G_PARAM_SPEC_TYPE (pspec)))

Retrieves the GType name of this pspec.

pspec : a valid GParamSpec

G_PARAM_SPEC_VALUE_TYPE()

#define	G_PARAM_SPEC_VALUE_TYPE(pspec)	(G_PARAM_SPEC (pspec)->value_type)

Retrieves the GType to initialize a GValue for this parameter.

pspec : a valid GParamSpec

GParamSpec

typedef struct {
  GTypeInstance  g_type_instance;

  gchar         *name;
  GParamFlags    flags;
  GType		 value_type;
  GType		 owner_type;	/* class or interface using this property */
} GParamSpec;

All fields of the GParamSpec struct are private and should not be used directly, except for the following:

GTypeInstance g_type_instance; | private GTypeInstance portion
gchar *name; | name of this parameter
GParamFlags flags; | GParamFlags flags for this parameter
GType value_type; | the GValue type for this parameter
GType owner_type; | GType type that uses (introduces) this paremeter

GParamSpecClass

typedef struct {
  GTypeClass      g_type_class;

  GType		  value_type;

  void	        (*finalize)		(GParamSpec   *pspec);

  /* GParam methods */
  void          (*value_set_default)    (GParamSpec   *pspec, GValue *value);
  gboolean      (*value_validate)       (GParamSpec   *pspec, GValue *value);
  gint          (*values_cmp)           (GParamSpec   *pspec, const GValue *value1, const GValue *value2);
} GParamSpecClass;

The class structure for the GParamSpec type. Normally, GParamSpec classes are filled by g_param_type_register_static().

GTypeClass g_type_class; | the parent class
GType value_type; | the GValue type for this parameter
finalize () | The instance finalization function (optional), should chain up to the finalize method of the parent class.
value_set_default () | Resets a value to the default value for this type (recommended, the default is g_value_reset()), see g_param_value_set_default().
value_validate () | Ensures that the contents of value comply with the specifications set out by this type (optional), see g_param_value_set_validate().
values_cmp () | Compares value1 with value2 according to this type (recommended, the default is memcmp()), see g_param_values_cmp().

enum GParamFlags

typedef enum
{
  G_PARAM_READABLE            = 1 << 0,
  G_PARAM_WRITABLE            = 1 << 1,
  G_PARAM_CONSTRUCT	      = 1 << 2,
  G_PARAM_CONSTRUCT_ONLY      = 1 << 3,
  G_PARAM_LAX_VALIDATION      = 1 << 4,
  G_PARAM_STATIC_NAME	      = 1 << 5,
#ifndef G_DISABLE_DEPRECATED
  G_PARAM_PRIVATE	      = G_PARAM_STATIC_NAME,
#endif
  G_PARAM_STATIC_NICK	      = 1 << 6,
  G_PARAM_STATIC_BLURB	      = 1 << 7
} GParamFlags;

Through the GParamFlags flag values, certain aspects of parameters can be configured.

G_PARAM_READABLE | the parameter is readable
G_PARAM_WRITABLE | the parameter is writable
G_PARAM_CONSTRUCT | the parameter will be set upon object construction
G_PARAM_CONSTRUCT_ONLY | the parameter will only be set upon object construction
G_PARAM_LAX_VALIDATION | upon parameter conversion (see g_param_value_convert()) strict validation is not required
G_PARAM_STATIC_NAME | the string used as name when constructing the parameter is guaranteed to remain valid and unmodified for the lifetime of the parameter.
G_PARAM_STATIC_BLURB | the string used as blurb when constructing the parameter is guaranteed to remain valid and unmodified for the lifetime of the parameter.

G_PARAM_READWRITE

#define	G_PARAM_READWRITE	(G_PARAM_READABLE | G_PARAM_WRITABLE)

GParamFlags value alias for G_PARAM_READABLE | G_PARAM_WRITABLE.

G_PARAM_MASK

#define	G_PARAM_MASK		(0x000000ff)

Masks containing the bits of GParamSpec flags which are reserved for GLib.

G_PARAM_USER_SHIFT

#define	G_PARAM_USER_SHIFT	(8)

Minimum shift count to be used for user defined flags, to be stored in GParamSpec flags.

g_param_spec_ref ()

GParamSpec* g_param_spec_ref                (GParamSpec *pspec);

Increments the reference count of pspec.

pspec : | a valid GParamSpec
Returns : | the GParamSpec that was passed into this function

g_param_spec_unref ()

void        g_param_spec_unref              (GParamSpec *pspec);

Decrements the reference count of a pspec.

pspec : a valid GParamSpec

g_param_spec_sink ()

void        g_param_spec_sink               (GParamSpec *pspec);

The initial reference count of a newly created GParamSpec is 1, even though no one has explicitly called g_param_spec_ref() on it yet. So the initial reference count is flagged as "floating", until someone calls g_param_spec_ref (pspec); g_param_spec_sink (pspec); in sequence on it, taking over the initial reference count (thus ending up with a pspec that has a reference count of 1 still, but is not flagged "floating" anymore).

pspec : a valid GParamSpec

g_param_spec_ref_sink ()

GParamSpec* g_param_spec_ref_sink           (GParamSpec *pspec);

Convenience function to ref and sink a GParamSpec.

pspec : | a valid GParamSpec
Returns : | the GParamSpec that was passed into this function

g_param_value_set_default ()

void        g_param_value_set_default       (GParamSpec *pspec, GValue *value);

Sets value to its default value as specified in pspec.

pspec : | a valid GParamSpec
value : | a GValue of correct type for pspec

g_param_value_defaults ()

gboolean    g_param_value_defaults          (GParamSpec *pspec, GValue *value);

Checks whether value contains the default value as specified in pspec.

pspec : | a valid GParamSpec
value : | a GValue of correct type for pspec
Returns : | whether value contains the canonical defualt for this pspec

g_param_value_validate ()

gboolean    g_param_value_validate          (GParamSpec *pspec, GValue *value);

Ensures that the contents of value comply with the specifications set out by pspec. For example, a GParamSpecInt might require that integers stored in value may not be smaller than -42 and not be greater than +42. If value contains an integer outside of this range, it is modified accordingly, so the resulting value will fit into the range -42 .. +42.

pspec : | a valid GParamSpec
value : | a GValue of correct type for pspec
Returns : | whether modifying value was necessary to ensure validity

g_param_value_convert ()

gboolean   g_param_value_convert       (GParamSpec *pspec, const GValue *src_value, GValue *dest_value,
                                        gboolean strict_validation);

Transforms src_value into dest_value if possible, and then validates dest_value, in order for it to conform to pspec. If strict_validation is TRUE this function will only succeed if the transformed dest_value complied to pspec without modifications. See also g_value_type_transformable(), g_value_transform() and g_param_value_validate().

pspec : | a valid GParamSpec
src_value : | souce GValue
dest_value : | destination GValue of correct type for pspec
strict_validation : | TRUE requires dest_value to conform to pspec without modifications
Returns : | TRUE if transformation and validation were successful, FALSE otherwise and dest_value is left untouched.

g_param_values_cmp ()

gint        g_param_values_cmp          (GParamSpec *pspec, const GValue *value1, const GValue *value2);

Compares value1 with value2 according to pspec, and return -1, 0 or +1, if value1 is found to be less than, equal to or greater than value2, respectively.

pspec : | a valid GParamSpec
value1 : | a GValue of correct type for pspec
value2 : | a GValue of correct type for pspec
Returns : | -1, 0 or +1, for a less than, equal to or greater than result

g_param_spec_get_name ()

const gchar* g_param_spec_get_name      (GParamSpec *pspec);

Returns the name of a GParamSpec.

pspec : | a valid GParamSpec
Returns : | the name of pspec.

g_param_spec_get_nick ()

const gchar* g_param_spec_get_nick          (GParamSpec *pspec);

Returns the nickname of a GParamSpec.

pspec : | a valid GParamSpec
Returns : | the nickname of pspec.

g_param_spec_get_blurb ()

const gchar* g_param_spec_get_blurb         (GParamSpec *pspec);

Returns the short description of a GParamSpec.

pspec : | a valid GParamSpec
Returns : | the short description of pspec.

g_param_spec_get_qdata ()

gpointer    g_param_spec_get_qdata          (GParamSpec *pspec, GQuark quark);

Gets back user data pointers stored via g_param_spec_set_qdata().

pspec : | a valid GParamSpec
quark : | a GQuark, naming the user data pointer
Returns : | the user data pointer set, or NULL

g_param_spec_set_qdata ()

void        g_param_spec_set_qdata          (GParamSpec *pspec, GQuark quark, gpointer data);

Sets an opaque, named pointer on a GParamSpec. The name is specified through a GQuark (retrieved e.g. via g_quark_from_static_string()), and the pointer can be gotten back from the pspec with g_param_spec_get_qdata(). Setting a previously set user data pointer, overrides (frees) the old pointer set, using NULL as pointer essentially removes the data stored.

pspec : | the GParamSpec to set store a user data pointer
quark : | a GQuark, naming the user data pointer
data : | an opaque user data pointer

g_param_spec_set_qdata_full ()

void        g_param_spec_set_qdata_full     (GParamSpec *pspec, GQuark quark, gpointer data, GDestroyNotify destroy);

This function works like g_param_spec_set_qdata(), but in addition, a void (*destroy) (gpointer) function may be specified which is called with data as argument when the pspec is finalized, or the data is being overwritten by a call to g_param_spec_set_qdata() with the same quark.

pspec : | the GParamSpec to set store a user data pointer
quark : | a GQuark, naming the user data pointer
data : | an opaque user data pointer
destroy : | function to invoke with data as argument, when data needs to be freed

g_param_spec_steal_qdata ()

gpointer    g_param_spec_steal_qdata        (GParamSpec *pspec, GQuark quark);

Gets back user data pointers stored via g_param_spec_set_qdata() and removes the data from pspec without invoking it's destroy() function (if any was set). Usually, calling this function is only required to update user data pointers with a destroy notifier.

pspec : | the GParamSpec to get a stored user data pointer from
quark : | a GQuark, naming the user data pointer
Returns : | the user data pointer set, or NULL

g_param_spec_get_redirect_target ()

GParamSpec* g_param_spec_get_redirect_target     (GParamSpec *pspec);

If the paramspec redirects operations to another paramspec, returns that paramspec. Redirect is used typically for providing a new implementation of a property in a derived type while preserving all the properties from the parent type. Redirection is established by creating a property of type GParamSpecOverride. See g_object_override_property() for an example of the use of this capability.

pspec : | a GParamSpec
Returns : | paramspec to which requests on this paramspec should be redirected, or NULL if none.

g_param_spec_internal ()

gpointer    g_param_spec_internal           (GType param_type, const gchar *name, const gchar *nick, const gchar *blurb, GParamFlags flags);

Creates a new GParamSpec instance.

A property name consists of segments consisting of ASCII letters and digits, separated by either the '-' or '_' character. The first character of a property name must be a letter. Names which violate these rules lead to undefined behaviour.

When creating and looking up a GParamSpec, either separator can be used, but they cannot be mixed. Using '-' is considerably more efficient and in fact required when using property names as detail strings for signals.

param_type : | the GType for the property; must be derived from G_TYPE_PARAM
name : | the canonical name of the property
nick : | the nickname of the property
blurb : | a short description of the property
flags : | a combination of GParamFlags
Returns : | a newly allocated GParamSpec instance

GParamSpecTypeInfo

typedef struct {
  /* type system portion */
  guint16       instance_size;                               /* obligatory */
  guint16       n_preallocs;                                 /* optional */
  void	        (*instance_init)	(GParamSpec   *pspec); /* optional */

  /* class portion */
  GType         value_type;				       /* obligatory */
  void          (*finalize)             (GParamSpec   *pspec); /* optional */
  void          (*value_set_default)    (GParamSpec   *pspec,  /* recommended */
                     GValue       *value);
  gboolean      (*value_validate)       (GParamSpec   *pspec,  /* optional */
                     GValue       *value);
  gint          (*values_cmp)           (GParamSpec   *pspec,  /* recommended */
                     const GValue *value1,
                     const GValue *value2);
} GParamSpecTypeInfo;

This structure is used to provide the type system with the information required to initialize and destruct (finalize) a parameter's class and instances thereof. The initialized structure is passed to the g_param_type_register_static() The type system will perform a deep copy of this structure, so it's memory does not need to be persistent across invocation of g_param_type_register_static().

guint16 instance_size; | Size of the instance (object) structure.
guint16 n_preallocs; | Prior to GLib 2.10, it specified the number of pre-allocated (cached) instances to reserve memory for (0 indicates no caching). Since GLib 2.10, it is ignored, since instances are allocated with the slice allocator now.
instance_init () | Location of the instance initialization function (optional).
GType value_type; | The GType of values conforming to this GParamSpec
finalize () | The instance finalization function (optional).
value_set_default () | Resets a value to the default value for pspec (recommended, the default is g_value_reset()), see g_param_value_set_default().
value_validate () | Ensures that the contents of value comply with the specifications set out by pspec (optional), see g_param_value_set_validate().
values_cmp () | Compares value1 with value2 according to pspec (recommended, the default is memcmp()), see g_param_values_cmp().

g_param_type_register_static ()

GType       g_param_type_register_static    (const gchar *name, const GParamSpecTypeInfo *pspec_info);

Registers name as the name of a new static type derived from G_TYPE_PARAM. The type system uses the information contained in the GParamSpecTypeInfo structure pointed to by info to manage the GParamSpec type and its instances.

name : | 0-terminated string used as the name of the new GParamSpec type.
pspec_info : | The GParamSpecTypeInfo for this GParamSpec type.
Returns : | The new type identifier.

GParamSpecPool

typedef struct _GParamSpecPool GParamSpecPool;

A GParamSpecPool maintains a collection of GParamSpecs which can be quickly accessed by owner and name. The implementation of the GObject property system uses such a pool to store the GParamSpecs of the properties all object types.

g_param_spec_pool_new ()

GParamSpecPool* g_param_spec_pool_new       (gboolean type_prefixing);

Creates a new GParamSpecPool.

If type_prefixing is TRUE, lookups in the newly created pool will allow to specify the owner as a colon-separated prefix of the property name, like "GtkContainer:border-width". This feature is deprecated, hence always set type_prefixing to FALSE.

type_prefixing : | Whether the pool will support type-prefixed property names.
Returns : | a newly allocated GParamSpecPool.

g_param_spec_pool_insert ()

void        g_param_spec_pool_insert        (GParamSpecPool *pool, GParamSpec *pspec, GType owner_type);

Inserts a GParamSpec in the pool.

pool : | a GParamSpecPool.
pspec : | the GParamSpec to insert
owner_type : | a GType identifying the owner of pspec

g_param_spec_pool_remove ()

void        g_param_spec_pool_remove     (GParamSpecPool *pool, GParamSpec *pspec);

Removes a GParamSpec from the pool.

pool : | a GParamSpecPool
pspec : | the GParamSpec to remove

g_param_spec_pool_lookup ()

GParamSpec* g_param_spec_pool_lookup      (GParamSpecPool *pool, const gchar *param_name, GType owner_type, gboolean walk_ancestors);

Looks up a GParamSpec in the pool.

pool : | a GParamSpecPool
param_name : | the name to look for
owner_type : | the owner to look for
walk_ancestors : | If TRUE, also try to find a GParamSpec with param_name owned by an ancestor of owner_type.
Returns : | The found GParamSpec, or NULL if no matching GParamSpec was found.

g_param_spec_pool_list ()

GParamSpec** g_param_spec_pool_list         (GParamSpecPool *pool, GType owner_type, guint *n_pspecs_p);

Gets an array of all GParamSpecs owned by owner_type in the pool.

pool : | a GParamSpecPool
owner_type : | the owner to look for
n_pspecs_p : | return location for the length of the returned array
Returns : | a newly allocated array containing pointers to all GParamSpecs owned by owner_type in the pool

g_param_spec_pool_list_owned ()

GList*    g_param_spec_pool_list_owned      (GParamSpecPool *pool, GType owner_type);

Gets an GList of all GParamSpecs owned by owner_type in the pool.

pool : | a GParamSpecPool
owner_type : | the owner to look for
Returns : | a GList of all GParamSpecs owned by owner_type in the poolGParamSpecs.

See Also

g_object_class_install_property(), g_object_set(), g_object_get(), g_object_set_property(), g_object_get_property(), g_value_register_transform_func()

Feedback

For additional information or queries on this page send feedback


Signals

Name

Signals — A means for customization of object behaviour and a general purpose notification mechanism.

Library

gobject.lib

Synopsis

#include <glib-object.h>
            GSignalInvocationHint;
gboolean    (*GSignalAccumulator)           (GSignalInvocationHint *ihint, GValue *return_accu, const GValue *handler_return,
                                             gpointer data);
typedef     GSignalCMarshaller;
gboolean    (*GSignalEmissionHook)          (GSignalInvocationHint *ihint, guint n_param_values, const GValue *param_values,
                                             gpointer data);
enum        GSignalFlags;
enum        GSignalMatchType;
            GSignalQuery;
#define     G_SIGNAL_TYPE_STATIC_SCOPE
#define     G_SIGNAL_MATCH_MASK
#define     G_SIGNAL_FLAGS_MASK
guint       g_signal_new                    (const gchar *signal_name, GType itype, GSignalFlags signal_flags,
                                             guint class_offset, GSignalAccumulator accumulator, gpointer accu_data,
                                             GSignalCMarshaller c_marshaller, GType return_type, guint n_params, ...);
guint       g_signal_newv                   (const gchar *signal_name, GType itype, GSignalFlags signal_flags,
                                             GClosure *class_closure, GSignalAccumulator accumulator, gpointer accu_data,
                                             GType return_type, GSignalCMarshaller c_marshaller, GSignalAccumulator accumulator,
                                              guint n_params, GType *param_types);
guint       g_signal_new_valist             (const gchar *signal_name, GType itype, GSignalFlags signal_flags,
                                             GClosure *class_closure, gpointer accu_data, GSignalCMarshaller c_marshaller,
                                             GType return_type, guint n_params, va_list args);
void        g_signal_query                         (guint signal_id, GSignalQuery *query);
guint       g_signal_lookup                        (const gchar *name, GType itype);
const gchar* g_signal_name                         (guint signal_id);
guint*      g_signal_list_ids                      (GType itype, guint *n_ids);
void        g_signal_emit                          (gpointer instance, guint signal_id, GQuark detail, ...);
void        g_signal_emit_by_name                  (gpointer instance, const gchar *detailed_signal, ...);
void        g_signal_emitv                         (const GValue *instance_and_params, guint signal_id, GQuark detail,
                                                    GValue *return_value);
void        g_signal_emit_valist                   (gpointer instance, guint signal_id, GQuark detail, va_list var_args);
#define     g_signal_connect                       (instance, detailed_signal, c_handler, data)
#define     g_signal_connect_after                 (instance, detailed_signal, c_handler, data)
#define     g_signal_connect_swapped               (instance, detailed_signal, c_handler, data)
gulong      g_signal_connect_object                (gpointer instance, const gchar *detailed_signal, GCallback c_handler,
                                                    gpointer gobject, GConnectFlags connect_flags);
enum        GConnectFlags;
gulong      g_signal_connect_data                  (gpointer instance, const gchar *detailed_signal, GCallback c_handler,
                                                    gpointer data, GClosureNotify destroy_data, GConnectFlags connect_flags);
gulong      g_signal_connect_closure               (gpointer instance, const gchar *detailed_signal, GClosure *closure,
                                                    gboolean after);
gulong      g_signal_connect_closure_by_id         (gpointer instance, guint signal_id, GQuark detail, GClosure *closure,
                                                    gboolean after);
void        g_signal_handler_block                 (gpointer instance, gulong handler_id);
void        g_signal_handler_unblock               (gpointer instance, gulong handler_id);
void        g_signal_handler_disconnect            (gpointer instance, gulong handler_id);
gulong      g_signal_handler_find                  (gpointer instance, GSignalMatchType mask, guint signal_id, GQuark detail,
                                                    GClosure *closure, gpointer func, gpointer data);
guint       g_signal_handlers_block_matched        (gpointer instance, GSignalMatchType mask, guint signal_id, GQuark detail,
                                                    GClosure *closure, gpointer func, gpointer data);
guint       g_signal_handlers_unblock_matched      (gpointer instance, GSignalMatchType mask, guint signal_id, GQuark detail,
                                                    GClosure *closure, gpointer func, gpointer data);
guint       g_signal_handlers_disconnect_matched   (gpointer instance, GSignalMatchType mask, guint signal_id, GQuark detail,
                                                    GClosure *closure, gpointer func, gpointer data);
gboolean    g_signal_handler_is_connected          (gpointer instance, gulong handler_id);
#define     g_signal_handlers_block_by_func        (instance, func, data)
#define     g_signal_handlers_unblock_by_func      (instance, func, data)
#define     g_signal_handlers_disconnect_by_func   (instance, func, data)
gboolean    g_signal_has_handler_pending    (gpointer instance, guint signal_id, GQuark detail, gboolean may_be_blocked);
void        g_signal_stop_emission          (gpointer instance, guint signal_id, GQuark detail);
void        g_signal_stop_emission_by_name  (gpointer instance, const gchar *detailed_signal);
void        g_signal_override_class_closure (guint signal_id, GType instance_type, GClosure *class_closure);
void        g_signal_chain_from_overridden  (const GValue *instance_and_params, GValue *return_value);
gulong      g_signal_add_emission_hook      (guint signal_id, GQuark detail, GSignalEmissionHook hook_func,
                                             gpointer hook_data, GDestroyNotify data_destroy);
void        g_signal_remove_emission_hook   (guint signal_id, gulong hook_id);
gboolean    g_signal_parse_name             (const gchar *detailed_signal, GType itype, guint *signal_id_p, GQuark *detail_p,
                                             gboolean force_detail_quark);
GSignalInvocationHint* g_signal_get_invocation_hint   (gpointer instance);
GClosure*   g_signal_type_cclosure_new                (GType itype, guint struct_offset);
gboolean    g_signal_accumulator_true_handled         (GSignalInvocationHint *ihint, GValue *return_accu,
                                                       const GValue *handler_return, gpointer dummy);

Detailed Description

The basic concept of the signal system is that of the emission of a signal. Signals are introduced per-type and are identified through strings. Signals introduced for a parent type are available in derived types as well, so basically they are a per-type facility that is inherited. A signal emission mainly involves invocation of a certain set of callbacks in precisely defined manner. There are two main categories of such callbacks, per-object [11] ones and user provided ones. The per-object callbacks are most often referred to as "object method handler" or "default (signal) handler", while user provided callbacks are usually just called "signal handler". The object method handler is provided at signal creation time (this most frequently happens at the end of an object class' creation), while user provided handlers are frequently connected and disconnected to/from a certain signal on certain object instances.

A signal emission consists of five stages, unless prematurely stopped:

1 - Invocation of the object method handler for G_SIGNAL_RUN_FIRST signals

2 - Invocation of normal user-provided signal handlers (after flag FALSE)

3 - Invocation of the object method handler for G_SIGNAL_RUN_LAST signals

4 - Invocation of user provided signal handlers, connected with an after flag of TRUE

5 - Invocation of the object method handler for G_SIGNAL_RUN_CLEANUP signals

The user-provided signal handlers are called in the order they were connected in. All handlers may prematurely stop a signal emission, and any number of handlers may be connected, disconnected, blocked or unblocked during a signal emission. There are certain criteria for skipping user handlers in stages 2 and 4 of a signal emission. First, user handlers may be blocked, blocked handlers are omitted during callback invocation, to return from the "blocked" state, a handler has to get unblocked exactly the same amount of times it has been blocked before. Second, upon emission of a G_SIGNAL_DETAILED signal, an additional "detail" argument passed in to g_signal_emit() has to match the detail argument of the signal handler currently subject to invocation. Specification of no detail argument for signal handlers (omission of the detail part of the signal specification upon connection) serves as a wildcard and matches any detail argument passed in to emission.

Details

GSignalInvocationHint

typedef struct {
  guint		signal_id;
  GQuark	detail;
  GSignalFlags	run_type;
} GSignalInvocationHint;

The GSignalInvocationHint structure is used to pass on additional information to callbacks during a signal emission.

guint signal_id; | The signal id of the signal invoking the callback
GQuark detail; | The detail passed on for this emission
GSignalFlags run_type; | The stage the signal emission is currently in, this field will contain one of G_SIGNAL_RUN_FIRST, G_SIGNAL_RUN_LAST or G_SIGNAL_RUN_CLEANUP.

GSignalAccumulator ()

gboolean    (*GSignalAccumulator)      (GSignalInvocationHint *ihint, GValue *return_accu, const GValue *handler_return,
                                        gpointer data);

The signal accumulator is a special callback function that can be used to collect return values of the various callbacks that are called during a signal emission. The signal accumulator is specified at signal creation time, if it is left NULL, no accumulation of callback return values is performed. The return value of signal emissions is then the value returned by the last callback.

ihint : | Signal invocation hint, see GSignalInvocationHint.
return_accu : | Accumulator to collect callback return values in, this is the return value of the current signal emission.
handler_return : | A GValue holding the return value of the signal handler.
data : | Callback data that was specified when creating the signal.
Returns : | The accumulator function returns whether the signal emission should be aborted. Returning FALSE means to abort the current emission and TRUE is returned for continuation.

GSignalCMarshaller

typedef GClosureMarshal			 GSignalCMarshaller;

This is the signature of marshaller functions, required to marshall arrays of parameter values to signal emissions into C language callback invocations. It is merely an alias to GClosureMarshal since the GClosure mechanism takes over responsibility of actual function invocation for the signal system.

GSignalEmissionHook ()

gboolean    (*GSignalEmissionHook)   (GSignalInvocationHint *ihint, guint n_param_values, const GValue *param_values,
                                      gpointer data);

A simple function pointer to get invoked when the signal is emitted. This allows to tie a hook to the signal type, so that it will trap all emissions of that signal, from any object.

Do not attach these to signals created with the G_SIGNAL_NO_HOOKS flag.

ihint : | Signal invocation hint, see GSignalInvocationHint.
n_param_values : | the number of parameters to the function, including the instance on which the signal was emitted.
param_values : | the instance on which the signal was emitted, followed by the parameters of the emission.
data : | user data associated with the hook.
Returns : | whether it wants to stay connected. If it returns FALSE, the signal hook is disconnected (and destroyed).

enum GSignalFlags

typedef enum
{
  G_SIGNAL_RUN_FIRST	= 1 << 0,
  G_SIGNAL_RUN_LAST	= 1 << 1,
  G_SIGNAL_RUN_CLEANUP	= 1 << 2,
  G_SIGNAL_NO_RECURSE	= 1 << 3,
  G_SIGNAL_DETAILED	= 1 << 4,
  G_SIGNAL_ACTION	= 1 << 5,
  G_SIGNAL_NO_HOOKS	= 1 << 6
} GSignalFlags;

The signal flags are used to specify a signal's behaviour, the overall signal description outlines how especially the RUN flags control the stages of a signal emission.

G_SIGNAL_RUN_FIRST | Invoke the object method handler in the first emission stage.
G_SIGNAL_RUN_LAST | Invoke the object method handler in the third emission stage.
G_SIGNAL_RUN_CLEANUP | Invoke the object method handler in the last emission stage.
G_SIGNAL_NO_RECURSE | Signals being emitted for an object while currently being in emission for this very object will not be emitted recursively, but instead cause the first emission to be restarted.
G_SIGNAL_DETAILED | This signal supports "::detail" appendices to the signal name upon handler connections and emissions.
G_SIGNAL_ACTION | Action signals are signals that may freely be emitted on alive objects from user code via g_signal_emit() and friends, without the need of being embedded into extra code that performs pre or post emission adjustments on the object. They can also be thought of as object methods which can be called generically by third-party code.
G_SIGNAL_NO_HOOKS | No emissions hooks are supported for this signal.

enum GSignalMatchType

typedef enum
{
  G_SIGNAL_MATCH_ID	   = 1 << 0,
  G_SIGNAL_MATCH_DETAIL	   = 1 << 1,
  G_SIGNAL_MATCH_CLOSURE   = 1 << 2,
  G_SIGNAL_MATCH_FUNC	   = 1 << 3,
  G_SIGNAL_MATCH_DATA	   = 1 << 4,
  G_SIGNAL_MATCH_UNBLOCKED = 1 << 5
} GSignalMatchType;

The match types specify what g_signal_handlers_block_matched(), g_signal_handlers_unblock_matched() and g_signal_handlers_disconnect_matched() match signals by.

G_SIGNAL_MATCH_ID | The signal id must be equal.
G_SIGNAL_MATCH_DETAIL | The signal detail be equal.
G_SIGNAL_MATCH_CLOSURE | The closure must be the same.
G_SIGNAL_MATCH_FUNC | The C closure callback must be the same.
G_SIGNAL_MATCH_DATA | The closure data must be the same.
G_SIGNAL_MATCH_UNBLOCKED | Only unblocked signals may matched.

GSignalQuery

typedef struct {
  guint		signal_id;
  const gchar  *signal_name;
  GType		itype;
  GSignalFlags	signal_flags;
  GType		return_type; /* mangled with G_SIGNAL_TYPE_STATIC_SCOPE flag */
  guint		n_params;
  const GType  *param_types; /* mangled with G_SIGNAL_TYPE_STATIC_SCOPE flag */
} GSignalQuery;

A structure holding in-depth information for a specific signal. It is filled in by the g_signal_query() function.

guint signal_id; | The signal id of the signal being queried, or 0 if the signal to be queried was unknown.
const gchar *signal_name; | The signal name.
GType itype; | The interface/instance type that this signal can be emitted for.
GSignalFlags signal_flags; | The signal flags as passed in to g_signal_new().
GType return_type; | The return type for user callbacks.
guint n_params; | The number of parameters that user callbacks take.
const GType *param_types; The individual parameter types for user callbacks, note that the effective callback signature is:
return_type callback (gpointer  data1, [param_types param_names,] gpointer  data2);

G_SIGNAL_TYPE_STATIC_SCOPE

#define	G_SIGNAL_TYPE_STATIC_SCOPE (G_TYPE_FLAG_RESERVED_ID_BIT)

This macro flags signal argument types for which the signal system may assume that instances thereof remain persistent across all signal emissions they are used in. This is only useful for non ref-counted, value-copy types.

To flag a signal argument in this way, add | G_SIGNAL_TYPE_STATIC_SCOPE to the corresponding argument of g_signal_new().

    g_signal_new ("size_request", G_TYPE_FROM_CLASS (gobject_class), G_SIGNAL_RUN_FIRST,
          G_STRUCT_OFFSET (GtkWidgetClass, size_request), NULL, NULL, _gtk_marshal_VOID__BOXED, G_TYPE_NONE, 1,
          GTK_TYPE_REQUISITION | G_SIGNAL_TYPE_STATIC_SCOPE);

G_SIGNAL_MATCH_MASK

#define G_SIGNAL_MATCH_MASK  0x3f

A mask for all GSignalMatchType bits.

G_SIGNAL_FLAGS_MASK

#define G_SIGNAL_FLAGS_MASK  0x7f

A mask for all GSignalFlags bits.

g_signal_new ()

guint       g_signal_new           (const gchar *signal_name, GType itype, GSignalFlags signal_flags, guint class_offset,
                                    GSignalAccumulator accumulator,gpointer accu_data, GSignalCMarshaller c_marshaller,
                                    GType return_type, guint n_params, ...);

Creates a new signal. (This is usually done in the class initializer.)

A signal name consists of segments consisting of ASCII letters and digits, separated by either the '-' or '_' character. The first character of a signal name must be a letter. Names which violate these rules lead to undefined behaviour of the GSignal system.
When registering a signal and looking up a signal, either separator can be used, but they cannot be mixed.

signal_name : | the name for the signal
itype : | the type this signal pertains to. It will also pertain to types which are derived from this type.
signal_flags : | a combination of GSignalFlags specifying detail of when the default handler is to be invoked. Specify either G_SIGNAL_RUN_FIRST, or G_SIGNAL_RUN_LAST.
class_offset : | The offset of the function pointer in the class structure for this type. Used to invoke a class method generically.
accumulator : | the accumulator for this signal; may be NULL.
accu_data : | user data for the accumulator.
c_marshaller : | the function to translate arrays of parameter values to signal emissions into C language callback invocations.
return_type : | the type of return value, or G_TYPE_NONE for a signal without a return value.
n_params : | the number of parameter types to follow.
... : | a list of types, one for each parameter.
Returns : | the signal id

g_signal_newv ()

guint       g_signal_newv         (const gchar *signal_name, GType itype, GSignalFlags signal_flags, GClosure *class_closure,
                                   GSignalAccumulator accumulator, gpointer accu_data, GSignalCMarshaller c_marshaller,
                                   GType return_type, guint n_params, GType *param_types);

Creates a new signal. (This is usually done in the class initializer.)
See g_signal_new() for details on allowed signal names.

signal_name : | the name for the signal
itype : | the type this signal pertains to. It will also pertain to types which are derived from this type.
signal_flags : | a combination of GSignalFlags specifying detail of when the default handler is to be invoked. Specify either G_SIGNAL_RUN_FIRST, or G_SIGNAL_RUN_LAST.
class_closure : | The closure to invoke on signal emission.
accumulator : | the accumulator for this signal; may be NULL.
accu_data : | user data for the accumulator.
c_marshaller : | the function to translate arrays of parameter values to signal emissions into C language callback invocations.
return_type : | the type of return value, or G_TYPE_NONE for a signal without a return value.
n_params : | the length of param_types.
param_types : | an array types, one for each parameter.
Returns : | the signal id

g_signal_new_valist ()

guint   g_signal_new_valist     (const gchar *signal_name, GType itype, GSignalFlags signal_flags, GClosure *class_closure,
                                 GSignalAccumulator accumulator, gpointer accu_data, GSignalCMarshaller c_marshaller,
                                 GType return_type, guint n_params, va_list args);

Creates a new signal. (This is usually done in the class initializer.)
See g_signal_new() for details on allowed signal names.

signal_name : | the name for the signal
itype : | the type this signal pertains to. It will also pertain to types which are derived from this type.
signal_flags : | a combination of GSignalFlags specifying detail of when the default handler is to be invoked. Specify either G_SIGNAL_RUN_FIRST, or G_SIGNAL_RUN_LAST.
class_closure : | The closure to invoke on signal emission.
accumulator : | the accumulator for this signal; may be NULL.
accu_data : | user data for the accumulator.
c_marshaller : | the function to translate arrays of parameter values to signal emissions into C language callback invocations.
return_type : | the type of return value, or G_TYPE_NONE for a signal without a return value.
n_params : | the number of parameter types in args.
args : | va_list of GType, one for each parameter.
Returns : | the signal id

g_signal_query ()

void        g_signal_query           (guint signal_id, GSignalQuery *query);

Queries the signal system for in-depth information about a specific signal. This function will fill in a user-provided structure to hold signal-specific information. If an invalid signal id is passed in, the signal_id member of the GSignalQuery is 0. All members filled into the GSignalQuery structure should be considered constant and have to be left untouched.

signal_id : | The signal id of the signal to query information for.
query : | A user provided structure that is filled in with constant values upon success.

g_signal_lookup ()

guint       g_signal_lookup          (const gchar *name, GType itype);

Given the name of the signal and the type of object it connects to, gets the signal's identifying integer. Emitting the signal by number is somewhat faster than using the name each time.

Also tries the ancestors of the given type.

See g_signal_new() for details on allowed signal names.

name : | the signal's name.
itype : | the type that the signal operates on.
Returns : | the signal's identifying number, or 0 if no signal was found.

g_signal_name ()

const gchar* g_signal_name           (guint signal_id);

Given the signal's identifier, finds its name.
Two different signals may have the same name, if they have differing types.

signal_id : | the signal's identifying number.
Returns : | the signal name, or NULL if the signal number was invalid.

g_signal_list_ids ()

guint*      g_signal_list_ids        (GType itype, guint *n_ids);

Lists the signals by id that a certain instance or interface type created. Further information about the signals can be acquired through g_signal_query().

itype : | Instance or interface type.
n_ids : | Location to store the number of signal ids for itype.
Returns : | Newly allocated array of signal IDs.

g_signal_emit ()

void        g_signal_emit          (gpointer instance, guint signal_id, GQuark detail, ...);

Emits a signal.
Note that g_signal_emit() resets the return value to the default if no handlers are connected, in contrast to g_signal_emitv().

instance : | the instance the signal is being emitted on.
signal_id : | the signal id
detail : | the detail
... : | parameters to be passed to the signal, followed by a location for the return value. If the return type of the signal is G_TYPE_NONE, the return value location can be omitted.

g_signal_emit_by_name ()

void        g_signal_emit_by_name       (gpointer instance, const gchar *detailed_signal, ...);

Emits a signal.

Note that g_signal_emit_by_name() resets the return value to the default if no handlers are connected, in contrast to g_signal_emitv().

instance : | the instance the signal is being emitted on.
detailed_signal : | a string of the form "signal-name::detail".
... : | parameters to be passed to the signal, followed by a location for the return value. If the return type of the signal is G_TYPE_NONE, the return value location can be omitted.

g_signal_emitv ()

void        g_signal_emitv        (const GValue *instance_and_params, guint signal_id, GQuark detail, GValue *return_value);

Emits a signal.

Note that g_signal_emitv() doesn't change return_value if no handlers are connected, in contrast to g_signal_emit() and g_signal_emit_valist().

instance_and_params : | argument list for the signal emission. The first element in the array is a GValue for the instance the signal is being emitted on. The rest are any arguments to be passed to the signal.
signal_id : | the signal id
detail : | the detail
return_value : | Location to store the return value of the signal emission.

g_signal_emit_valist ()

void        g_signal_emit_valist      (gpointer instance, guint signal_id, GQuark detail, va_list var_args);

Emits a signal.

Note that g_signal_emit_valist() resets the return value to the default if no handlers are connected, in contrast to g_signal_emitv().

instance : | the instance the signal is being emitted on.
signal_id : | the signal id
detail : | the detail
var_args : | a list of parameters to be passed to the signal, followed by a location for the return value. If the return type of the signal is G_TYPE_NONE, the return value location can be omitted.

g_signal_connect()

#define     g_signal_connect(instance, detailed_signal, c_handler, data)

Connects a GCallback function to a signal for a particular object.
The handler will be called before the default handler of the signal.

instance : | the instance to connect to.
detailed_signal : | a string of the form "signal-name::detail".
c_handler : | the GCallback to connect.
data : | data to pass to c_handler calls.
Returns : | the handler id

g_signal_connect_after()

#define     g_signal_connect_after(instance, detailed_signal, c_handler, data)

Connects a GCallback function to a signal for a particular object.
The handler will be called after the default handler of the signal.

instance : | the instance to connect to.
detailed_signal : | a string of the form "signal-name::detail".
c_handler : | the GCallback to connect.
data : | data to pass to c_handler calls.
Returns : | the handler id

g_signal_connect_swapped()

#define     g_signal_connect_swapped(instance, detailed_signal, c_handler, data)

Connects a GCallback function to a signal for a particular object.
The instance on which the signal is emitted and data will be swapped when calling the handler.

instance : | the instance to connect to.
detailed_signal : | a string of the form "signal-name::detail".
c_handler : | the GCallback to connect.
data : | data to pass to c_handler calls.
Returns : | the handler id

g_signal_connect_object ()

gulong   g_signal_connect_object      (gpointer instance, const gchar *detailed_signal, GCallback c_handler, gpointer gobject,
                                       GConnectFlags connect_flags);

This is similar to g_signal_connect_data(), but uses a closure which ensures that the gobject stays alive during the call to c_handler by temporarily adding a reference count to gobject.

Note that there is a bug in GObject that makes this function much less useful than it might seem otherwise. Once gobject is disposed, the callback will no longer be called, but, the signal handler is not currently disconnected. If the instance is itself being freed at the same time than this doesn't matter, since the signal will automatically be removed, but if instance persists, then the signal handler will leak. Do not remove the signal manually because in the future versions of GObject, the handler will automatically be disconnected.

It's possible to work around this problem in a way that will continue to work with future versions of GObject by checking that the signal handler is still connected before disconnected it:

 if (g_signal_handler_is_connected (instance, id))
   g_signal_handler_disconnect (instance, id);

instance : | the instance to connect to.
detailed_signal : | a string of the form "signal-name::detail".
c_handler : | the GCallback to connect.
gobject : | the object to pass as data to c_handler.
connect_flags : | a combination of GConnnectFlags.
Returns : | the handler id.

enum GConnectFlags

typedef enum
{
  G_CONNECT_AFTER	= 1 << 0,
  G_CONNECT_SWAPPED	= 1 << 1
} GConnectFlags;

The connection flags are used to specify the behaviour of a signal's connection.

G_CONNECT_AFTER | whether the handler should be called before or after the default handler of the signal.
G_CONNECT_SWAPPED | whether the instance and data should be swapped when calling the handler.

g_signal_connect_data ()

gulong      g_signal_connect_data        (gpointer instance, const gchar *detailed_signal, GCallback c_handler, gpointer data,
                                          GClosureNotify destroy_data, GConnectFlags connect_flags);

Connects a GCallback function to a signal for a particular object. Similar to g_signal_connect(), but allows to provide a GDestroyNotify for the data which will be called when the signal handler is disconnected and no longer used. Specify connect_flags if needed ..._after() pr ..._swapped() variants of this function.

instance : | the instance to connect to.
detailed_signal : | a string of the form "signal-name::detail".
c_handler : | the GCallback to connect.
data : | data to pass to c_handler calls.
destroy_data : | a GDestroyNotify for data.
connect_flags : | a combination of GConnectFlags.
Returns : | the handler id

g_signal_connect_closure ()

gulong   g_signal_connect_closure     (gpointer instance, const gchar *detailed_signal, GClosure *closure, gboolean after);

Connects a closure to a signal for a particular object.

instance : | the instance to connect to.
detailed_signal : | a string of the form "signal-name::detail".
closure : | the closure to connect.
after : | whether the handler should be called before or after the default handler of the signal.
Returns : | the handler id

g_signal_connect_closure_by_id ()

gulong  g_signal_connect_closure_by_id  (gpointer instance, guint signal_id, GQuark detail, GClosure *closure, gboolean after);

Connects a closure to a signal for a particular object.

instance : | the instance to connect to.
signal_id : | the id of the signal.
detail : | the detail.
closure : | the closure to connect.
after : | whether the handler should be called before or after the default handler of the signal.
Returns : | the handler id

g_signal_handler_block ()

void        g_signal_handler_block          (gpointer instance, gulong handler_id);

Blocks a handler of an instance so it will not be called during any signal emissions unless it is unblocked again. Thus "blocking" a signal handler means to temporarily deactive it, a signal handler has to be unblocked exactly the same amount of times it has been blocked before to become active again.

The handler_id has to be a valid signal handler id, connected to a signal of instance.

instance : | The instance to block the signal handler of.
handler_id : | Handler id of the handler to be blocked.

g_signal_handler_unblock ()

void        g_signal_handler_unblock        (gpointer instance, gulong handler_id);

Undoes the effect of a previous g_signal_handler_block() call. A blocked handler is skipped during signal emissions and will not be invoked, unblocking it (for exactly the amount of times it has been blocked before) reverts its "blocked" state, so the handler will be recognized by the signal system and is called upon future or currently ongoing signal emissions (since the order in which handlers are called during signal emissions is deterministic, whether the unblocked handler in question is called as part of a currently ongoing emission depends on how far that emission has proceeded yet).

The handler_id has to be a valid id of a signal handler that is connected to a signal of instance and is currently blocked.

instance : | The instance to unblock the signal handler of.
handler_id : | Handler id of the handler to be unblocked.

g_signal_handler_disconnect ()

void        g_signal_handler_disconnect     (gpointer instance, gulong handler_id);

Disconnects a handler from an instance so it will not be called during any future or currently ongoing emissions of the signal it has been connected to. The handler_id becomes invalid and may be reused.

The handler_id has to be a valid signal handler id, connected to a signal of instance.

instance : | The instance to remove the signal handler from.
handler_id : | Handler id of the handler to be disconnected.

g_signal_handler_find ()

gulong      g_signal_handler_find       (gpointer instance, GSignalMatchType mask, guint signal_id, GQuark detail, GClosure *closure,
                                         gpointer func, gpointer data);

Finds the first signal handler that matches certain selection criteria. The criteria mask is passed as an OR-ed combination of GSignalMatchType flags, and the criteria values are passed as arguments. The match mask has to be non-0 for successful matches. If no handler was found, 0 is returned.

instance : | The instance owning the signal handler to be found.
mask : | Mask indicating which of signal_id, detail, closure, func and/or data the handler has to match.
signal_id : | Signal the handler has to be connected to.
detail : | Signal detail the handler has to be connected to.
closure : | The closure the handler will invoke.
func : | The C closure callback of the handler (useless for non-C closures).
data : | The closure data of the handler's closure.
Returns : | A valid non-0 signal handler id for a successful match.

g_signal_handlers_block_matched ()

guint    g_signal_handlers_block_matched    (gpointer instance, GSignalMatchType mask, guint signal_id, GQuark detail,
                                             GClosure *closure, gpointer func, gpointer data);

Blocks all handlers on an instance that match a certain selection criteria. The criteria mask is passed as an OR-ed combination of GSignalMatchType flags, and the criteria values are passed as arguments. Passing at least one of the G_SIGNAL_MATCH_CLOSURE, G_SIGNAL_MATCH_FUNC or G_SIGNAL_MATCH_DATA match flags is required for successful matches. If no handlers were found, 0 is returned, the number of blocked handlers otherwise.

instance : | The instance to block handlers from.
mask : | Mask indicating which of signal_id, detail, closure, func and/or data the handlers have to match.
signal_id : | Signal the handlers have to be connected to.
detail : | Signal detail the handlers have to be connected to.
closure : | The closure the handlers will invoke.
func : | The C closure callback of the handlers (useless for non-C closures).
data : | The closure data of the handlers' closures.
Returns : | The amount of handlers that got blocked.

g_signal_handlers_unblock_matched ()

guint       g_signal_handlers_unblock_matched      (gpointer instance, GSignalMatchType mask, guint signal_id, GQuark detail,
                                                    GClosure *closure, gpointer func, gpointer data);

Unblocks all handlers on an instance that match a certain selection criteria. The criteria mask is passed as an OR-ed combination of GSignalMatchType flags, and the criteria values are passed as arguments. Passing at least one of the G_SIGNAL_MATCH_CLOSURE, G_SIGNAL_MATCH_FUNC or G_SIGNAL_MATCH_DATA match flags is required for successful matches. If no handlers were found, 0 is returned, the number of unblocked handlers otherwise. The match criteria should not apply to any handlers that are not currently blocked.

instance : | The instance to unblock handlers from.
mask : | Mask indicating which of signal_id, detail, closure, func and/or data the handlers have to match.
signal_id : | Signal the handlers have to be connected to.
detail : | Signal detail the handlers have to be connected to.
closure : | The closure the handlers will invoke.
func : | The C closure callback of the handlers (useless for non-C closures).
data : | The closure data of the handlers' closures.
Returns : | The amount of handlers that got unblocked.

g_signal_handlers_disconnect_matched ()

guint       g_signal_handlers_disconnect_matched    (gpointer instance, GSignalMatchType mask, guint signal_id, GQuark detail,
                                                     GClosure *closure, gpointer func, gpointer data);

Disconnects all handlers on an instance that match a certain selection criteria. The criteria mask is passed as an OR-ed combination of GSignalMatchType flags, and the criteria values are passed as arguments. Passing at least one of the G_SIGNAL_MATCH_CLOSURE, G_SIGNAL_MATCH_FUNC or G_SIGNAL_MATCH_DATA match flags is required for successful matches. If no handlers were found, 0 is returned, the number of disconnected handlers otherwise.

instance : | The instance to remove handlers from.
mask : | Mask indicating which of signal_id, detail, closure, func and/or data the handlers have to match.
signal_id : | Signal the handlers have to be connected to.
detail : | Signal detail the handlers have to be connected to.
closure : | The closure the handlers will invoke.
func : | The C closure callback of the handlers (useless for non-C closures).
data : | The closure data of the handlers' closures.
Returns : | The amount of handlers that got disconnected.

g_signal_handler_is_connected ()

gboolean    g_signal_handler_is_connected   (gpointer instance, gulong handler_id);

Returns whether handler_id is the id of a handler connected to instance.

instance : | The instance where a signal handler is sought.
handler_id : | the handler id.
Returns : | whether handler_id identifies a handler connected to instance.

g_signal_handlers_block_by_func()

#define     g_signal_handlers_block_by_func(instance, func, data)

Blocks all handlers on an instance that match func and data.

instance : | The instance to block handlers from.
func : | The C closure callback of the handlers (useless for non-C closures).
data : | The closure data of the handlers' closures.
Returns : | The number of handlers that got blocked.

g_signal_handlers_unblock_by_func()

#define     g_signal_handlers_unblock_by_func(instance, func, data)

Unblocks all handlers on an instance that match func and data.

instance : | The instance to unblock handlers from.
func : | The C closure callback of the handlers (useless for non-C closures).
data : | The closure data of the handlers' closures.
Returns : | The number of handlers that got unblocked.

g_signal_handlers_disconnect_by_func()

#define     g_signal_handlers_disconnect_by_func(instance, func, data)

Disconnects all handlers on an instance that match func and data.

instance : | The instance to remove handlers from.
func : | The C closure callback of the handlers (useless for non-C closures).
data : | The closure data of the handlers' closures.
Returns : | The number of handlers that got disconnected.

g_signal_has_handler_pending ()

gboolean    g_signal_has_handler_pending    (gpointer instance, guint signal_id, GQuark detail, gboolean may_be_blocked);

Returns whether there are any handlers connected to instance for the given signal id and detail.

One example of when this might be used; is when the arguments to the signal are difficult to compute. A class implementor may opt to not emit the signal if no one is attached anyway, thus saving the cost of building the arguments.

instance : | the object whose signal handlers are sought.
signal_id : | the signal id.
detail : | the detail.
may_be_blocked : | whether blocked handlers should count as match.
Returns : | TRUE if a handler is connected to the signal, FALSE otherwise.

g_signal_stop_emission ()

void   g_signal_stop_emission          (gpointer instance, guint signal_id, GQuark detail);

Stops a signal's current emission.
This will prevent the default method from running, if the signal was G_SIGNAL_RUN_LAST and connected normally (i.e. without the "after" flag). Prints a warning if used on a signal which is not being emitted.

instance : | the object whose signal handlers that need to be stopped.
signal_id : | the signal identifier, as returned by g_signal_lookup().
detail : | the detail which the signal was emitted with.

g_signal_stop_emission_by_name ()

void   g_signal_stop_emission_by_name   (gpointer instance, const gchar *detailed_signal);

Stops a signal's current emission.
This is just like g_signal_stop_emission() except it will look up the signal id.

instance : | the object whose signal handlers that need to be stopped. .
detailed_signal : | a string of the form "signal-name::detail".

g_signal_override_class_closure ()

void        g_signal_override_class_closure   (guint signal_id, GType instance_type, GClosure *class_closure);

Overrides the class closure (i.e. the default handler) for the given signal for emissions on instances of instance_type. instance_type must be derived from the type to which the signal belongs.

signal_id : | the signal id
instance_type : | the instance type on which to override the class closure for the signal.
class_closure : | the closure.

g_signal_chain_from_overridden ()

void        g_signal_chain_from_overridden  (const GValue *instance_and_params, GValue *return_value);

Calls the original class closure of a signal. This function should only be called from an overridden class closure; see g_signal_override_class_closure().

instance_and_params : | the argument list of the signal emission. The first element in the array is a GValue for the instance the signal is being emitted on. The rest are any arguments to be passed to the signal.
return_value : | Location for the return value.

g_signal_add_emission_hook ()

gulong      g_signal_add_emission_hook    (guint signal_id, GQuark detail, GSignalEmissionHook hook_func, gpointer hook_data,
                                           GDestroyNotify data_destroy);

Adds an emission hook for a signal, which will get called for any emission of that signal, independent of the instance. This is possible only for signals which don't have G_SIGNAL_NO_HOOKS flag set.

signal_id : | the signal identifier, as returned by g_signal_lookup().
detail : | the detail on which to call the hook.
hook_func : | a GSignalEmissionHook function.
hook_data : | user data for hook_func.
data_destroy : | a GDestroyNotify for hook_data.
Returns : | the hook id, for later use with g_signal_remove_emission_hook().

g_signal_remove_emission_hook ()

void   g_signal_remove_emission_hook   (guint signal_id, gulong hook_id);

Deletes an emission hook.

signal_id : | the id of the signal
hook_id : | the id of the emission hook, as returned by g_signal_add_emission_hook()

g_signal_parse_name ()

gboolean    g_signal_parse_name        (const gchar *detailed_signal, GType itype, guint *signal_id_p, GQuark *detail_p,
                                        gboolean force_detail_quark);

Internal function to parse a signal name into its signal_id and detail quark.

detailed_signal : | a string of the form "signal-name::detail".
itype : | The interface/instance type that introduced "signal-name".
signal_id_p : | Location to store the signal id.
detail_p : | Location to store the detail quark.
force_detail_quark : | TRUE forces creation of a GQuark for the detail.
Returns : | Whether the signal name could successfully be parsed and signal_id_p and detail_p contain valid return values.

g_signal_get_invocation_hint ()

GSignalInvocationHint* g_signal_get_invocation_hint    (gpointer instance);

Returns the invocation hint of the innermost signal emission of instance.

instance : | the instance to query
Returns : | the invocation hint of the innermost signal emission.

g_signal_type_cclosure_new ()

GClosure*   g_signal_type_cclosure_new     (GType itype, guint struct_offset);

Creates a new closure which invokes the function found at the offset struct_offset in the class structure of the interface or classed type identified by itype.

itype : | the GType identifier of an interface or classed type
struct_offset : | the offset of the member function of itype's class structure which is to be invoked by the new closure
Returns : | a new GCClosure

g_signal_accumulator_true_handled ()

gboolean g_signal_accumulator_true_handled    (GSignalInvocationHint *ihint, GValue *return_accu, const GValue *handler_return,
                                               gpointer dummy);

A predefined GSignalAccumulator for signals that return a boolean values. The behavior that this accumulator gives is that a return of TRUE stops the signal emission: no further callbacks will be invoked, while a return of FALSE allows the emission to coninue. The idea here is that a TRUE return indicates that the callback handled the signal, and no further handling is needed.

ihint : | standard GSignalAccumulator parameter
return_accu : | standard GSignalAccumulator parameter
handler_return : | standard GSignalAccumulator parameter
dummy : | standard GSignalAccumulator parameter
Returns : | standard GSignalAccumulator result

Feedback

For additional information or queries on this page send feedback

[11] Although signals can deal with any kind of instantiatable type, i'm referring to those types as "object types" in the following, simply because that is the context most users will encounter signals in.


Parameters and Values

Name

Parameters and Values — Standard Parameter and Value Types.

Library

gobject.lib

Synopsis

#include <glib-object.h>

#define     G_IS_PARAM_SPEC_BOOLEAN         (pspec)
#define     G_PARAM_SPEC_BOOLEAN            (pspec)
#define     G_VALUE_HOLDS_BOOLEAN           (value)
#define     G_TYPE_PARAM_BOOLEAN
            GParamSpecBoolean;
GParamSpec* g_param_spec_boolean            (const gchar *name, const gchar *nick, const gchar *blurb,
                                             gboolean default_value, GParamFlags flags);
void        g_value_set_boolean             (GValue *value, gboolean v_boolean);
gboolean    g_value_get_boolean             (const GValue *value);

#define     G_IS_PARAM_SPEC_CHAR            (pspec)
#define     G_PARAM_SPEC_CHAR               (pspec)
#define     G_VALUE_HOLDS_CHAR              (value)
#define     G_TYPE_PARAM_CHAR
            GParamSpecChar;
GParamSpec* g_param_spec_char               (const gchar *name, const gchar *nick, const gchar *blurb, gint8 minimum,
                                             gint8 maximum, gint8 default_value, GParamFlags flags);
void        g_value_set_char                (GValue *value, gchar v_char);
gchar       g_value_get_char                (const GValue *value);

#define     G_IS_PARAM_SPEC_UCHAR           (pspec)
#define     G_PARAM_SPEC_UCHAR              (pspec)
#define     G_VALUE_HOLDS_UCHAR             (value)
#define     G_TYPE_PARAM_UCHAR
            GParamSpecUChar;

GParamSpec* g_param_spec_uchar              (const gchar *name, const gchar *nick, const gchar *blurb, guint8 minimum,
                                             guint8 maximum, guint8 default_value, GParamFlags flags);
void        g_value_set_uchar               (GValue *value, guchar v_uchar);
guchar      g_value_get_uchar               (const GValue *value);

#define     G_IS_PARAM_SPEC_INT             (pspec)
#define     G_PARAM_SPEC_INT                (pspec)
#define     G_VALUE_HOLDS_INT               (value)
#define     G_TYPE_PARAM_INT
            GParamSpecInt;
GParamSpec* g_param_spec_int                (const gchar *name, const gchar *nick, const gchar *blurb, gint minimum,
                                             gint maximum, gint default_value, GParamFlags flags);
void        g_value_set_int                 (GValue *value, gint v_int);
gint        g_value_get_int                 (const GValue *value);

#define     G_IS_PARAM_SPEC_UINT            (pspec)
#define     G_PARAM_SPEC_UINT               (pspec)
#define     G_VALUE_HOLDS_UINT              (value)
#define     G_TYPE_PARAM_UINT
            GParamSpecUInt;
GParamSpec* g_param_spec_uint               (const gchar *name, const gchar *nick, const gchar *blurb, guint minimum,
                                             guint maximum, guint default_value, GParamFlags flags);
void        g_value_set_uint                (GValue *value, guint v_uint);
guint       g_value_get_uint                (const GValue *value);

#define     G_IS_PARAM_SPEC_LONG            (pspec)
#define     G_PARAM_SPEC_LONG               (pspec)
#define     G_VALUE_HOLDS_LONG              (value)
#define     G_TYPE_PARAM_LONG
            GParamSpecLong;
GParamSpec* g_param_spec_long               (const gchar *name, const gchar *nick, const gchar *blurb, glong minimum,
                                             glong maximum, glong default_value, GParamFlags flags);
void        g_value_set_long                (GValue *value, glong v_long);
glong       g_value_get_long                (const GValue *value);

#define     G_IS_PARAM_SPEC_ULONG           (pspec)
#define     G_PARAM_SPEC_ULONG              (pspec)
#define     G_VALUE_HOLDS_ULONG             (value)
#define     G_TYPE_PARAM_ULONG
            GParamSpecULong;
GParamSpec* g_param_spec_ulong              (const gchar *name, const gchar *nick, const gchar *blurb, gulong minimum,
                                             gulong maximum, gulong default_value, GParamFlags flags);
void        g_value_set_ulong               (GValue *value, gulong v_ulong);
gulong      g_value_get_ulong               (const GValue *value);

#define     G_IS_PARAM_SPEC_INT64           (pspec)
#define     G_PARAM_SPEC_INT64              (pspec)
#define     G_VALUE_HOLDS_INT64             (value)
#define     G_TYPE_PARAM_INT64
            GParamSpecInt64;
GParamSpec* g_param_spec_int64              (const gchar *name, const gchar *nick, const gchar *blurb, gint64 minimum,
                                             gint64 maximum, gint64 default_value, GParamFlags flags);
void        g_value_set_int64               (GValue *value, gint64 v_int64);
gint64      g_value_get_int64               (const GValue *value);

#define     G_IS_PARAM_SPEC_UINT64          (pspec)
#define     G_PARAM_SPEC_UINT64             (pspec)
#define     G_VALUE_HOLDS_UINT64            (value)
#define     G_TYPE_PARAM_UINT64
            GParamSpecUInt64;
GParamSpec* g_param_spec_uint64             (const gchar *name, const gchar *nick, const gchar *blurb, guint64 minimum,
                                             guint64 maximum, guint64 default_value, GParamFlags flags);
void        g_value_set_uint64              (GValue *value, guint64 v_uint64);
guint64     g_value_get_uint64              (const GValue *value);

#define     G_IS_PARAM_SPEC_FLOAT           (pspec)
#define     G_PARAM_SPEC_FLOAT              (pspec)
#define     G_VALUE_HOLDS_FLOAT             (value)
#define     G_TYPE_PARAM_FLOAT
            GParamSpecFloat;
GParamSpec* g_param_spec_float              (const gchar *name, const gchar *nick, const gchar *blurb, gfloat minimum,
                                             gfloat maximum, gfloat default_value, GParamFlags flags);
void        g_value_set_float               (GValue *value, gfloat v_float);
gfloat      g_value_get_float               (const GValue *value);

#define     G_IS_PARAM_SPEC_DOUBLE          (pspec)
#define     G_PARAM_SPEC_DOUBLE             (pspec)
#define     G_VALUE_HOLDS_DOUBLE            (value)
#define     G_TYPE_PARAM_DOUBLE
            GParamSpecDouble;
GParamSpec* g_param_spec_double             (const gchar *name, const gchar *nick, const gchar *blurb, gdouble minimum,
                                             gdouble maximum, gdouble default_value, GParamFlags flags);
void        g_value_set_double              (GValue *value, gdouble v_double);
gdouble     g_value_get_double              (const GValue *value);

#define     G_IS_PARAM_SPEC_ENUM            (pspec)
#define     G_PARAM_SPEC_ENUM               (pspec)
#define     G_VALUE_HOLDS_ENUM              (value)
#define     G_TYPE_PARAM_ENUM
            GParamSpecEnum;
GParamSpec* g_param_spec_enum               (const gchar *name, const gchar *nick, const gchar *blurb, GType enum_type,
                                             gint default_value, GParamFlags flags);
void        g_value_set_enum                (GValue *value, gint v_enum);
gint        g_value_get_enum                (const GValue *value);

#define     G_IS_PARAM_SPEC_FLAGS           (pspec)
#define     G_PARAM_SPEC_FLAGS              (pspec)
#define     G_VALUE_HOLDS_FLAGS             (value)
#define     G_TYPE_PARAM_FLAGS
            GParamSpecFlags;
GParamSpec* g_param_spec_flags              (const gchar *name, const gchar *nick, const gchar *blurb, GType flags_type,
                                             guint default_value, GParamFlags flags);
void        g_value_set_flags               (GValue *value, guint v_flags);
guint       g_value_get_flags               (const GValue *value);

#define     G_IS_PARAM_SPEC_STRING          (pspec)
#define     G_PARAM_SPEC_STRING             (pspec)
#define     G_VALUE_HOLDS_STRING            (value)
#define     G_TYPE_PARAM_STRING
            GParamSpecString;
typedef     gchararray;
GParamSpec* g_param_spec_string             (const gchar *name, const gchar *nick, const gchar *blurb,
                                             const gchar *default_value, GParamFlags flags);
void        g_value_set_string              (GValue *value, const gchar *v_string);
void        g_value_set_static_string       (GValue *value, const gchar *v_string);
void        g_value_take_string             (GValue *value, gchar *v_string);
void        g_value_set_string_take_ownership    (GValue *value, gchar *v_string);
const gchar* g_value_get_string             (const GValue *value);
gchar*      g_value_dup_string              (const GValue *value);

#define     G_IS_PARAM_SPEC_PARAM           (pspec)
#define     G_PARAM_SPEC_PARAM              (pspec)
#define     G_VALUE_HOLDS_PARAM             (value)
#define     G_TYPE_PARAM_PARAM
            GParamSpecParam;
GParamSpec* g_param_spec_param              (const gchar *name, const gchar *nick, const gchar *blurb, GType param_type,
                                             GParamFlags flags);
void        g_value_set_param               (GValue *value, GParamSpec *param);
void        g_value_take_param              (GValue *value, GParamSpec *param);
void        g_value_set_param_take_ownership  (GValue *value, GParamSpec *param);
GParamSpec* g_value_get_param               (const GValue *value);
GParamSpec* g_value_dup_param               (const GValue *value);

#define     G_IS_PARAM_SPEC_BOXED           (pspec)
#define     G_PARAM_SPEC_BOXED              (pspec)
#define     G_VALUE_HOLDS_BOXED             (value)
#define     G_TYPE_PARAM_BOXED
            GParamSpecBoxed;
GParamSpec* g_param_spec_boxed              (const gchar *name, const gchar *nick, const gchar *blurb, GType boxed_type,
                                             GParamFlags flags);
void        g_value_set_boxed               (GValue *value, gconstpointer v_boxed);
void        g_value_set_static_boxed        (GValue *value, gconstpointer v_boxed);
void        g_value_take_boxed              (GValue *value, gconstpointer v_boxed);
void        g_value_set_boxed_take_ownership  (GValue *value, gconstpointer v_boxed);
gpointer    g_value_get_boxed               (const GValue *value);
gpointer    g_value_dup_boxed               (const GValue *value);

#define     G_IS_PARAM_SPEC_POINTER         (pspec)
#define     G_PARAM_SPEC_POINTER            (pspec)
#define     G_VALUE_HOLDS_POINTER           (value)
#define     G_TYPE_PARAM_POINTER
            GParamSpecPointer;
GParamSpec* g_param_spec_pointer            (const gchar *name, const gchar *nick, const gchar *blurb, GParamFlags flags);
void        g_value_set_pointer             (GValue *value, gpointer v_pointer);
gpointer    g_value_get_pointer             (const GValue *value);

#define     G_IS_PARAM_SPEC_OBJECT          (pspec)
#define     G_PARAM_SPEC_OBJECT             (pspec)
#define     G_VALUE_HOLDS_OBJECT            (value)
#define     G_TYPE_PARAM_OBJECT
            GParamSpecObject;
GParamSpec* g_param_spec_object             (const gchar *name, const gchar *nick, const gchar *blurb,
                                             GType object_type, GParamFlags flags);
void        g_value_set_object              (GValue *value, gpointer v_object);
void        g_value_take_object             (GValue *value, gpointer v_object);
void        g_value_set_object_take_ownership  (GValue *value, gpointer v_object);
gpointer    g_value_get_object              (const GValue *value);
GObject*    g_value_dup_object              (const GValue *value);

#define     G_IS_PARAM_SPEC_UNICHAR         (pspec)
#define     G_PARAM_SPEC_UNICHAR            (pspec)
#define     G_TYPE_PARAM_UNICHAR
            GParamSpecUnichar;
GParamSpec* g_param_spec_unichar            (const gchar *name, const gchar *nick, const gchar *blurb,
                                             gunichar default_value, GParamFlags flags);

#define     G_IS_PARAM_SPEC_VALUE_ARRAY     (pspec)
#define     G_PARAM_SPEC_VALUE_ARRAY        (pspec)
#define     G_TYPE_PARAM_VALUE_ARRAY
            GParamSpecValueArray;
GParamSpec* g_param_spec_value_array        (const gchar *name, const gchar *blurb, GParamSpec *element_spec,
                                             const gchar *nick, GParamFlags flags);

#define     G_IS_PARAM_SPEC_OVERRIDE        (pspec)
#define     G_PARAM_SPEC_OVERRIDE           (pspec)
#define     G_TYPE_PARAM_OVERRIDE
            GParamSpecOverride;
GParamSpec* g_param_spec_override           (const gchar *name, GParamSpec *overridden);
#define     G_IS_PARAM_SPEC_GTYPE           (pspec)
#define     G_PARAM_SPEC_GTYPE              (pspec)
#define     G_TYPE_PARAM_GTYPE
            GParamSpecGType;
GParamSpec* g_param_spec_gtype              (const gchar *name, const gchar *nick, const gchar *blurb, GType is_a_type,
                                             GParamFlags flags);

Detailed Description

GValue provides an abstract container structure which can be copied, transformed and compared while holding a value of any (derived) type, which is registered as a GType with a GTypeValueTable in its GTypeInfo structure. Parameter specifications for most value types can be created as GParamSpec derived instances, to implement e.g. GObject properties which operate on GValue containers.

Parameter names need to start with a letter (a-z or A-Z). Subsequent characters can be letters, numbers or a '-'. All other characters are replaced by a '-' during construction.

Details

G_IS_PARAM_SPEC_BOOLEAN()

#define G_IS_PARAM_SPEC_BOOLEAN(pspec)     (G_TYPE_CHECK_INSTANCE_TYPE ((pspec), G_TYPE_PARAM_BOOLEAN))

Returns whether the given GParamSpec is of type G_TYPE_PARAM_BOOLEAN.

pspec : a valid GParamSpec instance

G_PARAM_SPEC_BOOLEAN()

#define G_PARAM_SPEC_BOOLEAN(pspec)        (G_TYPE_CHECK_INSTANCE_CAST ((pspec), G_TYPE_PARAM_BOOLEAN, GParamSpecBoolean))

Casts a GParamSpec instance into a GParamSpecBoolean.

pspec : a valid GParamSpec instance

G_VALUE_HOLDS_BOOLEAN()

#define G_VALUE_HOLDS_BOOLEAN(value)	 (G_TYPE_CHECK_VALUE_TYPE ((value), G_TYPE_BOOLEAN))

Returns whether the given GValue can hold values of type G_TYPE_BOOLEAN.

value : a valid GValue structure

G_TYPE_PARAM_BOOLEAN

#define	G_TYPE_PARAM_BOOLEAN		   (g_param_spec_types[2])

The GType of GParamSpecBoolean.

GParamSpecBoolean

typedef struct {
  GParamSpec    parent_instance;

  gboolean      default_value;
} GParamSpecBoolean;

A GParamSpec derived structure that contains the meta data for boolean properties.

GParamSpec parent_instance; | private GParamSpec portion
gboolean default_value; | default value for the property specified

g_param_spec_boolean ()

GParamSpec* g_param_spec_boolean            (const gchar *name, const gchar *nick, const gchar *blurb, gboolean default_value, GParamFlags flags);

Creates a new GParamSpecBoolean instance specifying a G_TYPE_BOOLEAN property.
See g_param_spec_internal() for details on property names.

name : | canonical name of the property specified
nick : | nick name for the property specified
blurb : | description of the property specified
default_value : | default value for the property specified
flags : | flags for the property specified
Returns : | a newly created parameter specification

g_value_set_boolean ()

void        g_value_set_boolean             (GValue *value, gboolean v_boolean);

Sets the contents of a G_TYPE_BOOLEAN GValue to v_boolean.

value : | a valid GValue of type G_TYPE_BOOLEAN
v_boolean : | boolean value to be set

g_value_get_boolean ()

gboolean    g_value_get_boolean             (const GValue *value);

Gets the contents of a G_TYPE_BOOLEAN GValue.

value : | a valid GValue of type G_TYPE_BOOLEAN
Returns : | boolean contents of value

G_IS_PARAM_SPEC_CHAR()

#define G_IS_PARAM_SPEC_CHAR(pspec)        (G_TYPE_CHECK_INSTANCE_TYPE ((pspec), G_TYPE_PARAM_CHAR))

Returns whether the given GParamSpec is of type G_TYPE_PARAM_CHAR.

pspec : a valid GParamSpec instance

G_PARAM_SPEC_CHAR()

#define G_PARAM_SPEC_CHAR(pspec)           (G_TYPE_CHECK_INSTANCE_CAST ((pspec), G_TYPE_PARAM_CHAR, GParamSpecChar))

Casts a GParamSpec instance into a GParamSpecChar.

pspec : a valid GParamSpec instance

G_VALUE_HOLDS_CHAR()

#define G_VALUE_HOLDS_CHAR(value)	 (G_TYPE_CHECK_VALUE_TYPE ((value), G_TYPE_CHAR))

Returns whether the given GValue can hold values of type G_TYPE_CHAR.

value : a valid GValue structure

G_TYPE_PARAM_CHAR

#define	G_TYPE_PARAM_CHAR		   (g_param_spec_types[0])

The GType of GParamSpecChar.

GParamSpecChar

typedef struct {
  GParamSpec    parent_instance;

  gint8         minimum;
  gint8         maximum;
  gint8         default_value;
} GParamSpecChar;

A GParamSpec derived structure that contains the meta data for character properties.

GParamSpec parent_instance; | private GParamSpec portion
gint8 minimum; | minimum value for the property specified
gint8 maximum; | maximum value for the property specified
gint8 default_value; | default value for the property specified

g_param_spec_char ()

GParamSpec* g_param_spec_char       (const gchar *name, const gchar *nick, const gchar *blurb, gint8 minimum, gint8 maximum, gint8 default_value, GParamFlags flags);

Creates a new GParamSpecChar instance specifying a G_TYPE_CHAR property.

name : | canonical name of the property specified
nick : | nick name for the property specified
blurb : | description of the property specified
minimum : | minimum value for the property specified
maximum : | maximum value for the property specified
default_value : | default value for the property specified
flags : | flags for the property specified
Returns : | a newly created parameter specification

g_value_set_char ()

void        g_value_set_char        (GValue *value, gchar v_char);

Sets the contents of a G_TYPE_CHAR GValue to v_char.

value : | a valid GValue of type G_TYPE_CHAR
v_char : | character value to be set

g_value_get_char ()

gchar       g_value_get_char         (const GValue *value);

Gets the contents of a G_TYPE_CHAR GValue.

value : | a valid GValue of type G_TYPE_CHAR
Returns : | character contents of value

G_IS_PARAM_SPEC_UCHAR()

#define G_IS_PARAM_SPEC_UCHAR(pspec)       (G_TYPE_CHECK_INSTANCE_TYPE ((pspec), G_TYPE_PARAM_UCHAR))

Returns whether the given GParamSpec is of type G_TYPE_PARAM_UCHAR.

pspec : a valid GParamSpec instance

G_PARAM_SPEC_UCHAR()

#define G_PARAM_SPEC_UCHAR(pspec)          (G_TYPE_CHECK_INSTANCE_CAST ((pspec), G_TYPE_PARAM_UCHAR, GParamSpecUChar))

Casts a GParamSpec instance into a GParamSpecUChar.

pspec : a valid GParamSpec instance

G_VALUE_HOLDS_UCHAR()

#define G_VALUE_HOLDS_UCHAR(value)	 (G_TYPE_CHECK_VALUE_TYPE ((value), G_TYPE_UCHAR))

Returns whether the given GValue can hold values of type G_TYPE_UCHAR.

value : a valid GValue structure

G_TYPE_PARAM_UCHAR

#define	G_TYPE_PARAM_UCHAR		   (g_param_spec_types[1])

The GType of GParamSpecUChar.

GParamSpecUChar

typedef struct {
  GParamSpec    parent_instance;

  guint8        minimum;
  guint8        maximum;
  guint8        default_value;
} GParamSpecUChar;

A GParamSpec derived structure that contains the meta data for unsigned character properties.

GParamSpec parent_instance; | private GParamSpec portion
guint8 minimum; | minimum value for the property specified
guint8 maximum; | maximum value for the property specified
guint8 default_value; | default value for the property specified

g_param_spec_uchar ()

GParamSpec* g_param_spec_uchar      (const gchar *name, const gchar *nick, const gchar *blurb, guint8 minimum, guint8 maximum,
                                     guint8 default_value, GParamFlags flags);

Creates a new GParamSpecUChar instance specifying a G_TYPE_UCHAR property.

name : | canonical name of the property specified
nick : | nick name for the property specified
blurb : | description of the property specified
minimum : | minimum value for the property specified
maximum : | maximum value for the property specified
default_value : | default value for the property specified
flags : | flags for the property specified
Returns : | a newly created parameter specification

g_value_set_uchar ()

void        g_value_set_uchar               (GValue *value, guchar v_uchar);

Sets the contents of a G_TYPE_UCHAR GValue to v_uchar.

value : | a valid GValue of type G_TYPE_UCHAR
v_uchar : | unsigned character value to be set

g_value_get_uchar ()

guchar      g_value_get_uchar               (const GValue *value);

Gets the contents of a G_TYPE_UCHAR GValue.

value : | a valid GValue of type G_TYPE_UCHAR
Returns : | unsigned character contents of value

G_IS_PARAM_SPEC_INT()

#define G_IS_PARAM_SPEC_INT(pspec)         (G_TYPE_CHECK_INSTANCE_TYPE ((pspec), G_TYPE_PARAM_INT))

Returns whether the given GParamSpec is of type G_TYPE_PARAM_INT.

pspec : a valid GParamSpec instance

G_PARAM_SPEC_INT()

#define G_PARAM_SPEC_INT(pspec)            (G_TYPE_CHECK_INSTANCE_CAST ((pspec), G_TYPE_PARAM_INT, GParamSpecInt))

Casts a GParamSpec instance into a GParamSpecInt.

pspec : a valid GParamSpec instance

G_VALUE_HOLDS_INT()

#define G_VALUE_HOLDS_INT(value)	 (G_TYPE_CHECK_VALUE_TYPE ((value), G_TYPE_INT))

Returns whether the given GValue can hold values of type G_TYPE_INT.

value : a valid GValue structure

G_TYPE_PARAM_INT

#define	G_TYPE_PARAM_INT		   (g_param_spec_types[3])

The GType of GParamSpecInt.

GParamSpecInt

typedef struct {
  GParamSpec    parent_instance;

  gint          minimum;
  gint          maximum;
  gint          default_value;
} GParamSpecInt;

A GParamSpec derived structure that contains the meta data for integer properties.

GParamSpec parent_instance; | private GParamSpec portion
gint minimum; | minimum value for the property specified
gint maximum; | maximum value for the property specified
gint default_value; | default value for the property specified

g_param_spec_int ()

GParamSpec* g_param_spec_int        (const gchar *name, const gchar *nick, const gchar *blurb, gint minimum,
                                     gint maximum, gint default_value,  GParamFlags flags);

Creates a new GParamSpecInt instance specifying a G_TYPE_INT property.
See g_param_spec_internal() for details on property names.

name : | canonical name of the property specified
nick : | nick name for the property specified
blurb : | description of the property specified
minimum : | minimum value for the property specified
maximum : | maximum value for the property specified
default_value : | default value for the property specified
flags : | flags for the property specified
Returns : | a newly created parameter specification

g_value_set_int ()

void        g_value_set_int                 (GValue *value, gint v_int);

Sets the contents of a G_TYPE_INT GValue to v_int.

value : | a valid GValue of type G_TYPE_INT
v_int : | integer value to be set

g_value_get_int ()

gint        g_value_get_int                 (const GValue *value);

Gets the contents of a G_TYPE_INT GValue.

value : | a valid GValue of type G_TYPE_INT
Returns : | integer contents of value

G_IS_PARAM_SPEC_UINT()

#define G_IS_PARAM_SPEC_UINT(pspec)        (G_TYPE_CHECK_INSTANCE_TYPE ((pspec), G_TYPE_PARAM_UINT))

Returns whether the given GParamSpec is of type G_TYPE_PARAM_INT.

pspec : a valid GParamSpec instance

G_PARAM_SPEC_UINT()

#define G_PARAM_SPEC_UINT(pspec)           (G_TYPE_CHECK_INSTANCE_CAST ((pspec), G_TYPE_PARAM_UINT, GParamSpecUInt))

Casts a GParamSpec instance into a GParamSpecUInt.

pspec : a valid GParamSpec instance

G_VALUE_HOLDS_UINT()

#define G_VALUE_HOLDS_UINT(value)	 (G_TYPE_CHECK_VALUE_TYPE ((value), G_TYPE_UINT))

Returns whether the given GValue can hold values of type G_TYPE_UINT.

value : a valid GValue structure

G_TYPE_PARAM_UINT

#define	G_TYPE_PARAM_UINT	        (g_param_spec_types[4])

The GType of GParamSpecUInt.

GParamSpecUInt

typedef struct {
  GParamSpec    parent_instance;

  guint         minimum;
  guint         maximum;
  guint         default_value;
} GParamSpecUInt;

A GParamSpec derived structure that contains the meta data for unsigned integer properties.

GParamSpec parent_instance; | private GParamSpec portion
guint minimum; | minimum value for the property specified
guint maximum; | maximum value for the property specified
guint default_value; | default value for the property specified

g_param_spec_uint ()

GParamSpec* g_param_spec_uint          (const gchar *name, const gchar *nick, const gchar *blurb, guint minimum, guint maximum,
                                        guint default_value, GParamFlags flags);

Creates a new GParamSpecUInt instance specifying a G_TYPE_UINT property.
See g_param_spec_internal() for details on property names.

name : | canonical name of the property specified
nick : | nick name for the property specified
blurb : | description of the property specified
minimum : | minimum value for the property specified
maximum : | maximum value for the property specified
default_value : | default value for the property specified
flags : | flags for the property specified
Returns : | a newly created parameter specification

g_value_set_uint ()

void        g_value_set_uint                (GValue *value, guint v_uint);

Sets the contents of a G_TYPE_UINT GValue to v_uint.

value : | a valid GValue of type G_TYPE_UINT
v_uint : | unsigned integer value to be set

g_value_get_uint ()

guint       g_value_get_uint                (const GValue *value);

Gets the contents of a G_TYPE_UINT GValue.

value : | a valid GValue of type G_TYPE_UINT
Returns : | unsigned integer contents of value

G_IS_PARAM_SPEC_LONG()

#define G_IS_PARAM_SPEC_LONG(pspec)        (G_TYPE_CHECK_INSTANCE_TYPE ((pspec), G_TYPE_PARAM_LONG))

Returns whether the given GParamSpec is of type G_TYPE_PARAM_LONG.

pspec : a valid GParamSpec instance

G_PARAM_SPEC_LONG()

#define G_PARAM_SPEC_LONG(pspec)           (G_TYPE_CHECK_INSTANCE_CAST ((pspec), G_TYPE_PARAM_LONG, GParamSpecLong))

Casts a GParamSpec instance into a GParamSpecLong.

pspec : a valid GParamSpec instance

G_VALUE_HOLDS_LONG()

#define G_VALUE_HOLDS_LONG(value)	 (G_TYPE_CHECK_VALUE_TYPE ((value), G_TYPE_LONG))

Returns whether the given GValue can hold values of type G_TYPE_LONG.

value : a valid GValue structure

G_TYPE_PARAM_LONG

#define	G_TYPE_PARAM_LONG		 (g_param_spec_types[5])

The GType of GParamSpecLong.

GParamSpecLong

typedef struct {
  GParamSpec    parent_instance;

  glong         minimum;
  glong         maximum;
  glong         default_value;
} GParamSpecLong;

A GParamSpec derived structure that contains the meta data for long integer properties.

GParamSpec parent_instance; | private GParamSpec portion
glong minimum; | minimum value for the property specified
glong maximum; | maximum value for the property specified
glong default_value; | default value for the property specified

g_param_spec_long ()

GParamSpec* g_param_spec_long            (const gchar *name, const gchar *nick, const gchar *blurb, glong minimum,
                                          glong maximum, glong default_value, GParamFlags flags);

Creates a new GParamSpecLong instance specifying a G_TYPE_LONG property.
See g_param_spec_internal() for details on property names.

name : | canonical name of the property specified
nick : | nick name for the property specified
blurb : | description of the property specified
minimum : | minimum value for the property specified
maximum : | maximum value for the property specified
default_value : | default value for the property specified
flags : | flags for the property specified
Returns : | a newly created parameter specification

g_value_set_long ()

void        g_value_set_long                (GValue *value, glong v_long);

Sets the contents of a G_TYPE_LONG GValue to v_long.

value : | a valid GValue of type G_TYPE_LONG
v_long : | long integer value to be set

g_value_get_long ()

glong       g_value_get_long                (const GValue *value);

Gets the contents of a G_TYPE_LONG GValue.

value : | a valid GValue of type G_TYPE_LONG
Returns : | long integer contents of value

G_IS_PARAM_SPEC_ULONG()

#define G_IS_PARAM_SPEC_ULONG(pspec)       (G_TYPE_CHECK_INSTANCE_TYPE ((pspec), G_TYPE_PARAM_ULONG))

Returns whether the given GParamSpec is of type G_TYPE_PARAM_ULONG.

pspec : a valid GParamSpec instance

G_PARAM_SPEC_ULONG()

#define G_PARAM_SPEC_ULONG(pspec)          (G_TYPE_CHECK_INSTANCE_CAST ((pspec), G_TYPE_PARAM_ULONG, GParamSpecULong))

Casts a GParamSpec instance into a GParamSpecULong.

pspec : a valid GParamSpec instance

G_VALUE_HOLDS_ULONG()

#define G_VALUE_HOLDS_ULONG(value)	 (G_TYPE_CHECK_VALUE_TYPE ((value), G_TYPE_ULONG))

Returns whether the given GValue can hold values of type G_TYPE_ULONG.

value : a valid GValue structure

G_TYPE_PARAM_ULONG

#define	G_TYPE_PARAM_ULONG		 (g_param_spec_types[6])

The GType of GParamSpecULong.

GParamSpecULong

typedef struct {
  GParamSpec    parent_instance;

  gulong        minimum;
  gulong        maximum;
  gulong        default_value;
} GParamSpecULong;

A GParamSpec derived structure that contains the meta data for unsigned long integer properties.

GParamSpec parent_instance; | private GParamSpec portion
gulong minimum; | minimum value for the property specified
gulong maximum; | maximum value for the property specified
gulong default_value; | default value for the property specified

g_param_spec_ulong ()

GParamSpec* g_param_spec_ulong        (const gchar *name, const gchar *nick, const gchar *blurb, gulong minimum,
                                       gulong maximum, gulong default_value, GParamFlags flags);

Creates a new GParamSpecULong instance specifying a G_TYPE_ULONG property.
See g_param_spec_internal() for details on property names.

name : | canonical name of the property specified
nick : | nick name for the property specified
blurb : | description of the property specified
minimum : | minimum value for the property specified
maximum : | maximum value for the property specified
default_value : | default value for the property specified
flags : | flags for the property specified
Returns : | a newly created parameter specification

g_value_set_ulong ()

void        g_value_set_ulong         (GValue *value, gulong v_ulong);

Sets the contents of a G_TYPE_ULONG GValue to v_ulong.

value : | a valid GValue of type G_TYPE_ULONG
v_ulong : | unsigned long integer value to be set

g_value_get_ulong ()

gulong      g_value_get_ulong         (const GValue *value);

Gets the contents of a G_TYPE_ULONG GValue.

value : | a valid GValue of type G_TYPE_ULONG
Returns : | unsigned long integer contents of value

G_IS_PARAM_SPEC_INT64()

#define G_IS_PARAM_SPEC_INT64(pspec)     (G_TYPE_CHECK_INSTANCE_TYPE ((pspec), G_TYPE_PARAM_INT64))

Returns whether the given GParamSpec is of type G_TYPE_PARAM_INT64.

pspec : a valid GParamSpec instance

G_PARAM_SPEC_INT64()

#define G_PARAM_SPEC_INT64(pspec)        (G_TYPE_CHECK_INSTANCE_CAST ((pspec), G_TYPE_PARAM_INT64, GParamSpecInt64))

Casts a GParamSpec instance into a GParamSpecInt64.

pspec : a valid GParamSpec instance

G_VALUE_HOLDS_INT64()

#define G_VALUE_HOLDS_INT64(value)	 (G_TYPE_CHECK_VALUE_TYPE ((value), G_TYPE_INT64))

Returns whether the given GValue can hold values of type G_TYPE_INT64.

value : a valid GValue structure

G_TYPE_PARAM_INT64

#define	G_TYPE_PARAM_INT64		(g_param_spec_types[7])

The GType of GParamSpecInt64.

GParamSpecInt64

typedef struct {
  GParamSpec    parent_instance;

  gint64        minimum;
  gint64        maximum;
  gint64        default_value;
} GParamSpecInt64;

A GParamSpec derived structure that contains the meta data for 64bit integer properties.

GParamSpec parent_instance; | private GParamSpec portion
gint64 minimum; | minimum value for the property specified
gint64 maximum; | maximum value for the property specified
gint64 default_value; | default value for the property specified

g_param_spec_int64 ()

GParamSpec* g_param_spec_int64        (const gchar *name, const gchar *nick, const gchar *blurb, gint64 minimum,
                                       gint64 maximum, gint64 default_value, GParamFlags flags);

Creates a new GParamSpecInt64 instance specifying a G_TYPE_INT64 property.
See g_param_spec_internal() for details on property names.

name : | canonical name of the property specified
nick : | nick name for the property specified
blurb : | description of the property specified
minimum : | minimum value for the property specified
maximum : | maximum value for the property specified
default_value : | default value for the property specified
flags : | flags for the property specified
Returns : | a newly created parameter specification

g_value_set_int64 ()

void        g_value_set_int64               (GValue *value, gint64 v_int64);

Sets the contents of a G_TYPE_INT64 GValue to v_int64.

value : | a valid GValue of type G_TYPE_INT64
v_int64 : | 64bit integer value to be set

g_value_get_int64 ()

gint64      g_value_get_int64               (const GValue *value);

Gets the contents of a G_TYPE_INT64 GValue.

value : | a valid GValue of type G_TYPE_INT64
Returns : | 64bit integer contents of value

G_IS_PARAM_SPEC_UINT64()

#define G_IS_PARAM_SPEC_UINT64(pspec)      (G_TYPE_CHECK_INSTANCE_TYPE ((pspec), G_TYPE_PARAM_UINT64))

Returns whether the given GParamSpec is of type G_TYPE_PARAM_UINT64.

pspec : a valid GParamSpec instance

G_PARAM_SPEC_UINT64()

#define G_PARAM_SPEC_UINT64(pspec)         (G_TYPE_CHECK_INSTANCE_CAST ((pspec), G_TYPE_PARAM_UINT64, GParamSpecUInt64))

Casts a GParamSpec instance into a GParamSpecUInt64.

pspec : a valid GParamSpec instance

G_VALUE_HOLDS_UINT64()

#define G_VALUE_HOLDS_UINT64(value)	 (G_TYPE_CHECK_VALUE_TYPE ((value), G_TYPE_UINT64))

Returns whether the given GValue can hold values of type G_TYPE_UINT64.

value : a valid GValue structure

G_TYPE_PARAM_UINT64

#define	G_TYPE_PARAM_UINT64		   (g_param_spec_types[8])

The GType of GParamSpecUInt64.

GParamSpecUInt64

typedef struct {
  GParamSpec    parent_instance;

  guint64       minimum;
  guint64       maximum;
  guint64       default_value;
} GParamSpecUInt64;

A GParamSpec derived structure that contains the meta data for unsigned 64bit integer properties.

GParamSpec parent_instance; | private GParamSpec portion
guint64 minimum; | minimum value for the property specified
guint64 maximum; | maximum value for the property specified
guint64 default_value; | default value for the property specified

g_param_spec_uint64 ()

GParamSpec* g_param_spec_uint64       (const gchar *name, const gchar *nick, const gchar *blurb, guint64 minimum, guint64 maximum,
                                       guint64 default_value, GParamFlags flags);

Creates a new GParamSpecUInt64 instance specifying a G_TYPE_UINT64 property.
See g_param_spec_internal() for details on property names.

name : | canonical name of the property specified
nick : | nick name for the property specified
blurb : | description of the property specified
minimum : | minimum value for the property specified
maximum : | maximum value for the property specified
default_value : | default value for the property specified
flags : | flags for the property specified
Returns : | a newly created parameter specification

g_value_set_uint64 ()

void        g_value_set_uint64              (GValue *value, guint64 v_uint64);

Sets the contents of a G_TYPE_UINT64 GValue to v_uint64.

value : | a valid GValue of type G_TYPE_UINT64
v_uint64 : | unsigned 64bit integer value to be set

g_value_get_uint64 ()

guint64     g_value_get_uint64              (const GValue *value);

Gets the contents of a G_TYPE_UINT64 GValue.

value : | a valid GValue of type G_TYPE_UINT64
Returns : | unsigned 64bit integer contents of value

G_IS_PARAM_SPEC_FLOAT()

#define G_IS_PARAM_SPEC_FLOAT(pspec)       (G_TYPE_CHECK_INSTANCE_TYPE ((pspec), G_TYPE_PARAM_FLOAT))

Returns whether the given GParamSpec is of type G_TYPE_PARAM_FLOAT.

pspec : a valid GParamSpec instance

G_PARAM_SPEC_FLOAT()

#define G_PARAM_SPEC_FLOAT(pspec)          (G_TYPE_CHECK_INSTANCE_CAST ((pspec), G_TYPE_PARAM_FLOAT, GParamSpecFloat))

Casts a GParamSpec instance into a GParamSpecFloat.

pspec : a valid GParamSpec instance

G_VALUE_HOLDS_FLOAT()

#define G_VALUE_HOLDS_FLOAT(value)	 (G_TYPE_CHECK_VALUE_TYPE ((value), G_TYPE_FLOAT))

Returns whether the given GValue can hold values of type G_TYPE_FLOAT.

value : a valid GValue structure

G_TYPE_PARAM_FLOAT

#define	G_TYPE_PARAM_FLOAT		(g_param_spec_types[12])

The GType of GParamSpecFloat.

GParamSpecFloat

typedef struct {
  GParamSpec    parent_instance;

  gfloat        minimum;
  gfloat        maximum;
  gfloat        default_value;
  gfloat        epsilon;
} GParamSpecFloat;

A GParamSpec derived structure that contains the meta data for float properties.

GParamSpec parent_instance; | private GParamSpec portion
gfloat minimum; | minimum value for the property specified
gfloat maximum; | maximum value for the property specified
gfloat default_value; | default value for the property specified
gfloat epsilon; | values closer than epsilon will be considered identical by g_param_values_cmp(); the default value is 1e-30.

g_param_spec_float ()

GParamSpec* g_param_spec_float        (const gchar *name, const gchar *nick, const gchar *blurb, gfloat minimum,
                                       gfloat maximum, gfloat default_value, GParamFlags flags);

Creates a new GParamSpecFloat instance specifying a G_TYPE_FLOAT property.
See g_param_spec_internal() for details on property names.

name : | canonical name of the property specified
nick : | nick name for the property specified
blurb : | description of the property specified
minimum : | minimum value for the property specified
maximum : | maximum value for the property specified
default_value : | default value for the property specified
flags : | flags for the property specified
Returns : | a newly created parameter specification

g_value_set_float ()

void        g_value_set_float               (GValue *value, gfloat v_float);

Sets the contents of a G_TYPE_FLOAT GValue to v_float.

value : | a valid GValue of type G_TYPE_FLOAT
v_float : | float value to be set

g_value_get_float ()

gfloat      g_value_get_float               (const GValue *value);

Gets the contents of a G_TYPE_FLOAT GValue.

value : | a valid GValue of type G_TYPE_FLOAT
Returns : | float contents of value

G_IS_PARAM_SPEC_DOUBLE()

#define G_IS_PARAM_SPEC_DOUBLE(pspec)      (G_TYPE_CHECK_INSTANCE_TYPE ((pspec), G_TYPE_PARAM_DOUBLE))

Returns whether the given GParamSpec is of type G_TYPE_PARAM_DOUBLE.

pspec : a valid GParamSpec instance

G_PARAM_SPEC_DOUBLE()

#define G_PARAM_SPEC_DOUBLE(pspec)         (G_TYPE_CHECK_INSTANCE_CAST ((pspec), G_TYPE_PARAM_DOUBLE, GParamSpecDouble))

Casts a GParamSpec instance into a GParamSpecDouble.

pspec : a valid GParamSpec instance

G_VALUE_HOLDS_DOUBLE()

#define G_VALUE_HOLDS_DOUBLE(value)	 (G_TYPE_CHECK_VALUE_TYPE ((value), G_TYPE_DOUBLE))

Returns whether the given GValue can hold values of type G_TYPE_DOUBLE.

value : a valid GValue structure

G_TYPE_PARAM_DOUBLE

#define	G_TYPE_PARAM_DOUBLE		(g_param_spec_types[13])

The GType of GParamSpecDouble.

GParamSpecDouble

typedef struct {
  GParamSpec    parent_instance;

  gdouble       minimum;
  gdouble       maximum;
  gdouble       default_value;
  gdouble       epsilon;
} GParamSpecDouble;

A GParamSpec derived structure that contains the meta data for double properties.

GParamSpec parent_instance; | private GParamSpec portion
gdouble minimum; | minimum value for the property specified
gdouble maximum; | maximum value for the property specified
gdouble default_value; | default value for the property specified
gdouble epsilon; | values closer than epsilon will be considered identical by g_param_values_cmp(); the default value is 1e-90.

g_param_spec_double ()

GParamSpec* g_param_spec_double       (const gchar *name, const gchar *nick, const gchar *blurb, gdouble minimum, gdouble maximum,
                                       gdouble default_value, GParamFlags flags);

Creates a new GParamSpecDouble instance specifying a G_TYPE_DOUBLE property.
See g_param_spec_internal() for details on property names.

name : | canonical name of the property specified
nick : | nick name for the property specified
blurb : | description of the property specified
minimum : | minimum value for the property specified
maximum : | maximum value for the property specified
default_value : | default value for the property specified
flags : | flags for the property specified
Returns : | a newly created parameter specification

g_value_set_double ()

void        g_value_set_double              (GValue *value, gdouble v_double);

Sets the contents of a G_TYPE_DOUBLE GValue to v_double.

value : | a valid GValue of type G_TYPE_DOUBLE
v_double : | double value to be set

g_value_get_double ()

gdouble     g_value_get_double              (const GValue *value);

Gets the contents of a G_TYPE_DOUBLE GValue.

value : | a valid GValue of type G_TYPE_DOUBLE
Returns : | double contents of value

G_IS_PARAM_SPEC_ENUM()

#define G_IS_PARAM_SPEC_ENUM(pspec)        (G_TYPE_CHECK_INSTANCE_TYPE ((pspec), G_TYPE_PARAM_ENUM))

Returns whether the given GParamSpec is of type G_TYPE_PARAM_ENUM.

pspec : a valid GParamSpec instance

G_PARAM_SPEC_ENUM()

#define G_PARAM_SPEC_ENUM(pspec)           (G_TYPE_CHECK_INSTANCE_CAST ((pspec), G_TYPE_PARAM_ENUM, GParamSpecEnum))

Casts a GParamSpec instance into a GParamSpecEnum.

pspec : a valid GParamSpec instance

G_VALUE_HOLDS_ENUM()

#define G_VALUE_HOLDS_ENUM(value)      (G_TYPE_CHECK_VALUE_TYPE ((value), G_TYPE_ENUM))

Returns whether the given GValue can hold values derived from type G_TYPE_ENUM.

value : a valid GValue structure

G_TYPE_PARAM_ENUM

#define	G_TYPE_PARAM_ENUM		   (g_param_spec_types[10])

The GType of GParamSpecEnum.

GParamSpecEnum

typedef struct {
  GParamSpec    parent_instance;

  GEnumClass   *enum_class;
  gint          default_value;
} GParamSpecEnum;

A GParamSpec derived structure that contains the meta data for enum properties.

GParamSpec parent_instance; | private GParamSpec portion
GEnumClass *enum_class; | the GEnumClass for the enum
gint default_value; | default value for the property specified

g_param_spec_enum ()

GParamSpec* g_param_spec_enum         (const gchar *name, const gchar *nick, const gchar *blurb, GType enum_type,
                                       gint default_value, GParamFlags flags);

Creates a new GParamSpecEnum instance specifying a G_TYPE_ENUM property.
See g_param_spec_internal() for details on property names.

name : | canonical name of the property specified
nick : | nick name for the property specified
blurb : | description of the property specified
enum_type : | a GType derived from G_TYPE_ENUM
default_value : | default value for the property specified
flags : | flags for the property specified
Returns : | a newly created parameter specification

g_value_set_enum ()

void        g_value_set_enum           (GValue *value, gint v_enum);

Sets the contents of a G_TYPE_ENUM GValue to v_enum..

value : | a valid GValue whose type is derived from G_TYPE_ENUM
v_enum : | enum value to be set

g_value_get_enum ()

gint        g_value_get_enum          (const GValue *value);

Gets the contents of a G_TYPE_ENUM GValue.

value : | a valid GValue whose type is derived from G_TYPE_ENUM
Returns : | enum contents of value

G_IS_PARAM_SPEC_FLAGS()

#define G_IS_PARAM_SPEC_FLAGS(pspec)       (G_TYPE_CHECK_INSTANCE_TYPE ((pspec), G_TYPE_PARAM_FLAGS))

Returns whether the given GParamSpec is of type G_TYPE_PARAM_FLAGS.

pspec : a valid GParamSpec instance

G_PARAM_SPEC_FLAGS()

#define G_PARAM_SPEC_FLAGS(pspec)       (G_TYPE_CHECK_INSTANCE_CAST ((pspec), G_TYPE_PARAM_FLAGS, GParamSpecFlags))

Casts a GParamSpec instance into a GParamSpecFlags.

pspec : a valid GParamSpec instance

G_VALUE_HOLDS_FLAGS()

#define G_VALUE_HOLDS_FLAGS(value)     (G_TYPE_CHECK_VALUE_TYPE ((value), G_TYPE_FLAGS))

Returns whether the given GValue can hold values derived from type G_TYPE_FLAGS.

value : a valid GValue structure

G_TYPE_PARAM_FLAGS

#define	G_TYPE_PARAM_FLAGS	     (g_param_spec_types[11])

The GType of GParamSpecFlags.

GParamSpecFlags

typedef struct {
  GParamSpec    parent_instance;

  GFlagsClass  *flags_class;
  guint         default_value;
} GParamSpecFlags;

A GParamSpec derived structure that contains the meta data for flags properties.

GParamSpec parent_instance; | private GParamSpec portion
GFlagsClass *flags_class; | the GFlagsClass for the flags
guint default_value; | default value for the property specified

g_param_spec_flags ()

GParamSpec* g_param_spec_flags        (const gchar *name, const gchar *nick, const gchar *blurb, GType flags_type, guint default_value,
                                       GParamFlags flags);

Creates a new GParamSpecEnum instance specifying a G_TYPE_FLAGS property.
See g_param_spec_internal() for details on property names.

name : | canonical name of the property specified
nick : | nick name for the property specified
blurb : | description of the property specified
flags_type : | a GType derived from G_TYPE_FLAGS
default_value : | default value for the property specified
flags : | flags for the property specified
Returns : | a newly created parameter specification

g_value_set_flags ()

void        g_value_set_flags        (GValue *value, guint v_flags);

Sets the contents of a G_TYPE_FLAGS GValue to v_flags.

value : | a valid GValue whose type is derived from G_TYPE_FLAGS
v_flags : | flags value to be set

g_value_get_flags ()

guint       g_value_get_flags         (const GValue *value);

Gets the contents of a G_TYPE_FLAGS GValue.

value : | a valid GValue whose type is derived from G_TYPE_FLAGS
Returns : | flags contents of value

G_IS_PARAM_SPEC_STRING()

#define G_IS_PARAM_SPEC_STRING(pspec)     (G_TYPE_CHECK_INSTANCE_TYPE ((pspec), G_TYPE_PARAM_STRING))

Returns whether the given GParamSpec is of type G_TYPE_PARAM_STRING.

pspec : a valid GParamSpec instance

G_PARAM_SPEC_STRING()

#define G_PARAM_SPEC_STRING(pspec)       (G_TYPE_CHECK_INSTANCE_CAST ((pspec), G_TYPE_PARAM_STRING, GParamSpecString))

Casts a GParamSpec instance into a GParamSpecString.

pspec : a valid GParamSpec instance

G_VALUE_HOLDS_STRING()

#define G_VALUE_HOLDS_STRING(value)	 (G_TYPE_CHECK_VALUE_TYPE ((value), G_TYPE_STRING))

Returns whether the given GValue can hold values of type G_TYPE_STRING.

value : a valid GValue structure

G_TYPE_PARAM_STRING

#define	G_TYPE_PARAM_STRING		(g_param_spec_types[14])

The GType of GParamSpecString.

GParamSpecString

typedef struct {
  GParamSpec    parent_instance;

  gchar        *default_value;
  gchar        *cset_first;
  gchar        *cset_nth;
  gchar         substitutor;
  guint         null_fold_if_empty : 1;
  guint         ensure_non_null : 1;
} GParamSpecString;

A GParamSpec derived structure that contains the meta data for string properties.

GParamSpec parent_instance; | private GParamSpec portion
gchar *default_value; | default value for the property specified
gchar *cset_first; | a string containing the allowed values for the first byte
gchar *cset_nth; | a string containing the allowed values for the subsequent bytes
gchar substitutor; | the replacement byte for bytes which don't match cset_first or cset_nth.
guint null_fold_if_empty : 1; | replace empty string by NULL
guint ensure_non_null : 1; | replace NULL strings by an empty string

gchararray

typedef gchar* gchararray;

A C representable type name for G_TYPE_STRING.

g_param_spec_string ()

GParamSpec* g_param_spec_string       (const gchar *name, const gchar *nick, const gchar *blurb, const gchar *default_value,
                                       GParamFlags flags);

Creates a new GParamSpecString instance.
See g_param_spec_internal() for details on property names.

name : | canonical name of the property specified
nick : | nick name for the property specified
blurb : | description of the property specified
default_value : | default value for the property specified
flags : | flags for the property specified
Returns : | a newly created parameter specification

g_value_set_string ()

void        g_value_set_string                    (GValue *value, const gchar *v_string);

Sets the contents of a G_TYPE_STRING GValue to v_string.

value : | a valid GValue of type G_TYPE_STRING
v_string : | string to be set

g_value_set_static_string ()

void        g_value_set_static_string              (GValue *value, const gchar *v_string);

Sets the contents of a G_TYPE_STRING GValue to v_string. The string is assumed to be static, and is thus not duplicated when setting the GValue.

value : | a valid GValue of type G_TYPE_STRING
v_string : | static string to be set

g_value_take_string ()

void        g_value_take_string                     (GValue *value, gchar *v_string);

Sets the contents of a G_TYPE_STRING GValue to v_string.

value : | a valid GValue of type G_TYPE_STRING
v_string : | duplicated unowned string to be set

g_value_set_string_take_ownership ()

void        g_value_set_string_take_ownership       (GValue *value, gchar *v_string);

Warning

g_value_set_string_take_ownership is deprecated and should not be used in newly-written code. Use g_value_take_string() instead.

This is an internal function introduced mainly for C marshallers.

value : | a valid GValue of type G_TYPE_STRING
v_string : | duplicated unowned string to be set

g_value_get_string ()

const gchar* g_value_get_string           (const GValue *value);

Gets the contents of a G_TYPE_STRING GValue.

value : | a valid GValue of type G_TYPE_STRING
Returns : | string content of value

g_value_dup_string ()

gchar*      g_value_dup_string            (const GValue *value);

Gets a copy the contents of a G_TYPE_STRING GValue.

value : | a valid GValue of type G_TYPE_STRING
Returns : | a newly allocated copy of the string content of value

G_IS_PARAM_SPEC_PARAM()

#define G_IS_PARAM_SPEC_PARAM(pspec)      (G_TYPE_CHECK_INSTANCE_TYPE ((pspec), G_TYPE_PARAM_PARAM))

Returns whether the given GParamSpec is of type G_TYPE_PARAM_PARAM.

pspec : a valid GParamSpec instance

G_PARAM_SPEC_PARAM()

#define G_PARAM_SPEC_PARAM(pspec)        (G_TYPE_CHECK_INSTANCE_CAST ((pspec), G_TYPE_PARAM_PARAM, GParamSpecParam))

Casts a GParamSpec instance into a GParamSpecParam.

pspec : a valid GParamSpec instance

G_VALUE_HOLDS_PARAM()

#define G_VALUE_HOLDS_PARAM(value)	(G_TYPE_CHECK_VALUE_TYPE ((value), G_TYPE_PARAM))

Returns whether the given GValue can hold values derived from type G_TYPE_PARAM.

value : a valid GValue structure

G_TYPE_PARAM_PARAM

#define	G_TYPE_PARAM_PARAM		(g_param_spec_types[15])

The GType of GParamSpecParam.

GParamSpecParam

typedef struct {
  GParamSpec    parent_instance;
} GParamSpecParam;

A GParamSpec derived structure that contains the meta data for G_TYPE_PARAM properties.

GParamSpec parent_instance; private GParamSpec portion

g_param_spec_param ()

GParamSpec* g_param_spec_param     (const gchar *name, const gchar *nick, const gchar *blurb, GType param_type,
                                    GParamFlags flags);

Creates a new GParamSpecParam instance specifying a G_TYPE_PARAM property.
See g_param_spec_internal() for details on property names.

name : | canonical name of the property specified
nick : | nick name for the property specified
blurb : | description of the property specified
param_type : | a GType derived from G_TYPE_PARAM
flags : | flags for the property specified
Returns : | a newly created parameter specification

g_value_set_param ()

void   g_value_set_param       (GValue *value, GParamSpec *param);

Sets the contents of a G_TYPE_PARAM GValue to param.

value : | a valid GValue of type G_TYPE_PARAM
param : | the GParamSpec to be set

g_value_take_param ()

void  g_value_take_param      (GValue *value, GParamSpec *param);

Sets the contents of a G_TYPE_PARAM GValue to param and takes over the ownership of the callers reference to param; the caller doesn't have to unref it any more.

value : | a valid GValue of type G_TYPE_PARAM
param : | the GParamSpec to be set

g_value_set_param_take_ownership ()

void   g_value_set_param_take_ownership    (GValue *value, GParamSpec *param);

Warning

g_value_set_param_take_ownership is deprecated and should not be used in newly-written code. Use g_value_take_param() instead.

This is an internal function introduced mainly for C marshallers.

value : | a valid GValue of type G_TYPE_PARAM
param : | the GParamSpec to be set

g_value_get_param ()

GParamSpec* g_value_get_param           (const GValue *value);

Gets the contents of a G_TYPE_PARAM GValue.

value : | a valid GValue whose type is derived from G_TYPE_PARAM
Returns : | GParamSpec content of value

g_value_dup_param ()

GParamSpec* g_value_dup_param          (const GValue *value);

Gets the contents of a G_TYPE_PARAM GValue, increasing its reference count.

value : | a valid GValue whose type is derived from G_TYPE_PARAM
Returns : | GParamSpec content of value, should be unreferenced when no longer needed.

G_IS_PARAM_SPEC_BOXED()

#define G_IS_PARAM_SPEC_BOXED(pspec)  (G_TYPE_CHECK_INSTANCE_TYPE ((pspec), G_TYPE_PARAM_BOXED))

Returns whether the given GParamSpec is of type G_TYPE_PARAM_BOXED.

pspec : a valid GParamSpec instance

G_PARAM_SPEC_BOXED()

#define G_PARAM_SPEC_BOXED(pspec)  (G_TYPE_CHECK_INSTANCE_CAST ((pspec), G_TYPE_PARAM_BOXED, GParamSpecBoxed))

Casts a GParamSpec instance into a GParamSpecBoxed.

pspec : a valid GParamSpec instance

G_VALUE_HOLDS_BOXED()

#define G_VALUE_HOLDS_BOXED(value) (G_TYPE_CHECK_VALUE_TYPE ((value), G_TYPE_BOXED))

Returns whether the given GValue can hold values derived from type G_TYPE_BOXED.

value : a valid GValue structure

G_TYPE_PARAM_BOXED

#define	G_TYPE_PARAM_BOXED	  (g_param_spec_types[16])

The GType of GParamSpecBoxed.

GParamSpecBoxed

typedef struct {
  GParamSpec    parent_instance;
} GParamSpecBoxed;

A GParamSpec derived structure that contains the meta data for boxed properties.

GParamSpec parent_instance; private GParamSpec portion

g_param_spec_boxed ()

GParamSpec* g_param_spec_boxed       (const gchar *name, const gchar *nick, const gchar *blurb, GType boxed_type,
                                      GParamFlags flags);

Creates a new GParamSpecBoxed instance specifying a G_TYPE_BOXED derived property.
See g_param_spec_internal() for details on property names.

name : | canonical name of the property specified
nick : | nick name for the property specified
blurb : | description of the property specified
boxed_type : | G_TYPE_BOXED derived type of this property
flags : | flags for the property specified
Returns : | a newly created parameter specification

g_value_set_boxed ()

void        g_value_set_boxed               (GValue *value, gconstpointer v_boxed);

Sets the contents of a G_TYPE_BOXED derived GValue to v_boxed.

value : | a valid GValue of G_TYPE_BOXED derived type
v_boxed : | boxed value to be set

g_value_set_static_boxed ()

void        g_value_set_static_boxed        (GValue *value, gconstpointer v_boxed);

Sets the contents of a G_TYPE_BOXED derived GValue to v_boxed. The boxed value is assumed to be static, and is thus not duplicated when setting the GValue.

value : | a valid GValue of G_TYPE_BOXED derived type
v_boxed : | static boxed value to be set

g_value_take_boxed ()

void        g_value_take_boxed            (GValue *value, gconstpointer v_boxed);

Sets the contents of a G_TYPE_BOXED derived GValue to v_boxed and takes over the ownership of the callers reference to v_boxed; the caller doesn't have to unref it any more.

value : | a valid GValue of G_TYPE_BOXED derived type
v_boxed : | duplicated unowned boxed value to be set

g_value_set_boxed_take_ownership ()

void      g_value_set_boxed_take_ownership       (GValue *value, gconstpointer v_boxed);

Warning

g_value_set_boxed_take_ownership is deprecated and should not be used in newly-written code. Use g_value_take_boxed() instead.

This is an internal function introduced mainly for C marshallers.

value : | a valid GValue of G_TYPE_BOXED derived type
v_boxed : | duplicated unowned boxed value to be set

g_value_get_boxed ()

gpointer    g_value_get_boxed               (const GValue *value);

Gets the contents of a G_TYPE_BOXED derived GValue.

value : | a valid GValue of G_TYPE_BOXED derived type
Returns : | boxed contents of value

g_value_dup_boxed ()

gpointer    g_value_dup_boxed             (const GValue *value);

Gets the contents of a G_TYPE_BOXED derived GValue. Upon getting, the boxed value is duplicated and needs to be later freed with g_boxed_free(), e.g. like: g_boxed_free (G_VALUE_TYPE (value), return_value);

value : | a valid GValue of G_TYPE_BOXED derived type
Returns : | boxed contents of value

G_IS_PARAM_SPEC_POINTER()

#define G_IS_PARAM_SPEC_POINTER(pspec)    (G_TYPE_CHECK_INSTANCE_TYPE ((pspec), G_TYPE_PARAM_POINTER))

Returns whether the given GParamSpec is of type G_TYPE_PARAM_POINTER.

pspec : a valid GParamSpec instance

G_PARAM_SPEC_POINTER()

#define G_PARAM_SPEC_POINTER(pspec)      (G_TYPE_CHECK_INSTANCE_CAST ((pspec), G_TYPE_PARAM_POINTER, GParamSpecPointer))

Casts a GParamSpec instance into a GParamSpecPointer.

pspec : a valid GParamSpec instance

G_VALUE_HOLDS_POINTER()

#define G_VALUE_HOLDS_POINTER(value)	 (G_TYPE_CHECK_VALUE_TYPE ((value), G_TYPE_POINTER))

Returns whether the given GValue can hold values of type G_TYPE_POINTER.

value : a valid GValue structure

G_TYPE_PARAM_POINTER

#define	G_TYPE_PARAM_POINTER	       (g_param_spec_types[17])

The GType of GParamSpecPointer.

GParamSpecPointer

typedef struct {
  GParamSpec    parent_instance;
} GParamSpecPointer;

A GParamSpec derived structure that contains the meta data for pointer properties.

GParamSpec parent_instance; private GParamSpec portion

g_param_spec_pointer ()

GParamSpec* g_param_spec_pointer         (const gchar *name, const gchar *nick, const gchar *blurb, GParamFlags flags);

Creates a new GParamSpecPoiner instance specifying a pointer property.
See g_param_spec_internal() for details on property names.

name : | canonical name of the property specified
nick : | nick name for the property specified
blurb : | description of the property specified
flags : | flags for the property specified
Returns : | a newly created parameter specification

g_value_set_pointer ()

void        g_value_set_pointer          (GValue *value, gpointer v_pointer);

Sets the contents of a pointer GValue to v_pointer.

value : | a valid GValue of G_TYPE_POINTER
v_pointer : | pointer value to be set

g_value_get_pointer ()

gpointer    g_value_get_pointer          (const GValue *value);

Gets the contents of a pointer GValue.

value : | a valid GValue of G_TYPE_POINTER
Returns : | pointer contents of value

G_IS_PARAM_SPEC_OBJECT()

#define G_IS_PARAM_SPEC_OBJECT(pspec)   (G_TYPE_CHECK_INSTANCE_TYPE ((pspec), G_TYPE_PARAM_OBJECT))

Returns whether the given GParamSpec is of type G_TYPE_PARAM_OBJECT.

pspec : a valid GParamSpec instance

G_PARAM_SPEC_OBJECT()

#define G_PARAM_SPEC_OBJECT(pspec)     (G_TYPE_CHECK_INSTANCE_CAST ((pspec), G_TYPE_PARAM_OBJECT, GParamSpecObject))

Casts a GParamSpec instance into a GParamSpecObject.

pspec : a valid GParamSpec instance

G_VALUE_HOLDS_OBJECT()

#define G_VALUE_HOLDS_OBJECT(value) (G_TYPE_CHECK_VALUE_TYPE ((value), G_TYPE_OBJECT))

Returns whether the given GValue can hold values derived from type G_TYPE_OBJECT.

value : a valid GValue structure

G_TYPE_PARAM_OBJECT

#define	G_TYPE_PARAM_OBJECT	   (g_param_spec_types[19])

The GType of GParamSpecObject.

GParamSpecObject

typedef struct {
  GParamSpec    parent_instance;
} GParamSpecObject;

A GParamSpec derived structure that contains the meta data for object properties.

GParamSpec parent_instance; private GParamSpec portion

g_param_spec_object ()

GParamSpec* g_param_spec_object       (const gchar *name, const gchar *nick, const gchar *blurb, GType object_type,
                                       GParamFlags flags);

Creates a new GParamSpecBoxed instance specifying a G_TYPE_OBJECT derived property.
See g_param_spec_internal() for details on property names.

name : | canonical name of the property specified
nick : | nick name for the property specified
blurb : | description of the property specified
object_type : | G_TYPE_OBJECT derived type of this property
flags : | flags for the property specified
Returns : | a newly created parameter specification

g_value_set_object ()

void    g_value_set_object                  (GValue *value, gpointer v_object);

Sets the contents of a G_TYPE_OBJECT derived GValue to v_object.

value : | a valid GValue of G_TYPE_OBJECT derived type
v_object : | object value to be set

g_value_take_object ()

void   g_value_take_object                  (GValue *value, gpointer v_object);

Sets the contents of a G_TYPE_OBJECT derived GValue to v_object and takes over the ownership of the callers reference to v_object; the caller doesn't have to unref it any more.

value : | a valid GValue of G_TYPE_OBJECT derived type
v_object : | object value to be set

g_value_set_object_take_ownership ()

void  g_value_set_object_take_ownership     (GValue *value, gpointer v_object);

Warning

g_value_set_object_take_ownership is deprecated and should not be used in newly-written code. Use g_value_take_object() instead.

This is an internal function introduced mainly for C marshallers.

value : | a valid GValue of G_TYPE_OBJECT derived type
v_object : | object value to be set

g_value_get_object ()

gpointer    g_value_get_object            (const GValue *value);

Gets the contents of a G_TYPE_OBJECT derived GValue.

value : | a valid GValue of G_TYPE_OBJECT derived type
Returns : | object contents of value

g_value_dup_object ()

GObject*    g_value_dup_object            (const GValue *value);

Gets the contents of a G_TYPE_OBJECT derived GValue, increasing its reference count.

value : | a valid GValue whose type is derived from G_TYPE_OBJECT
Returns : | object content of value, should be unreferenced when no longer needed.

G_IS_PARAM_SPEC_UNICHAR()

#define G_IS_PARAM_SPEC_UNICHAR(pspec)    (G_TYPE_CHECK_INSTANCE_TYPE ((pspec), G_TYPE_PARAM_UNICHAR))

Returns whether the given GParamSpec is of type G_TYPE_PARAM_UNICHAR.

pspec : a valid GParamSpec instance

G_PARAM_SPEC_UNICHAR()

#define G_PARAM_SPEC_UNICHAR(pspec)      (G_TYPE_CHECK_INSTANCE_CAST ((pspec), G_TYPE_PARAM_UNICHAR, GParamSpecUnichar))

Casts a GParamSpec instance into a GParamSpecUnichar.

pspec : a valid GParamSpec instance

G_TYPE_PARAM_UNICHAR

#define	G_TYPE_PARAM_UNICHAR		 (g_param_spec_types[9])

The GType of GParamSpecUnichar.

GParamSpecUnichar

typedef struct {
  GParamSpec    parent_instance;

  gunichar      default_value;
} GParamSpecUnichar;

A GParamSpec derived structure that contains the meta data for unichar (unsigned integer) properties.

GParamSpec parent_instance; | private GParamSpec portion
gunichar default_value; | default value for the property specified

g_param_spec_unichar ()

GParamSpec* g_param_spec_unichar          (const gchar *name, const gchar *nick, const gchar *blurb, gunichar default_value,
                                           GParamFlags flags);

Creates a new GParamSpecUnichar instance specifying a G_TYPE_UINT property. GValue structures for this property can be accessed with g_value_set_uint() and g_value_get_uint().

See g_param_spec_internal() for details on property names.

name : | canonical name of the property specified
nick : | nick name for the property specified
blurb : | description of the property specified
default_value : | default value for the property specified
flags : | flags for the property specified
Returns : | a newly created parameter specification

G_IS_PARAM_SPEC_VALUE_ARRAY()

#define G_IS_PARAM_SPEC_VALUE_ARRAY(pspec) (G_TYPE_CHECK_INSTANCE_TYPE ((pspec), G_TYPE_PARAM_VALUE_ARRAY))

Returns whether the given GParamSpec is of type G_TYPE_PARAM_VALUE_ARRAY.

pspec : a valid GParamSpec instance

G_PARAM_SPEC_VALUE_ARRAY()

#define G_PARAM_SPEC_VALUE_ARRAY(pspec)  (G_TYPE_CHECK_INSTANCE_CAST ((pspec), G_TYPE_PARAM_VALUE_ARRAY, GParamSpecValueArray))

Casts a GParamSpec instance into a GParamSpecValueArray.

pspec : a valid GParamSpec instance

G_TYPE_PARAM_VALUE_ARRAY

#define	G_TYPE_PARAM_VALUE_ARRAY	(g_param_spec_types[18])

The GType of GParamSpecValueArray.

GParamSpecValueArray

typedef struct {
  GParamSpec    parent_instance;
  GParamSpec   *element_spec;
  guint		fixed_n_elements;
} GParamSpecValueArray;

A GParamSpec derived structure that contains the meta data for GValueArray properties.

GParamSpec parent_instance; | private GParamSpec portion
GParamSpec *element_spec; | a GParamSpec describing the elements contained in arrays of this property, may be NULL
guint fixed_n_elements; | if greater than 0, arrays of this property will always have this many elements

g_param_spec_value_array ()

GParamSpec* g_param_spec_value_array      (const gchar *name, const gchar *nick, const gchar *blurb, GParamSpec *element_spec,
                                           GParamFlags flags);

Creates a new GParamSpecValueArray instance specifying a G_TYPE_VALUE_ARRAY property. G_TYPE_VALUE_ARRAY is a G_TYPE_BOXED type, as such, GValue structures for this property can be accessed with g_value_set_boxed() and g_value_get_boxed().

See g_param_spec_internal() for details on property names.

name : | canonical name of the property specified
nick : | nick name for the property specified
blurb : | description of the property specified
element_spec : | a GParamSpec describing the elements contained in arrays of this property, may be NULL
flags : | flags for the property specified
Returns : | a newly created parameter specification

G_IS_PARAM_SPEC_OVERRIDE()

#define G_IS_PARAM_SPEC_OVERRIDE(pspec)  (G_TYPE_CHECK_INSTANCE_TYPE ((pspec), G_TYPE_PARAM_OVERRIDE))

Returns whether the given GParamSpec is of type G_TYPE_PARAM_OBJECT.

pspec : a GParamSpec

G_PARAM_SPEC_OVERRIDE()

#define G_PARAM_SPEC_OVERRIDE(pspec)    (G_TYPE_CHECK_INSTANCE_CAST ((pspec), G_TYPE_PARAM_OVERRIDE, GParamSpecOverride))

Casts a GParamSpec into a GParamSpecObject.

pspec : a GParamSpec

G_TYPE_PARAM_OVERRIDE

#define	G_TYPE_PARAM_OVERRIDE	       (g_param_spec_types[20])

The GType of GParamSpecOverride.

GParamSpecOverride

typedef struct {
} GParamSpecOverride;

This is a type of GParamSpec type that simply redirects operations to another paramspec. All operations other than getting or setting the value are redirected, including accessing the nick and blurb, validating a value, and so forth. See g_param_spec_get_redirect_target() for retrieving the overidden property. GParamSpecOverride is used in implementing g_object_class_override_property(), and will not be directly useful unless a new base class type similar to CObject is implemented.

g_param_spec_override ()

GParamSpec* g_param_spec_override      (const gchar *name, GParamSpec *overridden);

Creates a new property of type GParamSpecOverride. This is used to direct operations to another paramspec, and will not be directly useful unless a new base class type similar to CObject is implemented.

name : | the name of the property.
overridden : | The property that is being overridden
Returns : | the newly created GParamSpec

G_IS_PARAM_SPEC_GTYPE()

#define G_IS_PARAM_SPEC_GTYPE(pspec)       (G_TYPE_CHECK_INSTANCE_TYPE ((pspec), G_TYPE_PARAM_GTYPE))

Returns whether the given GParamSpec is of type G_TYPE_PARAM_GTYPE.

pspec : a GParamSpec

G_PARAM_SPEC_GTYPE()

#define G_PARAM_SPEC_GTYPE(pspec)          (G_TYPE_CHECK_INSTANCE_CAST ((pspec), G_TYPE_PARAM_GTYPE, GParamSpecGType))

Casts a GParamSpec into a GParamSpecGType.

pspec : a GParamSpec

G_TYPE_PARAM_GTYPE

#define	G_TYPE_PARAM_GTYPE		   (g_param_spec_types[21])

The GType of GParamSpecGType.

GParamSpecGType

typedef struct {
  GParamSpec    parent_instance;
  GType         is_a_type;
} GParamSpecGType;

A GParamSpec derived structure that contains the meta data for GType properties.

GParamSpec parent_instance; | private GParamSpec portion
GType is_a_type; | a GType whose subtypes can occur as values

g_param_spec_gtype ()

GParamSpec* g_param_spec_gtype    (const gchar *name, const gchar *nick, const gchar *blurb, GType is_a_type, GParamFlags flags);

Creates a new GParamSpecGType instance specifying a G_TYPE_GTYPE property.

See g_param_spec_internal() for details on property names.

name : | canonical name of the property specified
nick : | nick name for the property specified
blurb : | description of the property specified
is_a_type : | a GType whose subtypes are allowed as values of the property (use G_TYPE_NONE for any type)
flags : | flags for the property specified
Returns : | a newly created parameter specification

See Also

GParamSpec, GValue, g_object_class_install_property().

Feedback

For additional information or queries on this page send feedback


GObject

Name

GObject — The base object type.

Library

gobject.lib

Synopsis

#include <glib-object.h>
GObject;
GObjectClass;
GObjectConstructParam;
void        (*GObjectGetPropertyFunc)       (GObject *object, guint property_id, GValue *value, GParamSpec *pspec);
void        (*GObjectSetPropertyFunc)       (GObject *object, guint property_id, const GValue *value, GParamSpec *pspec);
void        (*GObjectFinalizeFunc)          (GObject *object);
#define     G_TYPE_IS_OBJECT                (type)
#define     G_OBJECT                        (object)
#define     G_IS_OBJECT                     (object)
#define     G_OBJECT_CLASS                  (class)
#define     G_IS_OBJECT_CLASS               (class)
#define     G_OBJECT_GET_CLASS              (object)
#define     G_OBJECT_TYPE                   (object)
#define     G_OBJECT_TYPE_NAME              (object)
#define     G_OBJECT_CLASS_TYPE             (class)
#define     G_OBJECT_CLASS_NAME             (class)
void        g_object_class_install_property (GObjectClass *oclass, guint property_id, GParamSpec *pspec);
GParamSpec* g_object_class_find_property    (GObjectClass *oclass, const gchar *property_name);
GParamSpec** g_object_class_list_properties (GObjectClass *oclass, guint *n_properties);
void        g_object_class_override_property  (GObjectClass *oclass, guint property_id, const gchar *name);
void        g_object_interface_install_property   (gpointer g_iface, GParamSpec *pspec);
GParamSpec* g_object_interface_find_property      (gpointer g_iface, const gchar *property_name);
GParamSpec** g_object_interface_list_properties   (gpointer g_iface, guint *n_properties_p);
gpointer    g_object_new                    (GType object_type, const gchar *first_property_name, ...);
gpointer    g_object_newv                   (GType object_type, guint n_parameters, GParameter *parameters);
            GParameter;
gpointer    g_object_ref                    (gpointer object);
void        g_object_unref                  (gpointer object);

gpointer    g_object_ref_sink               (gpointer object);
gboolean    g_object_is_floating            (gpointer object);
void        g_object_force_floating         (GObject *object);
void        (*GWeakNotify)                  (gpointer data, GObject *where_the_object_was);
void        g_object_weak_ref               (GObject *object, GWeakNotify notify, gpointer data);
void        g_object_weak_unref             (GObject *object, GWeakNotify notify, gpointer data);
void        g_object_add_weak_pointer       (GObject *object, gpointer *weak_pointer_location);
void        g_object_remove_weak_pointer    (GObject *object, gpointer *weak_pointer_location);
void        (*GToggleNotify)                (gpointer data, GObject *object, gboolean is_last_ref);
void        g_object_add_toggle_ref         (GObject *object, GToggleNotify notify, gpointer data);
void        g_object_remove_toggle_ref      (GObject *object, GToggleNotify notify, gpointer data);
gpointer    g_object_connect                (gpointer object, const gchar *signal_spec, ...);
void        g_object_disconnect             (gpointer object, const gchar *signal_spec, ...);
void        g_object_set                    (gpointer object, const gchar *first_property_name, ...);
void        g_object_get                    (gpointer object, const gchar *first_property_name, ...);
void        g_object_notify                 (GObject *object, const gchar *property_name);
void        g_object_freeze_notify          (GObject *object);
void        g_object_thaw_notify            (GObject *object);
gpointer    g_object_get_data               (GObject *object, const gchar *key);
void        g_object_set_data               (GObject *object, const gchar *key, gpointer data);
void        g_object_set_data_full          (GObject *object, const gchar *key, gpointer data, GDestroyNotify destroy);
gpointer    g_object_steal_data             (GObject *object, const gchar *key);
gpointer    g_object_get_qdata              (GObject *object, GQuark quark);
void        g_object_set_qdata              (GObject *object, GQuark quark, gpointer data);
void        g_object_set_qdata_full         (GObject *object, GQuark quark, gpointer data, GDestroyNotify destroy);
gpointer    g_object_steal_qdata            (GObject *object, GQuark quark);
void        g_object_set_property           (GObject *object, const gchar *property_name, const GValue *value);
void        g_object_get_property           (GObject *object, const gchar *property_name, GValue *value);
GObject*    g_object_new_valist             (GType object_type, const gchar *first_property_name, va_list var_args);
void        g_object_set_valist             (GObject *object, const gchar *first_property_name, va_list var_args);
void        g_object_get_valist             (GObject *object, const gchar *first_property_name, va_list var_args);
void        g_object_watch_closure          (GObject *object, GClosure *closure);
void        g_object_run_dispose            (GObject *object);
#define     G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec)

Detailed Description

GObject is the fundamental type providing the common attributes and methods for all object types in GTK+, Pango and other libraries based on GObject. The GObject class provides methods for object construction and destruction, property access methods, and signal support. Signals are described in detail in Signals(3).

The initial reference a GObject is created with is flagged as a floating reference. This means that it is not specifically claimed to be "owned" by any code portion. The main motivation for providing floating references is C convenience. In particular, it allowes code to be written as:

Example 1.

  container = create_container();
  container_add_child (container, create_child());

If container_add_child() will g_object_ref_sink() the passed in child, no reference of the newly created child is leaked. Without floating references, container_add_child() can only g_object_ref() the new child, so to implement this code without reference leaks, it would have to be written as:

Example 2.

  Child *child;
  container = create_container();
  child = create_child();
  container_add_child (container, child);
  g_object_unref (child);

The floating reference can be converted into an ordinary reference by calling g_object_ref_sink(). For already sunken objects (objects that do not have a floating reference anymore), g_object_ref_sink() is equivalent to g_object_ref() and returns a new reference. Since floating references are useful allmost exclusively for C convenience, language bindings that provide automated reference and memory ownership maintenance (such as smart pointers or garbage collection) therefore do not need to expose floating references in their API.

Some object implementations may need to save an objects floating state across certain code portions (an example is GtkMenu), to achive this, the following sequence can be used:

Example 3.

  /* save floating state */
  gboolean was_floating = g_object_is_floating (object);
  g_object_ref_sink (object);
  /* protected code portion */
  ...;
  /* restore floating state */
  if (was_floating)
    g_object_force_floating (object);
  g_obejct_unref (object); /* release previously acquired reference */

Object Hierarchy

  GObject
   +----GTypeModule

Signals

"notify"    void    user_function   (GObject    *gobject, GParamSpec *arg1, gpointer    user_data)   : Run first / No recursion / Has details / Action / No hooks

Details

GObject

typedef struct _GObject GObject;

All the fields in the GObject structure are private to the GObject implementation and should never be accessed directly.

GObjectClass

typedef struct {
  GTypeClass   g_type_class;

  /* overridable methods */
  GObject*   (*constructor)     (GType   type, guint  n_construct_properties, GObjectConstructParam *construct_properties);
  void       (*set_property)	(GObject *object, guint property_id, const GValue *value, GParamSpec *pspec);
  void       (*get_property)	(GObject *object, guint property_id, GValue *value, GParamSpec *pspec);
  void       (*dispose)		(GObject *object);
  void       (*finalize)	(GObject *object);

  /* seldomly overidden */
  void       (*dispatch_properties_changed)   (GObject *object, guint n_pspecs, GParamSpec  **pspecs);

  /* signals */
  void	     (*notify)			(GObject *object, GParamSpec *pspec);
} GObjectClass;

The class structure for the GObject type.

Example 4. Implementing singletons using a constructor

static MySingleton *the_singleton = NULL;

static GObject*
my_singleton_constructor (GType   type, guint  n_construct_params, GObjectConstructParam *construct_params)
{
  GObject *object;

  if (!the_singleton)
    {
      object = G_OBJECT_CLASS (parent_class)->constructor (type, n_construct_params, construct_params);
      the_singleton = MY_SINGLETON (object);
    }
  else
    object = g_object_ref (G_OBJECT (the_singleton));
  return object;
}
GTypeClass g_type_class; | the parent class
constructor () | the constructor function is called by g_object_new() to complete the object initialization after all the construction properties are set. The first thing a constructor implementation must do is chain up to the constructor of the parent class. Overriding constructor should be rarely needed, e.g. to handle construct properties, or to implement singletons.
set_property () | the generic setter for all properties of this type. Should be overridden for every type with properties. Implementations of set_property do not need to emit property change notification explicitly, this is handled by the type system.
get_property () | the generic getter for all properties of this type. Should be overridden for every type with properties.
dispose () | the dispose function is supposed to drop all references to other objects, but keep the instance otherwise intact, so that client method invocations still work. It may be run multiple times (due to reference loops). Before returning, dispose should chain up to the dispose method of the parent class.
finalize () | instance finalization function, should finish the finalization of the instance begun in dispose and chain up to the finalize method of the parent class.
dispatch_properties_changed () | emits property change notification for a bunch of properties. Overriding dispatch_properties_changed should be rarely needed.
notify () | the class closure for the notify signal

GObjectConstructParam

typedef struct {
  GParamSpec *pspec;
  GValue     *value;
} GObjectConstructParam;

The GObjectConstructParam struct is an auxiliary structure used to hand GParamSpec/GValue pairs to the constructor of a GObjectClass.

GParamSpec *pspec; | the GParamSpec of the construct parameter
GValue *value; | the value to set the parameter to

GObjectGetPropertyFunc ()

void        (*GObjectGetPropertyFunc)       (GObject *object, guint property_id, GValue *value, GParamSpec *pspec);

The type of the get_property function of GObjectClass.

object : | a GObject
property_id : | the numeric id under which the property was registered with g_object_class_install_property().
value : | a GValue to return the property value in
pspec : | the GParamSpec describing the property

GObjectSetPropertyFunc ()

void        (*GObjectSetPropertyFunc)       (GObject *object, guint property_id, const GValue *value, GParamSpec *pspec);

The type of the set_property function of GObjectClass.

object : | a GObject
property_id : | the numeric id under which the property was registered with g_object_class_install_property().
value : | the new value for the property
pspec : | the GParamSpec describing the property

GObjectFinalizeFunc ()

void        (*GObjectFinalizeFunc)          (GObject *object);

The type of the finalize function of GObjectClass.

object : the GObject being finalized

G_TYPE_IS_OBJECT()

#define G_TYPE_IS_OBJECT(type)      (G_TYPE_FUNDAMENTAL (type) == G_TYPE_OBJECT)

Returns a boolean value of FALSE or TRUE indicating whether the passed in type id is a G_TYPE_OBJECT or derived from it.

type : | Type id to check for is a G_TYPE_OBJECT relationship.
Returns : | FALSE or TRUE, indicating whether type is a G_TYPE_OBJECT.

G_OBJECT()

#define G_OBJECT(object)            (G_TYPE_CHECK_INSTANCE_CAST ((object), G_TYPE_OBJECT, GObject))

Casts a GObject or derived pointer into a (GObject*) pointer. Depending on the current debugging level, this function may invoke certain runtime checks to identify invalid casts.

object : Object which is subject to casting.

G_IS_OBJECT()

#define G_IS_OBJECT(object)         (G_TYPE_CHECK_INSTANCE_TYPE ((object), G_TYPE_OBJECT))

Checks whether a valid GTypeInstance pointer is of type G_TYPE_OBJECT.

object : Instance to check for being a G_TYPE_OBJECT.

G_OBJECT_CLASS()

#define G_OBJECT_CLASS(class)       (G_TYPE_CHECK_CLASS_CAST ((class), G_TYPE_OBJECT, GObjectClass))

Casts a derived GObjectClass structure into a GObjectClass structure.

class : a valid GObjectClass

G_IS_OBJECT_CLASS()

#define G_IS_OBJECT_CLASS(class)    (G_TYPE_CHECK_CLASS_TYPE ((class), G_TYPE_OBJECT))

Checks whether class "is a" valid GObjectClass structure of type G_TYPE_OBJECT or derived.

class : a GObjectClass

G_OBJECT_GET_CLASS()

#define G_OBJECT_GET_CLASS(object)  (G_TYPE_INSTANCE_GET_CLASS ((object), G_TYPE_OBJECT, GObjectClass))

Returns the class structure associated to a GObject instance.

object : a GObject instance.

G_OBJECT_TYPE()

#define G_OBJECT_TYPE(object)       (G_TYPE_FROM_INSTANCE (object))

Returns the type id of an object.

object : | Object to return the type id for.
Returns : | Type id of object.

G_OBJECT_TYPE_NAME()

#define G_OBJECT_TYPE_NAME(object)  (g_type_name (G_OBJECT_TYPE (object)))

Returns the name of an object's type.

object : | Object to return the type name for.
Returns : | Type name of object. The string is owned by the type system and should not be freed.

G_OBJECT_CLASS_TYPE()

#define G_OBJECT_CLASS_TYPE(class)  (G_TYPE_FROM_CLASS (class))

Returns the type id of a class structure.

class : | a valid GObjectClass
Returns : | Type id of class.

G_OBJECT_CLASS_NAME()

#define G_OBJECT_CLASS_NAME(class)  (g_type_name (G_OBJECT_CLASS_TYPE (class)))

Returns the name of a class structure's type.

class : | a valid GObjectClass
Returns : | Type name of class. The string is owned by the type system and should not be freed.

g_object_class_install_property ()

void    g_object_class_install_property     (GObjectClass *oclass, guint property_id, GParamSpec *pspec);

Installs a new property. This is usually done in the class initializer.

oclass : | a GObjectClass
property_id : | the id for the new property
pspec : | the GParamSpec for the new property

g_object_class_find_property ()

GParamSpec* g_object_class_find_property    (GObjectClass *oclass, const gchar *property_name);

Looks up the GParamSpec for a property of a class.

oclass : | a GObjectClass
property_name : | the name of the property to look up
Returns : | the GParamSpec for the property, or NULL if the class does not have a property of that name

g_object_class_list_properties ()

GParamSpec** g_object_class_list_properties   (GObjectClass *oclass, guint *n_properties);

Returns an array of GParamSpec* for all properties of a class.

oclass : | a GObjectClass
n_properties : | return location for the length of the returned array
Returns : | an array of GParamSpec* which should be freed after use

g_object_class_override_property ()

void        g_object_class_override_property    (GObjectClass *oclass, guint property_id, const gchar *name);

Registers property_id as referring to a property with the name name in a parent class or in an interface implemented by oclass. This allows this class to override a property implementation in a parent class or to provide the implementation of a property from an interface.

Note

Note: Internally, overriding is implemented by creating a property of type GParamSpecOverride; generally operations that query the properties of the object class, such as g_object_class_find_property() or g_object_class_list_properties() will return the overridden property. However, in one case, the construct_properties argument of the constructor virtual function, the GParamSpecOverride is passed instead, so that the param_id field of the GParamSpec will be correct. For virtually all uses, this makes no difference. In order to get the overridden property,call g_param_spec_get_redirect_target().

oclass : | a GObjectClass
property_id : | the new property ID
name : | the name of a property registered in a parent class or in an interface of this class.

g_object_interface_install_property ()

void        g_object_interface_install_property        (gpointer g_iface, GParamSpec *pspec);

Adds a property to an interface; this is only useful for interfaces that are added to GObject-derived types. Adding a property to an interface forces all objects classes with that interface to have a compatible property. The compatible property could be a newly created GParamSpec, but normally g_object_class_override_property() will be used so that the object class only needs to provide an implementation and inherits the property description, default value, bounds, and so forth from the interface property.

This function is meant to be called from the interface's default vtable initialization function (the class_init member of GTypeInfo.) It must not be called after after class_init has been called for any object types implementing this interface.

g_iface : | any interface vtable for the interface, or the default vtable for the interface.
pspec : | the GParamSpec for the new property

g_object_interface_find_property ()

GParamSpec* g_object_interface_find_property         (gpointer g_iface, const gchar *property_name);

Finds the GParamSpec with the given name for an interface. Generally, the interface vtable passed in as g_iface will be the default vtable from g_type_default_interface_ref(), or, if the interface has already been loaded, g_type_default_interface_peek().

g_iface : | any interface vtable for the interface, or the default vtable for the interface
property_name : | name of a property to lookup.
Returns : | the GParamSpec for the property of the interface with the name property_name, or NULL if no such property exists.

g_object_interface_list_properties ()

GParamSpec** g_object_interface_list_properties      (gpointer g_iface, guint *n_properties_p);

Lists the properties of an interface. Generally, the interface vtable passed in as g_iface will be the default vtable from g_type_default_interface_ref(), or, if the interface has already been loaded, g_type_default_interface_peek().

g_iface : | any interface vtable for the interface, or the default vtable for the interface
n_properties_p : | location to store number of properties returned.
Returns : | a pointer to an array of pointers to GParamSpec structures. The paramspecs are owned by GLib, but the array should be freed with g_free() when done with it.

g_object_new ()

gpointer    g_object_new              (GType object_type, const gchar *first_property_name, ...);

Creates a new instance of a GObject subtype and sets its properties. Construction parameters (see G_PARAM_CONSTRUCT, G_PARAM_CONSTRUCT_ONLY) which are not explicitly specified are set to their default values.

object_type : | the type id of the GObject subtype to instantiate
first_property_name : | the name of the first property
... : | the value of the first property, followed optionally by more name/value pairs, followed by NULL
Returns : | a new instance of object_type

g_object_newv ()

gpointer    g_object_newv             (GType object_type, guint n_parameters, GParameter *parameters);

Creates a new instance of a GObject subtype and sets its properties. Construction parameters (see G_PARAM_CONSTRUCT, G_PARAM_CONSTRUCT_ONLY) which are not explicitly specified are set to their default values.

object_type : | the type id of the GObject subtype to instantiate
n_parameters : | the length of the parameters array
parameters : | an array of GParameter
Returns : | a new instance of object_type

GParameter

typedef struct {
  const gchar *name;
  GValue       value;
} GParameter;

The GParameter struct is an auxiliary structure used to hand parameter name/value pairs to g_object_newv().

const gchar *name; | the parameter name
GValue value; | the parameter value

g_object_ref ()

gpointer    g_object_ref                    (gpointer object);

Increases the reference count of object.

object : | a GObject
Returns : | object

g_object_unref ()

void        g_object_unref                  (gpointer object);

Decreases the reference count if object. When its reference count drops to 0, the object is finalized (i.e. its memory is freed).

object : a GObject

g_object_ref_sink ()

gpointer    g_object_ref_sink               (gpointer object);

Increase the reference count of object, and possibly remove the floating reference, if object has a floating reference.

object : | a GObject
Returns : | object

g_object_is_floating ()

gboolean    g_object_is_floating            (gpointer object);

Checks wether object has a floating reference.

object : | a GObject
Returns : | TRUE if object has a floating reference

g_object_force_floating ()

void       g_object_force_floating         (GObject *object);

This function is intended for GObject implementations to re-enforce a floating object reference. Doing this is seldomly required, all GObjects are created with a floating reference which usually just needs to be sunken by calling g_object_ref_sink().

object : a GObject

GWeakNotify ()

void        (*GWeakNotify)                  (gpointer data, GObject *where_the_object_was);

A GWeakNotify function can be added to an object as a callback that gets triggered when the object is finalized. Since the object is already being finalized when the GWeakNotify is called, there's not much that can be done with the object, apart from e.g. using its adress as hash-index or the like.

data : | data that was provided when the weak reference was established
where_the_object_was : | the object being finalized

g_object_weak_ref ()

void        g_object_weak_ref               (GObject *object, GWeakNotify notify, gpointer data);

Adds a weak reference callback to an object. Weak references are used for notification when an object is finalized. They are called "weak references" because they allow to safely hold a pointer to an object without calling g_object_ref() (g_object_ref() adds a strong reference, that is, forces the object to stay alive).

object : | GObject to reference weakly
notify : | callback to invoke before the object is freed
data : | extra data to pass to notify

g_object_weak_unref ()

void        g_object_weak_unref             (GObject *object, GWeakNotify notify, gpointer data);

Removes a weak reference callback to an object.

object : | GObject to remove a weak reference from
notify : | callback to search for
data : | data to search for

g_object_add_weak_pointer ()

void        g_object_add_weak_pointer       (GObject *object, gpointer *weak_pointer_location);

Adds a weak reference from weak_pointer to object to indicate that the pointer located at weak_pointer_location is only valid during the lifetime of object. When the object is finalized, weak_pointer will be set to NULL.

object : | The object that should be weak referenced.
weak_pointer_location : | The memory address of a pointer.

g_object_remove_weak_pointer ()

void        g_object_remove_weak_pointer    (GObject *object, gpointer *weak_pointer_location);

Removes a weak reference from object that was previously added using g_object_add_weak_pointer(). The weak_pointer_location has to match the one used with g_object_add_weak_pointer().

object : | The object that is weak referenced.
weak_pointer_location : | The memory address of a pointer.

GToggleNotify ()

void        (*GToggleNotify)           (gpointer data, GObject *object, gboolean is_last_ref);

A callback function used for notification when the state of a toggle reference changes. See g_object_add_toggle_ref().

data : | Callback data passed to g_object_add_toggle_ref()
object : | The object on which g_object_add_toggle_ref() was called.
is_last_ref : | TRUE if the toggle reference is now the last reference to the object. FALSE if the toggle reference was the last reference and there are now other references.

g_object_add_toggle_ref ()

void        g_object_add_toggle_ref         (GObject *object, GToggleNotify notify, gpointer data);

Increases the reference count of the object by one and sets a callback to be called when all other references to the object are dropped, or when this is already the last reference to the object and another reference is established.

This functionality is intended for binding object to a proxy object managed by another memory manager. This is done with two paired references: the strong reference added by g_object_add_toggle_ref() and a reverse reference to the proxy object which is either a strong reference or weak reference.

The setup is that when there are no other references to object, only a weak reference is held in the reverse direction from object to the proxy object, but when there are other references held to object, a strong reference is held. The notify callback is called when the reference from object to the proxy object should be toggled from strong to weak (is_last_ref true) or weak to strong (is_last_ref false).

Since a (normal) reference must be held to the object before calling g_object_toggle_ref(), the initial state of the reverse link is always strong.

Multiple toggle references may be added to the same gobject, however if there are multiple toggle references to an object, none of them will ever be notified until all but one are removed. For this reason, use a toggle reference only if there is an important state in the proxy object.

object : | a GObject
notify : | a function to call when this reference is the last reference to the object, or is no longer the last reference.
data : | data to pass to notify

g_object_remove_toggle_ref ()

void        g_object_remove_toggle_ref      (GObject *object, GToggleNotify notify, gpointer data);

Removes a reference added with g_object_add_toggle_ref(). The reference count of the object is decreased by one.

object : | a GObject
notify : | a function to call when this reference is the last reference to the object, or is no longer the last reference.
data : | data to pass to notify

g_object_connect ()

gpointer    g_object_connect        (gpointer object, const gchar *signal_spec, ...);

A convenient function to connect multiple signals at once.
The signal specs expected by this function have the form "modifier::signal_name", where modifier can be one of the following:

signal | equivalent to g_signal_connect_data (...)
object_signal, object-signal | equivalent to g_signal_connect_object (...)
swapped_signal, swapped-signal | equivalent to g_signal_connect_data (..., G_CONNECT_SWAPPED)
swapped_object_signal, swapped-object-signal | equivalent to g_signal_connect_object (..., G_CONNECT_SWAPPED)
signal_after, signal-after | equivalent to g_signal_connect_data (..., G_CONNECT_AFTER)
object_signal_after, object-signal-after | equivalent to g_signal_connect_object (..., G_CONNECT_AFTER)
swapped_signal_after, swapped-signal-after | equivalent to g_signal_connect_data (..., G_CONNECT_SWAPPED | G_CONNECT_AFTER)
swapped_object_signal_after, swapped-object-signal-after | equivalent to g_signal_connect_object (..., G_CONNECT_SWAPPED | G_CONNECT_AFTER)

menu->toplevel = g_object_connect (g_object_new (GTK_TYPE_WINDOW, "type", GTK_WINDOW_POPUP, "child", menu, NULL),
                   "signal::event", gtk_menu_window_event, menu, "signal::size_request",
                                   gtk_menu_window_size_request, menu, "signal::destroy", gtk_widget_destroyed,
                                   &menu->toplevel, NULL);
object : | a GObject
signal_spec : | the spec for the first signal
... : | GCallback for the first signal, followed by data for the first signal, followed optionally by more signal spec/callback/data triples, followed by NULL
Returns : | object

g_object_disconnect ()

void        g_object_disconnect             (gpointer object, const gchar *signal_spec, ...);

A convenience function to disconnect multiple signals at once.

The signal specs expected by this function have the form "any_signal", which means to disconnect any signal with matching callback and data, or "any_signal::signal_name", which only disconnects the signal named "signal_name".

object : | a GObject
signal_spec : | the spec for the first signal
... : | GCallback for the first signal, followed by data for the first signal, followed optionally by more signal spec/callback/data triples, followed by NULL

g_object_set ()

void        g_object_set                (gpointer object, const gchar *first_property_name, ...);

Sets properties on an object.

object : | a GObject
first_property_name : | name of the first property to set
... : | value for the first property, followed optionally by more name/value pairs, followed by NULL

g_object_get ()

void        g_object_get              (gpointer object, const gchar *first_property_name, ...);

Gets properties of an object.

In general, a copy is made of the property contents and the caller is responsible for freeing the memory in the appropriate manner for the type, for instance by calling g_free() or g_object_unref().

Example 5. Using g_object_get()

An example of using g_object_get() to get the contents of three properties - one of type G_TYPE_INT, one of type G_TYPE_STRING, and one of type G_TYPE_OBJECT:

 gint intval;
 gchar *strval;
 GObject *objval;

 g_object_get (my_object,
               "intproperty", &intval,
               "strproperty", &strval,
               "objproperty", &objval,
               NULL);

 /* Do something with intval, strval, objval */

 g_free (strval);
 g_object_unref (objval);
object : | a GObject
first_property_name : | name of the first property to get
... : | return location for the first property, followed optionally by more name/return location pairs, followed by NULL

g_object_notify ()

void        g_object_notify                 (GObject *object, const gchar *property_name);

Emits a "notify" signal for the property property_name on object.

object : | a GObject
property_name : | the name of a property installed on the class of object.

g_object_freeze_notify ()

void        g_object_freeze_notify          (GObject *object);

Stops emission of "notify" signals on object. The signals are queued until g_object_thaw_notify() is called on object. This is necessary for accessors that modify multiple properties to prevent premature notification while the object is still being modified.

object : a GObject

g_object_thaw_notify ()

void        g_object_thaw_notify            (GObject *object);

Reverts the effect of a previous call to g_object_freeze_notify(). This causes all queued "notify" signals on object to be emitted.

object : a GObject

g_object_get_data ()

gpointer    g_object_get_data               (GObject *object, const gchar *key);

Gets a named field from the objects table of associations (see g_object_set_data()).

object : | GObject containing the associations
key : | name of the key for that association
Returns : | the data if found, or NULL if no such data exists.

g_object_set_data ()

void        g_object_set_data               (GObject *object, const gchar *key, gpointer data);

Each object carries around a table of associations from strings to pointers. This function sets an association.
If the object already had an association with that name, the old association will be destroyed.

object : | GObject containing the associations.
key : | name of the key
data : | data to associate with that key

g_object_set_data_full ()

void        g_object_set_data_full          (GObject *object, const gchar *key, gpointer data, GDestroyNotify destroy);

Like g_object_set_data() except it adds notification for when the association is destroyed, either by setting it to a different value or when the object is destroyed.

object : | GObject containing the associations
key : | name of the key
data : | data to associate with that key
destroy : | function to call when the association is destroyed

g_object_steal_data ()

gpointer    g_object_steal_data             (GObject *object, const gchar *key);

Removes a specified datum from the object's data associations, without invoking the association's destroy handler.

object : | GObject containing the associations
key : | name of the key
Returns : | the data if found, or NULL if no such data exists.

g_object_get_qdata ()

gpointer    g_object_get_qdata              (GObject *object, GQuark quark);

This function gets back user data pointers stored via g_object_set_qdata().

object : | The GObject to get a stored user data pointer from
quark : | A GQuark, naming the user data pointer
Returns : | The user data pointer set, or NULL

g_object_set_qdata ()

void        g_object_set_qdata              (GObject *object, GQuark quark, gpointer data);

This sets an opaque, named pointer on an object. The name is specified through a GQuark (retrived e.g. via g_quark_from_static_string()), and the pointer can be gotten back from the object with g_object_get_qdata() until the object is finalized. Setting a previously set user data pointer, overrides (frees) the old pointer set, using NULL as pointer essentially removes the data stored.

object : | The GObject to set store a user data pointer
quark : | A GQuark, naming the user data pointer
data : | An opaque user data pointer

g_object_set_qdata_full ()

void        g_object_set_qdata_full         (GObject *object, GQuark quark, gpointer data, GDestroyNotify destroy);

This function works like g_object_set_qdata(), but in addition, a void (*destroy) (gpointer) function may be specified which is called with data as argument when the object is finalized, or the data is being overwritten by a call to g_object_set_qdata() with the same quark.

object : | The GObject to set store a user data pointer
quark : | A GQuark, naming the user data pointer
data : | An opaque user data pointer
destroy : | Function to invoke with data as argument, when data needs to be freed

g_object_steal_qdata ()

gpointer    g_object_steal_qdata            (GObject *object, GQuark quark);

This function gets back user data pointers stored via g_object_set_qdata() and removes the data from object without invoking it's destroy() function (if any was set). Usually, calling this function is only required to update user data pointers with a destroy notifier, for example:

void
object_add_to_user_list (GObject  *object, const gchar *new_string)
{
  /* the quark, naming the object data */
  GQuark quark_string_list = g_quark_from_static_string ("my-string-list");
  /* retrive the old string list */
  GList *list = g_object_steal_qdata (object, quark_string_list);

  /* prepend new string */
  list = g_list_prepend (list, g_strdup (new_string));
  /* this changed 'list', so we need to set it again */
  g_object_set_qdata_full (object, quark_string_list, list, free_string_list);
}
static void
free_string_list (gpointer data)
{
  GList *node, *list = data;

  for (node = list; node; node = node->next)
    g_free (node->data);
  g_list_free (list);
}

Using g_object_get_qdata() in the above example, instead of g_object_steal_qdata() would have left the destroy function set, and thus the partial string list would have been freed upon g_object_set_qdata_full().

object : | The GObject to get a stored user data pointer from
quark : | A GQuark, naming the user data pointer
Returns : | The user data pointer set, or NULL

g_object_set_property ()

void        g_object_set_property           (GObject *object, const gchar *property_name, const GValue *value);

Sets a property on an object.

object : | a GObject
property_name : | the name of the property to set
value : | the value

g_object_get_property ()

void        g_object_get_property           (GObject *object, const gchar *property_name, GValue *value);

Gets a property of an object.
In general, a copy is made of the property contents and the caller is responsible for freeing the memory by calling g_value_unset().
Note that g_object_get_property() is really intended for language bindings, g_object_get() is much more convenient for C programming.

object : | a GObject
property_name : | the name of the property to get
value : | return location for the property value

g_object_new_valist ()

GObject*    g_object_new_valist         (GType object_type, const gchar *first_property_name, va_list var_args);

Creates a new instance of a GObject subtype and sets its properties. Construction parameters (see G_PARAM_CONSTRUCT, G_PARAM_CONSTRUCT_ONLY) which are not explicitly specified are set to their default values.

object_type : | the type id of the GObject subtype to instantiate
first_property_name : | the name of the first property
var_args : | the value of the first property, followed optionally by more name/value pairs, followed by NULL
Returns : | a new instance of object_type

g_object_set_valist ()

void        g_object_set_valist        (GObject *object, const gchar *first_property_name, va_list var_args);

Sets properties on an object.

object : | a GObject
first_property_name : | name of the first property to set
var_args : | value for the first property, followed optionally by more name/value pairs, followed by NULL

g_object_get_valist ()

void        g_object_get_valist          (GObject *object, const gchar *first_property_name, va_list var_args);

Gets properties of an object.

In general, a copy is made of the property contents and the caller is responsible for freeing the memory in the appropriate manner for the type, for instance by calling g_free() or g_object_unref().

See g_object_get().

object : | a GObject
first_property_name : | name of the first property to get
var_args : | return location for the first property, followed optionally by more name/return location pairs, followed by NULL

g_object_watch_closure ()

void        g_object_watch_closure          (GObject *object, GClosure *closure);

This function essentially limits the life time of the closure to the life time of the object. That is, when the object is finalized, the closure is invalidated by calling g_closure_invalidate() on it, in order to prevent invocations of the closure with a finalized (nonexisting) object. Also, g_object_ref() and g_object_unref() are added as marshal guards to the closure, to ensure that an extra reference count is held on object during invocation of the closure. Usually, this function will be called on closures that use this object as closure data.

object : | GObject restricting lifetime of closure
closure : | GClosure to watch

g_object_run_dispose ()

void        g_object_run_dispose            (GObject *object);

Releases all references to other objects. This can be used to break reference cycles.

Note

Note: This functions should only be called from object system implementations.

object : a GObject

G_OBJECT_WARN_INVALID_PROPERTY_ID()

#define     G_OBJECT_WARN_INVALID_PROPERTY_ID(object, property_id, pspec)

This macros should be used to emit a standard warning about unexpected properties in set_property() and get_property() implementations.

object : | the GObject on which set_property() or get_property() was called
property_id : | the numeric id of the property
pspec : | the GParamSpec of the property

Signal Details

The "notify" signal

void        user_function        (GObject    *gobject, GParamSpec *arg1, gpointer    user_data)
                                  : Run first / No recursion / Has details / Action / No hooks

The notify signal is emitted on an object when one of its properties has been changed. Note that getting this signal does not guarantee that the value of the property has actually changed, it may also be emitted when the setter for the property is called to reinstate the previous value.

gobject : | the object which received the signal.
pspec : | the GParamSpec of the property which changed
user_data : | user data set when the signal handler was connected.

See Also

GParamSpecObject, g_param_spec_object()

Feedback

For additional information or queries on this page send feedback


GType

Name

GType — The GLib Runtime type identification and management system.

Library

gobject.lib

Synopsis

#include <glib-object.h>

typedef     GType;
#define     G_TYPE_FUNDAMENTAL              (type)
#define     G_TYPE_FUNDAMENTAL_MAX
#define     G_TYPE_MAKE_FUNDAMENTAL         (x)
#define     G_TYPE_IS_ABSTRACT              (type)
#define     G_TYPE_IS_DERIVED               (type)
#define     G_TYPE_IS_FUNDAMENTAL           (type)
#define     G_TYPE_IS_VALUE_TYPE            (type)
#define     G_TYPE_HAS_VALUE_TABLE          (type)
#define     G_TYPE_IS_CLASSED               (type)
#define     G_TYPE_IS_INSTANTIATABLE        (type)
#define     G_TYPE_IS_DERIVABLE             (type)
#define     G_TYPE_IS_DEEP_DERIVABLE        (type)
#define     G_TYPE_IS_INTERFACE             (type)
            GTypeInterface;
            GTypeInstance;
            GTypeClass;
            GTypeInfo;
            GTypeFundamentalInfo;
            GInterfaceInfo;
            GTypeValueTable;
#define     G_TYPE_FROM_INSTANCE            (instance)
#define     G_TYPE_FROM_CLASS               (g_class)
#define     G_TYPE_FROM_INTERFACE           (g_iface)
#define     G_TYPE_INSTANCE_GET_CLASS       (instance, g_type, c_type)
#define     G_TYPE_INSTANCE_GET_INTERFACE   (instance, g_type, c_type)
#define     G_TYPE_INSTANCE_GET_PRIVATE     (instance, g_type, c_type)
#define     G_TYPE_CHECK_INSTANCE           (instance)
#define     G_TYPE_CHECK_INSTANCE_CAST      (instance, g_type, c_type)
#define     G_TYPE_CHECK_INSTANCE_TYPE      (instance, g_type)
#define     G_TYPE_CHECK_CLASS_CAST         (g_class, g_type, c_type)
#define     G_TYPE_CHECK_CLASS_TYPE         (g_class, g_type)
#define     G_TYPE_CHECK_VALUE              (value)
#define     G_TYPE_CHECK_VALUE_TYPE         (value, g_type)
#define     G_TYPE_FLAG_RESERVED_ID_BIT
void        g_type_init                     (void);
enum        GTypeDebugFlags;
void        g_type_init_with_debug_flags    (GTypeDebugFlags debug_flags);
const gchar* g_type_name                    (GType type);
GQuark      g_type_qname                    (GType type);
GType       g_type_from_name                (const gchar *name);
GType       g_type_parent                   (GType type);
guint       g_type_depth                    (GType type);
GType       g_type_next_base                (GType leaf_type, GType root_type);
gboolean    g_type_is_a                     (GType type, GType is_a_type);
gpointer    g_type_class_ref                (GType type);
gpointer    g_type_class_peek               (GType type);
gpointer    g_type_class_peek_static        (GType type);
void        g_type_class_unref              (gpointer g_class);
gpointer    g_type_class_peek_parent        (gpointer g_class);
void        g_type_class_add_private        (gpointer g_class, gsize private_size);
gpointer    g_type_interface_peek           (gpointer instance_class, GType iface_type);
gpointer    g_type_interface_peek_parent    (gpointer g_iface);
gpointer    g_type_default_interface_ref    (GType g_type);
gpointer    g_type_default_interface_peek   (GType g_type);
void        g_type_default_interface_unref  (gpointer g_iface);
GType*      g_type_children                 (GType type, guint *n_children);
GType*      g_type_interfaces               (GType type, guint *n_interfaces);
GType*      g_type_interface_prerequisites  (GType interface_type, guint *n_prerequisites);
void        g_type_set_qdata                (GType type, GQuark quark, gpointer data);
gpointer    g_type_get_qdata                (GType type, GQuark quark);
void        g_type_query                    (GType type, GTypeQuery *query);
            GTypeQuery;
void        (*GBaseInitFunc)                (gpointer g_class);
void        (*GBaseFinalizeFunc)            (gpointer g_class);
void        (*GClassInitFunc)               (gpointer g_class, gpointer class_data);
void        (*GClassFinalizeFunc)           (gpointer g_class, gpointer class_data);
void        (*GInstanceInitFunc)            (GTypeInstance *instance, gpointer g_class);
void        (*GInterfaceInitFunc)           (gpointer g_iface, gpointer iface_data);
void        (*GInterfaceFinalizeFunc)       (gpointer g_iface, gpointer iface_data);
gboolean    (*GTypeClassCacheFunc)          (gpointer cache_data, GTypeClass *g_class);
enum        GTypeFlags;
enum        GTypeFundamentalFlags;
GType       g_type_register_static          (GType parent_type, const gchar *type_name, const GTypeInfo *info,
                                             GTypeFlags flags);
GType       g_type_register_dynamic         (GType parent_type, const gchar *type_name, GTypePlugin *plugin,
                                             GTypeFlags flags);
GType       g_type_register_fundamental     (GType type_id, const gchar *type_name, const GTypeInfo *info,
                                             const GTypeFundamentalInfo *finfo, GTypeFlags flags);
void        g_type_add_interface_static     (GType instance_type, GType interface_type, const GInterfaceInfo *info);
void        g_type_add_interface_dynamic    (GType instance_type, GType interface_type, GTypePlugin *plugin);
void        g_type_interface_add_prerequisite   (GType interface_type, GType prerequisite_type);
GTypePlugin* g_type_get_plugin              (GType type);
GTypePlugin* g_type_interface_get_plugin    (GType instance_type, GType interface_type);
GType       g_type_fundamental_next         (void);
GType       g_type_fundamental              (GType type_id);
GTypeInstance* g_type_create_instance       (GType type);
void        g_type_free_instance            (GTypeInstance *instance);
void        g_type_add_class_cache_func     (gpointer cache_data, GTypeClassCacheFunc cache_func);
void        g_type_remove_class_cache_func  (gpointer cache_data, GTypeClassCacheFunc cache_func);
void        g_type_class_unref_uncached     (gpointer g_class);
void        g_type_add_interface_check      (gpointer check_data, GTypeInterfaceCheckFunc check_func);
void        g_type_remove_interface_check   (gpointer check_data, GTypeInterfaceCheckFunc check_func);
void        (*GTypeInterfaceCheckFunc)      (gpointer check_data, gpointer g_iface);
GTypeValueTable* g_type_value_table_peek    (GType type);
#define     G_DEFINE_TYPE                   (TN, t_n, T_P)
#define     G_DEFINE_TYPE_WITH_CODE         (TN, t_n, T_P, _C_)
#define     G_DEFINE_ABSTRACT_TYPE          (TN, t_n, T_P)
#define     G_DEFINE_ABSTRACT_TYPE_WITH_CODE(TN, t_n, T_P, _C_)
#define     G_IMPLEMENT_INTERFACE           (TYPE_IFACE, iface_init)
#define     G_DEFINE_TYPE_EXTENDED          (TypeName, type_name, TYPE_PARENT, flags, CODE)

#define     G_TYPE_INVALID
#define     G_TYPE_NONE
#define     G_TYPE_INTERFACE
#define     G_TYPE_CHAR
#define     G_TYPE_UCHAR
#define     G_TYPE_BOOLEAN
#define     G_TYPE_INT
#define     G_TYPE_UINT
#define     G_TYPE_LONG
#define     G_TYPE_ULONG
#define     G_TYPE_INT64
#define     G_TYPE_UINT64
#define     G_TYPE_ENUM
#define     G_TYPE_FLAGS
#define     G_TYPE_FLOAT
#define     G_TYPE_DOUBLE
#define     G_TYPE_STRING
#define     G_TYPE_POINTER
#define     G_TYPE_BOXED
#define     G_TYPE_PARAM
#define     G_TYPE_OBJECT

#define     G_TYPE_RESERVED_GLIB_FIRST
#define     G_TYPE_RESERVED_GLIB_LAST
#define     G_TYPE_RESERVED_BSE_FIRST
#define     G_TYPE_RESERVED_BSE_LAST
#define     G_TYPE_RESERVED_USER_FIRST

Detailed Description

The GType API is the foundation of the GObject system. It provides the facilities for registering and managing all fundamental data types, user-defined object and interface types. Before using any GType or GObject functions, g_type_init() must be called to initialize the type system.

For type creation and registration purposes, all types fall into one of two categories: static or dynamic. Static types are never loaded or unloaded at run-time as dynamic types may be. Static types are created with g_type_register_static() that gets type specific information passed in via a GTypeInfo structure. Dynamic types are created with g_type_register_dynamic() which takes a GTypePlugin structure instead. The remaining type information (the GTypeInfo structure) is retrieved during runtime through GTypePlugin and the g_type_plugin_*() API. These registration functions are usually called only once from a function whose only purpose is to return the type identifier for a specific class. Once the type (or class or interface) is registered, it may be instantiated, inherited, or implemented depending on exactly what sort of type it is. There is also a third registration function for registering fundamental types called g_type_register_fundamental() which requires both a GTypeInfo structure and a GTypeFundamentalInfo structure but it is seldom used since most fundamental types are predefined rather than user-defined.

A final word about type names. Such an identifier needs to be at least three characters long. There is no upper length limit. The first character needs to be a letter (a-z or A-Z) or an underscore '_'. Subsequent characters can be letters, numbers or any of '-_+'.

Details

GType

A numerical value which represents the unique identifier of a registered type.

G_TYPE_FUNDAMENTAL()

#define G_TYPE_FUNDAMENTAL(type)	(g_type_fundamental (type))

Returns the fundamental type which is the ancestor of type. Fundamental types are types that serve as fundaments for the derived types, thus they are the roots of distinct inheritance hierarchies.

type : A GType value.

G_TYPE_FUNDAMENTAL_MAX

#define	G_TYPE_FUNDAMENTAL_MAX		(255 << G_TYPE_FUNDAMENTAL_SHIFT)

An integer constant that represents the number of identifiers reserved for types that are assigned at compile-time.

G_TYPE_MAKE_FUNDAMENTAL()

#define	G_TYPE_MAKE_FUNDAMENTAL(x)	((GType) ((x) << G_TYPE_FUNDAMENTAL_SHIFT))

Returns the type ID for the fundamental type number x. Use g_type_fundamental_next() instead of this macro to create new fundamental types.

x : the fundamental type number.

G_TYPE_IS_ABSTRACT()

#define G_TYPE_IS_ABSTRACT(type)                (g_type_test_flags ((type), G_TYPE_FLAG_ABSTRACT))

Returns TRUE if type is an abstract type. An abstract type can not be instantiated and is normally used as an abstract base class for derived classes.

type : A GType value.

G_TYPE_IS_DERIVED()

#define G_TYPE_IS_DERIVED(type)                 ((type) > G_TYPE_FUNDAMENTAL_MAX)

Returns TRUE if type is derived (or in object-oriented terminology: inherited) from another type (this holds true for all non-fundamental types).

type : A GType value.

G_TYPE_IS_FUNDAMENTAL()

#define G_TYPE_IS_FUNDAMENTAL(type)             ((type) <= G_TYPE_FUNDAMENTAL_MAX)

Returns TRUE if type is a fundamental type.

type : A GType value.

G_TYPE_IS_VALUE_TYPE()

#define G_TYPE_IS_VALUE_TYPE(type)              (g_type_check_is_value_type (type))

Returns TRUE if type is a value type which can be used for g_value_init().

type : A GType value.

G_TYPE_HAS_VALUE_TABLE()

#define G_TYPE_HAS_VALUE_TABLE(type)            (g_type_value_table_peek (type) != NULL)

Returns TRUE if type has a GTypeValueTable.

type : A GType value.

G_TYPE_IS_CLASSED()

#define G_TYPE_IS_CLASSED(type)                 (g_type_test_flags ((type), G_TYPE_FLAG_CLASSED))

Returns TRUE if type is a classed type.

type : A GType value.

G_TYPE_IS_INSTANTIATABLE()

#define G_TYPE_IS_INSTANTIATABLE(type)          (g_type_test_flags ((type), G_TYPE_FLAG_INSTANTIATABLE))

Returns TRUE if type can be instantiated. Instantiation is the process of creating an instance (object) of this type.

type : A GType value.

G_TYPE_IS_DERIVABLE()

#define G_TYPE_IS_DERIVABLE(type)               (g_type_test_flags ((type), G_TYPE_FLAG_DERIVABLE))

Returns TRUE if type is a derivable type. A derivable type can be used as the base class of a flat (single-level) class hierarchy.

type : A GType value.

G_TYPE_IS_DEEP_DERIVABLE()

#define G_TYPE_IS_DEEP_DERIVABLE(type)          (g_type_test_flags ((type), G_TYPE_FLAG_DEEP_DERIVABLE))

Returns TRUE if type is a deep derivable type. A deep derivable type can be used as the base class of a deep (multi-level) class hierarchy.

type : A GType value.

G_TYPE_IS_INTERFACE()

#define G_TYPE_IS_INTERFACE(type)               (G_TYPE_FUNDAMENTAL (type) == G_TYPE_INTERFACE)

Returns TRUE if type is an interface type. Interface types are types that provide pure APIs, the implementation of which is provided by another type (which is then said to conform to the interface). GLib interfaces are somewhat analogous to Java interfaces and C++ classes containing only pure virtual functions, with the difference that GType interfaces are not derivable (but see g_type_interface_add_prerequisite() for an alternative).

type : A GType value.

GTypeInterface

typedef struct {
} GTypeInterface;

An opaque structure used as the base of all interface types.

GTypeInstance

typedef struct {
} GTypeInstance;

An opaque structure used as the base of all type instances.

GTypeClass

typedef struct {
} GTypeClass;

An opaque structure used as the base of all classes.

GTypeInfo

typedef struct {
  /* interface types, classed types, instantiated types */
  guint16                class_size;
  GBaseInitFunc          base_init;
  GBaseFinalizeFunc      base_finalize;

  /* interface types, classed types, instantiated types */
  GClassInitFunc         class_init;
  GClassFinalizeFunc     class_finalize;
  gconstpointer          class_data;

  /* instantiated types */
  guint16                instance_size;
  guint16                n_preallocs;
  GInstanceInitFunc      instance_init;

  /* value handling */
  const GTypeValueTable	*value_table;
} GTypeInfo;

This structure is used to provide the type system with the information required to initialize and destruct (finalize) a type's class and instances thereof. The initialized structure is passed to the g_type_register_static() function (or is copied into the provided GTypeInfo structure in the g_type_plugin_complete_type_info()). The type system will perform a deep copy of this structure, so it's memory does not need to be persistent across invocation of g_type_register_static().

guint16 class_size; | Size of the class structure (required for interface, classed and instantiatable types).
GBaseInitFunc base_init; | Location of the base initialization function (optional).
GBaseFinalizeFunc base_finalize; | Location of the base finalization function (optional).
GClassInitFunc class_init; | Location of the class initialization function for classed and types. Location of the default vtable inititalization function for interface types. (optional) This function is used both to fill in virtual functions in the class or default vtable, and to do type-specific setup such as registering signals and object properties.
GClassFinalizeFunc class_finalize; | Location of the class finalization function for classed and types. Location fo the default vtable finalization function for interface types. (optional)
gconstpointer class_data; | User-supplied data passed to the class init/finalize functions.
guint16 instance_size; | Size of the instance (object) structure (required for instantiatable types only).
guint16 n_preallocs; | Prior to GLib 2.10, it specified the number of pre-allocated (cached) instances to reserve memory for (0 indicates no caching). Since GLib 2.10, it is ignored, since instances are allocated with the slice allocator now.
GInstanceInitFunc instance_init; | Location of the instance initialization function (optional, for instantiatable types only).
const GTypeValueTable *value_table; | A GTypeValueTable function table for generic handling of GValues of this type (usually only useful for fundamental types).

GTypeFundamentalInfo

typedef struct {
  GTypeFundamentalFlags  type_flags;
} GTypeFundamentalInfo;

A structure that provides information to the type system which is used specifically for managing fundamental types.

GTypeFundamentalFlags type_flags; GTypeFundamentalFlags describing the characteristics of the fundamental type

GInterfaceInfo

typedef struct {
  GInterfaceInitFunc     interface_init;
  GInterfaceFinalizeFunc interface_finalize;
  gpointer               interface_data;
} GInterfaceInfo;

A structure that provides information to the type system which is used specifically for managing interface types.

GTypeValueTable

typedef struct {
  void     (*value_init)         (GValue       *value);
  void     (*value_free)         (GValue       *value);
  void     (*value_copy)         (const GValue *src_value,
                  GValue       *dest_value);
  /* varargs functionality (optional) */
  gpointer (*value_peek_pointer) (const GValue *value);
  gchar	    *collect_format;
  gchar*   (*collect_value)      (GValue       *value, guint   n_collect_values, GTypeCValue  *collect_values, guint collect_flags);
  gchar	    *lcopy_format;
  gchar*   (*lcopy_value)        (const GValue *value, guint n_collect_values, GTypeCValue  *collect_values, guint collect_flags);
} GTypeValueTable;

The GTypeValueTable provides the functions required by the GValue implementation, to serve as a container for values of a type.

value_init () Default initialize values contents by poking values directly into the value->data array. The data array of the GValue passed into this function was zero-filled with memset(), so no care has to be taken to free any old contents. E.g. for the implementation of a string value that may never be NULL, the implementation might look like:
{
  value->data[0].v_pointer = g_strdup ("");
}
value_free () Free any old contents that might be left in the data array of the passed in value. No resources may remain allocated through the GValue contents after this function returns. E.g. for our above string type:
{
  /* only free strings without a specific flag for static storage */
  if (!(value->data[1].v_uint & G_VALUE_NOCOPY_CONTENTS))
    g_free (value->data[0].v_pointer);
}
value_copy () dest_value is a GValue with zero-filled data section and src_value is a properly setup GValue of same or derived type. The purpose of this function is to copy the contents of src_value into dest_value in a way, that even after src_value has been freed, the contents of dest_value remain valid. String type example:
{
  dest_value->data[0].v_pointer = g_strdup (src_value->data[0].v_pointer);
}
value_peek_pointer () If the value contents fit into a pointer, such as objects or strings, return this pointer, so the caller can peek at the current contents. To extend on our above string example:
{
  return value->data[0].v_pointer;
}
gchar *collect_format; A string format describing how to collect the contents of this value, bit-by-bit. Each character in the format represents an argument to be collected, the characters themselves indicate the type of the argument. Currently supported arguments are:

'i' - Integers. passed as collect_values[].v_int.

'l' - Longs. passed as collect_values[].v_long.

'd' - Doubles. passed as collect_values[].v_double.

'p' - Pointers. passed as collect_values[].v_pointer.

It should be noted, that for variable argument list construction, ANSI C promotes every type smaller than an integer to an int, and floats to doubles. So for collection of short int or char, 'i' needs to be used, and for collection of floats 'd'.
collect_value () The collect_value() function is responsible for converting the values collected from a variable argument list into contents suitable for storage in a GValue. This function should setup value similar to value_init(), e.g. for a string value that does not allow NULL pointers, it needs to either spew an error, or do an implicit conversion by storing an empty string. The value passed in to this function has a zero-filled data array, so just like for value_init() it is guaranteed to not contain any old contents that might need freeing. n_collect_values is exactly the string length of collect_format, and collect_values is an array of unions GTypeCValue with length n_collect_values, containing the collected values according to collect_format. collect_flags is an argument provided as a hint by the caller, which may contain the flag G_VALUE_NOCOPY_CONTENTS indicating, that the collected value contents may be considered "static" for the duration of the value lifetime. Thus an extra copy of the contents stored in collect_values is not required for assignment to value. For our above string example, we continue with:
{
  if (!collect_values[0].v_pointer)
    value->data[0].v_pointer = g_strdup ("");
  else if (collect_flags & G_VALUE_NOCOPY_CONTENTS)
    {
      value->data[0].v_pointer = collect_values[0].v_pointer;
      /* keep a flag for the value_free() implementation to not free this string */
      value->data[1].v_uint = G_VALUE_NOCOPY_CONTENTS;
    }
  else
    value->data[0].v_pointer = g_strdup (collect_values[0].v_pointer);

  return NULL;
}
It should be noted, that it is generally a bad idea to follow the G_VALUE_NOCOPY_CONTENTS hint for reference counted types. Due to reentrancy requirements and reference count assertions performed by the GSignal code, reference counts should always be incremented for reference counted contents stored in the value->data array. To deviate from our string example for a moment, and taking a look at an exemplary implementation for collect_value() of GObject:
{
  if (collect_values[0].v_pointer)
    {
      GObject *object = G_OBJECT (collect_values[0].v_pointer);

      /* never honour G_VALUE_NOCOPY_CONTENTS for ref-counted types */
      value->data[0].v_pointer = g_object_ref (object);
      return NULL;
    }
  else
    return g_strdup_printf ("Object passed as invalid NULL pointer");
}
The reference count for valid objects is always incremented, regardless of collect_flags. For invalid objects, the example returns a newly allocated string without altering value. Upon success, collect_value() needs to return NULL, if however a malicious condition occurred, collect_value() may spew an error by returning a newly allocated non-NULL string, giving a suitable description of the error condition. The calling code makes no assumptions about the value contents being valid upon error returns, value is simply thrown away without further freeing. As such, it is a good idea to not allocate GValue contents, prior to returning an error, however, collect_values() is not obliged to return a correctly setup value for error returns, simply because any non-NULL return is considered a fatal condition so further program behaviour is undefined.
gchar *lcopy_format; Format description of the arguments to collect for lcopy_value, analogous to collect_format. Usually, lcopy_format string consists only of 'p's to provide lcopy_value() with pointers to storage locations.
lcopy_value () This function is responsible for storing the value contents into arguments passed through a variable argument list which got collected into collect_values according to lcopy_format. n_collect_values equals the string length of lcopy_format, and collect_flags may contain G_VALUE_NOCOPY_CONTENTS. In contrast to collect_value(), lcopy_value() is obliged to always properly support G_VALUE_NOCOPY_CONTENTS. Similar to collect_value() the function may prematurely abort by returning a newly allocated string describing an error condition. To complete the string example:
{
  gchar **string_p = collect_values[0].v_pointer;

  if (!string_p)
    return g_strdup_printf ("string location passed as NULL");

  if (collect_flags & G_VALUE_NOCOPY_CONTENTS)
    *string_p = value->data[0].v_pointer;
  else
    *string_p = g_strdup (value->data[0].v_pointer);

}
And an exemplary version of lcopy_value() for reference-counted types:
{
  GObject **object_p = collect_values[0].v_pointer;

  if (!object_p)
    return g_strdup_printf ("object location passed as NULL");
  if (!value->data[0].v_pointer)
    *object_p = NULL;
  else if (collect_flags & G_VALUE_NOCOPY_CONTENTS) /* always honour */
    *object_p = value->data[0].v_pointer;
  else
    *object_p = g_object_ref (value->data[0].v_pointer);
  return NULL;
}

G_TYPE_FROM_INSTANCE()

#define G_TYPE_FROM_INSTANCE(instance)               (G_TYPE_FROM_CLASS (((GTypeInstance*) (instance))->g_class))

Returns the type identifier from a given instance structure.
This macro should only be used in type implementations.

instance : Location of a valid GTypeInstance structure.

G_TYPE_FROM_CLASS()

#define G_TYPE_FROM_CLASS(g_class)                  (((GTypeClass*) (g_class))->g_type)

Returns the type identifier from a given class structure.
This macro should only be used in type implementations.

g_class : Location of a valid GTypeClass structure.

G_TYPE_FROM_INTERFACE()

#define G_TYPE_FROM_INTERFACE(g_iface)             (((GTypeInterface*) (g_iface))->g_type)

Returns the type identifier from a given interface structure.
This macro should only be used in type implementations.

g_iface : Location of a valid GTypeInterface structure.

G_TYPE_INSTANCE_GET_CLASS()

#define G_TYPE_INSTANCE_GET_CLASS(instance, g_type, c_type)     (_G_TYPE_IGC ((instance), (g_type), c_type))

Returns the class structure of a given instance, casted to a specified anchestor type g_type of the instance.
This macro should only be used in type implementations.

instance : | Location of the GTypeInstance structure.
g_type : | The anchestor type of the class to be returned.
c_type : | The corresponding C type of g_type.

G_TYPE_INSTANCE_GET_INTERFACE()

#define G_TYPE_INSTANCE_GET_INTERFACE(instance, g_type, c_type) (_G_TYPE_IGI ((instance), (g_type), c_type))

Returns the interface structure for interface g_type of a given instance.
This macro should only be used in type implementations.

instance : | Location of the GTypeInstance structure.
g_type : | The interface type to be returned.
c_type : | The corresponding C type of g_type.

G_TYPE_INSTANCE_GET_PRIVATE()

#define G_TYPE_INSTANCE_GET_PRIVATE(instance, g_type, c_type)   ((c_type*) g_type_instance_get_private ((GTypeInstance*) (instance), (g_type)))

Gets the private structure for a particular type. The private structure must have been registered in the class_init function with g_type_class_add_private(). This macro should only be used in type implementations.

instance : | the instance of a type deriving from private_type.
g_type : | the type identifying which private data to retrieve.
c_type : | The C type for the private structure.

G_TYPE_CHECK_INSTANCE()

#define G_TYPE_CHECK_INSTANCE(instance)				(_G_TYPE_CHI ((GTypeInstance*) (instance)))

Returns TRUE if instance is a valid GTypeInstance structure, otherwise emits a warning and returns FALSE. This macro should only be used in type implementations.

instance : Location of a GTypeInstance structure.

G_TYPE_CHECK_INSTANCE_CAST()

#define G_TYPE_CHECK_INSTANCE_CAST(instance, g_type, c_type)    (_G_TYPE_CIC ((instance), (g_type), c_type))

Checks that instance is an instance of the type identified by g_type and emits a warning if this is not the case. Returns instance casted to a pointer to c_type. This macro should only be used in type implementations.

instance : | Location of a GTypeInstance structure.
g_type : | The type to be returned.
c_type : | The corresponding C type of g_type.

G_TYPE_CHECK_INSTANCE_TYPE()

#define G_TYPE_CHECK_INSTANCE_TYPE(instance, g_type)            (_G_TYPE_CIT ((instance), (g_type)))

Returns TRUE if instance is an instance of the type identified by g_type. Otherwise emits a warning and returns FALSE. This macro should only be used in type implementations.

instance : | Location of a GTypeInstance structure.
g_type : | The type to be checked

G_TYPE_CHECK_CLASS_CAST()

#define G_TYPE_CHECK_CLASS_CAST(g_class, g_type, c_type)        (_G_TYPE_CCC ((g_class), (g_type), c_type))

Checks that g_class is a class structure of the type identified by g_type and emits a warning if this is not the case. Returns g_class casted to a pointer to c_type. This macro should only be used in type implementations.

g_class : | Location of a GTypeClass structure.
g_type : | The type to be returned.
c_type : | The corresponding C type of class structure of g_type.

G_TYPE_CHECK_CLASS_TYPE()

#define G_TYPE_CHECK_CLASS_TYPE(g_class, g_type)                (_G_TYPE_CCT ((g_class), (g_type)))

Returns TRUE if g_class is a class structure of the type identified by g_type. Otherwise emits a warning and returns FALSE. This macro should only be used in type implementations.

g_class : | Location of a GTypeClass structure.
g_type : | The type to be checked.

G_TYPE_CHECK_VALUE()

#define G_TYPE_CHECK_VALUE(value)				(_G_TYPE_CHV ((value)))

Returns TRUE if value has been initialized to hold values of a value type. This macro should only be used in type implementations.

value : a GValue

G_TYPE_CHECK_VALUE_TYPE()

#define G_TYPE_CHECK_VALUE_TYPE(value, g_type)			(_G_TYPE_CVH ((value), (g_type)))

Returns TRUE if value has been initialized to hold values of type g_type. This macro should only be used in type implementations.

value : | a GValue
g_type : | The type to be checked.

G_TYPE_FLAG_RESERVED_ID_BIT

#define	G_TYPE_FLAG_RESERVED_ID_BIT	((GType) (1 << 0))

A bit in the type number that's supposed to be left untouched.

g_type_init ()

void        g_type_init            (void);

Prior to any use of the type system, g_type_init() has to be called to initialize the type system and assorted other code portions (such as the various fundamental type implementations or the signal system).

enum GTypeDebugFlags

typedef enum	/*< skip >*/
{
  G_TYPE_DEBUG_NONE	= 0,
  G_TYPE_DEBUG_OBJECTS	= 1 << 0,
  G_TYPE_DEBUG_SIGNALS	= 1 << 1,
  G_TYPE_DEBUG_MASK	= 0x03
} GTypeDebugFlags;

The GTypeDebugFlags enumeration values can be passed to g_type_init_with_debug_flags() to trigger debugging messages during runtime. Note that the messages can also be triggered by setting the GOBJECT_DEBUG environment variable to a ':'-separated list of "objects" and "signals".

G_TYPE_DEBUG_NONE | Print no messages.
G_TYPE_DEBUG_OBJECTS | Print messages about object bookkeeping.
G_TYPE_DEBUG_SIGNALS | Print messages about signal emissions.
G_TYPE_DEBUG_MASK | Mask covering all debug flags.

g_type_init_with_debug_flags ()

void        g_type_init_with_debug_flags    (GTypeDebugFlags debug_flags);

Similar to g_type_init(), but additionally sets debug flags.

debug_flags : Bitwise combination of GTypeDebugFlags values for debugging purposes.

g_type_name ()

const gchar* g_type_name                    (GType type);

Returns the unique name that is assigned to a type ID (this is the preferred method to find out whether a specific type has been registered for the passed in ID yet).

type : | Type to return name for.
Returns : | Static type name or NULL.

g_type_qname ()

GQuark      g_type_qname                    (GType type);

Return the corresponding quark of the type IDs name.

type : | Type to return quark of type name for.
Returns : | The type names quark or 0.

g_type_from_name ()

GType       g_type_from_name                (const gchar *name);

Looksup the type ID from a given type name, returns 0 if no type has been registered under this name (this is the preferred method to find out by name whether a specific type has been registered yet).

name : | Type name to lookup.
Returns : | Corresponding type ID or 0.

g_type_parent ()

GType       g_type_parent                   (GType type);

Returns the direct parent type of the passed in type. If the passed in type has no parent, i.e. is a fundamental type, 0 is returned.

type : | The derived type.
Returns : | The parent type.

g_type_depth ()

guint       g_type_depth                    (GType type);

Returns the length of the ancestry of the passed in type. This includes the type itself, so that e.g. a fundamental type has depth 1.

type : | A GType value.
Returns : | The depth of type.

g_type_next_base ()

GType       g_type_next_base                (GType leaf_type, GType root_type);

Given a leaf_type and a root_type which is contained in its anchestry, return the type that root_type is the immediate parent of. In other words, this function determines the type that is derived directly from root_type which is also a base class of leaf_type. Given a root type and a leaf type, this function can be used to determine the types and order in which the leaf type is descended from the root type.

leaf_type : | Descendant of root_type and the type to be returned.
root_type : | Immediate parent of the returned type.
Returns : | Immediate child of root_type and anchestor of leaf_type.

g_type_is_a ()

gboolean    g_type_is_a                     (GType type, GType is_a_type);

If is_a_type is a derivable type, check whether type is a descendant of is_a_type. If is_a_type is an interface, check whether type conforms to it.

type : | Type to check anchestry for.
is_a_type : | Possible anchestor of type or interface type could conform to.
Returns : | TRUE if type is_a is_a_type holds true.

g_type_class_ref ()

gpointer    g_type_class_ref                (GType type);

Increments the reference count of the class structure belonging to type. This function will demand-create the class if it does not exist already.

type : | Type ID of a classed type.
Returns : | The GTypeClass structure for the given type ID.

g_type_class_peek ()

gpointer    g_type_class_peek               (GType type);

This function is essentially the same as g_type_class_ref(), except that the classes reference count isn't incremented. Therefore, this function may return NULL if the class of the type passed in does not currently exist (hasn't been referenced before).

type : | Type ID of a classed type.
Returns : | The GTypeClass structure for the given type ID or NULL if the class does not currently exist.

g_type_class_peek_static ()

gpointer    g_type_class_peek_static        (GType type);

A more efficient version of g_type_class_peek() which works only for static types.

type : | Type ID of a classed type.
Returns : | The GTypeClass structure for the given type ID or NULL if the class does not currently exist or is dynamically loaded.

g_type_class_unref ()

void        g_type_class_unref              (gpointer g_class);

Decrements the reference count of the class structure being passed in. Once the last reference count of a class has been released, classes may be finalized by the type system, so further dereferencing of a class pointer after g_type_class_unref() are invalid.

g_class : The GTypeClass structure to unreference.

g_type_class_peek_parent ()

gpointer    g_type_class_peek_parent        (gpointer g_class);

This is a convenience function, often needed in class initializers. It essentially takes the immediate parent type of the class passed in, and returns the class structure thereof. Since derived classes hold a reference count on their parent classes as long as they are instantiated, the returned class will always exist. This function is essentially equivalent to:

g_type_class_peek (g_type_parent (G_TYPE_FROM_CLASS (g_class)));

g_class : | The GTypeClass structure to retrieve the parent class for.
Returns : | The parent class of g_class.

g_type_class_add_private ()

void        g_type_class_add_private        (gpointer g_class, gsize private_size);

Registers a private structure for a instantiatable type; when an object is allocated, the private structures for the type and and all of its parent types are allocated sequentially in the same memory block as the public structures. This function should be called in the type's class_init() function. The private structure can be retrieved using the G_TYPE_INSTANCE_GET_PRIVATE() macro. The following example shows attaching a private structure MyObjectPrivate to an object MyObject defined in the standard GObject fashion.

typedef struct _MyObjectPrivate MyObjectPrivate;

struct _MyObjectPrivate {
  int some_field;
};

#define MY_OBJECT_GET_PRIVATE(o)  \
   (G_TYPE_INSTANCE_GET_PRIVATE ((o), MY_TYPE_OBJECT, MyObjectPrivate))

static void
my_object_class_init (MyObjectClass *klass)
{
  g_type_class_add_private (klass, sizeof (MyObjectPrivate));
}

static int
my_object_get_some_field (MyObject *my_object)
{
  MyObjectPrivate *priv = MY_OBJECT_GET_PRIVATE (my_object);

  return priv->some_field;
}
g_class : | class structure for an instantiatable type
private_size : | size of private structure.

g_type_interface_peek ()

gpointer    g_type_interface_peek           (gpointer instance_class, GType iface_type);

Returns the GTypeInterface structure of an interface to which the passed in class conforms.

instance_class : | A GTypeClass structure.
iface_type : | An interface ID which this class conforms to.
Returns : | The GTypeInterface structure of iface_type, or NULL if the class is not instantiated.

g_type_interface_peek_parent ()

gpointer    g_type_interface_peek_parent    (gpointer g_iface);

Returns the corresponding GTypeInterface structure of the parent type of the instance type to which g_iface belongs. This is useful when deriving the implementation of an interface from the parent type and then possibly overriding some methods.

g_iface : | A GTypeInterface structure.
Returns : | The corresponding GTypeInterface structure of the parent type of the instance type to which g_iface belongs, or NULL if the parent type does not conform to the interface.

g_type_default_interface_ref ()

gpointer    g_type_default_interface_ref    (GType g_type);

Increments the reference count for the interface type g_type, and returns the default interface vtable for the type.

If the type is not currently in use, then the default vtable for the type will be created and initalized by calling the base interface init and default vtable init functions for the type (the @base_init and class_init members of GTypeInfo). Calling g_type_default_interface_ref() is useful to make sure that signals and properties for an interface have been installed.

g_type : | an interface type
Returns : | the default vtable for the interface; call g_type_default_interface_unref() when using the interface is done.

g_type_default_interface_peek ()

gpointer    g_type_default_interface_peek   (GType g_type);

If the interface type g_type is currently in use, returns its default interface vtable.

g_type : | an interface type
Returns : | the default vtable for the interface; or NULL if the type is not currently in use.

g_type_default_interface_unref ()

void        g_type_default_interface_unref  (gpointer g_iface);

Decrements the reference count for the type corresponding to the interface default vtable g_iface. If the type is dynamic, then when no one is using the interface and all references have been released, the finalize function for the interface's default vtable (the class_finalize member of GTypeInfo) will be called.

g_iface : the default vtable structure for a interface, as returned by g_type_default_interface_ref()

g_type_children ()

GType*      g_type_children                 (GType type, guint *n_children);

Returns a newly allocated and 0-terminated array of type IDs, listing the child types of type. The return value has to be g_free()ed after use.

type : | The parent type.
n_children : | Optional guint pointer to contain the number of child types.
Returns : | Newly allocated and 0-terminated array of child types.

g_type_interfaces ()

GType*      g_type_interfaces               (GType type, guint *n_interfaces);

Returns a newly allocated and 0-terminated array of type IDs, listing the interface types that type conforms to. The return value has to be g_free()ed after use.

type : | The type to list interface types for.
n_interfaces : | Optional guint pointer to contain the number of interface types.
Returns : | Newly allocated and 0-terminated array of interface types.

g_type_interface_prerequisites ()

GType*      g_type_interface_prerequisites  (GType interface_type, guint *n_prerequisites);

Returns the prerequisites of an interfaces type.

interface_type : | an interface type
n_prerequisites : | location to return the number of prerequisites, or NULL
Returns : | a newly-allocated zero-terminated array of GType containing the prerequisites of interface_type

g_type_set_qdata ()

void        g_type_set_qdata             (GType type, GQuark quark, gpointer data);

Attaches arbitrary data to a type.

type : | a GType
quark : | a GQuark id to identify the data
data : | the data

g_type_get_qdata ()

gpointer    g_type_get_qdata                (GType type, GQuark quark);

Obtains data which has previously been attached to type with g_type_set_qdata().

type : | a GType
quark : | a GQuark id to identify the data
Returns : | the data, or NULL if no data was found

g_type_query ()

void        g_type_query                    (GType type, GTypeQuery *query);

Queries the type system for information about a specific type. This function will fill in a user-provided structure to hold type-specific information. If an invalid GType is passed in, the type member of the GTypeQuery is 0. All members filled into the GTypeQuery structure should be considered constant and have to be left untouched.

type : | the GType value of a static, classed type.
query : | A user provided structure that is filled in with constant values upon success.

GTypeQuery

typedef struct {
  GType		type;
  const gchar  *type_name;
  guint		class_size;
  guint		instance_size;
} GTypeQuery;

A structure holding information for a specific type. It is filled in by the g_type_query() function.

GType type; | the GType value of the type.
const gchar *type_name; | the name of the type.
guint class_size; | the size of the class structure.
guint instance_size; | the size of the instance structure.

GBaseInitFunc ()

void        (*GBaseInitFunc)                (gpointer g_class);

A callback function used by the type system to do base initialization of the class structures of derived types. It is called as part of the initialization process of all derived classes and should reallocate or reset all dynamic class members copied over from the parent class. Therefore class members, e.g. strings, that are not sufficiently handled by a plain memory copy of the parent class into the derived class have to be altered. See GClassInitFunc() for a discussion of the class intialization process.

g_class : The GTypeClass structure to initialize.

GBaseFinalizeFunc ()

void        (*GBaseFinalizeFunc)            (gpointer g_class);

A callback function used by the type system to finalize those portions of a derived types class structure that were setup from the corresponding GBaseInitFunc() function. Class finalization basically works the inverse way in which class intialization is performed. See GClassInitFunc() for a discussion of the class intialization process.

g_class : The GTypeClass structure to finalize.

GClassInitFunc ()

void        (*GClassInitFunc)               (gpointer g_class, gpointer class_data);

A callback function used by the type system to initialize the class of a specific type. This function should initialize all static class members. The initialization process of a class involves:

1 - Copying common members from the parent class over to the derived class structure.

2 - Zero initialization of the remaining members not copied over from the parent class.

3 - Invocation of the GBaseInitFunc() initializers of all parent types and the class' type.

4 - Invocation of the class' GClassInitFunc() initializer.

Since derived classes are partially initialized through a memory copy of the parent class, the general rule is that GBaseInitFunc() and GBaseFinalizeFunc() should take care of necessary reinitialization and release of those class members that were introduced by the type that specified these GBaseInitFunc()/GBaseFinalizeFunc(). GClassInitFunc() should only care about initializing static class members, while dynamic class members (such as allocated strings or reference counted resources) are better handled by a GBaseInitFunc() for this type, so proper initialization of the dynamic class members is performed for class initialization of derived types as well. An example may help to correspond the intend of the different class initializers:

typedef struct {
  GObjectClass parent_class;
  gint         static_integer;
  gchar       *dynamic_string;
} TypeAClass;
static void
type_a_base_class_init (TypeAClass *class)
{
  class->dynamic_string = g_strdup ("some string");
}
static void
type_a_base_class_finalize (TypeAClass *class)
{
  g_free (class->dynamic_string);
}
static void
type_a_class_init (TypeAClass *class)
{
  class->static_integer = 42;
}

typedef struct {
  TypeAClass   parent_class;
  gfloat       static_float;
  GString     *dynamic_gstring;
} TypeBClass;
static void
type_b_base_class_init (TypeBClass *class)
{
  class->dynamic_gstring = g_string_new ("some other string");
}
static void
type_b_base_class_finalize (TypeBClass *class)
{
  g_string_free (class->dynamic_gstring);
}
static void
type_b_class_init (TypeBClass *class)
{
  class->static_float = 3.14159265358979323846;
}

Initialization of TypeBClass will first cause initialization of TypeAClass (derived classes reference their parent classes, see g_type_class_ref() on this). Initialization of TypeAClass roughly involves zero-initializing its fields, then calling its GBaseInitFunc() type_a_base_class_init() that allocates its dynamic members (dynamic_string) and finally calling its GClassInitFunc() type_a_class_init() to initialize its static members (static_integer). The first step in the initialization process of TypeBClass is then a plain memory copy of the contents of TypeAClass into TypeBClass and zero-initialization of the remaining fields in TypeBClass. The dynamic members of TypeAClass within TypeBClass now need reinitialization which is performed by calling type_a_base_class_init() with an argument of TypeBClass. After that, the GBaseInitFunc() of TypeBClass, type_b_base_class_init() is called to allocate the dynamic members of TypeBClass (dynamic_gstring), and finally the GClassInitFunc() of TypeBClass, type_b_class_init(), is called to complete the initialization process with the static members (static_float). Corresponding finalization counter parts to the GBaseInitFunc() functions have to be provided to release allocated resources at class finalization time.

g_class : | The GTypeClass structure to initialize.
class_data : | The class_data member supplied via the GTypeInfo structure.

GClassFinalizeFunc ()

void        (*GClassFinalizeFunc)           (gpointer g_class, gpointer class_data);

A callback function used by the type system to finalize a class. This function is rarely needed, as dynamically allocated class resources should be handled by GBaseInitFunc() and GBaseFinalizeFunc(). Also, specification of a GClassFinalizeFunc() in the GTypeInfo structure of a static type is invalid, because classes of static types will never be finalized (they are artificially kept alive when their reference count drops to zero).

g_class : | The GTypeClass structure to finalize.
class_data : | The class_data member supplied via the GTypeInfo structure.

GInstanceInitFunc ()

void        (*GInstanceInitFunc)            (GTypeInstance *instance, gpointer g_class);

A callback function used by the type system to initialize a new instance of a type. This function initializes all instance members and allocates any resources required by it. Initialization of a derived instance involves calling all its parent types instance initializers, therefore the class member of the instance is altered during its initialization to always point to the class that belongs to the type the current initializer was introduced for.

instance : | The instance to initialize.
g_class : | The class of the type the instance is created for.

GInterfaceInitFunc ()

void        (*GInterfaceInitFunc)           (gpointer g_iface, gpointer iface_data);

A callback function used by the type system to initialize a new interface. This function should initialize all internal data and allocate any resources required by the interface.

g_iface : | The interface structure to initialize.
iface_data : | The class_data supplied via the GTypeInfo structure.

GInterfaceFinalizeFunc ()

void        (*GInterfaceFinalizeFunc)       (gpointer g_iface, gpointer iface_data);

A callback function used by the type system to finalize an interface. This function should destroy any internal data and release any resources allocated by the corresponding GInterfaceInitFunc() function.

g_iface : | The interface structure to finalize.
iface_data : | The class_data supplied via the GTypeInfo structure.

GTypeClassCacheFunc ()

gboolean    (*GTypeClassCacheFunc)          (gpointer cache_data, GTypeClass *g_class);

A callback function which is called when the reference count of a class drops to zero. It may use g_type_class_ref() to prevent the class from being freed. Do not call g_type_class_unref() from a GTypeClassCacheFunc function to prevent infinite recursion, use g_type_class_unref_uncached() instead.

The functions have to check the class id passed in to figure whether they actually want to cache the class of this type, since all classes are routed through the same GTypeClassCacheFunc chain.

cache_data : | data that was given to the g_type_add_class_cache_func() call
g_class : | The GTypeClass structure which is unreferenced
Returns : | TRUE to stop further GTypeClassCacheFuncs from being called, FALSE to continue.

enum GTypeFlags

typedef enum    /*< skip >*/
{
  G_TYPE_FLAG_ABSTRACT		= (1 << 4),
  G_TYPE_FLAG_VALUE_ABSTRACT	= (1 << 5)
} GTypeFlags;

Bit masks used to check or determine characteristics of a type.

G_TYPE_FLAG_ABSTRACT | Indicates an abstract type. No instances can be created for an abstract type.
G_TYPE_FLAG_VALUE_ABSTRACT | Indicates an abstract value type, i.e. a type that introduces a value table, but cannot be used for g_value_init().

enum GTypeFundamentalFlags

typedef enum    /*< skip >*/
{
  G_TYPE_FLAG_CLASSED           = (1 << 0),
  G_TYPE_FLAG_INSTANTIATABLE    = (1 << 1),
  G_TYPE_FLAG_DERIVABLE         = (1 << 2),
  G_TYPE_FLAG_DEEP_DERIVABLE    = (1 << 3)
} GTypeFundamentalFlags;

Bit masks used to check or determine specific characteristics of a fundamental type.

G_TYPE_FLAG_CLASSED | Indicates a classed type.
G_TYPE_FLAG_INSTANTIATABLE | Indicates an instantiable type (implies classed).
G_TYPE_FLAG_DERIVABLE | Indicates a flat derivable type.
G_TYPE_FLAG_DEEP_DERIVABLE | Indicates a deep derivable type (implies derivable).

g_type_register_static ()

GType       g_type_register_static          (GType parent_type, const gchar *type_name, const GTypeInfo *info, GTypeFlags flags);

Registers type_name as the name of a new static type derived from parent_type. The type system uses the information contained in the GTypeInfo structure pointed to by info to manage the type and its instances (if not abstract). The value of flags determines the nature (e.g. abstract or not) of the type.

parent_type : | Type which this type will be derived from.
type_name : | 0-terminated string used as the name of the new type.
info : | The GTypeInfo structure for this type.
flags : | Bitwise combination of GTypeFlags values.
Returns : | The new type identifier.

g_type_register_dynamic ()

GType       g_type_register_dynamic         (GType parent_type, const gchar *type_name, GTypePlugin *plugin, GTypeFlags flags);

Registers type_name as the name of a new dynamic type derived from parent_type. The type system uses the information contained in the GTypePlugin structure pointed to by plugin to manage the type and its instances (if not abstract). The value of flags determines the nature (e.g. abstract or not) of the type.

parent_type : | Type which this type will be derived from.
type_name : | 0-terminated string used as the name of the new type.
plugin : | The GTypePlugin structure to retrieve the GTypeInfo from.
flags : | Bitwise combination of GTypeFlags values.
Returns : | The new type identifier or G_TYPE_INVALID if registration failed.

g_type_register_fundamental ()

GType       g_type_register_fundamental     (GType type_id, const gchar *type_name, const GTypeInfo *info, const GTypeFundamentalInfo *finfo, GTypeFlags flags);

Registers type_id as the predefined identifier and type_name as the name of a fundamental type. The type system uses the information contained in the GTypeInfo structure pointed to by info and the GTypeFundamentalInfo structure pointed to by finfo to manage the type and its instances. The value of flags determines additional characteristics of the fundamental type.

type_id : | A predefined GTypeFundamentals value.
type_name : | 0-terminated string used as the name of the new type.
info : | The GTypeInfo structure for this type.
finfo : | The GTypeFundamentalInfo structure for this type.
flags : | Bitwise combination of GTypeFlags values.
Returns : | The predefined type identifier.

g_type_add_interface_static ()

void        g_type_add_interface_static     (GType instance_type, GType interface_type, const GInterfaceInfo *info);

Adds the static interface_type to instantiable_type. The information contained in the GTypeInterfaceInfo structure pointed to by info is used to manage the relationship.

instance_type : | GType value of an instantiable type.
interface_type : | GType value of an interface type.
info : | The GInterfaceInfo structure for this (instance_type, interface_type) combination.

g_type_add_interface_dynamic ()

void     g_type_add_interface_dynamic    (GType instance_type, GType interface_type, GTypePlugin *plugin);

Adds the dynamic interface_type to instantiable_type. The information contained in the GTypePlugin structure pointed to by plugin is used to manage the relationship.

instance_type : | the GType value of an instantiable type.
interface_type : | the GType value of an interface type.
plugin : | the GTypePlugin structure to retrieve the GInterfaceInfo from.

g_type_interface_add_prerequisite ()

void     g_type_interface_add_prerequisite    (GType interface_type, GType prerequisite_type);

Adds prerequisite_type to the list of prerequisites of interface_type. This means that any type implementing interface_type must also implement prerequisite_type. Prerequisites can be thought of as an alternative to interface derivation (which GType does not support). An interface can have at most one instantiatable prerequisite type.

interface_type : | GType value of an interface type.
prerequisite_type : | GType value of an interface or instantiatable type.

g_type_get_plugin ()

GTypePlugin* g_type_get_plugin              (GType type);

Returns the GTypePlugin structure for type or NULL if type does not have a GTypePlugin structure.

type : | The GType to retrieve the plugin for.
Returns : | The corresponding plugin if type is a dynamic type, NULL otherwise.

g_type_interface_get_plugin ()

GTypePlugin* g_type_interface_get_plugin    (GType instance_type, GType interface_type);

Returns the GTypePlugin structure for the dynamic interface interface_type which has been added to instance_type, or NULL if interface_type has not been added to instance_type or does not have a GTypePlugin structure. See g_type_add_interface_dynamic().

instance_type : | the GType value of an instantiatable type.
interface_type : | the GType value of an interface type.
Returns : | the GTypePlugin for the dynamic interface interface_type of instance_type.

g_type_fundamental_next ()

GType       g_type_fundamental_next         (void);

Returns the next free fundamental type id which can be used to register a new fundamental type with g_type_register_fundamental(). The returned type ID represents the highest currently registered fundamental type identifier.

Returns : The nextmost fundamental type ID to be registered, or 0 if the type system ran out of fundamental type IDs.

g_type_fundamental ()

GType       g_type_fundamental              (GType type_id);

Internal function, used to extract the fundamental type ID portion. use G_TYPE_FUNDAMENTAL() instead.

type_id : | valid type ID
Returns : | fundamental type ID

g_type_create_instance ()

GTypeInstance* g_type_create_instance       (GType type);

Creates and initializes an instance of type if type is valid and can be instantiated. The type system only performs basic allocation and structure setups for instances, actual instance creation should happen through functions supplied by the type's fundamental type implementation. So use of g_type_create_instance() is reserved for implementators of fundamental types only. E.g. instances of the GObject hierarchy should be created via g_object_new() and never directly through g_type_create_instance() which does not handle things like singleton objects or object construction. Note: Do not use this function, unless you're implementing a fundamental type. Also language bindings should not use this function but g_object_new() instead.

type : | An instantiatable type to create an instance for.
Returns : | An allocated and initialized instance, subject to further treatment by the fundamental type implementation.

g_type_free_instance ()

void        g_type_free_instance            (GTypeInstance *instance);

Frees an instance of a type, returning it to the instance pool for the type, if there is one. Like g_type_create_instance(), this function is reserved for implementors of fundamental types.

instance : an instance of a type.

g_type_add_class_cache_func ()

void        g_type_add_class_cache_func     (gpointer cache_data, GTypeClassCacheFunc cache_func);

Adds a GTypeClassCacheFunc to be called before the reference count of a class goes from one to zero. This can be used to prevent premature class destruction. All installed GTypeClassCacheFunc functions will be chained until one of them returns TRUE. The functions have to check the class id passed in to figure whether they actually want to cache the class of this type, since all classes are routed through the same GTypeClassCacheFunc chain.

cache_data : | data to be passed to cache_func
cache_func : | a GTypeClassCacheFunc

g_type_remove_class_cache_func ()

void        g_type_remove_class_cache_func  (gpointer cache_data, GTypeClassCacheFunc cache_func);

Removes a previously installed GTypeClassCacheFunc. The cache maintained by cache_func has to be empty when calling g_type_remove_class_cache_func() to avoid leaks.

cache_data : | data that was given when adding cache_func
cache_func : | a GTypeClassCacheFunc

g_type_class_unref_uncached ()

void        g_type_class_unref_uncached     (gpointer g_class);

A variant of g_type_class_unref() for use in GTypeClassCacheFunc implementations. It unreferences a class without consulting the chain of GTypeClassCacheFuncs, avoiding the recursion which would occur otherwise.

g_class : The GTypeClass structure to unreference.

g_type_add_interface_check ()

void        g_type_add_interface_check      (gpointer check_data, GTypeInterfaceCheckFunc check_func);

Adds a function to be called after an interface vtable is initialized for any class. That is, after the interface_init member of GInterfaceInfo has been called.

This function is useful to check an invariant that depends on the interfaces of a class. For instance, the implementation of GObject uses this facility to check that an object implements all of the properties that are defined on its interfaces.

check_data : | data to pass to check_func
check_func : | function to be called after each interface is initialized.

g_type_remove_interface_check ()

void        g_type_remove_interface_check   (gpointer check_data, GTypeInterfaceCheckFunc check_func);

Removes an interface check function added with g_type_add_interface_check().

check_data : | callback data passed to g_type_add_interface_check()
check_func : | callback function passed to g_type_add_interface_check()

GTypeInterfaceCheckFunc ()

void        (*GTypeInterfaceCheckFunc)      (gpointer check_data, gpointer g_iface);

A callback called after an interface vtable is initialized. See g_type_add_interface_check().

check_data : | data passed to g_type_add_interface_check().
g_iface : | the interface that has been initialized

g_type_value_table_peek ()

GTypeValueTable* g_type_value_table_peek    (GType type);

Returns the location of the GTypeValueTable associated with type. Note, this function should only be used from source code that implements or has internal knowledge of the implementation of type.

type : | A GType value.
Returns : | Location of the GTypeValueTable associated with type or NULL if there is no GTypeValueTable associated with type.

G_DEFINE_TYPE()

#define G_DEFINE_TYPE(TN, t_n, T_P)                G_DEFINE_TYPE_EXTENDED (TN, t_n, T_P, 0, {})

A convenience macro for type implementations, which declares a class initialization function, an instance initialization function (see GTypeInfo for information about these) and a static variable named t_n_parent_class pointing to the parent class. Furthermore, it defines a *_get_type() function. See G_DEFINE_TYPE_EXTENDED() for an example.

TN : | The name of the new type, in Camel case.
t_n : | The name of the new type, in lowercase, with words separated by '_'.
T_P : | The GType of the parent type.

G_DEFINE_TYPE_WITH_CODE()

#define G_DEFINE_TYPE_WITH_CODE(TN, t_n, T_P, _C_)          G_DEFINE_TYPE_EXTENDED (TN, t_n, T_P, 0, _C_)

A convenience macro for type implementations. Similar to G_DEFINE_TYPE(), but allows to insert custom code into the *_get_type() function, e.g. interface implementations via G_IMPLEMENT_INTERFACE(). See G_DEFINE_TYPE_EXTENDED() for an example.

TN : | The name of the new type, in Camel case.
t_n : | The name of the new type in lowercase, with words separated by '_'.
T_P : | The GType of the parent type.
_C_ : | Custom code that gets inserted in the *_get_type() function.

G_DEFINE_ABSTRACT_TYPE()

#define G_DEFINE_ABSTRACT_TYPE(TN, t_n, T_P)                G_DEFINE_TYPE_EXTENDED (TN, t_n, T_P, G_TYPE_FLAG_ABSTRACT, {})

A convenience macro for type implementations. Similar to G_DEFINE_TYPE(), but defines an abstract type. See G_DEFINE_TYPE_EXTENDED() for an example.

TN : | The name of the new type, in Camel case.
t_n : | The name of the new type, in lowercase, with words separated by '_'.
T_P : | The GType of the parent type.

G_DEFINE_ABSTRACT_TYPE_WITH_CODE()

#define G_DEFINE_ABSTRACT_TYPE_WITH_CODE(TN, t_n, T_P, _C_) G_DEFINE_TYPE_EXTENDED (TN, t_n, T_P, G_TYPE_FLAG_ABSTRACT, _C_)

A convenience macro for type implementations. Similar to G_DEFINE_TYPE_WITH_CODE(), but defines an abstract type and allows to insert custom code into the *_get_type() function, e.g. interface implementations via G_IMPLEMENT_INTERFACE(). See G_DEFINE_TYPE_EXTENDED() for an example.

TN : | The name of the new type, in Camel case.
t_n : | The name of the new type, in lowercase, with words separated by '_'.
T_P : | The GType of the parent type.
_C_ : | Custom code that gets inserted in the @type_name_get_type() function.

G_IMPLEMENT_INTERFACE()

#define     G_IMPLEMENT_INTERFACE(TYPE_IFACE, iface_init)

A convenience macro to ease interface addition in the _C_ section of G_DEFINE_TYPE_WITH_CODE() or G_DEFINE_ABSTRACT_TYPE_WITH_CODE(). See G_DEFINE_TYPE_EXTENDED() for an example.

Note that this macro can only be used together with the G_DEFINE_TYPE_* macros, since it depends on variable names from those macros.

TYPE_IFACE : | The GType of the interface to add
iface_init : | The interface init function

G_DEFINE_TYPE_EXTENDED()

#define     G_DEFINE_TYPE_EXTENDED(TypeName, type_name, TYPE_PARENT, flags, CODE)

The most general convenience macro for type implementations, on which G_DEFINE_TYPE(), etc are based.

G_DEFINE_TYPE_EXTENDED (GtkGadget, gtk_gadget, GTK_TYPE_WIDGET, 0, G_IMPLEMENT_INTERFACE (TYPE_GIZMO, gtk_gadget_gizmo_init));
expands to
static void     gtk_gadget_init       (GtkGadget      *self);
static void     gtk_gadget_class_init (GtkGadgetClass *klass);
static gpointer gtk_gadget_parent_class = NULL;
static void     gtk_gadget_class_intern_init (gpointer klass)
{
  gtk_gadget_parent_class = g_type_class_peek_parent (klass);
  gtk_gadget_class_init ((GtkGadgetClass*) klass);
}

GType
gtk_gadget_get_type (void)
{
  static GType g_define_type_id = 0;
  if (G_UNLIKELY (g_define_type_id == 0))
    {
      static const GTypeInfo g_define_type_info = {
        sizeof (GtkGadgetClass),
        (GBaseInitFunc) NULL,
        (GBaseFinalizeFunc) NULL,
        (GClassInitFunc) gtk_gadget_class_intern_init,
        (GClassFinalizeFunc) NULL,
        NULL,   /* class_data */
        sizeof (GtkGadget),
        0,      /* n_preallocs */
        (GInstanceInitFunc) gtk_gadget_init,
      };
      g_define_type_id = g_type_register_static (GTK_TYPE_WIDGET, "GtkGadget", &g_define_type_info, 0);
      {
        static const GInterfaceInfo g_implement_interface_info = {
          (GInterfaceInitFunc) gtk_gadget_gizmo_init
        };
        g_type_add_interface_static (g_define_type_id, TYPE_GIZMO, &g_implement_interface_info);
      }
    }
  return g_define_type_id;
}
The only pieces which have to be manually provided are the definitions of the instance and class structure and the definitions of the instance and class init functions.
TypeName : | The name of the new type, in Camel case.
type_name : | The name of the new type, in lowercase, with words separated by '_'.
TYPE_PARENT : | The GType of the parent type.
flags : | GTypeFlags to pass to g_type_register_static()
CODE : | Custom code that gets inserted in the *_get_type() function.

G_TYPE_INVALID

#define G_TYPE_INVALID			G_TYPE_MAKE_FUNDAMENTAL (0)

An invalid GType, used as error return value in some functions which return a GType.

G_TYPE_NONE

#define G_TYPE_NONE			G_TYPE_MAKE_FUNDAMENTAL (1)

A fundamental type which is used as a replacement for the C void return type.

G_TYPE_INTERFACE

#define G_TYPE_INTERFACE		G_TYPE_MAKE_FUNDAMENTAL (2)

The fundamental type from which all interfaces are derived.

G_TYPE_CHAR

#define G_TYPE_CHAR			G_TYPE_MAKE_FUNDAMENTAL (3)

The fundamental type corresponding to gchar.

G_TYPE_UCHAR

#define G_TYPE_UCHAR			G_TYPE_MAKE_FUNDAMENTAL (4)

The fundamental type corresponding to guchar.

G_TYPE_BOOLEAN

#define G_TYPE_BOOLEAN			G_TYPE_MAKE_FUNDAMENTAL (5)

The fundamental type corresponding to gboolean.

G_TYPE_INT

#define G_TYPE_INT			G_TYPE_MAKE_FUNDAMENTAL (6)

The fundamental type corresponding to gint.

G_TYPE_UINT

#define G_TYPE_UINT			G_TYPE_MAKE_FUNDAMENTAL (7)

The fundamental type corresponding to guint.

G_TYPE_LONG

#define G_TYPE_LONG			G_TYPE_MAKE_FUNDAMENTAL (8)

The fundamental type corresponding to glong.

G_TYPE_ULONG

#define G_TYPE_ULONG			G_TYPE_MAKE_FUNDAMENTAL (9)

The fundamental type corresponding to gulong.

G_TYPE_INT64

#define G_TYPE_INT64			G_TYPE_MAKE_FUNDAMENTAL (10)

The fundamental type corresponding to gint64.

G_TYPE_UINT64

#define G_TYPE_UINT64			G_TYPE_MAKE_FUNDAMENTAL (11)

The fundamental type corresponding to guint64.

G_TYPE_ENUM

#define G_TYPE_ENUM			G_TYPE_MAKE_FUNDAMENTAL (12)

The fundamental type from which all enumeration types are derived.

G_TYPE_FLAGS

#define G_TYPE_FLAGS			G_TYPE_MAKE_FUNDAMENTAL (13)

The fundamental type from which all flags types are derived.

G_TYPE_FLOAT

#define G_TYPE_FLOAT			G_TYPE_MAKE_FUNDAMENTAL (14)

The fundamental type corresponding to gfloat.

G_TYPE_DOUBLE

#define G_TYPE_DOUBLE			G_TYPE_MAKE_FUNDAMENTAL (15)

The fundamental type corresponding to gdouble.

G_TYPE_STRING

#define G_TYPE_STRING			G_TYPE_MAKE_FUNDAMENTAL (16)

The fundamental type corresponding to nul-terminated C strings.

G_TYPE_POINTER

#define G_TYPE_POINTER			G_TYPE_MAKE_FUNDAMENTAL (17)

The fundamental type corresponding to gpointer.

G_TYPE_BOXED

#define G_TYPE_BOXED			G_TYPE_MAKE_FUNDAMENTAL (18)

The fundamental type from which all boxed types are derived.

G_TYPE_PARAM

#define G_TYPE_PARAM			G_TYPE_MAKE_FUNDAMENTAL (19)

The fundamental type from which all GParamSpec types are derived.

G_TYPE_OBJECT

#define G_TYPE_OBJECT			G_TYPE_MAKE_FUNDAMENTAL (20)

The fundamental type for GObject.

G_TYPE_RESERVED_GLIB_FIRST

#define G_TYPE_RESERVED_GLIB_FIRST	(21)

First fundamental type number to create a new fundamental type id with G_TYPE_MAKE_FUNDAMENTAL() reserved for GLib.

G_TYPE_RESERVED_GLIB_LAST

#define G_TYPE_RESERVED_GLIB_LAST	(31)

Last fundamental type number reserved for GLib.

G_TYPE_RESERVED_BSE_FIRST

#define G_TYPE_RESERVED_BSE_FIRST	(32)

First fundamental type number to create a new fundamental type id with G_TYPE_MAKE_FUNDAMENTAL() reserved for BSE.

G_TYPE_RESERVED_BSE_LAST

#define G_TYPE_RESERVED_BSE_LAST	(48)

Last fundamental type number reserved for BSE.

G_TYPE_RESERVED_USER_FIRST

#define G_TYPE_RESERVED_USER_FIRST	(49)

First available fundamental type number to create new fundamental type id with G_TYPE_MAKE_FUNDAMENTAL().

Feedback

For additional information or queries on this page send feedback


Value arrays

Name

Value arrays — A container structure to maintain an array of generic values.

Library

gobject.lib

Synopsis

#include <glib-object.h>

             GValueArray;
GValue*      g_value_array_get_nth           (GValueArray *value_array, guint index_);
GValueArray* g_value_array_new               (guint n_prealloced);
GValueArray* g_value_array_copy              (const GValueArray *value_array);
void         g_value_array_free              (GValueArray *value_array);
GValueArray* g_value_array_append            (GValueArray *value_array, const GValue *value);
GValueArray* g_value_array_prepend           (GValueArray *value_array, const GValue *value);
GValueArray* g_value_array_insert            (GValueArray *value_array, guint index_, const GValue *value);
GValueArray* g_value_array_remove            (GValueArray *value_array, guint index_);
GValueArray* g_value_array_sort              (GValueArray *value_array, GCompareFunc compare_func);
GValueArray* g_value_array_sort_with_data    (GValueArray *value_array, GCompareDataFunc compare_func, gpointer user_data);

Detailed Description

The prime purpose of a GValueArray is for it to be used as an object property that holds an array of values. A GValueArray wraps an array of GValue elements in order for it to be used as a boxed type through G_TYPE_VALUE_ARRAY.

Details

GValueArray

typedef struct {
  guint   n_values;
  GValue *values;
} GValueArray;

A GValueArray contains an array of GValue elements.

guint n_values; | number of values contained in the array
GValue *values; | array of values

g_value_array_get_nth ()

GValue*     g_value_array_get_nth           (GValueArray *value_array, guint index_);

Return a pointer to the value at index_ containd in value_array.

value_array : | GValueArray to get a value from
index_ : | index of the value of interest
Returns : | pointer to a value at index_ in value_array

g_value_array_new ()

GValueArray* g_value_array_new             (guint n_prealloced);

Allocates and initializes a new GValueArray, optionally preserves space for n_prealloced elements. New arrays always contain 0 elements, regardless of the value of n_prealloced.

n_prealloced : | number of values to preallocate space for
Returns : | a newly allocated GValueArray with 0 values

g_value_array_copy ()

GValueArray* g_value_array_copy            (const GValueArray *value_array);

Constructs an exact copy of a GValueArray by duplicating all its contents.

value_array : | GValueArray to copy
Returns : | Newly allocated copy of GValueArray

g_value_array_free ()

void        g_value_array_free              (GValueArray *value_array);

Frees a GValueArray including its contents.

value_array : GValueArray to free

g_value_array_append ()

GValueArray* g_value_array_append           (GValueArray *value_array, const GValue *value);

Inserts a copy of value as last element of value_array.

value_array : | GValueArray to add an element to
value : | GValue to copy into GValueArray
Returns : | the GValueArray passed in as value_array

g_value_array_prepend ()

GValueArray* g_value_array_prepend          (GValueArray *value_array, const GValue *value);

Inserts a copy of value as first element of value_array.

value_array : | GValueArray to add an element to
value : | GValue to copy into GValueArray
Returns : | the GValueArray passed in as value_array

g_value_array_insert ()

GValueArray* g_value_array_insert           (GValueArray *value_array, guint index_, const GValue *value);

Inserts a copy of value at specified position into value_array.

value_array : | GValueArray to add an element to
index_ : | insertion position, must be <= value_array->n_values
value : | GValue to copy into GValueArray
Returns : | the GValueArray passed in as value_array

g_value_array_remove ()

GValueArray* g_value_array_remove           (GValueArray *value_array, guint index_);

Removes the value at position index_ from value_array.

value_array : | GValueArray to remove an element from
index_ : | position of value to remove, must be < value_array->n_values
Returns : | the GValueArray passed in as value_array

g_value_array_sort ()

GValueArray* g_value_array_sort             (GValueArray *value_array, GCompareFunc compare_func);

Sorts value_array using compare_func to compare the elements accoring to the semantics of GCompareFunc.

The current implementation uses Quick-Sort as sorting algorithm.

value_array : | GValueArray to sort
compare_func : | function to compare elements
Returns : | the GValueArray passed in as value_array

g_value_array_sort_with_data ()

GValueArray* g_value_array_sort_with_data      (GValueArray *value_array, GCompareDataFunc compare_func, gpointer user_data);

Sorts value_array using compare_func to compare the elements accoring to the semantics of GCompareDataFunc.

The current implementation uses Quick-Sort as sorting algorithm.

value_array : | GValueArray to sort
compare_func : | function to compare elements
user_data : | extra data argument provided for compare_func
Returns : | the GValueArray passed in as value_array

See Also

GValue, GParamSpecValueArray, g_param_spec_value_array()

Feedback

For additional information or queries on this page send feedback

©2005-2006 Nokia


Varargs Value Collection

Name

Varargs Value Collection — Converting varargs to generic values.

Library

gobject.lib

Synopsis

#include <glib-object.h>
#include <gobject/gvaluecollector.h>

union       GTypeCValue;
#define     G_VALUE_COLLECT                   (value, var_args, flags, __error)
#define     G_VALUE_LCOPY                     (value, var_args, flags, __error)
#define     G_VALUE_COLLECT_FORMAT_MAX_LENGTH

Detailed Description

The macros in this section provide the varargs parsing support needed in variadic GObject functions such as g_object_new() or g_object_set(). They currently support the collection of integral types, floating point types and pointers.

Details

union GTypeCValue

union GTypeCValue
{
  gint     v_int;
  glong    v_long;
  gint64   v_int64;
  gdouble  v_double;
  gpointer v_pointer;
};

A union holding one collected value.

G_VALUE_COLLECT()

#define     G_VALUE_COLLECT(value, var_args, flags, __error)

Collects a variable argument value from a va_list. We have to implement the varargs collection as a macro, because on some systems va_list variables cannot be passed by reference.

value : | a GValue return location. value is supposed to be initialized according to the value type to be collected
var_args : | the va_list variable; it may be evaluated multiple times
flags : | flags which are passed on to the collect_value() function of the GTypeValueTable of value.
__error : | a gchar** variable that will be modified to hold a g_new() allocated error messages if something fails

G_VALUE_LCOPY()

#define     G_VALUE_LCOPY(value, var_args, flags, __error)

Collects a value's variable argument locations from a va_list.

value : | a GValue return location. value is supposed to be initialized according to the value type to be collected
var_args : | the va_list variable; it may be evaluated multiple times
flags : | flags which are passed on to the lcopy_value() function of the GTypeValueTable of value.
__error : | a gchar** variable that will be modified to hold a g_new() allocated error messages if something fails

G_VALUE_COLLECT_FORMAT_MAX_LENGTH

#define	G_VALUE_COLLECT_FORMAT_MAX_LENGTH	(8)

The maximal number of GTypeCValues which can be collected for a single GValue.

See Also

GValueTable

Feedback

For additional information or queries on this page send feedback


Conventions

There are a number of conventions users are expected to follow when creating new types which are to be exported in a header file:

  • Use the object_method pattern for function names: to invoke the method named foo on an instance of object type bar, call bar_foo.

  • Use prefixing to avoid namespace conflicts with other projects. If your library (or application) is named Maman, prefix all your function names with maman_. For example: maman_object_method.

  • Create a macro named PREFIX_OBJECT_TYPE which always returns the Gtype for the associated object type. For an object of type Bar in a libray prefixed by maman, use: MAMAN_BAR_TYPE. It is common although not a convention to implement this macro using either a global static variable or a function named prefix_object_get_type. We will follow the function pattern wherever possible in this document.

  • Create a macro named PREFIX_OBJECT (obj) which returns a pointer of type PrefixObject. This macro is used to enforce static type safety by doing explicit casts wherever needed. It also enforces dynamic type safety by doing runtime checks. It is possible to disable the dynamic type checks in production builds (see http://developer.gnome.org/doc/API/2.0/glib/glib-building.html). For example, we would create MAMAN_BAR (obj) to keep the previous example.

  • If the type is classed, create a macro named PREFIX_OBJECT_CLASS (klass). This macro is strictly equivalent to the previous casting macro: it does static casting with dynamic type checking of class structures. It is expected to return a pointer to a class structure of type PrefixObjectClass. Again, an example is: MAMAN_BAR_CLASS.

  • Create a macro named PREFIX_IS_BAR (obj): this macro is expected to return a gboolean which indicates whether or not the input object instance pointer of type BAR.

  • If the type is classed, create a macro named PREFIX_IS_OBJECT_CLASS (klass) which, as above, returns a boolean if the input class pointer is a pointer to a class of type OBJECT.

  • If the type is classed, create a macro named PREFIX_OBJECT_GET_CLASS (obj) which returns the class pointer associated to an instance of a given type. This macro is used for static and dynamic type safety purposes (just like the previous casting macros).

The implementation of these macros is pretty straightforward: a number of simple-to-use macros are provided in gtype.h. For the example we used above, we would write the following trivial code to declare the macros:

#define MAMAN_BAR_TYPE		  (maman_bar_get_type ())
#define MAMAN_BAR(obj)		  (G_TYPE_CHECK_INSTANCE_CAST ((obj), MAMAN_BAR_TYPE, MamanBar))
#define MAMAN_BAR_CLASS(klass)	  (G_TYPE_CHECK_CLASS_CAST ((klass), MAMAN_BAR_TYPE, MamanBarClass))
#define MAMAN_IS_BAR(obj)	  (G_TYPE_CHECK_INSTANCE_TYPE ((obj), MAMAN_BAR_TYPE))
#define MAMAN_IS_BAR_CLASS(klass) (G_TYPE_CHECK_CLASS_TYPE ((klass), MAMAN_BAR_TYPE))
#define MAMAN_BAR_GET_CLASS(obj)  (G_TYPE_INSTANCE_GET_CLASS ((obj), MAMAN_BAR_TYPE, MamanBarClass))

Note: Stick to the naming klass as class is a registered c++ keyword.

The following code shows how to implement the maman_bar_get_type function:

GType maman_bar_get_type (void)
{
  static GType type = 0;
  if (type == 0) {
    static const GTypeInfo info = {
      /* You fill this structure. */
    };
    type = g_type_register_static (G_TYPE_OBJECT, "MamanBarType", &info, 0);
  }
  return type;
}


Instantiable classed types: objects

Types which are registered with a class and are declared instantiable are what most closely resembles an object. Although GObjects (detailed in The GObject base class) are the most well known type of instantiable classed types, other kinds of similar objects used as the base of an inheritance hierarchy have been externally developped and they are all built on the fundamental features described below.

For example, the code below shows how you could register such a fundamental object type in the type system:

typedef struct {
  GObject parent;
  /* instance members */
  int field_a;
} MamanBar;

typedef struct {
  GObjectClass parent;
  /* class members */
  void (*do_action_public_virtual) (MamanBar *self, guint8 i);

  void (*do_action_public_pure_virtual) (MamanBar *self, guint8 i);
} MamanBarClass;

#define MAMAN_BAR_TYPE (maman_bar_get_type ())

GType
maman_bar_get_type (void)
{
  static GType type = 0;
  if (type == 0) {
    static const GTypeInfo info = {
      sizeof (MamanBarClass),
      NULL,           /* base_init */
      NULL,           /* base_finalize */
      (GClassInitFunc) foo_class_init,
      NULL,           /* class_finalize */
      NULL,           /* class_data */
      sizeof (MamanBar),
      0,              /* n_preallocs */
      (GInstanceInitFunc) NULL /* instance_init */
    };
    type = g_type_register_static (G_TYPE_OBJECT, "BarType", &info, 0);
  }
  return type;
}

Upon the first call to maman_bar_get_type, the type named BarType will be registered in the type system as inheriting from the type G_TYPE_OBJECT.

Every object must define two structures: its class structure and its instance structure. All class structures must contain as first member a GTypeClass structure. All instance structures must contain as first member a GTypeInstance structure. The declaration of these C types, coming from gtype.h is shown below:

struct _GTypeClass
{
  GType g_type;
};
struct _GTypeInstance
{
  GTypeClass *g_class;
};

These constraints allow the type system to make sure that every object instance (identified by a pointer to the object's instance structure) contains in its first bytes a pointer to the object's class structure.

This relationship is best explained by an example: let's take object B which inherits from object A:

/* A definitions */
typedef struct {
  GTypeInstance parent;
  int field_a;
  int field_b;
} A;
typedef struct {
  GTypeClass parent_class;
  void (*method_a) (void);
  void (*method_b) (void);
} AClass;

/* B definitions. */
typedef struct {
  A parent;
  int field_c;
  int field_d;
} B;
typedef struct {
  AClass parent_class;
  void (*method_c) (void);
  void (*method_d) (void);
} BClass;

The C standard mandates that the first field of a C structure is stored starting in the first byte of the buffer used to hold the structure's fields in memory. This means that the first field of an instance of an object B is A's first field which in turn is GTypeInstance's first field which in turn is g_class, a pointer to B's class structure.

Thanks to these simple conditions, it is possible to detect the type of every object instance by doing:

B *b;
b->parent.parent.g_class->g_type

or, more quickly:

B *b;
((GTypeInstance*)b)->g_class->g_type

Instanciation of these types can be done with g_type_create_instance:

GTypeInstance* g_type_create_instance (GType type);
void           g_type_free_instance   (GTypeInstance *instance);

g_type_create_instance will lookup the type information structure associated to the type requested. Then, the instance size and instanciation policy (if the n_preallocs field is set to a non-zero value, the type system allocates the object's instance structures in chunks rather than mallocing for every instance) declared by the user are used to get a buffer to hold the object's instance structure.

If this is the first instance of the object ever created, the type system must create a class structure: it allocates a buffer to hold the object's class structure and initializes it. It first copies the parent's class structure over this structure (if there is no parent, it initializes it to zero). It then invokes the base_class_initialization functions (GBaseInitFunc) from topmost fundamental object to bottom-most most derived object. The object's class_init (GClassInitFunc) function is invoked afterwards to complete initialization of the class structure. Finally, the object's interfaces are initialized (we will discuss interface initialization in more detail later). [3]

Once the type system has a pointer to an initialized class structure, it sets the object's instance class pointer to the object's class structure and invokes the object's instance_init (GInstanceInitFunc)functions, from top-most fundamental type to bottom-most most derived type.

Object instance destruction through g_type_free_instance is very simple: the instance structure is returned to the instance pool if there is one and if this was the last living instance of the object, the class is destroyed.

Class destruction [4] (the concept of destruction is sometimes partly refered to as finalization in Gtype) is the symmetric process of the initialization: interfaces are destroyed first. Then, the most derived class_finalize (ClassFinalizeFunc) function is invoked. The base_class_finalize (GBaseFinalizeFunc) functions are Finally invoked from bottom-most most-derived type to top-most fundamental type and the class structure is freed.

As many readers have now understood it, the base initialization/finalization process is very similar to the C++ Constructor/Destructor paradigm. The practical details are quite different though and it is important not to get confused by the superficial similarities. Typically, what most users have grown to know as a C++ constructor (that is, a list of object methods invoked on the object instance once for each type of the inheritance hierachy) does not exist in GType and must be built on top of the facilities offered by GType. Similarly, GTypes have no instance destruction mechanism. It is the user's responsibility to implement correct destruction semantics on top of the existing GType code. (this is what GObject does. See The GObject base class)

For example, if the object B which derives from A is instantiated, GType will only invoke the instance_init callback of object B while a C++ runtime will invoke the constructor of the object type A first and then of the object type B. Furthermore, the C++ code equivalent to the base_init and class_init callbacks of GType is usually not needed because C++ cannot really create object types at runtime.

The instanciation/finalization process can be summarized as follows:

Table 1. GType Instantiation/Finalization

Invocation time | Function Invoked | Function's parameters
First call to g_type_create_instance for target type | type's base_init function | On the inheritance tree of classes from fundamental type to target type. base_init is invoked once for each class structure.
First call to g_type_create_instance for target type | target type's class_init function | On target type's class structure
First call to g_type_create_instance for target type | interface initialization, see the section called “Interface Initialization” |
Each call to g_type_create_instance for target type | target type's instance_init function | On object's instance
Last call to g_type_free_instance for target type | interface destruction, see the section called “Interface Destruction” |
Last call to g_type_free_instance for target type | target type's class_finalize function | On target type's class structure
Last call to g_type_free_instance for target type | type's base_finalize function | On the inheritance tree of classes from fundamental type to target type. base_finalize is invoked once for each class structure.

[3] The class initialization process is entirely implemented in type_class_init_Wm in gtype.c.

[4] It is implemented in type_data_finalize_class_U (in gtype.c).

©2005-2006 Nokia


Non-Instantiable non-classed fundamental types

A lot of types are not instantiable by the type system and do not have a class. Most of these types are fundamental trivial types such as gchar, registered in g_value_types_init (in gvaluetypes.c).

To register such a type in the type system, you just need to fill the GTypeInfo structure with zeros since these types are also most of the time fundamental:

  GTypeInfo info = {
    0,				/* class_size */
    NULL,			/* base_init */
    NULL,			/* base_destroy */
    NULL,			/* class_init */
    NULL,			/* class_destroy */
    NULL,			/* class_data */
    0,				/* instance_size */
    0,				/* n_preallocs */
    NULL,			/* instance_init */
    NULL,			/* value_table */
    };
   static const GTypeValueTable value_table = {
   value_init_long0,		/* value_init */
   NULL,			/* value_free */
   value_copy_long0,		/* value_copy */
   NULL,			/* value_peek_pointer */
   "i",			        /* collect_format */
   value_collect_int,	        /* collect_value */
   "p",			        /* lcopy_format */
   value_lcopy_char,		/* lcopy_value */
  };
  info.value_table = &value_table;
  type = g_type_register_fundamental (G_TYPE_CHAR, "gchar", &info, &finfo, 0);

Having non-instantiable types might seem a bit useless: what good is a type if you cannot instanciate an instance of that type ? Most of these types are used in conjunction with GValues: a GValue is initialized with an integer or a string and it is passed around by using the registered type's value_table. GValues (and by extension these trivial fundamental types) are most useful when used in conjunction with object properties and signals.


Non-instantiable classed types: Interfaces

GType's Interfaces are very similar to Java's interfaces. To declare one of these you have to register a non-instantiable classed type which derives from GTypeInterface. The following piece of code declares such an interface.

#define MAMAN_IBAZ_TYPE                (maman_ibaz_get_type ())
#define MAMAN_IBAZ(obj)                (G_TYPE_CHECK_INSTANCE_CAST ((obj), MAMAN_IBAZ_TYPE, MamanIbaz))
#define MAMAN_IS_IBAZ(obj)             (G_TYPE_CHECK_INSTANCE_TYPE ((obj), MAMAN_IBAZ_TYPE))
#define MAMAN_IBAZ_GET_INTERFACE(inst) (G_TYPE_INSTANCE_GET_INTERFACE ((inst), MAMAN_IBAZ_TYPE, MamanIbazInterface))

typedef struct _MamanIbaz MamanIbaz; /* dummy object */
typedef struct _MamanIbazInterface MamanIbazInterface;

struct _MamanIbazInterface {
  GTypeInterface parent;

  void (*do_action) (MamanIbaz *self);
};

GType maman_ibaz_get_type (void);

void maman_ibaz_do_action (MamanIbaz *self);

The interface function, maman_ibaz_do_action is implemented in a pretty simple way:

void maman_ibaz_do_action (MamanIbaz *self)
{
  MAMAN_IBAZ_GET_INTERFACE (self)->do_action (self);
}

maman_ibaz_get_type registers a type named MamanIBaz which inherits from G_TYPE_INTERFACE. All interfaces must be children of G_TYPE_INTERFACE in the inheritance tree.

An interface is defined by only one structure which must contain as first member a GTypeInterface structure. The interface structure is expected to contain the function pointers of the interface methods. It is good style to define helper functions for each of the interface methods which simply call the interface' method directly: maman_ibaz_do_action is one of these.

Once an interface type is registered, you must register implementations for these interfaces. The function named maman_baz_get_type registers a new GType named MamanBaz which inherits from GObject and which implements the interface MamanIBaz.

static void maman_baz_do_action (MamanIbaz *self)
{
  g_print ("Baz implementation of IBaz interface Action.\n");
}

static void
baz_interface_init (gpointer g_iface, gpointer iface_data)
{
  MamanIbazInterface *iface = (MamanIbazInterface *)g_iface;
  iface->do_action = maman_baz_do_action;
}

GType
maman_baz_get_type (void)
{
  static GType type = 0;
  if (type == 0) {
    static const GTypeInfo info = {
      sizeof (MamanBazInterface),
      NULL,   /* base_init */
      NULL,   /* base_finalize */
      NULL,   /* class_init */
      NULL,   /* class_finalize */
      NULL,   /* class_data */
      sizeof (MamanBaz),
      0,      /* n_preallocs */
      NULL    /* instance_init */
    };
    static const GInterfaceInfo ibaz_info = {
      (GInterfaceInitFunc) baz_interface_init,    /* interface_init */
      NULL,               /* interface_finalize */
      NULL          /* interface_data */
    };
    type = g_type_register_static (G_TYPE_OBJECT, "MamanBazType", &info, 0);
    g_type_add_interface_static (type, MAMAN_IBAZ_TYPE, &ibaz_info);
  }
  return type;
}

g_type_add_interface_static records in the type system that a given type implements also FooInterface (foo_interface_get_type returns the type of FooInterface). The GInterfaceInfo structure holds information about the implementation of the interface:

struct _GInterfaceInfo
{
  GInterfaceInitFunc        interface_init;
  GInterfaceFinalizeFunc    interface_finalize;
  gpointer                  interface_data;
};

Interface Initialization

When an instantiable classed type which registered an interface implementation is created for the first time, its class structure is initialized following the process described in the section called “Instantiable classed types: objects”. Once the class structure is initialized,the function type_class_init_Wm (implemented in gtype.c) initializes the interface implementations associated with that type by calling type_iface_vtable_init_Wm for each interface.

First a memory buffer is allocated to hold the interface structure. The parent's interface structure is then copied over to the new interface structure (the parent interface is already initialized at that point). If there is no parent interface, the interface structure is initialized with zeros. The g_type and the g_instance_type fields are then initialized: g_type is set to the type of the most-derived interface and g_instance_type is set to the type of the most derived type which implements this interface.

Finally, the interface' most-derived base_init function and then the implementation's interface_init function are invoked. It is important to understand that if there are multiple implementations of an interface the base_init and interface_init functions will be invoked once for each implementation initialized.

It is thus common for base_init functions to hold a local static boolean variable which makes sure that the interface type is initialized only once even if there are multiple implementations of the interface:

static void
maman_ibaz_base_init (gpointer g_iface)
{
  static gboolean initialized = FALSE;

  if (!initialized) {
    /* create interface signals here. */
    initialized = TRUE;
  }
}

If you have found the stuff about interface hairy, you are right: it is hairy but there is not much I can do about it. What I can do is summarize what you need to know about interfaces:

The above process can be summarized as follows:

Table 2. Interface Initialization

Invocation time | Function Invoked | Function's parameters | Remark
First call to g_type_create_instance for type implementing interface | interface' base_init function | On interface' vtable | Register interface' signals here (use a local static boolean variable as described above to make sure not to register them twice.).
First call to g_type_create_instance for type implementing interface | interface' interface_init function | On interface' vtable | Initialize interface' implementation. That is, initialize the interface method pointers in the interface structure to the function's implementation.

It is highly unlikely (ie: I do not know of anyone who actually used it) you will ever need other more fancy things such as the ones described in the following section (the section called “Interface Destruction”).

Interface Destruction

When the last instance of an instantiable type which registered an interface implementation is destroyed, the interface's implementations associated to the type are destroyed by type_iface_vtable_finalize_Wm (in gtype.c).

type_iface_vtable_finalize_Wm invokes first the implementation's interface_finalize function and then the interface's most-derived base_finalize function.

Again, it is important to understand, as in the section called “Interface Initialization”, that both interface_finalize and base_finalize are invoked exactly once for the destruction of each implementation of an interface. Thus, if you were to use one of these functions, you would need to use a static integer variable which would hold the number of instances of implementations of an interface such that the interface's class is destroyed only once (when the integer variable reaches zero).

The above process can be summarized as follows:

Table 3. Interface Finalization

Invocation time | Function Invoked | Function's parameters
Last call to g_type_free_instance for type implementing interface | interface' interface_finalize function | On interface' vtable
Last call to g_type_free_instancefor type implementing interface | interface' base_finalize function | On interface' vtable

Now that you have read this section, you can forget about it. Please, forget it as soon as possible.


GTypeModule

Name

GTypeModule — Type loading modules.

Library

gobject.lib

Synopsis

#include <glib-object.h>
            GTypeModule;
            GTypeModuleClass;
gboolean    g_type_module_use               (GTypeModule *module);
void        g_type_module_unuse             (GTypeModule *module);
void        g_type_module_set_name          (GTypeModule *module, const gchar *name);
GType       g_type_module_register_type     (GTypeModule *module, GType parent_type, const gchar *type_name,
                                             const GTypeInfo *type_info, GTypeFlags flags);
void        g_type_module_add_interface     (GTypeModule *module, GType instance_type, GType interface_type,
                                             const GInterfaceInfo *interface_info);
GType       g_type_module_register_enum     (GTypeModule *module, const gchar *name, const GEnumValue *const_static_values);
GType       g_type_module_register_flags    (GTypeModule *module, const gchar *name, const GFlagsValue *const_static_values);

Object Hierarchy

  GObject
   +----GTypeModule

Implemented Interfaces

GTypeModule implements GTypePlugin.

Detailed Description

GTypeModule provides a simple implementation of the GTypePlugin interface. The model of GTypeModule is a dynamically loaded module which implements some number of types and interface implementations. When the module is loaded, it registers its types and interfaces using g_type_module_register_type() and g_type_module_add_interface(). As long as any instances of these types and interface implementations are in use, the module is kept loaded. When the types and interfaces are gone, the module may be unloaded. If the types and interfaces become used again, the module will be reloaded.

Keeping track of whether the module should be loaded or not is done by using a use count - it starts at zero, and whenever it is greater than zero, the module is loaded. The use count is maintained internally by the type system, but also can be explicitly controlled by g_type_module_use() and g_type_module_unuse(). Typically, when loading a module for the first type, g_type_module_use() will be used to load it so that it can initialize its types. At some later point, when the module no longer needs to be loaded except for the type implementations it contains, g_type_module_unuse() is called.

GTypeModule does not actually provide any implementation of module loading and unloading. To create a particular module type, derive from GTypeModule and implement the load and unload functions in GTypeModuleClass.

Details

GTypeModule

typedef struct {
  gchar *name;
} GTypeModule;

The members of the GTypeModule structure should not be accessed directly, except for the name field.

gchar *name; the name of the module

GTypeModuleClass

typedef struct {
  GObjectClass parent_class;

  gboolean (* load)   (GTypeModule *module);
  void     (* unload) (GTypeModule *module);
} GTypeModuleClass;

In order to implement dynamic loading of types based on GTypeModule, the load and unload functions in GTypeModuleClass must be implemented.

GObjectClass parent_class; | the parent class
load () | loads the module and registers one or more types using g_type_module_register_type().
unload () | unloads the module

g_type_module_use ()

gboolean    g_type_module_use        (GTypeModule *module);

Increases the use count of a GTypeModule by one. If the use count was zero before, the plugin will be loaded.

module : | a GTypeModule
Returns : | FALSE if the plugin needed to be loaded and loading the plugin failed.

g_type_module_unuse ()

void        g_type_module_unuse       (GTypeModule *module);

Decreases the use count of a GTypeModule by one. If the result is zero, the module will be unloaded. (However, the GTypeModule will not be freed, and types associated with the GTypeModule are not unregistered. Once a GTypeModule is initialized, it must exist forever.)

module : a GTypeModule

g_type_module_set_name ()

void        g_type_module_set_name    (GTypeModule *module, const gchar *name);

Sets the name for a GTypeModule.

module : | a GTypeModule.
name : | a human-readable name to use in error messages.

g_type_module_register_type ()

GType   g_type_module_register_type     (GTypeModule *module, GType parent_type, const gchar *type_name, const GTypeInfo *type_info, GTypeFlags flags);

Looks up or registers a type that is implemented with a particular type plugin. If a type with name type_name was previously registered, the GType identifier for the type is returned, otherwise the type is newly registered, and the resulting GType identifier returned.

When reregistering a type (typically because a module is unloaded then reloaded, and reinitialized), module and parent_type must be the same as they were previously.

As long as any instances of the type exist, the type plugin will not be unloaded.

module : | a GTypeModule
parent_type : | the type for the parent class
type_name : | name for the type
type_info : | type information structure
flags : | flags field providing details about the type
Returns : | the new or existing type ID

g_type_module_add_interface ()

void    g_type_module_add_interface     (GTypeModule *module, GType instance_type, GType interface_type, const GInterfaceInfo *interface_info);

Registers an additional interface for a type, whose interface lives in the given type plugin. If the interface was already registered for the type in this plugin, nothing will be done.

As long as any instances of the type exist, the type plugin will not be unloaded.

module : | a GTypeModule
instance_type : | type to which to add the interface.
interface_type : | interface type to add
interface_info : | type information structure

g_type_module_register_enum ()

GType    g_type_module_register_enum     (GTypeModule *module, const gchar *name, const GEnumValue *const_static_values);

Looks up or registers an enumeration that is implemented with a particular type plugin. If a type with name type_name was previously registered, the GType identifier for the type is returned, otherwise the type is newly registered, and the resulting GType identifier returned.

As long as any instances of the type exist, the type plugin will not be unloaded.

module : | a GTypeModule
name : | name for the type
const_static_values : | an array of GEnumValue structs for the possible enumeration values. The array is terminated by a struct with all members being 0.
Returns : | the new or existing type ID

g_type_module_register_flags ()

GType    g_type_module_register_flags    (GTypeModule *module, const gchar *name, const GFlagsValue *const_static_values);

Looks up or registers a flags type that is implemented with a particular type plugin. If a type with name type_name was previously registered, the GType identifier for the type is returned, otherwise the type is newly registered, and the resulting GType identifier returned.

As long as any instances of the type exist, the type plugin will not be unloaded.

module : | a GTypeModule
name : | name for the type
const_static_values : | an array of GFlagsValue structs for the possible flags values. The array is terminated by a struct with all members being 0.
Returns : | the new or existing type ID

See Also

GTypePlugin | The abstract type loader interface.
GModule | Portable mechanism for dynamically loaded modules.

Feedback

For additional information or queries on this page send feedback

©2005-2006 Nokia


GTypePlugin

Name

GTypePlugin — An interface for dynamically loadable types.

Library

gobject.lib

Synopsis

#include <glib-object.h>

             GTypePlugin;
             GTypePluginClass;
void        (*GTypePluginUse)                       (GTypePlugin *plugin);
void        (*GTypePluginUnuse)                     (GTypePlugin *plugin);
void        (*GTypePluginCompleteTypeInfo)          (GTypePlugin *plugin, GType g_type, GTypeInfo *info,
                                                     GTypeValueTable *value_table);
void        (*GTypePluginCompleteInterfaceInfo)     (GTypePlugin *plugin, GType instance_type, GType interface_type,
                                                     GInterfaceInfo *info);
void        g_type_plugin_use                       (GTypePlugin *plugin);
void        g_type_plugin_unuse                     (GTypePlugin *plugin);
void        g_type_plugin_complete_type_info        (GTypePlugin *plugin, GType g_type, GTypeInfo *info,
                                                     GTypeValueTable *value_table);
void        g_type_plugin_complete_interface_info   (GTypePlugin *plugin, GType instance_type, GType interface_type,
                                                     GInterfaceInfo *info);

Detailed Description

The GObject type system supports dynamic loading of types. The GTypePlugin interface is used to handle the lifecycle of dynamically loaded types. It goes as follows:

  1. The type is initially introduced (usually upon loading the module the first time, or by the main application that knows what modules introduces what types), like this: new_type_id = g_type_register_dynamic (parent_type_id, "TypeName", new_type_plugin, type_flags); where new_type_plugin is an implementation of the GTypePlugin interface.

  2. The type's implementation is referenced, e.g. through g_type_class_ref() or through g_type_create_instance() (this is being called by g_object_new()) or through one of the above done on a type derived from new_type_id.

  3. This causes the type system to load the type's implementation by calling g_type_plugin_use() and g_type_plugin_complete_type_info() on new_type_plugin.

  4. At some point the type's implementation isn't required anymore, e.g. after g_type_class_unref() or g_type_free_instance() (called when the reference count of an instance drops to zero).

  5. This causes the type system to throw away the information retrieved from g_type_plugin_complete_type_info() and then it calls g_type_plugin_unuse() on new_type_plugin.

  6. Things may repeat from the second step.

To implement a GTypePlugin type that carries a use_count, once use_count goes from zero to one, load the implementation to successfully handle the upcoming g_type_plugin_complete_type_info() call. Later, maybe after succeeding use/unuse calls, once use_count drops to zero, unload the implementation again. The type system makes sure to call g_type_plugin_use() and g_type_plugin_complete_type_info() again when the type is needed again.

GTypeModule is an implementation of GTypePlugin that already implements most of this except for the actual module loading and unloading. It even handles multiple registered types per module.

Object Hierarchy

  GInterface
   +----GTypePlugin

Known Implementations

GTypePlugin is implemented by GTypeModule.

Details

GTypePlugin

typedef struct _GTypePlugin GTypePlugin;

The GTypePlugin typedef is used as a placeholder for objects that implement the GTypePlugin interface.

GTypePluginClass

typedef struct {
  GTypePluginUse		   use_plugin;
  GTypePluginUnuse		   unuse_plugin;
  GTypePluginCompleteTypeInfo	   complete_type_info;
  GTypePluginCompleteInterfaceInfo complete_interface_info;
} GTypePluginClass;

The GTypePlugin interface is used by the type system in order to handle the lifecycle of dynamically loaded types.

GTypePluginUse use_plugin; | Increases the use count of the plugin.
GTypePluginUnuse unuse_plugin; | Decreases the use count of the plugin.
GTypePluginCompleteTypeInfo complete_type_info; | Fills in the GTypeInfo and GTypeValueTable structs for the type. The structs are initialized with memset(s, 0, sizeof (s)) before calling this function.
GTypePluginCompleteInterfaceInfo complete_interface_info; | Fills in missing parts of the GInterfaceInfo for the interface. The structs is initialized with memset(s, 0, sizeof (s)) before calling this function.

GTypePluginUse ()

void     (*GTypePluginUse)          (GTypePlugin *plugin);

The type of the use_plugin function of GTypePluginClass, which gets called to increase the use count of plugin.

plugin : the GTypePlugin whose use count should be increased

GTypePluginUnuse ()

void     (*GTypePluginUnuse)       (GTypePlugin *plugin);

The type of the unuse_plugin function of GTypePluginClass.

plugin : the GTypePlugin whose use count should be decreased

GTypePluginCompleteTypeInfo ()

void    (*GTypePluginCompleteTypeInfo)      (GTypePlugin *plugin, GType g_type, GTypeInfo *info, GTypeValueTable *value_table);

The type of the complete_type_info function of GTypePluginClass.

plugin : | the GTypePlugin
g_type : | the GType whose info is completed
info : | the GTypeInfo struct to fill in
value_table : | the GTypeValueTable to fill in

GTypePluginCompleteInterfaceInfo ()

void   (*GTypePluginCompleteInterfaceInfo)   (GTypePlugin *plugin, GType instance_type, GType interface_type,
                                              GInterfaceInfo *info);

The type of the complete_interface_info function of GTypePluginClass.

plugin : | the GTypePlugin
instance_type : | the GType of an instantiable type to which the interface is added
interface_type : | the GType of the interface whose info is completed
info : | the GInterfaceInfo to fill in

g_type_plugin_use ()

void     g_type_plugin_use    (GTypePlugin *plugin);

Calls the use_plugin function from the GTypePluginClass of plugin. There should be no need to use this function outside of the GObject type system itself.

plugin : a GTypePlugin

g_type_plugin_unuse ()

void    g_type_plugin_unuse    (GTypePlugin *plugin);

Calls the unuse_plugin function from the GTypePluginClass of plugin. There should be no need to use this function outside of the GObject type system itself.

plugin : a GTypePlugin

g_type_plugin_complete_type_info ()

void    g_type_plugin_complete_type_info    (GTypePlugin *plugin, GType g_type, GTypeInfo *info, GTypeValueTable *value_table);

Calls the complete_type_info function from the GTypePluginClass of plugin. There should be no need to use this function outside of the GObject type system itself.

plugin : | a GTypePlugin
g_type : | the GType whose info is completed
info : | the GTypeInfo struct to fill in
value_table : | the GTypeValueTable to fill in

g_type_plugin_complete_interface_info ()

void    g_type_plugin_complete_interface_info     (GTypePlugin *plugin, GType instance_type, GType interface_type,
                                                   GInterfaceInfo *info);

Calls the complete_interface_info function from the GTypePluginClass of plugin. There should be no need to use this function outside of the GObject type system itself.

plugin : | the GTypePlugin
instance_type : | the GType of an instantiable type to which the interface is added
interface_type : | the GType of the interface whose info is completed
info : | the GInterfaceInfo to fill in

See Also

GTypeModule and g_type_register_dynamic().

Feedback

For additional information or queries on this page send feedback


h_errno_location

Name

h_errno_location,
- bind a socket to a privileged IP port

Library

 libc.lib

Synopsis
#include <netdb.h>
int* h_errno_location (void);

Return values

 A -1 is returned if an error occurs, otherwise the return value is a descriptor referencing the socket.

Detailed description

 The h_errno_location function used to retrieve the memory location of h_errno.

Examples

#include <netdb.h>
void HErrNoLocation()
{
   TInt *ptr = __h_errno_location();
}

Errors

 None.

Feedback

For additional information or queries on this page send feedback


HMAC_cleanup - HMAC message authentication code

Name

HMAC, HMAC_Init
HMAC_Update, HMAC_Final
HMAC_cleanup

HMAC message authentication code

Library

libcrypto.lib

Synopsis

#include <openssl/hmac.h>
unsigned char *HMAC(const EVP_MD *evp_md, const void *key, int key_len, const unsigned char *d, int n, unsigned char *md,
                    unsigned int *md_len);
void HMAC_CTX_init(HMAC_CTX *ctx);
void HMAC_Init(HMAC_CTX *ctx, const void *key, int key_len, const EVP_MD *md);
void HMAC_Init_ex(HMAC_CTX *ctx, const void *key, int key_len, const EVP_MD *md);
void HMAC_Update(HMAC_CTX *ctx, const unsigned char *data, int len);
void HMAC_Final(HMAC_CTX *ctx, unsigned char *md, unsigned int *len);
void HMAC_CTX_cleanup(HMAC_CTX *ctx);
void HMAC_cleanup(HMAC_CTX *ctx);

Detailed Description

HMAC is a MAC (message authentication code), i.e. a keyed hash function used for message authentication, which is based on a hash function.

HMAC() computes the message authentication code of the n bytes at d using the hash function evp_md and the key key which is key_len bytes long.

It places the result in md (which must have space for the output of the hash function, which is no more than EVP_MAX_MD_SIZE bytes). If md is NULL, the digest is placed in a static array. The size of the output is placed in md_len, unless it is NULL.

evp_md can be EVP_sha1(), etc. key and evp_md may be NULL if a key and hash function have been set in a previous call to HMAC_Init() for that HMAC_CTX.

HMAC_CTX_init() initializes a HMAC_CTX before first use. It must be called.

HMAC_CTX_cleanup() erases the key and other data from the HMAC_CTX and releases any associated resources. It must be called when an HMAC_CTX is no longer required.

HMAC_cleanup() is an alias for HMAC_CTX_cleanup() included for back compatibility with 0.9.6b, it is deprecated.

The following functions may be used if the message is not completely stored in memory:

HMAC_Init() initializes a HMAC_CTX structure to use the hash function evp_md and the key key which is key_len bytes long. It is deprecated and only included for backward compatibility with OpenSSL 0.9.6b.

HMAC_Init_ex() initializes or reuses a HMAC_CTX structure to use the function evp_md and key key. Either can be NULL, in which case the existing one will be reused. HMAC_CTX_init() must have been called before the first use of an HMAC_CTX in this function. N.B. HMAC_Init() had this undocumented behaviour in previous versions of OpenSSL - failure to switch to HMAC_Init_ex() in programs that expect it will cause them to stop working.

HMAC_Update() can be called repeatedly with chunks of the message to be authenticated (len bytes at data).

HMAC_Final() places the message authentication code in md, which must have space for the hash function output.

Return Values

HMAC() returns a pointer to the message authentication code.

HMAC_CTX_init(), HMAC_Init_ex(), HMAC_Update(),
 HMAC_Final() and

HMAC_CTX_cleanup() do not return values.

Conforming To

RFC 2104

See Also

sha(), evp()

History

HMAC(), HMAC_Init(), HMAC_Update(),
HMAC_Final() and
HMAC_cleanup()
are available since SSLeay 0.9.0.

HMAC_CTX_init(), HMAC_Init_ex() and HMAC_CTX_cleanup() are available since OpenSSL 0.9.7.

Feedback

For additional information or queries on this page send feedback


How To define and implement a new GObject?

Clearly, this is one of the most common question people ask: they just want to crank code and implement a subclass of a GObject. Sometimes because they want to create their own class hierarchy, sometimes because they want to subclass one of GTK+'s widget. This chapter will focus on the implementation of a subtype of GObject. The sample source code associated to this section can be found in the documentation's source tarball, in the sample/gobject directory:

  • maman-bar.{h|c}: this is the source for a object which derives from GObject and which shows how to declare different types of methods on the object.

  • maman-subbar.{h|c}: this is the source for a object which derives from MamanBar and which shows how to override some of its parent's methods.

  • maman-foo.{h|c}: this is the source for an object which derives from GObject and which declares a signal.

  • test.c: this is the main source which instantiates an instance of type and exercises their API.

Boilerplate header code

The first step before writing the code for your GObject is to write the type's header which contains the needed type, function and macro definitions. Each of these elements is nothing but a convention which is followed not only by GTK+'s code but also by most users of GObject. If you feel the need not to obey the rules stated below, think about it twice:

  • If your users are a bit accustomed to GTK+ code or any Glib code, they will be a bit surprised and getting used to the conventions you decided upon will take time (money) and will make them grumpy (not a good thing)

  • You must assess the fact that these conventions might have been designed by both smart and experienced people: maybe they were at least partly right. Try to put your ego aside.

Pick a name convention for your headers and source code and stick to it:

  • use a dash to separate the prefix from the typename: maman-bar.h and maman-bar.c (this is the convention used by Nautilus and most Gnome libraries).

  • use an underscore to separate the prefix from the typename: maman_bar.h and maman_bar.c.

  • Do not separate the prefix from the typename: mamanbar.h and mamanbar.c. (this is the convention used by GTK+)

I personally like the first solution better: it makes reading file names easier for those with poor eyesight like me.

When you need some private (internal) declarations in several (sub)classes, you can define them in a private header file which is often named by appending the private keyword to the public header name. For example, one could use maman-bar-private.h, maman_bar_private.h or mamanbarprivate.h. Typically, such private header files are not installed.

The basic conventions for any header which exposes a GType are described in the section called “Conventions”. Most GObject-based code also obeys onf of the following conventions: pick one and stick to it.

  • If you want to declare a type named bar with prefix maman, name the type instance MamanBar and its class MamanBarClass (name is case-sensitive). It is customary to declare them with code similar to the following:

    /*
     * Copyright/Licensing information.
     */
    #ifndef MAMAN_BAR_H
    #define MAMAN_BAR_H

    /*
     * Potentially, include other headers on which this header depends.
     */
    /*
     * Type macros.
     */

    typedef struct _MamanBar MamanBar;
    typedef struct _MamanBarClass MamanBarClass;

    struct _MamanBar {
      GObject parent;
      /* instance members */
    };

    struct _MamanBarClass {
      GObjectClass parent;
      /* class members */
    };

    /* used by MAMAN_BAR_TYPE */
    GType maman_bar_get_type (void);

    /*
     * Method definitions.
     */

    #endif

  • Most GTK+ types declare their private fields in the public header with a /* private */ comment, relying on their user's intelligence not to try to play with these fields. Fields not marked private are considered public by default. The /* protected */ comment (same semantics as those of C++) is also used, mainly in the GType library, in code written by Tim Janik.

    struct _MamanBar {
      GObject parent;
      /* private */
      int hsize;
    };

  • All of Nautilus code and a lot of Gnome libraries use private indirection members, as described by Herb Sutter in his Pimpl articles (see Compilation Firewalls and The Fast Pimpl Idiom : he summarizes the different issues better than I will).

    typedef struct _MamanBarPrivate MamanBarPrivate;
    struct _MamanBar {
      GObject parent;
      /* private */
      MamanBarPrivate *priv;
    };

    Note

    Note: Do not call this private, as that is a registered c++ keyword.

    The private structure is then defined in the .c file, instantiated in the object's init function and destroyed in the object's finalize function.

    static void
maman_bar_finalize (GObject *object) {
  MamanBar *self = MAMAN_BAR (object);
  /* do stuff */
  g_free (self->priv);
}

static void
maman_bar_init (GTypeInstance *instance, gpointer g_class) {
  MamanBar *self = MAMAN_BAR (instance);
  self->priv = g_new0 (MamanBarPrivate,1);
  /* do stuff */
}

  • A similar alternative, available since Glib version 2.4, is to define a private structure in the .c file, declare it as a private structure in maman_bar_class_init using g_type_class_add_private. Instead of allocating memory in maman_bar_init a pointer to the private memory area is stored in the instance to allow convenient access to this structure. A private structure will then be attached to each newly created object by the GObject system. You dont need to free or allocate the private structure, only the objects or pointers that it may contain. Another advantage of this to the previous version is that is lessens memory fragmentation, as the public and private parts of the instance memory are allocated at once.

    typedef struct _MamanBarPrivate MamanBarPrivate;

    struct _MamanBarPrivate {
      int private_field;
    };

    static void
    maman_bar_class_init (MamanBarClass *klass)
    {
      ...
      g_type_class_add_private (klass, sizeof (MamanBarPrivate));
      ...
    }

    static void
maman_bar_init (GTypeInstance *instance, gpointer g_class) {
  MamanBar *self = MAMAN_BAR (instance);
  self->priv = G_TYPE_INSTANCE_GET_PRIVATE (self, MAMAN_BAR_TYPE, MamanBarPrivate);
  /* do stuff */
}

Finally, there are different header include conventions. Again, pick one and stick to it. I personally use indifferently any of the two, depending on the codebase I work on: the rule is consistency.

  • Some people add at the top of their headers a number of #include directives to pull in all the headers needed to compile client code. This allows client code to simply #include "maman-bar.h".

  • Other do not #include anything and expect the client to #include themselves the headers they need before including your header. This speeds up compilation because it minimizes the amount of pre-processor work. This can be used in conjunction with the re-declaration of certain unused types in the client code to minimize compile-time dependencies and thus speed up compilation.


How To define and implement Interfaces?

How To define Interfaces?

The bulk of interface definition has already been shown in the section called “Non-instantiable classed types: Interfaces.” but I feel it is needed to show exactly how to create an interface. The sample source code associated to this section can be found in the documentation's source tarball, in the sample/interface/maman-ibaz.{h|c} file.

As above, the first step is to get the header right:

#ifndef MAMAN_IBAZ_H
#define MAMAN_IBAZ_H
#include <glib-object.h>

#define MAMAN_TYPE_IBAZ                (maman_ibaz_get_type ())
#define MAMAN_IBAZ(obj)                (G_TYPE_CHECK_INSTANCE_CAST ((obj), MAMAN_TYPE_IBAZ, MamanIbaz))
#define MAMAN_IS_IBAZ(obj)             (G_TYPE_CHECK_INSTANCE_TYPE ((obj), MAMAN_TYPE_IBAZ))
#define MAMAN_IBAZ_GET_INTERFACE(inst) (G_TYPE_INSTANCE_GET_INTERFACE ((inst), MAMAN_TYPE_IBAZ, MamanIbazInterface))
typedef struct _MamanIbaz MamanIbaz; /* dummy object */
typedef struct _MamanIbazInterface MamanIbazInterface;
struct _MamanIbazInterface {
GTypeInterface parent;
  void (*do_action) (MamanIbaz *self);
};
GType maman_ibaz_get_type (void);
void maman_ibaz_do_action (MamanIbaz *self);
#endif /*MAMAN_IBAZ_H*/

This code is the same as the code for a normal GType which derives from a GObject except for a few details:

  • The _GET_CLASS macro is called _GET_INTERFACE and not implemented with G_TYPE_INSTANCE_GET_CLASS but with G_TYPE_INSTANCE_GET_INTERFACE.

  • The instance type, MamanIbaz is not fully defined: it is used merely as an abstract type which represents an instance of whatever object which implements the interface.

The implementation of the MamanIbaz type itself is trivial:

  • maman_ibaz_get_type registers the type in the type system.

  • maman_ibaz_base_init is expected to register the interface's signals if there are any (we will see a bit (later how to use them). Make sure to use a static local boolean variable to make sure not to run the initialization code twice (as described in the section called “Interface Initialization”, base_init is run once for each interface implementation instanciation)

  • maman_ibaz_do_action dereferences the class structure to access its associated class function and calls it.

static void
maman_ibaz_base_init (gpointer g_class)
{
 static gboolean initialized = FALSE;
 if (!initialized) {
 /* create interface signals here. */
 initialized = TRUE;
 }
}
GType
maman_ibaz_get_type (void)
{
 static GType type = 0;
 if (type == 0) {
 static const GTypeInfo info = {
 sizeof (MamanIbazInterface), maman_ibaz_base_init,   /* base_init */
 NULL,   /* base_finalize */
 NULL,   /* class_init */
 NULL,   /* class_finalize */
 NULL,   /* class_data */
 0,
 0,      /* n_preallocs */
 NULL    /* instance_init */
 };
   type = g_type_register_static (G_TYPE_INTERFACE, "MamanIbaz", &info, 0);
  }
  return type;
}
void maman_ibaz_do_action (MamanIbaz *self)
{
 MAMAN_IBAZ_GET_INTERFACE (self)->do_action (self);
}


How to create and use signals

The signal system which was built in GType is pretty complex and flexible: it is possible for its users to connect at runtime any number of callbacks (implemented in any language for which a binding exists) [15] to any signal and to stop the emission of any signal at any state of the signal emission process. This flexibility makes it possible to use GSignal for much more than just emit events which can be received by numerous clients.

Simple use of signals

The most basic use of signals is to implement simple event notification: for example, if we have a MamanFile object, and if this object has a write method, we might wish to be notified whenever someone uses this method. The code below shows how the user can connect a callback to the write signal. Full code for this simple example is located in sample/signal/maman-file.{h|c} and in sample/signal/test.c
file = g_object_new (MAMAN_FILE_TYPE, NULL);
g_signal_connect  (G_OBJECT (file), "write", (GCallback)write_event, NULL);
maman_file_write (file, buffer, 50);

The MamanFile signal is registered in the class_init function:

klass->write_signal_id =
  g_signal_newv ("write", G_TYPE_FROM_CLASS (g_class), G_SIGNAL_RUN_LAST | G_SIGNAL_NO_RECURSE | G_SIGNAL_NO_HOOKS,
                 NULL /* class closure */, NULL /* accumulator */, NULL /* accu_data */, g_cclosure_marshal_VOID__VOID,
                 G_TYPE_NONE /* return_type */, 0  /* n_params */, NULL  /* param_types */);

and the signal is emited in maman_file_write:

void maman_file_write (MamanFile *self, guint8 *buffer, guint32 size)
{
  /* First write data. */
  /* Then, notify user of data written. */
  g_signal_emit (self, MAMAN_FILE_GET_CLASS (self)->write_signal_id, 0 /* details */, NULL);
}
As shown above, you can safely set the details parameter to zero if you do not know what it can be used for. For a discussion of what you could used it for, see the section called “The detail argument”

The signature of the signal handler in the above example is defined as g_cclosure_marshal_VOID__VOID. Its name follows a simple convention which encodes the function parameter and return value types in the function name. Specifically, the value infront of the double underscore is the type of the return value, while the value(s) after the double underscore denote the parameter types. The header gobject/gmarshal.h defines a set of commonly needed closures that one can use.

[15] A python callback can be connected to any signal on any C-based GObject.


htonl

Name

htonl, htons, ntohl, ntohs
- convert values between host and network byte order

Library

 libc.lib

Synopsis
#include <arpa/inet.h>

or

#include <netinet/in.h>
uint32_t htonl (uint32_t hostlong);
uint16_t htons (uint16_t hostshort);
uint32_t ntohl (uint32_t netlong);
uint16_t ntohs (uint16_t netshort);

Detailed description

 These routines convert 16 and 32 bit quantities between network byte order and host byte order. On machines which have a byte order which is the same as the network order, routines are defined as null macros.

These routines are most often used in conjunction with Internet addresses and ports as returned by gethostbyname and getservent.

See also

 gethostbyaddr, getservent,

Bugs

 On the VAX bytes are handled backwards from most everyone else in the world. This is not expected to be fixed in the near future.

Feedback

For additional information or queries on this page send feedback


hypot

Name

hypot, hypotf, hypotl
- Euclidean distance function

Library

 libm.lib

Synopsis
#include <math.h>
double hypot (double x, double y);
float hypotf (float x, float y);
long double hypotl (long double x, long double y);

Detailed description

 The hypot and hypotf functions compute the sqrt(x*x+y*y) in such a way that underflow will not happen, and overflow occurs only if the final result deserves it.

The function hypotl is an alias to the function

Examples

void main( void )
{
   double x1 = 3.0 , x2 = 4.0, y;
   y = hypot( x1, x2 );
   printf( "atan2(%f , %f) = %f\n", x1, x2, y );
   y = hypotf( x1, x2 );
   printf( "atan2f(%f , %f) = %f\n", x1, x2, y );
   y = hypotl( x1, x2 );
   printf( "hypotl(%f , %f) = %f\n", x1, x2, y );
}

Output

hypot ( 3.0, 4.0  ) = 5.000000
hypotf( 3.0, 4.0 )  = 5.000000
hypotl( 3.0, 4.0 )  = 5.000000

Error (due to roundoff, etc.)

 Below 0.97 ulps. Consequently hypot (5.0, 12.0);
= 13.0 exactly; in general, the hypot and cabs functions return an integer whenever an integer might be expected.

Notes

 As might be expected, hypot (v, NaN);
and hypot (NaN, v);
are NaN for all finite v. But programmers might be surprised at first to discover that hypot (±oo, NaN);
= +oo. This is intentional; it happens because hypot (oo, v);
= +oo for all v, finite or infinite. Hence hypot (oo, v);
is independent of v. Unlike the reserved operand fault on a VAX, the IEEE NaN is designed to disappear when it turns out to be irrelevant, as it does in hypot (oo, NaN);

hypot.

hypot (oo, v);
= hypot (v, oo);
= +oo for all v, including NaN.

See also

 math, sqrt

Feedback

For additional information or queries on this page send feedback


iconv

Name

iconv - performs character set conversion

Library

 libc.lib

Synopsis
#include <iconv.h>
size_t iconv (iconv_t cd, const char **inbuf, size_t *inbytesleft, char **outbuf, size_t *outbytesleft);
Sh RETURN VALUES If the entire input string is converted the iconv function returns 0. If the conversion is stopped due to some reasons the inputbytesleft will be non-zero. In these case of errors,it sets errno and returns (size_t)(-1).

Detailed description

 cd is a conversion descriptor created using the function iconv_open.

The iconv function sets errno to EBADF ,if the conversion descriptor is a bad descriptor.

There are three cases. They are as follows:

The first case is when inbuf is not NULL and *inbuf is not NULL. In this case the iconv function converts the multibyte character string starting at *inbuf to a multibyte character sequence starting at *outbuf from source character set to destination character set.

The iconv function converts one multibyte character at a time, and for each character conversion it increments *inbuf by the number of converted input bytes and decrements *inbytesleft by the number of converted input bytes, it increments *outbuf by the number of converted output bytes and decrements *outbytesleft by the number of converted output bytes.

The conversion can stop for four reasons:

1.An invalid multibyte character sequence is encountered in the input. In this case it sets errno to EILSEQ and returns (size_t)(-1).*inbuf is left pointing to the beginning of the invalid multibyte character sequence.

2.The input multibyte sequence is fully converted, i.e when *inbytesleft reach 0. In this case iconv returns 0.

3.An incomplete multibyte sequence is encountered in the input and the input sequence ends there. In this case it sets errno to EINVAL and returns (size_t)(-1). *inbuf is made to point to the beginning of the incomplete multibyte sequence.

4. The *outbytesleft reached 0 i.e output buffer has no enough space for the next converted character. In this case it sets errno to E2BIG and returns (size_t)(-1).

The second case is when inbuf is NULL or *inbuf is NULL. In this case if outbuf is not NULL and *outbuf is not NULL the iconv returns 0. If *outbytesleft reached 0 i.e output buffer has no enough space for the next converted character it sets errno to E2BIG and returns (size_t)(-1).

A third case is when inbuf is NULL or *inbuf is NULL, and outbuf is NULL or *outbuf is NULL. In this case, the iconv function returns 0.

Examples

#include<stdio.h>
#include<iconv.h>
int main()
{
       iconv_t cd = NULL;
       char utf8[12] = "abcd";
       char iso[12];
       const char *inbuf;
       char *outbuf;
       size_t inbytes = 4;
       size_t outbytes = 4;
       inbuf = (const char*) utf8;
       outbuf = (char *) iso;
       //Allocate descriptor for charset conversion
       cd = iconv_open("UTF-8", "ISO-8859-1");
       if(cd == (iconv_t) -1)
       {
               printf("Unbale to create a conversion descriptor0);
       }
       else
       {
               printf("Conversion descriptor is created successfully0);
       }
       printf("before conversion inbytes = %d outbytes = %d0, inbytes, outbytes);
       iconv (cd, &inbuf, &inbytes, &outbuf, &outbytes);
       printf("After conversion inbytes = %d outbytes = %d0, inbytes, outbytes);
       iconv_close(cd);
       return 0;
}

Output

Conversion descriptor is created successfully
before conversion inbytes = 4 outbytes = 4
before conversion inbytes = 0 outbytes = 0

Errors

 The following errors can occur, among others:
E2BIG:There is not sufficient room in the output buffer i.e *outbuf is 0.
EILSEQ: An invalid multibyte sequence has been encountered in the input which does not belong to the input character set.
EINVAL: An incomplete multibyte sequence has been encountered in the input.
EBADF: cd is not a valid conversion descriptor

See also

 iconv_open, iconv_close

Feedback

For additional information or queries on this page send feedback


iconv_close

Name

iconv_close - deallocates descriptor for character set conversion

Library

 libc.lib

Synopsis
#include <iconv.h>
int iconv_close (iconv_t cd);

Return values

 On deallocating the conversion descriptor, the iconv_close function returns 0. In case of error, it sets the respective errno and returns -1.

Detailed description

 The iconv_close function deallocates a conversion descriptor cd allocated using iconv_open.

The iconv_close sets errno to EBADF if the conversion descriptor is a bad descriptor

Examples

#include<stdio.h>
#include<iconv.h>
int main()
{
        iconv_t cd = NULL;
        //Allocate descriptor for charset conversion
        cd = iconv_open("UTF-8", "ISO-8859-1");
        if(cd == (iconv_t) -1)
        {
                printf("Unbale to create a conversion descriptor0);
        }
        else
        {
                printf("Conversion descriptor is created successfully0);
        }
        if(!iconv_close(cd))
        {
         printf("Conversion descriptor is deallocated successfully0);
        }
        else
        {
         printf("Conversion descriptor deallocation failed0);
        }
        return 0;
}

Output

Conversion descriptor is created successfully
Conversion descriptor is deallocated successfully

Errors
EBADF Bad file descriptor

See also

 iconv, iconv_open

Feedback

For additional information or queries on this page send feedback


iconv_open

Name

iconv_open - allocates descriptor for character set conversion

Library

 libc.lib

Synopsis
#include <iconv.h>
iconv_t iconv_open (const char *tocode, const char *fromcode);
Sh RETURN VALUES The iconv_open function returns a newly allocated conversion descriptor. In case of error, it sets errno and returns (iconv_t)(-1).

Detailed description

 The iconv_open function allocates a conversion descriptor suitable for converting byte sequences from character encoding fromcode to character encoding tocode.

If enough memory is not available in the system to create conversion descriptor, the iconv_open function sets errno.

The character sets permitted for fromcode and tocode are system dependent.

The allocated conversion descriptor can be used with iconv any number of times until it is deallocated using iconv_close.

Examples

#include<stdio.h>
#include<iconv.h>
int main()
{
        iconv_t cd = NULL;
        //Allocate descriptor for charset conversion
        cd = iconv_open("UTF-8", "ISO-8859-1");
        if(cd == (iconv_t) -1)
        {
                printf("Unbale to create a conversion descriptor0);
        }
        else
        {
                printf("Conversion descriptor is created successfully0);
        }
        iconv_close(cd);
        return 0;
}

Output Conversion descriptor is created successfully

Errors

 EINVAL: The fromcode or tocode charcater set is not supported by the implementation.
ENOMEM: Enough memory is not available to create conversion descriptor.

See also

 iconv, iconv_close

Feedback

For additional information or queries on this page send feedback


ieee

Name

logb, logbf, logbl, scalb, scalbf, scalbl, significand, significandf, significandl
- IEEE test functions

Library

 libm.lib

Synopsis
#include <math.h>
double logb (double x);
float logbf (float x);
long double logbl (long double x);
double scalb (double x, double n);
float scalbf (float x, float n);
long double scalbl (long double x, long double n);
double significand (double x);
float significandf (float x);
long double significandl (long double x);

Detailed description

 These functions allow users to test conformance to -ieee754. Their use is not otherwise recommended.

logb (x);
and logbf (x);
return x ’s exponent n, a signed integer converted to double-precision floating-point. logb (±oo);
= +oo; logb (0);

= -oo

scalb (x, n);
and scalbf (x, n);
return x *(2** n) computed by exponent manipulation. If n is not an integer, ±oo, or an NaN, the result is unspecified.

significand (x);
and significandf (x);
return sig, where x = sig * 2** n with 1 <= sig < 2. significand (x);
and significandf (x);
are not defined when x is 0, ±oo, or NaN. Here , long double version function are just aliases to their corresponding double version apis.

Examples

#include <math.h>
int main( )
{
   double e = 2.718282;
   /*Logb(), logbf() and logbl() */
   y = logb( e );
   printf( "logb( %f) = %f\n", e, y );
   y = logbf( e );
   printf( "logbf( %f) = %f\n", e, y );
   y = logbl( e );
   printf( "logbl( %f) = %f\n\n", e, y );
   /*scalb(), scalbf() and scalbl()*/
   double x1 = 0.8, x2 = 4.0 ;
   y = scalb( x1, x2 );
   printf( "scalb( %f, %f) = %f\n", x1, x2, y );
   y = scalbf( x1, x2 );
   printf( "scalbf( %f, %f) = %f\n", x1, x2, y );
   y = scalbl( x1, x2 );
   printf( "scalbl( %f, %f) = %f\n", x1, x2, y );
   /*significand(), significandf() and significandl()*/
   x2 = 4.0 ;
   y = significand( x2 );
   printf( "significand(%f)  = %f\n",  x2, y );
   y = significandf( x2 );
   printf( "significandf(%f) = %f\n",x2, y );
   y = significandl( x2 );
   printf( "significandl(%f) = %f\n",x2, y );
}

Output

logb( 2.718282) = 1.000000
logbf( 2.718282) = 1.000000
logbl( 2.718282) = 1.000000
scalb( 0.8, 4.0 ) = 12.800000
scalbf( 0.8, 4.0 ) = 12.800000
scalbl( 0.8, 4.0 ) = 12.800000
significand ( 4.0) = 1.000000
significandf( 4.0) = 1.000000
significandl( 4.0) = 1.000000

See also

 ieee math

Feedback

For additional information or queries on this page send feedback


if_nameindex

Name

if_nametoindex, if_indextoname, if_nameindex, if_freenameindex
- return all network interface names and indexes

Synopsis
#include <net/if.h>
unsigned int if_nametoindex (const char *ifname);
char * if_indextoname (unsigned int ifindex, char *ifname);
struct if_nameindex * if_nameindex (void);
void if_freenameindex (struct if_nameindex *ptr);

Return values

 Upon successful completion, if_nametoindex returns the index number of the interface. If the interface is not found, a value of 0 is returned and errno is set to ENXIO.

Upon successful completion, if_indextoname returns ifname. If the interface is not found, a NULL pointer is returned and errno is set to ENXIO.

The if_nameindex returns a NULL pointer if sufficient memory cannot be allocated.

Detailed description

 The if_nametoindex function maps the interface name specified in ifname to its corresponding index. If the specified interface does not exist, it returns 0.

The if_indextoname function maps the interface index specified in ifindex to it corresponding name, which is copied into the buffer pointed to by ifname, which must be of at least IFNAMSIZ bytes. This pointer is also the return value of the function. If there is no interface corresponding to the specified index, NULL is returned.

The if_nameindex function returns an array of if_nameindex structures, one structure per interface, as defined in the include file
#include <net/if.h.>The if_nameindex structure contains at least the following entries:
    unsigned int   if_index;  /* 1, 2, ... */
    char          *if_name;   /* null terminated name: "le0", ... */

The end of the array of structures is indicated by a structure with an if_index of 0 and an if_name of NULL. A NULL pointer is returned upon an error.

The if_freenameindex function frees the dynamic memory that was allocated by if_nameindex.

See also
The if_nametoindex, if_indextoname, if_nameindex, and if_freenameindex functions conform to RFC 2553.
The implementation first appeared in BSDi.

Feedback

For additional information or queries on this page send feedback


ilogb

Name

ilogb, ilogbf, ilogbl
- extract exponent

Library

 libm.lib

Synopsis
#include <math.h>
int ilogb (double x);
int ilogbf (float x);
int ilogbl (long double x);

Detailed description

 The functions ilogb, ilogbf, and ilogbl return x ’s exponent, in integer format. ilogb (±oo);
returns INT_MAX, ilogb (±NaN);
returns FP_ILOGBNAN and ilogb (0);
returns FP_ILOGB0.

Examples

#include <math.h>
int main( )
{
   double e = 1024;
   /*iLogb(), ilogbf() and ilogbl() */
   y = ilogb( e );
   printf( "ilogb( %f) = %f\n", e, y );
   y = ilogbf( e );
   printf( "ilogbf( %f) = %f\n", e, y );
   y = ilogbl( e );
   printf( "ilogbl( %f) = %f\n\n", e, y );
}

Output

ilogb (1024) = 10.000000
ilogbf(1024) = 10.000000
ilogbl(1024) = 10.000000

See also

 frexp, ieee, math, scalbn
The ilogb, ilogbf, and ilogbl routines conform to -isoC-99. They provide functionality similar to the logb function recommended by -ieee754.
The ilogb and ilogbf functions appeared in BSD 4.3 and 2.0 , respectively.

Feedback

For additional information or queries on this page send feedback


index

Name

index, rindex
- locate character in string

Library

 libc.lib

Synopsis
#include <strings.h>
char * index (const char *s, int c);
char * rindex (const char *s, int c);

Return values

 The functions index and rindex return a pointer to the located character, or NULL if the character does not appear in the string.

Detailed description

 The index function locates the first occurrence of c (converted to a char ) in the string pointed to by s. The terminating null character is considered part of the string; therefore if c is ‘\0,’ the functions locate the terminating ‘\0.’

The rindex function is identical to index, except it locates the last occurrence of c.

Examples

#include <string.h>
#include <stdio.h>
int main()
{
    char one[50];
    char* ret;
    strcpy(one,"abcd");
    ret = index(one, ’c’);
    if(!strncmp(one+2,ret,1)) printf("index of \ ’c\ ’ in string \"abcd\" is %d \n",2);
    ret = index(one, ’z’);
    if(ret == NULL) printf("\ ’z\ ’ not found in string \"abcd\"\n");
    ret = index(one, ’\0’);
    if(!strncmp(one+4,ret,1)) printf("index of \ ’\ \0\ ’ in string \"abcd\" is %d\n",4);
    strcpy(one,"cdcab");
    ret = rindex(one, ’c’);
    if(!strncmp(one+2,ret,1)) printf("rindex of \ ’c\ ’ in string \"cscab\" is %d\n",2);
    strcpy(one,"dcab");
    ret = rindex(one, ’\0’);
    if(!strncmp(one+4,ret,1)) printf("index of \ ’\ \0\ ’ in string \"dcab\" is %d\n",4);
    return 0;
}

Output

index of ’c’ in string "abcd" is 2
 ’z’ not found in string "abcd"
index of ’\0’ in string "abcd" is 4
rindex of ’c’ in string "cscab" is 2
index of ’\0’ in string "dcab" is 4

See also

 memchr, strchr, strcspn, strpbrk, strsep, strspn, strstr, strtok

Feedback

For additional information or queries on this page send feedback


inet_pton

Name

inet_addr,inet_aton,inet_ntoa, inet_ntop, inet_pton
- Create a network address structure

Library

 libc.lib

Synopsis
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
in_addr_t inet_addr (const char *cp);
int inet_aton (const char *cp, struct in_addr *pin);
char * inet_ntoa (struct in_addr in);
const char *
.Fo inet_ntop int af const void * restrict src char * restrict dst socklen_t size
.Fc
int inet_pton (int af, const char * restrict src, void * restrict dst);

Detailed description

 The routines inet_addr and inet_aton interpret character strings representing numbers expressed in the Internet standard ‘.’ notation.

The inet_pton function converts a presentation format address (that is, printable form as held in a character string) to network format (usually a
struct in_addr or some other internal binary representation, in network byte order). It returns 1 if the address was valid for the specified address family, or 0 if the address was not parseable in the specified address family, or -1 if some system error occurred. This function is presently valid for AF_INET and AF_INET6.

The inet_aton routine interprets the specified character string as an Internet address, placing the address into the structure provided. It returns 1 if the string was successfully interpreted, or 0 if the string is invalid. The inet_addr functions return numbers suitable for use as Internet addresses.

The function inet_ntop converts an address *src from network format (usually a

struct in_addr or some other binary form, in network byte order) to presentation format (suitable for external display purposes). The size argument specifies the size, in bytes, of the buffer *dst It returns NULL if a system error occurs (in which case, errno will have been set), or it returns a pointer to the destination string. This function is presently valid for AF_INET and AF_INET6.

The routine inet_ntoa takes an Internet address and returns an ASCII string representing the address in ‘.’ notation.

All Internet addresses are returned in network order (bytes ordered from left to right). All network numbers and local address parts are returned as machine byte order integer values.

Internet addresses

 Values specified using the ‘.’ notation take one of the following forms:
a.b.c.d
a.b.c
a.b
a

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 an Internet address is viewed as a 32-bit integer quantity on the VAX the bytes referred to above appear as "d.c.b.a." That is, VAX bytes are ordered from right to left.

When a three part address is specified, the last part is interpreted as a 16-bit quantity and placed in the right-most two bytes of the network address. This makes the three 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 quantity and placed in the right most three bytes of the network address. This makes the two 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 address without any byte rearrangement.

All numbers supplied as "parts" in a ‘.’ notation may be decimal, octal, or hexadecimal, 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).

inet_aton and inet_ntoa function is semi-deprecated in favor of the addr2ascii family. However, since those functions are not yet widely implemented, portable programs cannot rely on their presence and will continue to use the inet functions for some time.

Diagnostics

 The constant INADDR_NONE is returned by inet_addr for malformed requests.

Errors

 The inet_ntop call fails if:
[ENOSPC]
 | size was not large enough to store the presentation form of the address.
[EAFNOSUPPORT]
 | *src was not an AF_INET or AF_INET6 family address.

See also

 gethostbyname
IP Version 6 Addressing Architecture

Examples

#include <stdio.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#define IPV6ADDRSIZE 48
int main()
    {
     unsigned int nbo_value;
     char *ipaddrstring="1.2.3.4";
     char *ipaddrholdr=NULL;
     char *ipv6addrstring="8000::123:4567:89AB:CDEF";
     struct in_addr ipstruct;
     struct in6_addr ipv6struct;
     char result[IPV6ADDRSIZE];
     int err;
     int size;
     const char* error;
     nbo_value=inet_addr(ipaddrstring);
     if(nbo_value == -1)
      {
       printf("inet_addr failed0);
      }
     else
      {
       printf("inet_addr passed0);
      }
     ipstruct.s_addr=nbo_value;
     ipaddrholdr=inet_ntoa(ipstruct);
     if(ipaddrholdr==NULL)
      {
       printf("inet_ntoa failed0);
      }
     else
      {
      printf("ipaddr is %s0,ipaddrholdr);
      }
     err=inet_pton(AF_INET6,ipv6addrstring ,&ipv6struct);
     if(err ==0  || err==-1)
     printf("inet_pton Failed0);
     else
     printf("inet_pton passed0);
     size=sizeof(result);
     error=inet_ntop(AF_INET6,&ipv6struct.s6_addr,result,size);
     if(error==NULL)
      {
      printf(’inet_ntop failed0);
      }
     else
      {
      printf("inet_ntop passed0);
      }
     err=inet_aton(ipaddrstring,&ipstruct);
     if(err==0)
     {
      printf("invalid address 0);
     }
     else
      {
      printf("inet_aton passed0);
      }

     return 0;
}
Output:
inet_addr passed
ipaddr is 1.2.3.4
inet_pton passed
inet_ntop passed
inet_aton passed
The inet_ntop and inet_pton functions conform to -xns5.2. Note that inet_pton does not accept 1-, 2-, or 3-part dotted addresses; all four parts must be specified and are interpreted only as decimal values. This is a narrower input set than that accepted by inet_aton.
These functions appeared in BSD 4.2.

Bugs

 The value INADDR_NONE (0xffffffff) is a valid broadcast address, but inet_addr cannot return that value without indicating failure. The newer inet_aton function does not share this problem. The problem of host byte ordering versus network byte ordering is confusing. The string returned by inet_ntoa resides in a static memory area.

Inet_addr should return a struct in_addr.

Feedback

For additional information or queries on this page send feedback


initgroups

Name

initgroups - initializes the supplementary group access list

Library

 libc.lib

Synopsis
#include <unistd.h>
int initgroups (const char *name, gid_t basegid);

Return values

 These functions always return 0.

Detailed description

 The getgroups function belongs to set of APIs which are only build supported and not available functionally. The reason why only build support is extended to these APIs is, symbian operating system does not support creation of multiple users and groups in its environment. More over it may not make sense to have multiple users and groups in the context of a mobile environment.

Errors

 No error values are set.

See also

Feedback

For additional information or queries on this page send feedback


ioctl

Name

ioctl - control device

Library

 libc.lib

Synopsis
#include <sys/ioctl.h>
int ioctl (int d, unsigned long request, ...);

Return values

 If an error has occurred, a value of -1 is returned and errno is set to indicate the error.

Detailed description

 The ioctl system call manipulates the underlying device parameters of special files. In particular, many operating characteristics of character special files (e.g. terminals) may be controlled with ioctl requests. The argument d must be an open file descriptor.

The third argument to ioctl is traditionally named char *argp. Most uses of ioctl in 3.0, however 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" argument or "out" argument, and the size of the argument argp in bytes. Macros and defines used in specifying an ioctl request are located in the file
#include <sys/ioctl.h>

Examples

 /**
  * Detailed description  : Sample usage of ioctl system call ,for command SIOCGIFINDEX which gets socket interface index , by passing socket interface home.
  *
  *
**/
#include <sys/types.h>
#include <sys/socket.h>
#include <stdio.h>
#include <sys/ioctl.h>
int main()
{
  int ret = 0;
        struct ifreq ifr;
        int sockfd;

        sockfd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
        strncpy(ifr.ifr_name, "Ethernet with Daemon Dynamic IP", sizeof(ifr.ifr_name));

                if (ioctl(sockfd, SIOCGIFINDEX, &ifr) != -1)
                {
                ret = -1;
                }

        close(sockfd);
        return ret; }

Errors

 The ioctl system call will fail if:
[EBADF]
 | The d argument is not a valid descriptor.
[ENOTTY]
 | The d argument is not associated with a character special device.
[ENOTTY]
 | The specified request does not apply to the kind of object that the descriptor d references.
[EINVAL]
 | The request or argp argument is not valid.
[EFAULT]
 | The argp argument points outside the process’s allocated address space.

See also

 fcntl

Feedback

For additional information or queries on this page send feedback


isalnum

Name

isalnum - character classification routines

Library

 libc.lib

Synopsis
#include <ctype.h>
int isalnum (int c);

Return values

 The isalnum function returns zero if the character is not alphanumeric and returns non-zero if the character tests true.

Detailed description

 The function isalnum returns non-zero if ’c’ is alphanumeric i.e. it belongs to class alnum(see defns for definition). In other words, it returns non-zero if the test for isalpha or isdigit is non-zero, irrespective of the program’s current locale. For single character representations, the value of the argument is representable as an unsigned char or the value of EOF.

The functionality of this API is independent of the program’s current locale and so it returns non-zero for all the characters (of various locales supported) that belong to the class alnum, irrespective of the locale they belong to.

Examples

#include<ctype.h> //isalnum()
#include<stdio.h> //printf()
void test_isalnum()
{
   int arr[]={’8’,0xe1,’5’,’Z’,0xfd};
   int i = 0;
   int size = 5;
   for( i=0; i<size; i++)
   {
      int ret = isalnum(arr[i]); //call to the API with chars in arr[]
      if( (!ret) != 0 )
      {
          printf("\n%c is not alphanumeric", arr[i]);
      }
      else
      {
          printf("\n%c is an alphanumeric ", arr[i]);
      }
   }
   printf("\n");
}

Output

a is an alphanumeric
á is an alphanumeric
5 is an alphanumeric
Z is an alphanumeric
ý is an alphanumeric

See also

 isalpha, isdigit, iswalnum

Feedback

For additional information or queries on this page send feedback


isalpha

Name

isalpha - character classification routines

Library

 libc.lib

Synopsis
#include <ctype.h>
int isalpha (int c);

Return values

 The isalpha function returns non-zero if the character is an alphabet and zero otherwise.

Detailed description

 The isalpha function returns non-zero if ’c’ is an alphabet i.e. it belongs to class alpha (see defns for definition). In other words, it returns non-zero if the test for isupper or islower is non-zero,irrespective of the program’s current locale. The function will return non-zero for also those characters that are alphabets and cannot be categorised as upper or lower case. For single character representations, the value of the argument is representable as an unsigned char or the value of EOF.

The functionality of this API is independent of the program’s current locale and so it returns non-zero for all the characters (of various locales supported) that belong to the class alpha,
irrespective of the locale they belong to.

Examples

#include<ctype.h> //isalpha()
#include<stdio.h> //printf()
void test_isalpha()
{
   int arr[]={’a’,0xe1,’5’,’Z’,0xfd};
   int i = 0;
   int size = 5;
   for( i=0; i<size; i++)
   {
      int ret = isalpha(arr[i]); //call to the API with chars in arr[]
      if( (!ret) != 0 )
      {
        printf("\n%c is not an alphabet", arr[i]);
      }
      else
      {
        printf("\n%c is an alphabet", arr[i]);
      }
   }
   printf("\n");
}

Output

a is an alphabet
á is an alphabet
5 is not an alphabet
Z is an alphabet
ý is an alphabet

See also

 islower, isupper, iswalpha

Feedback

For additional information or queries on this page send feedback


isascii

Name

isascii - character classification routines

Library

 libc.lib

Synopsis
#include <ctype.h>
int isascii (int c);

Return values

 The function returns non-zero if ’c’ is ASCII character, zero otherwise.

Detailed description

 The isascii function tests if ’c’ is an ASCII character, which is any character between 0 and octal 0177 inclusive.

Examples

#include<ctype.h> //isascii()
#include<stdio.h> //printf()
int test_isascii()
{
   int arr[]={’s’,’9’,’\r’, 128, ’\"’};
   int i = 0;
   int size = 5;
   for( i=0; i<size; i++)
   {
     int ret = isascii(arr[i]); //call to the API with chars in arr[]
     if( (!ret) != 0 )
     {
        printf("\n%d is not ascii char ", arr[i]);
     }
     else
     {
        printf("\n%c is ascii char", arr[i]);
     }
   }
printf("\n");
}

Output

s is ascii char
9 is ascii char
 is ascii char
128 is not ascii char
" is ascii char

See also

 toascii, defns

Feedback

For additional information or queries on this page send feedback


isatty

Name

isatty - determines if the file descriptor refers to a valid terminal type device.

Library

 libc.lib

Synopsis
#include <unistd.h>
int isatty (int fd);

Return values

 The isatty returns 1 if fd is an open descriptor connected to a terminal; returns 0 otherwise.

Detailed description

 This function operate on the system file descriptors for character special devices.

The isatty function determines if the file descriptor fd refers to a valid terminal type device.

Examples

#include<unistd.h>
#include<stdio.h>
#include<fcntl.h> //O_APPEND

int main()
{
 int x = isatty(0); //stdin (fd = 0)
 int y = isatty(1); //stdout (fd = 1)
 int z = isatty(2); //stderr (fd = 2)

 printf("{Expected: 1 1 1} %d %d %d\n", x, y, z);

 int i = isatty(5); //some invalid fd

 int fd_file = open("c:\\some.txt", O_APPEND);

 int j = isatty(fd_file); //valid fd of a text file

 int fd_pipe[3];
 int p = pipe(fd_pipe);

 int k = isatty(fd_pipe[1]); //valid fd of a pipe

 close(fd_file);
 close(fd_pipe[0]);
 close(fd_pipe[1]);

 printf("{Expected: 0 0 0} %d %d %d\n", i, j, k);

 unlink("c:\\some.txt");

 return 0;
}

Output

{Expected: 1 1 1} 1 1 1
{Expected: 0 0 0} 0 0 0

See also

 ioctl

Feedback

For additional information or queries on this page send feedback


iscntrl

Name

iscntrl - character classification routines

Library

 libc.lib

Synopsis
#include <ctype.h>
int iscntrl (int c);

Return values

 The iscntrl function returns non-zero if ’c’ is control character and zero otherwise.

Detailed description

 The iscntrl function tests if ’c’ is a control character i.e. it belongs to class cntrl(see defns for definition). For single character representations, the value of the argument is representable as an unsigned char or the value of EOF.

The functionality of this API is independent of the program’s current locale and so it returns non-zero for all the characters (of various locales supported) that belong to the class cntrl, irrespective of the locale they belong to.

Examples

#include<ctype.h> //iscntrl()
#include<stdio.h> //printf()
int test_iscntrl()
{
   int arr[]={0x7F,’9’,’A’,’$’,’\a’ };
   int i = 0;
   int size = 5;
   for( i=0; i<size; i++)
   {
      int ret = iscntrl(arr[i]); //call to the API with chars in arr[]
      if( (!ret) != 0 )
      {
         printf("\n%c is not cntrl char ", arr[i]);
      }
      else
      {
         printf("\n%c is cntrl char", arr[i]);
      }
   }
printf("\n");
}

Output

 is cntrl char
9 is not cntrl char
A is not cntrl char
$ is not cntrl char
 is cntrl char

See also

 iswcntrl

Feedback

For additional information or queries on this page send feedback


isdigit

Name

isdigit - character classification routines

Library

 libc.lib

Synopsis
#include <ctype.h>
int isdigit (int c);

Return values

 The isdigit function returns non-zero if the character is a digit and zero otherwise.

Detailed description

 The isdigit function tests if ’c’ is a decimal digit character. Regardless of locale, this includes the following characters only:

‘‘0’’ ‘‘1’’ ‘‘2’’ ‘‘3’’ ‘‘4’’
‘‘5’’ ‘‘6’’ ‘‘7’’ ‘‘8’’ ‘‘9’’

Examples

#include<ctype.h> //isdigit()
#include<stdio.h> //printf()
void test_isdigit()
{
   int arr[]={’8’,0xe1,’5’,’Z’,0xfd};
   int i = 0;
   int size = 5;
   for( i=0; i<size; i++)
   {
     int ret = isdigit(arr[i]); //call to the API with chars in arr[]
     if( (!ret) != 0 )
     {
         printf("\n%c is not a digit", arr[i]);
     }
     else
     {
         printf("\n%c is a digit", arr[i]);
     }
     }
printf("\n");
}

Output

8 is a digit
á is not a digit
5 is a digit
Z is not a digit
ý is not a digit

See also

 iswdigit, defns

Feedback

For additional information or queries on this page send feedback


isgraph

Name

isgraph - character classification routines

Library

 libc.lib

Synopsis
#include <ctype.h>
int isgraph (int c);

Return values

 The isgraph function returns non-zero if ’c’ has a visible representation and zero otherwise.

Detailed description

 The isgraph function returns non-zero if ’c’ has visible representation i.e. it belongs to class graph(see defns for definition). It does not consider characters classified under class space and class cntrl (see defns for definition). For single character representations, the value of the argument is representable as an unsigned char or the value of EOF.

The functionality of this API is independent of the program’s current locale and so it returns non-zero for all the characters (of various locales supported) that belong to the class graph, irrespective of the locale they belong to.

Examples

#include<ctype.h> //isgraph()
#include<stdio.h> //printf()
int test_isgraph()
{
   int arr[]={’n’,’\f’, ’6’, ’ ’};
   int i = 0;
   int size = 4;
   for( i=0; i<size; i++)
   {
     int ret = isgraph(arr[i]); //call to API with chars in arr[]
     if( (!ret) != 0 )
     {
        printf("\n%c is not visible char ", arr[i]);
     }
     else
     {
        printf("\n%c is visible char", arr[i]);
     }
   }
printf("\n");
}

Output

n is  visible char
is not visible char
6 is visible char
 is not visible char

See also

 iswgraph

Feedback

For additional information or queries on this page send feedback


islower

Name

islower - character classification routines

Library

 libc.lib

Synopsis
#include <ctype.h>
int islower (int c);

Return values

 The islower function returns non-zero is ’c’ is a lower-case alphabet and zero otherwise.

Detailed description

 The islower function tests if ’c’ belongs to the set of lower-case letters i.e. it belongs to class lower(see defns for definition). For single character representations, the value of the argument is representable as an unsigned char or the value of EOF.

The functionality of this API is independent of the program’s current locale and so it returns non-zero for all the characters (of various locales supported) that belong to the class lower, irrespective of the locale they belong to.

Examples

#include<ctype.h> //islower()
#include<stdio.h> //printf()
int test_islower()
{
  int arr[]={0x0126,0xee,’r’,’9’,’g’};
  int i = 0;
  int size = 5;
  for( i=0; i<size; i++)
  {
     int ret = islower(arr[i]); //call to the API with chars in the arr[]
     if( (!ret) != 0 )
     {
         printf("\n%c is not in lower-case ", arr[i]);
     }
     else
     {
         printf("\n%c is in lower-case", arr[i]);
     }
  }
printf("\n");
}

Output

& is not in lower-case
î is in lower-case
r is in lower-case
9 is not in lower-case
g is in lower-case

See also

 iswlower, tolower

Feedback

For additional information or queries on this page send feedback


isprint

Name

isprint - character classification routines

Library

 libc.lib

Synopsis
#include <ctype.h>
int isprint (int c);

Return values

 The isprint function returns non-zero if ’c’ is printable and zero otherwise.

Detailed description

 The isprint function returns true if ’c’ is a printable character. It considers characters under class space, but characters falling under class cntrl will not be considered(see defns for definition of these classes).

For single character representations, the value of the argument is representable as an unsigned char or the value of EOF.

The functionality of this API is independent of the program’s current locale and so it returns non-zero for all the characters (of various locales supported) that belong to the class print(see defns for definition), irrespective of the locale they belong to.

Examples

#include<ctype.h> //isprint()
#include<stdio.h> //printf()
int test_isprint()
{
   int arr[]={’n’,’\f’, 0xe1, ’6’, ’ ’};
   int i = 0;
   int size = 5;
   for( i=0; i<size; i++)
   {
      int ret = isprint(arr[i]); //call to the API with the chars in arr[]
      if( (!ret) != 0 )
      {
         printf("\n%c is not printable char ", arr[i]);
      }
      else
      {
         printf("\n%c is printable char", arr[i]);
      }
   }
printf("\n");
}

Output

n is printable char
  is not printable char
á is not printable char
6 is printable char
  is printable char

See also

 iswprint

Feedback

For additional information or queries on this page send feedback


ispunct

Name

ispunct - character classification routines

Library

 libc.lib

Synopsis
#include <ctype.h>
int ispunct (int c);

Return values

 The ispunct function returns non-zero if ’c’ is a punctuation character and zero otherwise.

Detailed description

 The ispunct function tests if ’c’ is a punctuation character i.e. it belongs to class punct(see defns for definition). Characters under class space or a character for which isalnum is true(non-zero) are excluded. In other words, it tests for punctuation characters. For single character representations, the value of the argument is representable as an unsigned char or the value of EOF.

The functionality of this API is independent of the program’s current locale and so it returns non-zero for all the characters (of various locales supported) that belong to the class punct, irrespective of the locale they belong to.

Examples

#include<ctype.h> //ispunct()
#include<stdio.h> //printf()
int test_ispunct()
{
  int arr[]={0x3003,’3’,0x301C,’*’, ’+’};
  int i = 0;
  int size = 5;
  for( i=0; i<size; i++)
  {
     int ret = ispunct(arr[i]); //call to the API with chars in arr[]
     if( (!ret) != 0 )
     {
         printf("\n0x%x is not a punc char ", arr[i]);
     }
     else
     {
         printf("\n0x%x is a punc char", arr[i]);
     }
}
printf("\n");
return 0;
}

Output

0x3003 is a punc char
0x33 is not a punc char
0x301c is a punc char
0x2a is a punc char
0x2b is a punc char

See also

 iswpunct

Feedback

For additional information or queries on this page send feedback


isspace

Name

isspace - character classification routines

Library

 libc.lib

Synopsis
#include <ctype.h>
int isspace (int c);

Return values

 The isspace function returns non-zero if ’c’ is space character and zero otherwise.

Detailed description

 The isspace function tests if ’c’ is from among white-space characters i.e. it belongs to class space(see defns for definition). This includes the following standard characters:

SPACE

FORM-FEED

NEWLINE

CARRIAGE-RETURN

TAB

VERTICAL-TAB

For single character representations, the value of the argument is representable as an unsigned char or the value of EOF.

The functionality of this API is independent of the program’s current locale and so it returns non-zero for all the characters (of various locales supported) that belong to the class space, irrespective of the locale they belong to.

Examples

#include<ctype.h> //isspace()
#include<stdio.h> //printf()
int test_isspace()
{
   int arr[]={’\n’,’0’,’w’,’R’,0x3000,’ ’};
   int i = 0;
   int size = 5;
   for( i=0; i<size; i++)
   {
      int ret = isspace(arr[i]); //call to the API with chars in arr[]
      if( (!ret) != 0 )
      {
         printf("\n%c is not space char ", arr[i]);
      }
      else
      {
         printf("\n%c is space char", arr[i]);
      }
   }
printf("\n");
}

Output

 is space char
0 is not space char
w is not space char
R is not space char
   is space char

See also

 iswspace

Feedback

For additional information or queries on this page send feedback


isupper

Name

isupper - character classification routines

Library

 libc.lib

Synopsis
#include <ctype.h>
int isupper (int c);

Return values

 The isupper function returns non-zero if ’c’ is in upper case and zero otherwise.

Detailed description

 The isupper function tests if ’c’ is an upper-case alphabet i.e. it belongs to class upper(see defns for definition). For single character representations, the value of the argument is representable as an unsigned char or the value of EOF.

The functionality of this API is independent of the program’s current locale and so it returns non-zero for all the characters (of various locales supported) that belong to the class upper, irrespective of the locale they belong to.

Examples

#include<ctype.h> //isupper()
#include<stdio.h> //printf()
int test_isupper()
{
int arr[]={0x0126,’G’,’7’,’B’,0x3041};
int i = 0;
int size = 5;
for( i=0; i<size; i++)
{
   int ret = isupper(arr[i]); //call to the API with chars in arr[]
   if( (!ret) != 0 )
   {
        printf("\n%c is not in upper-case ", arr[i]);
   }
   else
   {
        printf("\n%c is in upper-case", arr[i]);
   }
   }
printf("\n");
}

Output

& is in upper-case
G is in upper-case
7 is not in upper-case
B is in upper-case
A is in upper-case

See also

 iswupper, toupper

Feedback

For additional information or queries on this page send feedback


iswalnum

Name

iswalnum - test for alphanumeric wide character

Library

 libc.lib

Synopsis
#include <wctype.h>
int iswalnum (wint_t wch);

Return values

 The functions return non-zero if wch is wide alphabet or wide digit and zero otherwise.

Detailed description

The iswalnum() function tests whether ’wch’ is a wide alphabet or wide digit i.e. it belongs to class alnum(see defns for definition).

The result of this function is undefined unless the argument is WEOF or a valid wchar_t value.

The functionality of this API is independent of the program’s current locale and so it returns non-zero for all the characters (of various locales supported) that belong to the class alnum, irrespective of the locale they belong to.

Examples

#include<wctype.h> //iswalnum()
#include<stdio.h>  //printf()
void test_iswalnum()
{
   int arr[]={’8’,0xe1,’5’,’Z’,0xfd,0xFF12,0xFF19,0xFF71,0x03A3};
   int i = 0;
   int size = 9;
   for( i=0; i<size; i++)
   {
     int ret = iswalnum(arr[i]); //call to the API with chars in the arr[]
     if( (!ret) != 0 )
     {
        printf("\n%lc is not wide alnum", arr[i]);
     }
     else
     {
        printf("\n%lc is a wide alnum ", arr[i]);
     }
   }
printf("\n");
}

Output

8 is wide alnum
«¡ is wide alnum
5 is wide alnum
Z is wide alnum
«ò is wide alnum
£² is wide alnum
£¹ is wide alnum
± is wide alnum
¦² is wide alnum

See also

 isalnum, iswctype

Feedback

For additional information or queries on this page send feedback


iswalpha

iswalpha - test for alphabetic wide character

Library

 libc.lib

Synopsis
#include <wctype.h>
int iswalpha (wint_t wch);

Return values

 The functions return non-zero if ’wch’ is a wide alphabet and zero otherwise.

Detailed description

The iswalpha() function tests whether ’wch’ is a wide alphabet i.e. it belongs to class alpha(see defns for definition).

The result of this function is undefined unless the argument is WEOF or a valid wchar_t value.

The functionality of this API is independent of the program’s current locale and so it returns non-zero for all the characters (of various locales supported) that belong to the class alpha, irrespective of the locale they belong to.

Examples

#include<wctype.h> //iswalpha()
#include<stdio.h>  //printf()
void test_iswalpha()
{
   int arr[]={’a’,0xe1,’5’,’Z’,0xfd, 0x3041,0xFF9D,0x009F,0x007E};
   int i = 0;
   int size = 9;
   for( i=0; i<size; i++)
   {
     int ret = iswalpha(arr[i]); //call to API with chars in arr[]
     if( (!ret) != 0 )
     {
        printf("\n%lc is not wide alphabet", arr[i]);
     }
     else
     {
        printf("\n%lc is wide alphabet", arr[i]);
     }
   }
printf("\n");
}

Output

a is wide alphabet
«¡ is wide alphabet
5 is not wide alphabet
Z is wide alphabet
«ò is wide alphabet
¤¡ is wide alphabet
Ý is wide alphabet
 is not wide alphabet
~ is not wide alphabet

See also

 isalpha, iswctype

Feedback

For additional information or queries on this page send feedback


iswblank

Name

iswblank - test for whitespace wide character

Library

 libc.lib

Synopsis
#include <wctype.h>
int iswblank (wint_t wch);

Return values

 The functions return non-zero if ’wch’ is wide blank character and zero otherwise.

Detailed description

The iswblank() function tests whether ’wch’ is a wide-character that belongs to the character class - blank (see defns for definition). The character class blank contains the character space(’ ’) and the horizontal tabulation(’ ’).

The result of this function is undefined unless the argument is WEOF or a valid wchar_t value.

The functionality of this API is independent of the program’s current locale and so it returns non-zero for all the characters (of various locales supported) that belong to the class blank, irrespective of the locale they belong to.

Examples

#include<wctype.h> //iswblank()
#include<stdio.h> //printf()
int test_iswblank()
{
   int arr[]={0x0020,’0’,0x0009,’R’,0x3000, 0x000A, 0x002};
   int i = 0;
   int size = 7;
   for( i=0; i<size; i++)
   {
     int ret = iswblank(arr[i]); //call to the API with the chars in arr[]
     if( (!ret) != 0 )
     {
        printf("\n%lc is not wide blank ", arr[i]);
     }
     else
     {
        printf("\n%lc is wide blank", arr[i]);
     }
   }
printf("\n");
}

Output

is wide blank
0 is not wide blank
     is wide blank
R is not wide blank
¡¡ is wide blank
 is not wide blank
 is not wide blank

See also

 iswctype

Feedback

For additional information or queries on this page send feedback


iswcntrl

Name

iswcntrl - test for control wide character

Library

 libc.lib

Synopsis
#include <wctype.h>
int iswcntrl (wint_t wch);

Return values

 The functions return non-zero if ’wch’ is a wide control character and returns zero otherwise.

Detailed description

The iswcntrl() function tests whether ’wch’ is a wide control character i.e it belongs to class cntrl(see defns for definition).

The result of this function is undefined unless the argument is WEOF or a valid wchar_t value.

The functionality of this API is independent of the program’s current locale and so it returns non-zero for all the characters (of various locales supported) that belong to the class cntrl, irrespective of the locale they belong to.

The control characters are:

BELL

DELETE

BACKSPACE

LINE FEED

VERTICAL TABULATION

FORM FEED

CARRIAGE RETURN...and the like.

Examples

#include<wctype.h> //iswcntrl()
#include<stdio.h> //printf()
int test_iswcntrl()
{
   int arr[]={0x7F,’9’,’A’,’$’,’\a’ };
   int i = 0;
   int size = 5;
   for( i=0; i<size; i++)
   {
     int ret = iswcntrl(arr[i]); //call to API with chars in arr[]
     if( (!ret) != 0 )
     {
        printf("\n%lc is not wide cntrl char ", arr[i]);
     }
     else
     {
        printf("\n%lc is wide cntrl char", arr[i]);
     }
   }
printf("\n");
}

Output

is wide cntrl char
9 is not wide cntrl char
A is not wide cntrl char
$ is not wide cntrl char
 is wide cntrl char

See also

 iswcntrl, iswctype

Feedback

For additional information or queries on this page send feedback


iswctype

Name

iswctype - wide character classification

Library

 libc.lib

Synopsis
#include <wctype.h>
int iswctype (wint_t wch, wctype_t chcl);

Return values

 The functions return non-zero if ’wch’ belongs to category ’chcl’ and zero otherwise.

Detailed description

The iswctype() function tests whether the wide-character wch belongs to the character class/category chcl.

The result of this function is undefined unless the argument is WEOF or a valid wchar_t value.

The functionality of this API is independent of the program’s current locale and so it returns non-zero for all the characters given in ’wch’(of various locales supported) that belong to the class chcl(see _ctype.h for definition of values that can be used to specify category), irrespective of the locale they belong to.

For example: digits 0 to 9 would belong to _CTYPE_D class (i.e. class digit), and a to z would belong to _CTYPE_L class (i.e. class lower).

Examples

#include<wctype.h> //iswctype()
#include<stdio.h>  //printf()
int test_iswctype()
{
   struct st
   {
    int input;
    int category;
   };
   struct st arr[]={
   {0xFF21, _CTYPE_A},
   {0x0040, _CTYPE_P},
   {0x007F, _CTYPE_C},
   {0xFF10,_CTYPE_G},
   {0x007A, _CTYPE_U},
   {0xFF6F, _CTYPE_D},
   {0xFF10, _CTYPE_S},
   };
   int i = 0;
   int size = 7;
   for( i=0; i<size; i++)
   {
     //call to the API with the values in the arr[]
     int ret = iswctype(arr[i].input, arr[i].category);
     if( (!ret) != 0 )
     {
        printf("\n0x%x not from this category ", arr[i].input);
     }
     else
     {
        printf("\n0x%x from this category", arr[i].input);
     }
}
printf("\n");
}

Output

0xFF21 from this category
0x0040 from this category
0x007F from this category
0xFF10 from this category
0x007A not from this category
0xFF6F not from this category
0xFF10 not from this category

Feedback

For additional information or queries on this page send feedback


iswdigit

Name

iswdigit - test for decimal digit wide character
libc.lib

Synopsis
#include <wctype.h>
int iswdigit (wint_t wch);

Return values

 The functions return non-zero if ’wch’ is a wide digit and zero otherwise.

Detailed description

The iswdigit() function tests whether ’wch’ is a wide digit. The functionality of this API is independent of the program’s current locale and so it returns non-zero for all the characters (of various locales supported) that belong to the class digit(see defns for definition), irrespective of the locale they belong to.

For example, the digits 0 to 9 fall under class digit.

Examples

#include<wctype.h> //iswdigit()
#include<stdio.h> //printf()
void test_iswdigit()
{
   int arr[]={’8’,0xe1,’5’,’Z’,0xfd,
   0xFF12,0xFF19,0xFF71,0x03A3};
   int i = 0;
   int size = 9;
   for( i=0; i<size; i++)
   {
     int ret = iswdigit(arr[i]); //call to the API with chars in arr[]
     if( (!ret) != 0 )
     {
         printf("\n%lc is not a wide digit", arr[i]);
     }
     else
     {
         printf("\n%lc is a wide digit", arr[i]);
     }
   }
printf("\n");
}

Output

8 is wide digit
«¡ is not wide digit
5 is wide digit
Z is not wide digit
«ò is not wide digit
£² is wide digit
£¹ is wide digit
± is not wide digit
¦² is not wide digit

See also

 isdigit, iswctype

Feedback

For additional information or queries on this page send feedback


iswgraph

Name

iswgraph - tests for graphic wide character

Library

 libc.lib

Synopsis
#include <wctype.h>
int iswgraph (wint_t wch);

Return values

 The function returns non-zero if ’wch’ has visual representation and zero otherwise.

Detailed description

The iswgraph() function tests whether ’wch’ is a visible wide-character i.e it belongs to class graph(see defns for definition).

The result of this function is undefined unless the argument is WEOF or a valid wchar_t value.

The functionality of this API is independent of the program’s current locale and so it returns non-zero for all the characters (of various locales supported) that belong to the class graph, irrespective of the locale they belong to.

Examples

#include<wctype.h>
#include<stdio.h>
int test_iswgraph()
{
   int arr[]={’n’,’\f’, 0xe1, ’6’, ’ ’};
   int i = 0;
   int size = 5;
   for( i=0; i<size; i++)
   {
     int ret = iswgraph(arr[i]);
     if( (!ret) != 0 )
     {
        printf("\n%lc is not wide visible char ", arr[i]);
     }
     else
     {
        printf("\n%lc is wide visible char", arr[i]);
     }
   }
printf("\n");
}

Output

n is wide visible char
 is not wide visible char
«¡ is wide visible char
6 is wide visible char
  is not wide visible char

See also

 isgraph, iswctype

Feedback

For additional information or queries on this page send feedback


iswlower

Name

iswlower - tests for lowercase wide character

Library

 libc.lib

Synopsis
#include <wctype.h>
int iswlower (wint_t wch);

Return values

 The function returns non-zero if ’wch’ is wide lower-case and zero otherwise.

Detailed description

The iswlower() function tests whether ’wch’ is a wide-character which is from among lower-case alphabets.

Characters that belong to class cntrl, class punct and digit are not a part of class lower(see defns for definition).

The result of this function is undefined unless the argument is WEOF or a valid wchar_t value.

The functionality of this API is independent of the program’s current locale and so it returns non-zero for all the characters (of various locales supported) that belong to the class lower(see defns for definition), irrespective of the locale they belong to.

Examples

#include<wctype.h> //iswlower()
#include<stdio.h> //printf()
int test_iswlower()
{
   int arr[]={ 0x0126, 0xee, ’r’ , ’9’ , ’g’, 0xFF51, 0x0451, 0x03CE };
   int i = 0;
   int size = 8;
   for( i=0; i<size; i++)
   {
     int ret = iswlower(arr[i]); //call to the API with chars in arr[]
     if( (!ret) != 0 )
     {
        printf("\n%lc is not wide lower-case ", arr[i]);
     }
     else
     {
        printf("\n%lc is wide lower-case", arr[i]);
     }
   }
printf("\n");
}

Output

©¤ is not wide lower-case
«Â is wide lower-case
r is wide lower-case
9 is not wide lower-case
g is wide lower-case
£ñ is wide lower-case
§× is wide lower-case
¦ü is wide lower-case

See also

 islower, iswctype

Feedback

For additional information or queries on this page send feedback


iswprint

Name

iswprint - tests for printing wide character

Library

 libc.lib

Synopsis
#include <wctype.h>
int iswprint (wint_t wch);

Return values

 The function returns non-zero if the wide character is printable and returns zero otherwise.

Detailed description

The iswprint() function tests whether ’wch’ is a wide-character that can be printed i.e it belongs to class print(see defns for definition).

Characters used for representing the alphabets, digits, punctuation characters,space are classified as printable. No characters under class cntrl are printable.

The result of this function is undefined unless the argument is WEOF or a valid wchar_t value.

The functionality of this API is independent of the program’s current locale and so it returns non-zero for all the characters (of various locales supported) that belong to the class print, irrespective of the locale they belong to.

Examples

#include<wctype.h> //iswprint()
#include<stdio.h> //printf()
int test_iswprint()
{
   int arr[]={’n’,’, 0xe1, ’6’, ’ ’};
   int i = 0;
   int size = 5;
   for( i=0; i<size; i++)
   {
     int ret = iswprint(arr[i]); //call to the API with chars in the arr[]
     if( (!ret) != 0 )
     {
        printf("\n%lc is not wide printable char ", arr[i]);
     }
     else
     {
        printf("\n%lc is wide printable char", arr[i]);
     }
   }
printf("\n");
}

Output

n is wide printable char
 is not wide printable char
«¡ is wide printable char
6 is wide printable char
  is wide printable char

See also

 isprint, iswctype

Feedback

For additional information or queries on this page send feedback


iswpunct

Name

iswpunct - tests for punctuation or symbolic wide character

Library

 libc.lib

Synopsis
#include <wctype.h>
int iswpunct (wint_t wch);

Return values

 The function returns non-zero if ’wch’ is a wide character and returns zero otherwise.

Detailed description

The iswpunct() function tests whether ’wch’ can be classfied wide punctuation character i.e. it belongs to class punct(see defns for definition)

The characters that can be classified as alphabets, digits, space or control characters donot belong to punctuation wide-character code.

The result of this function is undefined unless the argument is WEOF or a valid wchar_t value.

The functionality of this API is independent of the program’s current locale and so it returns non-zero for all the characters (of various locales supported) that belong to the class punct, irrespective of the locale they belong to.

Examples

#include<wctype.h> //iswpunct()
#include<stdio.h>  //printf()
int test_iswpunct()
{

   int arr[]={0x3003,’3’,0x301C,’*’, ’+’};
   int i = 0;
   int size = 5;
   for( i=0; i<size; i++)
   {
     int ret = iswpunct(arr[i]);//call to the API with chars in arr[]
     if( (!ret) != 0 )
     {
         printf("\n0x%x is not wide punc char ", arr[i]);
     }
     else
     {
         printf("\n0x%x is a wide punc char", arr[i]);
     }
   }
printf("\n");
}

Output

0x3003 is a wide punc char
0 0x33 is not  wide punc char
0x301c is a wide punc char
0x2a is a wide punc char
0x2b is a wide punc char

See also

 ispunct, iswctype

Feedback

For additional information or queries on this page send feedback


iswspace

Name

iswspace - tests for whitespace wide character
defns for definition)

Library

 libc.lib

Synopsis
#include <wctype.h>
int iswspace (wint_t wch);

Return values

 The functions return zero if the character tests false and return non-zero if the character tests true.

Detailed description

The iswspace() function tests whether ’wch’ is a wide-character that introduces white-space.

The following are such characters in the POSIX locale:

SPACE

FORM-FEED

NEWLINE

CARRIAGE-RETURN

TAB

VERTICAL-TAB

The result of this function is undefined unless the argument is WEOF or a valid wchar_t value.

The functionality of this API is independent of the program’s current locale and so it returns non-zero for all the characters (of various locales supported) that belong to the class space, irrespective of the locale they belong to.

Examples

#include<wctype.h> //iswspace()
#include<stdio.h> //printf()
int test_iswspace()
{
   int arr[]={’\n’,’0’,’w’,’R’,0x3000,’ ’, 0x000A, 0x002};
   int i = 0;
   int size = 8;
   for( i=0; i<size; i++)
   {
     int ret = iswspace(arr[i]); //call to the API with chars in arr[]
     if( (!ret) != 0 )
     {
        printf("\n%lc is not wide space ", arr[i]);
     }
     else
     {
        printf("\n%lc is wide space", arr[i]);
     }
   }
printf("\n");
}

Output

is wide space
0 is not wide space
w is not wide space
R is not wide space
¡¡ is wide space
  is wide space
 is wide space
 is wide space

See also

 isspace, iswctype

Feedback

For additional information or queries on this page send feedback


iswupper

Name

iswupper - tests for uppercase wide character

Library

 libc.lib

Synopsis
#include <wctype.h>
int iswupper (wint_t wch);

Return values

 The functions return zero if the character tests false and return non-zero if the character tests true.

Detailed description

The iswupper() function tests whether wch is a wide-character that belongs to upper-case letters, i.e. checks if it belongs to class upper(see defns for definition).

Characters that belong to class cntrl, punct and digit are not a part of class upper(see defns for definition).

The result of this function is undefined unless the argument is WEOF or a valid wchar_t value.

The functionality of this API is independent of the program’s current locale and so it returns non-zero for all the characters (of various locales supported) that belong to the class upper, irrespective of the locale they belong to.

Examples

#include<wctype.h> //iswupper()
#include<stdio.h>  //printf()
int test_iswupper()
{
   int arr[]={’8’,0xe1,’5’,’Z’,0x0126 , 0xFF21 ,’G’ , 0x03A4 , 0x00CF };
   int i = 0;
   int size = 9;
   for( i=0; i<size; i++)
   {
     int ret = iswupper(arr[i]); //call to the API with the chars in arr[]
     if( (!ret) != 0 )
     {
        printf("\n%lc is not wide upper-case ", arr[i]);
     }
     else
     {
        printf("\n%lc is wide upper-case", arr[i]);
     }
   }
printf("\n");
}

Output

8 is not wide upper-case «¡ is not wide upper-case
5 is not wide upper-case
Z is wide upper-case
©¤ is wide upper-case
£Á is wide upper-case
G is wide upper-case
¦³ is wide upper-case
ªÁ is wide upper-case

See also

 isupper, iswctype

Feedback

For additional information or queries on this page send feedback


iswxdigit

Name

iswxdigit - tests for hexadecimal digit wide character

Library

 libc.lib

Synopsis
#include <wctype.h>
int iswxdigit (wint_t wch);

Return values

 The functions return zero if the character tests false and return non-zero if the character tests true.

Detailed description

The iswxdigit() function tests whether ’wch’ is a wide-character belongs to the set of characters that are used to represent hexadecimal digits.

For example: The characters that can be used to represent hexadecimal values: are - 0,1,2,3,4,5,6,7,8,9 and a,b,c,d,e,f and A,B,C,D,E,F.

Generally, the characters that can be classified as digits are used for the representing hexadecimal values along with one or more sets of continuous characters of other categories that are used to represent the hexadecimal values other than the digits(base 10).

The result of this function is undefined unless the argument is WEOF or a valid wchar_t value.

The functionality of this API is independent of the program’s current locale and so it returns non-zero for all the characters (of various locales supported) that belong to the class xdigit(see defns for definition), irrespective of the locale they belong to.

Examples

#include<wctype.h> //iswxdigit()
#include<stdio.h> //printf()
int test_iswxdigit()
{
   int arr[]={’F’,’a’,’M’,’9’,’2’};
   int i = 0;
   int size = 5;
   for( i=0; i<size; i++)
   {
     int ret = iswxdigit(arr[i]); //call to the API with the chars in arr[]
     if( (!ret) != 0 )
     {
        printf("\n%c is not wide hex-digit ", arr[i]);
     }
     else
     {
        printf("\n%c is wide hex-digit", arr[i]);
     }
   }
printf("\n");
}

Output

F is wide hex-digit
a is wide hex-digit
M is not wide hex-digit
9 is wide hex-digit
2 is wide hex-digit

See also

 isdigit, iswctype

Feedback

For additional information or queries on this page send feedback


isxdigit

Name

isxdigit - character classification routines

Library

 libc.lib

Synopsis
#include <ctype.h>
int isxdigit (int c);

Return values

 The isxdigit function returns non-zero if ’c’ is a character used for hex-representation and zero otherwise.

The iswxdigit function should be used instead.

Detailed description

 The isxdigit function tests if ’c’ is a hexadecimal-digit character. Regardless of locale, this includes the following characters only:

‘‘0’’ ‘‘1’’ ‘‘2’’ ‘‘3’’ ‘‘4’’
‘‘5’’ ‘‘6’’ ‘‘7’’ ‘‘8’’ ‘‘9’’
‘‘A’’ ‘‘B’’ ‘‘C’’ ‘‘D’’ ‘‘E’’
‘‘F’’ ‘‘a’’ ‘‘b’’ ‘‘c’’ ‘‘d’’
‘‘e’’ ‘‘f’’

Examples

#include<ctype.h> //isxdigit()
#include<stdio.h> //printf()
int test_isxdigit()
{
   int arr[]={’F’,’a’,’M’,’9’,’2’};
   int i = 0;
   int size = 5;
   for( i=0; i<size; i++)
   {
      int ret = isxdigit(arr[i]); //call to the API with chars in arr[]
      if( (!ret) != 0 )
      {
          printf("\n%c is not hex-digit ", arr[i]);
      }
      else
      {
          printf("\n%c is hex-digit", arr[i]);
      }
}
printf("\n");
}

Output

F is hex-digit
a is hex-digit
M is not hex-digit
9 is hex-digit
2 is hex-digit

See also

 iswxdigit, defns

Feedback

For additional information or queries on this page send feedback


j0

Name

j0, j0f, j0l, j1, j1f, j1l, jn, jnf, jnl, y0, y0f, y0l, y1, y1f, y1l, yn, ynf, ynl
- Bessel functions

Library

 libm.lib

Synopsis
#include <math.h>
double j0 (double x);
float j0f (float x);
long double j0l (long double x);
double j1 (double x);
float j1f (float x);
long double j1l (long double x);
double jn (int n, double x);
float jnf (int n, float x);
long double jnl (int n, long double x);
double y0 (double x);
float y0f (float x);
long double y0l (long double x);
double y1 (double x);
float y1f (float x);
long double y1l (long double x);
double yn (int n, double x);
float ynf (int n, float x);
long double ynl (int n, long double x);

Return values

 If these functions are successful, the computed value is returned.

Detailed description

 The functions j0, j0f, j1 and j1f compute the Bessel function of the first kind of the order 0 and the order 1, respectively, for the real value x; the functions jn and jnf compute the Bessel function of the first kind of the integer order n for the real value x.

The functions y0, y0f, y1, and y1f compute the linearly independent Bessel function of the second kind of the order 0 and the order 1, respectively, for the positive real value x; the functions yn and ynf compute the Bessel function of the second kind for the integer order n for the positive real value x.

Here the long double version APIs are aliases the double version APIs. All APIs <Function>l behaves similiar to that of <Function>.

Examples

#include <math.h>
int main( )
{
   double x = 1.0;
   /*J0(), j0f() and j0l() */
   double y = j0( x );
   printf( "j0( %f) = %f\n", x, y );
   y = j0f( x );
   printf( "j0f( %f) = %f\n", x, y );
   y = j0l( x );
   printf( "j0l( %f) = %f\n\n", x, y );
   /*J1(), j1f() and j1l() */
   y = j1( x );
   printf( "j1( %f) = %f\n", x, y );
   y = j1f( x );
   printf( "j1f( %f) = %f\n", x, y );
   y = j1l( x );
   printf( "j1l( %f) = %f\n\n", x, y );
   /*jn(), jnf() and jnl() */
   y = jn( 3, x );
   printf( "jn( 2, %f) = %f\n", x, y );
   y = jnf( 1, x );
   printf( "jnf( 1, %f) = %f\n", x, y );
   y = jnl( 10, 0.75 );
   printf( "jnl(10, %f) = %f\n\n", 0.75, y );
   /*y0(), y0f() and y0l() */
   y = y0( x );
   printf( "y0( %f) = %f\n", x, y );
   y = y0f( x );
   printf( "y0f( %f) = %f\n", x, y );
   y = y0l( x );
   printf( "y0l( %f) = %f\n\n", x, y );
   /*y1(), y1f() and y1l() */
   y = y1( x );
   printf( "y1( %f) = %f\n", x, y );
   y = y1f( x );
   printf( "y1f( %f) = %f\n", x, y );
   y = y1l( x );
   printf( "y1l( %f) = %f\n\n", x, y );
   /*yn(), ynf() and ynl() */
   y = yn( 3, x );
   printf( "yn( 2, %f) = %f\n", x, y );
   y = ynf( 1, x );
   printf( "ynf( 1, %f) = %f\n", x, y );
   y = ynl( 10, 0.75 );
   printf( "ynl(10, %f) = %f\n\n", 0.75, y );
}

Output

j0( 1.000) = 0.76519768
j0f( 1.000) = 0.76519768
j0l( 1.000) = 0.76519768
j1 ( 1.000) = 0.4400505
j1f( 1.000) = 0.4400505
j1l( 1.000) = 0.4400505
jn ( 3, 1.000) = 0.0195633
jnf( 1, 1.000) = 0.4400505
jnl( 10, 0.75) = 0.1496212
y0 ( 1.000) = 0.0882569
y0f( 1.000) = 0.0882569
y0l( 1.000) = 0.0882569
y1 ( 1.000) = -0.7812128
y1f( 1.000) = -0.7812128
y1l( 1.000) = -0.7812128
yn ( 3, 1.000) = -5.8215176
ynf( 1, 1.000) = -0.781212
ynl( 10, 0.75) = -2133501638.9

See also

 math

Feedback

For additional information or queries on this page send feedback


labs

Name

labs - computes the absolute value of an integer

Library

 libc.lib

Synopsis
#include <stdlib.h>
long labs (long j);

Return values

 The (labs, function, returns, the, absolute, value.);

Detailed description

 The labs function returns the absolute value of the long integer j.

Examples

#include  <stdio.h>
#include  <stdlib.h>

int main( void )
{
   int    ix = -4, iy;
   long   lx = -41567L, ly;
   long long llx = -5343546758, lly;

   iy = abs( ix );
   printf( "The abs value of %d is %d\n", ix, iy);

   ly = labs( lx );
   printf( "The abs value of %ld is %ld\n", lx, ly);

   lly = llabs( llx );
   printf( "The abs value of %lld is %lld\n", llx, lly );

   return 0;
}

Output

The absolute value of -4 is 4
The absolute value of -41567 is 41567
The absolute value of -5343546758 is 5343546758

See also

 abs, floor, llabs, math

Feedback

For additional information or queries on this page send feedback


ldexp

Name

ldexp, ldexpf, ldexpl
- multiply floating-point number by integral power of 2

Library

 libm.lib

Synopsis
#include <math.h>
double ldexp (double x, int exp);
float ldexpf (float x, int exp);
long double ldexpl (long double x, int exp);

Return values

 These functions return the value of x times 2 raised to the power exp.

Detailed description

 The ldexp, ldexpf, and ldexpl functions multiply a floating-point number by an integral power of 2.

Examples

#include <math.h>
int main( void )
{
   double x1 = 0.8, x2 = 4, y;
   y = ldexp( x1, x2 );
   printf( "ldexp(%f , %f) = %f\n", x1, x2, y );
   y = ldexpf( x1, x2 );
   printf( "ldexpf(%f , %f) = %f\n", x1, x2, y );
   y = ldexpl( x1, x2 );
   printf( "ldexpl(%f , %f) = %f\n", x1, x2, y );
}

Output

ldexp ( 0.8, 4 ) = 12.8
ldexpf( 0.8, 4 ) = 12.8
ldexpl( 0.8, 4 ) = 12.8

See also

 frexp, math, modf

Feedback

For additional information or queries on this page send feedback


ldiv

Name

ldiv - computes quotient and remainder of an integer division

Library

 libc.lib

Synopsis
#include <stdlib.h>
ldiv_t ldiv (long num, long denom);

Return values

 The ldiv function returns a structure of type ldiv_t that contains two long members named quot (quotient) and rem (remainder).

Detailed description

 The ldiv function computes the value num / denom and returns the quotient and remainder in a structure named ldiv_t that contains two long members named quot and rem.

Examples

#include <stdlib.h>
#include <stdio.h>

int main( void )
{
 long numer = 13;
 long denom = -3;

 /* call to ldiv */
 ldiv_t x = ldiv(numer, denom);

 printf("Result-> \nQuotient = %ld \nRemainder = %ld", x.quot, x.rem);

 long exp_numer = (denom * x.quot) + x.rem;

 if( exp_numer == (numer) )
    printf("\nResult is same as the expected output");
 else
    printf("\nUnexpected output");

 return 0;
}

Output

Result->
Quotient = 4
Remainder = -1
Result is same as the expected output

Errors

 No errors are defined.

See also

 div, lldiv

Feedback

For additional information or queries on this page send feedback


lgamma

Name

lgamma, lgamma_r, lgammaf, lgammal, lgammaf_r
gamma, gamma_r, gammaf, gammal, gammaf_r

- log gamma function

Library

 libm.lib

Synopsis
#include <math.h>
extern int signgam;

double lgamma (double x);
double lgamma_r (double x, int *signgamp);
float lgammaf (float x);
long double lgammal (long double x);
float lgammaf_r (float x, int *signgamp);
double gamma (double x);
double gamma_r (double x, int *signgamp);
float gammaf (float x);
long double gammal (long double x);
float gammaf_r (float x, int *signgamp);

Return values

 gamma, gamma_r, gammaf, gammaf_r, lgamma, lgamma_r, lgammaf, and lgammaf_r return appropriate values unless an argument is out of range. Overflow will occur for sufficiently large positive values, and non-positive integers. For large non-integer negative values, tgamma will underflow.

Detailed description

 lgamma (x);
and lgammaf (x);
return ln||_(x)| where |_(x) = I00oo0 tx-10 e-t0 dt for x > 0 and |_(x) = pi/(|_(1-x)sin(pix)) for x < 1. return ln||_(x)|.

The external integer signgam returns the sign of |_(x).

lgamma_r (x, signgamp);
and lgammaf_r (x, signgamp);
provide the same functionality as lgamma (x);
and lgammaf (x);
but the caller must provide an integer to store the sign of |_(x).

gamma, gammaf, gamma_r, and gammaf_r are deprecated aliases for lgamma, lgammaf, lgamma_r, and lgammaf_r, respectively. lgammal (and);
gammal (are, just, alias, to, the, functions);
lgamma (and);
gamma respectively.

Idiosyncrasies

 Do not use the expression "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 or lgammaf has returned can signgam be correct.

Examples

#include <math.h>
int main( void )
{
   double x1 = 0.0,  y;
   y = lgamma( 0.0 );
   printf( "lgamma(%f) = %f and signgam = %d\n", x1, signgam, y );
   y = lgammaf( 0.0 );
   printf( "lgammaf(%f) = %f and signgam = %d\n", x1, signgam, y );
   y = lgammal( 0.0 );
   printf( "lgammal(%f) = %f and signgam = %d\n", x1, signgam, y );
   y = gamma( 0.0 );
   printf( "gamma(%f) = %f and signgam = %d\n", x1, signgam, y );
   y = gammaf( 0.0 );
   printf( "gammaf(%f) = %f and signgam = %d\n", x1, signgam, y );
   y = gammal( 0.0 );
   printf( "gammal(%f) = %f and signgam = %d\n", x1, signgam, y );
}

Output

lgamma ( 0.0) = Inf and signgam = 1
lgammaf( 0.0 ) = Inf and signgam = 1
lgammal( 0.0 ) = Inf and signgam = 1
gamma ( 0.0 ) = Inf and signgam = 1
gammaf( 0.0 ) = Inf and signgam = 1
gammal( 0.0 ) = Inf and signgam = 1

See also

 math

Feedback

For additional information or queries on this page send feedback


lh_node_usage_stats_bio - LHASH statistics

Name

lh_stats, lh_node_stats
lh_node_usage_stats
lh_stats_bio, lh_node_stats_bio
lh_node_usage_stats_bio

LHASH statistics

Library

libcrypto.lib

Synopsis

#include <openssl/lhash.h>
void lh_stats(LHASH *table, FILE *out);
void lh_node_stats(LHASH *table, FILE *out);
void lh_node_usage_stats(LHASH *table, FILE *out);
void lh_stats_bio(LHASH *table, BIO *out);
void lh_node_stats_bio(LHASH *table, BIO *out);
void lh_node_usage_stats_bio(LHASH *table, BIO *out);

Detailed Description

The LHASH structure records statistics about most aspects of accessing the hash table. This is mostly a legacy of Eric Young writing this library for the reasons of implementing what looked like a nice algorithm rather than for a particular software product.

lh_stats() prints out statistics on the size of the hash table, how many entries are in it, and the number and result of calls to the routines in this library.

lh_node_stats() prints the number of entries for each 'bucket' in the hash table.

lh_node_usage_stats() prints out a short summary of the state of the hash table. It prints the 'load' and the 'actual load'. The load is the average number of data items per 'bucket' in the hash table. The 'actual load' is the average number of items per 'bucket', but only for buckets which contain entries. So the 'actual load' is the average number of searches that will need to find an item in the hash table, while the 'load' is the average number that will be done to record a miss.

lh_stats_bio(), lh_node_stats_bio() and lh_node_usage_stats_bio() are the same as the above, except that the output goes to a BIO.

Return Values

These functions do not return values.

See Also

bio(), lhash()

History

These functions are available in all versions of SSLeay and OpenSSL.

This manpage is derived from the SSLeay documentation.

Feedback

For additional information or queries on this page send feedback


lh_error - dynamic hash table

Name

lh_new, lh_free, lh_insert
lh_delete, lh_retrieve, lh_doall,
lh_doall_arg, lh_error

implements dynamic hash tables

Library

libcrypto.lib

Synopsis

#include <openssl/lhash.h>
LHASH *lh_new(LHASH_HASH_FN_TYPE hash, LHASH_COMP_FN_TYPE compare);
void lh_free(LHASH *table);
void *lh_insert(LHASH *table, void *data);
void *lh_delete(LHASH *table, void *data);
void *lh_retrieve(LHASH *table, void *data);
void lh_doall(LHASH *table, LHASH_DOALL_FN_TYPE func);
void lh_doall_arg(LHASH *table, LHASH_DOALL_ARG_FN_TYPE func, void *arg);
int lh_error(LHASH *table);
typedef int (*LHASH_COMP_FN_TYPE)(const void *, const void *);
typedef unsigned long (*LHASH_HASH_FN_TYPE)(const void *);
typedef void (*LHASH_DOALL_FN_TYPE)(const void *);
typedef void (*LHASH_DOALL_ARG_FN_TYPE)(const void *, const void *);

Detailed Description

This library implements dynamic hash tables. The hash table entries can be arbitrary structures. Usually they consist of key and value fields.

lh_new() creates a new LHASH structure to store arbitrary data entries, and provides the 'hash' and 'compare' callbacks to be used in organising the table's entries. The hash callback takes a pointer to a table entry as its argument and returns an unsigned long hash value for its key field. The hash value is normally truncated to a power of 2, so make sure that the hash function returns well mixed low order bits. The compare callback takes two arguments (pointers to two hash table entries), and returns 0 if their keys are equal, non-zero otherwise. If the hash table contains items of some particular type and the hash and compare callbacks hash/compare these types, then the DECLARE_LHASH_HASH_FN and IMPLEMENT_LHASH_COMP_FN macros can be used to create callback wrappers of the prototypes required by lh_new(). These provide per-variable casts before calling the type-specific callbacks written by the application author. These macros, as well as those used for the ``doall'' callbacks, are defined as;

 #define DECLARE_LHASH_HASH_FN(f_name,o_type) \
         unsigned long f_name##_LHASH_HASH(const void *);
 #define IMPLEMENT_LHASH_HASH_FN(f_name,o_type) \
         unsigned long f_name##_LHASH_HASH(const void *arg) { \
                 o_type a = (o_type)arg; \
                 return f_name(a); }
 #define LHASH_HASH_FN(f_name) f_name##_LHASH_HASH
 #define DECLARE_LHASH_COMP_FN(f_name,o_type) \
         int f_name##_LHASH_COMP(const void *, const void *);
 #define IMPLEMENT_LHASH_COMP_FN(f_name,o_type) \
         int f_name##_LHASH_COMP(const void *arg1, const void *arg2) { \
                 o_type a = (o_type)arg1; \
                 o_type b = (o_type)arg2; \
                 return f_name(a,b); }
 #define LHASH_COMP_FN(f_name) f_name##_LHASH_COMP
 #define DECLARE_LHASH_DOALL_FN(f_name,o_type) \
         void f_name##_LHASH_DOALL(const void *);
 #define IMPLEMENT_LHASH_DOALL_FN(f_name,o_type) \
         void f_name##_LHASH_DOALL(const void *arg) { \
                 o_type a = (o_type)arg; \
                 f_name(a); }
 #define LHASH_DOALL_FN(f_name) f_name##_LHASH_DOALL
 #define DECLARE_LHASH_DOALL_ARG_FN(f_name,o_type,a_type) \
         void f_name##_LHASH_DOALL_ARG(const void *, const void *);
 #define IMPLEMENT_LHASH_DOALL_ARG_FN(f_name,o_type,a_type) \
         void f_name##_LHASH_DOALL_ARG(const void *arg1, const void *arg2) { \
                 o_type a = (o_type)arg1; \
                 a_type b = (a_type)arg2; \
                 f_name(a,b); }
 #define LHASH_DOALL_ARG_FN(f_name) f_name##_LHASH_DOALL_ARG

An example of a hash table storing (pointers to) structures of type 'STUFF' could be defined as follows;

 /* Calculates the hash value of 'tohash' (implemented elsewhere) */
 unsigned long STUFF_hash(const STUFF *tohash);
 /* Orders 'arg1' and 'arg2' (implemented elsewhere) */
 int STUFF_cmp(const STUFF *arg1, const STUFF *arg2);
 /* Create the type-safe wrapper functions for use in the LHASH internals */
 static IMPLEMENT_LHASH_HASH_FN(STUFF_hash, const STUFF *)
 static IMPLEMENT_LHASH_COMP_FN(STUFF_cmp, const STUFF *);
 /* ... */
 int main(int argc, char *argv[]) {
         /* Create the new hash table using the hash/compare wrappers */
         LHASH *hashtable = lh_new(LHASH_HASH_FN(STUFF_hash),
                                   LHASH_COMP_FN(STUFF_cmp));
         /* ... */
 }

lh_free() frees the LHASH structure table. Allocated hash table entries will not be freed; consider using lh_doall() to deallocate any remaining entries in the hash table (see below).

lh_insert() inserts the structure pointed to by data into table. If there already is an entry with the same key, the old value is replaced. Note that lh_insert() stores pointers, the data are not copied.

lh_delete() deletes an entry from table.

lh_retrieve() looks up an entry in table. Normally, data is a structure with the key field(s) set; the function will return a pointer to a fully populated structure.

lh_doall() will, for every entry in the hash table, call func with the data item as its parameter. For lh_doall() and lh_doall_arg(), function pointer casting should be avoided in the callbacks (see NOTE) - instead, either declare the callbacks to match the prototype required in lh_new() or use the declare/implement macros to create type-safe wrappers that cast variables prior to calling the type-specific callbacks. An example of this is illustrated here where the callback is used to cleanup resources for items in the hash table prior to the hashtable itself being deallocated:

 /* Cleans up resources belonging to 'a' (this is implemented elsewhere) */
 void STUFF_cleanup(STUFF *a);
 /* Implement a prototype-compatible wrapper for "STUFF_cleanup" */
 IMPLEMENT_LHASH_DOALL_FN(STUFF_cleanup, STUFF *)
         /* ... then later in the code ... */
 /* So to run "STUFF_cleanup" against all items in a hash table ... */
 lh_doall(hashtable, LHASH_DOALL_FN(STUFF_cleanup));
 /* Then the hash table itself can be deallocated */
 lh_free(hashtable);

When doing this, be careful not to delete entries from the hash table in the callbacks: the table may decrease in size, moving the current item down lower in the hash table - this could cause some entries to be skipped during the iteration. The second best solution to this problem is to set hash->down_load=0 before starting (which will stop the hash table ever decreasing in size). The best solution is probably to avoid deleting items from the hash table inside a ``doall'' callback!

lh_doall_arg() is the same as lh_doall() except that func will be called with arg as the second argument and func should be of type LHASH_DOALL_ARG_FN_TYPE (a callback prototype that is passed both the table entry and an extra argument). As with lh_doall(), choose to declare the callback with a prototype matching the types dealt with and use the declare/implement macros to create compatible wrappers that cast variables before calling the type-specific callbacks. An example of this is demonstrated here (printing all hash table entries to a BIO that is provided by the caller):

 /* Prints item 'a' to 'output_bio' (this is implemented elsewhere) */
 void STUFF_print(const STUFF *a, BIO *output_bio);
 /* Implement a prototype-compatible wrapper for "STUFF_print" */
 static IMPLEMENT_LHASH_DOALL_ARG_FN(STUFF_print, const STUFF *, BIO *)
         /* ... then later in the code ... */
 /* Print out the entire hashtable to a particular BIO */
 lh_doall_arg(hashtable, LHASH_DOALL_ARG_FN(STUFF_print), logging_bio);

lh_error() can be used to determine if an error occurred in the last
operation. lh_error() is a macro.

Return Values

lh_new() returns NULL on error, otherwise a pointer to the new LHASH structure.

When a hash table entry is replaced, lh_insert() returns the value being replaced. NULL is returned on normal operation and on error.

lh_delete() returns the entry being deleted. NULL is returned if there is no such value in the hash table.

lh_retrieve() returns the hash table entry if it has been found, NULL otherwise.

lh_error() returns 1 if an error occurred in the last operation, 0 otherwise.

lh_free(), lh_doall() and lh_doall_arg() return no values.

Notes

The various LHASH macros and callback types exist to make it possible to write type-safe code without resorting to function-prototype casting - an evil that makes application code much harder to audit/verify and also opens the window of opportunity for stack corruption and other hard-to-find bugs. It also, apparently, violates ANSI-C.

The LHASH code regards table entries as constant data. As such, it internally represents lh_insert()'d items with a ``const void *'' pointer type. This is why callbacks such as those used by lh_doall() and lh_doall_arg() declare their prototypes with ``const'', even for the parameters that pass back the table items' data pointers - for consistency, user-provided data is ``const'' at all times as far as the LHASH code is concerned. However, as callers are themselves providing these pointers, they can choose whether they too should be treating all such parameters as constant.

As an example, a hash table may be maintained by code that, for reasons of encapsulation, has only ``const'' access to the data being indexed in the hash table (i.e. it is returned as ``const'' from elsewhere in their code) - in this case the LHASH prototypes are appropriate as-is. Conversely, if the caller is responsible for the life-time of the data in question, then they may well wish to make modifications to table item passed back in the lh_doall() or lh_doall_arg() callbacks (see the ``STUFF_cleanup'' example above). If so, the caller can either cast the ``const'' away (if they're providing the raw callbacks themselves) or use the macros to declare/implement the wrapper functions without ``const'' types.

Callers that only have ``const'' access to data they're indexing in a table, yet declare callbacks without constant types (or cast the ``const'' away themselves), are therefore creating their own risks/bugs without being encouraged to do so by the API. On a related note, those auditing code should pay special attention to any instances of DECLARE/IMPLEMENT_LHASH_DOALL_[ARG_]_FN macros that provide types without any ``const'' qualifiers.

Bugs

lh_insert() returns NULL both for success and error.

Internals

The following description is based on the SSLeay documentation:

The lhash library implements a hash table described in the Communications of the ACM in 1991. What makes this hash table different is that as the table fills, the hash table is increased (or decreased) in size via OPENSSL_realloc(). When a 'resize' is done, instead of all hashes being redistributed over twice as many 'buckets', one bucket is split. So when an 'expand' is done, there is only a minimal cost to redistribute some values. Subsequent inserts will cause more single 'bucket' redistributions but there will never be a sudden large cost due to redistributing all the 'buckets'.

The state for a particular hash table is kept in the LHASH structure. The decision to increase or decrease the hash table size is made depending on the 'load' of the hash table. The load is the number of items in the hash table divided by the size of the hash table. The default values are as follows. If (hash->up_load < load) => expand. if (hash->down_load > load) => contract. The up_load has a default value of 1 and down_load has a default value of 2. These numbers can be modified by the application by just playing with the up_load and down_load variables. The 'load' is kept in a form which is multiplied by 256. So hash->up_load=8*256; will cause a load of 8 to be set.

If interested in performance the field to watch is num_comp_calls. The hash library keeps track of the 'hash' value for each item so when a lookup is done, the 'hashes' are compared, if there is a match, then a full compare is done, and hash->num_comp_calls is incremented. If num_comp_calls is not equal to num_delete plus num_retrieve it means that the hash function is generating hashes that are the same for different values. It is probably worth changing the hash function if this is the case because even if the hash table has 10 items in a 'bucket', it can be searched with 10 unsigned long compares and 10 linked list traverses. This will be much less expensive than 10 calls to the compare function.

lh_strhash() is a demo string hashing function:

 unsigned long lh_strhash(const char *c);

Since the LHASH routines would normally be passed structures, this routine would not normally be passed to lh_new(), rather it would be used in the function passed to lh_new().

See Also

lh_stats()

History

The lhash library is available in all versions of SSLeay and OpenSSL. lh_error() was added in SSLeay 0.9.1b.

This manpage is derived from the SSLeay documentation.

In OpenSSL 0.9.7, all lhash functions that were passed function pointers were changed for better type safety, and the function types LHASH_COMP_FN_TYPE, LHASH_HASH_FN_TYPE, LHASH_DOALL_FN_TYPE and LHASH_DOALL_ARG_FN_TYPE became available.

Feedback

For additional information or queries on this page send feedback


link

Name

link - makes a new name for a file

Library

 libc.lib

Synopsis
#include <unistd.h>
int link (const char *name1, const char *name2);

Return values

 Upon successful completion, 0 shall be returned. Otherwise, -1 shall be returned and errno set to indicate the error.

Detailed description

 The link system call atomically creates the specified directory entry (hard link) name2 with the attributes of the underlying object pointed at by name1. If the link is successful: it is expected the link count of the underlying object to be incremented but since link as a functionality is simulated and not supported by the platform, the underlying object is not aware of a existing link; name1 and name2 share equal access and rights to the underlying object. Link is supported only on regular files, fifos and not on directories. Creation of link on a existing link file is not supported.

If name1 is removed, the file name2 is also deleted as the platform recognizes the underlying object only by name1.

The object pointed at by the name1 argument must exist for the hard link to succeed and both name1 and name2 must be in the same file system. The name1 argument may not be a directory. Creation time stamp of the file is not supported, accesstime stamp is equal to modification time stamp. Newly created file will not alter the time stamp of parent directory.

Examples

/*
* Detailed description  : Example to create link to a file
* Precondition : "Parent.txt" should exist in c: drive
*
*/
#include <unistd.h>
#include <stdio.h>
int main(void)
 {
    if(link("C:\\Parent.txt","C:\\Link") < 0)
    {
         printf("Link creation to parent file failed\n");
         return -1;
    }
    printf("Link to parent file created");
    return 0;
 }

Output

Link to parent file created.

Errors

 The link system call will fail and no link will be created if:
[ENOENT]
 | A component of either path prefix does not exist.
[ENOENT]
 | A relative path was encountered in translating name2 and is not supported by the platform.
[ENAMETOOLONG]
 | A component or an entire path name exceeded 255 characters.
[ENOENT]
 | A relative path was encountered in translating name1 and is not supported by the platform.
[ENOENT]
 | An empty path was encountered in translating one of the pathnames.
[ELOOP]
 | Too many symbolic links were encountered in translating one of the pathnames.
[ELOOP]
 | name2 itself is a link type file.
[ENOENT]
 | The file named by name1 does not exist.
[EEXIST]
 | The link named by name2 does exist.
[EMLINK]
 | This is not supported as link is a simulated functionality.

See also

 readlink, symlink, unlink

Feedback

For additional information or queries on this page send feedback


listen

Name

listen - listens for connections on a socket

Library

 libc.lib

Synopsis
#include <sys/socket.h>
int listen (int s, int backlog);

Return values

 The listen() function returns the value 0 if successful; otherwise the value -1 is returned and the global variable errno is set to indicate the error.

Detailed description

 To accept connections, a socket is first created with socket, a willingness to accept incoming connections and a queue limit for incoming connections are specified with listen, and then the connections are accepted with accept. The listen system call applies only to sockets of type SOCK_STREAM or SOCK_SEQPACKET.

The backlog argument defines the maximum length the queue of pending connections may grow to. The real maximum queue length will be 1.5 times more than the value specified in the backlog argument. A subsequent listen system call on the listening socket allows the caller to change the maximum queue length using a new backlog argument. If a connection request arrives with the queue full the client may receive an error with an indication of ECONNREFUSED, or, in the case of TCP, the connection will be silently dropped.

Note that before BSD 4.5 and the introduction of the syncache, the backlog argument also determined the length of the incomplete connection queue, which held TCP sockets in the process of completing TCP’s 3-way handshake. These incomplete connections are now held entirely in the syncache, which is unaffected by queue lengths. Inflated backlog values to help handle denial of service attacks are no longer necessary.

Examples

#include <sys/socket.h>
#include <netinet/in.h>
#include <unistd.h>
void listen_example()
{
   int sock_fd;
   int newsock_fd;
   struct sockaddr_in addr;
   struct sockaddr_in ss;
   struct sockaddr_in new_socket;
   unsigned int len;
   unsigned int addr_len;

   sock_fd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);

   addr.sin_family = AF_INET;
   addr.sin_addr.s_addr = htonl(INADDR_ANY);
   addr.sin_port = htons(5000);
   bind(sock_fd,(struct sockaddr*)&addr,sizeof(addr));
   listen(sock_fd,1);
   close(sock_fd);
}

Errors

 The listen system call will fail if:
[EBADF]
 | The argument s is not a valid descriptor.
[EINVAL]
 | The socket is already connected, or in the process of being connected.
[ENOTSOCK]
 | The argument s is not a socket.
[EOPNOTSUPP]
 | The socket is not of a type that supports the operation listen.

See also

 accept, connect, socket,
The listen system call appeared in BSD 4.2. The ability to configure the maximum backlog at run-time, and to use a negative backlog to request the maximum allowable value, was introduced in 2.2.

Feedback

For additional information or queries on this page send feedback


llabs

Name

llabs - computes the absolute value of an integer

Library

 libc.lib

Synopsis
#include <stdlib.h>
long long llabs (long long j);

Return values

 The llabs function returns the absolue value.

Detailed description

 The llabs function returns the absolute value of j.

Examples

#include  <stdio.h>
#include  <stdlib.h>

int main( void )
{
   int    ix = -4, iy;
   long   lx = -41567L, ly;
   long long llx = -5343546758, lly;

   iy = abs( ix );
   printf( "The abs value of %d is %d\n", ix, iy);

   ly = labs( lx );
   printf( "The abs value of %ld is %ld\n", lx, ly);

   lly = llabs( llx );
   printf( "The abs value of %lld is %lld\n", llx, lly );

   return 0;
}

Output

The absolute value of -4 is 4
The absolute value of -41567 is 41567
The absolute value of -5343546758 is 5343546758

Errors

 No errors are defined.

See also

 abs, fabs, hypot, labs, math

Feedback

For additional information or queries on this page send feedback


lldiv

Name

lldiv - computes quotient and remainder of an integer division

Library

 libc.lib

Synopsis
#include <stdlib.h>
lldiv_t lldiv (long long numer, long long denom);
Sh RETURN VALUES The lldiv function returns a structure of type lldiv_t that contains two long long members named quot (quotient) and rem (remainder).

Detailed description

 The lldiv function computes the value of numer divided by denom and returns the stored result in the form of the lldiv_t type.

The lldiv_t type is defined as:

typedef struct {
        long long quot; /* Quotient. */
        long long rem;  /* Remainder. */
} lldiv_t;

Examples

#include <stdlib.h>
#include <stdio.h>
#include <math.h> /* link to the math lib -libm */

int main( void )
{
 long long numer = pow(2, 40);
 long long denom = 3;

 /* call to lldiv */
 lldiv_t x = lldiv(-numer, denom);

 printf("Result-> \nQuotient = %ld \nRemainder = %ld", x.quot, x.rem);

 long long exp_numer = (denom * x.quot) + x.rem;

 if( exp_numer == (-numer) )
    printf("\nExpected output");
 else
    printf("Unexpected output");

 return 0;
}

Output

Result->
Quotient = -366503875925
Remainder = -1
Expected output

See also

 div, ldiv, math

Feedback

For additional information or queries on this page send feedback


localeconv

Name

localeconv -gets numeric formatting information

Library

 libc.lib

Synopsis
#include <locale.h>
struct lconv * localeconv (void);

Return values

 The localeconv function returns a pointer to a static object which may be altered by later calls to setlocale or localeconv.

Detailed description

 The localeconv function returns a pointer to a structure which provides parameters 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;
        char    int_p_cs_precedes;
        char    int_n_cs_precedes;
        char    int_p_sep_by_space;
        char    int_n_sep_by_space;
        char    int_p_sign_posn;
        char    int_n_sign_posn;
};

The individual fields have the following meanings:

decimal_point | The decimal point character, except for currency values, cannot be an empty string.
thousands_sep | The separator between groups of digits before the decimal point, except for currency values.
grouping | The sizes of the groups of digits, except for currency values.
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 currency values, usually the empty string.
negative_sign | The character used to denote negative currency values, usually a minus sign.
int_frac_digits | The number of digits after the decimal point in an international-style currency value.
frac_digits | The number of digits after the decimal point in the local style for currency values.
p_cs_precedes | 1 if the currency symbol precedes the currency value for nonnegative values, 0 if it follows.
p_sep_by_space | 1 if a space is inserted between the currency symbol 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 a nonnegative 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 values.
int_p_cs_precedes
 | Same as p_cs_precedes, but for internationally formatted monetary quantities.
int_n_cs_precedes
 | Same as n_cs_precedes, but for internationally formatted monetary quantities.
int_p_sep_by_space
 | Same as p_sep_by_space, but for internationally formatted monetary quantities.
int_n_sep_by_space
 | Same as n_sep_by_space, but for internationally formatted monetary quantities.
int_p_sign_posn
 | Same as p_sign_posn, but for internationally formatted monetary quantities.
int_n_sign_posn
 | Same as n_sign_posn, but for internationally formatted monetary quantities.

Unless mentioned above, an empty string as a value for a field indicates a zero length result or a value that is not in the current locale. A CHAR_MAX result similarly denotes an unavailable value.

Examples

#include<stdio.h>
#include<locale.h>
int main()
{
        //Set the locale to German
        char* locale = setlocale(LC_ALL,"de_DE.ISO-8859-1");
        struct lconv* str = NULL;
        //Check whether locale setting is succesful or not
        if(NULL != locale)
        {
              printf("Locale setting is successful\n");
              printf("Locale is set to %s\n", locale);
              //Get numeric formatting information
              str = localeconv();
              printf("Decimal separator is %s\n", str->mon_decimal_point);
              printf("Thousand separator is %s\n", str->mon_thousands_sep);
        }
        else
        {
              printf("Locale setting failed\n");
        }
        return 0;
}

Output

Locale setting is successful
Locale is set to de_DE.ISO-8859-1
Decimal separator is,
Thousand separator is.

Errors

 No errors are defined.

See also

 setlocale, strfmon

Feedback

For additional information or queries on this page send feedback


lrint

Name

llrint, llrintf, llrintl, lrint, lrintf, lrintl
- round to nearest integer

Library

 libm.lib

Synopsis
#include <math.h>
long long llrint (double x);
long long llrintf (float x);
long long llrintl (long double x);
long lrint (double x);
long lrintf (float x);
long lrintl (long double x);

Return values

Detailed description

 The lrint function returns the integer nearest to its argument x according to the current rounding mode. When the rounded result is representable as a long , the expression

The llrint, llrintf and lrintf functions differ from lrint only in their input and output types. lrintf and llrintl is just an aliases to the functions lrint (and);
llrint respectively

Examples

#include <math.h>
int main( void )
{
   double x1 = 1.4;
   long long y;
   int res ;
   y = llrint( x1 );
   printf( "llrint(%f) = %d\n", x1, y );
   y = llrintf( x1 );
   printf( "llrintf(%f) = %d\n", x1, y );
   y = llrintl( x1 );
   printf( "llrintl(%f) = %d\n", x1, y );
   res = lrint( x1 );
   printf( "lrint(%f) = %d\n", x1, res );
   res = lrintf( x1 );
   printf( "lrintf(%f) = %d\n", x1, res );
   res = lrintl( x1 );
   printf( "lrintl(%f) = %d\n", x1, res );
}

Output

llrint ( 1.4 ) = 1.000000
llrintf( 1.4 ) = 1.000000
llrintl( 1.4 ) = 1.000000
lrint ( 1.4 ) = 1.000000
lrintf( 1.4 ) = 1.000000
lrintl( 0.0 ) = 1.000000

See also

 lround, math, rint, round

Feedback

For additional information or queries on this page send feedback


lround

Name

llround, llroundf, llroundl, lround, lroundf, lroundl
- round to nearest integer

Library

 libm.lib

Synopsis
#include <math.h>
long long llround (double x);
long long llroundf (float x);
long long llroundl (long double x);
long lround (double x);
long lroundf (float x);
long lroundl (long double x);

Return values

Detailed description

 The lround function returns the integer nearest to its argument x, rounding away from zero in halfway cases. If the rounded result is too large to be represented as a long value, the return value is undefined. When the rounded result is representable as a long , the expression lround (x);
is equivalent to round (x);(long) (although the former may be more efficient).

The llround, llroundf, llroundl, lroundf and lroundl functions differ from lround only in their input and output types.

Examples

#include <math.h>
int main( void )
{
   double x1 = 1.5;
   long long y;
   int res ;
   y = llround( x1 );
   printf( "llround(%f) = %d\n", x1, y );
   y = llroundf( x1 );
   printf( "llroundf(%f) = %d\n", x1, y );
   y = llroundl( x1 );
   printf( "llroundl(%f) = %d\n\n", x1, y );
   res = lround( x1 );
   printf( "lround(%f) = %d\n", x1, res );
   res = lroundf( x1 );
   printf( "lroundf(%f) = %d\n", x1, res );
   res = lroundl( x1 );
   printf( "lroundl(%f) = %d\n", x1, res );
}

Output

llround ( 1.5 ) = 2.000000
llroundf( 1.5 ) = 2.000000
llroundl( 1.5 ) = 2.000000
lround ( 1.5 ) = 2.000000
lroundf( 1.5 ) = 2.000000
lroundl( 1.5 ) = 2.000000

See also

 lrint, math, rint, round

Feedback

For additional information or queries on this page send feedback


lseek

Name

lseek - repositions read/write file offset

Library

 libc.lib

Synopsis
#include <unistd.h>
off_t lseek (int fildes, off_t offset, int whence);

Return values

 Upon successful completion, lseek returns the resulting offset location as measured in bytes from the beginning of the file. Otherwise, a value of -1 is returned and errno is set to indicate the error.

Detailed description

 The lseek system call repositions the offset of the file descriptor fildes to the argument offset according to the directive whence. The argument fildes must be an open file descriptor. The lseek system call repositions the file position pointer associated with the file descriptor 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.
Some devices are incapable of seeking. The value of the pointer associated with such a device is undefined.

Note : The lseek function allows the file offset to be set beyond the existing end-of-file however, the subsequent read
operation fails returning -1. This is posix compliant behaviour.

Examples

/**
  * Detailed description  : Example for lseek usage.
**/
#include <stdio.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/types.h>
int main()
{
int fd = 0;
 fd = open("lseek.txt"  , O_CREAT | O_RDWR , 0666);
  if(lseek(fd , 0 , SEEK_SET) < 0 ) {
     printf("Lseek on file lseek.txt failed \n");
      return -1;
  }
  printf("Lseek on lseek.txt passed ");
 return 0;
}

Output

Lseek on lseek.txt passed

Errors

 The lseek system call will fail and the file position pointer will remain unchanged if:
[EBADF]
 | The fildes argument is not an open file descriptor.
[EINVAL]
 | The whence argument is not a proper value or the resulting file offset would be negative for a non-character special file.
[EOVERFLOW]
 | The resulting file offset would be a value which cannot be represented correctly in an object of type off_t(Not supported).
[ESPIPE]
 | The fildes argument is associated with a pipe, socket, or FIFO.

See also

 dup, open

Feedback

For additional information or queries on this page send feedback


S60 3rd Edition API Reference: Main Page

S60 Open C
API Reference Guide and Developer Guides

S60 3rd Edition API Reference Documentation

  • Main Page
  • Files
  • Directories

© Nokia 2007

Back to top


malloc

Name

malloc, calloc, realloc, free, reallocf
- Allocate and free dynamic memory

Library

 libc.lib

Synopsis
#include <stdlib.h>
void * malloc (size_t size);
void * calloc (size_t number, size_t size);
void * realloc (void *ptr, size_t size);
void * reallocf (void *ptr, size_t size);
void free (void *ptr);

Return values

 The malloc and calloc functions return a pointer to the allocated memory if successful; otherwise a NULL pointer is returned and errno is set to ENOMEM.

The realloc and reallocf functions return a pointer, possibly identical to ptr, to the allocated memory if successful; otherwise a NULL pointer is returned, and errno is set to ENOMEM if the error was the result of an allocation failure. The realloc function always leaves the original buffer intact when an error occurs, whereas reallocf deallocates it in this case.

The free function returns no value.

Detailed description

 The malloc function allocates size bytes of memory. The allocated space is suitably aligned (after possible pointer coercion) for storage of any type of object. If the space is at least pagesize bytes in length (see getpagesize the returned memory will be page boundary aligned as well. If malloc fails, a NULL pointer is returned.

Note that malloc does NOT normally initialize the returned memory to zero bytes.

The calloc function allocates space for number objects, each size bytes in length. The result is identical to calling malloc with an argument of "number * size", with the exception that the allocated memory is explicitly initialized to zero bytes.

The realloc function changes the size of the previously allocated memory referenced by ptr to size bytes. The contents of the memory are unchanged up to the lesser of the new and old sizes. If the new size is larger, the value of the newly allocated portion of the memory is undefined. If the requested memory cannot be allocated, NULL is returned and the memory referenced by ptr is valid and unchanged. If memory can be allocated, the memory referenced by ptr is freed and a pointer to the newly allocated memory is returned. Note that realloc and reallocf may move the memory allocation resulting in a different return value than ptr. If ptr is NULL, the realloc function behaves identically to malloc for the specified size.

The reallocf function is identical to the realloc function, except that it will free the passed pointer when the requested memory cannot be allocated. This is a
specific API designed to ease the problems with traditional coding styles for realloc causing memory leaks in libraries.

The free function causes the allocated memory referenced by ptr to be made available for future allocations. If ptr is NULL, no action occurs.

Examples

#include <stdlib.h>    //malloc
#include <stdio.h>    //printf

int main( void )
{
   /* allocate memory */
   char  *pc = (char *)malloc( sizeof(char) * 3);

   if( pc == NULL )
      printf( "memory insufficient\n" );
   else
   {
      printf( "memory allocated\n" );
      free( pc );
      printf( "memory freed\n" );
   }

   return 0;
}

Output

memory allocated
memory freed

#include <stdio.h> //printf
#include <stdlib.h> //calloc

int main( void )
{
   int  *pint = (int *)calloc(2, sizeof (int) * 2);
   if( pint != NULL )
      printf( "allocated 2 blocks of memory, each of size -
               twice the size of an integer\n" );
   else
      printf( "can’t allocate memory\n" );
   free( pint );

   return 0;
}

Output

allocated 2 blocks of memory, each of size - 2 integers

#include <stdio.h> //printf
#include <stdlib.h> //realloc

int main( void )
{
 int  *pint = (int *)calloc(2, sizeof (int) * 2);
 if (pint == NULL)
  {
  printf("calloc failed to allocate memory\n");
  return -1;
  }
 else
  {
  printf("calloc allocated memory: 128 bytes\n");
  }

 pint = (int *)realloc(pint, (sizeof (int) * 6) );
 if (pint == NULL)
  {
  printf("realloc failed to allocate memory\n");
  return -1;
  }
 else
  {
  printf("realloc allocated memory: 192 bytes\n");
  }

  free( pint );
  return 0;
}

Output

calloc allocated memory: 128 bytes
realloc allocated memory: 192 bytes

See also

 brk, mmap, getpagesize

Feedback

For additional information or queries on this page send feedback


math

Name

math
- floating-point mathematical library

Library

 libm.lib

Synopsis
#include <math.h>

Detailed description

 These functions constitute the C math library.

List of functions

 Each of the following double functions has a float counterpart with an ‘f’ appended to the name and a long double counterpart with an ‘l’ appended. As an example, the float and long double counterparts of
double acos (double x);
are
float acosf (float x);
and
long double acosl (long double x);
respectively.

Algebraic functions
Name Detailed description cbrt cube root fma fused multiply-add hypot Euclidean distance sqrt square root

Classification functions
Name Detailed description fpclassify classify a floating-point value isfinite determine whether a value is finite isinf determine whether a value is infinite isnan determine whether a value is NaN isnormal determine whether a value is normalized

Exponent manipulation functions
Name Detailed description frexp extract exponent and mantissa ilogb extract exponent ldexp multiply by power of 2 scalbln adjust exponent scalbn adjust exponent

Extremum- and sign-related functions
Name Detailed description copysign copy sign bit fabs absolute value fdim positive difference fmax maximum function fmin minimum function signbit extract sign bit

Residue and rounding functions
Name Detailed description ceil integer no less than floor integer no greater than fmod positive remainder llrint round to integer in fixed-point format llround round to nearest integer in fixed-point format lrint round to integer in fixed-point format lround round to nearest integer in fixed-point format modf extract integer and fractional parts nearbyint round to integer (silent) nextafter next representable value nexttoward next representable value remainder remainder remquo remainder with partial quotient rint round to integer round round to nearest integer trunc integer no greater in magnitude than

The ceil, floor, llround, lround, round, and trunc functions round in predetermined directions, whereas llrint, lrint, and rint round according to the current (dynamic) rounding mode. For more information on controlling the dynamic rounding mode, see fenv and fesetround.

Silent order predicates
Name Detailed description isgreater greater than relation isgreaterequal greater than or equal to relation isless less than relation islessequal less than or equal to relation islessgreater less than or greater than relation isunordered unordered relation

Transcendental functions
Name Detailed description acos inverse cosine acosh inverse hyperbolic cosine asin inverse sine asinh inverse hyperbolic sine atan inverse tangent atanh inverse hyperbolic tangent atan2 atan(y/x); complex argument cos cosine cosh hyperbolic cosine erf error function erfc complementary error function exp exponential base e exp2 exponential base 2 expm1 exp(x)-1 j0 Bessel function of the first kind of the order 0 j1 Bessel function of the first kind of the order 1 jn Bessel function of the first kind of the order n lgamma log gamma function log natural logarithm log10 logarithm to base 10 log1p log(1+x) pow exponential x**y sin trigonometric function sinh hyperbolic function tan trigonometric function tanh hyperbolic function tgamma gamma function y0 Bessel function of the second kind of the order 0 y1 Bessel function of the second kind of the order 1 yn Bessel function of the second kind of the order n

Unlike the algebraic functions listed earlier, the routines in this section may not produce a result that is correctly rounded, so reproducible results cannot be guaranteed across platforms. For most of these functions, however, incorrect rounding occurs rarely, and then only in very-close-to-halfway cases.

See also

 ieee

Bugs

 The log2 and nan functions are missing, and many functions are not available in their long double variants.

Many of the routines to compute transcendental functions produce inaccurate results in other than the default rounding mode.

On some architectures, trigonometric argument reduction is not performed accurately, resulting in errors greater than 1 ulp for large arguments to cos, sin, and tan.

Limitations

As there is no long double support in SYMBIAN OS, All long double version apis are just aliased to the double version of the apis. Long double Apis behaves similiar to that of their double counterparts.

In Symbian the Floating-Point operations are carried out with the help of a Floating-point emulator, It doesn’t support any hardware for floating point operations. So, the accuracy of the result is far from that of the accuracy obtained in a OS with a hardware floating-point unit.

Floating point exceptions are not supported, as there is no Hardware FP co-processor support in the current phone. If there is a hardware FP co-processor , it will be supported with ARM inline assembly code.

Complex number Apis are not supported in this library

Feedback

For additional information or queries on this page send feedback


mblen

Name

mblen - determines number of bytes in next multibyte character

Library

 libc.lib

Synopsis
#include <stdlib.h>
int mblen (const char *mbchar, size_t nbytes);

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 mbchar represents the null wide character, or returns the number of bytes processed in mbchar, or returns -1 if no multibyte character could be recognized or converted. In this case, mblen (Ns, ’s);
internal conversion state is undefined.

Detailed description

 The mblen function computes the length in bytes of a multibyte character mbchar according 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 shift states, zero otherwise; if shift states are required, the shift state is reset to the initial state.

The behavior of the mblen is affected by LC_CTYPE category of the current locale.

Examples

#include <stdlib.h>
#include <wchar.h>
/* Illustrates how to use mblen API */
int example_mblen(wchar_t wc)
{
 int len;

 /* determine the number bytes in the multibyte char */
 len = mblen(wc, MB_CUR_MAX);
 if(len == -1)
 {
        wprintf(L"mblen returned error!!\n");
 }
 /* return the no of bytes */
 return(len);
}

Errors

 The mblen function will fail if:
[EILSEQ]
 | An invalid multibyte sequence was detected.
[EINVAL]
 | The internal conversion state is not valid.

Limitations

 The current implementation of mblen is not affected by the LC_CTYPE category of the current locale. It works only for UTF8 character set.

See also

 mbrlen, mbtowc

Feedback

For additional information or queries on this page send feedback


mbrlen

Name

mbrlen - determines number of bytes in next multibyte character

Library

 libc.lib

Synopsis
#include <wchar.h>
size_t mbrlen (const char * restrict s, size_t n, mbstate_t * restrict ps);

Return values

 The mbrlen functions 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, mbrlen returns the number of bytes used to complete the multibyte character.
(size_t-2)
 | The next n contribute to, but do not complete, a valid multibyte character sequence, and all n bytes have been processed.
(size_t-1)
 | An encoding error has occurred. The next n or fewer bytes do not contribute to a valid multibyte character.

Detailed description

 The mbrlen function inspects at most n bytes pointed to by s to determine the number 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 initial conversion 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, internal mbstate_t object to keep track of the shift state. The behavior of the mbrlen is affected by LC_CTYPE category of the current locale.

Examples

 A function that calculates the number of characters in a multibyte character string:
size_t
nchars(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.

Limitations

 The current implementation of mbrlen is not affected by the LC_CTYPE category of the current locale. It works only for UTF8 character set.

See also

 mblen, mbrtowc

Feedback

For additional information or queries on this page send feedback


mbrtowc

Name

mbrtowc - converts a multibyte sequence to a wide character

Library

 libc.lib

Synopsis
#include <wchar.h>
size_t mbrtowc (wchar_t * restrict dst, const char * restrict src, size_t n, mbstate_t * restrict ps);

Return values

 The mbrtowc functions 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 character.
(size_t-2)
 | The next n contribute to, but do not complete, a valid multibyte character sequence, and all n bytes have been processed.
(size_t-1)
 | An encoding error has occurred. The next n or fewer bytes do not contribute to a valid multibyte character.

Detailed description

 The mbrtowc function inspects at most n bytes pointed to by s to determine the number of bytes needed to complete the next multibyte character. If a character can be completed, and pwc is not NULL, the wide character which is represented by s 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 the initial conversion state at program startup.

The behavior of the mbrtowc is affected by LC_CTYPE category of the current locale.

Examples

#include <stdio.h>
#include <stdlib.h>
#include <wchar.h>
/* Illustrates how to use mbrtowc API */
size_t example_mbrtowc()
{
 size_t len;
 wchar_t wc[100];
 char *s = ’a’;
 size_t n = 1;
 mbstate_t ps;
 /* converting multibyte sequence to a wide-char sequence */
 len = mbrtowc(wc,(const char *) s, n, &ps);
 /* checking for error value */
 if(len < 0)
 {
        wprintf(L"mbrtowc returned error!!\n");
 }
 /* returning no of bytes consumed */
 return (len);
}

Errors

 The mbrtowc function will fail if:
[EILSEQ]
 | An invalid multibyte sequence was detected.
[EINVAL]
 | The conversion state is invalid.

Limitations

 The current implementation of mbrtowc is not affected by the LC_CTYPE category of the current locale. It works only for UTF8 character set.

See also

 mbtowc, setlocale, wcrtomb

Feedback

For additional information or queries on this page send feedback


mbsinit

Name

mbsinit - tests for initial shift state

Library

 libc.lib

Synopsis
#include <wchar.h>
int mbsinit (const mbstate_t *ps);

Return values

 The mbsinit function returns non-zero if ps is NULL or describes an initial conversion state, otherwise it returns zero.

Detailed description

 The mbsinit function determines whether the mbstate_t object pointed to by ps describes an initial conversion state.

The behavior of the mbsinit is affected by LC_CTYPE category of the current locale.

Examples

#include <stdlib.h>
#include <wchar.h>
/* Illustrates how to use mbsinit API */
int example_mbsinit(void)
{
 mbstate_t mbs;
 int state;

 /* testing for the initial state */
 state = mbsinit(&mbs);
 /* return the state */
 return(state);
}

Limitations

 The current implementation of mbsinit is not affected by the LC_CTYPE category of the current locale. It works only for UTF8 character set.

See also

 mbrlen, mbrtowc, mbsrtowcs, wcrtomb, wcsrtombs

Feedback

For additional information or queries on this page send feedback


mbsrtowcs

Name

mbsrtowcs, mbsnrtowcs
- convert a multibyte string to a wide character string

Library

 libc.lib

Synopsis
#include <wchar.h>
size_t mbsrtowcs (wchar_t * restrict dst, const char ** restrict src, size_t len, mbstate_t * restrict ps);
size_t mbsnrtowcs (wchar_t * restrict dst, const char ** restrict src, size_t nms, size_t len, mbstate_t * restrict ps);

Return values

 The mbsrtowcs and mbsnrtowcs functions return the number of wide characters stored in the array pointed to by dst if successful, otherwise it returns (size_t-1.)

Detailed description

 The mbsrtowcs function converts a sequence of multibyte characters pointed to indirectly by src into a sequence of corresponding wide characters and stores at most len of them in the wchar_t array pointed to by dst, until it encounters a terminating null 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 character after the one that conversion stopped at. If conversion stops because a null character is 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 the initial conversion state at program startup.

The mbsnrtowcs function behaves identically to mbsrtowcs, except that conversion stops after reading at most nms bytes from the buffer pointed to by src.

The behavior of the mbsrtowcs and mbsnrtowcs is affected by LC_CTYPE category of the current locale.

Examples

/* Illustrates how to use mbsrtowcs API */
#include <stdio.h>
#include <stdlib.h>
#include <wchar.h>
size_t example_mbsrtowcs(wchar_t *wc, char *s, size_t n)
{
 size_t len;
 mbstate_t mbs;
 /* converting multibyte string to a wide-char string */
 len = mbsrtowcs(wc, &s, n, &mbs);
 /* checking for error */
 if(len < 0)
 {
        wprintf(L"mbsrtowcs returned error!!\n");
 }
 /* returning no of bytes consumed */
 return (len);
}

/* Illustrates how to use mbsrntowcs API */
#include <stdio.h>
#include <stdlib.h>
#include <wchar.h>
size_t example_mbsnrtowcs(wchar_t *wc, char *s, size_t n, size_t nms)
{
  size_t len;
  mbstate_t mbs;
 /* converting multibyte string to a wide-char string */
  len = mbsnrtowcs(wc, &s, nms, n, &mbs);
 /* checking for error */
 if(len < 0)
 {
        wprintf(L"mbsnrtowcs returned error!!\n");
 }
  /* returning no of bytes consumed */
  return (len);
}

Errors

 The mbsrtowcs and mbsnrtowcs functions will fail if:
[EILSEQ]
 | An invalid multibyte character sequence was encountered.
[EINVAL]
 | The conversion state is invalid.

Limitations

 The current implementation of mbsrtowcs and mbsnrtowcs is not affected by the LC_CTYPE category of the current locale. It works only for UTF8 character set.

See also

 mbrtowc, mbstowcs, wcsrtombs

Feedback

For additional information or queries on this page send feedback


mbstowcs

Name

mbstowcs - converts a multibyte string to a wide character string

Library

 libc.lib

Synopsis
#include <stdlib.h>
size_t mbstowcs (wchar_t * restrict dst, const char * restrict src, size_t nwchars);

Return values

 The mbstowcs function returns the number of wide characters converted, not counting any terminating null wide character, or -1 if an invalid multibyte character was encountered.

Detailed description

 The mbstowcs function converts a multibyte character string mbstring beginning in the initial conversion state into a wide character string wcstring. No more than nwchars wide characters are stored. A terminating null wide character is appended if there is room.

The behavior of the mbstowcs is affected by LC_CTYPE category of the current locale.

Examples

#include <stdio.h>
#include <stdlib.h>
#include <wchar.h>
/* Illustrates how to use mbstowcs API */
size_t example_mbstowcs(wchar_t *wc, char *s, size_t n)
{
 size_t len;
 /* converting multibyte string to a wide-char string */
 len = mbstowcs(wc, s, n);
 /* checking for error */
 if(len < 0)
 {
        wprintf(L"mbstowcs returned error!!\n");
 }
 /* returning no of bytes consumed */
 return (len);
}

Errors

 The mbstowcs function will fail if:
[EILSEQ]
 | An invalid multibyte sequence was detected.
[EINVAL]
 | The conversion state is invalid.

Limitations

 The current implementation of mbstowcs is not affected by the LC_CTYPE category of the current locale. It works only for UTF8 character set.

See also

 mbsrtowcs, mbtowc

Feedback

For additional information or queries on this page send feedback


mbtowc

Name

mbtowc - converts a multibyte sequence to a wide character

Library

 libc.lib

Synopsis
#include <stdlib.h>
int mbtowc (wchar_t * restrict dst, const char * restrict src, size_t nbytes);

Return values

 If mbchar is NULL, the mbtowc function returns nonzero if shift states are supported, zero otherwise.

Otherwise, if mbchar is not a null pointer, mbtowc either returns 0 if mbchar represents the null wide character, or returns the number of bytes processed in mbchar, or returns -1 if no multibyte character could be recognized or converted. In this case, mbtowc internal conversion state is undefined.

Detailed description

 The mbtowc function converts a multibyte character mbchar into a wide character according to the current conversion state, and stores the result in the object pointed to by wcharp. Up to nbytes bytes are examined.

A call with a null mbchar pointer returns nonzero if the current encoding requires shift states, zero otherwise; if shift states are required, the shift state is reset to the initial state.

The behavior of the mbtowc is affected by LC_CTYPE category of the current locale.

Examples

#include <stdlib.h>
#include <wchar.h>
/* Illustrates how to use mbtowc API */
int example_mbtowc(wchar_t *wc, char *s)
{
 int len;
 /* converting multibyte sequence to a wide-character */
 len = mbtowc(wc, s, MB_CUR_MAX);
 /* checking for error */
 if(len < 0)
 {
        wprintf(L"mbtowc returned error!!\n");
 }
 /* returning no of bytes consumed */
 return (len;);
}

Errors

 The mbtowc function will fail if:
[EILSEQ]
 | An invalid multibyte sequence was detected.
[EINVAL]
 | The internal conversion state is invalid.

Limitations

 The current implementation of mbtowc is not affected by the LC_CTYPE category of the current locale. It works only for UTF8 character set.

See also

 btowc, mblen, mbrtowc, mbstowcs, wctomb

Feedback

For additional information or queries on this page send feedback


MD5_Final - MD2, MD4, and MD5 hash functions

Name

MD2, MD5, MD2_Init
MD2_Update, MD2_Final, MD5_Init
MD5_Update, MD5_Final

Cryptographic hash functions with a 128 bit output

Library

libcrypto.lib

Synopsis

#include <openssl/md2.h>
unsigned char *MD2(const unsigned char *d, unsigned long n, unsigned char *md);
void MD2_Init(MD2_CTX *c);
void MD2_Update(MD2_CTX *c, const unsigned char *data, unsigned long len);
void MD2_Final(unsigned char *md, MD2_CTX *c);
#include <openssl/md5.h>
unsigned char *MD5(const unsigned char *d, unsigned long n, unsigned char *md);
void MD5_Init(MD5_CTX *c);
void MD5_Update(MD5_CTX *c, const void *data, unsigned long len);
void MD5_Final(unsigned char *md, MD5_CTX *c);

Detailed Description

MD2 and MD5 are cryptographic hash functions with a 128 bit output.

MD2() and MD5() compute the MD2, MD5 message digest of the n bytes at d and place it in md (which must have space for MD2_DIGEST_LENGTH == MD5_DIGEST_LENGTH == 16 bytes of output). If md is NULL, the digest is placed in a static array.

The following functions may be used if the message is not completely stored in memory:

MD2_Init() initializes a MD2_CTX structure.

MD2_Update() can be called repeatedly with chunks of the message to be hashed (len bytes at data).

MD2_Final() places the message digest in md, which must have space for MD2_DIGEST_LENGTH == 16 bytes of output, and erases the MD2_CTX.

MD5_Init(), MD5_Update(), and MD5_Final() are analogous using MD5_CTX structure.

Applications should use the higher level functions EVP_DigestInit() etc. instead of calling the hash functions directly.

Notes

MD2 and MD5 are recommended only for compatibility with existing applications. In new applications, SHA-1 should be preferred.

Return Values

MD2(), and MD5() return pointers to the hash value.

MD2_Init(), MD2_Update(), MD2_Final(), MD5_Init(), MD5_Update(), and MD5_Final() do not return values.

Conforming To

RFC 1319, RFC 1320, RFC 1321

See Also

sha(), EVP_DigestInit()

History

MD2(), MD2_Init(),  MD2_Update(),
MD2_Final(), MD5(), MD5_Init(),

MD5_Update() and
 MD5_Final() are available in all versions of SSLeay
and OpenSSL.

Feedback

For additional information or queries on this page send feedback


memccpy

Name

memccpy - copies memory area

Library

 libc.lib

Synopsis
#include <string.h>
void * memccpy (void *dst, const void *src, int c, size_t len);

Return values

memccpy function returns a pointer to the next character in dst after c, or NULL if c was not found in the first n characters of src

Detailed description

 The memccpy function copies bytes from string src to string dst. If the character c (as converted to an unsigned char) occurs in the string src, the copy stops and a pointer to the byte after the copy of c in the string dst is returned. Otherwise, len bytes are copied, and a NULL pointer is returned.

Examples

#include <string.h>
#include <stdio.h>
int main()
{
    char one[50] = {"\0"};
    (void) memccpy(one, "abcdefgh",8,3);
    printf("String after memcpy %s\n",one);
    (void) memccpy(one, "Hello",5,1);
    printf("String after memcpy %s\n",one);
    return 0;
}

Output

String after memcpy abc
String after memcpy Hbc

See also

 bcopy, memcpy, memmove, strcpy

Feedback

For additional information or queries on this page send feedback


memchr

Name

memchr - scans memory for a character

Library

 libc.lib

Synopsis
#include <string.h>
void * memchr (const void *b, int c, size_t len);

Return values

 The memchr function returns a pointer to the byte located, or NULL if no such byte exists within len bytes.

Detailed description

 The memchr function locates the first occurrence of c (converted to an unsigned char) in string b.

Examples

#include <string.h>
#include <stdio.h>
int main()
{
    char one[50];
    char* ret;
    strcpy(one,"abcd");
    ret = memchr("abcd", ’c’,4);
    if(!strncmp(one+2,ret,1)) printf("\ ’c\ ’ found in string \"abcd\"\n");
    ret = memchr(one, ’z’,4);
    if(ret == NULL) printf("\ ’z\ ’ not found in string \"abcd\"\n");
    return 0;
}

Output

 ’c’ found in string "abcd"
 ’z’ not found in string "abcd"

See also

 strchr, strcspn, strpbrk, strsep, strstr, strtok

Feedback

For additional information or queries on this page send feedback


memcmp

Name

memcmp - compares memory areas

Library

 libc.lib

Synopsis
#include <string.h>
int memcmp (const void *b1, const void *b2, size_t len);

Return values

 The memcmp function returns zero if the two strings are identical, otherwise returns the difference between the first two differing bytes (treated as unsigned char values, so that '\200' is greater than '\0,' for example). Zero-length strings are always identical.

Detailed description

 The memcmp function compares byte string b1 against byte string b2. Both strings are assumed to be len bytes long.

Examples

#include <string.h>
#include <stdio.h>
int main()
{
   char str1[]  = "abcdefg";
   char str2[] =  "abcdefr";
   int result;
   printf( "Compare ’%.6s’ to ’%.6s\n", str1, str2 );
   result = memcmp( str1, str2, 6);
   if( result < 0 )
      printf( "str1 is less than str2.\n" );
   else if( result == 0 )
      printf( "str1 is equal to str2.\n" );
   else if( result > 0 )
      printf( "str1 is greater than str2.\n" );
   printf( "Compare ’%.7s’ to ’%.7s\n", str1, str2 );
   result = memcmp( str1, str2, 7 );
   if( result < 0 )
      printf( "str1 is less than str2.\n" );
   else if( result == 0 )
      printf( "str1 is equal to str2.\n" );
   else if( result > 0 )
      printf( "str1 is greater than str2.\n" );
   return 0;
}

Output

Compare ’abcdef’ to ’abcdef
str1 is equal to str2.
Compare ’abcdefg’ to ’abcdefr
str1 is less than str2.

See also

 bcmp, strcasecmp, strcmp, strcoll, strxfrm

Feedback

For additional information or queries on this page send feedback


memcpy

Name

memcpy - copies memory area

Library

 libc.lib

Synopsis
#include <string.h>
void * memcpy (void *dst, const void *src, size_t len);

Return values

 The memcpy function returns the original value of dst.

Detailed description

 The memcpy function copies len bytes from string src to string dst.

Examples

#include <string.h>
#include <stdio.h>
int main()
{
    char one[50] = {"\0"};
    (void) memcpy(one, "abcdefgh",8);
    printf("String after memcpy %s\n",one);
    (void) memcpy(one, "Hello",5);
    printf("String after memcpy %s\n",one);
    return 0;
}

Output

String after memcpy abcdefgh
String after memcpy Hellofgh

See also

 bcopy, memccpy, memmove, strcpy

Feedback

For additional information or queries on this page send feedback


memmove

Name

memmove - copies memory area

Library

 libc.lib

Synopsis
#include <string.h>
void * memmove (void *dst, const void *src, size_t len);

Detailed description

 The memmove function copies len bytes from string src to string dst. The two strings may overlap; the copy is always done in a non-destructive manner.

Examples

#include <string.h>
#include <stdio.h>
int main()
{
    char one[50];
    (void) strcpy(one, "abcdefgh");
    printf("String before memmove %s\n",one);
    (void) memmove(one+1, "xyz", 2);
    printf("String after memmove %s\n",one);
    (void) strcpy(one, "abcdefgh");
    printf("String before memmove %s\n",one);
    (void) memmove(one+1, "xyz", 0);
    printf("String after memmove %s\n",one);
    return 0;
}

Output

String before memmove abcdefgh
String after memmove axydefgh
String before memmove abcdefgh
String after memmove abcdefgh

Return value

 The memmove function returns pointer to dst dst.

See also

 bcopy, memcpy, strcpy

Feedback

For additional information or queries on this page send feedback


memset

Name

memset - fills memory with a constant byte

Library

 libc.lib

Synopsis
#include <string.h>
void * memset (void *b, int c, size_t len);

Detailed description

 The memset function writes len bytes of value c (converted to an unsigned char) to the string b.

Examples

#include <string.h>
#include <stdio.h>
int main()
{
    char one[50];
    strcpy(one, "abcdefgh");
    printf("String before memset %s\n",one);
    memset(one+1, 'x', 3);
    printf("String after calling memset first time %s\n",one);
    memset(one+2, 'y', 0);
    printf("String after calling memset second time %s\n",one);
    return 0;
}

Output

String before memset abcdefgh
String after calling memset first time axxxefgh
String after calling memset second time axxxefgh

Return value

 The memset function returns its first argument.

See also

 bzero, swab

Feedback

For additional information or queries on this page send feedback


mkdir

Name

mkdir - creates a directory

Library

 libc.lib

Synopsis
#include <sys/types.h>
#include <sys/stat.h>
int mkdir (const char *path, mode_t mode);

Return values

 The mkdir() function returns the value 0 if successful; otherwise the value -1 is returned and the global variable errno is set to indicate the error.

Detailed description

 The directory path is created with the access permissions specified by mode.

Note: mode values will be ignored while directory creation.Default working directory of a process is initialized to C:\private\UID (UID of the calling application), and any data written into this C:\private\UID directory persists between phone resets.

Limitation: Parent directory time stamps will not be updated with new directory creation, created directory will be empty(i.e., it doesn’t have "." and ".." entries)

Examples

/**
*  Detailed description : This test code demonstrates usage of mkdir systemcall, it creates function
*  a  directory Example in current working directory.
**/
int main()
{
  if(mkdir("Example" , 0666) < 0 )
  {
      printf("Directory creation failed \n");
      return -1;
  }
  printf("Directory Example created \n");
  return 0;
}

Output

Directory Example created

Errors

 The mkdir system call will fail and no directory will be created if:
[ENOTDIR]
 | A component of the path prefix is not a directory.(Not supported).
[ENAMETOOLONG]
 | A component or an entire path name exceeded 255 characters.
[ENOENT]
 | A component of the path prefix does not exist.
[EACCES]
 | Search permission is denied for a component of the path prefix, or write permission is denied on the parent directory of the directory to be created(Not supported).
[ELOOP]
 | Too many symbolic links were encountered in translating the pathname( Not supported).
[EROFS]
 | The named file resides on a read-only file system(Not supported).
[EEXIST]
 | The named file exists.
[ENOSPC]
 | The new directory cannot be created because there is no space left on the file system that will contain the directory(Not supported).
[ENOSPC]
 | There are no free inodes on the file system on which the directory is being created(Not supported).
[EDQUOT]
 | The new directory cannot be created because the user’s quota of disk blocks on the file system that will contain the directory has been exhausted(Not supported).
[EDQUOT]
 | The user’s quota of inodes on the file system on which the directory is being created has been exhausted(Not supported).
[EIO] | An I/O error occurred while making the directory entry or allocating the inode(Not supported).
[EIO] | An I/O error occurred while reading from or writing to the file system(Not supported).
[EFAULT]
 | The path argument points outside the process’s allocated address space(Not supported).

See also

 chmod, stat, umask

Feedback

For additional information or queries on this page send feedback


mkfifo

Name

mkfifo - makes a FIFO(First In First Out) file

Library

 libc.lib

Synopsis
#include <sys/types.h>
#include <sys/stat.h>
int mkfifo (const char *path, mode_t mode);

Return values

 The mkfifo function returns the value 0 if successful; otherwise the value -1 is returned and errno is set to indicate the error.

Detailed description

 The mkfifo system call creates a new FIFO(First In First Out) file with name path. The access permissions are specified by mode and restricted by the umask of the calling process. With the current implementation, the use of umask has no effect.

The fifo’s owner ID and group ID is set to root.

Please note that running stat on fifo file does not provide modification time information and is set to file creation time. Use fstat (on the fd) instead to retrieve the last modified time.

Examples

#include <sys/types.h>
#include <sys/stat.h>
#include <stdio.h>

int main(void)
{
    char *pathname = "C:\\XXX";
    mode_t mode = 0666;
    if (mkfifo(pathname, mode) == -1) {
        printf("mkfifo() failed\n");
    }
    return 0;
}

Errors

 The mkfifo system call will fail and no fifo will be created if:
[ENOTDIR]
 | A component of the path prefix is not a directory.
[ENAMETOOLONG]
 | A component or an entire path name exceeded 255 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 pathname.
[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 placed cannot be extended because there is no space left on the file system containing the directory.

See also

 chmod, stat, umask

Feedback

For additional information or queries on this page send feedback


mkstemp

Name

mkstemp - creates a unique temporary file

Library

 libc.lib

Synopsis
#include <unistd.h>
int mkstemp (char *template);

Return values

 The mkstemp function returns -1 if no suitable file could be created and an error code is placed in the global variable. errno.

Detailed description

 The mkstemp function takes the given file name template and overwrites a portion of it to create a file with that name and returns a file descriptor opened for reading and writing. This file name is guaranteed not to exist at the time of function invocation and is suitable for use by the application. The template may be any file name with some number of ‘X s’ appended to it, for example /tmp/temp.XXXXXX. The trailing ‘X s’ are replaced with a unique alphanumeric combination. The number of unique file names mkstemp can return depends on the number of ‘X s’ provided; six ‘X s’ will result in mkstemp selecting one of 56800235584 (62 ** 6) possible temporary file names.

Examples

#include <stdlib.h>
#include <stdio.h> //printf, SEEK_SET
#include <unistd.h>

int main( void )
{
 char arr[] = "c:\\someXXXXXXXX";
 char buf[10];

 //create a temporary file using mkstemp()
 int fd = mkstemp(arr);

 if(fd != -1)
 {
    //write to the file
    write(fd, "hello", 5);
    //seek to the beginning of the file
    lseek(fd, 0, SEEK_SET); //beg of the file
    //read from the file
    read(fd, buf, 5);
    buf[5] = '\0';
    //close the file
    close(fd);
 }

 printf("buf read: %s", buf);
 return 0;
}

Output

buf read: hello

Errors

 The mkstemp function may set errno to one of the following values:
[ENOTDIR]
The pathname portion of the template is not an existing directory.

The mkstemp function may also set errno to any value specified by the stat function.

The mkstemp function may also set errno to any value specified by the open function.

Notes

 A common problem that results in a core dump is that the programmer passes in a read-only string to mkstemp, This is common with programs that were developed before -isoC compilers were common. For example, calling mkstemp with an argument of "/tmp/tempfile.XXXXXX" will result in a core dump due to mkstemp attempting to modify the string constant that was given. If the program in question makes heavy use of that type of function call,there is the option of compiling the program so that it will store string constants in a writable segment of memory.

See also

 chmod, getpid, mkdir, open, stat

Feedback

For additional information or queries on this page send feedback


mmap

Name

mmap - map files or devices into memory

Library

 libc.lib

Synopsis
#include <sys/mman.h>
void * mmap (void *addr, size_t len, int prot, int flags, int fd, off_t offset);

Return values

 Upon successful completion, mmap returns a pointer to the mapped region. Otherwise, a value of MAP_FAILED is returned and errno is set to indicate the error.

Detailed description

 The mmap system call causes the pages starting at addr and continuing for at most len bytes to be mapped from the object described by fd, starting at byte offset offset. If len is not a multiple of the pagesize, the mapped region may extend past the specified range. Any such extension beyond the end of the mapped object will be zero-filled.

If addr is non-zero, it is used as a hint to the system. (As a convenience to the system, the actual address of the region may differ from the address supplied.) If addr is zero, an address will be selected by the system. The actual starting address of the region is returned. A successful mmap deletes any previous mapping in the allocated address range.

The protections (region accessibility) are specified in the prot argument by or ’ing the following values:

PROT_READ | Pages may be read.
PROT_WRITE | Pages may be written.
PROT_EXEC | Pages may be executed.
PROT_NONE | This protection mode is currently not supported.

The flags argument specifies the type of the mapped object, mapping options and whether modifications made to the mapped copy of the page are private to the process or are to be shared with other references. Sharing, mapping type and options are specified in the flags argument by or ’ing the following values:

MAP_PRIVATE | Modifications are private.
MAP_SHARED | Modifications are shared.
MAP_FIXED, MAP_FILE, MAP_ANON, MAP_HASSEMAPHORE, MAP_STACK, MAP_NOSYNC -- These flags are currently not supported.

The close system call does not unmap pages, see munmap for further information.

The current design does not allow a process to specify the location of swap space. In the future we may define an additional mapping type, MAP_SWAP, in which the file descriptor argument specifies a file or device to which swapping should be done.

Examples

/*
* Detailed description  : Example to create a mapped memory to a file region.
* Precondition : None
*
*/
#include <unistd.h>
#include <stdio.h>
#include <sys/mman.h>
#include <fcntl.h>
int main(void)
{
    int fd = -1;
    char* mapaddr;
    int len = getpagesize();
    int prot = PROT_WRITE | PROT_READ;
    if((fd = open("C:\\Test.txt", O_RDWR | O_CREAT, 0666) ) < 0){
        printf("File open failed\n");
    }
    mapaddr = (char*)mmap((void*)0, len, prot, MAP_SHARED, fd, 0);
    if(mapaddr == MAP_FAILED){
        printf("mmap on file failed\n");
    }
    printf("mmap on file succeeded\n");
}

Errors

 The mmap system call will fail if:
[EACCES]
 | The flag PROT_READ was specified as part of the prot argument and fd was not open for reading. The flags MAP_SHARED and PROT_WRITE were specified as part of the flags and prot argument and fd was not open for writing.
[EBADF]
 | The fd argument is not a valid open file descriptor.
[ENOTSUP]
 | MAP_FIXED was specified in the flag argument.
[ENOTSUP]
 | PROT_NONE was specified in the prot argument.
[EMFILE]
 | The number of mapped regions would exceed an implementation-defined limit (per process or per system).
[ENXIO]
 | Addresses in the range( off,off + len ) are invalid for the object specified by fd.
[EINVAL]
 | The len argument was lesser or equal to 0.
[EINVAL]
 | The offset argument was not page-aligned.

See also

 mprotect, msync, munmap, getpagesize,

Feedback

For additional information or queries on this page send feedback


modf

Name

modf, modff, modfl
- extract signed integral and fractional values from floating-point number

Library

 libc.lib

Synopsis
#include <math.h>
double modf (double value, double *iptr);
float modff (float value, float *iptr);
long double modfl (long double value, long double *iptr);

Return values

 The modf modff and modfl functions return the signed fractional part of a value.

Detailed description

 The modf function breaks the argument value into integral and fractional parts, each of which has the same sign as the argument. It stores the integral part as a double in the object pointed to by iptr. The function modff (is, the, float, version, of, modf().);
The function modfl is an alias to the function modf.

Examples

#include <math.h>
#include <stdio.h>
int main()
{
   double x1 = 123.456703 , y;
   double  iptr;
   float fptr;
   y = modf( x1, &iptr );
   printf( "modf(%f , &iptr):: Int Part: %f and Fractional Part: %f 0, x1, iptr, y );
   y = modff( x1, &fptr );
   printf( "modff(%f , &iptr):: Int Part: %f and Fractional Part: %f 0, x1, fptr, y );
   y = modfl( x1, &iptr );
   printf( "modfl(%f , &iptr):: Int Part: %f and Fractional Part: %f 0, x1, iptr, y );
}

Output

modf ( 123.456703 , &iptr ) :: Int Part: 123 and Fractional Part: 0.456703
modff( 123.456703,  &iptr ) :: Int Part: 123 and Fractional Part: 0.456703
modfl( 123.456703,  &iptr ) :: Int Part: 123 and Fractional Part: 0.456703

See also

 frexp, ldexp, math

Feedback

For additional information or queries on this page send feedback


mprotect

Name

mprotect - controls allowable accesses to a region of memory

Library

 libc.lib

Synopsis
#include <sys/mman.h>
int mprotect (const void *addr, size_t len, int prot);

Return values

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

Detailed description

 The mprotect system call changes the specified pages to have protection prot. Not all implementations will guarantee protection on a page basis; the granularity of protection changes may be as large as an entire region. A region is the virtual address space defined by the start and end addresses of a struct vm_map_entry .

NOTE: This interface is currently not functional and only build supported. This is because of the fact that, mmap used for mapping, internally uses shared memory facility provided by the platform and shared memory interface does not support dynamic modification of memory protections.

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.

Errors

 The mprotect system call will fail if:
[EINVAL]
 | The virtual address range specified by the addr and len arguments is not valid.
[EACCES]
 | The calling process was not allowed to change the protection to the value specified by the prot argument.

See also

 msync, munmap

Feedback

For additional information or queries on this page send feedback


msgctl

Name

msgctl - message control operations

Library

 libc.lib

Synopsis
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
int msgctl (int msqid, int cmd, struct msqid_ds *buf);

Return values

 The msgctl function returns the value 0 if successful; otherwise the value -1 is returned and errno is set to indicate the error.

Detailed description

 The msgctl system call performs some control operations on the message queue specified by msqid.

Each message queue has a data structure associated with it, parts of which may be 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) the following 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];
};

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 operation 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 structure pointed to by buf.
IPC_SET | Set the value of the msg_perm.uid, msg_perm.gid, msg_perm.mode and msg_qbytes fields in the structure associated with msqid. The values are taken from the corresponding fields in the structure pointed to by buf. Values for msg_qbytes that exceed the system limit (MSGMNB from <sys/msg.h>) are silently truncated to that limit.
IPC_RMID | Remove the message queue specified by msqid and destroy the data associated with it.

The permission to read from or write to a message queue (see msgsnd and msgrcv is determined by the msg_perm.mode field in the same way as is done with files (see chmod)

Examples

#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>

#define MESSAGE_Q_KEY 1000

int main(void)
{
   int msq_id, len;
   struct {
       long mtype;
       char mtext[128];
   } msg_buf;
   /*
    * Create a message queue with a given key
    */
    if ((msq_id = msgget(MESSAGE_Q_KEY, IPC_CREAT | IPC_EXCL | 0666)) == -1) {
       printf("Message Q create failed with errno %d\n", errno);
       return -1;
    }
    msg_buf.mtype = 1; /* message identifier */
    strcpy(msg_buf.mtext, "some_data_to_send"); /* data */
    len = strlen(msg_buf.mtext)+1;
    /*
     * Put the message in the queue
     */
    if (msgsnd(msq_id, (struct msgbuf *)&msg_buf, len, 0) == -1) {
        printf("Message Q send failed with errno %d\n", errno);
    }
    return 0;
}

#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>

#define MESSAGE_Q_KEY 1000

int main(void)
{
   int msq_id;
   int msg_len = 128;
   int msg_type = 0; /* Any type of message */
   struct {
       long mtype;
       char mtext[128];
   } msg_buf;
   /*
    * Get the message queue id for the given key
    */
    if ((msq_id = msgget(MESSAGE_Q_KEY, 0)) == -1) {
       printf("Message Q  get id failed with errno %d\n", errno);
       return -1;
    }
    /*
     * Get the message from the queue
     */
    if (msgrcv(msq_id, (struct msgbuf *)&msg_buf, msg_len, msg_type, 0) == -1) {
        printf("Message Q recv failed with errno %d\n", errno);
    }
    /*
     * Remove the message queue
     */
     if (msgctl(msq_id, IPC_RMID, NULL) == -1) {
       printf("Message Q  delete failed with errno %d\n", errno);
       return -1;
     }
     return 0;
}

Errors

 The msgctl function will fail if:
[EPERM]
 | The cmd argument is equal to IPC_SET or IPC_RMID and the caller does not have the permission to perform this operation An attempt is made to increase the value of msg_qbytes through IPC_SET but the caller does not have the permission to perform this operation.
[EACCES]
 | The command is IPC_STAT and the caller has no read permission for this message queue.
[EINVAL]
 | The msqid argument is not a valid message queue identifier. cmd is not a valid command.

See also

 msgget, msgrcv, msgsnd

Feedback

For additional information or queries on this page send feedback


msgget

Name

msgget - gets a message queue identifier

Library

 libc.lib

Synopsis
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
int msgget (key_t key, int msgflg);

Return values

 Upon successful completion a positive message queue identifier is returned. Otherwise, -1 is returned and the global variable errno is set to indicate the error.

Detailed description

 The msgget function returns the message queue identifier associated with key. A message queue identifier is a unique integer greater than zero.

A message queue is created if either key is equal to IPC_PRIVATE, or key does not have a message queue identifier associated with it, and the IPC_CREAT bit is set in msgflg.

If a new message queue is created, the data structure associated with it (the msqid_ds structure, see msgctl is initialized as follows:

  • msg_perm.cuid and msg_perm.uid are set to the effective uid of the calling process. In the current implementation, uid is set to root.
  • msg_perm.gid and msg_perm.cgid are set to the effective gid of the calling process. In the current implementation, gid is set to root.
  • 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 are set to 0.
  • msg_qbytes is set to the system wide maximum value for the number of bytes in a queue (Dv MSGMNB).
  • msg_ctime is set to the current time.

Examples

 Example code to create a message queue using msgget
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>

#define MESSAGE_Q_KEY 1000

int main(void)
{
   int msq_id, len;
   struct {
       long mtype;
       char mtext[128];
   } msg_buf;
   /*
    * Create a message queue with a given key
    */
    if ((msq_id = msgget(MESSAGE_Q_KEY, IPC_CREAT | IPC_EXCL | 0666)) == -1) {
       printf("Message Q create failed with errno %d\n", errno);
       return -1;
    }
    msg_buf.mtype = 1; /* message identifier */
    strcpy(msg_buf.mtext, "some_data_to_send"); /* data */
    len = strlen(msg_buf.mtext)+1;
    /*
     * Put the message in the queue
     */
    if (msgsnd(msq_id, (struct msgbuf *)&msg_buf, len, 0) == -1) {
        printf("Message Q send failed with errno %d\n", errno);
    }
    return 0;
}

Example code to return an existing message queue with msgget

#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>

#define MESSAGE_Q_KEY 1000

int main(void)
{
   int msq_id;
   int msg_len = 128;
   int msg_type = 0; /* Any type of message */
   struct {
       long mtype;
       char mtext[128];
   } msg_buf;
   /*
    * Get the message queue id for the given key
    */
    if ((msq_id = msgget(MESSAGE_Q_KEY, 0)) == -1) {
       printf("Message Q  get id failed with errno %d\n", errno);
       return -1;
    }
    /*
     * Get the message from the queue
     */
    if (msgrcv(msq_id, (struct msgbuf *)&msg_buf, msg_len, msg_type, 0) == -1) {
        printf("Message Q recv failed with errno %d\n", errno);
    }
    /*
     * Remove the message queue
     */
     if (msgctl(msq_id, IPC_RMID, NULL) == -1) {
       printf("Message Q  delete failed with errno %d\n", errno);
       return -1;
     }
     return 0;
}

Errors

[EACCES]
 | A message queue is already associated with key and the caller has no permission to access it.
[EEXIST]
 | Both IPC_CREAT and IPC_EXCL are set in msgflg, and a message queue is already associated with key.
[ENOSPC]
 | A new message queue could not be created because the system limit for the number of message queues has been reached.
[ENOENT]
 | IPC_CREAT was not set in msgflg and no message queue associated with key was found.

See also

 msgctl, msgrcv, msgsnd

Feedback

For additional information or queries on this page send feedback


msgrcv

Name

msgrcv - message operations

Library

 libc.lib

Synopsis
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
int msgrcv (int msqid, void *msgp, size_t msgsz, long msgtyp, int msgflg);

Return values

 Upon successful completion, msgrcv returns the number of bytes received into the mtext field of the structure pointed to by msgp. Otherwise, -1 is returned, and errno set to indicate the error.

Detailed description

 The msgrcv function receives a message from the message queue specified in msqid, and places it into the structure pointed to by msgp. This structure should consist 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 is an array of bytes, with a size up to that of the system limit (Dv MSGMAX).

The value of msgtyp has one of the following meanings:

  • The msgtyp argument is greater than 0. The first message of type msgtyp will be received.
  • The msgtyp argument is equal to 0. The first message on the queue (of any message type) will be received.
  • The msgtyp argument is less than 0. The first message of the lowest message type 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 the received message has a length greater than msgsz it will be silently truncated if the MSG_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, the behavior of msgrcv depends on whether the IPC_NOWAIT flag is set in msgflg or not. If IPC_NOWAIT is set, msgrcv will immediately return a value of -1, and set errno to ENOMSG. If IPC_NOWAIT is not set, the calling process will be blocked until:

  • 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 errno set to EINVAL.

If a message is successfully received, the data structure associated with msqid is updated as follows:

  • msg_cbytes is decremented by the size of the message.
  • msg_lrpid is set to the pid of the caller.
  • msg_lrtime is set to the current time.
  • msg_qnum is decremented by 1.

Examples

 Receive a message from the queue
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>

#define MESSAGE_Q_KEY 1000

int main(void)
{
   int msq_id;
   int msg_len = 128;
   int msg_type = 0; /* Any type of message */
   struct {
       long mtype;
       char mtext[128];
   } msg_buf;
   int ret_val = -1;
   /*
    * Get the message queue id for the given key
    */
    if ((msq_id = msgget(MESSAGE_Q_KEY, IPC_CREAT)) == -1) {
       printf("Message Q  get id failed with errno %d\n", errno);
       return -1;
    }
    /*
     * Get the message from the queue
     */
    if ((ret_val = msgrcv(msq_id, (struct msgbuf *)&msg_buf, msg_len, msg_type, 0)) == -1) {
        printf("Message Q recv failed with errno %d\n", errno);
    }
    /*
     * Remove the message queue
     */
     if (msgctl(msq_id, IPC_RMID, NULL) == -1) {
       printf("Message Q  delete failed with errno %d\n", errno);
       return -1;
     }
     return ret_val;
}

 Send a message to the queue

#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>

#define MESSAGE_Q_KEY 1000

int main(void)
{
   int msq_id, len;
   struct {
       long mtype;
       char mtext[128];
   } msg_buf;
   /*
    * Create a message queue with the given key
    */
    if ((msq_id = msgget(MESSAGE_Q_KEY, IPC_CREAT | IPC_EXCL | 0666)) == -1) {
       printf("Message Q create failed with errno %d0, errno);
       return -1;
    }
    msg_buf.mtype = 1; /* message identifier */
    strcpy(msg_buf.mtext, "some_data_to_send"); /* data */
    len = strlen(msg_buf.mtext)+1;
    /*
     * Put the message in the queue
     */
    if (msgsnd(msq_id, (struct msgbuf *)&msg_buf, len, 0) == -1) {
        printf("Message Q send failed with errno %d\n", errno);
    }
    return 0;
}

Errors

 The msgrcv function will fail if:
[EINVAL]
 | The msqid argument is not a valid message queue identifier. The message queue was removed while msgrcv was waiting for a message of the requested type to become available on it. The msgsz argument is less than 0.
[E2BIG]
 | A matching message was received, but its size was greater than msgsz and the MSG_NOERROR flag was not set in msgflg.
[EACCES]
 | The calling process does not have read access to the message queue.
[EIDRM]
 | The message queue identifier msqid is removed from the system.
[ENOMSG]
 | There is no message of the requested type available on the message queue, and IPC_NOWAIT is set in msgflg.

See also

 msgctl, msgget, msgsnd

Feedback

For additional information or queries on this page send feedback


msgsnd

Name

msgsnd - message operations

Library

 libc.lib

Synopsis
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
int msgsnd (int msqid, const void *msgp, size_t msgsz, int msgflg);

Return values

 The msgsnd function returns the value 0 if successful; otherwise the value -1 is returned and errno is set to indicate the error.

Detailed description

 The msgsnd function sends a message to the message queue specified in msqid. The msgp argument points to a structure containing the message. This structure should consist 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 (see msgrcv mtext is an array of bytes, with a size up to that of the system limit (Dv MSGMAX).

If the number of bytes already on the message queue plus msgsz is bigger than the maximum number of bytes on the message queue (Va msg_qbytes, see msgctl or the number of messages on all queues system-wide is already equal to the system limit, msgflg determines the action of msgsnd. If msgflg has IPC_NOWAIT mask set in it, the call will return immediately. If msgflg does not have IPC_NOWAIT set in it, the call will block until:

  • The condition which caused the call to block does no longer exist. The message will be sent.
  • The message queue is removed, in which case -1 will be returned, and errno is set to EINVAL.

After a successful call, the data structure associated with the message queue is updated in the following way:

  • msg_cbytes is incremented by the size of the message.
  • 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.

Examples

#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>

#define MESSAGE_Q_KEY 1000

int main(void)
{
   int msq_id, len;
   struct {
       long mtype;
       char mtext[128];
   } msg_buf;
   /*
    * Create a message queue with the given key
    */
    if ((msq_id = msgget(MESSAGE_Q_KEY, IPC_CREAT | IPC_EXCL | 0666)) == -1) {
       printf("Message Q create failed with errno %d\n", errno);
       return -1;
    }
    msg_buf.mtype = 1; /* message identifier */
    strcpy(msg_buf.mtext, "some_data_to_send"); /* data */
    len = strlen(msg_buf.mtext)+1;
    /*
     * Put the message in the queue
     */
    if (msgsnd(msq_id, (struct msgbuf *)&msg_buf, len, 0) == -1) {
        printf("Message Q send failed with errno %d\n", errno);
    }
    return 0;
}

Errors

 The msgsnd function will fail if:
[EINVAL]
 | The msqid argument is not a valid message queue identifier The message queue was removed while msgsnd was waiting for a resource to become available in order to deliver the message. The msgsz argument is less than 0, or greater than msg_qbytes. The mtype argument 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 the whole system, and IPC_NOWAIT was set in msgflg.
[EIDRM]
 | The message queue identifier msqid is removed from the system.

Feedback

For additional information or queries on this page send feedback


msync

Name

msync - synchronizes a file with a memory map

Library

 libc.lib

Synopsis
#include <sys/mman.h>
int msync (void *addr, size_t len, int flags);

Return values

 Upon successful completion, msync() shall return 0; otherwise, it shall return -1 and set errno to indicate the error.

Detailed description

 The msync system call writes any modified pages back to the file system. if len is non-zero, only those pages containing addr and len-1 succeeding locations will be examined. The flags argument may be specified as follows:

MS_ASYNC
 | This flag is currently not supported.
MS_SYNC
 | Perform synchronous writes
MS_INVALIDATE
 | Invalidate all cached data

Examples

/*
* Detailed description: Example to sync changes on mapped memory to file.
* Precondition: None
*
*/
#include <unistd.h>
#include <stdio.h>
#include <sys/mman.h>
#include <fcntl.h>
#include <string.h>
int main(void)
{
    int fd = -1;
    char* mapaddr;
    int len = getpagesize();
    int prot = PROT_WRITE | PROT_READ;
    if((fd = open("C:\\Test.txt", O_RDWR | O_CREAT, 0666) ) < 0)
    {
         printf("File open failed");
    }
    mapaddr = (char*)mmap((void*)0, len, prot, MAP_SHARED, fd, 0);
    if(mapaddr == MAP_FAILED)
    {
         printf("mmap on file failed");
    }
    strcpy(mapaddr, "This is a write through mapped memory ");
    if(-1 == msync(mapaddr, len, MS_SYNC))
    {
        printf("Sync on mapped memory to file failed");
    }
    printf("Sync on mapped memory to file succeeded");
}

Errors

 The msync system call will fail if:
[EBUSY]
 | Some or all of the pages in the specified region are locked and MS_INVALIDATE is specified. (This errno is currently not supported)
[EINVAL]
 | The addr argument is not a multiple of the hardware page size.
[EINVAL]
 | The len argument is too large or negative.
[EINVAL]
 | The flags argument was both MS_ASYNC and MS_INVALIDATE. Only one of these flags is allowed or the flags are invalid.
[ENOMEM]
 | The addresses in the range starting at addr and continuing for len bytes are outside the range allowed for the address space of a process or specify one or more pages that are not mapped.

See also

 mlock, mprotect, munmap
The msync system call first appeared in BSD 4.4.

Feedback

For additional information or queries on this page send feedback


munmap

Name

munmap - unmap files or devices into memory

Library

 libc.lib

Synopsis
#include <sys/mman.h>
int munmap (void *addr, size_t len);

Return values

 Upon successful completion, munmap() shall return 0; otherwise, it shall return -1 and set errno to indicate the error.

Detailed description

 The munmap system call deletes the mappings for the specified address range, and causes further references to addresses within the range to generate invalid memory references. The current implementation does not support partial deletion of mapped memory, i.e if offset to offset+len section of memory was mapped using mmap, then the entire section of memory offset+len will be deleted.

Examples

/*
* Detailed description: Example to create a mapped memory to a file region.
* Precondition: None
*
*/
#include <unistd.h>
#include <stdio.h>
#include <sys/mman.h>
#include <fcntl.h>
int main(void)
{
    int fd = -1;
    char* mapaddr;
    int len = getpagesize();
    int prot = PROT_WRITE | PROT_READ;
    if((fd = open("C:\\Test.txt", O_RDWR | O_CREAT, 0666) ) < 0){
        printf("File open failed\n");
    }
    mapaddr = (char*)mmap((void*)0, len, prot, MAP_SHARED, fd, 0);
    if(mapaddr == MAP_FAILED){
        printf("mmap on file failed\n");
    }
    printf("mmap on file succeeded\n");
}

Errors

 The munmap system call will fail if:
[EINVAL]
The addr argument was not page aligned, the len argument was zero or negative, or some part of the region being unmapped is outside the valid address range for a process.

See also

 mmap, mprotect, msync, getpagesize

Feedback

For additional information or queries on this page send feedback


nanosleep

Name

nanosleep - pause execution for a specified time

Library

 libc.lib

Synopsis
#include <time.h>
int nanosleep (const struct timespec *rqtp, struct timespec *rmtp);

Return values

 If the nanosleep system call returns because the requested time has elapsed, the value returned will be zero.

If rmtp is non- NULL, the timespec structure it references is updated to contain the unslept amount (the request time minus the time actually slept).

Detailed description

 The nanosleep system call causes the process to sleep for the specified time. Currently only microsecond sleep resolution can be obtained.

Examples

/**
  * Detailed description: Sample usage of nanosleep system call.
**/
#include <stdio.h>
#include <time.h>
int main()
{
 struct timespec tim, tim2;
   tim.tv_sec = 1;
   tim.tv_nsec = 500;
   if(nanosleep(&tim , &tim2) < 0 )   {
      printf("Nano sleep system call failed \n");
      return -1;
   }
   printf("Nano sleep successfull \n");
  return 0;
}

Output

Nano sleep successfull

Errors

 The nanosleep system call fails if:
[EFAULT]
 | Either rqtp or rmtp points to memory that is not a valid part of the process address space.
[EINTR]
 | The nanosleep system call was interrupted by the delivery of a signal(Not supported).
[EINVAL]
 | The rqtp argument specified a nanosecond value less than zero or greater than or equal to 1000 million.
[ENOSYS]
 | The nanosleep system call is not supported by this implementation.

See also

 sleep

Feedback

For additional information or queries on this page send feedback


nextafter

Name

nextafter, nextafterf, nextafterl, nexttoward, nexttowardf, nexttowardl
- floating point number manipulation

Library

 libm.lib

Synopsis
#include <math.h>
double nextafter (double x, double y);
float nextafterf (float x, float y);
long double nextafterl (long double x, long double y);
double nexttoward (double x, long double y);
float nexttowardf (float x, long double y);
long double nexttowardl (long double x, long double y);

Detailed description

 These functions return the next machine representable number from x in direction y.

Examples

#include <math.h>
int main( )
{
   double inp1 = 1.3;
   double inp2 = 2;
   double y;
   y = nextafter( inp1, inp2 );
   printf( "nextafter(%f , %f) = %f\n", inp1,  inp2,  y );
   y = nextafterf( inp1, inp2 );
   printf( "nextafterf(%f , %f) = %f\n", inp1, inp2, y );
   y = nextafterl( inp1, inp2 );
   printf( "nextafterl(%f , %f) = %f\n\n", inp1, inp2, y );
   inp1 = 9;
   inp2 = 9;
   y = nexttoward( inp1, inp2 );
   printf( "nexttoward(%f , %f) = %f\n", inp1,  inp2,  y );
   y = nexttowardf( inp1, inp2 );
   printf( "nexttowardf(%f , %f) = %f\n", inp1, inp2, y );
   y = nexttowardl( inp1, inp2 );
   printf( "nexttowardl(%f , %f) = %f\n", inp1, inp2, y );
}

Output

nextafter  ( 1.3, 2.0 ) = 1.3
nextafterf ( 1.3, 2.0 ) = 1.3
nextafterl ( 1.3, 2.0 ) = 1.3
nexttoward  ( 9, 9 ) = 9
nexttowardf ( 9, 9 ) = 9
nexttowardl ( 9, 9 ) = 9

See also

 ieee, math

Feedback

For additional information or queries on this page send feedback


ngettext

Name

ngettext, dngettext, dcngettext - Translate message and choose the plural form.

Library

libintl.lib

Synopsis

#include <libintl.h>

char * ngettext(const char *msgid, const char *msgid_plural, unsigned long int n);
char * dngettext(const char *domainname, const char *msgid, const char *msgid_plural, unsigned long int n);
char * dcngettext(const char *domainname, const char *msgid, const char *msgid_plural, unsigned long int n, int category);

Return values

If a translation for the text string was found in one of the specified message catalogs, converts the appropriate plural form to the current locale's codeset and returns the translated string. Do not modify or free the returned string as it is statically allocated in the function.

If a translation for the text string was not found, then msgid or msgid_plural is returned as described below.

Detailed description

The ngettext(), dngettext() and dcngettext() functions try to translate a text string to the user's native language by looking up the translation message catalog for the appropriate plural form.

The ngettext(), dngettext() and dcngettext() functions work like gettext(), dgettext() and dcgettext() respectively, except they choose the appropriate plural forms.

In the "C" locale, or none of the used catalogs contain a translation for the text string specified by the argument msgid, these functions return msgid if n==1 or msgid_plural if n!= 1.

Errors

errno is not modified.

Feedback

For additional information or queries on this page send feedback

© 2006-2007 Nokia


nice

Name

nice - run a program with modified scheduling priority

Library

 libc.lib

Synopsis
#include <unistd.h>
int nice (int incr);

Detailed description

The nice function obtains the scheduling priority of the process from the system and sets it to the priority value specified in incr. The priority is a value in the range -20 to 20. The default priority is 0; lower priorities cause more favorable scheduling.

Examples

#include<unistd.h>
#include<stdio.h>
int test_nice()
{
   int retVal;
   errno = 0;
   int i = -10;
   int ret_get1 = getpriority(PRIO_PROCESS,0);
   retVal = nice(i);
   int ret_get2 = getpriority(PRIO_PROCESS,0);
   if((retVal == -1)&&(errno))
   {
      printf("failed");
      return -1;
   }
   else
   {
     if(!(i - (ret_get2 – retget1)))
     printf("Nice value: %d\n", i)
     printf("nice passed");
   }
   return 0;
}

Output

Nice value: -10
nice passed

See also

 getpriority

Feedback

For additional information or queries on this page send feedback


nl_langinfo

Name

nl_langinfo - query language and locale information

Library

 libc.lib

Synopsis
#include <langinfo.h>
char * nl_langinfo (nl_item item);

Return values

 In a locale where langinfo data is not defined, nl_langinfo returns a pointer to the corresponding string in the POSIX locale. In all locales, nl_langinfo returns a pointer to an empty string if item contains an invalid setting. "Dom" if the identified language was Portuguese, and "Sun" if the identified language was English.

Detailed description

 The nl_langinfo function returns a pointer to a string containing information relevant to the particular language or cultural area defined in the program’s locale. The manifest constant names and values of item are defined in
#include <langinfo.h>

YESEXPR, NOEXPR, YESSTR, NOSTR items are not supported since LC_MESSAGE category is not supported.

item passed to nl_langinfo can be any value listed below.
CODESET
 | Name of the character encoding used in the locale.
D_T_FMT
 | String for formatting date and time
D_FMT | Date format string
T_FMT | Time format string
T_FMT_AMPM
 | AM or PM time formatting string
AM_STR
 | Ante Meridian affix
PM_STR
 | Post Meridian affix
ABDAY_1 - ABDAY_7
 | Abbreviated name of the nth day of the week
DAY_1 - DAY_7
 | Name of the nth day of the week
MON_1 - MON_12
 | Name of the nth month of the year
ABMON_1 - ABMON_12
 | Name of the nth month of the year
RADIXCHAR
 | Radix character i.e character used to separate decimal value
THOUSEP
 | Separator for thousands

Examples

#include<stdio.h>
#include<locale.h>
#include<langinfo.h>
int main()
{
        //Set the locale to Finnish
        char* locale = setlocale(LC_ALL,"fi_FI.ISO-8859-1");
        char* str = NULL;
        //Check whether locale setting is succesfull or not
        if(NULL != locale)
        {
             printf("Locale setting is successful\n");
             printf("Locale is set to %s\n", locale);
             //Retrieve first day of the week
             str = nl_langinfo(DAY_1);
             if(NULL != str)
             {
                  printf("First day of the week is %s\n", str);
             }
             //Retrieve second month of the year
             str = nl_langinfo(MON_2);
             if(NULL != str)
             {
                  printf("Second month of the year is %s\n", str);
             }
        }
        else
        {
                printf("Locale setting failed\n");
        }
        return 0;
}

Output

Locale setting is successful
Locale is set to fi_FI.ISO-8859-1
First day of the week is sunnuntai
Second month of the year is helmikuu

See also

 setlocale

Feedback

For additional information or queries on this page send feedback


OBJ_cleanup - ASN1 object utility functions

Name

OBJ_nid2obj, OBJ_nid2ln
OBJ_nid2sn, OBJ_obj2nid
OBJ_txt2nid, OBJ_ln2nid
OBJ_sn2nid, OBJ_cmp
OBJ_dup, OBJ_txt2obj
OBJ_obj2txt, OBJ_create
OBJ_cleanup

ASN1 object utility functions

Library

libcrypto.lib

Synopsis

ASN1_OBJECT * OBJ_nid2obj(int n);
const char *  OBJ_nid2ln(int n);
const char *  OBJ_nid2sn(int n);
int OBJ_obj2nid(const ASN1_OBJECT *o);
int OBJ_ln2nid(const char *ln);
int OBJ_sn2nid(const char *sn);
int OBJ_txt2nid(const char *s);
ASN1_OBJECT * OBJ_txt2obj(const char *s, int no_name);
int OBJ_obj2txt(char *buf, int buf_len, const ASN1_OBJECT *a, int no_name);
int OBJ_cmp(const ASN1_OBJECT *a,const ASN1_OBJECT *b);
ASN1_OBJECT * OBJ_dup(const ASN1_OBJECT *o);
int OBJ_create(const char *oid,const char *sn,const char *ln);
void OBJ_cleanup(void);

Detailed Description

The ASN1 object utility functions process ASN1_OBJECT structures which are a representation of the ASN1 OBJECT IDENTIFIER (OID) type.

OBJ_nid2obj(), OBJ_nid2ln() and OBJ_nid2sn() convert the NID n to an ASN1_OBJECT structure, its long name and its short name respectively, or NULL is an error occurred.

OBJ_obj2nid(), OBJ_ln2nid(), OBJ_sn2nid() return the corresponding NID for the object o, the long name <ln> or the short name <sn> respectively or NID_undef if an error occurred.

OBJ_txt2nid() returns NID corresponding to text string <s>. s can be a long name, a short name or the numerical representation of an object.

OBJ_txt2obj() converts the text string s into an ASN1_OBJECT structure. If no_name is 0 then long names and short names will be interpreted as well as numerical forms. If no_name is 1 only the numerical form is acceptable.

OBJ_obj2txt() converts the ASN1_OBJECT a into a textual representation. The representation is written as a null terminated string to buf at most buf_len bytes are written, truncating the result if necessary. The total amount of space required is returned. If no_name is 0 then if the object has a long or short name then that will be used, otherwise the numerical form will be used. If no_name is 1 then the numerical form will always be used.

OBJ_cmp() compares a to b. If the two are identical 0 is returned.

OBJ_dup() returns a copy of o.

OBJ_create() adds a new object to the internal table. oid is the numerical form of the object, sn the short name and ln the long name. A new NID is returned for the created object.

OBJ_cleanup() cleans up OpenSSLs internal object table: this should be called before an application exits if any new objects were added using OBJ_create().

Examples

Create an object for commonName:
 ASN1_OBJECT *o;
 o = OBJ_nid2obj(NID_commonName);

Check if an object is commonName

 if (OBJ_obj2nid(obj) == NID_commonName)
        /* Do something */

Create a new NID and initialize an object from it:

 int new_nid;
 ASN1_OBJECT *obj;
 new_nid = OBJ_create("1.2.3.4", "NewOID", "New Object Identifier");
 obj = OBJ_nid2obj(new_nid);

Create a new object directly:
 obj = OBJ_txt2obj("1.2.3.4", 1);

Notes

Objects in OpenSSL can have a short name, a long name and a numerical identifier (NID) associated with them. A standard set of objects is represented in an internal table. The appropriate values are defined in the header file objects.h.

For example the OID for commonName has the following definitions:

 #define SN_commonName                   "CN"
 #define LN_commonName                   "commonName"
 #define NID_commonName                  13

New objects can be added by calling OBJ_create().

Table objects have certain advantages over other objects: for example their NIDs can be used in a C language switch statement. They are also static constant structures which are shared: that is there is only a single constant structure for each table object.

Objects which are not in the table have the NID value NID_undef.

Objects do not need to be in the internal tables to be processed, the functions OBJ_txt2obj() and OBJ_obj2txt() can process the numerical form of an OID.

Bugs

OBJ_obj2txt() is awkward and messy to use: it doesn't follow the convention of other OpenSSL functions where the buffer can be set to NULL to determine the amount of data that should be written. Instead buf must point to a valid buffer and buf_len should be set to a positive value. A buffer length of 80 should be more than enough to handle any OID encountered in practice.

Return Values

OBJ_nid2obj() returns an ASN1_OBJECT structure or NULL is an error occurred.

OBJ_nid2ln() and OBJ_nid2sn() returns a valid string or NULL on error.

OBJ_obj2nid(), OBJ_ln2nid(), OBJ_sn2nid() and OBJ_txt2nid() return a NID or NID_undef on error.

See Also

ERR_get_error()

History

TBA

Feedback

For additional information or queries on this page send feedback


open

Name

open - open and possibly create a file or device

Library

 libc.lib

Synopsis
#include <fcntl.h>
int open (const char *path, int flags, ...);

Return values

 If successful, open returns a non-negative integer, termed a file descriptor. It returns -1 on failure, and sets errno to indicate the error.

Detailed description

 The file name specified by path is opened for reading and/or writing as specified by the argument flags and the file descriptor returned to the calling process. The flags argument may indicate the file is to be created if it does not exist (by specifying the O_CREAT flag). In this case open requires a third argument mode_t mode, and the file is created with mode mode as described in chmod and modified by the process’ umask value (see umask

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_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_DIRECT        eliminate or reduce cache effects
O_FSYNC         synchronous writes
O_NOFOLLOW      do not follow symlinks
Following options are currently not supported :
O_NONBLOCK, O_SHLOCK, O_EXLOCK, O_DIRECT, O_FSYNC, O_NOFOLLOW.

Opening a file with O_APPEND set causes each write on the file to be appended to the end.

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 O_EXCL is set and the last component of the pathname is a symbolic link, open will fail even if the symbolic link points to a non-existent name.

If the O_NONBLOCK flag is specified and the open system call would result in the process being blocked for some reason (e.g., waiting for carrier on a dialup line), open returns immediately. The descriptor remains in non-blocking mode for subsequent operations.This mode need not have any effect on files other than FIFOs.

If O_FSYNC is used in the mask, all writes will immediately be written to disk, the kernel will not cache written data and all writes on the descriptor will not return until the data to be written completes.

If O_NOFOLLOW is used in the mask and the target file passed to open is a symbolic link then the open will fail.

When opening a file, a lock with flock semantics can be obtained by setting O_SHLOCK for a shared lock, or O_EXLOCK for an exclusive lock. If creating a file with O_CREAT, the request for the lock will never fail (provided that the underlying file system supports locking).

O_DIRECT may be used to minimize or eliminate the cache effects of reading and writing. The system will attempt to avoid caching the data,read or written. If it cannot avoid caching the data, it will minimize the impact the data has on the cache. Use of this flag can drastically reduce performance if not used with care.

If successful, open returns a non-negative integer, termed a file descriptor. It returns -1 on failure. The file pointer used to mark the current position within the file is set to the beginning of the file.

When a new file is created it is given the group of the directory which contains it.

The new descriptor is set to remain open across execve system calls; see close and fcntl.

The system imposes a limit on the number of file descriptors open simultaneously by one process. The getdtablesize system call returns the current system limit.

Note

 Mode values for group and others will be ignored for file creation. The execute bit and setuid on exec bit on an file do not have any effect during file creation.The default working directory of a process is initalized to C:\private\UID (UID of the calling application), and any data written into this C:\private\UID directory persists between phone resets.

If the specified file is a symbolic link and the file it is pointing to is invalid, the symbolic link file will be removed automatically.

Limitation

 A file cannot be created with write-only permissions and any attempt to do so will result in a file with read-write permissions.

Creation of a file with O_CREAT flag does not alter the time stamp of the parent directory. A new file has two time stamps namely: access time and modification time. The creation time stamp of a file is not supported as; the access time stamp is same as the modification time stamp.

Examples

/************************************************************************
* This example creates a file in the current working directory and
* opens it in read-write mode.
************************************************************************/
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
int main()
{
  int fd = 0;
   fd = open("Example.txt" , O_CREAT | O_EXCL , 0666);
   if(fd < 0 )
   {
      printf("Failed to create and open file in current working directory \n");
      return -1;
   }
   printf("File created and opened in current working directory \n"  );
   return 0;
}

Output

File created and opened in current working directory

Errors

 The named file is opened unless:
[ENOTDIR]
 | A component of the path prefix is not a directory.
[ENAMETOOLONG]
 | A component or an entire pathname exceeded 255 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 denied for the given flags.
[EACCES]
 | O_CREAT is specified, the file does not exist, and the directory in which it is to be created does not permit writing.
[ELOOP]
 | Too many symbolic links were encountered in translating the pathname(Not supported).
[EISDIR]
 | The named file is a directory, and the arguments specify it is to be opened for writing.
[EROFS]
 | The named file resides on a read-only file system, and the file is to be modified(Not supported).
[EMFILE]
 | The process has already reached its limit for open file descriptors.
[ENFILE]
 | The system file table is full.
[EMLINK]
 | O_NOFOLLOW was specified and the target is a symbolic link(Not supported).
[ENXIO]
 | The named file is a character special or block special file, and the device associated with this special file does not exist(Not supported).
[ENXIO]
 | The named file is a fifo, no process has it open for reading, and the arguments specify it is to be opened for writing.
[EINTR]
 | The open operation was interrupted by a signal(Not supported).
[EOPNOTSUPP]
 | O_SHLOCK or O_EXLOCK is specified but the underlying file system does not support locking(Not supported).
[EOPNOTSUPP]
 | The named file is a special file mounted through a file system that does not support access to it (e.g. NFS)(Not supported).
[EWOULDBLOCK]
 | O_NONBLOCK and one of O_SHLOCK or O_EXLOCK is specified and the file is locked(Not supported).
[ENOSPC]
 | O_CREAT is specified, the file does not exist, and the directory in which the entry for the new file is being placed cannot be extended because there is no space left on the file system containing the directory(Not implemented).
[ENOSPC]
 | O_CREAT is specified, the file does not exist, and there are no free inodes on the file system on which the file is being created.
[EDQUOT]
 | O_CREAT is specified, the file does not exist, and the directory in which the entry for the new file is being placed cannot be extended because the user’s quota of disk blocks on the file system containing the directory has been exhausted(Not supported).
[EDQUOT]
 | O_CREAT is specified, the file does not exist, and the user’s quota of inodes on the file system on which the file is being created has been exhausted(Not supported).
[EIO] | An I/O error occurred while making the directory entry or allocating the inode for O_CREAT.
[ETXTBSY]
 | The file is a pure procedure (shared text) file that is being executed and the open system call requests write access(Not supported).
[EFAULT]
 | The path argument 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 combination of O_RDONLY, O_WRONLY, and O_RDWR.

See also

 chmod, close, dup, getdtablesize, lseek, read, umask, write, fopen

Feedback

For additional information or queries on this page send feedback


opendir

Name

opendir, readdir, telldir, seekdir, rewinddir, closedir, dirfd
- directory operations

Library

 libc.lib

Synopsis
#include <sys/types.h>
#include <dirent.h>
DIR * opendir (const char *filename);
struct dirent * readdir (DIR *dirp);
int readdir_r (DIR *dirp, struct dirent *entry, struct dirent **result);
long telldir (DIR *dirp);
void seekdir (DIR *dirp, long loc);
void rewinddir (DIR *dirp);
int closedir (DIR *dirp);
int dirfd (DIR *dirp);

Return values

opendir function returns a pointer to the directory stream or NULL if an error occurred.

Detailed description

 The opendir function opens the directory named by filename, associates a directory stream with it and returns a pointer to be used to identify the directory stream in subsequent operations. The pointer NULL is returned if filename cannot be accessed, or if it cannot malloc enough memory to hold the whole thing.

The readdir function returns a pointer to the next directory entry. It returns NULL upon reaching the end of the directory or detecting an invalid seekdir operation.

The readdir_r function provides the same functionality as readdir, but the caller must provide a directory entry buffer to store the results in. If the read succeeds, result is pointed at the entry; upon reaching the end of the directory result is set to NULL. The readdir_r function returns 0 on success or an error number to indicate failure.

The telldir function returns the current location associated with the named directory stream. Values returned by telldir are good only for the lifetime of the DIR pointer, dirp, from which they are derived. If the directory is closed and then reopened, prior values returned by telldir will no longer be valid.

The seekdir function sets the position of the next readdir operation on the directory stream. The new position reverts to the one associated with the directory stream when the telldir operation was performed.

The rewinddir function resets the position of the named directory stream to the beginning of the directory.

The closedir function closes the named directory stream and frees the structure associated with the dirp pointer, returning 0 on success. On failure, -1 is returned and the global variable errno is set to indicate the error.

The dirfd function returns the integer file descriptor associated with the named directory stream, see open.

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;

Examples

/*************************************************************************************************************
* Detailed description: This test code demonstrates usage of opendir system call, open directory name test.
*
* Preconditions: Expects Test directory to be present in the current working directory.
**************************************************************************************************************/
 #include <sys/types.h>
 #include <dirent.h>
int main()
{
  DIR *DirHandle;
  if(!(DirHandle = opendir("Test") ) )
  {
     printf("Failed to open directory Test\n");
     return -1;
  }
  printf("Directory Test opened \n");
  return 0;
}

Output

Directory Test opened

See also

 close, lseek, open, rea

Feedback

For additional information or queries on this page send feedback


OpenSSL_add_all_digests - add algorithms to internal table

Name

OpenSSL_add_all_algorithms, OpenSSL_add_all_ciphers
OpenSSL_add_all_digests

add algorithms to internal table

Library

libcrypto.lib

Synopsis

#include <openssl/evp.h>
void OpenSSL_add_all_algorithms(void);
void OpenSSL_add_all_ciphers(void);
void OpenSSL_add_all_digests(void);
void EVP_cleanup(void);

Detailed Description

OpenSSL keeps an internal table of digest algorithms and ciphers. It uses this table to lookup ciphers via functions such as EVP_get_cipher_byname().

OpenSSL_add_all_digests() adds all digest algorithms to the table.

OpenSSL_add_all_algorithms() adds all algorithms to the table (digests and ciphers).

OpenSSL_add_all_ciphers() adds all encryption algorithms to the table including password based encryption algorithms.

EVP_cleanup() removes all ciphers and digests from the table.

Return Values

None of the functions return a value.

Notes

A typical application will call OpenSSL_add_all_algorithms() initially and EVP_cleanup() before exiting.

An application does not need to add algorithms to use them explicitly, for example by EVP_sha1(). It just needs to add them if it (or any of the functions it calls) needs to lookup algorithms.

The cipher and digest lookup functions are used in many parts of the library. If the table is not initialized several functions will misbehave and complain they cannot find algorithms. This includes the PEM, PKCS#12, SSL and S/MIME libraries. This is a common query in the OpenSSL mailing lists.

Calling OpenSSL_add_all_algorithms() links in all algorithms: as a result a statically linked executable can be quite large. If this is important it is possible to just add the required ciphers and digests.

Bugs

Although the functions do not return error codes it is possible for them to fail. This will only happen as a result of a memory allocation failure so this is not too much of a problem in practice.

See Also

evp(),
EVP_DigestInit(),
EVP_EncryptInit()

Feedback

For additional information or queries on this page send feedback


OPENSSL_Applink - glue between OpenSSL BIO and Win32 compiler run-time

Name

OPENSSL_Applink — glue between OpenSSL BIO and Win32 compiler run-time

Library

libcrypto.lib

Synopsis

__declspec(dllexport) void **OPENSSL_Applink();

Detailed Description

OPENSSL_Applink is application-side interface which provides a glue between OpenSSL BIO layer and Win32 compiler run-time environment. Even though it appears at application side, it's essentially OpenSSL private interface. For this reason application developers are not expected to implement it, but to compile provided module with compiler of their choice and link it into the target application. The referred module is available as <openssl>/ms/applink.c.

Feedback

For additional information or queries on this page send feedback


OPENSSL_no_config - simple OpenSSL configuration functions

Name

OPENSSL_config, OPENSSL_no_config — simple OpenSSL configuration functions

Library

libcrypto.lib

Synopsis

#include <openssl/conf.h>
void OPENSSL_config(const char *config_name);
void OPENSSL_no_config(void);

Detailed Description

OPENSSL_config() configures OpenSSL using the standard openssl.cnf configuration file name using config_name. If config_name is NULL then the default name openssl_conf will be used. Any errors are ignored. Further calls to OPENSSL_config() will have no effect. The configuration file format is documented in the conf() manual page.

OPENSSL_no_config() disables configuration. If called before OPENSSL_config() no configuration takes place.

Notes

It is strongly recommended that all new applications call OPENSSL_config() or the more sophisticated functions such as CONF_modules_load() during initialization (that is before starting any threads). By doing this an application does not need to keep track of all configuration options and some new functionality can be supported automatically.

It is also possible to automatically call OPENSSL_config() when an application calls OPENSSL_add_all_algorithms() by compiling an application with the preprocessor symbol OPENSSL_LOAD_CONF #define'd. In this way configuration can be added without source changes.

The environment variable OPENSSL_CONF can be set to specify the location of the configuration file.

Currently ASN1 OBJECTs and ENGINE configuration can be performed future
versions of OpenSSL will add new configuration options.

There are several reasons why calling the OpenSSL configuration routines is advisable. For example new ENGINE functionality was added to OpenSSL 0.9.7. In OpenSSL 0.9.7 control functions can be supported by ENGINEs, this can be used (among other things) to load dynamic ENGINEs from shared libraries (DSOs). However very few applications currently support the control interface and so very few can load and use dynamic ENGINEs. Equally in future more sophisticated ENGINEs will require certain control operations to customize them. If an application calls OPENSSL_config() it doesn't need to know or care about ENGINE control operations because they can be performed by editing a configuration file.

Applications should free up configuration at application closedown by calling CONF_modules_free().

Restrictions

The OPENSSL_config() function is designed to be a very simple "call it and forget it'' function. As a result its behaviour is somewhat limited. It ignores all errors silently and it can only load from the standard configuration file location for example.

It is however much better than nothing. Applications which need finer control over their configuration functionality should use the configuration functions such as CONF_load_modules() directly.

Return Values

Neither OPENSSL_config() nor OPENSSL_no_config() return a value.

See Also

conf(),
CONF_modules_load_file(),
CONF_modules_free()

History

OPENSSL_config() and OPENSSL_no_config() first appeared in OpenSSL 0.9.7

Feedback

For additional information or queries on this page send feedback


OPENSSL_ia32cap - finding the IA-32 processor capabilities

Name

OPENSSL_ia32cap — finding the IA-32 processor capabilities

Library

libcrypto.lib

Synopsis

unsigned long *OPENSSL_ia32cap_loc(void);
#define OPENSSL_ia32cap (*(OPENSSL_ia32cap_loc()))

Detailed Description

Value returned by OPENSSL_ia32cap_loc() is address of a variable containing IA-32 processor capabilities bit vector as it appears in EDX register after executing CPUID instruction with EAX=1 input value (see Intel Application Note #241618). Naturally it's meaningful on IA-32[E] platforms only. The variable is normally set up automatically upon toolkit initialization, but can be manipulated afterwards to modify crypto library behaviour. For the moment of this writing three bits are significant, namely bit #28 denoting Hyperthreading, which is used to distinguish Intel P4 core, bit #26 denoting SSE2 support, and bit #4 denoting presence of Time-Stamp Counter. Clearing bit #26 at run-time for example disables high-performance SSE2 code present in the crypto library. Do this if the target OpenSSL application is executed on SSE2 capable CPU, but under control of OS which does not support SSE2 extensions. Even though the value can be manipulated programmatically, it is more appropriate to set up an environment variable with the same name prior starting target application, e.g. 'env OPENSSL_ia32cap=0x10 apps/openssl', to achieve same effect without modifying the application source code. Alternatively, reconfigure the toolkit with no-sse2 option and recompile.

Feedback

For additional information or queries on this page send feedback.


OPENSSL_load_builtin_modules - add standard configuration modules

Name

OPENSSL_load_builtin_modules

Library

libcrypto.lib

Synopsis

#include <openssl/conf.h>
void OPENSSL_load_builtin_modules(void);
void ASN1_add_oid_module(void);
ENGINE_add_conf_module();

Detailed Description

The function OPENSSL_load_builtin_modules() adds all the standard OpenSSL configuration modules to the internal list. They can then be used by the OpenSSL configuration code.

ASN1_add_oid_module() adds just the ASN1 OBJECT module.

ENGINE_add_conf_module() adds just the ENGINE configuration module.

Notes

If the simple configuration function OPENSSL_config() is called then OPENSSL_load_builtin_modules() is called automatically.

Applications which use the configuration functions directly will need to call OPENSSL_load_builtin_modules() themselves before any other configuration code.

Applications should call OPENSSL_load_builtin_modules() to load all configuration modules instead of adding modules selectively: otherwise functionality may be missing from the application if an when new modules are added.

Return Values

None of the functions return a value.

See Also

conf(), OPENSSL_config()

History

These functions first appeared in OpenSSL 0.9.7.

Feedback

For additional information or queries on this page send feedback


SSLeay_version - get OpenSSL version number

Name

OPENSSL_VERSION_NUMBER, SSLeay
SSLeay_version

gets OpenSSL version number

Library

libcrypto.lib

Synopsis

#include <openssl/opensslv.h>
#define OPENSSL_VERSION_NUMBER 0xnnnnnnnnnL
#include <openssl/crypto.h>
long SSLeay(void);
const char *SSLeay_version(int t);

Detailed Description

OPENSSL_VERSION_NUMBER is a numeric release version identifier:

 MMNNFFPPS: major minor fix patch status

The status nibble has one of the values 0 for development, 1 to e for betas 1 to 14, and f for release.

for example

 0x000906000 == 0.9.6 dev
 0x000906023 == 0.9.6b beta 3
 0x00090605f == 0.9.6e release

Versions prior to 0.9.3 have identifiers < 0x0930. Versions between 0.9.3 and 0.9.5 had a version identifier with this interpretation:

 MMNNFFRBB major minor fix final beta/patch

for example

 0x000904100 == 0.9.4 release
 0x000905000 == 0.9.5 dev

Version 0.9.5a had an interim interpretation that is like the current one, except the patch level got the highest bit set, to keep continuity. The number was therefore 0x0090581f.

For backward compatibility, SSLEAY_VERSION_NUMBER is also defined.

SSLeay() returns this number. The return value can be compared to the macro to make sure that the correct version of the library has been loaded, especially when using DLLs on Windows systems.

SSLeay_version() returns different strings depending on t:

SSLEAY_VERSION
The text variant of the version number and the release date. For example, ``OpenSSL 0.9.5a 1 Apr 2000''.

SSLEAY_CFLAGS
The compiler flags set for the compilation process in the form ``compiler: ...'' if available or ``compiler: information not available'' otherwise.

SSLEAY_BUILT_ON
The date of the build process in the form ``built on: ...'' if available or ``built on: date not available'' otherwise.

SSLEAY_PLATFORM
The ``Configure'' target of the library build in the form ``platform: ...'' if available or ``platform: information not available'' otherwise.

SSLEAY_DIR
The "OPENSSLDIR'' setting of the library build in the form "OPENSSLDIR: ''...'' if available or ``OPENSSLDIR: N/A'' otherwise.

For an unknown t, the text "not available'' is returned.

Return Values

The version number.

See Also

crypto()

History

SSLeay() and SSLEAY_VERSION_NUMBER are available in all versions of SSLeay and OpenSSL. OPENSSL_VERSION_NUMBER is available in all versions of OpenSSL. SSLEAY_DIR was added in OpenSSL 0.9.7.

Feedback

For additional information or queries on this page send feedback


pathconf

Name

pathconf, fpathconf
- get configurable pathname variables

Library

 libc.lib

Synopsis
#include <unistd.h>
long pathconf (const char *path, int name);
long fpathconf (int fd, int name);

Return values

 If the call to pathconf or fpathconf is not successful, -1 is returned and errno is set appropriately. Otherwise, if the variable is associated with functionality that does not have a limit in the system, -1 is returned and errno is not modified. Otherwise, the current variable value is returned.

Detailed description

 The pathconf and fpathconf system calls provide a method for applications to determine the current value of a configurable system limit or option variable associated with a pathname or file descriptor.

For pathconf, the path argument is the name of a file or directory. For fpathconf, the fd argument is an open file descriptor. The name argument specifies the system variable to be queried. Symbolic constants for each name value are found in the include file <unistd.h>.

The available 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 available in 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 a pipe.
_PC_CHOWN_RESTRICTED
 | Return 1 if appropriate privilege is required for the chown system call, otherwise 0. -p1003.1-2001 requires appropriate privilege in all cases, but this behavior was optional in prior editions of the standard.
_PC_NO_TRUNC
 | Return greater than zero if attempts to use pathname components longer than .Brq Dv NAME_MAX will result in an [ENAMETOOLONG] error; otherwise, such components will be truncated to .Brq Dv NAME_MAX. -p1003.1-2001 requires the error in all cases, but this behavior was optional in prior editions of the standard, and some non- POSIX -compliant file systems do not support this behavior.
_PC_VDISABLE
 | Returns the terminal character disabling value.
_PC_ASYNC_IO
 | Return 1 if asynchronous I/O is supported, otherwise 0.
_PC_PRIO_IO
 | Returns 1 if prioritised I/O is supported for this file, otherwise 0.
_PC_SYNC_IO
 | Returns 1 if synchronised I/O is supported for this file, otherwise 0.
_PC_ALLOC_SIZE_MIN
 | Minimum number of bytes of storage allocated for any portion of a file.
_PC_FILESIZEBITS
 | Number of bits needed to represent the maximum file size.
_PC_REC_INCR_XFER_SIZE
 | Recommended increment for file transfer sizes between _PC_REC_MIN_XFER_SIZE and _PC_REC_MAX_XFER_SIZE.
_PC_REC_MAX_XFER_SIZE
 | Maximum recommended file transfer size.
_PC_REC_MIN_XFER_SIZE
 | Minimum recommended file transfer size.
_PC_REC_XFER_ALIGN
 | Recommended file transfer buffer alignment.
_PC_SYMLINK_MAX
 | Maximum number of bytes in a symbolic link.
_PC_ACL_EXTENDED
 | Returns 1 if an Access Control List (ACL) can be set on the specified file, otherwise 0.
_PC_ACL_PATH_MAX
 | Maximum number of ACL entries per file.
_PC_CAP_PRESENT
 | Returns 1 if a capability state can be set on the specified file, otherwise 0.
_PC_INF_PRESENT
 | Returns 1 if an information label can be set on the specified file, otherwise 0.
_PC_MAC_PRESENT
 | Returns 1 if a Mandatory Access Control (MAC) label can be set on the specified file, otherwise 0.

Examples

#include<unistd.h>
#include<stdio.h>
int test_pathconf()
{
   int fp = open("test_pathconf1.txt", O_RDWR|O_CREAT);
   if(fp != -1)
   {
     int n = pathconf("test_pathconf1.txt", _PC_LINK_MAX);
     if( n < _POSIX_LINK_MAX )
     {
       return -1;
     }
     else
     {
       printf("_PC_LINK_MAX value: %d", n);
       printf("Pathconf passed");
       return 0;
     }
   }
   else
   {
     printf("failed");
     return -1;
   }
}

Output

_PC_LINK_MAX value: 1
Pathconf passed

Errors

 If any of the following conditions occur, the pathconf and fpathconf system calls shall 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 variable name with the associated file.

The pathconf system call will fail if:
[ENOTDIR]
 | A component of the path prefix is not a directory.
[ENAMETOOLONG]
 | A component of a pathname exceeded .Brq Dv NAME_MAX characters (but see _PC_NO_TRUNC above), or an entire path name exceeded .Brq Dv PATH_MAX 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 pathname.
[EIO] | An I/O error occurred while reading from or writing to the file system.

The fpathconf system call will fail if:
[EBADF]
 | The fd argument is not a valid open file descriptor.
[EIO] | An I/O error occurred while reading from or writing to the file system.

See also
The pathconf and fpathconf system calls first appeared in BSD 4.4.

Note

 The current implementation of the functions pathconf and fpathconf considers only the following configurable variables.
_PC_LINK_MAX
_PC_MAX_CANON
_PC_MAX_INPUT
_PC_NAME_MAX
_PC_PATH_MAX
_PC_PIPE_BUF
_PC_CHOWN_RESTRICTED
_PC_NO_TRUNC
_PC_VDISABLE

Also, these functions return the limits as required by the POSIX standard instead of the actual system limits determined on the run.

Feedback

For additional information or queries on this page send feedback


PEM - PEM routines

Name

PEM — Reads or writes structures in PEM format

Library

libcrypto.lib

Synopsis

#include <openssl/pem.h>
EVP_PKEY *PEM_read_bio_PrivateKey(BIO *bp, EVP_PKEY **x, pem_password_cb *cb, void *u);
EVP_PKEY *PEM_read_PrivateKey(FILE *fp, EVP_PKEY **x, pem_password_cb *cb, void *u);
int PEM_write_bio_PrivateKey(BIO *bp, EVP_PKEY *x, const EVP_CIPHER *enc, unsigned char *kstr, int klen,
                             pem_password_cb *cb, void *u);
int PEM_write_PrivateKey(FILE *fp, EVP_PKEY *x, const EVP_CIPHER *enc, unsigned char *kstr, int klen,
                         pem_password_cb *cb, void *u);
int PEM_write_bio_PKCS8PrivateKey(BIO *bp, EVP_PKEY *x, const EVP_CIPHER *enc, char *kstr, int klen, pem_password_cb *cb, void *u);
int PEM_write_PKCS8PrivateKey(FILE *fp, EVP_PKEY *x, const EVP_CIPHER *enc, char *kstr, int klen, pem_password_cb *cb, void *u);
int PEM_write_bio_PKCS8PrivateKey_nid(BIO *bp, EVP_PKEY *x, int nid, char *kstr, int klen, pem_password_cb *cb, void *u);
int PEM_write_PKCS8PrivateKey_nid(FILE *fp, EVP_PKEY *x, int nid, char *kstr, int klen, pem_password_cb *cb, void *u);
EVP_PKEY *PEM_read_bio_PUBKEY(BIO *bp, EVP_PKEY **x, pem_password_cb *cb, void *u);
EVP_PKEY *PEM_read_PUBKEY(FILE *fp, EVP_PKEY **x, pem_password_cb *cb, void *u);
int PEM_write_bio_PUBKEY(BIO *bp, EVP_PKEY *x);
int PEM_write_PUBKEY(FILE *fp, EVP_PKEY *x);
RSA *PEM_read_bio_RSAPrivateKey(BIO *bp, RSA **x, pem_password_cb *cb, void *u);
RSA *PEM_read_RSAPrivateKey(FILE *fp, RSA **x, pem_password_cb *cb, void *u);
int PEM_write_bio_RSAPrivateKey(BIO *bp, RSA *x, const EVP_CIPHER *enc, unsigned char *kstr, int klen, pem_password_cb *cb, void *u);
int PEM_write_RSAPrivateKey(FILE *fp, RSA *x, const EVP_CIPHER *enc, unsigned char *kstr, int klen, pem_password_cb *cb, void *u);
RSA *PEM_read_bio_RSAPublicKey(BIO *bp, RSA **x, pem_password_cb *cb, void *u);
RSA *PEM_read_RSAPublicKey(FILE *fp, RSA **x, pem_password_cb *cb, void *u);
int PEM_write_bio_RSAPublicKey(BIO *bp, RSA *x);
int PEM_write_RSAPublicKey(FILE *fp, RSA *x);
RSA *PEM_read_bio_RSA_PUBKEY(BIO *bp, RSA **x, pem_password_cb *cb, void *u);
RSA *PEM_read_RSA_PUBKEY(FILE *fp, RSA **x, pem_password_cb *cb, void *u);
int PEM_write_bio_RSA_PUBKEY(BIO *bp, RSA *x);
int PEM_write_RSA_PUBKEY(FILE *fp, RSA *x);
DSA *PEM_read_bio_DSAPrivateKey(BIO *bp, DSA **x, pem_password_cb *cb, void *u);
DSA *PEM_read_DSAPrivateKey(FILE *fp, DSA **x, pem_password_cb *cb, void *u);
int PEM_write_bio_DSAPrivateKey(BIO *bp, DSA *x, const EVP_CIPHER *enc, unsigned char *kstr, int klen,
                                pem_password_cb *cb, void *u);
int PEM_write_DSAPrivateKey(FILE *fp, DSA *x, const EVP_CIPHER *enc, unsigned char *kstr, int klen, pem_password_cb *cb, void *u);
DSA *PEM_read_bio_DSA_PUBKEY(BIO *bp, DSA **x, pem_password_cb *cb, void *u);
DSA *PEM_read_DSA_PUBKEY(FILE *fp, DSA **x, pem_password_cb *cb, void *u);
int PEM_write_bio_DSA_PUBKEY(BIO *bp, DSA *x);
int PEM_write_DSA_PUBKEY(FILE *fp, DSA *x);
DSA *PEM_read_bio_DSAparams(BIO *bp, DSA **x, pem_password_cb *cb, void *u);
DSA *PEM_read_DSAparams(FILE *fp, DSA **x, pem_password_cb *cb, void *u);
int PEM_write_bio_DSAparams(BIO *bp, DSA *x);
int PEM_write_DSAparams(FILE *fp, DSA *x);
DH *PEM_read_bio_DHparams(BIO *bp, DH **x, pem_password_cb *cb, void *u);
DH *PEM_read_DHparams(FILE *fp, DH **x, pem_password_cb *cb, void *u);
int PEM_write_bio_DHparams(BIO *bp, DH *x);
int PEM_write_DHparams(FILE *fp, DH *x);
X509 *PEM_read_bio_X509(BIO *bp, X509 **x, pem_password_cb *cb, void *u);
X509 *PEM_read_X509(FILE *fp, X509 **x, pem_password_cb *cb, void *u);
int PEM_write_bio_X509(BIO *bp, X509 *x);
int PEM_write_X509(FILE *fp, X509 *x);
X509 *PEM_read_bio_X509_AUX(BIO *bp, X509 **x, pem_password_cb *cb, void *u);
X509 *PEM_read_X509_AUX(FILE *fp, X509 **x, pem_password_cb *cb, void *u);
int PEM_write_bio_X509_AUX(BIO *bp, X509 *x);
int PEM_write_X509_AUX(FILE *fp, X509 *x);
X509_REQ *PEM_read_bio_X509_REQ(BIO *bp, X509_REQ **x, pem_password_cb *cb, void *u);
X509_REQ *PEM_read_X509_REQ(FILE *fp, X509_REQ **x, pem_password_cb *cb, void *u);
int PEM_write_bio_X509_REQ(BIO *bp, X509_REQ *x);
int PEM_write_X509_REQ(FILE *fp, X509_REQ *x);
int PEM_write_bio_X509_REQ_NEW(BIO *bp, X509_REQ *x);
int PEM_write_X509_REQ_NEW(FILE *fp, X509_REQ *x);
X509_CRL *PEM_read_bio_X509_CRL(BIO *bp, X509_CRL **x, pem_password_cb *cb, void *u);
X509_CRL *PEM_read_X509_CRL(FILE *fp, X509_CRL **x, pem_password_cb *cb, void *u);
int PEM_write_bio_X509_CRL(BIO *bp, X509_CRL *x);
int PEM_write_X509_CRL(FILE *fp, X509_CRL *x);
PKCS7 *PEM_read_bio_PKCS7(BIO *bp, PKCS7 **x, pem_password_cb *cb, void *u);
PKCS7 *PEM_read_PKCS7(FILE *fp, PKCS7 **x, pem_password_cb *cb, void *u);
int PEM_write_bio_PKCS7(BIO *bp, PKCS7 *x);
int PEM_write_PKCS7(FILE *fp, PKCS7 *x);
NETSCAPE_CERT_SEQUENCE *PEM_read_bio_NETSCAPE_CERT_SEQUENCE(BIO *bp, NETSCAPE_CERT_SEQUENCE **x, pem_password_cb *cb, void *u);
NETSCAPE_CERT_SEQUENCE *PEM_read_NETSCAPE_CERT_SEQUENCE(FILE *fp, NETSCAPE_CERT_SEQUENCE **x, pem_password_cb *cb, void *u);
int PEM_write_bio_NETSCAPE_CERT_SEQUENCE(BIO *bp, NETSCAPE_CERT_SEQUENCE *x);
int PEM_write_NETSCAPE_CERT_SEQUENCE(FILE *fp, NETSCAPE_CERT_SEQUENCE *x);

Detailed Description

The PEM functions read or write structures in PEM format. In this sense PEM format is simply base64 encoded data surrounded by header lines.

For more details about the meaning of arguments see the PEM FUNCTION ARGUMENTS section.

Each operation has four functions associated with it. For
clarity the term ``foobar functions'' will be used to collectively
refer to the PEM_read_bio_foobar(), PEM_read_foobar(),

PEM_write_bio_foobar() and
 PEM_write_foobar() functions.

The PrivateKey functions read or write a private key in PEM format using an EVP_PKEY structure. The write routines use ``traditional'' private key format and can handle both RSA and DSA private keys. The read functions can additionally transparently handle PKCS#8 format encrypted and unencrypted keys too.

PEM_write_bio_PKCS8PrivateKey() and PEM_write_PKCS8PrivateKey() write a private key in an EVP_PKEY structure in PKCS#8 EncryptedPrivateKeyInfo format using PKCS#5 v2.0 password based encryption algorithms. The cipher argument specifies the encryption algorithm to use: unlike all other PEM routines the encryption is applied at the PKCS#8 level and not in the PEM headers. If cipher is NULL then no encryption is used and a PKCS#8 PrivateKeyInfo structure is used instead.

PEM_write_bio_PKCS8PrivateKey_nid() and PEM_write_PKCS8PrivateKey_nid() also write out a private key as a PKCS#8 EncryptedPrivateKeyInfo however it uses PKCS#5 v1.5 or PKCS#12 encryption algorithms instead. The algorithm to use is specified in the nid parameter and should be the NID of the corresponding OBJECT IDENTIFIER (see NOTES section).

The PUBKEY functions process a public key using an EVP_PKEY structure. The public key is encoded as a SubjectPublicKeyInfo structure.

The RSAPrivateKey functions process an RSA private key using an RSA structure. It handles the same formats as the PrivateKey functions but an error occurs if the private key is not RSA.

The RSAPublicKey functions process an RSA public key using an RSA structure. The public key is encoded using a PKCS#1 RSAPublicKey structure.

The RSA_PUBKEY functions also process an RSA public key using an RSA structure. However the public key is encoded using a SubjectPublicKeyInfo structure and an error occurs if the public key is not RSA.

The DSAPrivateKey functions process a DSA private key using a DSA structure. It handles the same formats as the PrivateKey functions but an error occurs if the private key is not DSA.

The DSA_PUBKEY functions process a DSA public key using a DSA structure. The public key is encoded using a SubjectPublicKeyInfo structure and an error occurs if the public key is not DSA.

The DSAparams functions process DSA parameters using a DSA structure. The parameters are encoded using a foobar structure.

The DHparams functions process DH parameters using a DH structure. The parameters are encoded using a PKCS#3 DHparameter structure.

The X509 functions process an X509 certificate using an X509 structure. They will also process a trusted X509 certificate but any trust settings are discarded.

The X509_AUX functions process a trusted X509 certificate using an X509 structure.

The X509_REQ and X509_REQ_NEW functions process a PKCS#10 certificate request using an X509_REQ structure. The X509_REQ write functions use CERTIFICATE REQUEST in the header whereas the X509_REQ_NEW functions use NEW CERTIFICATE REQUEST (as required by some CAs). The X509_REQ read functions will handle either form so there are no X509_REQ_NEW read functions.

The X509_CRL functions process an X509 CRL using an X509_CRL structure.

The PKCS7 functions process a PKCS#7 ContentInfo using a PKCS7 structure.

The NETSCAPE_CERT_SEQUENCE functions process a Netscape Certificate Sequence using a NETSCAPE_CERT_SEQUENCE structure.

Examples

Although the PEM routines take several arguments in almost all applications most of them are set to 0 or NULL.

Read a certificate in PEM format from a BIO:

 X509 *x;
 x = PEM_read_bio_X509(bp, NULL, 0, NULL);
 if (x == NULL)
        {
        /* Error */
        }

Alternative method:

 X509 *x = NULL;
 if (!PEM_read_bio_X509(bp, &x, 0, NULL))
        {
        /* Error */
        }

Write a certificate to a BIO:

 if (!PEM_write_bio_X509(bp, x))
        {
        /* Error */
        }

Write an unencrypted private key to a FILE pointer:

 if (!PEM_write_PrivateKey(fp, key, NULL, NULL, 0, 0, NULL))
        {
        /* Error */
        }

Write a private key (using traditional format) to a BIO using triple DES encryption, the pass phrase is prompted for:

 if (!PEM_write_bio_PrivateKey(bp, key, EVP_des_ede3_cbc(), NULL, 0, 0, NULL))
        {
        /* Error */
        }

Write a private key (using PKCS#8 format) to a BIO using triple DES encryption, using the pass phrase ``hello'':

 if (!PEM_write_bio_PKCS8PrivateKey(bp, key, EVP_des_ede3_cbc(), NULL, 0, 0, "hello"))
        {
        /* Error */
        }

Read a private key from a BIO using the pass phrase ``hello'':

 key = PEM_read_bio_PrivateKey(bp, NULL, 0, "hello");
 if (key == NULL)
        {
        /* Error */
        }

Read a private key from a BIO using a pass phrase callback:

 key = PEM_read_bio_PrivateKey(bp, NULL, pass_cb, "My Private Key");
 if (key == NULL)
        {
        /* Error */
        }

Skeleton pass phrase callback:

 int pass_cb(char *buf, int size, int rwflag, void *u);
        {
        int len;
        char *tmp;
        /* We'd probably do something else if 'rwflag' is 1 */
        printf("Enter pass phrase for \"%s\"\n", u);
        /* get pass phrase, length 'len' into 'tmp' */
        tmp = "hello";
        len = strlen(tmp);
        if (len <= 0) return 0;
        /* if too long, truncate */
        if (len > size) len = size;
        memcpy(buf, tmp, len);
        return len;
        }

PEM Function Arguments

The PEM functions have many common arguments.

The bp BIO parameter (if present) specifies the BIO to read from or write to.

The fp FILE parameter (if present) specifies the FILE pointer to read from or write to.

The PEM read functions all take an argument TYPE **x and return a TYPE * pointer. Where TYPE is whatever structure the function uses. If x is NULL then the parameter is ignored. If x is not NULL but *x is NULL then the structure returned will be written to *x. If neither x nor *x is NULL then an attempt is made to reuse the structure at *x (but see BUGS and EXAMPLES sections). Irrespective of the value of x a pointer to the structure is always returned (or NULL if an error occurred).

The PEM functions which write private keys take an enc parameter which specifies the encryption algorithm to use, encryption is done at the PEM level. If this parameter is set to NULL then the private key is written in unencrypted form.

The cb argument is the callback to use when querying for the pass phrase used for encrypted PEM structures (normally only private keys).

For the PEM write routines if the kstr parameter is not NULL then klen bytes at kstr are used as the passphrase and cb is ignored.

If the cb parameters is set to NULL and the u parameter is not NULL then the u parameter is interpreted as a null terminated string to use as the passphrase. If both cb and u are NULL then the default callback routine is used which will typically prompt for the passphrase on the current terminal with echoing turned off.

The default passphrase callback is sometimes inappropriate (for example in a GUI application) so an alternative can be supplied. The callback routine has the following form:

 int cb(char *buf, int size, int rwflag, void *u);

buf is the buffer to write the passphrase to. size is the maximum length of the passphrase (i.e. the size of buf). rwflag is a flag which is set to 0 when reading and 1 when writing. A typical routine will ask the user to verify the passphrase (for example by prompting for it twice) if rwflag is 1. The u parameter has the same value as the u parameter passed to the PEM routine. It allows arbitrary data to be passed to the callback by the application (for example a window handle in a GUI application). The callback must return the number of characters in the passphrase or 0 if an error occurred.

Notes

The old PrivateKey write routines are retained for compatibility. New applications should write private keys using the PEM_write_bio_PKCS8PrivateKey() or PEM_write_PKCS8PrivateKey() routines because they are more secure (they use an iteration count of 2048 whereas the traditional routines use a count of 1) unless compatibility with older versions of OpenSSL is important.

The PrivateKey read routines can be used in all applications because they handle all formats transparently.

A frequent cause of problems is attempting to use the PEM routines like this:

 X509 *x;
 PEM_read_bio_X509(bp, &x, 0, NULL);

this is a bug because an attempt will be made to reuse the data at x which is an uninitialized pointer.

PEM Encryption Format

This old PrivateKey routines use a non standard technique for encryption.

The private key (or other data) takes the following form:

 -----BEGIN RSA PRIVATE KEY-----
 Proc-Type: 4,ENCRYPTED
 DEK-Info: DES-EDE3-CBC,3F17F5316E2BAC89
 ...base64 encoded data...
 -----END RSA PRIVATE KEY-----

The line beginning DEK-Info contains two comma separated pieces of information: the encryption algorithm name as used by EVP_get_cipherbyname() and an 8 byte salt encoded as a set of hexadecimal digits.

After this is the base64 encoded encrypted data.

The encryption key is determined using EVP_bytestokey(), using salt and an iteration count of 1. The IV used is the value of salt and *not* the IV returned by EVP_bytestokey().

Bugs

The PEM read routines in some versions of OpenSSL will not correctly reuse an existing structure. Therefore the following:

 PEM_read_bio_X509(bp, &x, 0, NULL);

where x already contains a valid certificate, may not work, whereas:

 X509_free(x);
 x = PEM_read_bio_X509(bp, NULL, 0, NULL);

is guaranteed to work.

Return Codes

The read routines return either a pointer to the structure read or NULL if an error occurred.

The write routines return 1 for success or 0 for failure.

Feedback

For additional information or queries on this page send feedback


pipe

Name

pipe - create a pipe

Library

 libc.lib

Synopsis
#include <unistd.h>
int pipe (int *fildes);

Return values

 The pipe function returns the value 0 if successful; otherwise the value -1 is returned and errno is set to indicate the error.

Detailed description

 The pipe system call creates a pipe, which is an object allowing bidirectional data flow, and allocates a pair of file descriptors.

By convention, the first descriptor is normally used as the read end of the pipe, and the second is normally the write end, so that data written to fildes[1] appears on (i.e., can be read from) fildes[0]. This allows the output of one thread to be sent to another thread: the source’s standard output is set up to be the write end of the pipe, and the sink’s standard input is set up to be the read end of the pipe. The pipe itself persists until all its associated descriptors are closed.

A pipe that has had an end closed is considered widowed. Writing on such a pipe causes the writing process to fail and errno is set to EPIPE Widowing a pipe is the only way to deliver end-of-file to a reader: after the reader consumes any buffered data, reading a widowed pipe returns a zero count.

Examples

#include <unistd.h>
#include <stdio.h>

int main(void)
{
    int fds[2];
    if (pipe(fds) == -1) {
       printf("Pipe creation failed\n");
    }
    /* fds[0] - opened for read */
    /* fds[1] - opened for write */
    close(fds[0]);
    close(fds[1]);
    return 0;
}

Errors

 The pipe system call will fail if:
[EMFILE]
 | Too many descriptors are active.
[ENFILE]
 | The system file table is full.

See also

 read, write

Feedback

For additional information or queries on this page send feedback


PKCS7_decrypt - decrypt content from a PKCS#7 envelopedData structure

Name

PKCS7_decrypt — decrypt content from a PKCS#7 envelopedData structure

Library

libcrypto.lib

Synopsis

int PKCS7_decrypt(PKCS7 *p7, EVP_PKEY *pkey, X509 *cert, BIO *data, int flags);

Detailed Description

PKCS7_decrypt() extracts and decrypts the content from a PKCS#7 envelopedData structure. pkey is the private key of the recipient, cert is the recipients certificate, data is a BIO to write the content to and flags is an optional set of flags.

Notes

OpenSSL_add_all_algorithms() (or equivalent) should be called before using this function or errors about unknown algorithms will occur.

Although the recipients certificate is not needed to decrypt the data it is needed to locate the appropriate (of possible several) recipients in the PKCS#7 structure.

The following flags can be passed in the flags parameter.

If the PKCS7_TEXT flag is set MIME headers for type text/plain are deleted from the content. If the content is not of type text/plain then an error is returned.

Return Values

PKCS7_decrypt() returns either 1 for success or 0 for failure. The error can be obtained from ERR_get_error()

Bugs

PKCS7_decrypt() must be passed the correct recipient key and certificate. It would be better if it could look up the correct key and certificate from a database.

The lack of single pass processing and need to hold all data in memory as mentioned in PKCS7_sign() also applies to PKCS7_verify().

See Also

ERR_get_error(), PKCS7_encrypt()

History

PKCS7_decrypt() was added to OpenSSL 0.9.5

Feedback

For additional information or queries on this page send feedback


PKCS7_encrypt - create a PKCS#7 envelopedData structure

Name

PKCS7_encrypt — creates and returns a PKCS#7 envelopedData structure

Library

libcrypto.lib

Synopsis

PKCS7 *PKCS7_encrypt(STACK_OF(X509) *certs, BIO *in, const EVP_CIPHER *cipher, int flags);

Detailed Description

PKCS7_encrypt() creates and returns a PKCS#7 envelopedData structure. certs is a list of recipient certificates. in is the content to be encrypted. cipher is the symmetric cipher to use. flags is an optional set of flags.

Notes

Only RSA keys are supported in PKCS#7 and envelopedData so the recipient certificates supplied to this function must all contain RSA public keys, though they do not have to be signed using the RSA algorithm.

EVP_des_ede3_cbc() (triple DES) is the algorithm of choice for S/MIME use because most clients will support it.

Some old ``export grade'' clients may only support weak encryption using 40 or 64 bit RC2. These can be used by passing EVP_rc2_40_cbc() and EVP_rc2_64_cbc() respectively.

The algorithm passed in the cipher parameter must support ASN1 encoding of its parameters.

Many browsers implement a ``sign and encrypt'' option which is simply an S/MIME envelopedData containing an S/MIME signed message. This can be readily produced by storing the S/MIME signed message in a memory BIO and passing it to PKCS7_encrypt().

The following flags can be passed in the flags parameter.

If the PKCS7_TEXT flag is set MIME headers for type text/plain are prepended to the data.

Normally the supplied content is translated into MIME canonical format (as required by the S/MIME specifications) if PKCS7_BINARY is set no translation occurs. This option should be used if the supplied data is in binary format otherwise the translation will corrupt it. If PKCS7_BINARY is set then PKCS7_TEXT is ignored.

Return Values

PKCS7_encrypt() returns either a valid PKCS7 structure or NULL if an error occurred. The error can be obtained from ERR_get_error().

Bugs

The lack of single pass processing and need to hold all data in memory as mentioned in PKCS7_sign() also applies to PKCS7_verify().

See Also

ERR_get_error(), PKCS7_decrypt()

History

PKCS7_decrypt() was added to OpenSSL 0.9.5

Feedback

For additional information or queries on this page send feedback


PKCS7_sign - create a PKCS#7 signedData structure

Name

PKCS7_sign — creates and returns a PKCS#7 signedData structure

Library

libcrypto.lib

Synopsis

PKCS7 *PKCS7_sign(X509 *signcert, EVP_PKEY *pkey, STACK_OF(X509) *certs, BIO *data, int flags);

Detailed Description

PKCS7_sign() creates and returns a PKCS#7 signedData structure. signcert is the certificate to sign with, pkey is the corresponding private key. certs is an optional additional set of certificates to include in the PKCS#7 structure (for example any intermediate CAs in the chain).

The data to be signed is read from BIO data.

flags is an optional set of flags.

Notes

Any of the following flags (ored together) can be passed in the flags parameter.

Many S/MIME clients expect the signed content to include valid MIME headers. If the PKCS7_TEXT flag is set MIME headers for type text/plain are prepended to the data.

If PKCS7_NOCERTS is set the signer's certificate will not be included in the PKCS7 structure, the signer's certificate must still be supplied in the signcert parameter though. This can reduce the size of the signature if the signers certificate can be obtained by other means: for example a previously signed message.

The data being signed is included in the PKCS7 structure, unless PKCS7_DETACHED is set in which case it is omitted. This is used for PKCS7 detached signatures which are used in S/MIME plaintext signed messages for example.

Normally the supplied content is translated into MIME canonical format (as required by the S/MIME specifications) if PKCS7_BINARY is set no translation occurs. This option should be used if the supplied data is in binary format otherwise the translation will corrupt it.

The signedData structure includes several PKCS#7 autenticatedAttributes including the signing time, the PKCS#7 content type and the supported list of ciphers in an SMIMECapabilities attribute. If PKCS7_NOATTR is set then no authenticatedAttributes will be used. If PKCS7_NOSMIMECAP is set then just the SMIMECapabilities are omitted.

If present the SMIMECapabilities attribute indicates support for the following algorithms: triple DES, 128 bit RC2, 64 bit RC2, DES and 40 bit RC2. If any of these algorithms is disabled then it will not be included.

If the flags PKCS7_PARTSIGN is set then the returned PKCS7 structure is just initialized ready to perform the signing operation. The signing is however not performed and the data to be signed is not read from the data parameter. Signing is deferred until after the data has been written. In this way data can be signed in a single pass. Currently the flag PKCS7_DETACHED must also be set.

Currently the flag PKCS7_PARTSIGN is only supported for detached data. If this flag is set the returned PKCS7 structure is not complete and outputting its contents via a function that does not properly finalize the PKCS7 structure will give unpredictable results.

At present only the SMIME_write_PKCS7() function properly finalizes the structure.

Bugs

PKCS7_sign() is somewhat limited. It does not support multiple signers, some advanced attributes such as counter signatures are not supported.

The SHA1 digest algorithm is currently always used.

When the signed data is not detached it will be stored in memory within the PKCS7 structure. This effectively limits the size of messages which can be signed due to memory restraints. There should be a way to sign data without having to hold it all in memory, this would however require fairly major revisions of the OpenSSL ASN1 code.

Return Values

PKCS7_sign() returns either a valid PKCS7 structure or NULL if an error occurred. The error can be obtained from ERR_get_error().

See Also

ERR_get_error(), PKCS7_verify()

History

PKCS7_sign() was added to OpenSSL 0.9.5

The PKCS7_PARTSIGN flag was added in OpenSSL 0.9.8

Feedback

For additional information or queries on this page send feedback


PKCS7_verify - verify a PKCS#7 signedData structure

Name

PKCS7_verify — verifies a PKCS#7 signedData structure

Library

libcrypto.lib

Synopsis

int PKCS7_verify(PKCS7 *p7, STACK_OF(X509) *certs, X509_STORE *store, BIO *indata, BIO *out, int flags);
int PKCS7_get0_signers(PKCS7 *p7, STACK_OF(X509) *certs, int flags);

Detailed Description

PKCS7_verify() verifies a PKCS#7 signedData structure. p7 is the PKCS7 structure to verify. certs is a set of certificates in which to search for the signer's certificate. store is a trusted certificate store (used for chain verification). indata is the signed data if the content is not present in p7 (that is it is detached). The content is written to out if it is not NULL.

flags is an optional set of flags, which can be used to modify the verify operation.

PKCS7_get0_signers() retrieves the signer's certificates from p7, it does not check their validity or whether any signatures are valid. The certs and flags parameters have the same meanings as in PKCS7_verify().

Verify Process

Normally the verify process proceeds as follows.

Initially some sanity checks are performed on p7. The type of p7 must be signedData. There must be at least one signature on the data and if the content is detached indata cannot be NULL.

An attempt is made to locate all the signer's certificates, first looking in the certs parameter (if it is not NULL) and then looking in any certificates contained in the p7 structure itself. If any signer's certificates cannot be located the operation fails.

Each signer's certificate is chain verified using the smimesign purpose and the supplied trusted certificate store. Any internal certificates in the message are used as untrusted CAs. If any chain verify fails an error code is returned.

Finally the signed content is read (and written to out is it is not NULL) and the signature's checked.

If all signature's verify correctly then the function is successful.

Any of the following flags (ored together) can be passed in the flags parameter to change the default verify behaviour. Only the flag PKCS7_NOINTERN is meaningful to PKCS7_get0_signers().

If PKCS7_NOINTERN is set the certificates in the message itself are not searched when locating the signer's certificate. This means that all the signers certificates must be in the certs parameter.

If the PKCS7_TEXT flag is set MIME headers for type text/plain are deleted from the content. If the content is not of type text/plain then an error is returned.

If PKCS7_NOVERIFY is set the signer's certificates are not chain verified.

If PKCS7_NOCHAIN is set then the certificates contained in the message are not used as untrusted CAs. This means that the whole verify chain (apart from the signer's certificate) must be contained in the trusted store.

If PKCS7_NOSIGS is set then the signatures on the data are not checked.

Notes

One application of PKCS7_NOINTERN is to only accept messages signed by a small number of certificates. The acceptable certificates would be passed in the certs parameter. In this case if the signer is not one of the certificates supplied in certs then the verify will fail because the signer cannot be found.

Care should be taken when modifying the default verify behaviour, for example setting PKCS7_NOVERIFY|PKCS7_NOSIGS will totally disable all verification and any signed message will be considered valid. This combination is however useful if one merely wishes to write the content to out and its validity is not considered important.

Chain verification should arguably be performed using the signing time rather than the current time. However since the signing time is supplied by the signer it cannot be trusted without additional evidence (such as a trusted timestamp).

Return Values

PKCS7_verify() returns 1 for a successful verification and zero or a negative value if an error occurs.

PKCS7_get0_signers() returns all signers or NULL if an error occurred.

The error can be obtained from ERR_get_error()

Bugs

The trusted certificate store is not searched for the signers certificate, this is primarily due to the inadequacies of the current X509_STORE functionality.

The lack of single pass processing and need to hold all data in memory as mentioned in PKCS7_sign() also applies to PKCS7_verify().

See Also

ERR_get_error(), PKCS7_sign()

History

PKCS7_verify() was added to OpenSSL 0.9.5

Feedback

For additional information or queries on this page send feedback


PKCS12_create - create a PKCS#12 structure

Name

PKCS12_create — create a PKCS#12 structure

Library

libcrypto.lib

Synopsis

#include <openssl/pkcs12.h>
PKCS12 *PKCS12_create(char *pass, char *name, EVP_PKEY *pkey, X509 *cert, STACK_OF(X509) *ca, int nid_key, int nid_cert,
                      int iter, int mac_iter, int keytype);

Detailed Description

PKCS12_create() creates a PKCS#12 structure.

pass is the passphrase to use. name is the friendlyName to use for the supplied certificate and key. pkey is the private key to include in the structure and cert its corresponding certificates. ca, if not NULL is an optional set of certificates to also include in the structure.

nid_key and nid_cert are the encryption algorithms that should be used for the key and certificate respectively. iter is the encryption algorithm iteration count to use and mac_iter is the MAC iteration count to use. keytype is the type of key.

Notes

The parameters nid_key, nid_cert, iter, mac_iter and keytype can all be set to zero and sensible defaults will be used.

These defaults are: 40 bit RC2 encryption for certificates, triple DES encryption for private keys, a key iteration count of PKCS12_DEFAULT_ITER (currently 2048) and a MAC iteration count of 1.

The default MAC iteration count is 1 in order to retain compatibility with old software which did not interpret MAC iteration counts. If such compatibility is not required then mac_iter should be set to PKCS12_DEFAULT_ITER.

keytype adds a flag to the store private key. This is a non standard extension that is only currently interpreted by MSIE. If set to zero the flag is omitted, if set to KEY_SIG the key can be used for signing only, if set to KEY_EX it can be used for signing and encryption. This option was useful for old export grade software which could use signing only keys of arbitrary size but had restrictions on the permissible sizes of keys which could be used for encryption.

New Functionality in OpenSSL 0.9.8

Some additional functionality was added to PKCS12_create() in OpenSSL 0.9.8. These extensions are detailed below.

If a certificate contains an alias or keyid then this will be used for the corresponding friendlyName or localKeyID in the PKCS12 structure.

Either pkey, cert or both can be NULL to indicate that no key or certificate is required. In previous versions both had to be present or a fatal error is returned.

nid_key or nid_cert can be set to -1 indicating that no encryption should be used.

mac_iter can be set to -1 and the MAC will then be omitted entirely.

See Also

d2i_PKCS12()

History

PKCS12_create was added in OpenSSL 0.9.3

Feedback

For additional information or queries on this page send feedback


PKCS12_parse - parse a PKCS#12 structure

Name

PKCS12_parse — parses a PKCS12 structure

Library

libcrypto.lib

Synopsis

#include <openssl/pkcs12.h>
int PKCS12_parse(PKCS12 *p12, const char *pass, EVP_PKEY **pkey, X509 **cert, STACK_OF(X509) **ca);

Detailed Description

PKCS12_parse() parses a PKCS12 structure.

p12 is the PKCS12 structure to parse. pass is the passphrase to use. If successful the private key will be written to *pkey, the corresponding certificate to *cert and any additional certificates to *ca.

Notes

The parameters pkey and cert cannot be NULL. ca can be <NULL> in which case additional certificates will be discarded. *ca can also be a valid STACK in which case additional certificates are appended to *ca. If *ca is NULL a new STACK will be allocated.

The friendlyName and localKeyID attributes (if present) on each certificate will be stored in the alias and keyid attributes of the X509 structure.

Bugs

Only a single private key and corresponding certificate is returned by this function. More complex PKCS#12 files with multiple private keys will only return the first match.

Only friendlyName and localKeyID attributes are currently stored in certificates. Other attributes are discarded.

Attributes currently cannot be store in the private key EVP_PKEY structure.

See Also

d2i_PKCS12()

History

PKCS12_parse was added in OpenSSL 0.9.3

Feedback

For additional information or queries on this page send feedback


popen

Name

popen, pclose
- process I/O

Library

 libc.lib

Synopsis
#include <stdio.h>
FILE * popen (const char *command, const char *type);
int pclose (FILE *stream);

Return values

 The popen function returns NULL if the
fork or pipe calls fail, or if it cannot allocate memory.

The pclose function returns -1 if stream is not associated with a "popened" command, if stream already "pclosed," or if
wait4 returns an error.

Detailed description

 The popen function opens a process by creating a pipe, forking, and invoking the shell. Since a pipe is by definition unidirectional, The type argument may specify only reading or writing, not both; the resulting stream is correspondingly read-only ("r") or write-only "w". If type is anything other than this, then the behavior is undefined.

The command argument is a pointer to a null-terminated string containing a shell command line. This command is passed to /bin/sh using the -c flag; interpretation, if any, is performed by the shell.

The return value from popen is a normal standard I/O stream in all respects save that it must be closed with pclose rather than fclose. Writing to such a stream writes to the standard input of the command; the command’s standard output is the same as that of the process that called popen, unless this is altered by the command itself. Conversely, reading from a "popened" stream reads the command’s standard output, and the command’s standard input is the same as that 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 the exit status of the command as returned by wait4.

Errors

 The popen function does not reliably set errno.

Examples

/*************************************************************************************************************
* Detailed description: Parent Process that demonstrates usage of popen system call in read mode
*
* Preconditions: child process exe should be available in c:\sysnhld.exe in target (assuming its installed)
* EPOCROOT\poc32\release4ld.exe in emulator, before parent process is started.
**************************************************************************************************************/
#include <stdio.h>
#ifdef __WINSCW__
const char* const KChildProcess = "z:\sys\bin\TPopenReadChild.exe";
#else
const char* const KChildProcess = "C:\Sys\Bin\TPopenReadChild.exe";
#endif //__WINSCW__
int main() {
        char string[100];
        int ret;
        FILE* fp = popen(KChildProcess, "r");
        if(fp) {
                ret = fscanf(fp, "%s", string);
                printf("Read %s from child0, string);
                pclose(fp);
        }
        return 0;
}

/*************************************************************************************************************
* Detailed description: Chil Process that will be spawned by Parent as a result of popen system call
* If, this application is spawned independentl, printf flushes "Popened-Child" on to console.
* And if, its spawned as a result of popen (as its done by the parent process), string sent to printf wont be
* displayed onto console, instead, it will be wrote on to the pipe created by the parent between
* parent and child. So, parent process will get this string.
*
**************************************************************************************************************/
#include <stdio.h>
int main() {
        printf("Popened-Child");
        return 0;
}

Output

Read Popened-Child from child

See also

 pipe, fclose, fflush, fopen, system
A popen and a pclose function appeared in AT&T v7.

Bidirectional functionality was added in 2.2.6.

Bugs

 Since the standard input of a command opened for reading shares its seek offset with the 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 from a command opened for writing may become intermingled with that of the original process. The latter can be avoided by calling fflush before popen.

Failure to execute the shell is indistinguishable from the shell’s failure to execute command, or an immediate exit of the command. The only hint is an exit status of 127.

The popen function always calls
sh, never calls
csh.

Feedback

For additional information or queries on this page send feedback


posix_spawn

Name

posix_spawn - spawns a process.

Library

libc.lib

Synopsis

#include <spawn.h>

int posix_spawn(pid_t * pid, const char * path,
const posix_spawn_file_actions_t *file_actions,
const posix_spawnattr_t * attrp,
char *const argv[], char *const envp[]);

Detailed Description

The posix_spawn created a new child process from the specified process image. A C program executed as a result of this call will be a call to the C-language main function:

int main(int argc, char *argv[])
The argument argv is an array of character pointers to null terminated strings. The last member of this array will be NULL [not counted in argc]. The string argv[0] should point to a filename that is associated with the process image being started by the posix_spawn() function. Other strings constitute the arg list to the new process image.

The argument envp is an array of character pointers to null terminated strings. This array is terminated by a NULL pointer. These strings constitute the environment for the new process image.

The argument path is a pathname that identifies the new process image file to execute.

If the argument file_actions is a NULL pointer, then the file descriptors open in the parent process will remain open in the child process except for those whose FD_CLOEXEC [close on exec] is set [using fcntl]. For the file descriptors that remain open, all the flags of the open file descriptors will remain unchanged including file locks.

If the argument file_actions is not NULL, then the file descriptors open in the child process will be those open in the parent process as modified by the spawn fileactions object pointed to by file_actions and the FD_CLOEXEC flag of each of the remaining open file descriptor after the spawn file actions have been processed.
The effective order of processing the spawn file actions will be:

1. The set of open file descriptors for the child process will initially be the same set as is open for the calling process. All attributes of the corresponding open file descriptions, including file locks, will remain unchanged.
2. The signal mask, signal default actions, and the effective user and group IDs for the child process will be changed as specified in the attributes object referenced by attrp.
3. The file actions specified by the spawn file actions object will be performed in the order in which they were added to the spawn file actions object.
4. Any file descriptor that has its FD_CLOEXEC flag set will be closed.

The argument attrp is a pointer to posix_spawnattr_t spawn attributes defined in spawn.h. If the value of the attrp pointer is NULL, then the default values are used.

spawn attributes will contain at least the attributes defined below.

If the POSIX_SPAWN_SETPGROUP flag is set in the spawn-flags attribute of the object referenced by attrp, and the spawn-pgroup attribute of the same object is non-zero, then the child's process group will be as specified in the spawn-pgroup attribute of the object referenced by attrp. This attribute is currently ignored.

As a special case, if the POSIX_SPAWN_SETPGROUP flag is set in the spawn-flags attribute of the object referenced by attrp, and the spawn-pgroup attribute of the same object is set to zero, then the child will be in a new process group with a process group ID equal to its process ID. This attribute is currently ignored.

If the POSIX_SPAWN_SETPGROUP flag is not set in the spawn-flags attribute of the object referenced by attrp, the new child process will inherit the parent's process group. This attribute is currently ignored.

If the POSIX_SPAWN_SETSCHEDPARAM flag is set in the spawn-flags attribute of the object referenced by attrp, but POSIX_SPAWN_SETSCHEDULER is not set, the new process image will initially have the scheduling policy of the calling process with the scheduling parameters specified in the spawn-schedparam attribute of the object referenced by attrp. This attribute is currently ignored.

If the POSIX_SPAWN_SETSCHEDULER flag is set in the spawn-flags attribute of the object referenced by attrp (regardless of the setting of the POSIX_SPAWN_SETSCHEDPARAM flag), the new process image will initially have the scheduling policy specified in the spawn-schedpolicy attribute of the object referenced by attrp and the scheduling parameters specified in the spawn-schedparam attribute of the same object. This attribute is currently ignored.

The POSIX_SPAWN_RESETIDS flag in the spawn-flags attribute of the object referenced by attrp governs the effective user ID of the child process. If this flag is not set, the child process will inherit the parent process' effective user ID. If this flag is set, the child process' effective user ID will be reset to the parent's real user ID. In either case, if the set-user-ID mode bit of the new process image file is set, the effective user ID of the child process will become that file's owner ID before the new process image begins execution. This attribute is currently ignored.

The POSIX_SPAWN_RESETIDS flag in the spawn-flags attribute of the object referenced by attrp also governs the effective group ID of the child process. If this flag is not set, the child process will inherit the parent process' effective group ID. If this flag is set, the child process' effective group ID will be reset to the parent's real group ID. In either case, if the set-group-ID mode bit of the new process image file is set, the effective group ID of the child process will become that file's group ID before the new process image begins execution. This attribute is currently ignored.

If the POSIX_SPAWN_SETSIGMASK flag is set in the spawn-flags attribute of the object referenced by attrp, the child process will initially have the signal mask specified in the spawn-sigmask attribute of the object referenced by attrp. This attribute is currently ignored.

If the POSIX_SPAWN_SETSIGDEF flag is set in the spawn-flags attribute of the object referenced by attrp, the signals specified in the spawn-sigdefault attribute of the same object will be set to their default actions in the child process. Signals set to the default action in the parent process will be set to the default action in the child process. This attribute is currently ignored.

Return Values

On success, posix_spawn returns 0 and stores the process ID of the child process in the variable pointed to by the pid [if pid is not NULL]. If no child process is created, the error number that is set is returned to the caller.
On error, the value stored in the variable pointed to by pid [if pid is not NULL] is unspecified.

Errors

The posix_spawn() function may fail if:

[EINVAL]
The value specified by file_actions or attrp is invalid.

[ECHILD]
Unable to create the child process.

[EILSEQ]
Unable to convert input strings to their wchar variants.

Feedback

For additional information or queries on this page send feedback

© 2005-2007 Nokia


posix_spawn_file_actions_addclose

Name

posix_spawn_file_actions_addclose, posix_spawn_file_actions_addopen - addopen or addclose action to the spawn file actions object.

Library

libc.lib

Synopsis

#include <spawn.h>

int posix_spawn_file_actions_addclose(posix_spawn_file_actions_t *file_actions, int fildes);
int posix_spawn_file_actions_addopen(posix_spawn_file_actions_t *file_actions, int fildes,
const char * path, int oflag, mode_t mode);

Detailed Description

The posix_spawn_file_actions_addclose will add a close action to the file actions object referenced by file_actions argument. This causes the file descriptor to be closed when a new child process is spawned using this file action object.

The posix_spawn_file_actions_addopen will add a open action to the file action object referenced by file_actions argument. This causes the file named by path argument to be opened when a new child process is spawned using this file action object. If the file was already open, it will be closed before the new file is opened.

The string passed by the path argument will be copied by the posix_spawn_file_actions_addopen function.

Return Values

On success, these functions return 0. On error, they return the error number set to indicate the error.

Errors

These functions fail if:

[EBADF]
The value specified by file is negative, or greater than equal to {OPEN_MAX}.

[EINVAL]
The value specified by file_actions is invalid.

[ENOMEM]
Insufficient memory exists to add to the spawn file actions object.

Feedback

For additional information or queries on this page send feedback

© 2005-2007 Nokia


posix_spawn_file_actions_adddup2

Name

posix_spawn_file_actions_adddup2 - add dup2 action to the spawn file actions object.

Library

libc.lib

Synopsis

#include <spawn.h>

int posix_spawn_file_actions_adddup2(posix_spawn_file_actions_t *file_actions, int fildes, int newfildes);

Detailed Description

The posix_spawn_file_actions_adddup2 will add a dup2 action to the file actions object referenced by file_actions argument. This causes the file descriptor to be duplicated when a new child process is spawned using this file action object.

Return Values

On success, 0 is returned. On error it returns the error number, set to indicate the error.

Errors

The posix_spawn_file_actions_adddup2() function fails if:

[EBADF]
The value specified by fildes or newfildes is negative or greater than or equal to {OPEN_MAX}.

[ENOMEM]
Insufficient memory exists to add to the spawn file actions object.

The posix_spawn_file_actions_adddup2() function may fail if:

[EINVAL]
The value specified by file_actions is invalid.

Feedback

For additional information or queries on this page send feedback


posix_spawn_file_actions_destroy

Name

posix_spawn_file_actions_destroy, posix_spawn_file_actions_init - destroy or initialize the spawn file actions object.

Library

libc.lib

Synopsis

#include <spawn.h>

int posix_spawn_file_actions_destroy(posix_spawn_file_actions_t *file_actions);
int posix_spawn_file_actions_init(posix_spawn_file_actions_t *file_actions);

Detailed Description

The posix_spawn_file_actions_destroy will destroy the file action object referenced by the argument file_actions. The object becomes uninitialized. If the destroyed object is referenced the results will be undefined.

The posix_spawn_file_actions_init will initialize the file action object referenced by the file_actions argument to contain no action for posix_spawn.

The effect of initializing an already initialized spawn file actions object is undefined.

Return Values

On success, these functions return 0. On error it returns the error number that is set to indicate the error.

Errors

The posix_spawn_file_actions_init() function fails if:

[ENOMEM]
Insufficient memory exists to initialize the spawn file actions object.

The posix_spawn_file_actions_destroy() function may fail if:

[EINVAL]
The value specified by file_actions is invalid.

Feedback

For additional information or queries on this page send feedback


posix_spawnattr_destroy

Name

posix_spawnattr_destroy, posix_spawnattr_init - destroy/initialize the spawn attributes object.

Library

libc.lib

Synopsis

#include <spawn.h>

int posix_spawnattr_destroy(posix_spawnattr_t *attr);
int posix_spawnattr_init(posix_spawnattr_t *attr);

Detailed Description

The posix_spawnattr_destroy will destroy the spawn attribute object referenced by the argument attr. The object becomes uninitialized. If the destroyed object is referenced the results will be undefined.

The posix_spawnattr_init will initialize the spawn attribute object referenced by the attr argument with default value for all the individual attributes.

Return Values

On success, these functions return 0. On error they return the error number that is set to indicate the error.

Errors

The posix_spawnattr_init() function fails if:

[ENOMEM]
Insufficient memory exists to initialize the spawn attributes object.

The posix_spawnattr_destroy() function may fail if:

[EINVAL]
The value specified by attr is invalid.

Feedback

For additional information or queries on this page send feedback

© 2005-2007 Nokia


posix_spawnattr_getflags

Name

posix_spawnattr_getflags,posix_spawnattr_setflags - get/set spawn-flags attribute of a spawn attributes object.

Library

libc.lib

Synopsis

#include <spawn.h>

int posix_spawnattr_getflags(const posix_spawnattr_t * attr,short * flags);
int posix_spawnattr_setflags(posix_spawnattr_t *attr, short flags);

Detailed Description

The posix_spawnattr_getflags will get the value of the spawn-flags attribute from the attributes object referenced by the argument attr.

The posix_spawnattr_setflags will set the spawn-flags attribute in an initialized attributes object referenced by the argument attr.

The spawn-flags attribute is used to indicate which process attributes are to be changed in the new process image when invoking posix_spawn().The default value of this attribute will be as if no flags were set.

Return Values

On success, posix_spawnattr_getflags will return 0 and stores the spawn-flags attribute of attr in the object referenced by the argument flags. On error, error number is returned to indicate the error.

On success posix_spawnattr_setflags will return 0. On error, error number is returned to indicate the error.

Feedback

For additional information or queries on this page send feedback

© 2005-2007 Nokia


posix_spawnattr_getpgroup

Name

posix_spawnattr_getpgroup,posix_spawnattr_setpgroup - get or set spawn-pgroup attribute of a spawn attributes object.

Library

libc.lib

Synopsis

#include <spawn.h>

int posix_spawnattr_getpgroup(const posix_spawnattr_t *attr,pid_t *pgroup);
int posix_spawnattr_setpgroup(posix_spawnattr_t *attr, pid_t pgroup);

Detailed Description

The posix_spawnattr_getpgroup will get the value of the spawn-pgroup attribute from the attributes object referenced by the argument attr.

The posix_spawnattr_setpgroup will set the spawn-pgroup attribute in an initialized attributes object referenced by the argument attr.

The spawn-pgroup attribute represents the process group to be joined by the new process image in a spawn operation. The default value of this attribute shall be zero.

Return Values

On success, posix_spawnattr_getpgroup will return 0 and stores the spawn-group attribute of attr in the object referenced by the argument pgroup. On error, error number is returned to indicate the error.

On success posix_spawnattr_setpgroup will return 0. On error, error number is returned to indicate the error.

Errors

These functions may fail if:

[EINVAL]
The value specified by attr is invalid.

The posix_spawnattr_setpgroup() function may fail if:

[EINVAL]
The value of the attribute being set is not valid.

Feedback

For additional information or queries on this page send feedback


posix_spawnattr_getschedparam

Name

posix_spawnattr_getschedparam, posix_spawnattr_setschedparam - get or set the spawn-schedparam attribute of a spawn attributes object.

Library

libc.lib

Synopsis

#include <spawn.h>

int posix_spawnattr_getschedparam(const posix_spawnattr_t *attr, struct sched_param *schedparam);
int posix_spawnattr_setschedparam(posix_spawnattr_t *attr,const struct sched_param *schedparam);

Detailed Description

The posix_spawnattr_getschedparam will get the value of the spawn-schedparam attribute from the attributes object referenced by the argument attr.

The posix_spawnattr_setschedparam will set the spawn-schedparam attribute in an initialized attributes object referenced by the argument attr.

The spawn-schedparam attribute represents the scheduling parameters to be assigned to the new process image in a spawn operation. The default value of this attribute is unspecified.

Return Values

On success, posix_spawnattr_getschedparam will return 0 and stores the spawn-schedparam attribute of attr in the object referenced by the argument schedparam. On error, error number is returned to indicate the error.

On success posix_spawnattr_setschedparam will return 0. On error, error number is returned to indicate the error.

Errors

These functions may fail if:

[EINVAL]
The value specified by attr is invalid.

The posix_spawnattr_setschedparam() function may fail if:

[EINVAL]
The value of the attribute being set is not valid.

Feedback

For additional information or queries on this page send feedback


posix_spawnattr_getschedpolicy

Name

posix_spawnattr_getschedpolicy, posix_spawnattr_setschedpolicy - get or set the spawn-schedpolicy attribute of a spawn attributes object.

Library

libc.lib

Synopsis

#include <spawn.h>

int posix_spawnattr_getschedpolicy(const posix_spawnattr_t *attr, int *schedpolicy);
int posix_spawnattr_setschedpolicy(posix_spawnattr_t *attr,int schedpolicy);

Detailed Description

The posix_spawnattr_getschedpolicy will get the value of the spawn-schedpolicy attribute from the attributes object referenced by the argument attr.

The posix_spawnattr_setschedpolicy will set the spawn-schedpolicy attribute in an initialized attributes object referenced by the argument attr.

The spawn-schedpolicy attribute represents the scheduling policy to be assigned to the new process image in a spawn operation. The default value of this attribute is unspecified.

Return Values

On success, posix_spawnattr_getschedpolicy will return 0 and stores the spawn-schedpolicy attribute of attr in the object referenced by the argument schedpolicy. On error, error number is returned to indicate the error.

On success posix_spawnattr_setschedpolicy will return 0. On error, error number is returned to indicate the error.

Errors

These functions may fail if:

[EINVAL]
The value specified by attr is invalid.

The posix_spawnattr_setschedpolicy() function may fail if:

[EINVAL]
The value of the attribute being set is not valid.

Feedback

For additional information or queries on this page send feedback


posix_spawnattr_getsigdefault

Name

posix_spawnattr_getsigdefault, posix_spawnattr_setsigdefault - get or set the spawn-sigdefault attribute of a spawn attributes object.

Library

libc.lib

Synopsis

#include <spawn.h>

int posix_spawnattr_getsigdefault(const posix_spawnattr_t *attr, sigset_t *sigdefault);
int posix_spawnattr_setsigdefault(posix_spawnattr_t *attr,const sigset_t *sigdefault);

Detailed Description

The posix_spawnattr_getsigdefault will get the value of the spawn-sigdefault attribute from the attributes object referenced by the argument attr.

The posix_spawnattr_setsigdefault will set the spawn-sigdefault attribute in an initialized attributes object referenced by the argument attr.

The spawn-sigdefault attribute represents the set of signals to be forced to default signal handling in the new process image. The default value of this attribute will be an empty signal set.

Return Values

On success, posix_spawnattr_getsigdefault will return 0 and stores the spawn-sigdefault attribute of attr in the object referenced by the argument sigdefault. On error, error number is returned to indicate the error.

On success posix_spawnattr_setsigdefault will return 0. On error, error number is returned to indicate the error.

Errors

These functions may fail if:

[EINVAL]
The value specified by attr is invalid.

The posix_spawnattr_setsigdefault() function may fail if:

[EINVAL]
The value of the attribute being set is not valid.

Feedback

For additional information or queries on this page send feedback


posix_spawnattr_getsigmask

Name

posix_spawnattr_getsigmask, posix_spawnattr_setsigmask - get or set the spawn-sigmask attribute of a spawn attributes object

Library

libc.lib

Synopsis

#include <spawn.h>

int posix_spawnattr_getsigmask(const posix_spawnattr_t *attr,sigset_t *sigmask);
int posix_spawnattr_setsigmask(posix_spawnattr_t *attr,const sigset_t *sigmask);

Detailed Description

The posix_spawnattr_getsigmask will get the value of the spawn-sigmask attribute from the attributes object referenced by the argument attr.

The posix_spawnattr_setsigmask will set the spawn-sigmask attribute in an initialized attributes object referenced by the argument attr.

The spawn-sigmask attribute represents the signal mask in effect in the new process image of a spawn operation. The default value of this attribute is unspecified.

Return Values

On success, posix_spawnattr_getsigmask will return 0 and stores the spawn-sigmask attribute of attr in the object referenced by the argument sigmask. On error, error number is returned to indicate the error.

On success posix_spawnattr_setsigmask will return 0. On error, error number is returned to indicate the error.

Errors

These functions may fail if:

[EINVAL]
The value specified by attr is invalid.

The posix_spawnattr_setsigmask() function may fail if:

[EINVAL]
The value of the attribute being set is not valid.

Feedback

For additional information or queries on this page send feedback


Introduction

Most modern programming languages come with their own native object systems and additional fundamental algorithmic language constructs. Just as GLib serves as an implementation of such fundamental types and algorithms (linked lists, hash tables and so forth), the GLib Object System provides the required implementations of a flexible extensible and intentionally easy to map (into other languages) object oriented framework for C. The substantial elements that are provided can be summarized as:

  • A generic type system to register arbitrary single-inherited flat and deep derived types as well as interfaces for structured types. It takes care of creation, initialization and memory management of the assorted object and class structures, maintains parent/child relationships and deals with dynamic implementations of such types. That is, their type specific implementations are relocatable/unloadable during runtime.

  • A collection of fundamental type implementations, such as integers, doubles, enums and structured types, to name a few.

  • A sample fundamental type implementation to base object hierarchies upon - the GObject fundamental type.

  • A signal system that allows very flexible user customization of virtual/overridable object methods and can serve as a powerful notification mechanism.

  • An extensible parameter/value system, supporting all the provided fundamental types that can be used to generically handle object properties or otherwise parameterized types.

©2005-2006 Nokia


printf

Name

printf, fprintf, sprintf, snprintf, asprintf,
vprintf, vfprintf, vsprintf, vsnprintf, vasprintf

- formatted output conversion

Library

 libc.lib

Synopsis
#include <stdio.h>
int printf (const char * restrict format, ...);
int fprintf (FILE * restrict stream, const char * restrict format, ...);
int sprintf (char * restrict str, const char * restrict format, ...);
int snprintf (char * restrict str, size_t size, const char * restrict format, ...);
int asprintf (char **ret, const char *format, ...);
#include <stdarg.h>
int vprintf (const char * restrict format, va_list ap);
int vfprintf (FILE * restrict stream, const char * restrict format, va_list ap);
int vsprintf (char * restrict str, const char * restrict format, va_list ap);
int vsnprintf (char * restrict str, size_t size, const char * restrict format, va_list ap);
int vasprintf (char **ret, const char *format, va_list ap);

Return values

Upon successful return, these functions return the number of characters printed (not including the trailing \0 used to end output to strings). The functions snprintf and vsnprintf do not write more than size bytes (including the trailing \0). If the output was truncated due to this limit then the return value is the number of characters (not including the trailing \0) which would have been written to the final string if enough space had been available. Thus, a return value of size or more means that the output was truncated. If an output error is encountered, a negative value is returned.

Detailed description

 The printf family of functions produces output according to a format as described below. The printf and vprintf functions write output to stdout, the standard output stream; fprintf and vfprintf write output to the given output stream; sprintf, snprintf, vsprintf, and vsnprintf write to the character string str; and asprintf and vasprintf dynamically allocate a new string with malloc.

These functions write the output under the control of a format string that specifies how subsequent arguments (or arguments accessed via the variable-length argument facilities of stdarg ) are converted for output.

These functions return the number of characters printed (not including the trailing ‘\0’ used to end output to strings) or a negative value if an output error occurs, except for snprintf and vsnprintf, which return the number of characters that would have been printed if the size were unlimited (again, not including the final ‘\0).’

The asprintf and vasprintf functions set *ret to be a pointer to a buffer sufficiently large to hold the formatted string. This pointer should be passed to free to release the allocated 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.

The snprintf and vsnprintf functions will write at most size -1 of the characters printed into the output string (the size ’th character then gets the terminating ‘\0 );’ if the return value is greater than or equal to the size argument, the string was too short and some of the printed characters were discarded. The output is always null-terminated.

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 conversion specification is introduced by the % character. The arguments must correspond 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 $, specifying the next argument to access. If this field is not provided, the argument following the last argument accessed will be used. Arguments are numbered starting at 1. If unaccessed arguments in the format string are interspersed with 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. For o conversions, the precision of the number is increased to force the first character of the output string to a zero (except if a zero value is printed with an explicit precision of zero). For x and X conversions, a non-zero result has the string ‘0x’ (or ‘0X’ for X conversions) prepended to it. For a, A, e, E, f, F, g, and G conversions, the result will always contain a decimal point, even if no digits follow it (normally, a decimal point appears in the results of those conversions only if a digit follows). For g and G conversions, trailing zeros are not removed from the result as they would otherwise be.
    '0(zero)' | 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; the converted value is to be left adjusted on the field boundary. Except for n conversions, the converted value is padded on the right with blanks, rather than on the left with blanks or zeros. A - overrides a 0 if both are given.
    ' (space)' | A blank should be left before a positive number produced by a signed conversion (a, A, d, e, E, f, F, g, G, or i).
    '+' A sign must always be placed before a number produced by a signed conversion. A + overrides a space if both are used.
    '’' Decimal conversions (d, u, or i) or the integral portion of a floating point conversion (f or F) should be grouped and separated by thousands using the non-monetary separator returned by localeconv.
  • An optional decimal digit string specifying a minimum field width. If the converted value has fewer characters than the field width, it will be padded with spaces on the left (or right, if the left-adjustment flag has been given) to fill out the field width.
  • An optional precision, in the form of a period . followed by an optional digit 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 X conversions, 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 G conversions, or the maximum number of characters to be printed from a string for s conversions.
  • An optional length modifier, that specifies the size of the argument. The following length modifiers are valid for the d, i, n, o, u, x, or X conversion:
    Modifier        d, i              o, u, x, X                n
hh              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 that the argument is of an unsigned type equivalent in size to a ptrdiff_t. The z modifier, when applied to a d or i conversion, indicates that the argument is of a signed type equivalent in size to a size_t. Similarly, when applied to an n conversion, it indicates that the argument is a pointer to a signed type equivalent 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, G
l (ell)     double (ignored, same behavior as without it)
L           long double

    The following length modifier is valid for the c or s conversion:

    Modifier    c         s
l (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 asterisk followed by one or more decimal digits and a ‘$’ instead of a digit string. In this case, an int argument supplies the field width or precision. A negative field width is treated as a left adjustment flag followed by a positive field width; a negative precision is treated as though it were missing. If a single format directive mixes positional (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 decimal (d and i), unsigned octal (o,) unsigned decimal (u,) or unsigned hexadecimal (x and X) notation. The letters "abcdef" are used for x conversions; the letters "ABCDEF" are used for X conversions. The precision, if any, gives the minimum number of digits that must appear; if the converted value requires fewer digits, it is padded on the left with zeros.
DOU | The long int argument is converted to signed decimal, unsigned octal, or unsigned decimal, as if the format had been ld, lo, or lu respectively. These conversion characters are deprecated, and will eventually disappear.
eE The double argument is rounded and converted in the style [-d . ddd e \*[Pm] dd] where there is one digit before the decimal-point character and the number 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 appears. An E conversion uses the letter ‘E’ (rather than ‘e’) to introduce the exponent. The exponent always contains at least two digits; if the value is zero, the exponent is 00.

For a, A, e, E, f, F, g, and G conversions, positive and negative infinity are represented as inf and -inf respectively when using the lowercase conversion character, and INF and -INF respectively when using the uppercase conversion character. Similarly, NaN is represented as nan when using the lowercase conversion, and NAN when using the uppercase conversion.

fF | The double argument is rounded and converted to decimal notation in the style [-ddd . ddd,] where the number of digits after the decimal-point character is equal to the precision specification. If the precision is missing, it is taken as 6; if the precision is explicitly zero, no decimal-point character appears. If a decimal point appears, at least one digit appears before it.
gG | The double argument is converted in style f or e (or F or E for G conversions). The precision specifies the number of significant digits. If the precision is missing, 6 digits are given; if the precision is zero, it is treated as 1. Style e is used if the exponent from its conversion is less than -4 or greater than or equal to the precision. Trailing zeros are removed from the fractional part of the result; a decimal point appears only if it is followed by at least one digit.
aA The double argument is rounded and converted to hexadecimal notation in the style [-0x h . hhhp[\*[Pm]d,]] where the number of digits after the hexadecimal-point character is equal to the precision specification. If the precision is missing, it is taken as enough to represent the floating-point number exactly, and no rounding occurs. If the precision is zero, no hexadecimal-point character appears. The p is a literal character ‘p,’ and the exponent consists of a positive or negative sign followed by a decimal number representing an exponent of 2. The A conversion uses the prefix "0X" (rather than "0x)," the letters "ABCDEF" (rather than "abcdef)" to represent the hex digits, and the letter ‘P’ (rather than ‘p)’ to separate the mantissa and exponent.

Note that there may be multiple valid ways to represent floating-point numbers in this hexadecimal format. For example, 0x3.24p+0, 0x6.48p-1 and 0xc.9p-2 are all equivalent. The format chosen depends on the internal representation of the number, but the implementation guarantees that the length of the mantissa will be minimized. Zeroes are always represented with a mantissa of 0 (preceded by a ‘-’ if appropriate) and an exponent of +0.

C | Treated as c with the l (ell) modifier.
c The int argument is converted to an unsigned char , and the resulting character is written.

If the l (ell) modifier is used, the wint_t argument shall be converted to a wchar_t, and the (potentially multi-byte) sequence representing the single wide character is written, including any shift sequences. If a shift sequence is used, the shift state is also restored to the original state after the character.

S | Treated as s with the l (ell) modifier.
s The char * argument is expected to be a pointer to an array of character type (pointer to a string). Characters from the array are written up to (but not 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 is greater than the size of the array, the array must contain a terminating NUL character.

If the l (ell) modifier is used, the wchar_t * argument is expected to be a pointer to an array of wide characters (pointer to a wide string). For each wide character in the string, the (potentially multi-byte) sequence representing the wide character is written, including any shift sequences. If any shift sequence is used, the shift state is also restored to the original state after the string. Wide characters from the array are written up to (but not including) a terminating wide NUL character; if a precision is specified, no more than the number of bytes specified are written (including shift sequences). Partial characters are never written. If a precision is given, no null character need be present; if the precision is not specified, or is greater than the number of bytes required to render the multibyte representation of the string, the array must contain a terminating wide 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 indicated by the int * (or variant) pointer argument. No argument is converted.
% A ‘%’ is written. No argument is converted. The complete conversion specification is ‘%%.’

The decimal point character is defined in the program’s locale (category LC_NUMERIC ).

In no case does a non-existent or small field width cause truncation of a numeric field; if the result of a conversion is wider than the field width, the field is expanded to contain the conversion result.

Examples

 To print a date and time in the form "Sunday, July 3, 10:02", where weekday and month 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)
                return (NULL);
        va_start(ap, fmt);
        (void) vsnprintf(p, 128, fmt, ap);
        va_end(ap);
        return (p);
}

/****************** this program shows printing onto the console using printf **************/
#include <stdio.h>
int main(void)
{
        char * msg="hello world\n";
        printf("%s",msg);
        return 0;
}

Output

hello world

/****************** this program shows reading from console using scanf **************/
#include <stdio.h>
int main(void)
{
        char msg[100];
        printf("enter message to be printed\n");
        scanf("%s",msg);
        printf("message entered is: %s\n",msg);
        return 0;
}

Output

enter message to be printed
hello (assuming this is user input)
message entered is: hello

Security considerations

 The sprintf and vsprintf functions are easily misused in a manner which enables malicious users to arbitrarily change a running program’s functionality through a buffer overflow attack. Because sprintf and vsprintf assume an infinitely long string, callers must be careful not to overflow the actual space; this is often hard to assure. For safety, programmers should use the snprintf interface instead. For example:
void
foo(const char *arbitrary_string, const char *and_another)
{
        char onstack[8];
#ifdef BAD
        /*
         * This first sprintf is bad behavior.  Do not use sprintf!
         */
        sprintf(onstack, "%s, %s", arbitrary_string, and_another);
#else
        /*
         * The following two lines demonstrate better use of
         * snprintf().
         */
        snprintf(onstack, sizeof(onstack), "%s, %s", arbitrary_string,
            and_another);
#endif
}

The printf and sprintf family of functions are also easily misused in a manner allowing malicious users to arbitrarily change a running program’s functionality by either causing the program to print potentially sensitive data "left on the stack", or causing it to generate a memory fault or bus error by dereferencing an invalid pointer.

%n can be used to write arbitrary data to potentially carefully-selected addresses. Programmers are therefore strongly advised to never pass untrusted strings as the format argument, as an attacker can put format specifiers in the string to mangle the stack, leading to a possible security hole. This holds true even if the string was built using a function like snprintf, as the resulting string may still contain user-supplied conversion specifiers for later interpolation by printf.

Always use the proper secure idiom:

     snprintf(buffer, sizeof(buffer), "%s", string);

Errors

 In addition to the errors documented for the write system call, the printf family of functions may fail if:
[EILSEQ]
 | An invalid wide character code was encountered.
[ENOMEM]
 | Insufficient storage space is available.

Limitations

 All these functions don’t support the long double length modifiers. All the floating point format specifiers supports maximum precision of 15 digits as this is the maximum that is supported in SYMBIAN.

See also

 printf, scanf, setlocale, wprintf

Bugs

 The conversion formats %D, %O, and %U are not standard and are provided only for backward compatibility. The effect of padding the %p format with zeros (either by the 0 flag or by specifying a precision), and the benign effect (i.e., none) of the # flag on %n and %p conversions, as well as other nonsensical combinations such as %Ld, are not standard; such combinations should be avoided. The printf family of functions do not correctly handle multibyte characters in the format argument.

Feedback

For additional information or queries on this page send feedback


pthread_attr

Name

pthread_attr_init ,pthread_attr_destroy ,pthread_attr_setstacksize
pthread_attr_getstacksize ,pthread_attr_setdetachstate ,pthread_attr_getdetachstate

pthread_attr_setschedparam ,pthread_attr_getschedparam ,pthread_attr_setschedpolicy

pthread_attr_getschedpolicy ,pthread_attr_setscope ,pthread_attr_setscope,

pthread_attr_getscope,thread attribute operations

- formatted output conversion

Library

 libc_r.lib libpthread.lib libthr.lib

Synopsis
#include <pthread.h>
int pthread_attr_init (pthread_attr_t *attrib);
int pthread_attr_destroy (pthread_attr_t *attrib);
int pthread_attr_setstacksize (pthread_attr_t *attrib, size_t stkSize);
int pthread_attr_getstacksize (const pthread_attr_t *attrib, size_t *stkSize);
int pthread_attr_setdetachstate (pthread_attr_t *attrib, int detState);
int pthread_attr_getdetachstate (const pthread_attr_t *attrib, int *detState);
int pthread_attr_setschedparam (pthread_attr_t *attrib, const struct sched_param *param);
int pthread_attr_getschedparam (const pthread_attr_t *attrib, struct sched_param *param);
int pthread_attr_setschedpolicy (pthread_attr_t *attrib, int policy);
int pthread_attr_getschedpolicy (const pthread_attr_t *attrib, int *policy);
int pthread_attr_setscope (pthread_attr_t *attrib, int conscope);
int pthread_attr_getscope (const pthread_attr_t *attrib, int *scope);

Return values

 If successful, these functions return 0. Otherwise, an error number is returned to indicate the error.

Detailed description

 Thread attributes are used to specify parameters to pthread_create. One attribute object can be used in multiple calls to pthread_create, with or without modifications between calls.

The pthread_attr_init function initializes attrib with all the default thread attributes.

The pthread_attr_destroy function destroys attrib.

The pthread_attr_set* functions set the attribute that corresponds to each function name.

The pthread_attr_get* functions copy the value of the attribute that corresponds to each function name to the location pointed to by the second function parameter.

Limitation

 The pthread_attr_setscope supports only PTHREAD_SCOPE_SYSTEM.

The pthread_attr_setschedpolicy supports only SCHED_RR.

pthread_join : Only one thread can join on one specific target thread.

Errors

 The pthread_attr_init function will fail if:
[EINVAL]
Invalid value for attrib.

The pthread_attr_destroy function will fail if:
[EINVAL]
Invalid value for attrib.

The pthread_attr_setstacksize function will fail if:
[EINVAL]
stacksize is less than PTHREAD_STACK_MIN. or if the attrib is not initialized or if attrib is NULL

The pthread_attr_getstacksize function will fail if:
[EINVAL]
attrib is NULL or if the attrib is not initialized

The pthread_attr_setdetachstate function will fail if:
[EINVAL]
Invalid value for detachstate or if the attrib is not initialized or if attrib is NULL

The pthread_attr_getdetachstate function will fail if:
[EINVAL]
attrib is NULL or if the attrib is not initialized

The pthread_attr_setschedparam function will fail if:
[EINVAL]
Invalid value for param. or if the attrib is not initialized or if attrib is NULL

The pthread_attr_getschedparam function may fail if:
[EINVAL]
attrib does not refer to an initialized thread attribute or if attrib is NULL

The pthread_attr_setschedpolicy function will fail if:
[EINVAL]
Invalid value for policy. or if the attrib is not initialized or if attrib is NULL

The pthread_attr_getschedpolicy function may fail if:
[EINVAL]
attrib does not refer to an initialized thread attribute or if attrib is NULL

The pthread_attr_setscope function will fail if:
[EINVAL]
Invalid value for contentionscope or if the attrib is not initialized or if attrib is NULL

The pthread_attr_getscope function may fail if:
[EINVAL]
attrib does not refer to an initialized thread attribute or if attrib is NULL

Examples

/* ***************************************************** */
/* Example for pthread_attr_init & pthread_attr_destroy  */
/* ***************************************************** */
pthread_attr_t new_attr;
/* Initialize attribute */
if(pthread_attr_init(&new_attr) != 0)
{
  printf("Cannot initialize attribute object\n");
  return -1; /* or exit */
}
/* Create thread */
/* Destroy attribute */
if(pthread_attr_destroy(&new_attr) != 0)
{
  perror("Cannot destroy the attribute object\n");
  return -1; /* or exit*/
}

/* ***************************************************** */
/* Example for pthread_attr_getdetachstate               */
/* ***************************************************** */
pthread_attr_t new_attr;
int detach_state;
/* Initialize attribute */
if(pthread_attr_init(&new_attr) != 0)
{
  printf("Cannot initialize attribute object\n");
  return -1;
}
if(pthread_attr_getdetachstate(&new_attr, &detach_state) != 0)
{
  printf("Cannot get the state\n");
  return -1;
}
if(detach_state == PTHREAD_CREATE_JOINABLE)
{
  printf("State is joinable \n");
}
else
{
  printf("State is detached \n");
}
/* Create thread */
/* Destroy attribute */

/* ***************************************************** */
/* Example for pthread_attr_getschedpolicy               */
/* ***************************************************** */
pthread_attr_t new_attr;
int rc;
int policy;
/* Initialize attribute */
if(pthread_attr_init(&new_attr) != 0)
{
  printf("Cannot initialize attribute object\n");
  return -1; /* or exit */
}
rc = pthread_attr_getschedpolicy(new_attr, &policy);
if( rc != 0) {
  printf("pthread_attr_getschedpolicy failed\n");
  return -1;
}
switch(policy) {
 case SCHED_FIFO:
       printf("Scheduling policy: SCHED_FIFO 0);
       break;
 case SCHED_RR:
       printf("Scheduling policy: SCHED_RR \n");
       break;
 case SCHED_OTHER:
       printf("Scheduling policy: SCHED_OTHER \n");
       break;
}
/* Create thread */
/* Destroy attribute */

/* ***************************************************** */
/* Example for pthread_attr_getscope                     */
/* ***************************************************** */
pthread_attr_t new_attr;
int rc;
int scope;
/* Initialize attribute */
if(pthread_attr_init(&new_attr) != 0)
{
  printf("Cannot initialize attribute object\n");
  return -1; /* or exit */
}
rc = pthread_attr_getscope(new_attr, &scope);
if( rc != 0) {
  printf("pthread_attr_getscope failed");
  return -1;
}
switch(scope) {
 case SYSTEMSCOPE:
       printf("scope: System \n ");
       break;
 case PROCESSSCOPE:
       printf("scope: Process \n ");
       break;
}
/* Create thread */
/* Destroy attribute */

/* ***************************************************** */
/* Example for pthread_attr_getstacksize                 */
/* ***************************************************** */
pthread_attr_t new_attr;
size_t ssize;
int rc;
/* Initialize attribute */
if(pthread_attr_init(&new_attr) != 0)
{
  printf("Cannot initialize attribute object\n");
  return -1; /* or exit */
}
/* Get the default stack_size value */
rc = pthread_attr_getstacksize(&new_attr, &stack_size);
if( rc != 0) {
  printf("pthread_attr_getstacksize failed");
  return -1;
}
printf("ssize = %lu\n", stack_size);
/* Create thread */
/* Destroy attribute */

/* ***************************************************** */
/* Example for pthread_attr_getschedparam               */
/* ***************************************************** */
pthread_attr_t         attr;
int                    rc=0;
struct sched_param     param;
struct sched_param     param2;
rc = pthread_attr_init(&attr);
if(rc != 0) {
  printf("pthread_attr_init failed\n");
  return -1;
}
param.sched_priority = 50;
rc = pthread_attr_setschedparam(&attr, & param);
if(rc != 0) {
  printf("pthread_attr_setschedparam failed\n");
  return -1;
}
rc = pthread_attr_getschedparam(&attr, & param2);
if(rc != 0) {
  printf("pthread_attr_getschedparam failed\n");
  return -1;
}
/* priority will be stored in param2.sched_priority */
/* Create thread */
/* Destroy attribute */

/* ***************************************************** */
/* Example for pthread_attr_setdetachstate               */
/* ***************************************************** */
pthread_attr_t new_attr;
int detach_state;
/* Initialize attribute */
if(pthread_attr_init(&new_attr) != 0)
{
  perror("Cannot initialize attribute object\n");
  return -1;
}
/* Set the attribute object to PTHREAD_CREATE_JOINABLE. */
if(pthread_attr_setdetachstate(&new_attr, PTHREAD_CREATE_JOINABLE) != 0)
{
  perror("Error in pthread_attr_setdetachstate()\n");
  return -1;
}
/* Create thread */
/* Destroy attribute */

/* ***************************************************** */
/* Example for pthread_attr_setschedparam               */
/* ***************************************************** */
pthread_attr_t         attr;
int                    rc=0;
struct sched_param     param;
rc = pthread_attr_init(&attr);
if(rc != 0) {
  printf("pthread_attr_init failed\n");
  return -1;
}
param.sched_priority = 50;
rc = pthread_attr_setschedparam(&attr, & param);
if(rc != 0) {
  printf("pthread_attr_setschedparam failed\n");
  return -1;
}
/* Create thread */
/* Destroy attribute */

/* ***************************************************** */
/* Example for pthread_attr_setschedpolicy               */
/* ***************************************************** */
pthread_attr_t attr;
int rc;
int policy = SCHED_RR;
if(pthread_attr_init(&attr) != 0) {
  printf("Error on pthread_attr_init()\n");
  return -1;
}

if((rc=pthread_attr_setschedpolicy(&attr,policy)) != 0) {
      printf("Error on pthread_attr_setschedpolicy()\t rc=%d\n", rc);
      return -1;
}
/* Create thread */
/* Destroy attribute */

/* ***************************************************** */
/* Example for pthread_attr_setstacksize                 */
/* ***************************************************** */
pthread_attr_t attr;
int rc;
int policy = SCHED_RR;
if(pthread_attr_init(&attr) != 0) {
  printf("Error on pthread_attr_init()\n");
  return -1;
}

if((rc=pthread_attr_setstacksize(&attr,8192)) != 0) {
      printf("Error on pthread_attr_setstacksize()\t rc=%d\n", rc);
      return -1;
}
/* Create thread */
/* Destroy attribute */

/* ***************************************************** */
/* Example for pthread_attr_setscope                     */
/* ***************************************************** */
pthread_attr_t attr;
int rc;
/* Initialize attr */
rc = pthread_attr_init(&attr);
if( rc != 0) {
  perror("pthread_attr_init failed");
  return -1;
}
rc = pthread_attr_setscope(&attr, PTHREAD_SCOPE_SYSTEM);
if (rc != 0 ) {
  perror("PTHREAD_SCOPE_SYSTEM is not supported");
  return -1;
}
/* Create thread */
/* Destroy attribute */

See also

 pthread_create

Feedback

For additional information or queries on this page send feedback


pthread_cond_broadcast

Name

pthread_cond_broadcast
- unblock all threads waiting for a condition variable

Library

 libc_r.lib libpthread.lib libthr.lib

Synopsis
#include <pthread.h>
int pthread_cond_broadcast (pthread_cond_t *cond);

Return values

 If successful, the pthread_cond_broadcast function will return zero, otherwise an error number will be returned to indicate the error.

Detailed description

 The pthread_cond_broadcast function unblocks all threads waiting for the condition variable cond.

Examples

 int rc;
struct testdata
{
 pthread_mutex_t mutex;
 pthread_cond_t  cond;
};
static struct testdata td;
 if (pthread_mutex_init(&td.mutex, NULL) != 0) {
  fprintf(stderr,"Fail to initialize mutex\n");
  return -1;
 }
 if (pthread_cond_init(&td.cond, NULL) != 0) {
  fprintf(stderr,"Fail to initialize cond\n");
  return -1;
 }
/* ....... other thread wait for signal */
 /* Acquire the mutex to make sure that all waiters are currently
    blocked on pthread_cond_wait */
 if (pthread_mutex_lock(&td.mutex) != 0) {
  fprintf(stderr,"Main: Fail to acquire mutex\n");
  return -1;
 }
 if (pthread_mutex_unlock(&td.mutex) != 0) {
  fprintf(stderr,"Main: Fail to release mutex\n");
  return -1;
 }
 /* signal the condition to wake up all waiters */
 fprintf(stderr," signal the condition0);
 rc = pthread_cond_broadcast(&td.cond);
 if (rc != 0) {
  fprintf(stderr," failed to signal the condition\n");
  return -1;
 }

Errors

 The pthread_cond_broadcast function will fail if:
[EINVAL]
The value specified by cond is invalid.

See also

 pthread_cond_destroy, pthread_cond_init, pthread_cond_signal, pthread_cond_timedwait, pthread_cond_wait

Feedback

For additional information or queries on this page send feedback


pthread_cond_destroy

Name

pthread_cond_destroy
- destroy a condition variable

Library

 libc_r.lib libpthread.lib libthr.lib

Synopsis
#include <pthread.h>
int pthread_cond_destroy (pthread_cond_t *cond);

Return values

 If successful, the pthread_cond_destroy function will return zero, otherwise an error number will be returned to indicate the error.

Detailed description

 The pthread_cond_destroy function frees the resources allocated by the condition variable cond.

Examples

int rc;
struct testdata
{
 pthread_mutex_t mutex;
 pthread_cond_t  cond;
};
static struct testdata td;
int function1()
{
 /* Initialize a condition variable object */
 if (pthread_cond_init(&td.cond, NULL) != 0) {
  fprintf(stderr,"Fail to initialize cond\n");
  return -1;
 }
 /* ... Use it for wait, signal, broadcast */
 /* Destroy the condition variable object */
 if((rc=pthread_cond_destroy(&td.cond)) != 0)
 {
   fprintf(stderr,"Error at pthread_cond_destroy(), rc=%d\n",rc);
   return -1;
 }
}

Errors

 The pthread_cond_destroy function will fail if:
[EINVAL]
 | The value specified by cond is invalid.
[EAGAIN]
 | The variable cond is locked by another thread.

See also

 pthread_cond_broadcast, pthread_cond_init, pthread_cond_signal, pthread_cond_timedwait, pthread_cond_wait

Feedback

For additional information or queries on this page send feedback


pthread_cond_init

Name

pthread_cond_init
- create a condition variable

Library

 libc_r.lib libpthread.lib libthr.lib

Synopsis
#include <pthread.h>
int pthread_cond_init (pthread_cond_t *cond, const pthread_condattr_t * attr);

Return values

 If successful, the pthread_cond_init function will return zero and put the new condition variable id into cond, otherwise an error number will be returned to indicate the error.

Detailed description

 The pthread_cond_init function creates a new condition variable referenced by cond with attributes referenced by attr. If attr is NULL, the default condition variable attributes shall be used; Upon successful initialization, the state of the condition variable shall become initialized.

Examples

int rc;
struct testdata
{
 pthread_mutex_t mutex;
 pthread_cond_t  cond;
};
static struct testdata td;
int function1()
{
 /* Initialize a condition variable object */
 if (pthread_cond_init(&td.cond, NULL) != 0) {
  fprintf(stderr,"Fail to initialize cond\n");
  return -1;
 }
 /* ... Use it for wait, signal, broadcast */
 /* Destroy the condition variable object */
 if((rc=pthread_cond_destroy(&td.cond)) != 0)
 {
   fprintf(stderr,"Error at pthread_cond_destroy(), rc=%d\n",rc);
   return -1;
 }
}

Errors

 The pthread_cond_init function will fail if:
[EINVAL]
The cond is NULL.

See also

 pthread_cond_broadcast, pthread_cond_destroy, pthread_cond_signal, pthread_cond_timedwait, pthread_cond_wait

Feedback

For additional information or queries on this page send feedback


pthread_cond_signal

Name

pthread_cond_signal
- unblock a thread waiting for a condition variable

Library

 libc_r.lib libpthread.lib libthr.lib

Synopsis
#include <pthread.h>
int pthread_cond_signal (pthread_cond_t *cond);

Return values

 If successful, the pthread_cond_signal function will return zero, otherwise an error number will be returned to indicate the error.

Detailed description

 The pthread_cond_signal function unblocks one thread waiting for the condition variable cond.

Examples

 int rc;
struct testdata
{
 pthread_mutex_t mutex;
 pthread_cond_t  cond;
};
static struct testdata td;
int function1()
{
 if (pthread_mutex_init(&td.mutex, NULL) != 0) {
  fprintf(stderr,"Fail to initialize mutex\n");
  return -1;
 }
 if (pthread_cond_init(&td.cond, NULL) != 0) {
  fprintf(stderr,"Fail to initialize cond\n");
  return -1;
 }
 /* ....... other thread wait for signal */
 /* Acquire the mutex to make sure that all waiters are currently
    blocked on pthread_cond_wait */
 if (pthread_mutex_lock(&td.mutex) != 0) {
  fprintf(stderr,"Main: Fail to acquire mutex\n");
  return -1;
 }
 if (pthread_mutex_unlock(&td.mutex) != 0) {
  fprintf(stderr,"Main: Fail to release mutex\n");
  return -1;
 }
 /* signal the condition to wake up all waiters */
 fprintf(stderr," signal the condition\n");
 rc = pthread_cond_signal(&td.cond);
 if (rc != 0) {
  fprintf(stderr," failed to signal the condition\n");
  return -1;
 }
}

Errors

 The pthread_cond_signal function will fail if:
[EINVAL]
The value specified by cond is invalid.

See also

 pthread_cond_broadcast, pthread_cond_destroy, pthread_cond_init, pthread_cond_timedwait, pthread_cond_wait

Feedback

For additional information or queries on this page send feedback


pthread_cond_timedwait

Name

pthread_cond_timedwait
- wait on a condition variable for a specific amount of time

Library

 libc_r.lib libpthread.lib libthr.lib

Synopsis
#include <pthread.h>
int pthread_cond_timedwait (pthread_cond_t *cond, pthread_mutex_t *mutex, const struct timespec *abstime);

Return values

 If successful, the pthread_cond_timedwait function will return zero. Otherwise an error number will be returned to indicate the error.

Detailed description

 The pthread_cond_timedwait function atomically blocks the current thread waiting on the condition variable specified by cond, and unblocks the mutex specified by mutex. The waiting thread unblocks only after another thread calls pthread_cond_signal, or pthread_cond_broadcast with the same condition variable, or if the system time reaches the time specified in abstime, and the current thread reacquires the lock on mutex.

Examples

struct testdata
{
 pthread_mutex_t mutex;
 pthread_cond_t  cond;
};
static struct testdata td;
 int rc;
 struct timespec timeout;
 struct timeval  curtime;
/* mutex and conditional variable must be initialized */
 if (pthread_mutex_lock(&td.mutex) != 0) {
  fprintf(stderr,"Thread: Fail to acquire mutex\n");
  return -1;
 }
 if (gettimeofday(&curtime, NULL) !=0 ) {
  fprintf(stderr,"Fail to get current time\n");
  return -1;
 }
 timeout.tv_sec = curtime.tv_sec;
 timeout.tv_nsec = curtime.tv_usec * 1000;
 timeout.tv_sec += TIMEOUT;
 fprintf(stderr,"Thread is waiting for the cond\n");
 rc = pthread_cond_timedwait(&td.cond, &td.mutex, &timeout);
 if(rc != 0) {
  if (rc == ETIMEDOUT) {
   fprintf(stderr,"Thread stops waiting when time is out\n");
   return -1;
  }
  else {
   fprintf(stderr,"pthread_cond_timedwait return %d\n", rc);
   return -1;
  }
 }
 fprintf(stderr,"Thread wakened up\n");
 pthread_mutex_unlock(&td.mutex);

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 abstime.
[ENOMEM]
 | If this function was not able to acquire a required resource.

See also

 pthread_cond_broadcast, pthread_cond_destroy, pthread_cond_init, pthread_cond_signal, pthread_cond_wait

Feedback

For additional information or queries on this page send feedback


pthread_cond_wait

Name

pthread_cond_wait
- wait on a condition variable

Library

 libc_r.lib libpthread.lib libthr.lib

Synopsis
#include <pthread.h>
int pthread_cond_wait (pthread_cond_t *cond, pthread_mutex_t *mutex);

Return values

 If successful, the pthread_cond_wait function will return zero. Otherwise an error number will be returned to indicate the error.

Detailed description

 The pthread_cond_wait function atomically blocks the current thread waiting on the condition variable specified by cond, and unblocks the mutex specified by mutex. The waiting thread unblocks only after another thread calls pthread_cond_signal, or pthread_cond_broadcast with the same condition variable, and the current thread reacquires the lock on mutex.

Examples

struct testdata
{
 pthread_mutex_t mutex;
 pthread_cond_t  cond;
};
static struct testdata td;
int rc;
/* mutex and conditional variable must be initialized */
if (pthread_mutex_lock(&td.mutex) != 0) {
  fprintf(stderr,"Thread failed to acquire mutex\n");
  return -1;
 }
fprintf(stderr,"Thread started\n");
fprintf(stderr,"Thread is waiting for the cond\n");
rc = pthread_cond_wait(&td.cond, &td.mutex);
if (rc != 0) {
  fprintf(stderr,"pthread_cond_wait return %d\n", rc);
  return -1;
}
fprintf(stderr,"Thread wakened\n");
pthread_mutex_unlock(&td.mutex);

Errors

 The pthread_cond_wait function will fail if:
[EINVAL]
 | The value specified by cond or the value specified by mutex is invalid.
[ENOMEM]
 | This function was not able to acquire a required resource.
[ETIMEDOUT]
 | The absolute time specified by abstime parameter occurred before the condition variable was signaled.

See also

 pthread_cond_broadcast, pthread_cond_destroy, pthread_cond_init, pthread_cond_signal, pthread_cond_timedwait
The pthread_cond_wait function conforms to -p1003.1-96.

Feedback

For additional information or queries on this page send feedback


pthread_condattr

Name

pthread_condattr_init, pthread_condattr_destroy
- condition attribute operations

Library

 libc_r.lib libpthread.lib libthr.lib

Synopsis
#include <pthread.h>
int pthread_condattr_init (pthread_condattr_t *attr);
int pthread_condattr_destroy (pthread_condattr_t *attr);

Return values

 If successful, these functions return 0. Otherwise, an error number is returned to indicate the error.

Detailed description

 Condition attribute objects are used to specify parameters to pthread_cond_init. Current implementation of conditional variables does not support any attributes, so these functions are not very useful.

The pthread_condattr_init function initializes a condition attribute object with the default attributes.(As of now None)

The pthread_condattr_destroy function destroys a condition attribute object.

Examples

 pthread_condattr_t condattr;
 int rc;
 /* Initialize a condition variable attributes object */
 if((rc=pthread_condattr_init(&condattr)) != 0)
 {
  fprintf(stderr,"Cannot initialize condition variable attributes object\n");
  return -1;
 }
 /* Destroy the condition variable attributes object */
 if(pthread_condattr_destroy(&condattr) != 0)
 {
  fprintf(stderr,"Error at pthread_condattr_destroy(), rc=%d\n", rc);
  return -1;
 }

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.

See also

 pthread_cond_init

Feedback

For additional information or queries on this page send feedback


pthread_create

Name

pthread_create
- create a new thread

Library

 libc_r.lib libpthread.lib libthr.lib

Synopsis
#include <pthread.h>
int pthread_create (pthread_t *threadhdl, const pthread_attr_t *attrib, void *(*begin_routine)(void *), void *param);

Return values

 If successful, the pthread_create function will return zero. Otherwise an error number will be returned to indicate the error.

Detailed description

 The pthread_create function is used to create a new thread, with attributes specified by attrib, within a process. If attrib is NULL, the default attributes are used. If the attributes specified by attrib are modified later, the thread’s attributes are not affected. Upon successful completion pthread_create will store the ID of the created thread in the location specified by threadhdl.

The thread is created executing begin_routine with param as its sole argument. If the begin_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 thread in which main was originally invoked differs from this. When it returns from main, the effect is as if there was an implicit call to exit using the return value of main as the exit status.

Examples

void *a_thread_func_1_1(void*)
{
 return NULL;
}
int XYZ()
{
 pthread_t new_th;
 if(pthread_create(&new_th, NULL, a_thread_func_1_1, NULL) != 0)
 {
  perror("Error creating thread\n");
  return -1;
 }
}

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 a process [PTHREAD_THREADS_MAX] would be exceeded.
[EINVAL]
 | The value specified by attrib is invalid.

See also

 pthread_exit, pthread_join

Feedback

For additional information or queries on this page send feedback


pthread_detach

Name

pthread_detach
- detach a thread

Library

 libc_r.lib libpthread.lib libthr.lib

Synopsis
#include <pthread.h>
int pthread_detach (pthread_t thrHandle);

Return values

 If successful, the pthread_detach function will return zero. Otherwise an error number will be returned to indicate the error.

Detailed description

 The pthread_detach function is used to indicate to the implementation that storage for the thread thrHandle can be reclaimed when the thread terminates. If thrHandle has not terminated, pthread_detach will not cause it to terminate. The effect of multiple pthread_detach calls on the same target thread is unspecified.

Examples

void *a_thread_func_1_1(void*)
{
 sleep(10);
 return NULL;
}
int main_1_1()
{
 pthread_attr_t new_attr;
 pthread_t new_th;
 int ret;
 /* Initialize attribute */
 if(pthread_attr_init(&new_attr) != 0)
 {
  perror("Cannot initialize attribute object\n");
  return -1;
 }
 /* Set the attribute object to be joinable */
 if(pthread_attr_setdetachstate(&new_attr, PTHREAD_CREATE_JOINABLE) != 0)
 {
  perror("Error in pthread_attr_setdetachstate()\n");
  return -1;
 }
 /* Create the thread */
 if(pthread_create(&new_th, &new_attr, a_thread_func_1_1, NULL) != 0)
 {
  perror("Error creating thread\n");
  return -1;
 }
 /* Detach the thread. */
 if(pthread_detach(new_th) != 0)
 {
  printf("Error detaching thread\n");
  return -1;
 }

Errors

 The pthread_detach function will fail if:
[EINVAL]
 | The implementation has detected that the value specified by thrHandle does not refer to a joinable thread. or if someother thread has already joined
[ESRCH]
 | No thread could be found corresponding to that specified by the given thread ID, thrHandle.

See also

 pthread_join

Feedback

For additional information or queries on this page send feedback


pthread_equal

Name

pthread_equal
- compare thread IDs

Library

 libc_r.lib libpthread.lib libthr.lib

Synopsis
#include <pthread.h>
int pthread_equal (pthread_t t1, pthread_t t2);

Return values

 The pthread_equal function will return non-zero if the thread IDs t1 and t2 correspond to the same thread, otherwise it will return zero.

Detailed description

 The pthread_equal function compares the thread IDs t1 and t2.

Examples

void *a_thread_func_1_2(void*)
{
 pthread_exit(0);
 return NULL;
}
void XYZ()
{
pthread_t new_th1, new_th2;
 /* Create a new thread. */
 if(pthread_create(&new_th1, NULL, a_thread_func_1_2, NULL) != 0)
 {
  perror("Error creating thread\n");
  return -1;
 }
 /* Create another new thread. */
 if(pthread_create(&new_th2, NULL, a_thread_func_1_2, NULL) != 0)
 {
  perror("Error creating thread\n");
  return -1;
 }
 /* Call pthread_equal() and pass to it the 2 new threads.
  * It should return a zero value, indicating that
  * they are not equal. */
 if(pthread_equal(new_th1, new_th2) != 0)
 {
  printf("pthread_equal FAILED\n");
  return -1;
 }
}

Errors

 None.

See also

 pthread_create, pthread_exit

Feedback

For additional information or queries on this page send feedback


pthread_exit

Name

pthread_exit
- terminate the calling thread

Library

 libc_r.lib libpthread.lib libthr.lib

Synopsis
#include <pthread.h>
void pthread_exit (void *retValPtr);

Return values

 The pthread_exit function cannot return to its caller.

Detailed description

 The pthread_exit function terminates the calling thread and makes the value retValPtr available to any successful join with the terminating thread. Thread termination does not release any application visible process resources, including, but not limited to, mutexes and file descriptors, nor does it perform any process level cleanup actions, 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 thread in which main was first invoked returns from the start routine that was used to create 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 handler or destructor function that was invoked as the result of an implicit or explicit call to pthread_exit.

After a thread has terminated, the result of access to local (auto) variables of the thread is undefined. Thus, references to local variables of the exiting thread should not be used for the pthread_exit retValPtr parameter value.

The process will exit with an exit status of 0 after the last thread has been terminated. The behavior is as if the implementation called exit with a zero argument at thread termination time.

Examples

/* Thread’s function. */
void *a_thread_func_1_1(void*)
{
 /* ….. Do some thing….. */
 pthread_exit((void*)RETURN_CODE);
}

Errors

 None.

See also

 _exit, exit, pthread_create, pthread_join

Feedback

For additional information or queries on this page send feedback


pthread_getspecific

Name

pthread_getspecific
- get a thread-specific data value

Library

 libc_r.lib libpthread.lib libthr.lib

Synopsis
#include <pthread.h>
void * pthread_getspecific (pthread_key_t key);

Return values

 The pthread_getspecific function will return the thread-specific data value associated with the given key. If no thread-specific data value is associated with key, then the value NULL is returned.

Detailed description

 The pthread_getspecific function returns the value currently bound to the specified key on behalf of the calling thread.

The effect of calling pthread_getspecific with a key value not obtained from pthread_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 data destructor function.

Examples

pthread_key_t keys;
 void* rc;
if(pthread_key_create(&keys, NULL) != 0)
{
   printf("Error: pthread_key_create() failed0);
   return -1;
} else
{
   if(pthread_setspecific(keys, (void *)(long)(100)) != 0)
   {
    printf("Error: pthread_setspecific() failed\n");
    return -1;
   }
}
rc = pthread_getspecific(keys);
if(rc != (void *)(long)(100))
{
   printf("getspecific failed \n");
   return -1;
}

Errors

 None.

See also

 pthread_key_create, pthread_key_delete, pthread_setspecific

Feedback

For additional information or queries on this page send feedback


pthread_join

Name

pthread_join
- wait for thread termination

Library

 libc_r.lib libpthread.lib libthr.lib

Synopsis
#include <pthread.h>
int pthread_join (pthread_t thrHandle, void **retValPtr);

Return values

 If successful, the pthread_join function will return zero. Otherwise an error number will be returned to indicate the error.

Detailed description

 The pthread_join function suspends execution of the calling thread until the target thrHandle terminates unless the target thrHandle has already terminated.

On return from a successful pthread_join call with a non-NULL retValPtr argument, the value passed to pthread_exit by the terminating thread is stored in the location referenced by retValPtr. When a pthread_join returns successfully, the target thread has been terminated. The results of multiple simultaneous calls to pthread_join specifying the same target thread are undefined.

Examples

/* Thread’s function. */
void *a_thread_func_1_1(void*)
{
 int i;
 printf("Wait for 3 seconds for thread to finish execution:0);
 for(i=1;i<4;i++)
 {
  printf("Waited (%d) second0, i);
  sleep(1);
 }
 return NULL;
}
int XYZ()
{
 pthread_t new_th;
 /* Create a new thread. */
 if(pthread_create(&new_th, NULL, a_thread_func_1_1, NULL) != 0)
 {
  perror("Error creating thread\n");
  return -1;
 }
 /* Wait for thread to return */
 if(pthread_join(new_th, NULL) != 0)
 {
  perror("Error in pthread_join()\n");
  return -1;
 }

Errors

 The pthread_join function will fail if:
[EINVAL]
 | The implementation has detected that the value specified by thrHandle does not refer to a joinable thread. or some other thread has already joined
[ESRCH]
 | No thread could be found corresponding to that specified by the given thread ID, thrHandle.
[EDEADLK]
 | A deadlock was detected or the value of thrHandle specifies the calling thread.

See also

 wait, pthread_create

Feedback

For additional information or queries on this page send feedback


pthread_key_create

Name

pthread_key_create
- thread-specific data key creation

Library

 libc_r.lib libpthread.lib libthr.lib

Synopsis
#include <pthread.h>
int pthread_key_create (pthread_key_t *key, void (*dest)(void *));

Return values

 If successful, the pthread_key_create function will store the newly created key value at the location specified by key and returns zero. Otherwise an error number will be returned to indicate the error.

Detailed description

 The pthread_key_create function creates a thread-specific data key visible to all threads in the process. Key values provided by pthread_key_create are opaque objects used to locate thread-specific data. Although the same key value may be used 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 active threads. Upon thread creation, the value NULL is associated with all defined keys in the new thread.

An optional destructor function dest may be associated with each key value. At thread exit, 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 current associated value as its sole argument. The order of destructor calls is unspecified if more than one destructor exists for a thread when it exits.

If, after all the destructors have been called for all non-NULL values with associated 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 some non-NULL values with associated destructors, the implementation stops calling destructors.

Examples

pthread_key_t keys;
if(pthread_key_create(&keys, NULL) != 0)
{
   printf("Error: pthread_key_create() failed\n");
   return -1;
}

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 number of keys per process [PTHREAD_KEYS_MAX] would be exceeded.

See also

 pthread_getspecific, pthread_key_delete, pthread_setspecific

Feedback

For additional information or queries on this page send feedback


pthread_key_delete

Name

pthread_key_delete
- delete a thread-specific data key

Library

 libc_r.lib libpthread.lib libthr.lib

Synopsis
#include <pthread.h>
int pthread_key_delete (pthread_key_t key);

Return values

 If successful, the pthread_key_delete function will return zero. Otherwise an error number will be returned to indicate the error.

Detailed description

 The pthread_key_delete function deletes a thread-specific data key previously returned by pthread_key_create. The thread-specific data values associated with key need not be NULL at the time that pthread_key_delete is called. It is the responsibility of the application to free any application storage or perform any cleanup actions for data structures related to the deleted key or associated thread-specific data in any threads; this cleanup can be done either before or after pthread_key_delete is called. Any attempt to use key following the call to pthread_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 destructor function that may have been associated with key will no longer be called upon thread exit.

Examples

pthread_key_t keys;
if(pthread_key_create(&keys, NULL) != 0)
{
   printf("Error: pthread_key_create() failed\n");
   return -1;
}
if(pthread_key_delete(keys) != 0)
{
  printf("Error: pthread_key_delete() failed\n");
  return -1;
}

Errors

 The pthread_key_delete function will fail if:
[EINVAL]
The key value is invalid.

See also

 pthread_getspecific, pthread_key_create, pthread_setspecific

Feedback

For additional information or queries on this page send feedback


pthread_mutex_destroy

Name

pthread_mutex_destroy
- free resources allocated for a mutex

Library

 libc_r.lib libpthread.lib libthr.lib

Synopsis
#include <pthread.h>
int pthread_mutex_destroy (pthread_mutex_t *mutex);

Return values

 If successful, pthread_mutex_destroy will return zero, otherwise an error number will be returned to indicate the error.

Detailed description

 The pthread_mutex_destroy function frees the resources allocated for mutex.

Examples

 pthread_mutexattr_t mta;
 int rc;
 /* Initialize a mutex attributes object */
 if((rc=pthread_mutexattr_init(&mta)) != 0) {
  fprintf(stderr,"Error at pthread_mutexattr_init(), rc=%d\n",rc);
  return -1;
 }
 /* Destroy the mutex attributes object */
 if((rc=pthread_mutexattr_destroy(&mta)) != 0) {
  fprintf(stderr,"Error at pthread_mutexattr_destroy(), rc=%d\n",rc);
  return -1;
 }

Errors

 The pthread_mutex_destroy function will fail if:
[EINVAL]
 | The value specified by mutex is invalid.
[EAGAIN]
 | Mutex is locked by another thread.

See also

 pthread_mutex_init, pthread_mutex_lock, pthread_mutex_trylock, pthread_mutex_unlock

Feedback

For additional information or queries on this page send feedback


pthread_mutex_init

Name

pthread_mutex_init
- create a mutex

Library

 libc_r.lib libpthread.lib libthr.lib

Synopsis
#include <pthread.h>
int pthread_mutex_init (pthread_mutex_t *mutex, const pthread_mutexattr_t *attr);

Return values

 If successful, pthread_mutex_init will return zero and put the new mutex id into mutex, otherwise an error number will be returned to indicate the error.

Detailed description

 The pthread_mutex_init function creates a new mutex, with attributes specified with attr. If attr is NULL the default attributes are used.

Examples

pthread_mutexattr_t mta;
 int rc;
 /* Initialize a mutex attributes object */
 if((rc=pthread_mutexattr_init(&mta)) != 0) {
  fprintf(stderr,"Error at pthread_mutexattr_init(), rc=%d\n",rc);
  return -1;
 }

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 mutex.

See also

 pthread_mutex_destroy, pthread_mutex_lock, pthread_mutex_trylock, pthread_mutex_unlock
The pthread_mutex_init function conforms to -p1003.1-96.

Feedback

For additional information or queries on this page send feedback


pthread_mutex_lock

Name

pthread_mutex_lock
- lock a mutex

Library

 libc_r.lib libpthread.lib libthr.lib

Synopsis
#include <pthread.h>
int pthread_mutex_lock (pthread_mutex_t *mutex);

Return values

 If successful, pthread_mutex_lock will return zero, otherwise an error number will be returned to indicate the error.

Detailed description

 The pthread_mutex_lock function locks mutex. If the mutex is already locked, the calling thread will block until the mutex becomes available.

Examples

pthread_mutex_t  mutex;
int XYZ()
{
 int rc;
 /* Initialize a mutex object with the default mutex attributes */
 if((rc=pthread_mutex_init(&mutex,NULL)) != 0) {
  fprintf(stderr,"Error at pthread_mutex_init(), rc=%d\n",rc);
  return -1;
 }
 /* Lock the mutex using pthread_mutex_lock() */
 if((rc=pthread_mutex_lock(&mutex)) == 0) {
  printf(" lock is successful\n");
 }
}

Errors

 The pthread_mutex_lock function will fail if:
[ENOSYS]
 | If locking is not supported for this mutex kind.
[ETIMEDOUT]
 | Mutex wait is timed out.
[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, pthread_mutex_init, pthread_mutex_trylock, pthread_mutex_unlock
The pthread_mutex_lock function conforms to -p1003.1-96.

Feedback

For additional information or queries on this page send feedback


pthread_mutex_timedlock

Name

pthread_mutex_timedlock
- lock a mutex without blocking indefinitely

Library

 libpthread.lib libthr.lib

Synopsis
#include <pthread.h>
#include <time.h>
int pthread_mutex_timedlock (pthread_mutex_t *mutex, const struct timespec *abstime);

Return values

 If successful, pthread_mutex_timedlock will return zero, otherwise an error number will be returned to indicate the error.

Detailed description

 The pthread_mutex_timedlock function will lock mutex. If it is already locked the calling thread will block until the mutex becomes available or the timeout, specified by abstime, expires. The time of the timeout is an absolute time and is not relative to the current time.

Examples

#include <sys/time.h>
#define TIMEOUT 3
/* 3 seconds of timeout time for  pthread_mutex_timedlock(). */
struct timespec timeout;
struct timeval currsec1;
int rc;
pthread_mutex_t  mutex;

/* Get the current time before the mutex locked. */
gettimeofday(&currsec1, NULL);
/* Absolute time, not relative. */
timeout.tv_sec = currsec1.tv_sec + TIMEOUT;
timeout.tv_nsec = currsec1.tv_usec * 1000;
printf("Timed mutex lock will block for %d seconds starting from: %ld.%06ld\n", TIMEOUT, (long)currsec1.tv_sec, (long)currsec1.tv_usec);
rc = pthread_mutex_timedlock(&mutex, &timeout);
if(rc != 0) {
  if (rc == ETIMEDOUT) {
   fprintf(stderr,"Thread stops waiting when time is out\n");
  }
  else {
   fprintf(stderr,"pthread_mutex_timedwait return %d\n", rc);
  }
}
fprintf(stderr,"Thread wakened up\n");

Errors

 The pthread_mutex_timedlock function will fail if:
[EINVAL]
 | The mutex was created with the protocol attribute having the value PTHREAD_PRIO_PROTECT and the calling thread’s priority is higher than the mutex’s current priority ceiling.
[EINVAL]
 | The process or thread would have blocked, and abs_timeout specified a nanosecond value less than zero or greater than or equal to 1 billion.
[EINVAL]
 | The mutex parameter is invalid.
[ETIMEDOUT]
 | The mutex could not be locked before the timeout expired.
[ENOSYS]
 | If locking is not supported for this mutex kind.
[EDEADLK]
 | The current thread already owns the mutex.

See also

 pthread_mutex_destroy, pthread_mutex_init, pthread_mutex_lock, pthread_mutex_trylock, pthread_mutex_unlock

Feedback

For additional information or queries on this page send feedback


pthread_mutex_trylock

Name

pthread_mutex_trylock
- attempt to lock a mutex without blocking

Library

 libc_r.lib libpthread.lib libthr.lib

Synopsis
#include <pthread.h>
int pthread_mutex_trylock (pthread_mutex_t *mutex);

Return values

 If successful, pthread_mutex_trylock will return zero, otherwise an error number will be returned to indicate the error.

Detailed description

 The pthread_mutex_trylock function locks mutex. If the mutex is already locked, pthread_mutex_trylock will not block waiting for the mutex, but will return an error condition.

Examples

int rc;
pthread_mutex_t  mutex;
rc = pthread_mutex_trylock(&mutex);
switch (rc)
{
   case 0:
       printf ("Locked successfully\n");
       break;
   case EAGAIN:
       printf ("could not lock, try later.....\n");
       break;
}

Errors

 The pthread_mutex_trylock function will fail if:
[EINVAL]
 | The value specified by mutex is invalid.
[EAGAIN]
 | Mutex is already locked.
[ENOSYS]
 | If locking is not supported for this mutex kind.

See also

 pthread_mutex_destroy, pthread_mutex_init, pthread_mutex_lock, pthread_mutex_unlock

Feedback

For additional information or queries on this page send feedback


pthread_mutex_unlock

Name

pthread_mutex_unlock
- unlock a mutex

Library

 libc_r.lib libpthread.lib libthr.lib

Synopsis
#include <pthread.h>
int pthread_mutex_unlock (pthread_mutex_t *mutex);

Return values

 If successful, pthread_mutex_unlock will return zero, otherwise an error number will be returned to indicate the error.

Detailed description

 If the current thread holds the lock on mutex, then the pthread_mutex_unlock function unlocks mutex.

Examples

static pthread_mutex_t    mutex = PTHREAD_MUTEX_INITIALIZER;
int XYZ()
{
   int  rc;
 /* Get the mutex using pthread_mutex_lock() */
 if((rc=pthread_mutex_lock(&mutex)) != 0) {
  fprintf(stderr,"Error at pthread_mutex_lock(), rc=%d\n",rc);
  return -1;
 }
 /* Release the mutex using pthread_mutex_unlock() */
 if((rc=pthread_mutex_unlock(&mutex)) != 0) {
  printf("unlock failed \n");
  return -1;
 }

Errors

 The pthread_mutex_unlock function will fail if:
[EINVAL]
 | The value specified by mutex is invalid.
[ENOSYS]
 | If locking is not supported for this mutex kind.

See also

 pthread_mutex_destroy, pthread_mutex_init, pthread_mutex_lock, pthread_mutex_trylock

Feedback

For additional information or queries on this page send feedback


pthread_mutexattr

Name

pthread_mutexattr_init, pthread_mutexattr_destroy, pthread_mutexattr_settype
pthread_mutexattr_gettype, pthread_mutexattr_getpshared, pthread_mutexattr_setpshared

- mutex attribute operations

Library

 libc_r.lib libpthread.lib libthr.lib

Synopsis
#include <pthread.h>
int pthread_mutexattr_init (pthread_mutexattr_t *attr);
int pthread_mutexattr_destroy (pthread_mutexattr_t *attr);
int pthread_mutexattr_settype (pthread_mutexattr_t *attr, int type);
int pthread_mutexattr_gettype (pthread_mutexattr_t *attr, int *type);
int pthread_mutexattr_getpshared (pthread_mutexattr_t *attr, int *pshared);
int pthread_mutexattr_setpshared (pthread_mutexattr_t *attr, int pshared);

Return values

 If successful, these functions return 0. Otherwise, an error number is returned to indicate the error.

Detailed description

 Mutex attributes are used to specify parameters to pthread_mutex_init. One attribute object can be used in multiple calls to pthread_mutex_init, with or without modifications between calls.

The pthread_mutexattr_init function initializes attr with all the default mutex attributes.

The pthread_mutexattr_destroy function destroys attr.

The pthread_mutexattr_set* functions set the attribute that corresponds to each function name.

The pthread_mutexattr_get* functions copy the value of the attribute that corresponds to each function name to the location pointed to by the second function parameter.

Examples

pthread_mutexattr_t mta;
 int rc;
 /* Initialize a mutex attributes object */
 if((rc=pthread_mutexattr_init(&mta)) != 0)
 {
  fprintf(stderr,"Cannot initialize mutex attributes object\n");
  return -1;
 }
 /* Destroy the mutex attributes object */
 if(pthread_mutexattr_destroy(&mta) != 0)
 {
  fprintf(stderr,"Error at pthread_mutexattr_destroy(), rc=%d\n", rc);
  return -1;
 }

 pthread_mutexattr_t mta;
 int pshared;
 /* Initialize a mutex attributes object */
 if(pthread_mutexattr_init(&mta) != 0)
 {
  perror("Error at pthread_mutexattr_init()\n");
  return -1;
 }
  /* The default ’pshared’ attribute is PTHREAD_PROCESS_PRIVATE  */
 if(pthread_mutexattr_getpshared(&mta, &pshared) != 0)
 {
  fprintf(stderr,"Error obtaining the attribute process-shared\n");
  return -1;
 }
if (pshared != PTHREAD_PROCESS_PRIVATE)
     printf (" pshared is NOT PTHREAD_PROCESS_PRIVATE\n");

 pthread_mutexattr_t mta;
 int type;
 /* Initialize a mutex attributes object */
 if(pthread_mutexattr_init(&mta) != 0)
 {
  perror("Error at pthread_mutexattr_init()\n");
  return -1;
 }
  /* The default ’type’ attribute  is PTHREAD_MUTEX_DEFAULT  */
 if(pthread_mutexattr_gettype(&mta, &type) != 0)
 {
  fprintf(stderr,"pthread_mutexattr_gettype(): Error obtaining the attribute ’type’\n");
  return -1;
 }
 if(type != PTHREAD_MUTEX_DEFAULT)
 {
  printf("FAILED: Incorrect default mutexattr ’type’ value: %d\n", type);
  return -1;
 }

pthread_mutexattr_t mta;
 int rc;
 /* Initialize a mutex attributes object */
 if((rc=pthread_mutexattr_init(&mta)) != 0)
 {
  fprintf(stderr,"Cannot initialize mutex attributes object\n");
  return -1;
 }
 /* Destroy the mutex attributes object */
 if(pthread_mutexattr_destroy(&mta) != 0)
 {
  fprintf(stderr,"Error at pthread_mutexattr_destroy(), rc=%d\n", rc);
  return -1;
 }

pthread_mutexattr_t mta;
 int ret;
 /* Initialize a mutex attributes object */
 if(pthread_mutexattr_init(&mta) != 0)
 {
  perror("Error at pthread_mutexattr_init()\n");
  return -1;
 }
 /* Set the ’pshared’ attribute to PTHREAD_PROCESS_PRIVATE */
 if((ret=pthread_mutexattr_setpshared(&mta, PTHREAD_PROCESS_PRIVATE)) != 0)
 {
  printf("FAILED: Cannot set pshared attribute to PTHREAD_PROCESS_PRIVATE. Error: %d\n", ret);
  return -1;
 }

 pthread_mutexattr_t mta;
 int type;
 /* Initialize a mutex attributes object */
 if(pthread_mutexattr_init(&mta) != 0)
 {
  perror("Error at pthread_mutexattr_init()\n");
  return -1;
 }
 if(pthread_mutexattr_gettype(&mta, &type) != 0)
 {
  printf("Error getting the attribute ’type’\n");
  return -1;
 }
 if(type != PTHREAD_MUTEX_DEFAULT)
 {
  printf("FAILED: Default value of the ’type’ attribute is not PTHREAD_MUTEX_DEFAULT \n");
  return -1;
 }
 if(pthread_mutexattr_settype(&mta, PTHREAD_MUTEX_NORMAL) != 0)
 {
  printf("FAILED: Error setting the attribute ’type’\n");
  return -1;
 }

Limitation

 The pthread_mutexattr_setpshared supports only PTHREAD_PROCESS_PRIVATE

Errors

 The pthread_mutexattr_init function will fail if:
[EINVAL]
Invalid value for attr.

The pthread_mutexattr_destroy function will fail if:
[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.

The pthread_mutexattr_setpshared function will fail if:
[EINVAL]
Invalid value for attr, or invalid value for type.

The pthread_mutexattr_getpshared function will fail if:
[EINVAL]
Invalid value for attr.

See also

 pthread_mutex_init

Feedback

For additional information or queries on this page send feedback


pthread_once

Name

pthread_once
- dynamic package initialization

Library

 libc_r.lib libpthread.lib libthr.lib

Synopsis
#include <pthread.h>

pthread_once_t once_control = PTHREAD_ONCE_INIT;

int pthread_once (pthread_once_t *once_control, void (*init_routine)(void));

Return values

 If successful, the pthread_once function will return zero. Otherwise an error number will be returned to indicate the error.

Detailed description

 The first call to pthread_once by any thread in a process, with a given once_control, will call the init_routine with no arguments. Subsequent calls to pthread_once with the same once_control will not call the init_routine. On return from pthread_once, it is guaranteed that init_routine has completed. The once_control parameter is used to determine whether the associated initialization routine has been called.

The constant PTHREAD_ONCE_INIT is defined by header
#include <pthread.h .>

The behavior of pthread_once is undefined if once_control has automatic storage duration or is not initialized by PTHREAD_ONCE_INIT.

Examples

/* The init function that pthread_once calls */
void an_init_func_1_1()
{
printf (" Initialized ..\n");
}
int XYZ()
{
 pthread_once_t once_control = PTHREAD_ONCE_INIT;
 /* Call pthread_once, passing it the once_control */
 pthread_once(&once_control, an_init_func_1_1);
 /* Call pthread_once again. The init function should not be
  * called. */
 pthread_once(&once_control, an_init_func_1_1);
}

Errors

 The pthread_once function may fail if:
[EINVAL]
If either once_control or init_routine is invalid.

Feedback

For additional information or queries on this page send feedback


pthread_schedparam

Name

pthread_setschedparam, pthread_getschedparam
- thread scheduling parameter manipulation

Library

 libc_r.lib libpthread.lib libthr.lib

Synopsis
#include <pthread.h>
int pthread_setschedparam (pthread_t thread, int policy, const struct sched_param *param);
int pthread_getschedparam (pthread_t thread, int *policy, struct sched_param *param);

Return values

 If successful, these functions return 0. Otherwise, an error number is returned to indicate the error.

Detailed description

 The pthread_setschedparam and pthread_getschedparam functions set and get the scheduling parameters of individual threads. The scheduling policy for a thread will be SCHED_RR (round-robin). ( SCHED_FIFO is not supported) The thread priority (accessed via param->sched_priority) must be at least PTHREAD_MIN_PRIORITY and no more than PTHREAD_MAX_PRIORITY.

Examples

struct sched_param sparam;
int policy, priority, policy_1;
int rc;
policy = SCHED_RR;
priority = 50;
sparam.sched_priority = priority;
rc = pthread_setschedparam(pthread_self(), policy, &sparam);
if (rc != 0)
{
  printf("Error at pthread_setschedparam: rc=%d\n", rc);
  return -1;
}

int e ;
struct sched_param param;
pthread_t thread; // Thread which will be assigned the scheduling priority and the policy.
pthread_t thread = pthread_self();
param.sched_priority = 100;

e = pthread_setschedparam(thread,SCHED_RR, & param);
if(e != 0)
{
   printf("setting scheduling policy and priority failed."));
   return -1;
}

int e ;
struct sched_param param;
pthread_t thread; // Thread which will be assigned the scheduling priority and the policy.
int policy;
pthread_t thread = pthread_self();
param.sched_priority = 100;

e = pthread_setschedparam(thread,SCHED_RR, & param);
if(e != 0)
{
   printf("setting scheduling policy and priority failed."));
   return -1;
}
e = pthread_getschedparam(thread,&policy,& param);
if (e != 0)
{
   printf("getting scheduling policy and priority failed."));
   return -1;
}

Limitation

 Only SCHED_RR policy is supported.

Errors

 The pthread_setschedparam function will fail if:
[EINVAL]
 | Invalid value for policy or param
[ENOTSUP]
 | Invalid value for scheduling parameters.
[ESRCH]
 | Non-existent thread thread.

The pthread_getschedparam function will fail if:
[ESRCH]
Non-existent thread thread.

Feedback

For additional information or queries on this page send feedback


pthread_self

Name

pthread_self
- get the calling thread’s ID

Library

 libc_r.lib libpthread.lib libthr.lib

Synopsis
#include <pthread.h>
pthread_t pthread_self (void);

Return values

 The pthread_self function returns the thread ID of the calling thread.

Detailed description

 The pthread_self function returns the thread ID of the calling thread.

Examples

pthread_t new_th2;
new_th2=pthread_self();

Errors

 None.

See also

 pthread_create, pthread_equal

Feedback

For additional information or queries on this page send feedback


pthread_setspecific

Name

pthread_setspecific
- set a thread-specific data value

Library

 libc_r.lib libpthread.lib libthr.lib

Synopsis
#include <pthread.h>
int pthread_setspecific (pthread_key_t key, const void *value);

Return values

 If successful, the pthread_setspecific function will return zero. Otherwise an error number will be returned to indicate the error.

Detailed description

 The pthread_setspecific function associates a thread-specific value with a key obtained via a previous call to pthread_key_create. Different threads can bind different values to the same key. These values are typically pointers to blocks of dynamically allocated memory that have been reserved for use by the calling thread.

The effect of calling pthread_setspecific with a key value not obtained from pthread_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 destructor function, however this may result in lost storage or infinite loops.

Examples

 pthread_key_t keys;
 void* rc;
if(pthread_key_create(&keys, NULL) != 0)
{
   printf("Error: pthread_key_create() failed\n");
   return -1;
} else
{
   if(pthread_setspecific(keys, (void *)(long)(100)) != 0)
   {
    printf("Error: pthread_setspecific() failed\n");
    return -1;
   }
}

Errors

 The pthread_setspecific function will fail if:
[EINVAL]
The key value is invalid.

See also

 pthread_getspecific, pthread_key_create, pthread_key_delete

Feedback

For additional information or queries on this page send feedback


putc

Name

fputc, putc, putc_unlocked, putchar, putchar_unlocked, putw
- output of characters and strings

Library

 libc.lib

Synopsis
#include <stdio.h>
int fputc (int c, FILE *stream);
int putc (int c, FILE *stream);
int putc_unlocked (int c, FILE *stream);
int putchar (int c);
int putchar_unlocked (int c);
int putw (int w, FILE *stream);

Return values

 The functions, fputc, putc, putchar, putc_unlocked, and putchar_unlocked return the character written. If an error 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 to a read-only stream.

Detailed description

 The fputc function writes the character c (converted to an ‘‘unsigned char’’) to the output stream pointed to by stream.

The putc macro that is identically to fputc, but is a macro that expands in-line. It may evaluate stream more than once, so arguments given to putc should not be expressions with potential side effects.

The putchar function is identical to putc with an output stream of stdout.

The putw function writes the specified int to the named output stream.

The putc_unlocked and putchar_unlocked functions are equivalent to putc and putchar respectively, except that the caller is responsible for locking the stream with flockfile before calling them. These functions may be used to avoid the overhead of locking the stream for each character, and to avoid output being interspersed from multiple threads writing to the same stream.

Examples

#include <stdio.h>
int main()
{
        FILE * fp;
        fp=fopen("C:\\input.txt","w+");

        if(fp==NULL)
                {
                printf("file opening failed\n");
                return -1;
                }
        if(putc('a',fp)!='a')
                {
                printf("putc failed\n");
                fclose(fp);
                return -1;
                }
        else printf("character successfully put by putc\n");

        fclose(fp);
        return 0;
}

Output

character successfully put by putc

See also

 ferror, flockfile, fopen, getc, putwc,

Limitation

 The size and byte order of an int varies from one machine to another, and putw is not recommended for portable applications.

Feedback

For additional information or queries on this page send feedback


putwc

Name

fputwc, putwc, putwchar
- write a wide character to a FILE stream

Library

 libc.lib

Synopsis
#include <stdio.h>
#include <wchar.h>
wint_t fputwc (wchar_t wc, FILE *stream);
wint_t putwc (wchar_t wc, FILE *stream);
wint_t putwchar (wchar_t wc);

Return values

 The fputwc, putwc, and putwchar functions return the wide character written. If an error occurs, the value WEOF is returned.

Detailed description

 The fputwc function writes the wide character wc to the output stream pointed to by stream.

The putwc function acts essentially identically to fputwc.

The putwchar function is identical to putwc with an output stream of stdout.

Examples

/* Illustrates how to use putwc API */
#include <stdio.h>
#include <wchar.h>
wint_t example_putwc(void)
{
 FILE *fp = NULL;
 wchar_t wc = L’a’;
 wint_t rval;
 /* opening the file to write*/
 fp = fopen("input.txt","w");
 if(fp == NULL)
 {
  wprintf(L"Error: File open\n");
  return (-1);
 }
/* write a character into fp */
 rval = putwc(wc, fp);
 /* Close the file opened for writing */
 fclose(fp);
 /* return the value that was written */
 return (rval);
}

/* Illustrates how to use fputwc API */
#include <stdio.h>
#include <wchar.h>
wint_t example_fputwc(void)
{
 FILE *fp = NULL;
 wchar_t wc = L’a’;
 wint_t rval;
 /* opening the file to write*/
 fp = fopen("input.txt","w");
 if(fp == NULL)
 {
  wprintf(L"Error: File open\n");
  return (-1);
 }
/* write a character into fp */
 rval = fputwc(wc, fp);
 /* Close the file opened for writing */
 fclose(fp);
 /* return the value that was written */
 return (rval);
}

/* Illustrates how to use putwchar API */
#include <stdio.h>
#include <wchar.h>
wint_t example_putwchar(void)
{
 wint_t rval;
 wchar_t wc = L’q’;

 /* write a character onto the standard output */
 rval = putwchar(wc);
 /* return the character that was written */
 return (rval);
}

Output of putwchar

q

See also

 ferror fopen getwc putc

Feedback

For additional information or queries on this page send feedback


qsort

Name

qsort - sorts an array

Library

 libc.lib

Synopsis
#include <stdlib.h>
void qsort (void *base, size_t nmemb, size_t size, int (*compar) (const void *, const void));

Return values

 The qsort function returns no value.

Detailed description

 The qsort function is a modified partition-exchange sort, or quicksort.

The qsort function sorts an array of nmemb objects, the initial member of which is pointed to by base. The size of each object is specified by size.

The contents of the array base are sorted in ascending order according to a comparison function pointed to by compar, which requires two arguments pointing to the objects being compared.

The comparison function must return an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second.

The algorithm implemented by qsort is not stable, that is, if two members compare as equal, their order in the sorted array is undefined.

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 Ns ’s Algorithm Q. Quicksort takes O N lg N average time. This implementation uses median selection to avoid its O N**2 worst-case behavior.

Examples

#include <stdio.h>
#include <stdlib.h>
int sort_function( const void *a, const void *b);

int main(void)
{
   int  x;
   int list[5] = {4,2,3,5,1};
   qsort((void *)list, 5, sizeof(list[0]), sort_function);
   for (x = 0; x < 5; x++)
   printf("%d\n", list[x]);

   return 0;
}
int sort_function( const void *a, const void *b)
{
 int *p1 = (int *)a;
 int val1 = *p1;
 int *p2 = (int *)b;
 int val2 = *p2;
 int x = -1;
 if(val1  > val2 )
   x=1;
 if(val1  == val2 )
   x=0;

 return x;
}

Output

1
2
3
4
5

Errors

 No errors are defined.

Feedback

For additional information or queries on this page send feedback


rand

Name

rand, srand
- pseudo-random number generator

Library

 libc.lib

Synopsis
#include <stdlib.h>
void srand (unsigned seed);
int rand (void);

Return values

 The rand function never returns return the next pseudo-random number in the sequence.

The srand function never returns.

Detailed description

 The rand function computes a sequence of pseudo-random integers in the range of 0 to RAND_MAX (as defined by the header file
#include <stdlib.h>).

The srand function sets its argument seed as the seed for a new sequence of pseudo-random numbers to be returned by rand. These sequences are repeatable by calling srand with the same seed value.

If no seed value is provided, the functions are automatically seeded with a value of 1.

The

Examples

#include <stdlib.h>
#include <stdio.h>

int main( void )
{
  int randArray[20];
  int i=0;

  while(i<20)
  {
        randArray[i]=rand();
        printf("\n%d", randArray[i]);
        i++;
  }

  return 0;
}

Output

16807
282475249
1622650073
984943658
1144108930
470211272
101027544
1457850878
1458777923
2007237709
823564440
1115438165
1784484492
74243042
114807987
1137522503
1441282327
16531729
823378840
143542612

#include <stdlib.h>
#include <stdio.h>
int main( void )
{
 int seedVal = 45454652;
 int randVal;
 srand(seedVal);
 randVal=rand();
 printf("Random Value returned is %d"), randVal);
}

Output

Random Value returned is 1599641479

Errors

 No errors are defined.

Feedback

For additional information or queries on this page send feedback


RAND_screen - add entropy to the PRNG

Name

RAND_add, RAND_seed
RAND_status

add entropy to the PRNG

Library

libcrypto.lib

Synopsis

#include <openssl/rand.h>
void RAND_seed(const void *buf, int num);
void RAND_add(const void *buf, int num, double entropy);
int  RAND_status(void);

Detailed Description

RAND_add() mixes the num bytes at buf into the PRNG state. Thus, if the data at buf are unpredictable to an adversary, this increases the uncertainty about the state and makes the PRNG output less predictable. Suitable input comes from user interaction (random key presses, mouse movements) and certain hardware events. The entropy argument is (the lower bound of) an estimate of how much randomness is contained in buf, measured in bytes. Details about sources of randomness and how to estimate their entropy can be found in the literature, e.g. RFC 1750.

RAND_add() may be called with sensitive data such as user entered passwords. The seed values cannot be recovered from the PRNG output.

OpenSSL makes sure that the PRNG state is unique for each thread. The application is responsible for seeding the PRNG by calling RAND_add() or RAND_load_file().

RAND_seed() is equivalent to RAND_add() when num == entropy.

Return Values

The functions do not return values.

See Also

rand(),
RAND_load_file(),
RAND_egd(), RAND_cleanup()

History

RAND_seed() and is available in all versions of SSLeay and OpenSSL. RAND_add() and RAND_status() have been added in OpenSSL 0.9.5.

Feedback

For additional information or queries on this page send feedback


RAND_pseudo_bytes - generate random data

Name

RAND_bytes, RAND_pseudo_bytes — generate random data

Library

libcrypto.lib

Synopsis

#include <openssl/rand.h>
int RAND_bytes(unsigned char *buf, int num);
int RAND_pseudo_bytes(unsigned char *buf, int num);

Detailed Description

RAND_bytes() puts num cryptographically strong pseudo-random bytes into buf. An error occurs if the PRNG has not been seeded with enough randomness to ensure an unpredictable byte sequence.

RAND_pseudo_bytes() puts num pseudo-random bytes into buf. Pseudo-random byte sequences generated by RAND_pseudo_bytes() will be unique if they are of sufficient length, but are not necessarily unpredictable. They can be used for non-cryptographic purposes and for certain purposes in cryptographic protocols, but usually not for key generation etc.

Return Values

RAND_bytes() returns 1 on success, 0 otherwise. The error code can be obtained by ERR_get_error(). RAND_pseudo_bytes() returns 1 if the bytes generated are cryptographically strong, 0 otherwise. Both functions return -1 if they are not supported by the current RAND method.

See Also

rand(),
ERR_get_error(),
RAND_add()

History

RAND_bytes() is available in all versions of SSLeay and OpenSSL. It has a return value since OpenSSL 0.9.5. RAND_pseudo_bytes() was added in OpenSSL 0.9.5.

Feedback

For additional information or queries on this page send feedback


RAND_cleanup - erase the PRNG state

Name

RAND_cleanup — erase the PRNG state

Library

libcrypto.lib

Synopsis

#include <openssl/rand.h>
void RAND_cleanup(void);

Detailed Description

RAND_cleanup() erases the memory used by the PRNG.

Return Values

RAND_cleanup() returns no value.

See Also

rand()

History

RAND_cleanup() is available in all versions of SSLeay and OpenSSL.

Feedback

For additional information or queries on this page send feedback


RAND_egd - query entropy gathering daemon

Name

RAND_egd — query entropy gathering daemon

Library

libcrypto.lib

Synopsis

#include <openssl/rand.h>
int RAND_egd(const char *path);
int RAND_egd_bytes(const char *path, int bytes);
int RAND_query_egd_bytes(const char *path, unsigned char *buf, int bytes);

Detailed Description

RAND_egd() queries the entropy gathering daemon EGD on socket path. It queries 255 bytes and uses RAND_add() to seed the OpenSSL built-in PRNG. RAND_egd(path) is a wrapper for RAND_egd_bytes(path, 255);

RAND_egd_bytes() queries the entropy gathering daemon EGD on socket path. It queries bytes bytes and uses RAND_add() to seed the OpenSSL built-in PRNG. This function is more flexible than RAND_egd(). When only one secret key must be generated, it is not necessary to request the full amount 255 bytes from the EGD socket. This can be advantageous, since the amount of entropy that can be retrieved from EGD over time is limited.

RAND_query_egd_bytes() performs the actual query of the EGD daemon on socket path. If buf is given, bytes bytes are queried and written into buf. If buf is NULL, bytes bytes are queried and used to seed the OpenSSL built-in PRNG using RAND_add().

Return Values

The functions always return -1

See Also

rand(),
RAND_add(),
RAND_cleanup()

History

RAND_egd() is available since OpenSSL 0.9.5.

RAND_egd_bytes() is available since OpenSSL 0.9.6.

RAND_query_egd_bytes() is available since OpenSSL 0.9.7.

Feedback

For additional information or queries on this page send feedback


RAND_file_name - PRNG seed file

Name

RAND_load_file, RAND_write_file
RAND_file_name

PRNG seed file

Library

libcrypto.lib

Synopsis

#include <openssl/rand.h>
const char *RAND_file_name(char *buf, size_t num);
int RAND_load_file(const char *filename, long max_bytes);
int RAND_write_file(const char *filename);

Detailed Description

RAND_file_name() generates a default path for the random seed file. buf points to a buffer of size num in which to store the filename. The seed file is $RANDFILE if that environment variable is set, $HOME/.rnd otherwise. If $HOME is not set either, or num is too small for the path name, an error occurs.

RAND_load_file() reads a number of bytes from file filename and adds them to the PRNG. If max_bytes is non-negative, up to max_bytes are read; starting with OpenSSL 0.9.5, if max_bytes is -1, the complete file is read.

RAND_write_file() writes a number of random bytes (currently 1024) to file filename which can be used to initialize the PRNG by calling RAND_load_file() in a later session.

Return Values

RAND_load_file() returns the number of bytes read.

RAND_write_file() returns the number of bytes written, and -1 if the bytes written were generated without appropriate seed.

RAND_file_name() always returns a NULL value.

See Also

rand(),
RAND_add(),
RAND_cleanup()

History

RAND_load_file(), RAND_write_file() and RAND_file_name() are available in all versions of SSLeay and OpenSSL.

Feedback

For additional information or queries on this page send feedback


RAND_SSLeay - select RAND method

Name

RAND_set_rand_method, RAND_get_rand_method
RAND_SSLeay

select RAND method

Library

libcrypto.lib

Synopsis

#include <openssl/rand.h>
void RAND_set_rand_method(const RAND_METHOD *meth);
const RAND_METHOD *RAND_get_rand_method(void);
RAND_METHOD *RAND_SSLeay(void);

Detailed Description

A RAND_METHOD specifies the functions that OpenSSL uses for random number generation. By modifying the method, alternative implementations such as hardware RNGs may be used. IMPORTANT: See the NOTES section for important information about how these RAND API functions are affected by the use of ENGINE API calls.

Initially, the default RAND_METHOD is the OpenSSL internal implementation, as returned by RAND_SSLeay().

RAND_set_default_method() makes meth the method for PRNG use. NB: This is true only whilst no ENGINE has been set as a default for RAND, so this function is no longer recommended.

RAND_get_default_method() returns a pointer to the current RAND_METHOD. However, the meaningfulness of this result is dependant on whether the ENGINE API is being used, so this function is no longer recommended.

The RAND_METHOD Structure

 typedef struct rand_meth_st
 {
        void (*seed)(const void *buf, int num);
        int (*bytes)(unsigned char *buf, int num);
        void (*cleanup)(void);
        void (*add)(const void *buf, int num, int entropy);
        int (*pseudorand)(unsigned char *buf, int num);
        int (*status)(void);
 } RAND_METHOD;

The components point to the implementation of RAND_seed(), RAND_bytes(), RAND_cleanup(), RAND_add(), RAND_pseudo_rand() and RAND_status(). Each component may be NULL if the function is not implemented.

Return Values

RAND_set_rand_method() returns no value. RAND_get_rand_method() and RAND_SSLeay() return pointers to the respective methods.

Notes

As of version 0.9.7, RAND_METHOD implementations are grouped together with other algorithmic APIs (eg. RSA_METHOD, EVP_CIPHER, etc) in ENGINE modules. If a default ENGINE is specified for RAND functionality using an ENGINE API function, that will override any RAND defaults set using the RAND API (i.e. RAND_set_rand_method()). For this reason, the ENGINE API is the recommended way to control default implementations for use in RAND and other cryptographic algorithms.

See Also

rand(), engine()

History

RAND_set_rand_method(),
RAND_get_rand_method() and
 RAND_SSLeay() are
available in all versions of OpenSSL.

In the engine version of version 0.9.6, RAND_set_rand_method() was altered to take an ENGINE pointer as its argument. As of version 0.9.7, that has been reverted as the ENGINE API transparently overrides RAND defaults if used, otherwise RAND API functions work as before. RAND_set_rand_engine() was also introduced in version 0.9.7.

Feedback

For additional information or queries on this page send feedback


random

Name

random, srandom, srandomdev, initstate, setstate
- better random number generator; routines for changing generators

Library

 libc.lib

Synopsis
#include <stdlib.h>
long random (void);
void srandom (unsigned long seed);
void srandomdev (void);
char * initstate (unsigned long seed, char *state, long n);
char * setstate (char *state);

Detailed description

 The random function uses a non-linear additive feedback random number generator employing a default table of size 31 long integers to return successive pseudo-random numbers in the range from 0 to 2310-1. The period of this random number generator is very large, approximately 16×(2310-1).

The random and srandom functions have (almost) the same calling sequence and initialization properties as the rand3 and srand3 functions. The difference is that rand3 produces a much less random sequence — in fact, the low dozen bits generated 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, random will by default produce a sequence of numbers that can be duplicated by calling srandom with ‘1’ as the seed.

The srandomdev routine initializes a state array using the random random number device which returns good random numbers, suitable for cryptographic use. Note that this particular seeding procedure can generate states which are impossible to reproduce by calling srandom with any value, since the succeeding terms in the state buffer are no longer derived from the LC algorithm applied to a fixed seed.

The initstate routine allows a state array, passed in as an argument, to be initialized for future use. The size of the state array (in bytes) is used by initstate to decide how sophisticated a random number generator it should use — the more state, the better the random numbers will be. (Current "optimal" values for the amount of state information are 8, 32, 64, 128, and 256 bytes; other amounts will be rounded down to the nearest known amount. Using less than 8 bytes will cause an error.) The seed for the initialization (which specifies a starting point for the random number sequence, and provides for restarting at the same point) is also an argument. The initstate function returns a pointer to the previous state information array.

Once a state has been initialized, the setstate routine provides for rapid switching between states. The setstate function returns a pointer to the previous state array; its argument state array is used for further random number generation until the next call to initstate or setstate.

Once a state array has been initialized, it may be restarted at a different point either by calling initstate (with the desired seed, the state array, and its size) or by calling both setstate (with the state array) and srandom (with the desired seed). The advantage of calling both setstate and srandom is that the size of the 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 is greater than 2690, which should be sufficient for most purposes.

Examples

//Illustrates how to use random API.
#include <stdlib.h>
void  randomTest()
{
      long randNum;
       // Function call to generate the random number.
       randNum = random();
       //print the random number generated.
       printf(“ random number is %d \n”,randNum);
}

Output

random number is 1804289383

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 on the standard error output.

See also

 arc4random, rand, srand, random
These functions appeared in BSD 4.2.

Authors

 Earl T. Cohen

Bugs

 About 2/3 the speed of rand

The historical implementation used to have a very weak seeding; the random sequence did not vary much with the seed. The current implementation employs a better pseudo-random number generator for the initial state calculation.

Applications requiring cryptographic quality randomness should use arc4random

Feedback

For additional information or queries on this page send feedback


RC4 - RC4 encryption

Name

RC4_set_key, RC4 — RC4 encryption

Library

libcrypto.lib

Synopsis

#include <openssl/rc4.h>void RC4_set_key(RC4_KEY *key, int len, const unsigned char *data);
void RC4(RC4_KEY *key, unsigned long len, const unsigned char *indata, unsigned char *outdata);

Detailed Description

This library implements the Alleged RC4 cipher, which is described for example in Applied Cryptography. It is believed to be compatible with RC4[TM], a proprietary cipher of RSA Security Inc.

RC4 is a stream cipher with variable key length. Typically, 128 bit (16 byte) keys are used for strong encryption, but shorter insecure key sizes have been widely used due to export restrictions.

RC4 consists of a key setup phase and the actual encryption or decryption phase.

RC4_set_key() sets up the RC4_KEY key using the len bytes long key at data.

RC4() encrypts or decrypts the len bytes of data at indata using key and places the result at outdata. Repeated RC4() calls with the same key yield a continuous key stream.

Since RC4 is a stream cipher (the input is XORed with a pseudo-random key stream to produce the output), decryption uses the same function calls as encryption.

Applications should use the higher level functions EVP_EncryptInit() etc. instead of calling the RC4 functions directly.

Return Values

RC4_set_key() and RC4() do not return values.

Notes

Certain conditions have to be observed to securely use stream ciphers. It is not permissible to perform multiple encryptions using the same key stream.

See Also

des(), rc2()

History

RC4_set_key() and RC4() are available in all versions of SSLeay and OpenSSL.

Feedback

For additional information or queries on this page send feedback


read

Name

read, readv
- bash built-in commands

Library

 libc.lib

Synopsis
#include <sys/types.h>
#include <sys/uio.h>
#include <unistd.h>
ssize_t read (int d, void *buf, size_t nbytes);

ssize_t readv (int d, const struct iovec *iov, int iovcnt);

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 is set to indicate the error.

Detailed description

 The read system call attempts to read nbytes of data from the object referenced by the descriptor d into the buffer pointed to by buf. The readv system call performs the same action, but scatters the input data into the iovcnt buffers specified by the members of the iov array: iov[0], iov[1], ..., iov[iovcnt-1].

For readv the iovec structure is defined as:

struct iovec {
        void   *iov_base;  /* Base address. */
        size_t iov_len;    /* Length. */
};

Each iovec entry specifies the base address and length of an area in memory where data should be placed. The readv system call will always fill an area completely before proceeding to the next.

On objects capable of seeking, the read starts at a position given by the pointer associated with d (see lseek Upon return from read, the pointer is incremented by the number of bytes actually read.

Objects that are not capable of seeking always read from the current position. The value of the pointer associated with such an object is undefined.

Upon successful completion, read, and readv return the number of bytes actually read and placed in the buffer. The system guarantees to read the number of bytes requested if the descriptor references a normal file that has that many bytes left before the end-of-file, but in no other case.

Examples

/************************************************************************************
* Detailed description :This example demonstrates usage of read-system call, this
* Example reads 10 bytes from a file specified
*
* Preconditions: Example.txt file should be present in C: and should contain
* string Hello World.
*
*************************************************************************************** /
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
int main()
{
  int fd = 0;
  char Buff[12] = {0};

  fd = open("C:\\Example.txt" , O_RDONLY );

  if(fd < 0 )  {
     printf("Failed to open C:\\Example.txt file\n");
     return -1;
  }

  if(read(fd , Buff , 11) < 11)   {
     printf("Failed to read specified number of bytes from file\n");
     return -1;
  }

  printf("file contains %s \n" , Buff);
  return 0;
}

Output

file contains Hello World

/**
  * Detailed description: Sample usage of readv system call
  * Preconditions: Example.txt file should be present in working directory containing  Hello world   in it
  *
**/
#include <stdio.h>
#include <sys/types.h>
#include <sys/uio.h>
#include <fcntl.h>
int main()
{
  int fd = 0;
  struct iovec io_vec[1];
  char Buf[12] = { 0 };
  io_vec[0].iov_base  = Buf;
  io_vec[0].iov_len = 11;
  fd = open("Example.txt" , O_RDONLY );
  if(fd < 0 )  {
    printf("File open failed  \n");
    return -1;
  }
  if(readv(fd , io_vec , 1) <  11 )   {
    printf("Failed to read fron Example.txt file \n");
    return -1;
  }
  printf("Read succes %s \n"  , io_vec[0].iov_base);
  return 0;
}

Output

Read succes Hello World

Errors

 The read, and readv system calls will succeed unless:
[EBADF]
 | The d argument is not a valid file or socket descriptor open for reading.
[ECONNRESET]
 | The d argument refers to a socket, and the remote socket end is forcibly closed.
[EFAULT]
 | The buf argument points outside the allocated address space(Not supported).
[EIO] | An I/O error occurred while reading from the file system(Not supported).
[EINTR]
 | A read from a slow device was interrupted before any data arrived by the delivery of a signal(Not supported).
[EINVAL]
 | The pointer associated with d was negative.
[EAGAIN]
 | The file was marked for non-blocking I/O, and no data were ready to be read.
[EISDIR]
 | The file descriptor is associated with a directory residing on a file system that does not allow regular read operations on directories (e.g. NFS)(Not supported).
[EOPNOTSUPP]
 | The file descriptor is associated with a file system and file type that do not allow regular read operations on it(Not supported).
[EOVERFLOW]
 | The file descriptor is associated with a regular file, nbytes is greater than 0, offset is before the end-of-file, and offset is greater than or equal to the offset maximum established for this file system(Not supported).
[EINVAL]
 | The value nbytes is greater than INT_MAX.

In addition, readv and preadv may return one of the following errors:
[EINVAL]
 | The iovcnt argument was less than or equal to 0, or greater than IOV_MAX.
[EINVAL]
 | One of the iov_len values in the iov array was negative.
[EINVAL]
 | The sum of the iov_len values in the iov array overflowed a 32-bit integer.
[EFAULT]
 | Part of the iov array points outside the process’s allocated address space.

See also

 dup, fcntl, getdirentries, open, pipe, select, socket, socketpair, fread, readdir

Feedback

For additional information or queries on this page send feedback


readdir

Name

opendir, readdir, readdir_r, telldir, seekdir, rewinddir, closedir, dirfd
- directory operations

Library

 libc.lib

Synopsis
#include <sys/types.h>
#include <dirent.h>
DIR * opendir (const char *filename);
struct dirent * readdir (DIR *dirp);
int readdir_r (DIR *dirp, struct dirent *entry, struct dirent **result);
long telldir (DIR *dirp);
void seekdir (DIR *dirp, long loc);
void rewinddir (DIR *dirp);
int closedir (DIR *dirp);
int dirfd (DIR *dirp);

Return values

readdir function returns a pointer to a dirent structure, or NULL if an error occurs or end-of-file is reached.

Detailed description

 The opendir function opens the directory named by filename, associates a directory stream with it and returns a pointer to be used to identify the directory stream in subsequent operations. The pointer NULL is returned if filename cannot be accessed, or if it cannot malloc enough memory to hold the whole thing.

The readdir function returns a pointer to the next directory entry. It returns NULL upon reaching the end of the directory or detecting an invalid seekdir operation.

The readdir_r function provides the same functionality as readdir, but the caller must provide a directory entry buffer to store the results in. If the read succeeds, result is pointed at the entry; upon reaching the end of the directory result is set to NULL. The readdir_r function returns 0 on success or an error number to indicate failure.

The telldir function returns the current location associated with the named directory stream. Values returned by telldir are good only for the lifetime of the DIR pointer, dirp, from which they are derived. If the directory is closed and then reopened, prior values returned by telldir will no longer be valid.

The seekdir function sets the position of the next readdir operation on the directory stream. The new position reverts to the one associated with the directory stream when the telldir operation was performed.

The rewinddir function resets the position of the named directory stream to the beginning of the directory.

The closedir function closes the named directory stream and frees the structure associated with the dirp pointer, returning 0 on success. On failure, -1 is returned and the global variable errno is set to indicate the error.

The dirfd function returns the integer file descriptor associated with the named directory stream, see open

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;
Note:
 Any changes happening to Directory after opendir call, will not be reflected by subsiquent readdir calls.

Examples

 /**
  * Detailed description: Sample usage of readdir call
  * Preconditions:  Example Directory should be present in current working directory
**/
#include <dirent.h>
#include  <unistd.h>
#include <sys/types.h>
int main()
{
  DIR *dirName;
  struct dirent *Dir;
  dirName = opendir("Example");
  if(dirName == NULL )  {
     printf("Failed to open directory \n");
     return -1;
  }
  if(!(Dir = readdir(dirName))  )  {
    printf("Read dir failed  \n");
    return -1;
  }
 printf("Directory Example read \n");
 closedir(dirName);
 return 0;
}

Output

Directory Example read

See also

 close, lseek, open, read, dir
The opendir, readdir, telldir, seekdir, rewinddir, closedir, and dirfd functions appeared in BSD 4.2

Feedback

For additional information or queries on this page send feedback


readlink

Name

readlink - read value of a symbolic link

Library

 libc.lib

Synopsis
#include <unistd.h>
int readlink (const char *path, char *buf, int bufsiz);

Return values

 The call returns the count of characters placed in the buffer if it succeeds, or a -1 if an error occurs, placing the error code in the global variable errno.

Detailed description

 The readlink system call places the contents of the symbolic link path in the buffer buf, which has size bufsiz. The readlink system call does not append a NUL character to buf.

Examples

/*
* Detailed description: Example to read a link file
* Precondition: "Parent.txt" should exist in c: drive with some contents
*                of length atleast 25 characters.  And a link file by name
*                "C:\Link" pointing to parent file should exist.
*
*/
#include <unistd.h>
#include <stdio.h>
int main(void)
{
    char rdbuff[25];
    int retval;
   if((retval = (readlink("C:\\Link", rdbuff, (sizeof(char)*25)))) < 0)
    {
       printf("Read through link file failed");
       perror(" ");
       return -1;
    }
    printf("Read through link file succeeded");
}

Output

Read through link file succeeded.

Errors

 The readlink system call will fail if:
[ENOENT]
 | The named file does not exist.
[ENAMETOOLONG]
 | A component or an entire path name exceeded 255 characters.
[EINVAL]
 | A relative path was encountered in translating path and is not supported by the platform.
[ENOENT]
 | An empty path was encountered while translating the pathname.

See also

 lstat, stat, symlink, symlink

Feedback

For additional information or queries on this page send feedback


realpath

Name

realpath - returns the canonicalized absolute pathname

Library

 libc.lib

Synopsis
#include <sys/param.h>
#include <stdlib.h>
char * realpath (const char *pathname, char resolved_path[PATH_MAX]);

Return values

 The realpath function returns resolved_path on success. If an error occurs, realpath returns NULL, and resolved_path contains the pathname which caused the problem.

Detailed description

 The realpath function resolves all symbolic links, extra "/" characters and references to /./ and /../ in pathname, and copies the resulting absolute pathname into the memory referenced by resolved_path. The resolved_path argument must refer to a buffer capable of storing at least PATH_MAX characters.

The realpath function will resolve both absolute and relative paths and return the absolute pathname corresponding to pathname. All but the last component of pathname must exist when realpath is called.

Examples

#include<stdlib.h>
#include<stdio.h> //printf
#include<sys/stat.h> //S_IWUSR
#include<sys/syslimits.h> //PATH_MAX
#include<unistd.h> //chdir

int main()
{
 char resolvepath[PATH_MAX];
 FILE *fp = NULL;
 char *rpath = NULL;
 int isymlink = 0;

 fp = fopen("c:\\xyz.txt", "w");
 if(!fp)
 {
     printf("fopen failed!!");
     return -1;
 }

 mkdir("c:\\tmdir", S_IWUSR);

 int c = chdir("c:\\");
 if(c == -1)
 {
     printf("chdir failed!!");
     return -1;
 }

 rpath = realpath(".\\tmdir\\..\\xyz.txt", resolvepath);
 printf("resolvepath: %s\n", resolvepath);
 if(rpath != NULL)
    printf("rpath: %s\n\n", rpath);

 fclose(fp);
 rmdir("c:\\tmdir");
 unlink("c:\\xyz.txt");

 mkdir("c:\\tdir", S_IWUSR);

 fp = fopen("c:\\tdir\\xyz.txt", "w");
 if(!fp)
 {
     printf("fopen failed!!");
     return -1;
 }

 fclose(fp);

 unlink("c:\\linkname.txt");

 isymlink = symlink("c:\\tdir\\xyz.txt", "c:\\linkname.txt");
 if (isymlink == -1)
 {
     printf("symlink failed!!");
     return -1;
 }

 rpath = realpath("c:\\linkname.txt", resolvepath);

 printf("resolvepath: %s\n", resolvepath);
 if(rpath != NULL)
    printf("rpath: %s\n", rpath);

 unlink("c:\\tdir\\xyz.txt");
 rmdir("c:\\tdir");

 return 0;
}

Output

resolvepath: C:\xyz.txt
rpath: C:\xyz.txt
resolvepath: c:\tdir\xyz.txt
rpath: c:\tdir\xyz.txt

Security considerations

 The realpath has Off-by-One Overflow.If possible the user must supply a specially crafted pathname that is 1024 characters in length to the realpath function. A buffer can be overwritten with a single byte (NULL) if the pathname contains two or more directory separators.

This function may permit buffer overflow depeding upon its user.

Errors

 The function realpath may fail and set the external variable errno for any of the errors specified for the library functions readlink and getcwd.

See also

 getcwd

Feedback

For additional information or queries on this page send feedback


recv

Name

recv, recvfrom, recvmsg
- receive a message from a socket

Library

 libc.lib

Synopsis
#include <sys/socket.h>
ssize_t recv (int s, void *buf, size_t len, int flags);
ssize_t recvfrom (int s, void * restrict buf, size_t len, int flags, struct sockaddr * restrict from, socklen_t * restrict fromlen);
ssize_t recvmsg (int s, struct msghdr *msg, int flags);

Return values

 These calls return the number of bytes received, or -1 if an error occurred.

Detailed description

 The recvfrom and recvmsg system calls are used to receive messages from a socket, and may be used to receive data on a socket whether or not it is connection-oriented.

If from is not a null pointer and the socket is not connection-oriented, the source address of the message is filled in. The fromlen argument is a value-result argument, initialized to the size of the buffer associated with from, and modified on return to indicate the actual size of the address stored there.

The recv function is normally used only on a connected socket (see connect and is identical to recvfrom with a null pointer passed as its from argument. As it is redundant, it may not be supported in future releases.

All three routines return the length of the message on successful completion. If a message is too long to fit in the supplied buffer, excess bytes may be discarded depending on the type of socket the message is received from (see socket

If no messages are available at the socket, the receive call waits for a message to arrive, unless the socket is nonblocking (see fcntl in which case the value -1 is returned and the external variable errno set to EAGAIN. The receive calls normally return any data available, up to the requested amount, rather than waiting for receipt of the full amount requested; this behavior is affected by the socket-level options SO_RCVLOWAT and SO_RCVTIMEO described in getsockopt.

The select system call may be used to determine when more data arrive.

The flags argument to a recv function is formed by or Ap 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
MSG_DONTWAIT       do not block

The MSG_OOB flag requests receipt of out-of-band data that would not be received in the normal data stream. Some protocols place expedited data at the head of the normal data queue, and thus this flag cannot be used with such protocols. The MSG_PEEK flag causes the receive operation to return data from the beginning of the receive queue without removing that data from the queue. Thus, a subsequent receive call will return the same data. The MSG_WAITALL flag requests that the operation block until the full request is satisfied. The MSG_DONTWAIT flag requests the call to return when it would block otherwise. If no data is available, errno is set to EAGAIN.

The recvmsg system call uses a msghdr structure to minimize the number of directly supplied arguments. This structure has the following form, as defined in
#include <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 is unconnected; msg_name may be given as a null pointer if no names are desired or required. The msg_iov and msg_iovlen arguments describe scatter gather locations, as discussed in read. The msg_control argument, which has length msg_controllen, points to a buffer for other protocol control related messages or other miscellaneous ancillary data. The messages are of the form:

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 in XNS/SPP, or in ISO, to obtain user-connection-request data by requesting a recvmsg with no data buffer provided immediately after an accept system call.

Open file descriptors are now passed as ancillary data for AF_UNIX domain sockets, with cmsg_level set to SOL_SOCKET and cmsg_type set to SCM_RIGHTS.

Process credentials can also be passed as ancillary data for AF_UNIX domain sockets using a cmsg_type of SCM_CREDS. In this case, cmsg_data should be a structure of type cmsgcred, which is defined in

#include <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_ngroups;         /* number or groups */
        gid_t   cmcred_groups[CMGROUP_MAX];     /* groups */
};

The kernel will fill in the credential information of the sending process and deliver it to the receiver.

The msg_flags field is set on return according to the message received. MSG_EOR indicates end-of-record; the data returned completed a record (generally used with sockets of type SOCK_SEQPACKET). MSG_TRUNC indicates that the trailing portion of a datagram was discarded because the datagram was larger than the buffer supplied. MSG_CTRUNC indicates that some control data were discarded due to lack of space in the buffer for ancillary data. MSG_OOB is returned to indicate that expedited or out-of-band data were received.

Examples

#include <sys/socket.h>
#include <netinet/in.h>
#include <unistd.h>
void Recv()
{
   struct sockaddr_in serv_addr;
   int sock_fd;
   char line[10];
   int size = 10;
   serv_addr.sin_family = AF_INET;
   serv_addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
   serv_addr.sin_port = htons(5000);
   sock_fd = socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
   connect(sock_fd,(struct sockaddr*)&serv_addr,sizeof(serv_addr));
   recv(sock_fd, line, size, 0);
   close(sock_fd);
}

#include <sys/socket.h>
#include <netinet/in.h>
#include <unistd.h>
void Sendto()
{
   struct sockaddr_in sender_addr;
   int sock_fd;
   char line[15] = "Hello World!";
   unsigned int size = sizeof(sender_addr);
   sock_fd = socket(AF_INET,SOCK_DGRAM,IPPROTO_UDP);
   sender_addr.sin_family = AF_INET;
   sender_addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
   sender_addr.sin_port = htons(5000);
   recvfrom(sock_fd,line,13,0,(struct sockaddr*)&sender_addr,&size);
   close(sock_fd);
}

#include <sys/socket.h>
#include <netinet/in.h>
#include <unistd.h>
void SendMsgRecvMsg()
{
   int sock_fd;
   unsigned int sender_len;
   struct msghdr msg;
   struct iovec iov;
   struct sockaddr_in receiver_addr,sender_addr;
   char line[10];
   sock_fd = socket(AF_INET,SOCK_DGRAM,IPPROTO_UDP);
   receiver_addr.sin_family = AF_INET;
   receiver_addr.sin_addr.s_addr = htonl(INADDR_ANY);
   receiver_addr.sin_port = htons(5000);
   bind(sock_fd,(struct sockaddr*)&receiver_addr,sizeof(receiver_addr));
   sender_len = sizeof(sender_addr);
   msg.msg_name = &sender_addr;
   msg.msg_namelen = sender_len;
   msg.msg_iov = &iov;
   msg.msg_iovlen = 1;
   msg.msg_iov->iov_base = line;
   msg.msg_iov->iov_len = 10;
   msg.msg_control = 0;
   msg.msg_controllen = 0;
   msg.msg_flags = 0;
   recvmsg(sock_fd,&msg,0);
   close(sock_fd);
}

Errors

 The calls fail if:
[EBADF]
 | The argument s is an invalid descriptor.
[ECONNRESET]
 | The remote socket end is forcibly closed.
[ENOTCONN]
 | The socket is associated with a connection-oriented protocol and has not been connected (see connect and accept
[ENOTSOCK]
 | The argument s does not refer to a socket.
[EMSGSIZE]
 | The recvmsg system call was used to receive rights (file descriptors) that were in flight on the connection. However, the receiving program did not have enough free file descriptor slots to accept the them. In this case the descriptors are closed, any pending data can be returned by another call to recvmsg.
[EAGAIN]
 | The socket is marked non-blocking, and the receive operation would block, or a receive timeout had been set, and the timeout expired before data were received.
[EFAULT]
 | The receive buffer pointer(s) point outside the process’s address space.

See also

 fcntl, getsockopt, read, select socket
The recv function appeared in BSD 4.2.

Feedback

For additional information or queries on this page send feedback


regex

Name

regcomp, regexec, regerror, regfree
- POSIX regex functions

Library

 libc.lib

Synopsis
#include <regex.h>
int regcomp (regex_t * restrict preg, const char * restrict pattern, int cflags);
int regexec (const regex_t * restrict preg, const char * restrict string, size_t nmatch, regmatch_t pmatch[restrict], int eflags);
size_t regerror (int errcode, const regex_t * restrict preg, char * restrict errbuf, size_t errbuf_size);
void regfree (regex_t *preg);

Return values

regcomp function returns zero for a successful compilation or an error code for failure.

regexec function returns zero for a successful match or REG_NOMATCH for failure.

Detailed description

 These routines implement regular expressions ("REs.") The regcomp function compiles an RE written as a string into an internal form, regexec matches that internal form against a string and reports results, regerror transforms error codes from either into human-readable messages, and regfree frees any dynamically-allocated storage used by the internal form of an RE.

The header
#include <regex.h>declares two structure types,
regex_t and
regmatch_t, the former for compiled internal forms and the latter for match reporting. It also declares the four functions, a type
regoff_t, and a number of constants with names starting with "REG_."

The regcomp function compiles the regular expression contained in the pattern string, subject to the flags in cflags, and places the results in the

regex_t structure pointed to by preg. The cflags argument 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 to REG_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 a literal string. This is an extension, compatible with but not specified by, and should be used with caution in software intended to be portable to other systems. REG_EXTENDED and REG_NOSPEC may not be used in the same call to regcomp.
REG_ICASE | Compile for matching that ignores upper/lower case distinctions.
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, newline is a completely ordinary character with no special meaning in either REs or strings. With this flag, ‘[^’ bracket expressions and ‘.’ never match newline, a ‘^’ anchor matches the null string after any newline in the string in addition to its normal function, and the ‘$’ anchor matches the null string before any newline in the string in addition to its normal function.
REG_PEND | The regular expression ends, not at the first NUL, but just before the character pointed to by the re_endp member of the structure pointed to by preg. The re_endp member is of type
const char *. This flag permits inclusion of NULs in the RE; they are considered ordinary characters.

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 type

size_t, contains the number of parenthesized subexpressions within the RE (except that the value of this member is undefined if the REG_NOSUB flag was used). If regcomp fails, it returns a non-zero error code; see DIAGNOSTICS.

The regexec function matches the compiled RE pointed to by preg against the string, subject to the flags in eflags, and reports results using nmatch, pmatch, and the returned value. 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 compiled RE can be used simultaneously by multiple threads.

By default, the NUL-terminated string pointed to by string is considered to be the text of an entire line, minus any terminating newline. The eflags argument is the bitwise 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 not affect 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 affect the 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 located at string + pmatch [0]. rm_eo (there need not actually be a NUL at that location), regardless of the value of nmatch. See below for the definition of pmatch and nmatch. Note that a non-zero rm_so does not imply REG_NOTBOL; REG_STARTEND affects only the location of the string, not how it is matched.

Normally, regexec returns 0 for success and the non-zero code REG_NOMATCH for failure. Other non-zero error codes may be returned in exceptional situations; see DIAGNOSTICS.

If REG_NOSUB was specified in the compilation of the RE, or if nmatch is 0, regexec ignores the pmatch argument (but see below for the case where REG_STARTEND is specified). 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), containing respectively the offset of the first character of a substring and the offset of the first character after the end of the substring. Offsets are measured from the beginning of the string argument given to regexec. An empty substring is denoted by equal offsets, both indicating the character following the empty substring.

The 0th member of the pmatch array is filled in to indicate what substring of string was matched by the entire RE. Remaining members report what substring was matched by parenthesized subexpressions within the RE; member i reports subexpression i, with subexpressions counted (starting at 1) by the order of their opening parentheses in the RE, left to right. Unused entries in the array (corresponding either to subexpressions that did not participate in the match at all, or to subexpressions that do not exist in the RE (that is, i > preg -> re_nsub)) have both rm_so and rm_eo set to -1. If a subexpression participated in the match several times, the reported substring is the last one it matched. (Note, as an example in particular, that when the RE ‘(b*)+’ matches ‘bbb,’ the parenthesized subexpression matches each of the three 'bs' and then an infinite number of empty strings following 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 if nmatch 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 was specified, the value of pmatch [0] will not be changed by a successful regexec.

The regerror function maps a non-zero errcode from either regcomp or regexec to a human-readable, printable message. If preg is non- NULL, the error code should have arisen from use of the

regex_t pointed to by preg, and if the error code came from regcomp, it should have been the result from the most recent regcomp using that
regex_t. The ( (regerror);
may be able to supply a more detailed message using information from the
regex_t.) The regerror function places the NUL-terminated message into the buffer pointed to by errbuf, limiting the length (including the NUL) to at most errbuf_size bytes. If the whole message will not fit, as much of it as will fit before the terminating NUL is supplied. In any case, the returned value is the size of buffer needed 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" that results is the printable name of the error code, e.g. "REG_NOMATCH," rather than an explanation thereof. If errcode is REG_ATOI, then preg shall be non- NULL and the re_endp member of the structure it points to must point to the printable name of an error code; in this case, the result in errbuf is the decimal digits of the numeric value of the error code (0 if the name is not recognized). REG_ITOA and REG_ATOI are intended primarily as debugging facilities

The regfree function frees any dynamically-allocated storage associated with the compiled RE pointed to by preg. The remaining

regex_t is no longer a valid compiled RE and the effect of supplying it to regexec or regerror is undefined.

None of these functions references global variables except for tables of constants; all are safe for use from multiple threads if the arguments are safe.

Examples

#include <stdio.h>
#include <regex.h>
int main()
{
   int ret,match=0;
   regex_t re;
   char errbuf[256];
   ret=regcomp(&re,"[a-c]",REG_EXTENDED|REG_NOSUB);
   if(ret)
   {
      regerror(ret,&re,errbuf,sizeof(errbuf));
      printf("compilation failed with error %s\n",errbuf);
   }
   else
   {
      match=regexec(&re,"access.txt|log.txt|passwd.txt",0,NULL,0);
      if(!match) printf("match found\n");
      else printf("match not found");
      regfree(&re);
   }
   return 0;
}

Output

match found

Implementation choices

Any unmatched ‘[’ is a REG_EBRACK error.

Equivalence classes cannot begin or end bracket-expression ranges. The endpoint of one 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., an operand of ‘|’ cannot be an empty subexpression. An empty parenthesized subexpression, ‘()’, is legal and matches an empty (sub)string. An empty string is not a legal RE.

A ‘{’ followed by a digit is considered the beginning of bounds for a bounded repetition, which must then follow the syntax for bounds. A ‘{’ not followed by a digit is considered an ordinary character.

‘^’ and ‘$’ beginning and ending subexpressions in obsolete ("basic") REs are anchors, not ordinary characters.

Diagnostics

 Non-zero error codes from regcomp and regexec include the following:

REG_NOMATCH | The regexec function 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 | cannot happen - found a bug
REG_INVARG | invalid argument, e.g. negative-length string
REG_ILLSEQ | illegal byte sequence (bad multibyte character)

Feedback

For additional information or queries on this page send feedback


remainder

Name

remainder, remainderf, remainderl, remquo, remquof, remquol,
- floating-point remainder function

Library

 libm.lib

Synopsis
#include <math.h>
double remainder (double x, double y);
float remainderf (float x, float y);
long double remainder (long double x, long double y);
double remquo (double x, double y, int *quo);
float remquof (float x, float y, int *quo);
long double remquol (long double x, long double y, int *quo);

Return values

remainder function returns the remainder, unless y is zero, when the function fails.

Detailed description

 The functions remainder, remainderf, remquo, and remquof return the remainder r := x - n*y where n is the integer nearest the exact value of -words x Ns / Ns Fa y
moreover if \*(Ba n - x / y \*(Ba = 1/2 then n is even. Consequently the remainder is computed exactly and \*(Ba r \*(Ba <= \*(Ba y \*(Ba/2. But attempting to take the remainder when y is 0 or x is ±oo is an invalid operation that produces a NaN.

The remquo and remquof functions also store the last k bits of n in the location pointed to by quo, provided that n exists. The number of bits k is platform-specific, but is guaranteed to be at least 3. remainderl and remquol are aliases to the functions remainder and remquo respectively.

Examples

#include <math.h>
int main( )
{
   double inp1 = 1.625;
   double inp2 = 1.0;
   double y;
   y = remainder( inp1, inp2 );
   printf( "remainder(%f , %f) = %f\n", inp1,  inp2,  y );
   y = remainderf( inp1, inp2 );
   printf( "remainderf(%f , %f) = %f\n", inp1, inp2, y );
   y = remainderl( inp1, inp2 );
   printf( "remainderl(%f , %f) = %f\n\n", inp1, inp2, y );
   y = remquo( inp1, inp2 );
   printf( "remquo(%f , %f) = %f\n", inp1,  inp2,  y );
   y = remquof( inp1, inp2 );
   printf( "remquof(%f , %f) = %f\n", inp1, inp2, y );
   y = remquol( inp1, inp2 );
   printf( "remquol(%f , %f) = %f\n", inp1, inp2, y );
}

Output

remainder  ( 1.625, 1.0) = -0.375
remainderf ( 1.625, 1.0) = -0.375
remainderl ( 1.625, 1.0) = -0.375
remquo ( 1.625, 1.0) = -0.375
remquof( 1.625, 1.0) = -0.375
remquol( 1.625, 1.0) = -0.375

See also

 fmod, ieee, math

Feedback

For additional information or queries on this page send feedback


remove

Name

remove - delete a name and possibly the file it refers to

Library

 libc.lib

Synopsis
#include <stdio.h>
int remove (const char *path);

Return values

Upon successful completion, reomve return 0. Otherwise, -1 is returned and the global variable errno is set to indicate the error.

Detailed description

 The remove function removes the file or directory specified by path.

If path specifies a directory, remove (path);
is the equivalent of rmdir (path);
Otherwise, it is the equivalent of unlink (path);

Examples

/****************** this program shows deleting a file using remove **************/
#include <stdio.h>
int main()
{
        char * name = "C:\\input.txt";
        FILE *fp = fopen(name, "w+");
        if (fp == NULL)
                {
                printf ("fopen failed\n");
                return -1;
                }
        fprintf(fp,"hello world");
        fclose(fp);

        remove(name);
        fp=fopen(name,"r");
        if (fp == NULL)
                {
                printf ("file has been deleted already\n");
                }
        else
                {
                printf("remove failed\n");
                return -1;
                }

        return 0;
}

Output

file has been deleted already

Errors

 The remove function may fail and set errno for any of the errors specified for the routines lstat, rmdir or unlink.

See also

 rmdir, unlink

Feedback

For additional information or queries on this page send feedback


rename

Name

rename - rename files

Library

 libc.lib

Synopsis
#include <stdio.h>
int rename (const char *from, const char *to);

Return values

 The rename() function returns the value 0 if successful; otherwise the value -1 is returned and the global variable errno is set to indicate the error.

Detailed description

 The rename system call causes the link named from to be renamed as to. If to exists, it is first removed. Both from and to must be of the same type (that is, both directories or both non-directories), and must reside on the same file system.

If the final component of from is a symbolic link, the symbolic link is renamed, not the file or directory to which it points.

If a file with a symbolic link pointing to it is renamed, then a subsequent open call on the symbolic link file would automatically remove the link file, i.e consider a symbolic file link.x pointing to a file abc.x. If the file abc.x is renamed to abcd.x then, a subsequent open call on link.x file would automatically remove link.x file.

Note: 1>rename call doesn’t differenciate between hard and soft links. 2>If the specified file is a dangling link file, then this link file will be automatically removed.

Limitation: rename call fails if from and to are files, and are in use(i.e., if any one of these files is kept open by a process). Parent directory time stamps remain uneffected if rename creates a new entry in the directory, this new entry has only two time stamps, modification and access time stamps, here access time stamp is equal to modification time stamp.

Examples

/****************************************************************************************
* Detailed description: This sample code demonstrates usage of rename system call.
*
* Preconditions: Example.cfg file should be present in the current working directory.
****************************************************************************************/
#include <stdio.h>
int main()
{
  if(rename("Example.txt" , "Example2.txt") < 0 )  {
     printf("Failed to rename Example.txt\n");
     return -1;
  }
  printf("Rename successful \n");
  return 0;
}

Output

Rename successful

Errors

 The rename system call will fail and neither of the argument files will be affected if:
[ENAMETOOLONG]
 | A component or an entire path name exceeded 255 characters.
[ENOENT]
 | A component of the from path does not exist, or a path prefix of to does not exist.
[EACCES]
 | A component of either path prefix denies search permission(Not supported).
[EACCES]
 | The requested link requires writing in a directory with a mode that denies write permission(Not supported).
[EPERM]
 | The directory containing from is marked sticky, and neither the containing directory nor from are owned by the effective user ID. Too many symbolic links were encountered in translating either pathname(Currenlty not supported).
[ENOTDIR]
 | A component of either path prefix is not a directory.
[ENOTDIR]
 | The from argument is a directory, but to is not a directory.
[EISDIR]
 | The to argument is a directory, but from is not a directory.
[EXDEV]
 | The link named by to and the file named by from are on different logical devices (file systems). Note that this error code will not be returned if the implementation permits cross-device links(Not supported).
[ENOSPC]
 | The directory in which the entry for the new name is being placed cannot be extended because there is no space left on the file system containing the directory(Currently not supported).
[EDQUOT]
 | The directory in which the entry for the new name is being placed cannot be extended because the user’s quota of disk blocks on the file system containing the directory has been exhausted(Currently not supported).
[EIO] | An I/O error occurred while making or updating a directory entry(Not supported).
[EROFS]
 | The requested link requires writing in a directory on a read-only file system(Not supported).
[EFAULT]
 | Path points outside the process’s allocated address space(Currently not supported).
[EINVAL]
 | The from argument is a parent directory of to, or an attempt is made to rename ‘.’ or ‘..’.
[ENOTEMPTY]
 | The to argument is a directory and is not empty.

See also

 open, symlink
The rename system call is expected to conform to -p1003.1-96.

Feedback

For additional information or queries on this page send feedback


rint

Name

nearbyint, nearbyintf, nearbyintl, rint, rintf, rintl
- round to nearest integer

Library

 libm.lib

Synopsis
#include <math.h>
double nearbyint (double x);
float nearbyintf (float x);
long double nearbyintl (long double x);
double rint (double x);
float rintf (float x);
long double rintl (long double x);

Return values

x is integral or infinite, x itself is returned.

Detailed description

 The rint and rintf functions return the integral value nearest to x according to the prevailing rounding mode.

The nearbyint and nearbyintf functions perform the same operation. The functions nearbyintl and rintl are aliases to the functions nearbyint and rint respectively.

Examples

#include <math.h>
int main( )
{
   double inp = 1.5;
   double y;
   y = nearbyint( inp );
   printf( "nearbyint(%f ) = %f\n", inp,  y );
   y = nearbyintf( inp );
   printf( "nearbyintf(%f ) = %f\n", inp, y );
   y = nearbyintl( inp );
   printf( "nearbyintl(%f ) = %f\n\n", inp, y );
   y = rint( inp );
   printf( "rint(%f ) = %f\n", inp,  y );
   y = rintf( inp );
   printf( "rintf(%f ) = %f\n", inp, y );
   y = rintl( inp );
   printf( "rintl(%f ) = %f\n\n", inp, y );
}

Output

nearbyint  ( 1.5 ) = 2.000000
nearbyintf ( 1.5 ) = 2.000000
nearbyintl ( 1.5 ) = 2.000000
rint ( 1.5 ) = 2.000000
rintf( 1.5 ) = 2.000000
rintl( 1.5 ) = 2.000000

See also

 abs, ceil, fabs, floor, ieee, lrint, lround, math, round

Feedback

For additional information or queries on this page send feedback


rmdir

Name

rmdir - delete a directory

Library

 libc.lib

Synopsis
#include <unistd.h>
int rmdir (const char *path);

Return values

 The rmdir() function returns the value 0 if successful; otherwise the value -1 is returned and the global variable errno is set to indicate the error.

Detailed description

 The rmdir system call removes a directory file whose name is given by path. The directory must not have any entries other than ‘.’ and ‘..’.

Examples

/**
 *  Detailed description: This test code demonstrates usage of rmdir systemcall, it removes directory
 *  Example from the current working directory.
 *
 *  Preconditions: Expects empty directory "Example" in current working directory.
**/
#include  <unistd.h>
int main()
{
  if(rmdir("Example") < 0 )
  {
     printf("Rmdir failed \n");
     return -1;
  }
  printf("Directory Example removed \n");
  return 0;
}

Output Directory Example removed

Errors

 The named file is removed unless:
[ENOTDIR]
 | A component of the path is not a directory.
[ENAMETOOLONG]
 | A component or an entire path name exceeded 255 characters.
[ENOENT]
 | The named directory does not exist.
[ELOOP]
 | Too many symbolic links were encountered in translating the pathname.(Not supported)
[ENOTEMPTY]
 | The named directory contains files other than ‘.’ and ‘..’ in it.
[EACCES]
 | Search permission is denied for a component of the path prefix.(Not supported).
[EACCES]
 | Write permission is denied on the directory containing the link to be removed.
[EPERM]
 | The directory containing the directory to be removed is marked sticky, and neither the containing directory nor the directory to be removed are owned by the effective user ID.(Not supported)
[EBUSY]
 | The directory to be removed is the mount point for a mounted file system.(Not supported).
[EIO] | An I/O error occurred while deleting the directory entry or deallocating the inode.(Not supported).
[EROFS]
 | The directory entry to be removed resides on a read-only file system.(Not supported)
[EFAULT]
 | The path argument points outside the process’s allocated address space.(Not supported).

Feedback

For additional information or queries on this page send feedback


round

Name

round, roundf, roundl
- round to nearest integer, away from zero

Library

 libm.lib

Synopsis
#include <math.h>
double round (double x);
float roundf (float x);
long double roundl (long double x);

Return values

x is integral or infinite, x itself is returned.

Detailed description

 The round, roundf, and roundl functions return the nearest integral value to x; if x lies halfway between two integral values, then these functions return the integral value with the larger absolute value (i.e., they round away from zero).

Examples

#include <math.h>
int main( )
{
   double inp = 0.5;
   double y;
   y = round( inp );
   printf( "round(%f ) = %f\n", inp,  y );
   y = roundf( inp );
   printf( "roundf(%f ) = %f\n", inp, y );
   y = roundl( inp );
   printf( "roundl(%f ) = %f\n\n", inp, y );
}

Output

round  ( 0.5 ) = 1.000000
roundf ( 0.5 ) = 1.000000
roundl ( 0.5 ) = 1.000000

See also

 ceil, floor, ieee, lrint, lround, math, rint, trunc

Feedback

For additional information or queries on this page send feedback


rsa - RSA public key cryptosystem

Name

rsa — implements RSA public key cryptosystem

Library

libcrypto.lib

Synopsis

#include <openssl/rsa.h>
#include <openssl/engine.h>
RSA * RSA_new(void);
void RSA_free(RSA *rsa);
int RSA_public_encrypt(int flen, unsigned char *from, unsigned char *to, RSA *rsa, int padding);
int RSA_private_decrypt(int flen, unsigned char *from, unsigned char *to, RSA *rsa, int padding);
int RSA_private_encrypt(int flen, unsigned char *from, unsigned char *to, RSA *rsa,int padding);
int RSA_public_decrypt(int flen, unsigned char *from, unsigned char *to, RSA *rsa,int padding);
int RSA_sign(int type, unsigned char *m, unsigned int m_len, unsigned char *sigret, unsigned int *siglen, RSA *rsa);
int RSA_verify(int type, unsigned char *m, unsigned int m_len, unsigned char *sigbuf, unsigned int siglen, RSA *rsa);
int RSA_size(const RSA *rsa);
RSA *RSA_generate_key(int num, unsigned long e, void (*callback)(int,int,void *), void *cb_arg);
int RSA_check_key(RSA *rsa);
int RSA_blinding_on(RSA *rsa, BN_CTX *ctx);
void RSA_blinding_off(RSA *rsa);
void RSA_set_default_method(const RSA_METHOD *meth);
const RSA_METHOD *RSA_get_default_method(void);
int RSA_set_method(RSA *rsa, const RSA_METHOD *meth);
const RSA_METHOD *RSA_get_method(const RSA *rsa);
RSA_METHOD *RSA_PKCS1_SSLeay(void);
RSA_METHOD *RSA_null_method(void);
int RSA_flags(const RSA *rsa);
RSA *RSA_new_method(ENGINE *engine);
int RSA_print(BIO *bp, RSA *x, int offset);
int RSA_print_fp(FILE *fp, RSA *x, int offset);
int RSA_get_ex_new_index(long argl, char *argp, int (*new_func)(), int (*dup_func)(), void (*free_func)());
int RSA_set_ex_data(RSA *r,int idx,char *arg);
char *RSA_get_ex_data(RSA *r, int idx);
int RSA_sign_ASN1_OCTET_STRING(int dummy, unsigned char *m, unsigned int m_len, unsigned char *sigret,
                               unsigned int *siglen, RSA *rsa);
int RSA_verify_ASN1_OCTET_STRING(int dummy, unsigned char *m, unsigned int m_len, unsigned char *sigbuf, unsigned int siglen,
                                 RSA *rsa);

Detailed Description

These functions implement RSA public key encryption and signatures as defined in PKCS #1 v2.0 [RFC 2437].

The RSA structure consists of several BIGNUM components. It can contain public as well as private RSA keys:

 struct
        {
        BIGNUM *n;              // public modulus
        BIGNUM *e;              // public exponent
        BIGNUM *d;              // private exponent
        BIGNUM *p;              // secret prime factor
        BIGNUM *q;              // secret prime factor
        BIGNUM *dmp1;           // d mod (p-1)
        BIGNUM *dmq1;           // d mod (q-1)
        BIGNUM *iqmp;           // q^-1 mod p
        // ...
        };
 RSA

In public keys, the private exponent and the related secret values are NULL.

p, q, dmp1, dmq1 and iqmp may be NULL in private keys, but the RSA operations are much faster when these values are available.

Note that RSA keys may use non-standard RSA_METHOD implementations, either directly or by the use of ENGINE modules. In some cases (eg. an ENGINE providing support for hardware-embedded keys), these BIGNUM values will not be used by the implementation or may be used for alternative data storage. For this reason, applications should generally avoid using RSA structure elements directly and instead use API functions to query or modify keys.

Conforming To

SSL, PKCS #1 v2.0

Patents

RSA was covered by a US patent which expired in September 2000.

See Also

rsa(),
bn(), dsa(),
dh(),
rand(), engine(),
RSA_new(),
RSA_public_encrypt(),
RSA_sign(), RSA_size(),
RSA_generate_key(),
RSA_check_key(),
RSA_blinding_on(),
RSA_set_method(),
RSA_print(),
RSA_get_ex_new_index(),
RSA_private_encrypt(),
RSA_sign_ASN1_OCTET_STRING(),
RSA_padding_add_PKCS1_type_1()

Feedback

For additional information or queries on this page send feedback


RSA_blinding_off - protect the RSA operation from timing attacks

Name

RSA_blinding_on, RSA_blinding_off — protect the RSA operation from timing attacks

Library

libcrypto.lib

Synopsis

#include <openssl/rsa.h>
int RSA_blinding_on(RSA *rsa, BN_CTX *ctx);
void RSA_blinding_off(RSA *rsa);

Detailed Description

RSA is vulnerable to timing attacks. In a setup where attackers can measure the time of RSA decryption or signature operations, blinding must be used to protect the RSA operation from that attack.

RSA_blinding_on() turns blinding on for key rsa and generates a random blinding factor. ctx is NULL or a pre-allocated and initialized BN_CTX. The random number generator must be seeded prior to calling RSA_blinding_on().

RSA_blinding_off() turns blinding off and frees the memory used for the blinding factor.

Return Values

RSA_blinding_on() returns 1 on success, and 0 if an error occurred.

RSA_blinding_off() returns no value.

See Also

rsa(), rand()

History

RSA_blinding_on() and RSA_blinding_off() appeared in SSLeay 0.9.0.

Feedback

For additional information or queries on this page send feedback


RSA_check_key - validate private RSA keys

Name

RSA_check_key — validate private RSA keys

Library

libcrypto.lib

Synopsis

#include <openssl/rsa.h>
int RSA_check_key(RSA *rsa);

Detailed Description

This function validates RSA keys. It checks that p and q are in fact prime, and that n = p*q.

It also checks that d*e = 1 mod (p-1*q-1), and that dmp1, dmq1 and iqmp are set correctly or are NULL.

As such, this function can not be used with any arbitrary RSA key object, even if it is otherwise fit for regular RSA operation. See NOTES for more information.

Return Values

RSA_check_key() returns 1 if rsa is a valid RSA key, and 0 otherwise. -1 is returned if an error occurs while checking the key.

If the key is invalid or an error occurred, the reason code can be obtained using ERR_get_error().

Notes

This function does not work on RSA public keys that have only the modulus and public exponent elements populated. It performs integrity checks on all the RSA key material, so the RSA key structure must contain all the private key data too.

Unlike most other RSA functions, this function does not work transparently with any underlying ENGINE implementation because it uses the key data in the RSA structure directly. An ENGINE implementation can override the way key data is stored and handled, and can even provide support for HSM keys - in which case the RSA structure may contain no key data at all! If the ENGINE in question is only being used for acceleration or analysis purposes, then in all likelihood the RSA key data is complete and untouched, but this can't be assumed in the general case.

Bugs

A method of verifying the RSA key using opaque RSA API functions might need to be considered. Right now RSA_check_key() simply uses the RSA structure elements directly, bypassing the RSA_METHOD table altogether (and completely violating encapsulation and object-orientation in the process). The best fix will probably be to introduce a ``check_key()'' handler to the RSA_METHOD function table so that alternative implementations can also provide their own verifiers.

See Also

rsa(), ERR_get_error()

History

RSA_check_key() appeared in OpenSSL 0.9.4.

Feedback

For additional information or queries on this page send feedback


RSA_generate_key - generate RSA key pair

Name

RSA_generate_key — generate RSA key pair

Library

libcrypto.lib

Synopsis

#include <openssl/rsa.h>
RSA *RSA_generate_key(int num, unsigned long e, void (*callback)(int,int,void *), void *cb_arg);

Detailed Description

RSA_generate_key() generates a key pair and returns it in a newly allocated RSA structure. The pseudo-random number generator must be seeded prior to calling RSA_generate_key().

The modulus size will be num bits, and the public exponent will be e. Key sizes with num < 1024 should be considered insecure. The exponent is an odd number, typically 3, 17 or 65537.

A callback function may be used to provide feedback about the progress of the key generation. If callback is not NULL, it will be called as follows:

    • While a random prime number is generated, it is called as described in BN_generate_prime().

    • When the n-th randomly generated prime is rejected as not suitable for the key, callback(2, n, cb_arg) is called.

    • When a random p has been found with p-1 relatively prime to e, it is called as callback(3, 0, cb_arg).

The process is then repeated for prime q with callback(3, 1, cb_arg).

Return Values

If key generation fails, RSA_generate_key() returns NULL; the error codes can be obtained by ERR_get_error().

Bugs

callback(2, x, cb_arg) is used with two different meanings.

RSA_generate_key() goes into an infinite loop for illegal input values.

See Also

ERR_get_error(),
rand(),
rsa(),
RSA_free()

History

The cb_arg argument was added in SSLeay 0.9.0.

Feedback

For additional information or queries on this page send feedback


RSA_generate_key_ex - generate RSA key pair

Name

RSA_generate_key_ex — generates RSA key pair

Library

libcrypto.lib

Synopsis

#include <openssl/rsa.h>
int RSA_generate_key_ex(RSA *rsa, int bits, BIGNUM *e, BN_GENCB *cb);

Detailed Description

RSA_generate_key_ex() generates a key pair. The pseudo-random number generator must be seeded prior to calling RSA_generate_key_ex().

It accepts RSA structure and the modulus size will be num bits, and the public exponent will be e. Key sizes with bits < 1024 should be considered insecure. The exponent is an odd number, typically 3, 17 or 65537.

A callback function may be used to provide feedback about the progress of the key generation. If callback is not NULL, it will be called as follows:

    • While a random prime number is generated, it is called as described in BN_generate_prime().

    • When the n-th randomly generated prime is rejected as not suitable for the key, callback(2, n, cb_arg) is called.

    • When a random p has been found with p-1 relatively prime to e, it is called as callback(3, 0, cb_arg).

The process is then repeated for prime q with callback(3, 1, cb_arg).

Return Values

If key generation fails, RSA_generate_key_ex() returns -1; the error codes can be obtained by ERR_get_error().

Bugs

callback(2, x, cb_arg) is used with two different meanings.

RSA_generate_key() goes into an infinite loop for illegal input values.

See Also

ERR_get_error(),
rand(),
rsa(),
RSA_free()

History

The cb_arg argument was added in SSLeay 0.9.0.

Feedback

For additional information or queries on this page send feedback


RSA_get_ex_data - add application specific data to RSA structures

Name

RSA_get_ex_new_index, RSA_set_ex_data
RSA_get_ex_data

add application specific data to RSA structures

Library

libcrypto.lib

Synopsis

#include <openssl/rsa.h>
int RSA_get_ex_new_index(long argl, void *argp, CRYPTO_EX_new *new_func, CRYPTO_EX_dup *dup_func,
                         CRYPTO_EX_free *free_func);
int RSA_set_ex_data(RSA *r, int idx, void *arg);
void *RSA_get_ex_data(RSA *r, int idx);
typedef int new_func(void *parent, void *ptr, CRYPTO_EX_DATA *ad, int idx, long argl, void *argp);
typedef void free_func(void *parent, void *ptr, CRYPTO_EX_DATA *ad, int idx, long argl, void *argp);
typedef int dup_func(CRYPTO_EX_DATA *to, CRYPTO_EX_DATA *from, void *from_d, int idx, long argl, void *argp);

Detailed Description

Several OpenSSL structures can have application specific data attached to them. This has several potential uses, it can be used to cache data associated with a structure (for example the hash of some part of the structure) or some additional data (for example a handle to the data in an external library).

Since the application data can be anything at all it is passed and retrieved as a void * type.

The RSA_get_ex_new_index() function is initially called to ``register'' some new application specific data. It takes three optional function pointers which are called when the parent structure (in this case an RSA structure) is initially created, when it is copied and when it is freed up. If any or all of these function pointer arguments are not used they should be set to NULL. The precise manner in which these function pointers are called is described in more detail below. RSA_get_ex_new_index() also takes additional long and pointer parameters which will be passed to the supplied functions but which otherwise have no special meaning. It returns an index which should be stored (typically in a static variable) and passed used in the idx parameter in the remaining functions. Each successful call to RSA_get_ex_new_index() will return an index greater than any previously returned, this is important because the optional functions are called in order of increasing index value.

RSA_set_ex_data() is used to set application specific data, the data is supplied in the arg parameter and its precise meaning is up to the application.

RSA_get_ex_data() is used to retrieve application specific data. The data is returned to the application, this will be the same value as supplied to a previous RSA_set_ex_data() call.

new_func() is called when a structure is initially allocated (for example with RSA_new(). The parent structure members will not have any meaningful values at this point. This function will typically be used to allocate any application specific structure.

free_func() is called when a structure is being freed up. The dynamic parent structure members should not be accessed because they will be freed up when this function is called.

new_func() and free_func() take the same parameters. parent is a pointer to the parent RSA structure. ptr is a the application specific data (this wont be of much use in new_func(). ad is a pointer to the CRYPTO_EX_DATA structure from the parent RSA structure: the functions CRYPTO_get_ex_data() and CRYPTO_set_ex_data() can be called to manipulate it. The idx parameter is the index: this will be the same value returned by RSA_get_ex_new_index() when the functions were initially registered. Finally the argl and argp parameters are the values originally passed to the same corresponding parameters when RSA_get_ex_new_index() was called.

dup_func() is called when a structure is being copied. Pointers to the destination and source CRYPTO_EX_DATA structures are passed in the to and from parameters respectively. The from_d parameter is passed a pointer to the source application data when the function is called, when the function returns the value is copied to the destination: the application can thus modify the data pointed to by from_d and have different values in the source and destination. The idx, argl and argp parameters are the same as those in new_func() and free_func().

Return Values

RSA_get_ex_new_index() returns a new index or -1 on failure (note 0 is a valid index value).

RSA_set_ex_data() returns 1 on success or 0 on failure.

RSA_get_ex_data() returns the application data or 0 on failure. 0 may also be valid application data but currently it can only fail if given an invalid idx parameter.

new_func() and dup_func() should return 0 for failure and 1 for success.

On failure an error code can be obtained from ERR_get_error().

Bugs

dup_func() is currently never called.

The return value of new_func() is ignored.

The new_func() function isn't very useful because no meaningful values are present in the parent RSA structure when it is called.

See Also

rsa(), CRYPTO_set_ex_data()

History

RSA_get_ex_new_index(),
RSA_set_ex_data() and
 RSA_get_ex_data() are
available since SSLeay 0.9.0.

Feedback

For additional information or queries on this page send feedback


RSA_free - allocate and free RSA objects

Name

RSA_new, RSA_free — allocate and free RSA objects

Library

libcrypto.lib

Synopsis

#include <openssl/rsa.h>
RSA * RSA_new(void);
void RSA_free(RSA *rsa);

Detailed Description

RSA_new() allocates and initializes an RSA structure. It is equivalent to calling RSA_new_method(NULL).

RSA_free() frees the RSA structure and its components. The key is erased before the memory is returned to the system.

Return Values

If the allocation fails, RSA_new() returns NULL and sets an error code that can be obtained by ERR_get_error(). Otherwise it returns a pointer to the newly allocated structure.

RSA_free() returns no value.

See Also

ERR_get_error(),

rsa(),
RSA_generate_key(),
RSA_new_method()

History

RSA_new() and RSA_free() are available in all versions of SSLeay and OpenSSL.

Feedback

For additional information or queries on this page send feedback


RSA_padding_check_none - asymmetric encryption padding

Name

RSA_padding_add_PKCS1_type_1, RSA_padding_check_PKCS1_type_1
RSA_padding_add_PKCS1_type_2, RSA_padding_check_PKCS1_type_2
RSA_padding_add_PKCS1_OAEP, RSA_padding_check_PKCS1_OAEP
RSA_padding_add_SSLv23, RSA_padding_check_SSLv23
RSA_padding_add_none, RSA_padding_check_none

asymmetric encryption padding

Library

libcrypto.lib

Synopsis

#include <openssl/rsa.h>
int RSA_padding_add_PKCS1_type_1(unsigned char *to, int tlen, unsigned char *f, int fl);
int RSA_padding_check_PKCS1_type_1(unsigned char *to, int tlen, unsigned char *f, int fl, int rsa_len);
int RSA_padding_add_PKCS1_type_2(unsigned char *to, int tlen, unsigned char *f, int fl);
int RSA_padding_check_PKCS1_type_2(unsigned char *to, int tlen, unsigned char *f, int fl, int rsa_len);

int RSA_padding_add_PKCS1_OAEP(unsigned char *to, int tlen, unsigned char *f, int fl, unsigned char *p, int pl);
int RSA_padding_check_PKCS1_OAEP(unsigned char *to, int tlen, unsigned char *f, int fl, int rsa_len,
                                 unsigned char *p, int pl);
int RSA_padding_add_SSLv23(unsigned char *to, int tlen, unsigned char *f, int fl);
int RSA_padding_check_SSLv23(unsigned char *to, int tlen, unsigned char *f, int fl, int rsa_len);
int RSA_padding_add_none(unsigned char *to, int tlen, unsigned char *f, int fl);
int RSA_padding_check_none(unsigned char *to, int tlen, unsigned char *f, int fl, int rsa_len);

Detailed Description

The RSA_padding_xxx_xxx() functions are called from the RSA encrypt, decrypt, sign and verify functions. Normally they should not be called from application programs.

However, they can also be called directly to implement padding for other asymmetric ciphers. RSA_padding_add_PKCS1_OAEP() and RSA_padding_check_PKCS1_OAEP() may be used in an application combined with RSA_NO_PADDING in order to implement OAEP with an encoding parameter.

RSA_padding_add_xxx() encodes fl bytes from f so as to fit into tlen bytes and stores the result at to. An error occurs if fl does not meet the size requirements of the encoding method.

The following encoding methods are implemented:

PKCS1_type_1
PKCS #1 v2.0 EMSA-PKCS1-v1_5 (PKCS #1 v1.5 block type 1); used for signatures

PKCS1_type_2
PKCS #1 v2.0 EME-PKCS1-v1_5 (PKCS #1 v1.5 block type 2)

PKCS1_OAEP
PKCS #1 v2.0 EME-OAEP

SSLv23
PKCS #1 EME-PKCS1-v1_5 with SSL-specific modification

none
simply copy the data

The random number generator must be seeded prior to calling RSA_padding_add_xxx().

RSA_padding_check_xxx() verifies that the fl bytes at f contain a valid encoding for a rsa_len byte RSA key in the respective encoding method and stores the recovered data of at most tlen bytes (for RSA_NO_PADDING: of size tlen) at to.

For RSA_padding_xxx_OAEP(), p points to the encoding parameter of length pl. p may be NULL if pl is 0.

Return Values

The RSA_padding_add_xxx() functions return 1 on success, 0 on error. The RSA_padding_check_xxx() functions return the length of the recovered data, -1 on error. Error codes can be obtained by calling ERR_get_error().

See Also

RSA_public_encrypt(),
RSA_private_decrypt(),
RSA_sign(), RSA_verify()

History

RSA_padding_add_PKCS1_type_1(), RSA_padding_check_PKCS1_type_1(),
RSA_padding_add_PKCS1_type_2(), RSA_padding_check_PKCS1_type_2(),
RSA_padding_add_SSLv23(), RSA_padding_check_SSLv23(),

RSA_padding_add_none() and
 RSA_padding_check_none()
appeared in
SSLeay 0.9.0.

RSA_padding_add_PKCS1_OAEP() and RSA_padding_check_PKCS1_OAEP() were added in OpenSSL 0.9.2b.

Feedback

For additional information or queries on this page send feedback


DHparams_print_fp - print cryptographic parameters

Name

RSA_print, RSA_print_fp
DSAparams_print, DSAparams_print_fp
DSA_print, DSA_print_fp
DHparams_print, DHparams_print_fp

print cryptographic parameters

Library

libcrypto.lib

Synopsis

#include <openssl/rsa.h>
int RSA_print(BIO *bp, RSA *x, int offset);
int RSA_print_fp(FILE *fp, RSA *x, int offset);
#include <openssl/dsa.h>
int DSAparams_print(BIO *bp, DSA *x);
int DSAparams_print_fp(FILE *fp, DSA *x);
int DSA_print(BIO *bp, DSA *x, int offset);
int DSA_print_fp(FILE *fp, DSA *x, int offset);
#include <openssl/dh.h>
int DHparams_print(BIO *bp, DH *x);
int DHparams_print_fp(FILE *fp, DH *x);

Detailed Description

A human-readable hexadecimal output of the components of the RSA key, DSA parameters or key or DH parameters is printed to bp or fp.

The output lines are indented by offset spaces.

Return Values

These functions return 1 on success, 0 on error.

See Also

dh(),
dsa(), rsa(),
BN_bn2bin()

History

RSA_print(), RSA_print_fp(), DSA_print(), DSA_print_fp(), DH_print(), DH_print_fp() are available in all versions of SSLeay and OpenSSL. DSAparams_print() and DSAparams_print_fp() were added in SSLeay 0.8.

Feedback

For additional information or queries on this page send feedback


RSA_public_decrypt - low level signature operations

Name

RSA_private_encrypt, RSA_public_decrypt — low level signature operations

Library

libcrypto.lib

Synopsis

#include <openssl/rsa.h>
int RSA_private_encrypt(int flen, unsigned char *from, unsigned char *to, RSA *rsa, int padding);
int RSA_public_decrypt(int flen, unsigned char *from, unsigned char *to, RSA *rsa, int padding);

Detailed Description

These functions handle RSA signatures at a low level.

RSA_private_encrypt() signs the flen bytes at from (usually a message digest with an algorithm identifier) using the private key rsa and stores the signature in to. to must point to RSA_size(rsa) bytes of memory.

padding denotes one of the following modes:

RSA_PKCS1_PADDING
PKCS #1 v1.5 padding. This function does not handle the algorithmIdentifier specified in PKCS #1. When generating or verifying PKCS #1 signatures, RSA_sign() and RSA_verify() should be used.

RSA_NO_PADDING
Raw RSA signature. This mode should only be used to implement cryptographically sound padding modes in the application code. Signing user data directly with RSA is insecure.

RSA_public_decrypt() recovers the message digest from the flen bytes long signature at from using the signer's public key rsa. to must point to a memory section large enough to hold the message digest (which is smaller than RSA_size(rsa) - 11). padding is the padding mode that was used to sign the data.

Return Values

RSA_private_encrypt() returns the size of the signature (i.e., RSA_size(rsa)). RSA_public_decrypt() returns the size of the recovered message digest.

On error, -1 is returned; the error codes can be obtained by ERR_get_error().

See Also

ERR_get_error(),
rsa(),
RSA_sign(), RSA_verify()

History

The padding argument was added in SSLeay 0.8. RSA_NO_PADDING is available since SSLeay 0.9.0.

Feedback

For additional information or queries on this page send feedback


RSA_private_decrypt - RSA public key cryptography

Name

RSA_public_encrypt, RSA_private_decrypt RSA — public key cryptography

Library

libcrypto.lib

Synopsis

#include <openssl/rsa.h>
int RSA_public_encrypt(int flen, unsigned char *from, unsigned char *to, RSA *rsa, int padding);
int RSA_private_decrypt(int flen, unsigned char *from, unsigned char *to, RSA *rsa, int padding);

Detailed Description

RSA_public_encrypt() encrypts the flen bytes at from (usually a session key) using the public key rsa and stores the ciphertext in to. to must point to RSA_size(rsa) bytes of memory.

padding denotes one of the following modes:

RSA_PKCS1_PADDING
PKCS #1 v1.5 padding. This currently is the most widely used mode.

RSA_PKCS1_OAEP_PADDING
EME-OAEP as defined in PKCS #1 v2.0 with SHA-1, MGF1 and an empty encoding parameter. This mode is recommended for all new applications.

RSA_SSLV23_PADDING
PKCS #1 v1.5 padding with an SSL-specific modification that denotes that the server is SSL3 capable.

RSA_NO_PADDING
Raw RSA encryption. This mode should only be used to implement cryptographically sound padding modes in the application code. Encrypting user data directly with RSA is insecure.

flen must be less than RSA_size(rsa) - 11 for the PKCS #1 v1.5 based padding modes, less than RSA_size(rsa) - 41 for RSA_PKCS1_OAEP_PADDING and exactly RSA_size(rsa) for RSA_NO_PADDING. The random number generator must be seeded prior to calling RSA_public_encrypt().

RSA_private_decrypt() decrypts the flen bytes at from using the private key rsa and stores the plaintext in to. to must point to a memory section large enough to hold the decrypted data (which is smaller than RSA_size(rsa)). padding is the padding mode that was used to encrypt the data.

Return Values

RSA_public_encrypt() returns the size of the encrypted data (i.e., RSA_size(rsa)). RSA_private_decrypt() returns the size of the recovered plaintext.

On error, -1 is returned; the error codes can be obtained by ERR_get_error().

Conforming To

SSL, PKCS #1 v2.0

See Also

ERR_get_error(),
rand(),
rsa(),
RSA_size()

History

The padding argument was added in SSLeay 0.8. RSA_NO_PADDING is available since SSLeay 0.9.0, OAEP was added in OpenSSL 0.9.2b.

Feedback

For additional information or queries on this page send feedback


RSA_new_method - select RSA method

Name

RSA_set_default_method, RSA_get_default_method
RSA_set_method, RSA_get_method
RSA_PKCS1_SSLeay, RSA_null_method
RSA_flags, RSA_new_method

select RSA method

Library

libcrypto.lib

Synopsis

#include <openssl/rsa.h>
void RSA_set_default_method(const RSA_METHOD *meth);
RSA_METHOD *RSA_get_default_method(void);
int RSA_set_method(RSA *rsa, const RSA_METHOD *meth);
RSA_METHOD *RSA_get_method(const RSA *rsa);
RSA_METHOD *RSA_PKCS1_SSLeay(void);
RSA_METHOD *RSA_null_method(void);
int RSA_flags(const RSA *rsa);
RSA *RSA_new_method(RSA_METHOD *method);

Detailed Description

An RSA_METHOD specifies the functions that OpenSSL uses for RSA operations. By modifying the method, alternative implementations such as hardware accelerators may be used. IMPORTANT: See the NOTES section for important information about how these RSA API functions are affected by the use of ENGINE API calls.

Initially, the default RSA_METHOD is the OpenSSL internal implementation, as returned by RSA_PKCS1_SSLeay().

RSA_set_default_method() makes meth the default method for all RSA structures created later. NB: This is true only whilst no ENGINE has been set as a default for RSA, so this function is no longer recommended.

RSA_get_default_method() returns a pointer to the current default RSA_METHOD. However, the meaningfulness of this result is dependant on whether the ENGINE API is being used, so this function is no longer recommended.

RSA_set_method() selects meth to perform all operations using the key rsa. This will replace the RSA_METHOD used by the RSA key and if the previous method was supplied by an ENGINE, the handle to that ENGINE will be released during the change. It is possible to have RSA keys that only work with certain RSA_METHOD implementations (eg. from an ENGINE module that supports embedded hardware-protected keys), and in such cases attempting to change the RSA_METHOD for the key can have unexpected results.

RSA_get_method() returns a pointer to the RSA_METHOD being used by rsa. This method may or may not be supplied by an ENGINE implementation, but if it is, the return value can only be guaranteed to be valid as long as the RSA key itself is valid and does not have its implementation changed by RSA_set_method().

RSA_flags() returns the flags that are set for rsa's current RSA_METHOD. See the BUGS section.

RSA_new_method() allocates and initializes an RSA structure so that engine will be used for the RSA operations. If engine is NULL, the default ENGINE for RSA operations is used, and if no default ENGINE is set, the RSA_METHOD controlled by RSA_set_default_method() is used.

RSA_flags() returns the flags that are set for rsa's current method.

RSA_new_method() allocates and initializes an RSA structure so that method will be used for the RSA operations. If method is NULL, the default method is used.

The RSA_METHOD Structure

typedef struct rsa_meth_st
 {
     /* name of the implementation */
        const char *name;
     /* encrypt */
        int (*rsa_pub_enc)(int flen, unsigned char *from,
          unsigned char *to, RSA *rsa, int padding);
     /* verify arbitrary data */
        int (*rsa_pub_dec)(int flen, unsigned char *from,
          unsigned char *to, RSA *rsa, int padding);
     /* sign arbitrary data */
        int (*rsa_priv_enc)(int flen, unsigned char *from,
          unsigned char *to, RSA *rsa, int padding);
     /* decrypt */
        int (*rsa_priv_dec)(int flen, unsigned char *from,
          unsigned char *to, RSA *rsa, int padding);
     /* compute r0 = r0 ^ I mod rsa->n (May be NULL for some
                                        implementations) */
        int (*rsa_mod_exp)(BIGNUM *r0, BIGNUM *I, RSA *rsa);
     /* compute r = a ^ p mod m (May be NULL for some implementations) */
        int (*bn_mod_exp)(BIGNUM *r, BIGNUM *a, const BIGNUM *p,
          const BIGNUM *m, BN_CTX *ctx, BN_MONT_CTX *m_ctx);
     /* called at RSA_new */
        int (*init)(RSA *rsa);
     /* called at RSA_free */
        int (*finish)(RSA *rsa);
     /* RSA_FLAG_EXT_PKEY        - rsa_mod_exp is called for private key
      *                            operations, even if p,q,dmp1,dmq1,iqmp
      *                            are NULL
      * RSA_FLAG_SIGN_VER        - enable rsa_sign and rsa_verify
      * RSA_METHOD_FLAG_NO_CHECK - don't check pub/private match
      */
        int flags;
        char *app_data; /* ?? */
     /* sign. For backward compatibility, this is used only
      * if (flags & RSA_FLAG_SIGN_VER)
      */
        int (*rsa_sign)(int type, unsigned char *m, unsigned int m_len,
           unsigned char *sigret, unsigned int *siglen, RSA *rsa);
     /* verify. For backward compatibility, this is used only
      * if (flags & RSA_FLAG_SIGN_VER)
      */
        int (*rsa_verify)(int type, unsigned char *m, unsigned int m_len,
           unsigned char *sigbuf, unsigned int siglen, RSA *rsa);
} RSA_METHOD;

Return Values

RSA_PKCS1_SSLeay(), RSA_PKCS1_null_method(), RSA_get_default_method() and RSA_get_method() return pointers to the respective RSA_METHODs.

RSA_set_default_method() returns no value.

RSA_set_method() returns a pointer to the old RSA_METHOD implementation that was replaced. However, this return value should probably be ignored because if it was supplied by an ENGINE, the pointer could be invalidated at any time if the ENGINE is unloaded (in fact it could be unloaded as a result of the RSA_set_method() function releasing its handle to the ENGINE). For this reason, the return type may be replaced with a void declaration in a future release.

RSA_new_method() returns NULL and sets an error code that can be obtained by ERR_get_error() if the allocation fails. Otherwise it returns a pointer to the newly allocated structure.

Notes

As of version 0.9.7, RSA_METHOD implementations are grouped together with other algorithmic APIs (eg. DSA_METHOD, EVP_CIPHER, etc) into ENGINE modules. If a default ENGINE is specified for RSA functionality using an ENGINE API function, that will override any RSA defaults set using the RSA API (i.e. RSA_set_default_method()). For this reason, the ENGINE API is the recommended way to control default implementations for use in RSA and other cryptographic algorithms.

Bugs

The behaviour of RSA_flags() is a mis-feature that is left as-is for now to avoid creating compatibility problems. RSA functionality, such as the encryption functions, are controlled by the flags value in the RSA key itself, not by the flags value in the RSA_METHOD attached to the RSA key (which is what this function returns). If the flags element of an RSA key is changed, the changes will be honored by RSA functionality but will not be reflected in the return value of the RSA_flags() function - in effect RSA_flags() behaves more like an RSA_default_flags() function (which does not currently exist).

See Also

rsa(), RSA_new()

History

RSA_new_method() and RSA_set_default_method() appeared in SSLeay 0.8. RSA_get_default_method(), RSA_set_method() and RSA_get_method() as well as the rsa_sign and rsa_verify components of RSA_METHOD were added in OpenSSL 0.9.4.

RSA_set_default_openssl_method() and RSA_get_default_openssl_method() replaced RSA_set_default_method() and RSA_get_default_method() respectively, and RSA_set_method() and RSA_new_method() were altered to use ENGINEs rather than RSA_METHODs during development of the engine version of OpenSSL 0.9.6. For 0.9.7, the handling of defaults in the ENGINE API was restructured so that this change was reversed, and behaviour of the other functions resembled more closely the previous behaviour. The behaviour of defaults in the ENGINE API now transparently overrides the behaviour of defaults in the RSA API without requiring changing these function prototypes.

Feedback

For additional information or queries on this page send feedback


RSA_verify - RSA signatures

Name

RSA_sign, RSA_verify — RSA signatures

Library

libcrypto.lib

Synopsis

#include <openssl/rsa.h>
int RSA_sign(int type, const unsigned char *m, unsigned int m_len, unsigned char *sigret, unsigned int *siglen, RSA *rsa);
int RSA_verify(int type, const unsigned char *m, unsigned int m_len, unsigned char *sigbuf, unsigned int siglen, RSA *rsa);

Detailed Description

RSA_sign() signs the message digest m of size m_len using the private key rsa as specified in PKCS #1 v2.0. It stores the signature in sigret and the signature size in siglen. sigret must point to RSA_size(rsa) bytes of memory.

type denotes the message digest algorithm that was used to generate m. It usually is one of NID_sha1, NID_md5; see objects() for details. If type is NID_md5_sha1, an SSL signature (MD5 and SHA1 message digests with PKCS #1 padding and no algorithm identifier) is created.

RSA_verify() verifies that the signature sigbuf of size siglen matches a given message digest m of size m_len. type denotes the message digest algorithm that was used to generate the signature. rsa is the signer's public key.

Return Values

RSA_sign() returns 1 on success, 0 otherwise. RSA_verify() returns 1 on successful verification, 0 otherwise.

The error codes can be obtained by ERR_get_error().

Bugs

Certain signatures with an improper algorithm identifier are accepted for compatibility with SSLeay 0.4.5

Conforming To

SSL, PKCS #1 v2.0

See Also

ERR_get_error(), objects(),
rsa(), RSA_private_encrypt(),
RSA_public_decrypt()

History

RSA_sign() and RSA_verify() are available in all versions of SSLeay and OpenSSL.

Feedback

For additional information or queries on this page send feedback


RSA_verify_ASN1_OCTET_STRING - RSA signatures

Name

RSA_sign_ASN1_OCTET_STRING, RSA_verify_ASN1_OCTET_STRING — RSA signatures

Library

libcrypto.lib

Synopsis

#include <openssl/rsa.h>
int RSA_sign_ASN1_OCTET_STRING(int dummy, unsigned char *m, unsigned int m_len, unsigned char *sigret, unsigned int *siglen,
                               RSA *rsa);
int RSA_verify_ASN1_OCTET_STRING(int dummy, unsigned char *m, unsigned int m_len, unsigned char *sigbuf, unsigned int siglen,
                                 RSA *rsa);

Detailed Description

RSA_sign_ASN1_OCTET_STRING() signs the octet string m of size m_len using the private key rsa represented in DER using PKCS #1 padding. It stores the signature in sigret and the signature size in siglen. sigret must point to RSA_size(rsa) bytes of memory.

dummy is ignored.

The random number generator must be seeded prior to calling RSA_sign_ASN1_OCTET_STRING().

RSA_verify_ASN1_OCTET_STRING() verifies that the signature sigbuf of size siglen is the DER representation of a given octet string m of size m_len. dummy is ignored. rsa is the signer's public key.

Return Values

RSA_sign_ASN1_OCTET_STRING() returns 1 on success, 0 otherwise. RSA_verify_ASN1_OCTET_STRING() returns 1 on successful verification, 0 otherwise.

The error codes can be obtained by ERR_get_error().

Bugs

These functions serve no recognizable purpose.

See Also

ERR_get_error(), objects(),
rand(), rsa(),
RSA_sign()

History

RSA_sign_ASN1_OCTET_STRING() and RSA_verify_ASN1_OCTET_STRING() were added in SSLeay 0.8.

Feedback

For additional information or queries on this page send feedback


RSA_size - get RSA modulus size

Name

RSA_size — gets RSA modulus size

Library

libcrypto.lib

Synopsis

#include <openssl/rsa.h>
int RSA_size(const RSA *rsa);

Detailed Description

This function returns the RSA modulus size in bytes. It can be used to determine how much memory must be allocated for an RSA encrypted value.

rsa->n must not be NULL.

Return Values

The size in bytes.

See Also

rsa()

History

RSA_size() is available in all versions of SSLeay and OpenSSL.

Feedback

For additional information or queries on this page send feedback


scalbn

Name

scalbln, scalblnf, scalblnl, scalbn, scalbnf, scalbnl
- compute exponent using FLT_RADIX

Library

 libm.lib

Synopsis
#include <math.h>
double scalbln (double x, long n);
float scalblnf (float x, long n);
long double scalblnl (long double x, long n);
double scalbn (double x, int n);
float scalbnf (float x, int n);
long double scalbnl (long double x, int n);

Return values

x (*, FLT_RADIX**n);

±HUGE_VAL, (±HUGE_VALF,, and, ±HUGE_VALL);
(according to the sign of x ) as appropriate for the return type of the function.

x is NaN , a shall be returned.

x is ±0 or ±Inf, x shall be returned.

n is 0, x shall be returned.

Detailed description

 These routines return x *(2** n) computed by exponent manipulation.

Examples

#include <math.h>
int main( )
{
   /*scalbn(), scalbnf() and scalbnl()*/
   double x1 = 0.8, x2 = 4.0 ;
   y = scalbn( x1, x2 );
   printf( "scalbn( %f, %f) = %f\n", x1, x2, y );
   y = scalbnf( x1, x2 );
   printf( "scalbnf( %f, %f) = %f\n", x1, x2, y );
   y = scalbnl( x1, x2 );
   printf( "scalbnl( %f, %f) = %f\n", x1, x2, y );
  /*scalbln(), scalblnf() and scalblnl()*/
   x1 = 0.8, x2 = 4.0 ;
   y = scalbln( x1, x2 );
   printf( "scalbln( %f, %f) = %f\n", x1, x2, y );
   y = scalblnf( x1, x2 );
   printf( "scalblnf( %f, %f) = %f\n", x1, x2, y );
   y = scalblnl( x1, x2 );
   printf( "scalblnl( %f, %f) = %f\n", x1, x2, y );
}

Output

scalbn ( 0.8, 4.0 ) = 12.800000
scalbnf( 0.8, 4.0 ) = 12.800000
scalbnl( 0.8, 4.0 ) = 12.800000
scalbln ( 0.8, 4.0 ) = 12.800000
scalblnf( 0.8, 4.0 ) = 12.800000
scalblnl( 0.8, 4.0 ) = 12.800000

See also

 ieee, math
These routines conform to -isoC-99, and they implement the Scalb function recommended by -ieee754.

Here long double version apis are just an alias to the corresponding double version apis, Long double version Apis behaves similiar to that of double version Apis.

The scalbn and scalbnf functions appeared in BSD 4.3 and 2.0 , respectively. The scalbln and scalblnf functions first appeared in 5.3 , and scalblnl and scalbln in 5.5 .

Feedback

For additional information or queries on this page send feedback


scandir

Name

scandir, alphasort
- scan a directory

Library

 libc.lib

Synopsis
#include <sys/types.h>
#include <dirent.h>
int scandir (const char *dirname, struct dirent ***namelist, int \*(lp*select\*(rp\*(lpstruct dirent *\*(rp, int \*(lp*compar\*(rp\*(lpconst void *, const void *\*(rp);
int alphasort (const void *d1, const void *d2);

Detailed description

 The scandir function reads the directory dirname and builds an array of pointers to directory entries using malloc It returns the number of entries in the array. A pointer to the array of directory entries is stored in the location referenced by namelist.

The select argument is a pointer to a user supplied subroutine which is called by scandir to select which entries are to be included in the array. The select routine is passed a pointer to a directory entry and should return a non-zero value if the directory entry is to be included in the array. If select is null, then all the directory entries will be included.

The compar argument is a pointer to a user supplied subroutine which is passed to qsort to sort the completed array. If this pointer is null, the array is not sorted.

The alphasort function is a routine which can be used for the compar argument to sort the array alphabetically.

The memory allocated for the array can be deallocated with free, by freeing each pointer in the array and then the array itself.

Examples

//Illustrates how to use scandir API.
#include <dirent.h>
Void  scandirTest()
    {
       struct dirent **namelist;
       int n;
       // Function call to get the dir entries into the namelist.
       n = scandir("\home\manjus\GETTEXT", &namelist, 0, 0);

       if(n > 0) // if scandir is successful it retuns the number of entries greater than 0
       {
             // print all the entries in the directory.
        while(n--)
        {
                printf("dir name @ pos %d is %s \n",n,namelist[n]->d_name);
        }
       }
     }

Diagnostics

 Returns -1 if the directory cannot be opened for reading or if malloc cannot allocate enough memory to hold all the data structures.

See also

 directory, malloc, qsort, dir
The scandir and alphasort functions appeared in BSD 4.2.

Feedback

For additional information or queries on this page send feedback


scanf

Name

scanf, fscanf, sscanf, vscanf, vsscanf, vfscanf
- input format conversion

Library

 libc.lib

Synopsis
#include <stdio.h>
int scanf (const char * restrict format, ...);
int fscanf (FILE * restrict stream, const char * restrict format, ...);
int sscanf (const char * restrict str, const char * restrict format, ...);
#include <stdarg.h>
int vscanf (const char * restrict format, va_list ap);
int vsscanf (const char * restrict str, const char * restrict format, va_list ap);
int vfscanf (FILE * restrict stream, const char * restrict format, va_list ap);
Sh RETURN VALUES These functions return the number of input items assigned, which can be fewer than provided 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 due to 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 as an 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.

Detailed description

 The scanf family of functions scans input according to a format as described below. This format may contain conversion specifiers; the results from such conversions, if any, are stored through the pointer arguments. The scanf function reads input from the standard input stream stdin, fscanf reads input from the stream pointer stream, and sscanf reads its input from the character string pointed to by str. The vfscanf function is analogous to
vfprintf and reads input from the stream pointer stream using a variable argument list of pointers (see
stdarg). The vscanf function scans a variable argument list from the standard input and the vsscanf function scans it from a string; these are analogous to the vprintf and vsprintf functions respectively. Each successive pointer argument must correspond properly with each successive conversion specifier (but see the * conversion below). All conversions are introduced by the % (percent sign) character. The format 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 input character does not match such a format character. Scanning also stops when an input conversion cannot be made (see below).

Conversions

 Following the % character introducing a conversion there may be a number of flag characters, as follows:
* | Suppresses assignment. The conversion that follows occurs as usual, but no 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 pointer is a pointer to a char (rather than int).
h | Indicates that the conversion will be one of dioux or n and the next pointer 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 next pointer is a pointer to a long int (rather than int), that the conversion will 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, s or [ and the next 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 next pointer 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 next pointer is a pointer to long double
j | Indicates that the conversion will be one of dioux or n and the next pointer is a pointer to a intmax_t (rather than int).
t | Indicates that the conversion will be one of dioux or n and the next pointer is a pointer to a ptrdiff_t (rather than int).
z | Indicates that the conversion will be one of dioux or n and the next pointer is a pointer to a size_t (rather than int).
q | (deprecated.) Indicates that the conversion will be one of dioux or n and the 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, expressed as a decimal integer, between the % and the conversion. If no width is given, a default of "infinity" is used (with one exception, below); otherwise at most this many bytes are scanned in processing the conversion. In the case of the lc, ls and l[ conversions, the field width specifies the maximum number of multibyte characters that will be scanned. Before conversion begins, most conversions skip white space; this white space is not counted against the field width.

The following conversions are available:
% Matches a literal ‘%.’ That is, "%%" in the format string matches a single input ‘%’ character. No conversion is done, and assignment does not occur.
d | Matches an optionally signed decimal integer; the next pointer must be a pointer to int.
i | Matches an optionally signed integer; the next pointer must be a pointer to int. The integer is read in base 16 if it begins with ‘0x’ or ‘0X,’ in base 8 if it begins with ‘0,’ and in base 10 otherwise. Only characters that correspond to the base are used.
o | Matches an octal integer; the next pointer must be a pointer to unsigned int .
u | Matches an optionally signed decimal integer; the next pointer must be a pointer to unsigned int .
x, X | Matches an optionally signed hexadecimal integer; the next pointer must be a pointer to unsigned int .
a, A, e, E, f, F, g, G
Matches a floating-point number in the style of strtod. The next 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 must be a pointer to char, and the array must be large enough to accept all the sequence and the terminating NULL character. The input string stops at white space or at the maximum field width, 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 after conversion by mbrtowc.

S | The same as ls.
c Matches a sequence of width count characters (default 1); the next pointer must be a pointer to char, and there must be enough room for all the characters (no terminating NUL is added). The usual skip of leading white space is suppressed. To skip white space first, use an explicit space in the format.

If an l qualifier is present, the next pointer must be a pointer to wchar_t, into which the input will be placed after conversion by mbrtowc.

C | The same as lc.
[ Matches a nonempty sequence of characters from the specified set of accepted characters; the next pointer must be a pointer to char, and there must be enough room for all the characters in the string, plus a terminating 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 [ character and a close bracket ] character. The set excludes those 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 after the open bracket or the circumflex; any other position will end the set. The hyphen character - is also special; when placed between two other characters, it adds all intervening characters to the set. To include a hyphen, make it the last character before the final close bracket. For instance, ‘[^]0-9-]’ means the set "everything except close bracket, zero through nine, and hyphen". The string ends with the appearance of a character not in the (or, with a circumflex, in) set or when the 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 after conversion by mbrtowc.

p | Matches a pointer value (as printed by ‘%p’ in printf); the next pointer must be a pointer to void.
n | Nothing is expected; instead, the number of characters consumed thus far from the input is stored through the next pointer, which must be a pointer to 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 (category LC_NUMERIC).

For backwards compatibility, a "conversion" of ‘%\0’ causes an immediate return of EOF.

Examples

/****************** this program shows scanning from file using fscanf **************/
#include <stdio.h>
int main(void)
{
        char x;
        int ret;
        char* filename="c:\ScanfTest1.txt";
        FILE *fp=fopen(filename,"w");
        fprintf(fp,"%s","abcdesdafg");
        fclose(fp);
        fp=fopen(filename,"r");
        ret=fscanf(fp,"%c",&x);
        fclose(fp);
        printf("fscanf returned:%c\n",x);
        unlink(filename);
        getchar();
        if(ret!= 1)
                return -1;
        else
                return 0;
}

Output

fscanf returned:a

Security considerations

 The scanf family of function can be misused by a malicious user to arbitrarily change the functionality of a program under execution using the buffer overflow attack. The buffer overflow attack is possible in the scanf family of functions since the function assumes that an infinitely long string is passed to it. Thus users must ensure that they do not overflow the actual space.

Limitations

 All these functions don’t support the long double length.

See also

 getc, mbrtowc, printf, strtod, strtol, strtoul, wscanf

Feedback

For additional information or queries on this page send feedback


sched_get_priority_max

Name

sched_get_priority_max, sched_get_priority_min
- get static priority range

Library

 libc.lib

Synopsis
#include <sched.h>
int sched_get_priority_max (int policy);
int sched_get_priority_min (int policy);

Return values

 The call would always be succesfull, and would always return a absolute maximum or minimum value.

Detailed description

 The sched_get_priority_max and sched_get_priority_min system calls return the appropriate maximum or minimum priority, respectively.

It should be noted that as the symbian platform does not support monitoring functions, current implementation returns absolute maximum or minimum value independent of the requested policy.

Errors

 No error value is set.

Feedback

For additional information or queries on this page send feedback


sched_yield

Name

sched_yield - yield the processor

Library

 libc.lib

Synopsis
#include <sched.h>
int sched_yield (void);

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.

Detailed description

 The sched_yield system call forces the running process to relinquish the processor until it again becomes the head of its process list. It takes no arguments.

Examples

#include <stdio.h>
#include <sched.h>
int main()
{
 int i = sched_yield(void);
 printf("Expected: 0, sched_yield returned: %d"), i);
}

Output

Expected: 0, sched_yield returned: 0

Errors
[EINTR]
A signal was delivered to the process and its action was to invoke a signal-catching function.

Feedback

For additional information or queries on this page send feedback


select

Name

select - synchronous I/O multiplexing

Library

 libc.lib

Synopsis
#include <sys/select.h>
int select (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);

Return values

 The select system call returns the number of ready descriptors that are contained in the descriptor sets, or -1 if an error occurred. If the time limit expires, select returns 0. If select returns with an error, the descriptor sets will be unmodified.

Detailed description

 The select system call 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, are ready for writing, or have an exceptional condition pending, respectively. The only exceptional condition detectable is out-of-band data received on a socket. The first nfds descriptors are checked in each set; i.e., the descriptors from 0 through nfds -1 in the descriptor sets are examined. On return, select replaces the given descriptor sets with subsets consisting of those descriptors that are ready for the requested operation. The select system call 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 macros are provided for manipulating such descriptor sets: FD_ZERO (&fdset);
initializes a descriptor set fdset to the null set. FD_SET (fd, &fdset);
includes a particular descriptor fd in fdset. FD_CLR (fd, &fdset);
removes fd from fdset. FD_ISSET (fd, &fdset);
is non-zero if fd is a member of fdset, zero otherwise. The behavior of these macros is undefined if a descriptor value is less than zero or greater than or equal to FD_SETSIZE, which is normally at least equal to the maximum number of descriptors supported by the system.

If timeout is not a null pointer, it specifies the maximum interval to wait for the selection to complete. System activity can lengthen the interval by an indeterminate amount.

To effect a poll, the timeout argument should not be a null pointer, but it should point to a zero-valued timeval structure.

Any of readfds, writefds, and exceptfds may be given as null pointers if no descriptors are of interest.

Examples

#include <sys/select.h>
#include <unistd.h>
/*
* A simple example of testing a single FD for readability
* This example returns 1 when the fd is ready for reading.
*/
#include <sys/select.h>
#include <unistd.h>
/*
* A simple example of testing a single FD for readability
* This example returns 1 when the fd is ready for reading.
*/
int isready(int fd)
{
    int rc;
    fd_set fds;
    struct timeval tv;

    /*
     * FD_ZERO() clears out the fd_set called fds, so that
     * it doesn’t contain any file descriptors.
     */
    FD_ZERO(&fds);
    /*
     * FD_SET() adds the file descriptor "fd" to the fd_set,
     * so that select() will return if fd is readable
     */
    FD_SET(fd,&fds);
    tv.tv_sec = tv.tv_usec = 0;
    /*
     * The first argument to select is the highest file
     * descriptor value plus 1.
     */

     /* The second argument to select() is the address of
      * the fd_set that contains fd’s we’re waiting
      * to be readable.
      */

     /* The third parameter is an fd_set that you want to
      * know if you can write on -- this example doesn’t
      * use it, so it passes 0, or NULL.
      */
     /* The fourth parameter is sockets you’re waiting for
      * out-of-band data for.
      */

     /* The last parameter to select() is a time-out of how
      * long select() should block.
      */
     rc = select(fd+1, &fds, NULL, NULL, &tv);
     /* select() returns the number of fd’s that are ready
      * Once select() returns, the original fd_set has been
      * modified so it now reflects the state of why select()
      * woke up. i.e. If file descriptor 4 was originally in
      * the fd_set, and then it became readable, the fd_set
      * contains file descriptor 4 in it.
      */
     if (rc < 0)
       return -1;
     return FD_ISSET(fd,&fds) ? 1 : 0;
}

Errors

 An error return from select indicates:
[EBADF]
 | One of the descriptor sets specified an invalid descriptor.
[EFAULT]
 | One of the arguments readfds, writefds, exceptfds, or timeout points to an invalid address.
[EINVAL]
 | The specified time limit is invalid. One of its components is negative or too large.
[EINVAL]
 | The nfds argument was invalid.

See also

 accept, connect, getdtablesize, gettimeofday, read, recv, send, write,

Notes

 The default size of FD_SETSIZE is currently 1024. In order to accommodate programs which might potentially use a larger number of open files with select, it is possible to increase this size by having the program define FD_SETSIZE before the inclusion of any header which includes
#include <sys/types.h>

If nfds is greater than the number of open files, select is not guaranteed to examine the unused file descriptors. For historical reasons, select will always examine the first 256 descriptors.

The select system call appeared in BSD 4.2.

Bugs

 -susv2 allows systems to modify the original timeout in place. Thus, it is unwise to assume that the timeout value will be unmodified by the select system call.

Limitations

 select is not interrupted by the signals, as signals are not supported by Symbian. If timeout is set to null, select does not block forever, but waits for a maximum of 10 seconds and returns. select operation cannot be called for the second time on the same socket descriptor before the first select operation on the same socket descriptor completes. (i.e) Only one select operation can be outstanding on a Socket. This is because of the limitation of the underlying Ioctl operation. Only one Ioctl operation may be outstanding for each socket.

Feedback

For additional information or queries on this page send feedback


sem_destroy

Name

sem_destroy
- destroy an unnamed semaphore

Library

 libc.lib

Synopsis
#include <semaphore.h>
int sem_destroy (sem_t *sem);

Return values

 Upon successful completion, a value of zero shall be returned. Other-wise, a value of -1 shall be returned and errno set to indicate the error.

Detailed description

 The sem_destroy function destroys the unnamed semaphore pointed to by sem. After a successful call to sem_destroy, sem is unusable until re-initialized by another call to sem_init.

Examples

sem_t psem;
if (sem_init(&psem, 0, 1) < 0) {
        perror("sem_init");
        return -1;
}
if (sem_destroy(&psem) == 0)
        return -1;
}

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 sem points to.

See also

 sem_init,

Feedback

For additional information or queries on this page send feedback


sem_getvalue

Name

sem_getvalue
- get the value of a semaphore

Library

 libc.lib

Synopsis
#include <semaphore.h>
int sem_getvalue (sem_t * sem, int * sval);

Return values

 Upon successful completion, function return a value of zero. Otherwise, it shall return a value of -1 and set errno to indicate the error.

Detailed description

 The sem_getvalue function sets the variable pointed to by sval to the current value of the semaphore pointed to by sem, as of the time that the call to sem_getvalue is actually run.

Examples

sem_t psem;
int val;
if (sem_init(&psem, 0, 1) < 0) {
        perror("sem_init");
        return -1;
   }
if( sem_getvalue(psem, &val) == -1 ) {
  perror("sem_getvalue failed");
  return -1;
 }

Errors

 The sem_getvalue function will fail if:
[EINVAL]
The sem argument points to an invalid semaphore.

See also

 sem_post, sem_trywait, sem_wait,

Feedback

For additional information or queries on this page send feedback


sem_init

Name

sem_init
- initialize an unnamed semaphore

Library

 libc.lib

Synopsis
#include <semaphore.h>
int sem_init (sem_t *sem, int pshared, unsigned int value);

Return values

 Upon successful completion, the sem_init function shall initialize the semaphore in sem. Otherwise, it shall return -1 and set errno to indicate the error.

Detailed description

 The sem_init function initializes the unnamed semaphore pointed to by sem to have the value value. A non-zero value for pshared specifies a shared semaphore that can 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 subsequent calls to sem_wait, sem_trywait, sem_post, and sem_destroy. The sem argument is no longer valid after a successful call to sem_destroy.

Examples

sem_t psem;
if (sem_init(&psem, 0, 1) < 0) {
        perror("sem_init");
        return -1;
   }

Limitation

 Semaphore can be used only within the process, semaphore across the processes is not supported

Errors

 The sem_init function will fail if:
[ENOSYS]
 | the value of the pshared is not 0.
[EINVAL]
 | The value argument exceeds SEM_VALUE_MAX.
[ENOSPC]
 | Memory allocation error.

See also

 sem_destroy, sem_getvalue, sem_post, sem_trywait, sem_wait

Feedback

For additional information or queries on this page send feedback


sem_post

Name

sem_post
- increment (unlock) a semaphore

Library

 libc.lib

Synopsis
#include <semaphore.h>
int sem_post (sem_t *sem);

Return values

 If successful, function shall return zero; otherwise, the function shall return -1 and set errno to indicate the error.

Detailed 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, then the highest priority thread that has been blocked the longest on the semaphore will be allowed to return from sem_wait.

Examples

sem_t psem;
if (sem_init(&psem, 0, 1) < 0) {
        perror("sem_init");
        return -1;
   }
if( sem_post(psem) == -1 ) {
  perror( "sem_post failed");
  return -1;
 }

Errors

 The sem_post function will fail if:
[EINVAL]
The sem argument points to an invalid or uninitialized semaphore.

See also

 sem_getvalue, sem_trywait, sem_wait

Feedback

For additional information or queries on this page send feedback


sem_timedwait

Name

sem_timedwait
- decrement (lock) a semaphore

Library

 libc.lib

Synopsis
#include <semaphore.h>
int sem_timedwait (sem_t *sem, const struct timespec* abstime);

Return values

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

Detailed description

 The sem_timedwait function decrements (locks) the semaphore pointed to by sem, but blocks if the value of sem is zero, until the value is non-zero or timeout occurs.

Examples

sem_t mysemp;
struct timespec ts;
int val, sts;
#define TIMEOUT 3
if ( sem_init (&mysemp, 0, 1) == -1 ) {
      perror( "sem_init failed");
      return -1;
}

struct timeval now;
gettimeofday(&now,NULL);
ts.tv_sec=now.tv_sec + TIMEOUT;
ts.tv_nsec=0;
/* Lock Semaphore */
if (sem_timedwait(&mysemp, &ts) == 0)
{
    switch(errno)
    {
     case 0:
        printf ("Locked successfully\n");
        break;
     case ETIMEDOUT:
        printf ("could not lock, try later.....\n");
        break;
    }
}
else
    printf ("Sem_timedwait failed \n")
fprintf(stderr,"Thread wakened up\n");

Errors

 The sem_timedwait function will fail if:
[EINVAL]
The sem argument points to an invalid or uninitialized semaphore.
[ETIMEDOUT]
The semaphore could not be locked before the specified timeout value.

See also

 sem_getvalue, sem_post

Feedback

For additional information or queries on this page send feedback


sem_wait

Name

sem_wait, sem_trywait
sem_trywait

- decrement (lock) a semaphore

Library

 libc.lib

Synopsis
#include <semaphore.h>
int sem_wait (sem_t *sem);
int sem_trywait (sem_t *sem);

Return values

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

Detailed description

 The sem_wait function decrements (locks) the semaphore pointed to by sem, but blocks if the value of sem is zero, until the value is non-zero and the value can be decremented.

The sem_trywait function decrements (locks) the semaphore pointed to by sem only if the value is non-zero. Otherwise, the semaphore is not decremented and an error is returned.

Examples

sem_t psem;
if (sem_init(&psem, 0, 1) < 0) {
        perror("sem_init");
        return -1;
   }
 /* Lock Semaphore */
if( sem_wait(psem) == -1 ) {
  perror("sem_wait failed");
  return -1;
}
else
    printf ("Locked successfully\n");

sem_t psem;
if (sem_init(&psem, 0, 1) < 0) {
        perror("sem_init");
        return -1;
   }
 /* Lock Semaphore */
if ( sem_trywait(psem) == 0)
{   switch(errno)
     {
     case 0:
        printf ("Locked successfully\n");
        break;
    case EAGAIN:
        printf ("could not lock, try later.....\n");
        break;
    }
}
else
    printf ("Sem_trywait failed \n");

Errors

 The sem_wait and sem_trywait functions will fail if:
[EINVAL]
The sem argument points to an invalid or uninitialized semaphore.

Additionally, sem_trywait will fail if:
[EAGAIN]
The semaphore value was zero, and thus could not be decremented.

See also

 sem_getvalue, sem_post

Feedback

For additional information or queries on this page send feedback


semctl

Name

semctl - semaphore control operations

Library

 libc.lib

Synopsis
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/sem.h>
int semctl (int semid, int semnum, int cmd, ...);

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.

Detailed description

 The semctl system call performs the operation indicated by cmd on the semaphore set indicated by semid. A fourth argument, a union semun arg, is required for certain values of cmd. For the commands that use the arg argument, union semun is defined as follows:
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 memory pointed to by arg.buf.
IPC_SET | Changes the sem_perm.uid, sem_perm.gid, and sem_perm.mode members of the semaphore set’s struct semid_ds to match those of the struct pointed to by arg.buf.
IPC_RMID | Immediately removes the semaphore set from the system. The calling process’s uid must equal the semaphore set’s sem_perm.uid or sem_perm.cuid,
GETVAL | Return the value of semaphore number semnum.
SETVAL | Set the value of semaphore number semnum to arg.val. Outstanding adjust on exit values for this semaphore in any process are cleared.
GETPID | Return the pid of the last process to perform an operation on semaphore number semnum.
GETNCNT | Return the number of processes waiting for semaphore number semnum ’s value to become greater than its current value.
GETZCNT | Return the number of processes waiting for semaphore number semnum ’s value to become 0.
GETALL | Fetch the value of all of the semaphores in the set into the array pointed to by arg.array.
SETALL | Set the values of all of the semaphores in the set to the values in the array pointed to by arg.array. Outstanding adjust on exit values for all semaphores in this set, in any process are cleared.

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 */
};

Examples

#include <sys/ipc.h>
#include <sys/sem.h>
#include <stdio.h>
#include <errno.h>

#define SEM_SET_KEY 1000
#define NO_OF_SEMAPHORES 2

int main(void)
{
    int sem_set_id;
    union semun sem_val;
    /*
     * Create 2 semaphores in a set, with access only to
     * the owner
     */
    if((sem_set_id = semget(SEM_SET_KEY, NO_OF_SEMAPHORES, IPC_CREAT | 0600))
        == -1) {
       printf("Semaphore creation failed with errno %d\n", errno);
       return -1;
    }
    /*
     * Initialize the first semaphore in our set to 1
     */
    sem_val.array = NULL;
    sem_val.buf = NULL;
    sem_val.val = 1;
    if(semctl(sem_set_id, 0, SETVAL, sem_val) == -1) {
       printf("Could not initialize first semaphore (errno %d)\n", errno);
       return -1;
    }
    /*
     * Initialize the second semaphore in our set to 0
     */
    sem_val.val = 0;
    if(semctl(sem_set_id, 1, SETVAL, sem_val) == -1) {
       printf("Could not initialize second semaphore (errno %d)\n", errno);
       return -1;
    }
    /*
     * Delete the semaphore set
     */
    if(semctl(sem_set_id, NO_OF_SEMAPHORES, IPC_RMID) == -1) {
       printf("Could not delete semaphore set (errno %d)\n", errno);
       return -1;
    }
    return 0;
}

Errors

 The semctl system call will fail if:
[EINVAL]
 | No semaphore set corresponds to semid.
[EINVAL]
 | The semnum argument is not in the range of valid semaphores for given semaphore set.
[EPERM]
 | The calling process’s uid does not match the uid of the semaphore set’s owner or creator.
[EACCES]
 | Permission denied due to mismatch between operation and mode of semaphore set.
[ERANGE]
 | SETVAL or SETALL attempted to set a semaphore outside the allowable range [0 .. SEMVMX.]

See also

 semget, semop

Feedback

For additional information or queries on this page send feedback


semget

Name

semget - get a semaphore set identifier

Library

 libc.lib

Synopsis
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/sem.h>
int semget (key_t key, int nsems, int flag);

Return values

 The semget call returns the id of a semaphore set if successful; otherwise, -1 is returned and errno is set to indicate the error.

Detailed description

 Based on the values of key and flag, semget returns the identifier of a newly created 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 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 key is specified and the IPC_CREAT bit is set in flag, a new one will be created.
  • The ftok function may be used to generate a key from a pathname.

The mode of a newly created IPC object is determined by OR ’ing the following constants into the flag argument:
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 number of semaphores the set should contain. Otherwise, nsems may be specified as 0.

Examples

#include <sys/ipc.h>
#include <sys/sem.h>
#include <stdio.h>
#include <errno.h>

#define SEM_SET_KEY 1000
#define NO_OF_SEMAPHORES 2

int main(void)
{
    int sem_set_id;
    int perm;
    /*
     * Create 2 semaphores in a set, with access only to
     * the owner
     */
    perm = SEM_R | SEM_A;
    if((sem_set_id = semget(SEM_SET_KEY, NO_OF_SEMAPHORES, IPC_CREAT | perm))
        == -1) {
       printf("Semaphore creation failed with errno %d\n", errno);
       return -1;
    }
    return 0;
}

Errors

 The semget call will fail with:
[EACCES]
 | Access permission failure.
[EEXIST]
 | IPC_CREAT and IPC_EXCL were specified, and a semaphore set corresponding to key already exists.
[EINVAL]
 | The number of semaphores requested exceeds the system imposed maximum per set.
[ENOSPC]
 | A semaphore set has to be created but the system wide maximum number of semaphores would be exceeded.
[ENOSPC]
 | The kernel could not allocate a struct semid_ds.
[ENOENT]
 | No semaphore set was found corresponding to key, and IPC_CREAT was not specified.

See also

 semctl, semop, ftok

Feedback

For additional information or queries on this page send feedback


semop

Name

semop - semaphore operations

Library

 libc.lib

Synopsis
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/sem.h>
int semop (int semid, struct sembuf *array, size_t nops);

Return values

 The semop function returns 0 if successful; otherwise the value -1 is returned and errno is set to indicate the error.

Detailed description

 The semop system call atomically performs the array of operations indicated by array on the semaphore set indicated by semid. The length of array is indicated by nops. Each operation 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 be performed on semaphore number sem_num in the set. The values SEM_UNDO and IPC_NOWAIT may be OR ’ed into the sem_flg member in order to modify the behavior of the given operation.

The operation performed depends as follows on the value of sem_op:

  • When sem_op is positive and the process has alter permission, the semaphore’s value is incremented by sem_op ’s value. If SEM_UNDO is specified, the semaphore’s adjust on exit value is decremented by sem_op ’s value. A positive value for sem_op generally corresponds to a process releasing a resource associated with the semaphore.
  • The behavior when sem_op is negative and the process has alter permission, depends on the current value of the semaphore:
    • If the current value of the semaphore is greater than or equal to the absolute value of sem_op, then the value is decremented by the absolute value of sem_op. If SEM_UNDO is specified, the semaphore’s adjust on exit value is incremented by the absolute value of sem_op.
    • If the current value of the semaphore is less than the absolute value of sem_op, one of the following happens:
      • If IPC_NOWAIT was specified, then semop returns immediately with a return value of EAGAIN.
      • Otherwise, the calling process is put to sleep until one of the following conditions is satisfied:
        • Some other process removes the semaphore with the IPC_RMID option of semctl. In this case, semop returns immediately with a return value of EIDRM.
        • The semaphore’s value is greater than or equal to the absolute value of sem_op. When this condition becomes true, the semaphore’s value is decremented by the absolute value of sem_op, the semaphore’s adjust on exit value is incremented by the absolute value of sem_op.

    A negative value for sem_op generally means that a process is waiting for a resource to become available.

  • When sem_op is zero and the process has read permission, one of the following will occur:
    • If the current value of the semaphore is equal to zero then semop can return immediately.
    • If IPC_NOWAIT was specified, then semop returns immediately with a return value of EAGAIN.
    • Otherwise, the calling process is put to sleep until one of the following conditions is satisfied:
      • Some other process removes the semaphore with the IPC_RMID option of semctl. In this case, semop returns immediately with a return value of EIDRM.
      • The semaphore’s value becomes zero.

For each semaphore a process has in use, an "adjust on exit" value is maintained, as alluded to earlier. When a process exits, either voluntarily or involuntarily, the adjust on exit value for each semaphore is added to the semaphore’s value. This can be used to insure that a resource is released if a process terminates unexpectedly.

Examples

#include <sys/ipc.h>
#include <sys/sem.h>
#include <stdio.h>

void File_Update(char* path, int val)
{
    struct sembuf sem_op;
    FILE* fp;
    /*
     * Wait on the semaphore till the value is non-negative.
     */
    sem_op.sem_num = 0;
    sem_op.sem_op = -1;
    sem_op.sem_flg = 0;
    semop(sem_set_id, &sem_op, 1);
    /*
     * If we are here, then We have locked the semaphore,
     * and are assured exclusive access to file.
     * We can now manipulate the file
     */
    fp = fopen(path, "w");
    if (fp) {
        fprintf(fp, "%d\n", val);
        fclose(fp);
    }
    /*
     * Increase the value of the semaphore by 1 so that others blocked on
     * this semaphore get awakened.
     */
    sem_op.sem_num = 0;
    sem_op.sem_op = 1;
    sem_op.sem_flg = 0;
    semop(sem_set_id, &sem_op, 1);
}

Errors

 The semop system call will fail if:
[EINVAL]
 | No semaphore set corresponds to semid, or the process would exceed the system-defined limit for the number of per-process SEM_UNDO structures.
[EACCES]
 | Permission denied due to mismatch between operation and mode of semaphore set.
[EAGAIN]
 | The semaphore’s value would have resulted in the process being put to sleep and IPC_NOWAIT was specified.
[E2BIG]
 | Too many operations were specified. [SEMOPM]
[EFBIG]
 | sem_num was not in the range of valid semaphores for the set.
[EIDRM]
 | The semaphore set was removed from the system.
[ENOSPC]
 | The system SEM_UNDO pool [SEMMNU] is full.
[ERANGE]
 | The requested operation would cause either the semaphore’s current value [SEMVMX] or its adjust on exit value [SEMAEM] to exceed the system-imposed limits.

See also

 semctl, semget,

Bugs

 The semop system call may block waiting for memory even if IPC_NOWAIT was specified.

Feedback

For additional information or queries on this page send feedback


send

Name

send, sendto, sendmsg
- send a message from a socket

Library

 libc.lib

Synopsis
#include <sys/socket.h>
ssize_t send (int s, const void *msg, size_t len, int flags);
ssize_t sendto (int s, const void *msg, size_t len, int flags, const struct sockaddr *to, socklen_t tolen);
ssize_t sendmsg (int s, const struct msghdr *msg, int flags);

Detailed description

 The send function, and sendto and sendmsg system calls are used to transmit a message to another socket. The send function may be used only when the socket is in a connected state, while sendto and sendmsg may be used at any time.

The address of the target is given by to with tolen specifying its size. The length of the message is given by len. If the message is too long to pass atomically through the underlying protocol, the error EMSGSIZE is returned, and the message is not transmitted.

No indication of failure to deliver is implicit in a send. Locally detected errors are 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/O mode. The select system call may be used to determine when it is possible to send more data.

The flags argument may include one or more of the following:

#define MSG_OOB         0x00001 /* process out-of-band data */
#define MSG_PEEK        0x00002 /* peek at incoming message */
#define MSG_DONTROUTE   0x00004 /* bypass routing, use direct interface */
#define MSG_EOR         0x00008 /* data completes record */
#define MSG_EOF         0x00100 /* data completes transaction */

The flag MSG_OOB is used to send "out-of-band" data on sockets that support this notion (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 the concept. MSG_EOF requests that the sender side of a socket be shut down, and that an appropriate indication be sent at the end of the specified data; this flag is only implemented for SOCK_STREAM sockets in the PF_INET protocol family, and is used to implement Transaction TCP MSG_DONTROUTE is usually used only by diagnostic or routing programs.

See recv for a description of the msghdr structure.

Examples

#include <sys/socket.h>
#include <netinet/in.h>
#include <unistd.h>
void Recv()
{
   struct sockaddr_in serv_addr;
   int sock_fd;
   char line[15] = "Hello world!";
   int size = 13;
   serv_addr.sin_family = AF_INET;
   serv_addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
   serv_addr.sin_port = htons(5000);
   sock_fd = socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
   connect(sock_fd,(struct sockaddr*)&serv_addr,sizeof(serv_addr));
   send(sock_fd, line, size, 0);
   close(sock_fd);
}

#include <sys/socket.h>
#include <netinet/in.h>
#include <unistd.h>
void Sendto()
{
   sockaddr_in receiver_addr;
   int sock_fd;
   char line[15] = "Hello World!";
   sock_fd = socket(AF_INET,SOCK_DGRAM,IPPROTO_UDP);
   receiver_addr.sin_family = AF_INET;
   receiver_addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
   receiver_addr.sin_port = htons(5000);
   sendto(sock_fd, line, 13, 0,(struct sockaddr*)&receiver_addr,sizeof(receiver_addr));
   close(sock_fd);
}

#include <sys/socket.h>
#include <netinet/in.h>
#include <unistd.h>
void sendmsg()
{
   struct sockaddr_in receiver_addr;
   int sock_fd;
   char line[15] = "Hello World!";
   struct msghdr msg;
   struct iovec iov;
   sock_fd = socket(AF_INET,SOCK_DGRAM,IPPROTO_UDP);

   receiver_addr.sin_family = AF_INET;
   receiver_addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
   receiver_addr.sin_port = htons(5000);
   msg.msg_name = &receiver_addr;
   msg.msg_namelen = sizeof(receiver_addr);
   msg.msg_iov = &iov;
   msg.msg_iovlen = 1;
   msg.msg_iov->iov_base = line;
   msg.msg_iov->iov_len = 13;
   msg.msg_control = 0;
   msg.msg_controllen = 0;
   msg.msg_flags = 0;
   sendmsg(sock_fd,&msg,0);
   close(sock_fd);
}

Return values

 This function call returns the number of characters sent; otherwise the value -1 is returned and the global variable errno is set to indicate the error.

Errors

 The send function and sendto and sendmsg system calls fail if:
[EBADF]
 | An invalid descriptor was specified.
[EACCES]
 | The destination address is a broadcast address, and SO_BROADCAST has not been set on the socket.
[ENOTSOCK]
 | The argument s is not a socket.
[EFAULT]
 | An invalid user space address was specified for an argument.
[EMSGSIZE]
 | The socket requires that message be sent atomically, and the size of the message to be sent made this impossible.
[EAGAIN]
 | The socket is marked non-blocking and the requested operation would block.
[ENOBUFS]
 | The system was unable to allocate an internal buffer. The operation may succeed when buffers become available.
[ENOBUFS]
 | The output queue for a network interface was full. This generally indicates that the interface has stopped sending, but may be caused by transient congestion.
[EHOSTUNREACH]
 | The remote host was unreachable.
[EISCONN]
 | A destination address was specified and the socket is already connected.
[ECONNREFUSED]
 | The socket received an ICMP destination unreachable message from the last message sent. This typically means that the receiver is not listening on the remote port.
[EHOSTDOWN]
 | The remote host was down.
[ENETDOWN]
 | The remote network was down.
[EPERM]
 | The process using a SOCK_RAW socket was jailed and the source address specified in the IP header did not match the IP address bound to the prison.
[EPIPE]
 | The socket is unable to send anymore data ( SBS_CANTSENDMORE has been set on the socket). This typically means that the socket is not connected.

See also

 fcntl, getsockopt, recv, select, socket, write
The send function appeared in BSD 4.2.

Bugs

 Because sendmsg does not 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 then close it before it has actually been sent, the result being that the receiver gets a closed file descriptor. It is left to the application to implement an acknowledgment mechanism to prevent this from happening.

Feedback

For additional information or queries on this page send feedback


setbuf

Name

setbuf, setbuffer, setlinebuf, setvbuf
- stream buffering operations

Library

 libc.lib

Synopsis
#include <stdio.h>
void setbuf (FILE * restrict stream, char * restrict buf);
void setbuffer (FILE *stream, char *buf, int size);
int setlinebuf (FILE *stream);
int setvbuf (FILE * restrict stream, char * restrict buf, int mode, size_t size);
Sh RETURN VALUES The setvbuf function returns 0 on success, or EOF if the request cannot be honoured (note that the stream is still functional in this case).

The setlinebuf function returns what the equivalent setvbuf would have returned.

Detailed description

 The three types of buffering available are unbuffered, block buffered, and line buffered. When an output stream is unbuffered, information appears on the destination file or terminal as soon as written; when it is block buffered many characters are saved up and written as a block; when it is line buffered characters are saved up until a newline is output or input is read from any stream attached to a terminal device (typically stdin). The function fflush may be used to force the block out early.

Normally all files are block buffered. When the first I/O operation occurs on a file, malloc is called, and an optimally-sized buffer is obtained. If a stream refers to a terminal (as stdout normally does) it is line buffered. The standard error stream stderr is always unbuffered.

The setvbuf function may be used to alter the buffering behavior of a stream. The mode argument must be one of the following three macros:
_IONBF
 | unbuffered
_IOLBF
 | line buffered
_IOFBF
 | fully buffered

The size argument may be given as zero to obtain deferred optimal-size buffer allocation as usual. If it is not zero, then except for unbuffered files, the buf argument should point to a buffer at least size bytes long; this buffer will be used instead of the current buffer. If buf is not NULL, it is the caller’s responsibility to free this buffer after closing the stream.

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’’. Portable applications should call it only once on any given stream, and before any I/O is performed.

The other three calls are, in effect, simply aliases for calls to setvbuf. Except for the 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 to the caller, rather than being determined by the default BUFSIZ. The setlinebuf function is exactly equivalent to the call:
     setvbuf(stream, (char *)NULL, _IOLBF, 0);

Examples

/****************** this program shows setting up a buffer using setbuf **************/
#include <stdio.h>
int main()
{
        FILE *fp;
        char FullBuf[100];
        char msg[100];
        char * rptr;
        char name[20] = "c:\\setbuf1.txt";
        fp = fopen(name, "w+");
        if (fp == NULL)
                {
                printf ("fopen failed\n");
                return -1;
                }
        setbuf(fp, FullBuf);  // Fully buffered
        if (ferror(fp))
                {
                printf ("setbuf failed\n");
                fclose(fp);
                unlink(name);
                return -1;
                }
        fprintf(fp, "we are trying to buffer 20 characters at once\n ");

        fclose(fp);
        fp=fopen(name,"r");
        rptr = fgets(msg,100,fp);
        if(rptr == NULL)
                {
                printf("fgets failed\n");
                fclose(fp);
                return -1;
                }
        printf("file reading returned \"%s\"\n",msg);
        fclose(fp);

        unlink(name);
        return 0;
}

Output

file reading returned "we are trying to buffer 20 characters at once"

See also

 fopen, fread, malloc, printf

Feedback

For additional information or queries on this page send feedback


setjmp

Name

setjmp, longjmp, _setjmp, _longjmp
- save stack context for non-local goto

Library

 libc.lib

Synopsis
#include <setjmp.h>
int setjmp (jmp_buf env);
void longjmp (jmp_buf env, int val);
int _setjmp (jmp_buf env);
void _longjmp (jmp_buf env, int val);

Return values

 If the return is from a direct invocation, the setjmp function returns 0. If the return is from a call to longjmp(), setjmp() returns a non-zero value. After the longjmp is completed, program execution continues as if the corresponding invocation of setjmp() had just returned the value specified by val. If val is 0, setjmp() returns 1.

Detailed description

 The setjmp, and _setjmp functions save their calling environment in env. Each of these functions returns 0.

The corresponding longjmp functions restore the environment saved by their most recent respective invocations of the setjmp function. They then return so that program execution continues as if the corresponding invocation of the setjmp call had just returned the value specified by val, instead of 0.

The longjmp routines may not be called after the routine which called the setjmp routines returns.

All accessible objects have values as of the time longjmp routine was called, except that the values of objects of automatic storage invocation duration that do 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 while _setjmp / _longjmp pairs save and restore only the register set and the stack.

Examples

#include <setjmp.h>
#include <stdio.h>
#include <stdlib.h>

static void f1( int, int, int );
static void f2( void );
static jmp_buf jmpbuffer;

int main()
{
        int count;
        register int val;
        volatile int sum;

        count = 2; val = 3; sum = 4;

        if ( setjmp( jmpbuffer ) != 0 )
        {
    printf("in main: count = %d, val = %d, sum = %d\n", count, val, sum );
    exit(0);
  }

        f1(97, 98, 99 );

        return 0;
}

static void f1 (int i, int j, int k )
{
          printf("in f1: count = %d, val = %d, sum = %d\n", i, j , k );
    f2();
}

static void f2( void )
{
    longjmp( jmpbuffer, 1 );
}

Output

in f1: count = 97, val = 98, sum = 99
in main: count = 2, val = 3, sum = 4

Errors

 No errors are defined.

Limitations

 The signal related functionalities aren’t applicable to the symbian implementation as there is no support for signals from symbian. This essentially means that the setjmp and _setjmp routines have the same functionality and so is the case with longjmp and _longjmp routines.

Feedback

For additional information or queries on this page send feedback


setkey

Name

setkey
- manually manipulate the IPsec SA/SP database

Synopsis

 setkey
[-v] -c setkey

[-v] -f filename setkey

[-aPlv] -D setkey

[-Pv] -F setkey

[-h] -x

Detailed description

 The setkey

utility adds, updates, dumps, or flushes Security Association Database (SAD) entries as well as Security Policy Database (SPD) entries in the kernel.

The setkey

utility takes a series of operations from the standard input (if invoked with -c ) or the file named filename (if invoked with -f filename).
-D | Dump the SAD entries. If with -P , the SPD entries are dumped.
-F | Flush the SAD entries. If with -P , the SPD entries are flushed.
-a | The setkey utility usually does not display dead SAD entries with -D . If with -a , the dead SAD entries will be displayed as well. A dead SAD entry means that it has been expired but remains in the system because it is referenced by some SPD entries.
-h | Add hexadecimal dump on -x mode.
-l | Loop forever with short output on -D .
-v | Be verbose. The program will dump messages exchanged on PF_KEY socket, including messages sent from other processes to the kernel.
-x | Loop forever and dump all the messages transmitted to PF_KEY socket. -xx makes each timestamps unformatted.

Configuration syntax

With -c or -f on the command line, setkey

accepts the following configuration syntax. Lines starting with hash signs (‘#’) are treated as comment lines.
add [-46n] src dst protocol spi [extensions] algorithm ... ;
Add an SAD entry. add can fail with multiple reasons, including when the key length does not match the specified algorithm.
get [-46n] src dst protocol spi ;
Show an SAD entry.
delete [-46n] src dst protocol spi ;
Remove an SAD entry.
deleteall [-46n] src dst protocol ;
Remove all SAD entries that match the specification.
flush [protocol] ;
Clear all SAD entries matched by the options. -F on the command line achieves the same functionality.
dump [protocol] ;
Dumps all SAD entries matched by the options. -D on the command line achieves the same functionality.
spdadd [-46n] src_range dst_range upperspec policy ;
Add an SPD entry.
spddelete [-46n] src_range dst_range upperspec-P direction ;
Delete an SPD entry.
spdflush ;
Clear all SPD entries. -FP on the command line achieves the same functionality.
spddump ;
Dumps all SPD entries. -DP on the command line achieves the same functionality.

Meta-arguments are as follows:

src
dst
Source/destination of the secure communication is specified as IPv4/v6 address. The setkey

utility can resolve a FQDN into numeric addresses. If the FQDN resolves into multiple addresses, setkey

will install multiple SAD/SPD entries into the kernel by trying all possible combinations. -4 , -6 and -n restricts the address resolution of FQDN in certain ways. -4 and -6 restrict results into IPv4/v6 addresses only, respectively. -n avoids FQDN resolution and requires addresses to be numeric addresses.

protocol | protocol is one of following:
esp | ESP based on rfc2406
esp-old
ESP based on rfc1827
ah | AH based on rfc2402
ah-old
AH based on rfc1826
ipcomp
IPComp
tcp | TCP-MD5 based on rfc2385

spi Security Parameter Index (SPI) for the SAD and the SPD. spi must be a decimal number, or a hexadecimal number with ‘0x’ prefix. SPI values between 0 and 255 are reserved for future use by IANA and they cannot be used. TCP-MD5 associations must use 0x1000 and therefore only have per-host granularity at this time.

extensions
take some of the following:
-m mode
Specify a security protocol mode for use. mode is one of following: transport, tunnel or any. The default value is any.
-r size
Specify window size of bytes for replay prevention. size must be decimal number in 32-bit word. If size is zero or not specified, replay check does not take place.
-u id Specify the identifier of the policy entry in SPD. See policy.
-f pad_option
defines the content of the ESP padding. pad_option is one of following:
zero-pad | All of the padding are zero.
random-pad
A series of randomized values are set.
seq-pad | A series of sequential increasing numbers started from 1 are set.
-f nocyclic-seq
Do not allow cyclic sequence number.
-lh time
-ls time
Specify hard/soft life time duration of the SA.

algorithm
-E ealgo key
Specify an encryption algorithm ealgo for ESP.
-E ealgo key -A aalgo key
Specify a encryption algorithm ealgo, as well as a payload authentication algorithm aalgo, for ESP.
-A aalgo key
Specify an authentication algorithm for AH.
-C calgo [-R]
Specify a compression algorithm for IPComp. If -R is specified, spi field value will be used as the IPComp CPI (compression parameter index) on wire as is. If -R is not specified, the kernel will use well-known CPI on wire, and spi field will be used only as an index for kernel internal usage.

key must be double-quoted character string, or a series of hexadecimal digits preceded by ‘0x’.

Possible values for ealgo, aalgo and calgo are specified in separate section.

src_range
dst_range
These are selections of the secure communication specified as IPv4/v6 address or IPv4/v6 address range, and it may accompany TCP/UDP port specification. This takes the following form:

 address

 address/prefixlen

 address[port]

 address/prefixlen[port]

prefixlen and port must be decimal number. The square bracket around port is really necessary. They are not manpage metacharacters. For FQDN resolution, the rules applicable to src and dst apply here as well.

upperspec
Upper-layer protocol to be used. Use one of the words in /etc/protocols as upperspec. Or icmp6, ip4, and any can be specified. any stands for "any protocol". Also, use the protocol number. Specify a type and/or a code of ICMPv6 when upper-layer protocol is ICMPv6. The specification can be placed after icmp6. A type is separated with a code by single comma. A code must be specified anytime. When a zero is specified, the kernel deals with it as a wildcard. Note that the kernel cannot distinguish a wildcard from that a type of ICMPv6 is zero. For example, the following means the policy does not require IPsec for any inbound Neighbor Solicitation:

     spdadd ::/0 ::/0 icmp6 135,0 -P in none;
NOTE: upperspec does not work against forwarding case at this moment, as it requires extra reassembly at forwarding node (not implemented at this moment). There are many protocols in /etc/protocols, but protocols except of TCP, UDP and ICMP may not be suitable to use with IPsec. be cautious when using the protocols.
policy
policy is the one of the following three formats:
-P direction discard
-P direction none
protocol/mode/src-dst/level [...]

Specify the direction of its policy as direction. Either out or in are used. discard means the packet matching indexes will be discarded. none means that IPsec operation will not take place onto the packet. ipsec means that IPsec operation will take place onto the packet. The part of protocol/mode/src-dst/level specifies the rule how to process the packet. Either ah, esp or ipcomp is to be set as protocol. mode is either transport or tunnel. If mode is tunnel, specify the end-points addresses of the SA as src and dst with '-' between these addresses which is used to specify the SA to use. If mode is transport, both src and dst can be omitted. level is to be one of the following: default, use, require or unique. If the SA is not available in every level, the kernel will request getting SA to the key exchange daemon. default means the kernel consults to the system wide default against the specified protocol , for example, esp_trans_deflev sysctl variable, when the kernel processes the packet. use means that the kernel use a SA if it is available, otherwise the kernel keeps normal operation. require means SA is required whenever the kernel sends a packet matched with the policy. unique is the same to require. In addition, it allows the policy to bind with the unique out-bound SA. Specify the policy level unique, racoon will configure the SA for the policy. If the SA is configured by manual keying for that policy, put the decimal number as the policy identifier after unique separated by colon ‘:’ like the following; unique:number. In order to bind this policy to the SA, number must be between 1 and 32767. It corresponds to extensions-u of the manual SA configuration. In order to use the SA bundle, multiple rules can be defined. For example, if an IP header was followed by AH header followed by ESP header followed by an upper layer protocol header, the rule would be:

     esp/transport//require ah/transport//require
The rule order is very important. Note that "discard" and "none" are not in the syntax described in ipsec_set_policy. There are little differences in the syntax. See ipsec_set_policy for detail.

Algorithms

 The following list shows the supported algorithms. protocol and algorithm are almost orthogonal. Followings are the list of authentication algorithms that can be used as aalgo in -A aalgo of protocol parameter:
algorithm       keylen (bits)   comment
hmac-md5        128             ah: rfc2403
                128             ah-old: rfc2085
hmac-sha1       160             ah: rfc2404
                160             ah-old: 128bit ICV (no document)
keyed-md5       128             ah: 96bit ICV (no document)
                128             ah-old: rfc1828
keyed-sha1      160             ah: 96bit ICV (no document)
                160             ah-old: 128bit ICV (no document)
null            0 to 2048       for debugging
hmac-sha2-256   256             ah: 96bit ICV
                                (draft-ietf-ipsec-ciph-sha-256-00)
                256             ah-old: 128bit ICV (no document)
hmac-sha2-384   384             ah: 96bit ICV (no document)
                384             ah-old: 128bit ICV (no document)
hmac-sha2-512   512             ah: 96bit ICV (no document)
                512             ah-old: 128bit ICV (no document)
hmac-ripemd160  160             ah: 96bit ICV (RFC2857)
                                ah-old: 128bit ICV (no document)
aes-xcbc-mac    128             ah: 96bit ICV (RFC3566)
                128             ah-old: 128bit ICV (no document)
tcp-md5         8 to 640        tcp: rfc2385

Followings are the list of encryption algorithms that can be used as ealgo in -E ealgo of protocol parameter:

algorithm       keylen (bits)   comment
des-cbc         64              esp-old: rfc1829, esp: rfc2405
3des-cbc        192             rfc2451
null            0 to 2048       rfc2410
blowfish-cbc    40 to 448       rfc2451
cast128-cbc     40 to 128       rfc2451
des-deriv       64              ipsec-ciph-des-derived-01
3des-deriv      192             no document
rijndael-cbc    128/192/256     rfc3602
aes-ctr         160/224/288     draft-ietf-ipsec-ciph-aes-ctr-03

Note that the first 128 bits of a key for aes-ctr will be used as AES key, and remaining 32 bits will be used as nonce.

Followings are the list of compression algorithms that can be used as calgo in -C calgo of protocol parameter:

algorithm       comment
deflate         rfc2394

Exit status
.Ex -std

Examples

add 3ffe:501:4819::1 3ffe:501:481d::1 esp 123457
        -E des-cbc 0x3ffe05014819ffff ;
add -6 myhost.example.com yourhost.example.com ah 123456
        -A hmac-sha1 "AH SA configuration!" ;
add 10.0.11.41 10.0.11.33 esp 0x10001
        -E des-cbc 0x3ffe05014819ffff
        -A hmac-md5 "authentication!!" ;
get 3ffe:501:4819::1 3ffe:501:481d::1 ah 123456 ;
flush ;
dump esp ;
spdadd 10.0.11.41/32[21] 10.0.11.33/32[any] any
        -P out ipsec esp/tunnel/192.168.0.1-192.168.1.2/require ;
add 10.1.10.34 10.1.10.36 tcp 0x1000 -A tcp-md5 "TCP-MD5 BGP secret" ;

See also

 ipsec_set_policy, racoon, sysctl
Changed manual key configuration for IPsec
The setkey

utility first appeared in WIDE Hydrangea IPv6 protocol stack kit. The utility was completely re-designed in June 1998.

Bugs

 The setkey

utility should report and handle syntax errors better.

For IPsec gateway configuration, src_range and dst_range with TCP/UDP port number do not work, as the gateway does not reassemble packets (cannot inspect upper-layer headers).

Feedback

For additional information or queries on this page send feedback


setlocale

Name

setlocale - set the current locale

Library

 libc.lib

Synopsis
#include <locale.h>
char * setlocale (int category, const char *locale);

Return values

 Upon successful completion, setlocale returns the string associated with the specified category for the requested locale. The setlocale function returns NULL and fails to change the locale if the given combination of category and locale makes no sense.

Detailed description

 The setlocale function sets the C library’s notion of natural language formatting style for particular sets of routines. Each such style is called a 'locale' and is invoked using an appropriate name passed as a C string.

The setlocale function recognizes several categories of routines. These are the categories and the sets of routines they select:

LC_ALL | Set the entire locale generically.
LC_COLLATE | Set a locale for string collation routines. Currently locale setting does not have effect on this category.
LC_CTYPE | This controls recognition of upper and lower case, alphabetic or non-alphabetic characters, and so on. Currently locale setting does not have effect on this category.
LC_MESSAGES
 | Set a locale for message catalogs. Currently this category is not supported.
LC_MONETARY
 | Set a locale for formatting monetary values; this affects the localeconv function.
LC_NUMERIC | Set a locale for formatting numbers. This controls the formatting of decimal points in input and output of floating point numbers in functions such as printf and scanf, as well as values returned by localeconv.
LC_TIME | Set a locale for formatting dates and times using the strftime function.

Only three locales are defined by default, the empty string which denotes the native environment, and the C and POSIX locales, which denote the C language environment. A locale argument of NULL causes setlocale to return the current locale. By default, C programs start in the C locale. The only function in the library that sets the locale is setlocale; the locale is never changed as a side effect of some other routine.

Examples

#include<stdio.h>
#include<locale.h>
int main()
{
        //Set the locale to UK English
        char* locale = setlocale(LC_ALL,"en_GB.ISO-8859-1");
        //Check whether locale setting is succesful or not
        if(NULL != locale)
        {
                printf("Locale setting is successful\n");
                printf("Locale is set to %s\n", locale);
        }
        else
        {
                printf("Locale setting failed\n");
        }
        return 0;
}

Output

Locale setting is successful
Locale is set to en_GB.ISO-8859-1

Errors

 No errors are defined.

See also

 localeconv, nl_langinfo

Feedback

For additional information or queries on this page send feedback


setpgid

Name

setpgid, setpgrp
- set process group

Library

 libc.lib

Synopsis
#include <unistd.h>
int setpgid (pid_t pid, pid_t pgrp);
int setpgrp (pid_t pid, pid_t pgrp);

Return values

 These functions always return 0.

Detailed description

 setpgid and setpgrp are functions belonging to set of APIs which are only build supported and not available functionally. The reason why only build support is extended to these APIs is, symbian operating system does not support creation of multiple users and groups in its environment. More over it may not make sense to have multiple users and groups in the context of a mobile environment.

Errors

 No error values are set.

Feedback

For additional information or queries on this page send feedback


setregid

Name

setregid
- set real and/or effective user or group ID

Library

 libc.lib

Synopsis
#include <unistd.h>
int setregid (gid_t rgid, gid_t egid);

Return values

 These functions always return 0.

Detailed description

 The setregid function belongs to set of APIs which are only build supported and not available functionally. The reason why only build support is extended to these APIs is, symbian operating system does not support creation of multiple users and groups in its environment. More over it may not make sense to have multiple users and groups in the context of a mobile environment.

Errors

 No error values are set.

Feedback

For additional information or queries on this page send feedback


setreuid

Name

setreuid
- set real and/or effective user or group ID

Library

 libc.lib

Synopsis
#include <unistd.h>
int setreuid (uid_t ruid, uid_t euid);

Return values

 These functions always return 0.

Detailed description

 The setreuid function belongs to set of APIs which are only build supported and not available functionally. The reason why only build support is extended to these APIs is, symbian operating system does not support creation of multiple users and groups in its environment. More over it may not make sense to have multiple users and groups in the context of a mobile environment.

Errors

 No error values are set.

Feedback

For additional information or queries on this page send feedback


setsid

Name

setsid - creates a session and sets the process group ID

Library

 libc.lib

Synopsis
#include <unistd.h>
pid_t setsid (void);

Return values

 These functions always return 0.

Detailed description

 The setsid function belongs to set of APIs which are only build supported and not available functionally. The reason why only build support is extended to these APIs is, symbian operating system does not support creation of multiple users and groups in its environment. More over it may not make sense to have multiple users and groups in the context of a mobile environment.

Errors

 No error values are set.

Feedback

For additional information or queries on this page send feedback


setuid

Name

setuid, seteuid, setgid, setegid
- set user identity

Library

 libc.lib

Synopsis
#include <sys/types.h>
#include <unistd.h>
int setuid (uid_t uid);
int seteuid (uid_t euid);
int setgid (gid_t gid);
int setegid (gid_t egid);

Return values

 These functions always return 0.

Detailed description

 setuid, seteuid, setgid and setegid are functions belonging to set of APIs which are only build supported and not available functionally. The reason why only build support is extended to these APIs is, symbian operating system does not support creation of multiple users and groups in its environment. More over it may not make sense to have multiple users and groups in the context of a mobile environment.

Errors

 No error values are set.

Feedback

For additional information or queries on this page send feedback


SHA1_Final - Secure Hash Algorithm

Name

SHA1, SHA1_Init
SHA1_Update, SHA1_Final

Secure Hash Algorithm, is a cryptographic hash function with a 160 bit output

Library

libcrypto.lib

Synopsis

#include <openssl/sha.h>
unsigned char *SHA1(const unsigned char *d, unsigned long n, unsigned char *md);
void SHA1_Init(SHA_CTX *c);
void SHA1_Update(SHA_CTX *c, const void *data, unsigned long len);
void SHA1_Final(unsigned char *md, SHA_CTX *c);

Detailed Description

SHA-1 (Secure Hash Algorithm) is a cryptographic hash function with a 160 bit output.

SHA1() computes the SHA-1 message digest of the n bytes at d and places it in md (which must have space for SHA_DIGEST_LENGTH == 20 bytes of output). If md is NULL, the digest is placed in a static array.

The following functions may be used if the message is not completely stored in memory:

SHA1_Init() initializes a SHA_CTX structure.

SHA1_Update() can be called repeatedly with chunks of the message to be hashed (len bytes at data).

SHA1_Final() places the message digest in md, which must have space for SHA_DIGEST_LENGTH == 20 bytes of output, and erases the SHA_CTX.

Applications should use the higher level functions EVP_DigestInit() etc. instead of calling the hash functions directly.

The predecessor of SHA-1, SHA, is also implemented, but it should be used only when backward compatibility is required.

Return Values

SHA1() returns a pointer to the hash value.

SHA1_Init(),
SHA1_Update() and
SHA1_Final() do not return values.

Conforming To

SHA: US Federal Information Processing Standard FIPS PUB 180 (Secure Hash Standard), SHA-1: US Federal Information Processing Standard FIPS PUB 180-1 (Secure Hash Standard), ANSI X9.30

See Also

hmac(), EVP_DigestInit()

History

SHA1(), SHA1_Init(),
SHA1_Update() and
 SHA1_Final() are available in all
versions of SSLeay and OpenSSL.

Feedback

For additional information or queries on this page send feedback


shmat

Name

shmat, shmdt
- shared memory operations

Library

 libc.lib

Synopsis
#include <machine/param.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
void * shmat (int shmid, const void *addr, int flag);
int shmdt (const void *addr);

Return values

 Upon success, shmat returns the address where the segment is attached; otherwise, -1 is returned and errno is set to indicate the error.

The shmdt function returns the value 0 if successful; otherwise the value -1 is returned and errno is set to indicate the error.

Detailed description

 The shmat system call attaches the shared memory segment identified by shmid to the calling process’s address space. The address where the segment is attached is determined as follows:
  • If addr is 0, the segment is attached at an address selected by the kernel.
  • If addr is nonzero and SHM_RND is not specified in flag, the segment is attached the specified address. (a nonzero addr is not supported)
  • If addr is specified and SHM_RND is specified, addr is rounded down to the nearest multiple of SHMLBA.(a nonzero addr is not supported)

The shmdt system call detaches the shared memory segment at the address specified by addr from the calling process’s address space.

Examples

#include <sys/ipc.h>
#include <sys/shm.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>

#define SHM_SEG_SIZE 1024

int main(void)
{
    int shm_id;
    char *shm_addr;
    /*
     * Create a shared memory segment
     */
    if ((shm_id = shmget(IPC_PRIVATE, SHM_SEG_SIZE,
                         IPC_CREAT | IPC_EXCL | 0666))
         == -1) {
        printf("Shared memory create failed with errno %d\n", errno);
        return -1;
    }
    /*
     * Attach the shared memory segment to the
     * process address space
     */
    if((shm_addr = (char *)shmat(shm_id, NULL, 0)) == (void *)-1) {
       printf("Shared memory attach failed with errno %d\n", errno);
       return -1;
    }
    /*
     * Copy data to shared memory segment
     */
    strcpy(shm_addr, "some_random_data");
    /*
     * Detach the shared memory segment
     */
    if(shmdt(shm_addr) == -1) {
       printf("Shared memory detach failed with errno %d\n", errno);
    }
    /*
     * Remove the shared memory segment
     */
    if(shmctl(shm_id, IPC_RMID, NULL) == -1) {
       printf("Shared memory destroy failed with errno %d\n", errno);
    }
    return 0;
}

Errors

 The shmat system call will fail if:
[EINVAL]
 | No shared memory segment was found corresponding to shmid.
[EINVAL]
 | The addr argument was not an acceptable address.
[ENOTSUP]
 | The addr argument was not zero.

The shmdt system call will fail if:
[EINVAL]
The addr argument does not point to a shared memory segment.

See also

 shmctl, shmget

Feedback

For additional information or queries on this page send feedback


shmctl

Name

shmctl - shared memory control

Library

 libc.lib

Synopsis
#include <machine/param.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
int shmctl (int shmid, int cmd, struct shmid_ds *buf);

Return values

 The shmctl function returns the value 0 if successful; otherwise the value -1 is returned and errno is set to indicate the error.

Detailed description

 Performs the action specified by cmd on the shared memory segment identified by shmid:
IPC_STAT | Fetch the segment’s struct shmid_ds, storing it in the memory pointed to by buf.
IPC_SET | Changes the shm_perm.uid, shm_perm.gid, and shm_perm.mode members of the segment’s struct shmid_ds to match those of the struct pointed to by buf.
IPC_RMID | Removes the segment from the system. The removal will not take effect until all processes having attached the segment have exited; however, once the IPC_RMID operation has taken place, no further processes will be allowed to attach the segment.

The shmid_ds structure is defined as follows:

struct shmid_ds {
    struct ipc_perm shm_perm;   /* operation permission structure */
    int             shm_segsz;  /* size of segment in bytes */
    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 */
};

Examples

#include <sys/ipc.h>
#include <sys/shm.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>

#define SHM_SEG_SIZE 1024

int main(void)
{
    int shm_id;
    char *shm_addr;
    /*
     * Create a shared memory segment
     */
    if ((shm_id = shmget(IPC_PRIVATE, SHM_SEG_SIZE,
                         IPC_CREAT | IPC_EXCL | 0666))
         == -1) {
        printf("Shared memory create failed with errno %d\n", errno);
        return -1;
    }
    /*
     * Attach the shared memory segment to the
     * process address space
     */
    if((shm_addr = (char *)shmat(shm_id, NULL, 0)) == (void *)-1) {
       printf("Shared memory attach failed with errno %d\n", errno);
       return -1;
    }
    /*
     * Copy data to shared memory segment
     */
    strcpy(shm_addr, "some_random_data");
    /*
     * Detach the shared memory segment
     */
    if(shmdt(shm_addr) == -1) {
       printf("Shared memory detach failed with errno %d\n", errno);
    }
    /*
     * Remove the shared memory segment
     */
    if(shmctl(shm_id, IPC_RMID, NULL) == -1) {
       printf("Shared memory destroy failed with errno %d\n", errno);
    }
    return 0;
}

Errors

 The shmctl system call will fail if:
[EINVAL]
 | Invalid operation, or no shared memory segment was found corresponding to shmid.
[EPERM]
 | The calling process’s uid does not match the uid of the shared memory segment’s owner or creator.
[EACCES]
 | Permission denied due to mismatch between operation and mode of shared memory segment.

See also

 shmat, shmdt, shmget, ftok

Feedback

For additional information or queries on this page send feedback


shmget

Name

shmget - allocates a shared memory segment

Library

 libc.lib

Synopsis
#include <machine/param.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
int shmget (key_t key, size_t size, int flag);

Return values

 Upon successful completion, shmget returns the positive integer identifier of a shared memory segment. Otherwise, -1 is returned and errno set to indicate the error.

Detailed description

 Based on the values of key and flag, shmget returns the identifier of a newly created or previously existing shared memory segment. The key is analogous to a filename: it provides a handle that names an IPC object. There are three ways to specify 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 key is specified and the IPC_CREAT bit is set in flag, a new one will be created.
  • The ftok may be used to generate a key from a pathname.

The mode of a newly created IPC object is determined by OR Ns’ing the following constants into the flag argument:
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 the new segment in bytes. The size of the segment may be rounded up to a multiple convenient to the kernel (i.e., the page size).

Examples

#include <sys/ipc.h>
#include <sys/shm.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>

#define SHM_SEG_SIZE 1024

int main(void)
{
    int shm_id;
    int perm;
    /*
     * Create a shared memory segment
     */
    perm = SHM_R | SHM_W;
    if ((shm_id = shmget(IPC_PRIVATE, SHM_SEG_SIZE,
                         IPC_CREAT | IPC_EXCL | perm))
         == -1) {
        printf("Shared memory create failed with errno %d\n", errno);
        return -1;
    }
    return 0;
}

Errors

 The shmget system call will fail if:
[EINVAL]
 | Size specified is greater than the size of the previously existing segment. Size specified is less than the system imposed minimum (1 byte), or greater than the system imposed maximum (512kb).
[ENOENT]
 | No shared memory segment was found matching key, and IPC_CREAT was not specified.
[ENOSPC]
 | A shared memory identifier is to be created but the system-imposed limit on the maximum number of allowed shared memory identifiers (256) system-wide would be exceeded.
[ENOMEM]
 | The kernel was unable to allocate enough memory to satisfy the request.
[EEXIST]
 | IPC_CREAT and IPC_EXCL were specified, and a shared memory segment corresponding to key already exists.

See also

 shmat, shmctl, shmdt, ftok

Feedback

For additional information or queries on this page send feedback


shutdown

Name

shutdown - shut down part of a full-duplex connection

Library

 libc.lib

Synopsis
#include <sys/types.h>
#include <sys/socket.h>
int shutdown (int sockfd, int how);

Return values

 The shutdown() function returns the value 0 if successful; otherwise the value -1 is returned and the global variable errno is set to indicate the error.

Detailed description

 The shutdown system call causes all or part of a full-duplex connection on the socket associated with the file descriptor sockfd to be shut down. The how argument specifies the type of shutdown. Possible values are:
SHUT_RD | further receives will be disallowed.
SHUT_WR | further sends will be disallowed.
SHUT_RDWR
 | further sends and receives will be disallowed.

Examples

#include <sys/socket.h>
#include <netinet/in.h>
#include <unistd.h>
TInt shutdown_example()
{
   int sock_fd;
   sockaddr_in addr,ss;
   unsigned int len;

   sock_fd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);

   addr.sin_family = AF_INET;
   addr.sin_addr.s_addr = htonl(INADDR_ANY);
   addr.sin_port = htons(5000);
   bind(sock_fd,(sockaddr*)&addr,sizeof(addr));
   shutdown(sock_fd, SHUT_RD)
   close(sock_fd);
}

Errors

 The shutdown system call fails if:
[EBADF]
 | The s argument is not a valid file descriptor.
[EINVAL]
 | The how argument is invalid.
[ENOTCONN]
 | The socket is not connected.
[ENOTSOCK]
 | The s argument does not refer to a socket.

See also

 connect, socket
The shutdown system call is expected to comply with -p1003.1g-2000, when finalized.
The shutdown system call appeared in BSD 4.2. The SHUT_RD, SHUT_WR, and SHUT_RDWR constants appeared in -p1003.1g-2000.

Feedback

For additional information or queries on this page send feedback


Signals

GObject's signals have nothing to do with standard UNIX signals: they connect arbitrary application-specific events with any number of listeners. For example, in GTK+, every user event (keystroke or mouse move) is received from the X server and generates a GTK+ event under the form of a signal emission on a given object instance.

Each signal is registered in the type system together with the type on which it can be emitted: users of the type are said to connect to the signal on a given type instance when they register a closure to be invoked upon the signal emission. Users can also emit the signal by themselves or stop the emission of the signal from within one of the closures connected to the signal.

When a signal is emitted on a given type instance, all the closures connected to this signal on this type instance will be invoked. All the closures connected to such a signal represent callbacks whose signature looks like:

return_type function_callback (gpointer instance, ... , gpointer user_data);

Signal registration

To register a new signal on an existing type, we can use any of g_signal_newv, g_signal_new_valist or g_signal_new functions:

guint     g_signal_newv       (const gchar *signal_name, GType itype, GSignalFlags signal_flags, GClosure *class_closure,
                               GSignalAccumulator  accumulator, gpointer accu_data, GSignalCMarshaller  c_marshaller,
                               GType return_type, guint n_params, GType *param_types);

The number of parameters to these functions is a bit intimidating but they are relatively simple:

  • signal_name: is a string which can be used to uniquely identify a given signal.

  • itype: is the instance type on which this signal can be emitted.

  • signal_flags: partly defines the order in which closures which were connected to the signal are invoked.

  • class_closure: this is the default closure for the signal: if it is not NULL upon the signal emission, it will be invoked upon this emission of the signal. The moment where this closure is invoked compared to other closures connected to that signal depends partly on the signal_flags.

  • accumulator: this is a function pointer which is invoked after each closure has been invoked. If it returns FALSE, signal emission is stopped. If it returns TRUE, signal emission proceeds normally. It is also used to compute the return value of the signal based on the return value of all the invoked closures.

  • accumulator_data: this pointer will be passed down to each invocation of the accumulator during emission.

  • c_marshaller: this is the default C marshaller for any closure which is connected to this signal.

  • return_type: this is the type of the return value of the signal.

  • n_params: this is the number of parameters this signal takes.

  • param_types: this is an array of GTypes which indicate the type of each parameter of the signal. The length of this array is indicated by n_params.

As you can see from the above definition, a signal is basically a description of the closures which can be connected to this signal and a description of the order in which the closures connected to this signal will be invoked.

Signal connection

If you want to connect to a signal with a closure, you have three possibilities:

  • You can register a class closure at signal registration: this is a system-wide operation. i.e.: the class_closure will be invoked during each emission of a given signal on all the instances of the type which supports that signal.

  • You can use g_signal_override_class_closure which overrides the class_closure of a given type. It is possible to call this function only on a derived type of the type on which the signal was registered. This function is of use only to language bindings.

  • You can register a closure with the g_signal_connect family of functions. This is an instance-specific operation: the closure will be invoked only during emission of a given signal on a given instance.

It is also possible to connect a different kind of callback on a given signal: emission hooks are invoked whenever a given signal is emitted whatever the instance on which it is emitted. Emission hooks are used for example to get all mouse_clicked emissions in an application to be able to emit the small mouse click sound. Emission hooks are connected with g_signal_add_emission_hook and removed with g_signal_remove_emission_hook.

Signal emission

Signal emission is done through the use of the g_signal_emit family of functions.

void  g_signal_emitv        (const GValue *instance_and_params, guint signal_id, GQuark detail, GValue *return_value);

  • The instance_and_params array of GValues contains the list of input parameters to the signal. The first element of the array is the instance pointer on which to invoke the signal. The following elements of the array contain the list of parameters to the signal.

  • signal_id identifies the signal to invoke.

  • detail identifies the specific detail of the signal to invoke. A detail is a kind of magic token/argument which is passed around during signal emission and which is used by closures connected to the signal to filter out unwanted signal emissions. In most cases, you can safely set this value to zero. See the section called “The detail argument” for more details about this parameter.

  • return_value holds the return value of the last closure invoked during emission if no accumulator was specified. If an accumulator was specified during signal creation, this accumulator is used to calculate the return_value as a function of the return values of all the closures invoked during emission. [9] If no closure is invoked during emission, the return_value is nonetheless initialized to zero/null.

Internally, the GValue array is passed to the emission function proper, signal_emit_unlocked_R (implemented in gsignal.c). Signal emission can be decomposed in 5 steps:

  • RUN_FIRST: if the G_SIGNAL_RUN_FIRST flag was used during signal registration and if there exist a class_closure for this signal, the class_closure is invoked. Jump to EMISSION_HOOK state.

  • EMISSION_HOOK: if any emission hook was added to the signal, they are invoked from first to last added. Accumulate return values and jump to HANDLER_RUN_FIRST state.

  • HANDLER_RUN_FIRST: if any closure were connected with the g_signal_connect family of functions, and if they are not blocked (with the g_signal_handler_block family of functions) they are run here, from first to last connected. Jump to RUN_LAST state.

  • RUN_LAST: if the G_SIGNAL_RUN_LAST flag was set during registration and if a class_closure was set, it is invoked here. Jump to HANDLER_RUN_LAST state.

  • HANDLER_RUN_LAST: if any closure were connected with the g_signal_connect_after family of functions, if they were not invoked during HANDLER_RUN_FIRST and if they are not blocked, they are run here, from first to last connected. Jump to RUN_CLEANUP state.

  • RUN_CLEANUP: if the G_SIGNAL_RUN_CLEANUP flag was set during registration and if a class_closure was set, it is invoked here. Signal emission is completed here.

If, at any point during emission (except in RUN_CLEANUP state), one of the closures or emission hook stops the signal emission with g_signal_stop, emission jumps to CLEANUP state.

If, at any point during emission, one of the closures or emission hook emits the same signal on the same instance, emission is restarted from the RUN_FIRST state.

The accumulator function is invoked in all states, after invocation of each closure (except in EMISSION_HOOK and CLEANUP). It accumulates the closure return value into the signal return value and returns TRUE or FALSE. If, at any point, it does not return TRUE, emission jumps to CLEANUP state.

If no accumulator function was provided, the value returned by the last handler run will be returned by g_signal_emit.

The detail argument

All the functions related to signal emission or signal connection have a parameter named the detail. Sometimes, this parameter is hidden by the API but it is always there, under one form or another.

Of the three main connection functions, only one has an explicit detail parameter as a GQuark [10]:

gulong	 g_signal_connect_closure_by_id	   (gpointer instance, guint signal_id, GQuark detail, GClosure *closure, gboolean after);

The two other functions hide the detail parameter in the signal name identification:

gulong	 g_signal_connect_closure   (gpointer instance, const gchar *detailed_signal, GClosure *closure, gboolean after);
gulong	 g_signal_connect_data	    (gpointer instance, const gchar *detailed_signal, GCallback c_handler, gpointer data, GClosureNotify destroy_data, GConnectFlags connect_flags);

Their detailed_signal parameter is a string which identifies the name of the signal to connect to. However, the format of this string is structured to look like signal_name::detail_name. Connecting to the signal named notify::cursor_position will actually connect to the signal named notify with the cursor_position name. Internally, the detail string is transformed to a GQuark if it is present.

Of the four main signal emission functions, three have an explicit detail parameter as a GQuark again:

void    g_signal_emitv        (const GValue *instance_and_params, guint signal_id, GQuark detail, GValue *return_value);
void    g_signal_emit_valist  (gpointer instance, guint signal_id, GQuark detail, va_list var_args);
void    g_signal_emit         (gpointer instance, guint signal_id, GQuark detail, ...);

The fourth function hides it in its signal name parameter:

void    g_signal_emit_by_name (gpointer instance, const gchar *detailed_signal, ...);

The format of the detailed_signal parameter is exactly the same as the format used by the g_signal_connect functions: signal_name::detail_name.

If a detail is provided by the user to the emission function, it is used during emission to match against the closures which also provide a detail. The closures which provided a detail will not be invoked (even though they are connected to a signal which is being emitted) if their detail does not match the detail provided by the user.

This completely optional filtering mechanism is mainly used as an optimization for signals which are often emitted for many different reasons: the clients can filter out which events they are interested into before the closure's marshalling code runs. For example, this is used extensively by the notify signal of GObject: whenever a property is modified on a GObject, instead of just emitting the notify signal, GObject associates as a detail to this signal emission the name of the property modified. This allows clients who wish to be notified of changes to only one property to filter most events before receiving them.

As a simple rule, users can and should set the detail parameter to zero: this will disable completely this optional filtering.

[9] James (again!!) gives a few non-trivial examples of accumulators: “ For instance, you may have an accumulator that ignores NULL returns from closures, and only accumulates the non-NULL ones. Another accumulator may try to return the list of values returned by the closures. ”

[10] A GQuark is an integer which uniquely represents a string. It is possible to transform back and forth between the integer and string representations with the functions g_quark_from_string and g_quark_to_string.

©2005-2006 Nokia


signbit

Name

signbit
- test sign of a real floating point number

Library

 libm.lib

Synopsis
#include <math.h>
int signbit (real-floating x);

Detailed description

 The signbit macro takes an argument of x and returns non-zero if the value of its sign is negative, otherwise 0.

Examples

#include <math.h>
int main( )
{
   double x1 = 0.0, x2 = -4.0 ;
   int y;
   y = signbit( x1);
   printf( "signbit( %f)  = %d\n", x1,  y );
   y = signbit( x2);
   printf( "signbit( %f)  = %d\n", x2,  y );
}

Output

signbit ( 0.0 ) = 0
signbit( -4.0 ) = 1

See also

 fpclassify, math

Feedback

For additional information or queries on this page send feedback


sin

Name

sin, sinf, sinl
- sine functions

Library

 libm.lib

Synopsis
#include <math.h>
double sin (double x);
float sinf (float x);
long double sinl (long double x);

Return values

 The sin and the sinf functions return the sine value.

Detailed description

 The sin and the sinf functions compute the sine of x (measured in radians). A large magnitude argument may yield a result with little or no significance. sinl is just an alias to the function sin

Examples

#include <math.h>
int main( )
{
   double pi_by_6 = 0.52359877559829887307710723054658383 ;
   double y;
   y = sin( pi_by_6 );
   printf( "sin( %f)  = %f\n", x1,  y );
   y = sinf( pi_by_6);
   printf( "sinf( %f) = %f\n", pi_by_6, y );
   y = sinl( pi_by_6);
   printf( "sinl( %f) = %f\n", pi_by_6, y );
 }

Output

sin ( 0.52359877559829887307710723054658383 ) = 0.500000
sinf( 0.52359877559829887307710723054658383 ) = 0.500000
sinl( 0.52359877559829887307710723054658383 ) = 0.500000

See also

 acos, asin, atan, atan2, cos, cosh, math, sinh, tan, tanh

Feedback

For additional information or queries on this page send feedback


sinh

Name

sinh, sinhf, sinhl
- hyperbolic sine function

Library

 libm.lib

Synopsis
#include <math.h>
double sinh (double x);
float sinhf (float x);
long double sinhl (long double x);

Detailed description

 The sinh and the sinhf functions compute the hyperbolic sine of x. The function sinhl is an alias to the function sinh

Examples

#include <math.h>
int main( )
{
   double inp = 0.75;
   double y;
   y = sinh( inp );
   printf( "sinh( %f)  = %f\n", inp,  y );
   y = sinhf( inp);
   printf( "sinhf( %f) = %f\n", inp, y );
   y = sinhl( inp);
   printf( "sinhl( %f) = %f\n", inp, y );
}

Output

sinh ( 0.75 ) = 0.8223167
sinhf( 0.75 ) = 0.8223167
sinhl( 0.75 ) = 0.8223167

See also

 acos, asin, atan, atan2, cos, cosh, math, sin, tan, tanh

Feedback

For additional information or queries on this page send feedback


sleep

Name

sleep - Sleep for the specified number of seconds

Library

 libc.lib

Synopsis
#include <unistd.h>
unsigned int sleep (unsigned int seconds);

Return values

 If the sleep function returns because the requested time has elapsed, the value returned will be zero.

Detailed description

 The sleep function suspends execution of the calling process until seconds seconds have elapse

Time interval is internally represented using 32 bit value(range +-2147483647). any time interval greater 2147483647, returns 0 without sleeping. Hence Maximum sleep time supported here is 35 minutes, 47 seconds.

Examples

/**
 * Detailed description: This test code shows usage of sleep system call , here sample code
 * sleeps for 2 seconds.
**/
#include <unistd.h>
int main()
{
  if(sleep(2) < 0 )
  {
    printf("Sleep failed \n");
    return -1;
  }
  printf("Sleep successful");
  return 0;
}

Output

Sleep successful

See also

 nanosleep

Feedback

For additional information or queries on this page send feedback


SMIME_read_PKCS7 - parse S/MIME message.

Name

SMIME_read_PKCS7 — parses S/MIME message

Library

libcrypto.lib

Synopsis

PKCS7 *SMIME_read_PKCS7(BIO *in, BIO **bcont);

Detailed Description

SMIME_read_PKCS7() parses a message in S/MIME format.

in is a BIO to read the message from.

If cleartext signing is used then the content is saved in a memory bio which is written to *bcont, otherwise *bcont is set to NULL.

The parsed PKCS#7 structure is returned or NULL if an error occurred.

Notes

If *bcont is not NULL then the message is clear text signed. *bcont can then be passed to PKCS7_verify() with the PKCS7_DETACHED flag set.

Otherwise the type of the returned structure can be determined using PKCS7_type().

To support future functionality if bcont is not NULL *bcont should be initialized to NULL. For example:

 BIO *cont = NULL;
 PKCS7 *p7;
 p7 = SMIME_read_PKCS7(in, &cont);

Bugs

The MIME parser used by SMIME_read_PKCS7() is somewhat primitive. While it will handle most S/MIME messages more complex compound formats may not work.

The parser assumes that the PKCS7 structure is always base64 encoded and will not handle the case where it is in binary format or uses quoted printable format.

The use of a memory BIO to hold the signed content limits the size of message which can be processed due to memory restraints: a streaming single pass option should be available.

Return Values

SMIME_read_PKCS7() returns a valid PKCS7 structure or NULL is an error occurred. The error can be obtained from ERR_get_error().

See Also

ERR_get_error(), PKCS7_type(),
PKCS7_sign(),
PKCS7_verify(),
PKCS7_encrypt(), PKCS7_decrypt()

History

SMIME_read_PKCS7() was added to OpenSSL 0.9.5

Feedback

For additional information or queries on this page send feedback


SMIME_write_PKCS7 - convert PKCS#7 structure to S/MIME format.

Name

SMIME_write_PKCS7— converts PKCS#7 structure to S/MIME format

Library

libcrypto.lib

Synopsis

int SMIME_write_PKCS7(BIO *out, PKCS7 *p7, BIO *data, int flags);

Detailed Description

SMIME_write_PKCS7() adds the appropriate MIME headers to a PKCS#7 structure to produce an S/MIME message.

out is the BIO to write the data to. p7 is the appropriate PKCS7 structure. If cleartext signing (multipart/signed) is being used then the signed data must be supplied in the data argument. flags is an optional set of flags.

Notes

The following flags can be passed in the flags parameter.

If PKCS7_DETACHED is set then cleartext signing will be used, this option only makes sense for signedData where PKCS7_DETACHED is also set when PKCS7_sign() is also called.

If the PKCS7_TEXT flag is set MIME headers for type text/plain are added to the content, this only makes sense if PKCS7_DETACHED is also set.

If the PKCS7_PARTSIGN flag is set the signed data is finalized and output along with the content. This flag should only be set if PKCS7_DETACHED is also set and the previous call to PKCS7_sign() also set these flags.

If cleartext signing is being used and PKCS7_PARTSIGN not set then the data must be read twice: once to compute the signature in PKCS7_sign() and once to output the S/MIME message.

Bugs

SMIME_write_PKCS7() always base64 encodes PKCS#7 structures, there should be an option to disable this.

Return Values

SMIME_write_PKCS7() returns 1 for success or 0 for failure.

See Also

ERR_get_error(),
PKCS7_sign(),
PKCS7_verify(),
PKCS7_encrypt(), PKCS7_decrypt()

History

SMIME_write_PKCS7() was added to OpenSSL 0.9.5

Feedback

For additional information or queries on this page send feedback


sockatmark

Name

sockatmark - determine whether a socket is at the out-of-band mark

Library

 libc.lib

Synopsis
#include <sys/socket.h>
int sockatmark (int s);

Return values

 Upon successful completion, the sockatmark function returns the value 1 if the read pointer is pointing at the OOB mark, 0 if it is not. Otherwise the value -1 is returned and the global variable errno is set to indicate the error.

Detailed description

 To find out if the read pointer is currently pointing at the mark in the data stream, the sockatmark function is provided. If sockatmark returns 1, the next read will return data after the mark. Otherwise (assuming out of band data has arrived), the next read will provide data sent by the client prior to transmission of the out of band signal. The routine used in the remote login process to flush output on receipt of an interrupt or quit signal is shown below. It reads the normal data up to the mark (to discard it), then reads the out-of-band byte.
#include <sys/socket.h>
...
oob()
{
        int out = FWRITE, mark;
        char waste[BUFSIZ];
        /* flush local terminal output */
        ioctl(1, TIOCFLUSH, (char *)&out);
        for (;;) {
                if ((mark = sockatmark(rem)) < 0) {
                        perror("sockatmark");
                        break;
                }
                if (mark)
                        break;
                (void) read(rem, waste, sizeof (waste));
        }
        if (recv(rem, &mark, 1, MSG_OOB) < 0) {
                perror("recv");
                ...
        }
        ...
}

Examples

#include <sys/socket.h>
#include <netinet/in.h>
#include <unistd.h>
void SockAtMark()
{
   int sockfd;
   sockaddr_in selfAddr;
   sockfd = socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);

   selfAddr.sin_family = AF_INET;
   selfAddr.sin_addr.s_addr = INADDR_ANY;
   selfAddr.sin_port = htons(5000);
   bind(sockfd,(struct sockaddr*)&selfAddr, sizeof(selfAddr));
   sockatmark(sockfd);
   close(sockfd);
}

Errors

 The sockatmark call fails if:
[EBADF]
 | The s argument is not a valid descriptor.
[ENOTTY]
 | The s argument is a descriptor for a file, not a socket.

See also

 recv send
The sockatmark function was introduced by -p1003.1-2001, to standardize the historical SIOCATMARK ioctl The ENOTTY error instead of the usual ENOTSOCK is to match the historical behavior of SIOCATMARK.

Feedback

For additional information or queries on this page send feedback


socket

Name

socket - create an endpoint for communication

Library

 libc.lib

Synopsis
#include <sys/socket.h>
int socket (int domain, int type, int protocol);

Detailed description

 The socket system call creates an endpoint for communication and returns a descriptor.

The domain argument specifies a communications domain within which communication will take place; this selects the protocol family which should be used. These families are defined in the include file
#include <sys/socket.h.>The currently understood formats are:

PF_LOCAL        Host-internal protocols, formerly called PF_UNIX,
PF_INET         Internet version 4 protocols,

The socket has the indicated type, which specifies the semantics of communication. Currently defined types are:

SOCK_STREAM     Stream socket,
SOCK_DGRAM      Datagram socket,
SOCK_SEQPACKET  Sequenced packet stream

A SOCK_STREAM type provides sequenced, reliable, two-way connection based byte streams. An out-of-band data transmission mechanism may be supported. A SOCK_DGRAM socket supports datagrams (connectionless, unreliable messages of a fixed (typically small) maximum length). A SOCK_SEQPACKET socket may provide a sequenced, reliable, two-way connection-based data transmission path for datagrams of fixed maximum length; a consumer may be required to read an entire packet with each read system call. This facility is protocol specific, and presently unimplemented.

The protocol argument specifies a particular protocol to be used with the socket. Normally only a single protocol exists to support a particular socket type within a given protocol family. However, it is possible that many protocols may exist, in which case a particular protocol must be specified in this manner. The protocol number to use is particular to the "communication domain" in which communication is to take place.

Sockets of type SOCK_STREAM are full-duplex byte streams, similar to pipes. A stream socket must be in a connected state before any data may be sent or received on it. A connection to another socket is created with a connect system call. Once connected, data may be transferred using read and write calls or some variant of the send and recv functions. (Some protocol families, such as the Internet family, support the notion of an "implied connect," which permits data to be sent piggybacked onto a connect operation by using the sendto system call.) When a session has been completed a close may be performed. Out-of-band data may also be transmitted as described in send and received as described in recv

The communications protocols used to implement a SOCK_STREAM insure that data is not lost or duplicated. If a piece of data for which the peer protocol has buffer space cannot be successfully transmitted within a reasonable length of time, then the connection is considered broken and calls will indicate an error with -1 returns and with ETIMEDOUT as the specific code in the global variable errno. The protocols optionally keep sockets "warm" by forcing transmissions roughly every minute in the absence of other activity. An error is then indicated if no response can be elicited on an otherwise idle connection for an extended period (e.g. 5 minutes).

SOCK_SEQPACKET sockets employ the same system calls as SOCK_STREAM sockets. The only difference is that read calls will return only the amount of data requested, and any remaining in the arriving packet will be discarded.

SOCK_DGRAM sockets allow sending of datagrams to correspondents named in send calls. Datagrams are generally received with recvfrom which returns the next datagram with its return address.

Examples

#include <sys/socket.h>
#include <unistd.h>
#include <stdio.h>
#inlcude <netinet/in.h>
void SocketExample()
{
    int sock_fd;
    sock_fd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
    close(sock_fd);
}

Return values

 The socket() function returns valid socket descriptor if successful; otherwise the value -1 is returned and the global variable errno is set to indicate the error.

Errors

 The socket system call fails if:
[EPROTONOSUPPORT]
 | The protocol type or the specified protocol is not supported within 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 protocol is denied.
[ENOBUFS]
 | Insufficient buffer space is available. The socket cannot be created until sufficient resources are freed.

See also

 accept bind connect getpeername getsockname getsockopt ioctl listen read recv select send shutdown write
An Introductory 4.3 BSD Interprocess Communication Tutorial
BSD Interprocess Communication Tutorial
The socket system call appeared in BSD 4.2 .

Feedback

For additional information or queries on this page send feedback


sqrt

Name

cbrt, cbrtf, cbrtl, sqrt, sqrtf, sqrtl
- square root function

Library

 libm.lib

Synopsis
#include <math.h>
double cbrt (double x);
float cbrtf (float x);
long double cbrtl (long double x);
double sqrt (double x);
float sqrtf (float x);
long double sqrtl (long double x);

Return values

 The cbrt and cbrtf functions return the requested cube root. The sqrt and sqrtf functions return the requested square root unless an error occurs. An attempt to take the sqrt of negative x causes an NaN to be returned.

Detailed description

 The cbrt and cbrtf functions compute the cube root of x. The function cbrtl is an alias to the function cbrt.

The sqrt and sqrtf functions compute the non-negative square root of x. The function sqrtl is an alias to the function sqrt.

Examples

#include <math.h>
int main( )
{
   double inp = -0.001;
   double y;
   y = cbrt( inp );
   printf( "cbrt( %f)  = %f\n", x1,  y );
   y = cbrtf( inp);
   printf( "cbrtf( %f) = %f\n", inp, y );
   y = cbrtl( inp);
   printf( "cbrtl( %f) = %f\n\n", inp, y );
   inp = 2209.0;
   y = sqrt( inp);
   printf( "sqrt( %f)  = %d\n", inp,  y );
   y = sqrtf( inp);
   printf( "sqrtf( %f) = %d\n", inp, y );
   y = sqrtl( inp);
   printf( "sqrtl( %f) = %d\n", inp, y );
}

Output

cbrt ( -0.001 ) = -0.100000
cbrtf( -0.001 ) = -0.100000
cbrtl( -0.001 ) = -0.100000
sqrt ( 2209.0 ) = 47.0
sqrtf( 2209.0 ) = 47.0
sqrtl( 2209.0 ) = 47.0

See also

 math

Feedback

For additional information or queries on this page send feedback


SSL_accept - wait for a TLS/SSL client to initiate a TLS/SSL handshake

Name

SSL_accept — waits for a TLS/SSL client to initiate the TLS/SSL handshake

Library

libssl.lib

Synopsis

#include <openssl/ssl.h>
int SSL_accept(SSL *ssl);

Detailed Description

SSL_accept() waits for a TLS/SSL client to initiate the TLS/SSL handshake. The communication channel must already have been set and assigned to the ssl by setting an underlying BIO.

Notes

The behaviour of SSL_accept() depends on the underlying BIO.

If the underlying BIO is blocking, SSL_accept() will only return once the handshake has been finished or an error occurred, except for SGC (Server Gated Cryptography). For SGC, SSL_accept() may return with -1, but SSL_get_error() will yield SSL_ERROR_WANT_READ/WRITE and SSL_accept() should be called again.

If the underlying BIO is non-blocking, SSL_accept() will also return when the underlying BIO could not satisfy the needs of SSL_accept() to continue the handshake, indicating the problem by the return value -1. In this case a call to SSL_get_error() with the return value of SSL_accept() will yield SSL_ERROR_WANT_READ or SSL_ERROR_WANT_WRITE. The calling process then must repeat the call after taking appropriate action to satisfy the needs of SSL_accept(). The action depends on the underlying BIO. When using a non-blocking socket, nothing is to be done, but select() can be used to check for the required condition. When using a buffering BIO, like a BIO pair, data must be written into or retrieved out of the BIO before being able to continue.

Return Values

The following return values can occur:

    2. The TLS/SSL handshake was successfully completed, a TLS/SSL connection has been established.

  2. The TLS/SSL handshake was not successful but was shut down controlled and by the specifications of the TLS/SSL protocol. Call SSL_get_error() with the return value ret to find out the reason.

    <0
    The TLS/SSL handshake was not successful because a fatal error occurred either at the protocol level or a connection failure occurred. The shutdown was not clean. It can also occur of action is need to continue the operation for non-blocking BIOs. Call SSL_get_error() with the return value ret to find out the reason.

See Also

SSL_get_error(),
SSL_connect(),
SSL_shutdown(),
ssl(), bio(),
SSL_set_connect_state(),
SSL_do_handshake(),
SSL_CTX_new()

Feedback

For additional information or queries on this page send feedback


SSL_alert_desc_string_long - get textual description of alert information

Name

SSL_alert_type_string, SSL_alert_type_string_long
SSL_alert_desc_string, SSL_alert_desc_string_long

gets textual description of alert information

Library

libssl.lib

Synopsis

#include <openssl/ssl.h>
const char *SSL_alert_type_string(int value);
const char *SSL_alert_type_string_long(int value);
const char *SSL_alert_desc_string(int value);
const char *SSL_alert_desc_string_long(int value);

Detailed Description

SSL_alert_type_string() returns a one letter string indicating the type of the alert specified by value.

SSL_alert_type_string_long() returns a string indicating the type of the alert specified by value.

SSL_alert_desc_string() returns a two letter string as a short form describing the reason of the alert specified by value.

SSL_alert_desc_string_long() returns a string describing the reason of the alert specified by value.

Notes

When one side of an SSL/TLS communication wants to inform the peer about a special situation, it sends an alert. The alert is sent as a special message and does not influence the normal data stream (unless its contents results in the communication being canceled).

A warning alert is sent, when a non-fatal error condition occurs. The ``close notify'' alert is sent as a warning alert. Other examples for non-fatal errors are certificate errors (``certificate expired'', ``unsupported certificate''), for which a warning alert may be sent. (The sending party may however decide to send a fatal error.) The receiving side may cancel the connection on reception of a warning alert on it discretion.

Several alert messages must be sent as fatal alert messages as specified by the TLS RFC. A fatal alert always leads to a connection abort.

Return Values

The following strings can occur for SSL_alert_type_string() or SSL_alert_type_string_long():

``W''/``warning''
``F''/``fatal''
``U''/``unknown''
This indicates that no support is available for this alert type. Probably value does not contain a correct alert message.

The following strings can occur for SSL_alert_desc_string() or SSL_alert_desc_string_long():

``CN''/``close notify''
The connection shall be closed. This is a warning alert.

``UM''/``unexpected message''
An inappropriate message was received. This alert is always fatal and should never be observed in communication between proper implementations.

``BM''/``bad record mac''
This alert is returned if a record is received with an incorrect MAC. This message is always fatal.

``DF''/``decompression failure''
The decompression function received improper input (e.g. data that would expand to excessive length). This message is always fatal.

``HF''/``handshake failure''
Reception of a handshake_failure alert message indicates that the sender was unable to negotiate an acceptable set of security parameters given the options available. This is a fatal error.

``NC''/``no certificate''
A client, that was asked to send a certificate, does not send a certificate (SSLv3 only).

``BC''/``bad certificate''
A certificate was corrupt, contained signatures that did not verify correctly, etc

``UC''/``unsupported certificate''
A certificate was of an unsupported type.

``CR''/``certificate revoked''
A certificate was revoked by its signer.

``CE''/``certificate expired''
A certificate has expired or is not currently valid.

``CU''/``certificate unknown''
Some other (unspecified) issue arose in processing the certificate, rendering it unacceptable.

``IP''/``illegal parameter''
A field in the handshake was out of range or inconsistent with other fields. This is always fatal.

``DC''/``decryption failed''
A TLSCiphertext decrypted in an invalid way: either it wasn't an even multiple of the block length or its padding values, when checked, weren't correct. This message is always fatal.

``RO''/``record overflow''
A TLSCiphertext record was received which had a length more than 2^14+2048 bytes, or a record decrypted to a TLSCompressed record with more than 2^14+1024 bytes. This message is always fatal.

``CA''/``unknown CA''
A valid certificate chain or partial chain was received, but the certificate was not accepted because the CA certificate could not be located or couldn't be matched with a known, trusted CA. This message is always fatal.

``AD''/``access denied''
A valid certificate was received, but when access control was applied, the sender decided not to proceed with negotiation. This message is always fatal.

``DE''/``decode error''
A message could not be decoded because some field was out of the specified range or the length of the message was incorrect. This message is always fatal.

``CY''/``decrypt error''
A handshake cryptographic operation failed, including being unable to correctly verify a signature, decrypt a key exchange, or validate a finished message.

``ER''/``export restriction''
A negotiation not in compliance with export restrictions was detected; for example, attempting to transfer a 1024 bit ephemeral RSA key for the RSA_EXPORT handshake method. This message is always fatal.

``PV''/``protocol version''
The protocol version the client has attempted to negotiate is recognized, but not supported. (For example, old protocol versions might be avoided for security reasons). This message is always fatal.

``IS''/``insufficient security''
Returned instead of handshake_failure when a negotiation has failed specifically because the server requires ciphers more secure than those supported by the client. This message is always fatal.

``IE''/``internal error''
An internal error unrelated to the peer or the correctness of the protocol makes it impossible to continue (such as a memory allocation failure). This message is always fatal.

``US''/``user canceled''
This handshake is being canceled for some reason unrelated to a protocol failure. If the user cancels an operation after the handshake is complete, just closing the connection by sending a close_notify is more appropriate. This alert should be followed by a close_notify. This message is generally a warning.

``NR''/``no renegotiation''
Sent by the client in response to a hello request or by the server in response to a client hello after initial handshaking. Either of these would normally lead to renegotiation; when that is not appropriate, the recipient should respond with this alert; at that point, the original requester can decide whether to proceed with the connection. One case where this would be appropriate would be where a server has spawned a process to satisfy a request; the process might receive security parameters (key length, authentication, etc.) at startup and it might be difficult to communicate changes to these parameters after that point. This message is always a warning.

``UK''/``unknown''
This indicates that no description is available for this alert type. Probably value does not contain a correct alert message.

See Also

ssl(), SSL_CTX_set_info_callback()

Feedback

For additional information or queries on this page send feedback


SSL_CIPHER_description - get SSL_CIPHER properties

Name

SSL_CIPHER_get_name, SSL_CIPHER_get_bits
SSL_CIPHER_get_version,

gets SSL_CIPHER properties.

Library

libssl.lib

Synopsis

#include <openssl/ssl.h>
const char *SSL_CIPHER_get_name(const SSL_CIPHER *cipher);
int SSL_CIPHER_get_bits(const SSL_CIPHER *cipher, int *alg_bits);
char *SSL_CIPHER_get_version(const SSL_CIPHER *cipher);
char *SSL_CIPHER_description(SSL_CIPHER *cipher, char *buf, int size);

Detailed Description

SSL_CIPHER_get_name() returns a pointer to the name of cipher. If the argument is the NULL pointer, a pointer to the constant value ``NONE'' is returned.

SSL_CIPHER_get_bits() returns the number of secret bits used for cipher. If alg_bits is not NULL, it contains the number of bits processed by the chosen algorithm. If cipher is NULL, 0 is returned.

SSL_CIPHER_get_version() returns the protocol version for cipher, currently ``SSLv2'', ``SSLv3'', or ``TLSv1''. If cipher is NULL, ``(NONE)'' is returned.

SSL_CIPHER_description() returns a textual description of the cipher used into the buffer buf of length len provided. len must be at least 128 bytes, otherwise a pointer to the string ``Buffer too small'' is returned. If buf is NULL, a buffer of 128 bytes is allocated using OPENSSL_malloc(). If the allocation fails, a pointer to the string ``OPENSSL_malloc Error'' is returned.

Notes

The number of bits processed can be different from the secret bits. An export cipher like e.g. EXP-RC4-MD5 has only 40 secret bits. The algorithm does use the full 128 bits (which would be returned for alg_bits), of which however 88bits are fixed. The search space is hence only 40 bits.

The string returned by SSL_CIPHER_description() in case of success consists of cleartext information separated by one or more blanks in the following sequence:

<ciphername>
Textual representation of the cipher name.

<protocol version>
Protocol version: SSLv2, SSLv3. The TLSv1 ciphers are flagged with SSLv3.

Kx=<key exchange>
Key exchange method: RSA (for export ciphers as RSA(512) or RSA(1024)), DH (for export ciphers as DH(512) or DH(1024)), DH/RSA, DH/DSS, Fortezza.

Au=<authentication>
Authentication method: RSA, DSS, DH, None. None is the representation of anonymous ciphers.

Enc=<symmetric encryption method>
Encryption method with number of secret bits: DES(40), DES(56), 3DES(168), RC4(40), RC4(56), RC4(64), RC4(128), RC2(40), RC2(56), RC2(128), IDEA(128), Fortezza, None.

Mac=<message authentication code>
Message digest: MD5, SHA1.

<export flag>
If the cipher is flagged exportable with respect to old US crypto regulations, the word ``export'' is printed.

Examples

Some examples for the output of SSL_CIPHER_description():

 EDH-RSA-DES-CBC3-SHA    SSLv3 Kx=DH       Au=RSA  Enc=3DES(168) Mac=SHA1
 EDH-DSS-DES-CBC3-SHA    SSLv3 Kx=DH       Au=DSS  Enc=3DES(168) Mac=SHA1
 RC4-MD5                 SSLv3 Kx=RSA      Au=RSA  Enc=RC4(128)  Mac=MD5
 EXP-RC4-MD5             SSLv3 Kx=RSA(512) Au=RSA  Enc=RC4(40)   Mac=MD5  export

Bugs

If SSL_CIPHER_description() is called with cipher being NULL, the library crashes.

If SSL_CIPHER_description() cannot handle a built-in cipher, the according description of the cipher property is unknown. This case should not occur.

Return Values

See Detailed Description

See Also

ssl(),
SSL_get_current_cipher(),
SSL_get_ciphers(), ciphers()

Feedback

For additional information or queries on this page send feedback


SSL_clear - reset SSL object to allow another connection

Name

SSL_clear — Resets ssl to allow another connection.

Library

libssl.lib

Synopsis

#include <openssl/ssl.h>
int SSL_clear(SSL *ssl);

Detailed Description

Resets ssl to allow another connection. All settings (method, ciphers, BIOs) are kept.

Notes

SSL_clear is used to prepare an SSL object for a new connection. While all settings are kept, a side effect is the handling of the current SSL session. If a session is still open, it is considered bad and will be removed from the session cache, as required by RFC2246. A session is considered open, if SSL_shutdown() was not called for the connection or at least SSL_set_shutdown() was used to set the SSL_SENT_SHUTDOWN state.

If a session was closed cleanly, the session object will be kept and all settings corresponding. This explicitly means, that e.g. the special method used during the session will be kept for the next

handshake. So if the session was a TLSv1 session, a SSL client object will use a TLSv1 client method for the next handshake and a SSL server object will use a TLSv1 server method, even if SSLv23_*_methods were chosen on startup. This will might lead to connection failures (see SSL_new()) for a description of the method's properties.

Warnings

SSL_clear() resets the SSL object to allow for another connection. The reset operation however keeps several settings of the last sessions (some of these settings were made automatically during the last handshake). It only makes sense when opening a new session (or reusing an old one) with the same peer that shares these settings. SSL_clear() is not a short form for the sequence SSL_free(); SSL_new(); .

Return Values

The following return values can occur:

  1. The SSL_clear() operation could not be performed. Check the error stack to find out the reason.

  2. The SSL_clear() operation was successful.

See Also

SSL_new(),
SSL_free(),
SSL_shutdown(),
SSL_set_shutdown(),
SSL_CTX_set_options(),
ssl(),
SSL_CTX_set_client_cert_cb()

Feedback

For additional information or queries on this page send feedback


SSL_COMP_add_compression_method - handle SSL/TLS integrated compression methods

Name

SSL_COMP_add_compression_method — handle SSL/TLS integrated compression methods

Library

libssl.lib

Synopsis

#include <openssl/ssl.h>
int SSL_COMP_add_compression_method(int id, COMP_METHOD *cm);

Detailed Description

SSL_COMP_add_compression_method() adds the compression method cm with the identifier id to the list of available compression methods. This list is globally maintained for all SSL operations within this application. It cannot be set for specific SSL_CTX or SSL objects.

Notes

The TLS standard (or SSLv3) allows the integration of compression methods into the communication. The TLS RFC does however not specify compression methods or their corresponding identifiers, so there is currently no compatible way to integrate compression with unknown peers. It is therefore currently not recommended to integrate compression into applications. Applications for non-public use may agree on certain compression methods. Using different compression methods with the same identifier will lead to connection failure.

An OpenSSL client speaking a protocol that allows compression (SSLv3, TLSv1) will unconditionally send the list of all compression methods enabled with SSL_COMP_add_compression_method() to the server during the handshake. Unlike the mechanisms to set a cipher list, there is no method available to restrict the list of compression method on a per connection basis.

An OpenSSL server will match the identifiers listed by a client against its own compression methods and will unconditionally activate compression when a matching identifier is found. There is no way to restrict the list of compression methods supported on a per connection basis.

The OpenSSL library has the compression methods COMP_rle() and (when especially enabled during compilation) COMP_zlib() available.

Warnings

Once the identities of the compression methods for the TLS protocol have been standardized, the compression API will most likely be changed. Using it in the current state is not recommended.

Return Values

SSL_COMP_add_compression_method() may return the following values:

  1. The operation succeeded.

    3. The operation failed. Check the error queue to find out the reason.

See Also

ssl()

Feedback

For additional information or queries on this page send feedback


SSL_connect - initiate the TLS/SSL handshake with an TLS/SSL server

Name

SSL_connect — initiate the TLS/SSL handshake with an TLS/SSL server.

Library

libssl.lib

Synopsis

#include <openssl/ssl.h>
int SSL_connect(SSL *ssl);

Detailed Description

SSL_connect()initiates the TLS/SSL handshake with a server. The communication channel must already have been set and assigned to the ssl by setting an underlying BIO.

Notes

The behaviour of SSL_connect() depends on the underlying BIO.

If the underlying BIO is blocking, SSL_connect() will only return once the handshake has been finished or an error occurred.

If the underlying BIO is non-blocking, SSL_connect() will also return when the underlying BIO could not satisfy the needs of SSL_connect() to continue the handshake, indicating the problem by the return value -1. In this case a call to SSL_get_error() with the return value of SSL_connect() will yield SSL_ERROR_WANT_READ or SSL_ERROR_WANT_WRITE. The calling process then must repeat the call after taking appropriate action to satisfy the needs of SSL_connect(). The action depends on the underlying BIO. When using a non-blocking socket, nothing is to be done, but select() can be used to check for the required condition. When using a buffering BIO, like a BIO pair, data must be written into or retrieved out of the BIO before being able to continue.

Return Values

The following return values can occur:

  1. The TLS/SSL handshake was successfully completed, a TLS/SSL connection has been established.

    3. The TLS/SSL handshake was not successful but was shut down controlled and by the specifications of the TLS/SSL protocol. Call SSL_get_error() with the return value ret to find out the reason.

    <0
    The TLS/SSL handshake was not successful, because a fatal error occurred either at the protocol level or a connection failure occurred. The shutdown was not clean. It can also occur of action is need to continue the operation for non-blocking BIOs. Call SSL_get_error() with the return value ret to find out the reason.

See Also

SSL_get_error(),
SSL_accept(),
SSL_shutdown(), ssl(),
bio(),
SSL_set_connect_state(),
SSL_do_handshake(),
SSL_CTX_new()

Feedback

For additional information or queries on this page send feedback


SSL_CTX_add_extra_chain_cert - add certificate to chain

Name

SSL_CTX_add_extra_chain_cert - adds certificate to chain

Library

libssl.lib

Synopsis

#include <openssl/ssl.h>
long SSL_CTX_add_extra_chain_cert(SSL_CTX ctx, X509 *x509)

Detailed Description

SSL_CTX_add_extra_chain_cert() adds the certificate x509 to the certificate chain presented together with the certificate. Several certificates can be added one after the other.

Notes

When constructing the certificate chain, the chain will be formed from these certificates explicitly specified. If no chain is specified, the library will try to complete the chain from the available CA certificates in the trusted CA storage, see SSL_CTX_load_verify_locations().

Return Values

SSL_CTX_add_extra_chain_cert() returns 1 on success. Check out the error stack to find out the reason for failure otherwise.

See Also

ssl(),
SSL_CTX_use_certificate(),
SSL_CTX_set_client_cert_cb(),
SSL_CTX_load_verify_locations()

Feedback

For additional information or queries on this page send feedback


SSL_remove_session - manipulate session cache

Name

SSL_CTX_add_session, SSL_add_session
SSL_CTX_remove_session, SSL_remove_session

manipulates session cache

Library

libssl.lib

Synopsis

#include <openssl/ssl.h>
int SSL_CTX_add_session(SSL_CTX *ctx, SSL_SESSION *c);
int SSL_add_session(SSL_CTX *ctx, SSL_SESSION *c);
int SSL_CTX_remove_session(SSL_CTX *ctx, SSL_SESSION *c);
int SSL_remove_session(SSL_CTX *ctx, SSL_SESSION *c);

Detailed Description

SSL_CTX_add_session() adds the session c to the context ctx. The reference count for session c is incremented by 1. If a session with the same session id already exists, the old session is removed by calling SSL_SESSION_free().

SSL_CTX_remove_session() removes the session c from the context ctx. SSL_SESSION_free() is called once for c.

SSL_add_session() and SSL_remove_session() are synonyms for their SSL_CTX_*() counterparts.

Notes

When adding a new session to the internal session cache, it is examined whether a session with the same session id already exists. In this case it is assumed that both sessions are identical. If the same session is stored in a different SSL_SESSION object, The old session is removed and replaced by the new session. If the session is actually identical (the SSL_SESSION object is identical), SSL_CTX_add_session() is a no-op, and the return value is 0.

If a server SSL_CTX is configured with the SSL_SESS_CACHE_NO_INTERNAL_STORE flag then the internal cache will not be populated automatically by new sessions negotiated by the SSL/TLS implementation, even though the internal cache will be searched automatically for session-resume requests (the latter can be suppressed by SSL_SESS_CACHE_NO_INTERNAL_LOOKUP). So the application can use SSL_CTX_add_session() directly to have full control over the sessions that can be resumed if desired.

Return Values

The following values are returned by all functions:

  1. The operation failed. In case of the add operation, it was tried to add
 the same (identical) session twice. In case of the remove operation, the
 session was not found in the cache.
  2.  The operation succeeded.

See Also

ssl(),
SSL_CTX_set_session_cache_mode(),
SSL_SESSION_free()

Feedback

For additional information or queries on this page send feedback


SSL_callback_ctrl - internal handling functions for SSL_CTX and SSL objects

Name

SSL_CTX_ctrl, SSL_CTX_callback_ctrl
SSL_ctrl, SSL_callback_ctrl

internal handling functions for SSL_CTX and SSL objects

Library

libssl.lib

Synopsis

#include <openssl/ssl.h>
long SSL_CTX_ctrl(SSL_CTX *ctx, int cmd, long larg, void *parg);
long SSL_CTX_callback_ctrl(SSL_CTX *, int cmd, void (*fp)());
long SSL_ctrl(SSL *ssl, int cmd, long larg, void *parg);
long SSL_callback_ctrl(SSL *, int cmd, void (*fp)());

Detailed Description

The SSL_*_ctrl() family of functions is used to manipulate settings of the SSL_CTX and SSL objects. Depending on the command cmd the arguments larg, parg, or fp are evaluated. These functions should never be called directly. All functionalities needed are made available via other functions or macros.

Return Values

The return values of the SSL*_ctrl() functions depend on the command supplied via the cmd parameter.

See Also

ssl()

Feedback

For additional information or queries on this page send feedback


SSL_flush_sessions - remove expired sessions

Name

SSL_CTX_flush_sessions, SSL_flush_sessions — remove expired sessions

Library

libssl.lib

Synopsis

#include <openssl/ssl.h>
void SSL_CTX_flush_sessions(SSL_CTX *ctx, long tm);
void SSL_flush_sessions(SSL_CTX *ctx, long tm);

Detailed Description

SSL_CTX_flush_sessions() causes a run through the session cache of ctx to remove sessions expired at time tm.

SSL_flush_sessions() is a synonym for SSL_CTX_flush_sessions().

Notes

If enabled, the internal session cache will collect all sessions established up to the specified maximum number (see SSL_CTX_sess_set_cache_size()). As sessions will not be reused ones they are expired, they should be removed from the cache to save resources. This can either be done automatically whenever 255 new sessions were established (see SSL_CTX_set_session_cache_mode()) or manually by calling SSL_CTX_flush_sessions().

The parameter tm specifies the time which should be used for the expiration test, in most cases the actual time given by time(0) will be used.

SSL_CTX_flush_sessions() will only check sessions stored in the internal cache. When a session is found and removed, the remove_session_cb is however called to synchronize with the external cache (see SSL_CTX_sess_set_get_cb()).

Return Values

See Also

ssl(),
SSL_CTX_set_session_cache_mode(),
SSL_CTX_set_timeout(),
SSL_CTX_sess_set_get_cb()

Feedback

For additional information or queries on this page send feedback


SSL_CTX_free - free an allocated SSL_CTX object

Name

SSL_CTX_free — free an allocated SSL_CTX object

Library

libssl.lib

Synopsis

#include <openssl/ssl.h>
void SSL_CTX_free(SSL_CTX *ctx);

Detailed Description

SSL_CTX_free() decrements the reference count of ctx, and removes the SSL_CTX object pointed to by ctx and frees up the allocated memory if the reference count has reached 0.

It also calls the free()ing procedures for indirectly affected items, if applicable: the session cache, the list of ciphers, the list of Client CAs, the certificates and keys.

Warnings

If a session-remove callback is set (SSL_CTX_sess_set_remove_cb()), this callback will be called for each session being freed from ctx's session cache. This implies, that all corresponding sessions from an external session cache are removed as well. If this is not desired, the user should explicitly unset the callback by calling SSL_CTX_sess_set_remove_cb(ctx, NULL) prior to calling SSL_CTX_free().

Return Values

SSL_CTX_free() does not provide diagnostic information.

See Also

SSL_CTX_new(),
ssl(),
SSL_CTX_sess_set_get_cb()

Feedback

For additional information or queries on this page send feedback


SSL_CTX_get_ex_data - internal application specific data functions

Name

SSL_CTX_get_ex_new_index, SSL_CTX_set_ex_data
SSL_CTX_get_ex_data

internal application specific data functions

Library

libssl.lib

Synopsis

#include <openssl/ssl.h>
int SSL_CTX_get_ex_new_index(long argl, void *argp, CRYPTO_EX_new *new_func, CRYPTO_EX_dup *dup_func, CRYPTO_EX_free *free_func);
int SSL_CTX_set_ex_data(SSL_CTX *ctx, int idx, void *arg);
void *SSL_CTX_get_ex_data(const SSL_CTX *ctx, int idx);
typedef int new_func(void *parent, void *ptr, CRYPTO_EX_DATA *ad, int idx, long argl, void *argp);
typedef void free_func(void *parent, void *ptr, CRYPTO_EX_DATA *ad, int idx, long argl, void *argp);
typedef int dup_func(CRYPTO_EX_DATA *to, CRYPTO_EX_DATA *from, void *from_d, int idx, long argl, void *argp);

Detailed Description

Several OpenSSL structures can have application specific data attached to them. These functions are used internally by OpenSSL to manipulate application specific data attached to a specific structure.

SSL_CTX_get_ex_new_index() is used to register a new index for application specific data.

SSL_CTX_set_ex_data() is used to store application data at arg for idx into the ctx object.

SSL_CTX_get_ex_data() is used to retrieve the information for idx from ctx.

A detailed description for the *_get_ex_new_index() functionality can be found in RSA_get_ex_new_index(). The *_get_ex_data() and *_set_ex_data() functionality is described in CRYPTO_set_ex_data().

See Also

ssl(),
RSA_get_ex_new_index(),
CRYPTO_set_ex_data()

Feedback

For additional information or queries on this page send feedback


SSL_CTX_get_verify_callback - get currently set verification parameters

Name

SSL_CTX_get_verify_mode, SSL_get_verify_mode
SSL_CTX_get_verify_depth, SSL_get_verify_depth
SSL_get_verify_callback, SSL_CTX_get_verify_callback

get currently set verification parameters

Library

libssl.lib

Synopsis

#include <openssl/ssl.h>
int SSL_CTX_get_verify_mode(const SSL_CTX *ctx);
int SSL_get_verify_mode(const SSL *ssl);
int SSL_CTX_get_verify_depth(const SSL_CTX *ctx);
int SSL_get_verify_depth(const SSL *ssl);
int (*SSL_CTX_get_verify_callback(const SSL_CTX *ctx))(int, X509_STORE_CTX *);
int (*SSL_get_verify_callback(const SSL *ssl))(int, X509_STORE_CTX *);

Detailed Description

SSL_CTX_get_verify_mode() returns the verification mode currently set in ctx.

SSL_get_verify_mode() returns the verification mode currently set in ssl.

SSL_CTX_get_verify_depth() returns the verification depth limit currently set in ctx. If no limit has been explicitly set, -1 is returned and the default value will be used.

SSL_get_verify_depth() returns the verification depth limit currently set in ssl. If no limit has been explicitly set, -1 is returned and the default value will be used.

SSL_CTX_get_verify_callback() returns a function pointer to the verification callback currently set in ctx. If no callback was explicitly set, the NULL pointer is returned and the default callback will be used.

SSL_get_verify_callback() returns a function pointer to the verification callback currently set in ssl. If no callback was explicitly set, the NULL pointer is returned and the default callback will be used.

Return Values

See Detailed Description.

See Also

ssl(), SSL_CTX_set_verify()

Feedback

For additional information or queries on this page send feedback


SSL_CTX_load_verify_locations - set default locations for trusted CA certificates

Name

SSL_CTX_load_verify_locations — set default locations for trusted CA certificates

Library

libssl.lib

Synopsis

#include <openssl/ssl.h>
int SSL_CTX_load_verify_locations(SSL_CTX *ctx, const char *CAfile, const char *CApath);

Detailed Description

SSL_CTX_load_verify_locations() specifies the locations for ctx, at which CA certificates for verification purposes are located. The certificates available via CAfile and CApath are trusted.

Examples

Generate a CA certificate file with descriptive text from the CA certificates ca1.pem ca2.pem ca3.pem:
 #!/bin/sh
 rm CAfile.pem
 for i in ca1.pem ca2.pem ca3.pem ; do
   openssl x509 -in $i -text >> CAfile.pem
 done

Prepare the directory /some/where/certs containing several CA certificates for use as CApath:

 cd /some/where/certs
 c_rehash .

Notes

If CAfile is not NULL, it points to a file of CA certificates in PEM format. The file can contain several CA certificates identified by

 -----BEGIN CERTIFICATE-----
 ... (CA certificate in base64 encoding) ...
 -----END CERTIFICATE-----

sequences. Before, between, and after the certificates text is allowed which can be used e.g. for descriptions of the certificates.

The CAfile is processed on execution of the SSL_CTX_load_verify_locations() function.

If CApath is not NULL, it points to a directory containing CA certificates in PEM format. The files each contain one CA certificate. The files are looked up by the CA subject name hash value, which must hence be available. If more than one CA certificate with the same name hash value exist, the extension must be different (e.g. 9d66eef0.0, 9d66eef0.1 etc). The search is performed in the ordering of the extension number, regardless of other properties of the certificates. Use the c_rehash utility to create the necessary links.

The certificates in CApath are only looked up when required, e.g. when building the certificate chain or when actually performing the verification of a peer certificate.

When looking up CA certificates, the OpenSSL library will first search the certificates in CAfile, then those in CApath. Certificate matching is done based on the subject name, the key identifier (if present), and the serial number as taken from the certificate to be verified. If these data do not match, the next certificate will be tried. If a first certificate matching the parameters is found, the verification process will be performed; no other certificates for the same parameters will be searched in case of failure.

In server mode, when requesting a client certificate, the server must send the list of CAs of which it will accept client certificates. This list is not influenced by the contents of CAfile or CApath and must explicitly be set using the SSL_CTX_set_client_CA_list() family of functions.

When building its own certificate chain, an OpenSSL client/server will try to fill in missing certificates from CAfile/CApath, if the certificate chain was not explicitly specified (see SSL_CTX_add_extra_chain_cert(), SSL_CTX_use_certificate().

Warnings

If several CA certificates matching the name, key identifier, and serial number condition are available, only the first one will be examined. This may lead to unexpected results if the same CA certificate is available with different expiration dates. If a ``certificate expired'' verification error occurs, no other certificate will be searched. Make sure to not have expired certificates mixed with valid ones.

Return Values

The following return values can occur:

  1. The operation failed because CAfile and CApath are NULL or the processing at one of the locations specified failed. Check the error stack to find out the reason.

    3. The operation succeeded.

See Also

ssl(),
SSL_CTX_set_client_CA_list(),
SSL_get_client_CA_list(),
SSL_CTX_use_certificate(),
SSL_CTX_add_extra_chain_cert(),
SSL_CTX_set_cert_store()

Feedback

For additional information or queries on this page send feedback


SSL_CTX_new - create a new SSL_CTX object as framework for TLS/SSL enabled functions

Name

SSL_CTX_new — creates a new SSL_CTX object as framework for TLS/SSL enabled functions

Library

libssl.lib

Synopsis

#include <openssl/ssl.h>
SSL_CTX *SSL_CTX_new(SSL_METHOD *method);

Detailed Description

SSL_CTX_new() creates a new SSL_CTX object as framework to establish TLS/SSL enabled connections.

Notes

The SSL_CTX object uses method as connection method. The methods exist in a generic type (for client and server use), a server only type, and a client only type. method can be of the following types:

SSLv2_method(void), SSLv2_server_method(void), SSLv2_client_method(void)
A TLS/SSL connection established with these methods will only understand the SSLv2 protocol. A client will send out SSLv2 client hello messages and will also indicate that it only understand SSLv2. A server will only understand SSLv2 client hello messages.

SSLv3_method(void), SSLv3_server_method(void), SSLv3_client_method(void)
A TLS/SSL connection established with these methods will only understand the SSLv3 protocol. A client will send out SSLv3 client hello messages and will indicate that it only understands SSLv3. A server will only understand SSLv3 client hello messages. This especially means, that it will not understand SSLv2 client hello messages which are widely used for compatibility reasons, see SSLv23_*_method().

TLSv1_method(void), TLSv1_server_method(void), TLSv1_client_method(void)
A TLS/SSL connection established with these methods will only understand the TLSv1 protocol. A client will send out TLSv1 client hello messages and will indicate that it only understands TLSv1. A server will only understand TLSv1 client hello messages. This especially means, that it will not understand SSLv2 client hello messages which are widely used for compatibility reasons, see SSLv23_*_method(). It will also not understand SSLv3 client hello messages.

SSLv23_method(void), SSLv23_server_method(void), SSLv23_client_method(void)
A TLS/SSL connection established with these methods will understand the SSLv2, SSLv3, and TLSv1 protocol. A client will send out SSLv2 client hello messages and will indicate that it also understands SSLv3 and TLSv1. A server will understand SSLv2, SSLv3, and TLSv1 client hello messages. This is the best choice when compatibility is a concern.

The list of protocols available can later be limited using the SSL_OP_NO_SSLv2, SSL_OP_NO_SSLv3, SSL_OP_NO_TLSv1 options of the SSL_CTX_set_options() or SSL_set_options() functions. Using these options it is possible to choose e.g. SSLv23_server_method() and be able to negotiate with all possible clients, but to only allow newer protocols like SSLv3 or TLSv1.

SSL_CTX_new() initializes the list of ciphers, the session cache setting, the callbacks, the keys and certificates, and the options to its default values.

Return Values

The following return values can occur:

NULL
The creation of a new SSL_CTX object failed. Check the error stack to find out the reason.

Pointer to an SSL_CTX object
The return value points to an allocated SSL_CTX object.

See Also

SSL_CTX_free(),
SSL_accept(),
ssl(),
SSL_set_connect_state()

Feedback

For additional information or queries on this page send feedback


SSL_CTX_sess_cache_full - obtain session cache statistics

Name

SSL_CTX_sess_number, SSL_CTX_sess_connect
SSL_CTX_sess_connect_good, SSL_CTX_sess_connect_renegotiate
SSL_CTX_sess_accept, SSL_CTX_sess_accept_good
SSL_CTX_sess_accept_renegotiate, SSL_CTX_sess_hits
SSL_CTX_sess_cb_hits, SSL_CTX_sess_misses
SSL_CTX_sess_timeouts, SSL_CTX_sess_cache_full

obtain session cache statistics

Library

libssl.lib

Synopsis

#include <openssl/ssl.h>
long SSL_CTX_sess_number(SSL_CTX *ctx);
long SSL_CTX_sess_connect(SSL_CTX *ctx);
long SSL_CTX_sess_connect_good(SSL_CTX *ctx);
long SSL_CTX_sess_connect_renegotiate(SSL_CTX *ctx);
long SSL_CTX_sess_accept(SSL_CTX *ctx);
long SSL_CTX_sess_accept_good(SSL_CTX *ctx);
long SSL_CTX_sess_accept_renegotiate(SSL_CTX *ctx);
long SSL_CTX_sess_hits(SSL_CTX *ctx);
long SSL_CTX_sess_cb_hits(SSL_CTX *ctx);
long SSL_CTX_sess_misses(SSL_CTX *ctx);
long SSL_CTX_sess_timeouts(SSL_CTX *ctx);
long SSL_CTX_sess_cache_full(SSL_CTX *ctx);

Detailed Description

SSL_CTX_sess_number() returns the current number of sessions in the internal session cache.

SSL_CTX_sess_connect() returns the number of started SSL/TLS handshakes in client mode.

SSL_CTX_sess_connect_good() returns the number of successfully established SSL/TLS sessions in client mode.

SSL_CTX_sess_connect_renegotiate() returns the number of start renegotiations in client mode.

SSL_CTX_sess_accept() returns the number of started SSL/TLS handshakes in server mode.

SSL_CTX_sess_accept_good() returns the number of successfully established SSL/TLS sessions in server mode.

SSL_CTX_sess_accept_renegotiate() returns the number of start renegotiations in server mode.

SSL_CTX_sess_hits() returns the number of successfully reused sessions. In client mode a session set with SSL_set_session() successfully reused is counted as a hit. In server mode a session successfully retrieved from internal or external cache is counted as a hit.

SSL_CTX_sess_cb_hits() returns the number of successfully retrieved sessions from the external session cache in server mode.

SSL_CTX_sess_misses() returns the number of sessions proposed by clients that were not found in the internal session cache in server mode.

SSL_CTX_sess_timeouts() returns the number of sessions proposed by clients and either found in the internal or external session cache in server mode, but that were invalid due to timeout. These sessions are not included in the SSL_CTX_sess_hits() count.

SSL_CTX_sess_cache_full() returns the number of sessions that were removed because the maximum session cache size was exceeded.

Return Values

The functions return the values indicated in the Detailed Description section.

See Also

ssl(), SSL_set_session(),
SSL_CTX_set_session_cache_mode(),
SSL_CTX_sess_set_cache_size()

Feedback

For additional information or queries on this page send feedback


SSL_CTX_sess_get_cache_size - manipulate session cache size

Name

SSL_CTX_sess_set_cache_size, SSL_CTX_sess_get_cache_size — manipulates session cache size

Library

libssl.lib

Synopsis

#include <openssl/ssl.h>
long SSL_CTX_sess_set_cache_size(SSL_CTX *ctx, long t);
long SSL_CTX_sess_get_cache_size(SSL_CTX *ctx);

Detailed Description

SSL_CTX_sess_set_cache_size() sets the size of the internal session cache of context ctx to t.

SSL_CTX_sess_get_cache_size() returns the currently valid session cache size.

Notes

The internal session cache size is SSL_SESSION_CACHE_MAX_SIZE_DEFAULT, currently 1024*20, so that up to 20000 sessions can be held. This size can be modified using the SSL_CTX_sess_set_cache_size() call. A special case is the size 0, which is used for unlimited size.

When the maximum number of sessions is reached, no more new sessions are added to the cache. New space may be added by calling SSL_CTX_flush_sessions() to remove expired sessions.

If the size of the session cache is reduced and more sessions are already in the session cache, old session will be removed at the next time a session shall be added. This removal is not synchronized with the expiration of sessions.

Return Values

SSL_CTX_sess_set_cache_size() returns the previously valid size.

SSL_CTX_sess_get_cache_size() returns the currently valid size.

See Also

ssl(),
SSL_CTX_set_session_cache_mode(),
SSL_CTX_sess_number(),
SSL_CTX_flush_sessions()

Feedback

For additional information or queries on this page send feedback


SSL_CTX_sess_get_get_cb - provide callback functions for server side external session caching

Name

SSL_CTX_sess_set_new_cb, SSL_CTX_sess_set_remove_cb
SSL_CTX_sess_set_get_cb, SSL_CTX_sess_get_new_cb
SSL_CTX_sess_get_remove_cb, SSL_CTX_sess_get_get_cb

provides callback functions for server side external session caching

Library

libssl.lib

Synopsis

#include <openssl/ssl.h>
void SSL_CTX_sess_set_new_cb(SSL_CTX *ctx, int (*new_session_cb)(SSL *, SSL_SESSION *));
void SSL_CTX_sess_set_remove_cb(SSL_CTX *ctx, void (*remove_session_cb)(SSL_CTX *ctx, SSL_SESSION *));
void SSL_CTX_sess_set_get_cb(SSL_CTX *ctx, SSL_SESSION (*get_session_cb)(SSL *, unsigned char *, int, int *));
int (*SSL_CTX_sess_get_new_cb(SSL_CTX *ctx))(struct ssl_st *ssl, SSL_SESSION *sess);
void (*SSL_CTX_sess_get_remove_cb(SSL_CTX *ctx))(struct ssl_ctx_st *ctx, SSL_SESSION *sess);
SSL_SESSION *(*SSL_CTX_sess_get_get_cb(SSL_CTX *ctx))(struct ssl_st *ssl, unsigned char *data, int len, int *copy);
int (*new_session_cb)(struct ssl_st *ssl, SSL_SESSION *sess);
void (*remove_session_cb)(struct ssl_ctx_st *ctx, SSL_SESSION *sess);
SSL_SESSION *(*get_session_cb)(struct ssl_st *ssl, unsigned char *data, int len, int *copy);

Detailed Description

SSL_CTX_sess_set_new_cb() sets the callback function, which is automatically called whenever a new session was negotiated.

SSL_CTX_sess_set_remove_cb() sets the callback function, which is automatically called whenever a session is removed by the SSL engine, because it is considered faulty or the session has become obsolete because of exceeding the timeout value.

SSL_CTX_sess_set_get_cb() sets the callback function which is called, whenever a SSL/TLS client proposed to resume a session but the session could not be found in the internal session cache (see SSL_CTX_set_session_cache_mode()). (SSL/TLS server only.)

SSL_CTX_sess_get_new_cb(), SSL_CTX_sess_get_remove_cb(), and SSL_CTX_sess_get_get_cb() allow to retrieve the function pointers of the provided callback functions. If a callback function has not been set, the NULL pointer is returned.

Notes

In order to allow external session caching, synchronization with the internal session cache is realized via callback functions. Inside these callback functions, session can be saved to disk or put into a database using the d2i_SSL_SESSION() interface.

The new_session_cb() is called, whenever a new session has been negotiated and session caching is enabled (see SSL_CTX_set_session_cache_mode()). The new_session_cb() is passed the ssl connection and the ssl session sess. If the callback returns 0, the session will be immediately removed again.

The remove_session_cb() is called, whenever the SSL engine removes a session from the internal cache. This happens when the session is removed because it is expired or when a connection was not shutdown cleanly. It also happens for all sessions in the internal session cache when SSL_CTX_free() is called. The remove_session_cb() is passed the ctx and the ssl session sess. It does not provide any feedback.

The get_session_cb() is only called on SSL/TLS servers with the session id proposed by the client. The get_session_cb() is always called, also when session caching was disabled. The get_session_cb() is passed the ssl connection, the session id of length length at the memory location data. With the parameter copy the callback can require the SSL engine to increment the reference count of the SSL_SESSION object, Normally the reference count is not incremented and therefore the session must not be explicitly freed with SSL_SESSION_free().

See Also

ssl(),
d2i_SSL_SESSION(),
SSL_CTX_set_session_cache_mode(),
SSL_CTX_flush_sessions(),
SSL_SESSION_free(),
SSL_CTX_free()

Feedback

For additional information or queries on this page send feedback


SSL_CTX_sessions - access internal session cache

Name

SSL_CTX_sessions — access internal session cache

Library

libssl.lib

Synopsis

#include <openssl/ssl.h>
struct lhash_st *SSL_CTX_sessions(SSL_CTX *ctx);

Detailed Description

SSL_CTX_sessions() returns a pointer to the lhash databases containing the internal session cache for ctx.

Notes

The sessions in the internal session cache are kept in an lhash() type database. It is possible to directly access this database e.g. for searching. In parallel, the sessions form a linked list which is maintained separately from the lhash() operations, so that the database must not be modified directly but by using the SSL_CTX_add_session() family of functions.

See Also

ssl(),
lhash(),
SSL_CTX_add_session(),
SSL_CTX_set_session_cache_mode()

Feedback

For additional information or queries on this page send feedback


SSL_CTX_get_cert_store - manipulate X509 certificate verification storage

Name

SSL_CTX_set_cert_store, SSL_CTX_get_cert_store — manipulates X509 certificate verification storage

Library

libssl.lib

Synopsis

#include <openssl/ssl.h>
void SSL_CTX_set_cert_store(SSL_CTX *ctx, X509_STORE *store);
X509_STORE *SSL_CTX_get_cert_store(const SSL_CTX *ctx);

Detailed Description

SSL_CTX_set_cert_store() sets/replaces the certificate verification storage of ctx to/with store. If another X509_STORE object is currently set in ctx, it will be X509_STORE_free()ed.

SSL_CTX_get_cert_store() returns a pointer to the current certificate verification storage.

Notes

In order to verify the certificates presented by the peer, trusted CA certificates must be accessed. These CA certificates are made available via lookup methods, handled inside the X509_STORE. From the X509_STORE the X509_STORE_CTX used when verifying certificates is created.

Typically the trusted certificate store is handled indirectly via using SSL_CTX_load_verify_locations(). Using the SSL_CTX_set_cert_store() and SSL_CTX_get_cert_store() functions it is possible to manipulate the X509_STORE object beyond the SSL_CTX_load_verify_locations() call.

Currently no detailed documentation on how to use the X509_STORE object is available. Not all members of the X509_STORE are used when the verification takes place. So will e.g. the verify_callback() be overridden with the verify_callback() set via the SSL_CTX_set_verify() family of functions. This document must therefore be updated when documentation about the X509_STORE object and its handling becomes available.

Return Values

SSL_CTX_set_cert_store() does not return diagnostic output.

SSL_CTX_get_cert_store() returns the current setting.

See Also

ssl(),
SSL_CTX_load_verify_locations(),
SSL_CTX_set_verify()

Feedback

For additional information or queries on this page send feedback


SSL_CTX_set_cert_verify_callback - set peer certificate verification procedure

Name

SSL_CTX_set_cert_verify_callback — set peer certificate verification procedure

Library

libssl.lib

Synopsis

#include <openssl/ssl.h>
void SSL_CTX_set_cert_verify_callback(SSL_CTX *ctx, int (*callback)(X509_STORE_CTX *,void *), void *arg);

Detailed Description

SSL_CTX_set_cert_verify_callback() sets the verification callback function for ctx. SSL objects that are created from ctx inherit the setting valid at the time when SSL_new() is called.

Notes

Whenever a certificate is verified during a SSL/TLS handshake, a verification function is called. If the application does not explicitly specify a verification callback function, the built-in verification function is used. If a verification callback callback is specified via SSL_CTX_set_cert_verify_callback(), the supplied callback function is called instead. By setting callback to NULL, the default behaviour is restored.

When the verification must be performed, callback will be called with the arguments callback(X509_STORE_CTX *x509_store_ctx, void *arg). The argument arg is specified by the application when setting callback.

callback should return 1 to indicate verification success and 0 to indicate verification failure. If SSL_VERIFY_PEER is set and callback returns 0, the handshake will fail. As the verification procedure may allow to continue the connection in case of failure (by always returning 1) the verification result must be set in any case using the error member of x509_store_ctx so that the calling application will be informed about the detailed result of the verification procedure!

Within x509_store_ctx, callback has access to the verify_callback function set using SSL_CTX_set_verify().

Warnings

Do not mix the verification callback described in this function with the verify_callback function called during the verification process. The latter is set using the SSL_CTX_set_verify() family of functions.

Providing a complete verification procedure including certificate purpose settings etc is a complex task. The built-in procedure is quite powerful and in most cases it should be sufficient to modify its behaviour using the verify_callback function.

Bugs

Return Values

SSL_CTX_set_cert_verify_callback() does not provide diagnostic information.

See Also

ssl(),
SSL_CTX_set_verify(),
SSL_get_verify_result(),
SSL_CTX_load_verify_locations()

History

Previous to OpenSSL 0.9.7, the arg argument to SSL_CTX_set_cert_verify_callback was ignored, and callback was called simply as int (*callback)(X509_STORE_CTX *) To compile software written for previous versions of OpenSSL, a dummy argument will have to be added to callback.

Feedback

For additional information or queries on this page send feedback


SSL_set_cipher_list - choose list of available SSL_CIPHERs

Name

SSL_CTX_set_cipher_list, SSL_set_cipher_list — chooses list of available SSL_CIPHERs

Library

libssl.lib

Synopsis

#include <openssl/ssl.h>
int SSL_CTX_set_cipher_list(SSL_CTX *ctx, const char *str);
int SSL_set_cipher_list(SSL *ssl, const char *str);

Detailed Description

SSL_CTX_set_cipher_list() sets the list of available ciphers for ctx using the control string str. The format of the string is described in ciphers(1). The list of ciphers is inherited by all ssl objects created from ctx.

SSL_set_cipher_list() sets the list of ciphers only for ssl.

Notes

The control string str should be universally usable and not depend on details of the library configuration (ciphers compiled in). Thus no syntax checking takes place. Items that are not recognized, because the corresponding ciphers are not compiled in or because they are mistyped, are simply ignored. Failure is only flagged if no ciphers could be collected at all.

It should be noted, that inclusion of a cipher to be used into the list is a necessary condition. On the client side, the inclusion into the list is also sufficient. On the server side, additional restrictions apply. All ciphers have additional requirements. ADH ciphers don't need a certificate, but DH-parameters must have been set. All other ciphers need a corresponding certificate and key.

A RSA cipher can only be chosen, when a RSA certificate is available. RSA export ciphers with a key length of 512 bits for the RSA key require a temporary 512 bit RSA key, as typically the supplied key has a length of 1024 bit (see SSL_CTX_set_tmp_rsa_callback()). RSA ciphers using EDH need a certificate and key and additional DH-parameters (see SSL_CTX_set_tmp_dh_callback()).

A DSA cipher can only be chosen, when a DSA certificate is available. DSA ciphers always use DH key exchange and therefore need DH-parameters (see SSL_CTX_set_tmp_dh_callback()).

When these conditions are not met for any cipher in the list (e.g. a client only supports export RSA ciphers with a asymmetric key length of 512 bits and the server is not configured to use temporary RSA keys), the ``no shared cipher'' (SSL_R_NO_SHARED_CIPHER) error is generated and the handshake will fail.

Return Values

SSL_CTX_set_cipher_list() and SSL_set_cipher_list() return 1 if any cipher could be selected and 0 on complete failure.

See Also

ssl(),
SSL_get_ciphers(),
SSL_CTX_use_certificate(),
SSL_CTX_set_tmp_rsa_callback(),
SSL_CTX_set_tmp_dh_callback(),
ciphers()

Feedback

For additional information or queries on this page send feedback


SSL_add_client_CA - set list of CAs sent to the client when requesting a client certificate

Name

SSL_CTX_set_client_CA_list, SSL_set_client_CA_list
SSL_CTX_add_client_CA, SSL_add_client_CA

sets list of CAs sent to the client when requesting a client certificate

Library

libssl.lib

Synopsis

#include <openssl/ssl.h>

void SSL_CTX_set_client_CA_list(SSL_CTX *ctx, STACK_OF(X509_NAME) *list);
void SSL_set_client_CA_list(SSL *s, STACK_OF(X509_NAME) *list);
int SSL_CTX_add_client_CA(SSL_CTX *ctx, X509 *cacert);
int SSL_add_client_CA(SSL *ssl, X509 *cacert);

Detailed Description

SSL_CTX_set_client_CA_list() sets the list of CAs sent to the client when requesting a client certificate for ctx.

SSL_set_client_CA_list() sets the list of CAs sent to the client when requesting a client certificate for the chosen ssl, overriding the setting valid for ssl's SSL_CTX object.

SSL_CTX_add_client_CA() adds the CA name extracted from cacert to the list of CAs sent to the client when requesting a client certificate for ctx.

SSL_add_client_CA() adds the CA name extracted from cacert to the list of CAs sent to the client when requesting a client certificate for the chosen ssl, overriding the setting valid for ssl's SSL_CTX object.

Notes

When a TLS/SSL server requests a client certificate (see SSL_CTX_set_verify_options()), it sends a list of CAs, for which it will accept certificates, to the client.

This list must explicitly be set using SSL_CTX_set_client_CA_list() for ctx and SSL_set_client_CA_list() for the specific ssl. The list specified overrides the previous setting. The CAs listed do not become trusted (list only contains the names, not the complete certificates); use SSL_CTX_load_verify_locations() to additionally load them for verification.

If the list of acceptable CAs is compiled in a file, the SSL_load_client_CA_file() function can be used to help importing the necessary data.

SSL_CTX_add_client_CA() and SSL_add_client_CA() can be used to add additional items the list of client CAs. If no list was specified before using SSL_CTX_set_client_CA_list() or SSL_set_client_CA_list(), a new client CA list for ctx or ssl (as appropriate) is opened.

These functions are only useful for TLS/SSL servers.

Return Values

SSL_CTX_set_client_CA_list() and SSL_set_client_CA_list() do not return diagnostic information.

SSL_CTX_add_client_CA() and SSL_add_client_CA() have the following return values:

    2. The operation succeeded.

  2. A failure while manipulating the STACK_OF(X509_NAME) object occurred or the X509_NAME could not be extracted from cacert. Check the error stack to find out the reason.

Examples

Scan all certificates in CAfile and list them as acceptable CAs:

  SSL_CTX_set_client_CA_list(ctx,SSL_load_client_CA_file(CAfile));

See Also

ssl(),
SSL_get_client_CA_list(),
SSL_load_client_CA_file(),
SSL_CTX_load_verify_locations()

Feedback

For additional information or queries on this page send feedback


SSL_CTX_get_client_cert_cb - handle client certificate callback function

Name

SSL_CTX_set_client_cert_cb, SSL_CTX_get_client_cert_cb — handles client certificate callback function

Library

libssl.lib

Synopsis

#include <openssl/ssl.h>
void SSL_CTX_set_client_cert_cb(SSL_CTX *ctx, int (*client_cert_cb)(SSL *ssl, X509 **x509, EVP_PKEY **pkey));
int (*SSL_CTX_get_client_cert_cb(SSL_CTX *ctx))(SSL *ssl, X509 **x509, EVP_PKEY **pkey);
int (*client_cert_cb)(SSL *ssl, X509 **x509, EVP_PKEY **pkey);

Detailed Description

SSL_CTX_set_client_cert_cb() sets the client_cert_cb() callback, that is called when a client certificate is requested by a server and no certificate was yet set for the SSL object.

When client_cert_cb() is NULL, no callback function is used.

SSL_CTX_get_client_cert_cb() returns a pointer to the currently set callback function.

client_cert_cb() is the application defined callback. If it wants to set a certificate, a certificate/private key combination must be set using the x509 and pkey arguments and ``1'' must be returned. The certificate will be installed into ssl, see the NOTES and BUGS sections. If no certificate should be set, ``0'' has to be returned and no certificate will be sent. A negative return value will suspend the handshake and the handshake function will return immediately. SSL_get_error() will return SSL_ERROR_WANT_X509_LOOKUP to indicate, that the handshake was suspended. The next call to the handshake function will again lead to the call of client_cert_cb(). It is the job of the client_cert_cb() to store information about the state of the last call, if required to continue.

Notes

During a handshake (or renegotiation) a server may request a certificate from the client. A client certificate must only be sent, when the server did send the request.

When a certificate was set using the SSL_CTX_use_certificate() family of functions, it will be sent to the server. The TLS standard requires that only a certificate is sent, if it matches the list of acceptable CAs sent by the server. This constraint is violated by the default behavior of the OpenSSL library. Using the callback function it is possible to implement a proper selection routine or to allow a user interaction to choose the certificate to be sent.

If a callback function is defined and no certificate was yet defined for the SSL object, the callback function will be called. If the callback function returns a certificate, the OpenSSL library will try to load the private key and certificate data into the SSL object using the SSL_use_certificate() and SSL_use_private_key() functions. Thus it will permanently install the certificate and key for this SSL object. It will not be reset by calling SSL_clear(). If the callback returns no certificate, the OpenSSL library will not send a certificate.

Bugs

The client_cert_cb() cannot return a complete certificate chain, it can only return one client certificate. If the chain only has a length of 2, the root CA certificate may be omitted according to the TLS standard and thus a standard conforming answer can be sent to the server. For a longer chain, the client must send the complete chain (with the option to leave out the root CA certificate). This can only be accomplished by either adding the intermediate CA certificates into the trusted certificate store for the SSL_CTX object (resulting in having to add CA certificates that otherwise maybe would not be trusted), or by adding the chain certificates using the SSL_CTX_add_extra_chain_cert() function, which is only available for the SSL_CTX object as a whole and that therefore probably can only apply for one client certificate, making the concept of the callback function (to allow the choice from several certificates) questionable.

Once the SSL object has been used in conjunction with the callback function, the certificate will be set for the SSL object and will not be cleared even when SSL_clear() is being called. It is therefore mandatory to destroy the SSL object using SSL_free() and create a new one to return to the previous state.

See Also

ssl(),
SSL_CTX_use_certificate(),
SSL_CTX_add_extra_chain_cert(),
SSL_get_client_CA_list(),

SSL_clear(), SSL_free()

Feedback

For additional information or queries on this page send feedback


SSL_CTX_set_default_passwd_cb_userdata - set passwd callback for encrypted PEM file handling

Name

SSL_CTX_set_default_passwd_cb, SSL_CTX_set_default_passwd_cb_userdata — sets passwd callback for encrypted PEM file handling

Library

libssl.lib

Synopsis

#include <openssl/ssl.h>
void SSL_CTX_set_default_passwd_cb(SSL_CTX *ctx, pem_password_cb *cb);
void SSL_CTX_set_default_passwd_cb_userdata(SSL_CTX *ctx, void *u);
int pem_passwd_cb(char *buf, int size, int rwflag, void *userdata);

Detailed Description

SSL_CTX_set_default_passwd_cb() sets the default password callback called when loading/storing a PEM certificate with encryption.

SSL_CTX_set_default_passwd_cb_userdata() sets a pointer to userdata which will be provided to the password callback on invocation.

The pem_passwd_cb(), which must be provided by the application, hands back the password to be used during decryption. On invocation a pointer to userdata is provided. The pem_passwd_cb must write the password into the provided buffer buf which is of size size. The actual length of the password must be returned to the calling function. rwflag indicates whether the callback is used for reading/decryption (rwflag=0) or writing/encryption (rwflag=1).

Examples

The following example returns the password provided as userdata to the calling function. The password is considered to be a '\0' terminated string. If the password does not fit into the buffer, the password is truncated.
 int pem_passwd_cb(char *buf, int size, int rwflag, void *password)
 {
  strncpy(buf, (char *)(password), size);
  buf[size - 1] = '\0';
  return(strlen(buf));
 }

Notes

When loading or storing private keys, a password might be supplied to protect the private key. The way this password can be supplied may depend on the application. If only one private key is handled, it can be practical to have pem_passwd_cb() handle the password dialog interactively. If several keys have to be handled, it can be practical to ask for the password once, then keep it in memory and use it several times. In the last case, the password could be stored into the userdata storage and the pem_passwd_cb() only returns the password already stored.

When asking for the password interactively, pem_passwd_cb() can use rwflag to check, whether an item shall be encrypted (rwflag=1). In this case the password dialog may ask for the same password twice for comparison in order to catch typos, that would make decryption impossible.

Other items in PEM formatting (certificates) can also be encrypted, it is however not usual, as certificate information is considered public.

Return Values

SSL_CTX_set_default_passwd_cb() and SSL_CTX_set_default_passwd_cb_userdata() do not provide diagnostic information.

See Also

ssl(), SSL_CTX_use_certificate()

Feedback

For additional information or queries on this page send feedback


SSL_has_matching_session_id - manipulate generation of SSL session IDs

Name

SSL_CTX_set_generate_session_id, SSL_set_generate_session_id
SSL_has_matching_session_id

manipulate generation of SSL session IDs (server only)

Library

libssl.lib

Synopsis

#include <openssl/ssl.h>
typedef int (*GEN_SESSION_CB)(const SSL *ssl, unsigned char *id, unsigned int *id_len);
int SSL_CTX_set_generate_session_id(SSL_CTX *ctx, GEN_SESSION_CB cb);
int SSL_set_generate_session_id(SSL *ssl, GEN_SESSION_CB, cb);
int SSL_has_matching_session_id(const SSL *ssl, const unsigned char *id, unsigned int id_len);

Detailed Description

SSL_CTX_set_generate_session_id() sets the callback function for generating new session ids for SSL/TLS sessions for ctx to be cb.

SSL_set_generate_session_id() sets the callback function for generating new session ids for SSL/TLS sessions for ssl to be cb.

SSL_has_matching_session_id() checks, whether a session with id id (of length id_len) is already contained in the internal session cache of the parent context of ssl.

Notes

When a new session is established between client and server, the server generates a session id. The session id is an arbitrary sequence of bytes. The length of the session id is 16 bytes for SSLv2 sessions and between 1 and 32 bytes for SSLv3/TLSv1. The session id is not security critical but must be unique for the server. Additionally, the session id is transmitted in the clear when reusing the session so it must not contain sensitive information.

Without a callback being set, an OpenSSL server will generate a unique session id from pseudo random numbers of the maximum possible length. Using the callback function, the session id can be changed to contain additional information like e.g. a host id in order to improve load balancing or external caching techniques.

The callback function receives a pointer to the memory location to put id into and a pointer to the maximum allowed length id_len. The buffer at location id is only guaranteed to have the size id_len. The callback is only allowed to generate a shorter id and reduce id_len; the callback must never increase id_len or write to the location id exceeding the given limit.

If a SSLv2 session id is generated and id_len is reduced, it will be restored after the callback has finished and the session id will be padded with 0x00. It is not recommended to change the id_len for SSLv2 sessions. The callback can use the SSL_get_version() function to check, whether the session is of type SSLv2.

The location id is filled with 0x00 before the callback is called, so the callback may only fill part of the possible length and leave id_len untouched while maintaining reproducibility.

Since the sessions must be distinguished, session ids must be unique. Without the callback a random number is used, so that the probability of generating the same session id is extremely small (2^128 possible ids for an SSLv2 session, 2^256 for SSLv3/TLSv1). In order to assure the uniqueness of the generated session id, the callback must call SSL_has_matching_session_id() and generate another id if a conflict occurs. If an id conflict is not resolved, the handshake will fail. If the application codes e.g. a unique host id, a unique process number, and a unique sequence number into the session id, uniqueness could easily be achieved without randomness added (it should however be taken care that no confidential information is leaked this way). If the application can not guarantee uniqueness, it is recommended to use the maximum id_len and fill in the bytes not used to code special information with random data to avoid collisions.

SSL_has_matching_session_id() will only query the internal session cache, not the external one. Since the session id is generated before the handshake is completed, it is not immediately added to the cache. If another thread is using the same internal session cache, a race condition can occur in that another thread generates the same session id. Collisions can also occur when using an external session cache, since the external cache is not tested with SSL_has_matching_session_id() and the same race condition applies.

When calling SSL_has_matching_session_id() for an SSLv2 session with reduced id_len, the match operation will be performed using the fixed length required and with a 0x00 padded id.

The callback must return 0 if it cannot generate a session id for whatever reason and return 1 on success.

Examples

The callback function listed will generate a session id with the server id given, and will fill the rest with pseudo random bytes:
 const char session_id_prefix = "www-18";
 #define MAX_SESSION_ID_ATTEMPTS 10
 static int generate_session_id(const SSL *ssl, unsigned char *id, unsigned int *id_len)
      {
      unsigned int count = 0;
      const char *version;
      version = SSL_get_version(ssl);
      if (!strcmp(version, "SSLv2"))
          /* we must not change id_len */;
      do      {
              RAND_pseudo_bytes(id, *id_len);
              /* Prefix the session_id with the required prefix. NB: If our
               * prefix is too long, clip it - but there will be worse effects
               * anyway, eg. the server could only possibly create 1 session
               * ID (i.e.. the prefix!) so all future session negotiations will
               * fail due to conflicts. */
              memcpy(id, session_id_prefix,
                      (strlen(session_id_prefix) < *id_len) ?
                      strlen(session_id_prefix) : *id_len);
              }
      while(SSL_has_matching_session_id(ssl, id, *id_len) &&
              (++count < MAX_SESSION_ID_ATTEMPTS));
      if(count >= MAX_SESSION_ID_ATTEMPTS)
              return 0;
      return 1;
      }

Return Values

SSL_CTX_set_generate_session_id() and SSL_set_generate_session_id() always return 1.

SSL_has_matching_session_id() returns 1 if another session with the same id is already in the cache.

See Also

ssl(), SSL_get_version()

History

SSL_CTX_set_generate_session_id(),
 SSL_set_generate_session_id()
and  SSL_has_matching_session_id() have been introduced in
OpenSSL 0.9.7.

Feedback

For additional information or queries on this page send feedback


SSL_get_info_callback - handle information callback for SSL connections

Name

SSL_CTX_set_info_callback, SSL_CTX_get_info_callback
SSL_set_info_callback, SSL_get_info_callback

handles information callback for SSL connections

Library

libssl.lib

Synopsis

#include <openssl/ssl.h>
void SSL_CTX_set_info_callback(SSL_CTX *ctx, void (*callback)());
void (*SSL_CTX_get_info_callback(const SSL_CTX *ctx))();
void SSL_set_info_callback(SSL *ssl, void (*callback)());
void (*SSL_get_info_callback(const SSL *ssl))();

Detailed Description

SSL_CTX_set_info_callback() sets the callback function, that can be used to obtain state information for SSL objects created from ctx during connection setup and use. The setting for ctx is overridden from the setting for a specific SSL object, if specified. When callback is NULL, not callback function is used.

SSL_set_info_callback() sets the callback function, that can be used to obtain state information for ssl during connection setup and use. When callback is NULL, the callback setting currently valid for ctx is used.

SSL_CTX_get_info_callback() returns a pointer to the currently set information callback function for ctx.

SSL_get_info_callback() returns a pointer to the currently set information callback function for ssl.

Examples

The following example callback function prints state strings, information about alerts being handled and error messages to the bio_err BIO.
void apps_ssl_info_callback(SSL *s, int where, int ret)
        {
        const char *str;
        int w;
        w=where& ~SSL_ST_MASK;
        if (w & SSL_ST_CONNECT) str="SSL_connect";
        else if (w & SSL_ST_ACCEPT) str="SSL_accept";
        else str="undefined";
        if (where & SSL_CB_LOOP)
                {
                BIO_printf(bio_err,"%s:%s\n",str,SSL_state_string_long(s));
                }
        else if (where & SSL_CB_ALERT)
                {
                str=(where & SSL_CB_READ)?"read":"write";
                BIO_printf(bio_err,"SSL3 alert %s:%s:%s\n", str, SSL_alert_type_string_long(ret), SSL_alert_desc_string_long(ret));
                }
        else if (where & SSL_CB_EXIT)
                {
                if (ret == 0)
                        BIO_printf(bio_err,"%s:failed in %s\n", str,SSL_state_string_long(s));
                else if (ret < 0)
                        {
                        BIO_printf(bio_err,"%s:error in %s\n", str,SSL_state_string_long(s));
                        }
                }
        }

Notes

When setting up a connection and during use, it is possible to obtain state information from the SSL/TLS engine. When set, an information callback function is called whenever the state changes, an alert appears, or an error occurs.

The callback function is called as callback (SSL *ssl, int where, int ret). The where argument specifies information about where (in which context) the callback function was called. If ret is 0, an error condition occurred. If an alert is handled, SSL_CB_ALERT is set and ret specifies the alert information.

where is a bitmask made up of the following bits:

SSL_CB_LOOP
Callback has been called to indicate state change inside a loop.

SSL_CB_EXIT
Callback has been called to indicate error exit of a handshake function. (May be soft error with retry option for non-blocking setups.)

SSL_CB_READ
Callback has been called during read operation.

SSL_CB_WRITE
Callback has been called during write operation.

SSL_CB_ALERT
Callback has been called due to an alert being sent or received.

SSL_CB_READ_ALERT (SSL_CB_ALERT|SSL_CB_READ)
SSL_CB_WRITE_ALERT (SSL_CB_ALERT|SSL_CB_WRITE)
SSL_CB_ACCEPT_LOOP (SSL_ST_ACCEPT|SSL_CB_LOOP)
SSL_CB_ACCEPT_EXIT (SSL_ST_ACCEPT|SSL_CB_EXIT)
SSL_CB_CONNECT_LOOP (SSL_ST_CONNECT|SSL_CB_LOOP)
SSL_CB_CONNECT_EXIT (SSL_ST_CONNECT|SSL_CB_EXIT)
SSL_CB_HANDSHAKE_START
Callback has been called because a new handshake is started.

SSL_CB_HANDSHAKE_DONE 0x20
Callback has been called because a handshake is finished.

The current state information can be obtained using the SSL_state_string() family of functions.
The ret information can be evaluated using the SSL_alert_type_string() family of functions.

Return Values

SSL_set_info_callback() does not provide diagnostic information.

SSL_get_info_callback() returns the current setting.

See Also

ssl(),
SSL_state_string(),
SSL_alert_type_string()

Feedback

For additional information or queries on this page send feedback


SSL_get_max_cert_list, - manipulate allowed for the peer's certificate chain

Name

SSL_CTX_set_max_cert_list, SSL_CTX_get_max_cert_list
SSL_set_max_cert_list, SSL_get_max_cert_list

manipulate allowed for the peer's certificate chain

Library

libssl.lib

Synopsis

#include <openssl/ssl.h>
long SSL_CTX_set_max_cert_list(SSL_CTX *ctx, long size);
long SSL_CTX_get_max_cert_list(SSL_CTX *ctx);
long SSL_set_max_cert_list(SSL *ssl, long size);
long SSL_get_max_cert_list(SSL *ctx);

Detailed Description

SSL_CTX_set_max_cert_list() sets the maximum size allowed for the peer's certificate chain for all SSL objects created from ctx to be <size> bytes. The SSL objects inherit the setting valid for ctx at the time SSL_new() is being called.

SSL_CTX_get_max_cert_list() returns the currently set maximum size for ctx.

SSL_set_max_cert_list() sets the maximum size allowed for the peer's certificate chain for ssl to be <size> bytes. This setting stays valid until a new value is set.

SSL_get_max_cert_list() returns the currently set maximum size for ssl.

Notes

During the handshake process, the peer may send a certificate chain. The TLS/SSL standard does not give any maximum size of the certificate chain. The OpenSSL library handles incoming data by a dynamically allocated buffer. In order to prevent this buffer from growing without bounds due to data received from a faulty or malicious peer, a maximum size for the certificate chain is set.

The default value for the maximum certificate chain size is 100kB (30kB on the 16bit DOS platform). This should be sufficient for usual certificate chains (OpenSSL's default maximum chain length is 10, see SSL_CTX_set_verify(), and certificates without special extensions have a typical size of 1-2kB).

For special applications it can be necessary to extend the maximum certificate chain size allowed to be sent by the peer, see e.g. the work on ``Internet X.509 Public Key Infrastructure Proxy Certificate Profile'' and ``TLS Delegation Protocol'' at http://www.ietf.org/ and http://www.globus.org/ .

Under normal conditions it should never be necessary to set a value smaller than the default, as the buffer is handled dynamically and only uses the memory actually required by the data sent by the peer.

If the maximum certificate chain size allowed is exceeded, the handshake will fail with a SSL_R_EXCESSIVE_MESSAGE_SIZE error.

Return Values

SSL_CTX_set_max_cert_list() and SSL_set_max_cert_list() return the previously set value.

SSL_CTX_get_max_cert_list() and SSL_get_max_cert_list() return the currently set value.

See Also

ssl(),
SSL_new(),
SSL_CTX_set_verify()

History

SSL*_set/get_max_cert_list() have been introduced in OpenSSL 0.9.7.

Feedback

For additional information or queries on this page send feedback


SSL_get_mode - manipulate SSL engine mode

Name

SSL_CTX_set_mode, SSL_set_mode
SSL_CTX_get_mode, SSL_get_mode

manipulate SSL engine mode

Library

libssl.lib

Synopsis

#include <openssl/ssl.h>
long SSL_CTX_set_mode(SSL_CTX *ctx, long mode);
long SSL_set_mode(SSL *ssl, long mode);
long SSL_CTX_get_mode(SSL_CTX *ctx);
long SSL_get_mode(SSL *ssl);

Detailed Description

SSL_CTX_set_mode() adds the mode set via bitmask in mode to ctx. Options already set before are not cleared.

SSL_set_mode() adds the mode set via bitmask in mode to ssl. Options already set before are not cleared.

SSL_CTX_get_mode() returns the mode set for ctx.

SSL_get_mode() returns the mode set for ssl.

Notes

The following mode changes are available:

SSL_MODE_ENABLE_PARTIAL_WRITE
Allow SSL_write(..., n) to return r with 0 < r < n (i.e. report success when just a single record has been written). When not set (the default), SSL_write() will only report success once the complete chunk was written. Once SSL_write() returns with r, r bytes have been successfully written and the next call to SSL_write() must only send the n-r bytes left, imitating the behaviour of write().

SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER
Make it possible to retry SSL_write() with changed buffer location (the buffer contents must stay the same). This is not the default to avoid the misconception that non-blocking SSL_write() behaves like non-blocking write().

SSL_MODE_AUTO_RETRY
Never bother the application with retries if the transport is blocking. If a renegotiation take place during normal operation, a SSL_read() or SSL_write() would return with -1 and indicate the need to retry with SSL_ERROR_WANT_READ. In a non-blocking environment applications must be prepared to handle incomplete read/write operations. In a blocking environment, applications are not always prepared to deal with read/write operations returning without success report. The flag SSL_MODE_AUTO_RETRY will cause read/write operations to only return after the handshake and successful completion.

Return Values

SSL_CTX_set_mode() and SSL_set_mode() return the new mode bitmask after adding mode.

SSL_CTX_get_mode() and SSL_get_mode() return the current bitmask.

See Also

ssl(),
SSL_read(),
SSL_write()

History

SSL_MODE_AUTO_RETRY as been added in OpenSSL 0.9.6.

Feedback

For additional information or queries on this page send feedback


SSL_get_msg_callback_arg - install callback for observing protocol messages

Name

SSL_CTX_set_msg_callback, SSL_CTX_set_msg_callback_arg
SSL_set_msg_callback, SSL_get_msg_callback_arg

install callback for observing protocol

Library

libssl.lib

Synopsis

#include <openssl/ssl.h>
void SSL_CTX_set_msg_callback(SSL_CTX *ctx, void (*cb)(int write_p, int version, int content_type, const void *buf, size_t len,
                              SSL *ssl, void *arg));
void SSL_CTX_set_msg_callback_arg(SSL_CTX *ctx, void *arg);
void SSL_set_msg_callback(SSL_CTX *ctx, void (*cb)(int write_p, int version, int content_type, const void *buf, size_t len,
                          SSL *ssl, void *arg));
void SSL_set_msg_callback_arg(SSL_CTX *ctx, void *arg);

Detailed Description

SSL_CTX_set_msg_callback() or SSL_set_msg_callback() can be used to define a message callback function cb for observing all SSL/TLS protocol messages (such as handshake messages) that are received or sent. SSL_CTX_set_msg_callback_arg() and SSL_set_msg_callback_arg() can be used to set argument arg to the callback function, which is available for arbitrary application use.

SSL_CTX_set_msg_callback() and SSL_CTX_set_msg_callback_arg() specify default settings that will be copied to new SSL objects by SSL_new(). SSL_set_msg_callback() and SSL_set_msg_callback_arg() modify the actual settings of an SSL object. Using a 0 pointer for cb disables the message callback.

When cb is called by the SSL/TLS library for a protocol message, the function arguments have the following meaning:

write_p
This flag is 0 when a protocol message has been received and 1 when a protocol message has been sent.

version
The protocol version according to which the protocol message is interpreted by the library. Currently, this is one of SSL2_VERSION, SSL3_VERSION and TLS1_VERSION (for SSL 2.0, SSL 3.0 and TLS 1.0, respectively).

content_type
In the case of SSL 2.0, this is always 0. In the case of SSL 3.0 or TLS 1.0, this is one of the ContentType values defined in the protocol specification (change_cipher_spec(20), alert(21), handshake(22); but never application_data(23) because the callback will only be called for protocol messages).

buf, len
buf points to a buffer containing the protocol message, which consists of len bytes. The buffer is no longer valid after the callback function has returned.

ssl
The SSL object that received or sent the message.

arg
The user-defined argument optionally defined by SSL_CTX_set_msg_callback_arg() or SSL_set_msg_callback_arg().

Notes

Protocol messages are passed to the callback function after decryption and fragment collection where applicable. (Thus record boundaries are not visible.)

If processing a received protocol message results in an error, the callback function may not be called. For example, the callback function will never see messages that are considered too large to be processed.

Due to automatic protocol version negotiation, version is not necessarily the protocol version used by the sender of the message: If a TLS 1.0 ClientHello message is received by an SSL 3.0-only server, version will be SSL3_VERSION.

See Also

ssl(), SSL_new()

History

SSL_CTX_set_msg_callback(), SSL_CTX_set_msg_callback_arg(),
SSL_set_msg_callback()
and SSL_get_msg_callback_arg()
were added in OpenSSL 0.9.7.

Feedback

For additional information or queries on this page send feedback


SSL_get_options - manipulate SSL engine options

Name

SSL_CTX_set_options, SSL_set_options
SSL_CTX_get_options, SSL_get_options

manipulate SSL engine options

Library

libssl.lib

Synopsis

#include <openssl/ssl.h>
long SSL_CTX_set_options(SSL_CTX *ctx, long options);
long SSL_set_options(SSL *ssl, long options);
long SSL_CTX_get_options(SSL_CTX *ctx);
long SSL_get_options(SSL *ssl);

Detailed Description

SSL_CTX_set_options() adds the options set via bitmask in options to ctx. Options already set before are not cleared!

SSL_set_options() adds the options set via bitmask in options to ssl. Options already set before are not cleared!

SSL_CTX_get_options() returns the options set for ctx.

SSL_get_options() returns the options set for ssl.

Notes

The behaviour of the SSL library can be changed by setting several options. The options are coded as bitmasks and can be combined by a logical or operation (|). Options can only be added but can never be reset.

SSL_CTX_set_options() and SSL_set_options() affect the (external) protocol behaviour of the SSL library. The (internal) behaviour of the API can be changed by using the similar SSL_CTX_set_mode() and SSL_set_mode() functions.

During a handshake, the option settings of the SSL object are used. When a new SSL object is created from a context using SSL_new(), the current option setting is copied. Changes to ctx do not affect already created SSL objects. SSL_clear() does not affect the settings.

The following bug workaround options are available:

s
www.microsoft.com - when talking SSLv2, if session-id reuse is performed, the session-id passed back in the server-finished message is different from the one decided upon.

SSL_OP_NETSCAPE_CHALLENGE_BUG
Netscape-Commerce/1.12, when talking SSLv2, accepts a 32 byte challenge but then appears to only use 16 bytes when generating the encryption keys. Using 16 bytes is ok but it should be ok to use 32. According to the SSLv3 spec, one should use 32 bytes for the challenge when operating in SSLv2/v3 compatibility mode, but as mentioned above, this breaks this server so 16 bytes is the way to go.

SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG
ssl3.netscape.com:443, first a connection is established with RC4-MD5. If it is then resumed, we end up using DES-CBC3-SHA. It should be RC4-MD5 according to 7.6.1.3, 'cipher_suite'.

Netscape-Enterprise/2.01 (https://merchant.netscape.com) has this bug. It only really shows up when connecting via SSLv2/v3 then reconnecting via SSLv3. The cipher list changes....

NEW INFORMATION. Try connecting with a cipher list of just DES-CBC-SHA:RC4-MD5. For some weird reason, each new connection uses RC4-MD5, but a re-connect tries to use DES-CBC-SHA. So netscape, when re-connecting, always takes the first cipher in the cipher list.

SSL_OP_SSLREF2_REUSE_CERT_TYPE_BUG
...

SSL_OP_MICROSOFT_BIG_SSLV3_BUFFER
...

SSL_OP_MSIE_SSLV2_RSA_PADDING
As of OpenSSL 0.9.7h and 0.9.8a, this option has no effect.

SSL_OP_SSLEAY_080_CLIENT_DH_BUG
...

SSL_OP_TLS_D5_BUG
...

SSL_OP_TLS_BLOCK_PADDING_BUG
...

SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS
Disables a countermeasure against a SSL 3.0/TLS 1.0 protocol vulnerability affecting CBC ciphers, which cannot be handled by some broken SSL implementations. This option has no effect for connections using other ciphers.

SSL_OP_ALL
All of the above bug workarounds.

It is usually safe to use SSL_OP_ALL to enable the bug workaround options if compatibility with somewhat broken implementations is desired.

The following modifying options are available:

SSL_OP_TLS_ROLLBACK_BUG
Disable version rollback attack detection.

During the client key exchange, the client must send the same information about acceptable SSL/TLS protocol levels as during the first hello. Some clients violate this rule by adapting to the server's answer. (Example: the client sends a SSLv2 hello and accepts up to SSLv3.1=TLSv1, the server only understands up to SSLv3. In this case the client must still use the same SSLv3.1=TLSv1 announcement. Some clients step down to SSLv3 with respect to the server's answer and violate the version rollback protection.)

SSL_OP_SINGLE_DH_USE
Always create a new key when using temporary/ephemeral DH parameters (see SSL_CTX_set_tmp_dh_callback()). This option must be used to prevent small subgroup attacks, when the DH parameters were not generated using ``strong'' primes (e.g. when using DSA-parameters, see dhparam()). If ``strong'' primes were used, it is not strictly necessary to generate a new DH key during each handshake but it is also recommended. SSL_OP_SINGLE_DH_USE should therefore be enabled whenever temporary/ephemeral DH parameters are used.

SSL_OP_EPHEMERAL_RSA
Always use ephemeral (temporary) RSA key when doing RSA operations (see SSL_CTX_set_tmp_rsa_callback()). According to the specifications this is only done, when a RSA key can only be used for signature operations (namely under export ciphers with restricted RSA keylength). By setting this option, ephemeral RSA keys are always used. This option breaks compatibility with the SSL/TLS specifications and may lead to interoperability problems with clients and should therefore never be used. Ciphers with EDH (ephemeral Diffie-Hellman) key exchange should be used instead.

SSL_OP_CIPHER_SERVER_PREFERENCE
When choosing a cipher, use the server's preferences instead of the client preferences. When not set, the SSL server will always follow the clients preferences. When set, the SSLv3/TLSv1 server will choose following its own preferences. Because of the different protocol, for SSLv2 the server will send its list of preferences to the client and the client chooses.

SSL_OP_PKCS1_CHECK_1
...

SSL_OP_PKCS1_CHECK_2
...

SSL_OP_NETSCAPE_CA_DN_BUG
If we accept a netscape connection, demand a client cert, have a non-self-signed CA which does not have its CA in netscape, and the browser has a cert, it will crash/hang. Works for 3.x and 4.xbeta

SSL_OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG
...

SSL_OP_NO_SSLv2
Do not use the SSLv2 protocol.

SSL_OP_NO_SSLv3
Do not use the SSLv3 protocol.

SSL_OP_NO_TLSv1
Do not use the TLSv1 protocol.

SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION
When performing renegotiation as a server, always start a new session (i.e., session resumption requests are only accepted in the initial handshake). This option is not needed for clients.

Return Values

SSL_CTX_set_options() and SSL_set_options() return the new options bitmask after adding options.

SSL_CTX_get_options() and SSL_get_options() return the current bitmask.

See Also

ssl(),
SSL_new(), SSL_clear(),
SSL_CTX_set_tmp_dh_callback(),
SSL_CTX_set_tmp_rsa_callback(),
dhparam()

History

SSL_OP_CIPHER_SERVER_PREFERENCE and SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION have been added in OpenSSL 0.9.7.

SSL_OP_TLS_ROLLBACK_BUG has been added in OpenSSL 0.9.6 and was automatically enabled with SSL_OP_ALL. As of 0.9.7, it is no longer included in SSL_OP_ALL and must be explicitly set.

SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS has been added in OpenSSL 0.9.6e. Versions up to OpenSSL 0.9.6c do not include the countermeasure that can be disabled with this option (in OpenSSL 0.9.6d, it was always enabled).

Feedback

For additional information or queries on this page send feedback


SSL_get_quiet_shutdown - manipulate shutdown behaviour

Name

SSL_CTX_set_quiet_shutdown, SSL_CTX_get_quiet_shutdown
SSL_set_quiet_shutdown, SSL_get_quiet_shutdown

manipulates shutdown behaviour

Library

libssl.lib

Synopsis

#include <openssl/ssl.h>
void SSL_CTX_set_quiet_shutdown(SSL_CTX *ctx, int mode);
int SSL_CTX_get_quiet_shutdown(const SSL_CTX *ctx);
void SSL_set_quiet_shutdown(SSL *ssl, int mode);
int SSL_get_quiet_shutdown(const SSL *ssl);

Detailed Description

SSL_CTX_set_quiet_shutdown() sets the ``quiet shutdown'' flag for ctx to be mode. SSL objects created from ctx inherit the mode valid at the time SSL_new() is called. mode may be 0 or 1.

SSL_CTX_get_quiet_shutdown() returns the ``quiet shutdown'' setting of ctx.

SSL_set_quiet_shutdown() sets the ``quiet shutdown'' flag for ssl to be mode. The setting stays valid until ssl is removed with SSL_free() or SSL_set_quiet_shutdown() is called again. It is not changed when SSL_clear() is called. mode may be 0 or 1.

SSL_get_quiet_shutdown() returns the ``quiet shutdown'' setting of ssl.

Notes

Normally when a SSL connection is finished, the parties must send out ``close notify'' alert messages using SSL_shutdown() for a clean shutdown.

When setting the ``quiet shutdown'' flag to 1, SSL_shutdown() will set the internal flags to SSL_SENT_SHUTDOWN|SSL_RECEIVED_SHUTDOWN. (SSL_shutdown() then behaves like SSL_set_shutdown() called with SSL_SENT_SHUTDOWN|SSL_RECEIVED_SHUTDOWN.) The session is thus considered to be shutdown, but no ``close notify'' alert is sent to the peer. This behaviour violates the TLS standard.

The default is normal shutdown behaviour as described by the TLS standard.

Return Values

SSL_CTX_set_quiet_shutdown() and SSL_set_quiet_shutdown() do not return diagnostic information.

SSL_CTX_get_quiet_shutdown() and SSL_get_quiet_shutdown return the current setting.

See Also

ssl(),
SSL_shutdown(),
SSL_set_shutdown(),
SSL_new(),
SSL_clear(), SSL_free()

Feedback

For additional information or queries on this page send feedback


SSL_CTX_get_session_cache_mode - enable/disable session caching

Name

SSL_CTX_set_session_cache_mode, SSL_CTX_get_session_cache_mode — enable/disable session caching

Library

libssl.lib

Synopsis

#include <openssl/ssl.h>
long SSL_CTX_set_session_cache_mode(SSL_CTX ctx, long mode);
long SSL_CTX_get_session_cache_mode(SSL_CTX ctx);

Detailed Description

SSL_CTX_set_session_cache_mode() enables/disables session caching by setting the operational mode for ctx to <mode>.

SSL_CTX_get_session_cache_mode() returns the currently used cache mode.

Notes

The OpenSSL library can store/retrieve SSL/TLS sessions for later reuse. The sessions can be held in memory for each ctx, if more than one SSL_CTX object is being maintained, the sessions are unique for each SSL_CTX object.

In order to reuse a session, a client must send the session's id to the server. It can only send exactly one id. The server then either agrees to reuse the session or it starts a full handshake (to create a new session).

A server will lookup up the session in its internal session storage. If the session is not found in internal storage or lookups for the internal storage have been deactivated (SSL_SESS_CACHE_NO_INTERNAL_LOOKUP), the server will try the external storage if available.

Since a client may try to reuse a session intended for use in a different context, the session id context must be set by the server (see SSL_CTX_set_session_id_context()).

The following session cache modes and modifiers are available:

SSL_SESS_CACHE_OFF
No session caching for client or server takes place.

SSL_SESS_CACHE_CLIENT
Client sessions are added to the session cache. As there is no reliable way for the OpenSSL library to know whether a session should be reused or which session to choose (due to the abstract BIO layer the SSL engine does not have details about the connection), the application must select the session to be reused by using the SSL_set_session() function. This option is not activated by default.

SSL_SESS_CACHE_SERVER
Server sessions are added to the session cache. When a client proposes a session to be reused, the server looks for the corresponding session in (first) the internal session cache (unless SSL_SESS_CACHE_NO_INTERNAL_LOOKUP is set), then (second) in the external cache if available. If the session is found, the server will try to reuse the session. This is the default.

SSL_SESS_CACHE_BOTH
Enable both SSL_SESS_CACHE_CLIENT and SSL_SESS_CACHE_SERVER at the same time.

SSL_SESS_CACHE_NO_AUTO_CLEAR
Normally the session cache is checked for expired sessions every 255 connections using the SSL_CTX_flush_sessions() function. Since this may lead to a delay which cannot be controlled, the automatic flushing may be disabled and SSL_CTX_flush_sessions() can be called explicitly by the application.

SSL_SESS_CACHE_NO_INTERNAL_LOOKUP
By setting this flag, session-resume operations in an SSL/TLS server will not automatically look up sessions in the internal cache, even if sessions are automatically stored there. If external session caching callbacks are in use, this flag guarantees that all lookups are directed to the external cache. As automatic lookup only applies for SSL/TLS servers, the flag has no effect on clients.

SSL_SESS_CACHE_NO_INTERNAL_STORE
Depending on the presence of SSL_SESS_CACHE_CLIENT and/or SSL_SESS_CACHE_SERVER, sessions negotiated in an SSL/TLS handshake may be cached for possible reuse. Normally a new session is added to the internal cache as well as any external session caching (callback) that is configured for the SSL_CTX. This flag will prevent sessions being stored in the internal cache (though the application can add them manually using SSL_CTX_add_session()). Note: in any SSL/TLS servers where external caching is configured, any successful session lookups in the external cache (i.e.. for session-resume requests) would normally be copied into the local cache before processing continues - this flag prevents these additions to the internal cache as well.

SSL_SESS_CACHE_NO_INTERNAL
Enable both SSL_SESS_CACHE_NO_INTERNAL_LOOKUP and SSL_SESS_CACHE_NO_INTERNAL_STORE at the same time.

The default mode is SSL_SESS_CACHE_SERVER.

Return Values

SSL_CTX_set_session_cache_mode() returns the previously set cache mode.

SSL_CTX_get_session_cache_mode() returns the currently set cache mode.

See Also

ssl(),
SSL_set_session(),
SSL_session_reused(),
SSL_CTX_add_session(),
SSL_CTX_sess_number(),
SSL_CTX_sess_set_cache_size(),
SSL_CTX_sess_set_get_cb(),
SSL_CTX_set_session_id_context(),
SSL_CTX_set_timeout(),
SSL_CTX_flush_sessions()

History

SSL_SESS_CACHE_NO_INTERNAL_STORE and SSL_SESS_CACHE_NO_INTERNAL were introduced in OpenSSL 0.9.6h.

Feedback

For additional information or queries on this page send feedback


SSL_set_session_id_context - set context within which session can be reused

Name

SSL_CTX_set_session_id_context, SSL_set_session_id_context — set context within which session can be reused (server side only)

Library

libssl.lib

Synopsis

#include <openssl/ssl.h>
int SSL_CTX_set_session_id_context(SSL_CTX *ctx, const unsigned char *sid_ctx, unsigned int sid_ctx_len);
int SSL_set_session_id_context(SSL *ssl, const unsigned char *sid_ctx, unsigned int sid_ctx_len);

Detailed Description

SSL_CTX_set_session_id_context() sets the context sid_ctx of length sid_ctx_len within which a session can be reused for the ctx object.

SSL_set_session_id_context() sets the context sid_ctx of length sid_ctx_len within which a session can be reused for the ssl object.

Notes

Sessions are generated within a certain context. When exporting/importing sessions with i2d_SSL_SESSION/d2i_SSL_SESSION it would be possible, to re-import a session generated from another context (e.g. another application), which might lead to malfunctions. Therefore each application must set its own session id context sid_ctx which is used to distinguish the contexts and is stored in exported sessions. The sid_ctx can be any kind of binary data with a given length, it is therefore possible to use e.g. the name of the application and/or the hostname and/or service name ...

The session id context becomes part of the session. The session id context is set by the SSL/TLS server. The SSL_CTX_set_session_id_context() and SSL_set_session_id_context() functions are therefore only useful on the server side.

OpenSSL clients will check the session id context returned by the server when reusing a session.

The maximum length of the sid_ctx is limited to SSL_MAX_SSL_SESSION_ID_LENGTH.

Warnings

If the session id context is not set on an SSL/TLS server and client certificates are used, stored sessions will not be reused but a fatal error will be flagged and the handshake will fail.

If a server returns a different session id context to an OpenSSL client when reusing a session, an error will be flagged and the handshake will fail. OpenSSL servers will always return the correct session id context, as an OpenSSL server checks the session id context itself before reusing a session as described above.

Return Values

SSL_CTX_set_session_id_context() and SSL_set_session_id_context() return the following values:

  1. The length sid_ctx_len of the session id context sid_ctx exceeded the maximum allowed length of SSL_MAX_SSL_SESSION_ID_LENGTH. The error is logged to the error stack.

    3. The operation succeeded.

See Also

ssl()

Feedback

For additional information or queries on this page send feedback


SSL_get_ssl_method - choose a new TLS/SSL method

Name

SSL_CTX_set_ssl_version, SSL_set_ssl_method
SSL_get_ssl_method

choose a new TLS/SSL method

Library

libssl.lib

Synopsis

#include <openssl/ssl.h>
int SSL_CTX_set_ssl_version(SSL_CTX *ctx, SSL_METHOD *method);
int SSL_set_ssl_method(SSL *s, SSL_METHOD *method);
SSL_METHOD *SSL_get_ssl_method(SSL *ssl);

Detailed Description

SSL_CTX_set_ssl_version() sets a new default TLS/SSL method for SSL objects newly created from this ctx. SSL objects already created with SSL_new() are not affected, except when SSL_clear() is being called.

SSL_set_ssl_method() sets a new TLS/SSL method for a particular ssl object. It may be reset, when SSL_clear() is called.

SSL_get_ssl_method() returns a function pointer to the TLS/SSL method set in ssl.

Notes

The available method choices are described in SSL_CTX_new().

When SSL_clear() is called and no session is connected to an SSL object, the method of the SSL object is reset to the method currently set in the corresponding SSL_CTX object.

Return Values

The following return values can occur for SSL_CTX_set_ssl_version() and SSL_set_ssl_method():

    2. The new choice failed, check the error stack to find out the reason.

    3. The operation succeeded.

See Also

SSL_CTX_new(),
SSL_new(),
SSL_clear(), ssl(),
SSL_set_connect_state()

Feedback

For additional information or queries on this page send feedback


SSL_CTX_get_timeout - manipulate timeout values for session caching

Name

SSL_CTX_set_timeout, SSL_CTX_get_timeout — manipulates timeout values for session caching

Library

libssl.lib

Synopsis

#include <openssl/ssl.h>
long SSL_CTX_set_timeout(SSL_CTX *ctx, long t);
long SSL_CTX_get_timeout(SSL_CTX *ctx);

Detailed Description

SSL_CTX_set_timeout() sets the timeout for newly created sessions for ctx to t. The timeout value t must be given in seconds.

SSL_CTX_get_timeout() returns the currently set timeout value for ctx.

Notes

Whenever a new session is created, it is assigned a maximum lifetime. This lifetime is specified by storing the creation time of the session and the timeout value valid at this time. If the actual time is later than creation time plus timeout, the session is not reused.

Due to this realization, all sessions behave according to the timeout value valid at the time of the session negotiation. Changes of the timeout value do not affect already established sessions.

The expiration time of a single session can be modified using the SSL_SESSION_get_time() family of functions.

Expired sessions are removed from the internal session cache, whenever SSL_CTX_flush_sessions() is called, either directly by the application or automatically (see SSL_CTX_set_session_cache_mode())

The default value for session timeout is decided on a per protocol basis, see SSL_get_default_timeout(). All currently supported protocols have the same default timeout value of 300 seconds.

Return Values

SSL_CTX_set_timeout() returns the previously set timeout value.

SSL_CTX_get_timeout() returns the currently set timeout value.

See Also

ssl(),
SSL_CTX_set_session_cache_mode(),
SSL_SESSION_get_time(),
SSL_CTX_flush_sessions(),
SSL_get_default_timeout()

Feedback

For additional information or queries on this page send feedback


SSL_set_tmp_dh - handle DH keys for ephemeral key exchange

Name

SSL_CTX_set_tmp_dh_callback, SSL_CTX_set_tmp_dh
SSL_set_tmp_dh_callback, SSL_set_tmp_dh

handles DH keys for ephemeral key exchange

Library

libssl.lib

Synopsis

#include <openssl/ssl.h>
void SSL_CTX_set_tmp_dh_callback(SSL_CTX *ctx, DH *(*tmp_dh_callback)(SSL *ssl, int is_export, int keylength));
long SSL_CTX_set_tmp_dh(SSL_CTX *ctx, DH *dh);
void SSL_set_tmp_dh_callback(SSL_CTX *ctx, DH *(*tmp_dh_callback)(SSL *ssl, int is_export, int keylength));
long SSL_set_tmp_dh(SSL *ssl, DH *dh)
DH *(*tmp_dh_callback)(SSL *ssl, int is_export, int keylength));

Detailed Description

SSL_CTX_set_tmp_dh_callback() sets the callback function for ctx to be used when a DH parameters are required to tmp_dh_callback. The callback is inherited by all ssl objects created from ctx.

SSL_CTX_set_tmp_dh() sets DH parameters to be used to be dh. The key is inherited by all ssl objects created from ctx.

SSL_set_tmp_dh_callback() sets the callback only for ssl.

SSL_set_tmp_dh() sets the parameters only for ssl.

These functions apply to SSL/TLS servers only.

Examples

Handle DH parameters for key lengths of 512 and 1024 bits. (Error handling partly left out.)
 ...
 /* Set up ephemeral DH stuff */
 DH *dh_512 = NULL;
 DH *dh_1024 = NULL;
 FILE *paramfile;
 ...
 /* "openssl dhparam -out dh_param_512.pem -2 512" */
 paramfile = fopen("dh_param_512.pem", "r");
 if (paramfile) {
   dh_512 = PEM_read_DHparams(paramfile, NULL, NULL, NULL);
   fclose(paramfile);
 }
 /* "openssl dhparam -out dh_param_1024.pem -2 1024" */
 paramfile = fopen("dh_param_1024.pem", "r");
 if (paramfile) {
   dh_1024 = PEM_read_DHparams(paramfile, NULL, NULL, NULL);
   fclose(paramfile);
 }
 ...
 /* "openssl dhparam -C -2 512" etc... */
 DH *get_dh512() { ... }
 DH *get_dh1024() { ... }
 DH *tmp_dh_callback(SSL *s, int is_export, int keylength)
 {
    DH *dh_tmp=NULL;
    switch (keylength) {
    case 512:
      if (!dh_512)
        dh_512 = get_dh512();
      dh_tmp = dh_512;
      break;
    case 1024:
      if (!dh_1024)
        dh_1024 = get_dh1024();
      dh_tmp = dh_1024;
      break;
    default:
      /* Generating a key on the fly is very costly, so use what is there */
      setup_dh_parameters_like_above();
    }
    return(dh_tmp);
 }

Notes

When using a cipher with RSA authentication, an ephemeral DH key exchange can take place. Ciphers with DSA keys always use ephemeral DH keys as well. In these cases, the session data are negotiated using the ephemeral/temporary DH key and the key supplied and certified by the certificate chain is only used for signing. Anonymous ciphers (without a permanent server key) also use ephemeral DH keys.

Using ephemeral DH key exchange yields forward secrecy, as the connection can only be decrypted, when the DH key is known. By generating a temporary DH key inside the server application that is lost when the application is left, it becomes impossible for an attacker to decrypt past sessions, even if he gets hold of the normal (certified) key, as this key was only used for signing.

In order to perform a DH key exchange the server must use a DH group (DH parameters) and generate a DH key. The server will always generate a new DH key during the negotiation, when the DH parameters are supplied via callback and/or when the SSL_OP_SINGLE_DH_USE option of SSL_CTX_set_options(3) is set. It will immediately create a DH key, when DH parameters are supplied via SSL_CTX_set_tmp_dh() and SSL_OP_SINGLE_DH_USE is not set. In this case, it may happen that a key is generated on initialization without later being needed, while on the other hand the computer time during the negotiation is being saved.

If ``strong'' primes were used to generate the DH parameters, it is not strictly necessary to generate a new key for each handshake but it does improve forward secrecy. If it is not assured, that ``strong'' primes were used (see especially the section about DSA parameters below), SSL_OP_SINGLE_DH_USE must be used in order to prevent small subgroup attacks. Always using SSL_OP_SINGLE_DH_USE has an impact on the computer time needed during negotiation, but it is not very large, so application authors/users should consider to always enable this option.

As generating DH parameters is extremely time consuming, an application should not generate the parameters on the fly but supply the parameters. DH parameters can be reused, as the actual key is newly generated during the negotiation. The risk in reusing DH parameters is that an attacker may specialize on a very often used DH group. Applications should therefore generate their own DH parameters during the installation process using the openssl dhparam() application. In order to reduce the computer time needed for this generation, it is possible to use DSA parameters instead (see dhparam()), but in this case SSL_OP_SINGLE_DH_USE is mandatory.

Application authors may compile in DH parameters. Files dh512.pem, dh1024.pem, dh2048.pem, and dh4096 in the 'apps' directory of current version of the OpenSSL distribution contain the 'SKIP' DH parameters, which use safe primes and were generated verifiably pseudo-randomly. These files can be converted into C code using the -C option of the dhparam() application. Authors may also generate their own set of parameters using dhparam(), but a user may not be sure how the parameters were generated. The generation of DH parameters during installation is therefore recommended.

An application may either directly specify the DH parameters or can supply the DH parameters via a callback function. The callback approach has the advantage, that the callback may supply DH parameters for different key lengths.

The tmp_dh_callback is called with the keylength needed and the is_export information. The is_export flag is set, when the ephemeral DH key exchange is performed with an export cipher.

Return Values

SSL_CTX_set_tmp_dh_callback() and SSL_set_tmp_dh_callback() do not return diagnostic output.

SSL_CTX_set_tmp_dh() and SSL_set_tmp_dh() do return 1 on success and 0 on failure. Check the error queue to find out the reason of failure.

See Also

ssl(),
SSL_CTX_set_cipher_list(),
SSL_CTX_set_tmp_rsa_callback(),
SSL_CTX_set_options(),
ciphers(), dhparam()

Feedback

For additional information or queries on this page send feedback


SSL_need_tmp_rsa - handle RSA keys for ephemeral key exchange

Name

SSL_CTX_set_tmp_rsa_callback, SSL_CTX_set_tmp_rsa
SSL_CTX_need_tmp_rsa, SSL_set_tmp_rsa_callback
SSL_set_tmp_rsa, SSL_need_tmp_rsa

handles RSA keys for ephemeral key exchange

Library

libssl.lib

Synopsis

#include <openssl/ssl.h>
void SSL_CTX_set_tmp_rsa_callback(SSL_CTX *ctx, RSA *(*tmp_rsa_callback)(SSL *ssl, int is_export, int keylength));
long SSL_CTX_set_tmp_rsa(SSL_CTX *ctx, RSA *rsa);
long SSL_CTX_need_tmp_rsa(SSL_CTX *ctx);
void SSL_set_tmp_rsa_callback(SSL_CTX *ctx, RSA *(*tmp_rsa_callback)(SSL *ssl, int is_export, int keylength));
long SSL_set_tmp_rsa(SSL *ssl, RSA *rsa)
long SSL_need_tmp_rsa(SSL *ssl)
RSA *(*tmp_rsa_callback)(SSL *ssl, int is_export, int keylength));

Detailed Description

SSL_CTX_set_tmp_rsa_callback() sets the callback function for ctx to be used when a temporary/ephemeral RSA key is required to tmp_rsa_callback. The callback is inherited by all SSL objects newly created from ctx with <SSL_new()|SSL_new()>. Already created SSL objects are not affected.

SSL_CTX_set_tmp_rsa() sets the temporary/ephemeral RSA key to be used to be rsa. The key is inherited by all SSL objects newly created from ctx with <SSL_new()|SSL_new()>. Already created SSL objects are not affected.

SSL_CTX_need_tmp_rsa() returns 1, if a temporary/ephemeral RSA key is needed for RSA-based strength-limited 'exportable' cipher suites because a RSA key with a keysize larger than 512 bits is installed.

SSL_set_tmp_rsa_callback() sets the callback only for ssl.

SSL_set_tmp_rsa() sets the key only for ssl.

SSL_need_tmp_rsa() returns 1, if a temporary/ephemeral RSA key is needed, for RSA-based strength-limited 'exportable' ciphersuites because a RSA key with a keysize larger than 512 bits is installed.

These functions apply to SSL/TLS servers only.

Examples

Generate temporary RSA keys to prepare ephemeral RSA key exchange. As the generation of a RSA key costs a lot of computer time, they saved for later reuse. For demonstration purposes, two keys for 512 bits and 1024 bits respectively are generated.
 ...
 /* Set up ephemeral RSA stuff */
 RSA *rsa_512 = NULL;
 RSA *rsa_1024 = NULL;
 rsa_512 = RSA_generate_key(512,RSA_F4,NULL,NULL);
 if (rsa_512 == NULL)
     evaluate_error_queue();
 rsa_1024 = RSA_generate_key(1024,RSA_F4,NULL,NULL);
 if (rsa_1024 == NULL)
   evaluate_error_queue();
 ...
 RSA *tmp_rsa_callback(SSL *s, int is_export, int keylength)
 {
    RSA *rsa_tmp=NULL;
    switch (keylength) {
    case 512:
      if (rsa_512)
        rsa_tmp = rsa_512;
      else { /* generate on the fly, should not happen in this example */
        rsa_tmp = RSA_generate_key(keylength,RSA_F4,NULL,NULL);
        rsa_512 = rsa_tmp; /* Remember for later reuse */
      }
      break;
    case 1024:
      if (rsa_1024)
        rsa_tmp=rsa_1024;
      else
        should_not_happen_in_this_example();
      break;
    default:
      /* Generating a key on the fly is very costly, so use what is there */
      if (rsa_1024)
        rsa_tmp=rsa_1024;
      else
        rsa_tmp=rsa_512; /* Use at least a shorter key */
    }
    return(rsa_tmp);
 }

Notes

When using a cipher with RSA authentication, an ephemeral RSA key exchange can take place. In this case the session data are negotiated using the ephemeral/temporary RSA key and the RSA key supplied and certified by the certificate chain is only used for signing.

Under previous export restrictions, ciphers with RSA keys shorter (512 bits) than the usual key length of 1024 bits were created. To use these ciphers with RSA keys of usual length, an ephemeral key exchange must be performed, as the normal (certified) key cannot be directly used.

Using ephemeral RSA key exchange yields forward secrecy, as the connection can only be decrypted, when the RSA key is known. By generating a temporary RSA key inside the server application that is lost when the application is left, it becomes impossible for an attacker to decrypt past sessions, even if he gets hold of the normal (certified) RSA key, as this key was used for signing only. The downside is that creating a RSA key is computationally expensive.

Additionally, the use of ephemeral RSA key exchange is only allowed in the TLS standard, when the RSA key can be used for signing only, that is for export ciphers. Using ephemeral RSA key exchange for other purposes violates the standard and can break interoperability with clients. It is therefore strongly recommended to not use ephemeral RSA key exchange and use EDH (Ephemeral Diffie-Hellman) key exchange instead in order to achieve forward secrecy (see SSL_CTX_set_tmp_dh_callback()).

On OpenSSL servers ephemeral RSA key exchange is therefore disabled by default and must be explicitly enabled using the SSL_OP_EPHEMERAL_RSA option of SSL_CTX_set_options(), violating the TLS/SSL standard. When ephemeral RSA key exchange is required for export ciphers, it will automatically be used without this option!

An application may either directly specify the key or can supply the key via a callback function. The callback approach has the advantage, that the callback may generate the key only in case it is actually needed. As the generation of a RSA key is however costly, it will lead to a significant delay in the handshake procedure. Another advantage of the callback function is that it can supply keys of different size (e.g. for SSL_OP_EPHEMERAL_RSA usage) while the explicit setting of the key is only useful for key size of 512 bits to satisfy the export restricted ciphers and does give away key length if a longer key would be allowed.

The tmp_rsa_callback is called with the keylength needed and the is_export information. The is_export flag is set, when the ephemeral RSA key exchange is performed with an export cipher.

Return Values

SSL_CTX_set_tmp_rsa_callback() and SSL_set_tmp_rsa_callback() do not return diagnostic output.

SSL_CTX_set_tmp_rsa() and SSL_set_tmp_rsa() do return 1 on success and 0 on failure. Check the error queue to find out the reason of failure.

SSL_CTX_need_tmp_rsa() and SSL_need_tmp_rsa() return 1 if a temporary RSA key is needed and 0 otherwise.

See Also

ssl(),
SSL_CTX_set_cipher_list(),
SSL_CTX_set_options(),
SSL_CTX_set_tmp_dh_callback(),
SSL_new(), ciphers()

Feedback

For additional information or queries on this page send feedback


SSL_set_verify_depth - set peer certificate verification parameters

Name

SSL_CTX_set_verify, SSL_set_verify
SSL_CTX_set_verify_depth, SSL_set_verify_depth

sets peer certificate verification parameters

Library

libssl.lib

Synopsis

#include <openssl/ssl.h>
void SSL_CTX_set_verify(SSL_CTX *ctx, int mode, int (*verify_callback)(int, X509_STORE_CTX *));
void SSL_set_verify(SSL *s, int mode, int (*verify_callback)(int, X509_STORE_CTX *));
void SSL_CTX_set_verify_depth(SSL_CTX *ctx,int depth);
void SSL_set_verify_depth(SSL *s, int depth);
int verify_callback(int preverify_ok, X509_STORE_CTX *x509_ctx);

Detailed Description

SSL_CTX_set_verify() sets the verification flags for ctx to be mode and specifies the verify_callback function to be used. If no callback function shall be specified, the NULL pointer can be used for verify_callback.

SSL_set_verify() sets the verification flags for ssl to be mode and specifies the verify_callback function to be used. If no callback function shall be specified, the NULL pointer can be used for verify_callback. In this case last verify_callback set specifically for this ssl remains. If no special callback was set before, the default callback for the underlying ctx is used, that was valid at the time ssl was created with SSL_new().

SSL_CTX_set_verify_depth() sets the maximum depth for the certificate chain verification that shall be allowed for ctx. (See the BUGS section.)

SSL_set_verify_depth() sets the maximum depth for the certificate chain verification that shall be allowed for ssl. (See the BUGS section.)

Notes

The verification of certificates can be controlled by a set of logically or'ed mode flags:

SSL_VERIFY_NONE
Server mode: the server will not send a client certificate request to the client, so the client will not send a certificate.

Client mode: if not using an anonymous cipher (by default disabled), the server will send a certificate which will be checked. The result of the certificate verification process can be checked after the TLS/SSL handshake using the SSL_get_verify_result() function. The handshake will be continued regardless of the verification result.

SSL_VERIFY_PEER
Server mode: the server sends a client certificate request to the client. The certificate returned (if any) is checked. If the verification process fails, the TLS/SSL handshake is immediately terminated with an alert message containing the reason for the verification failure. The behaviour can be controlled by the additional SSL_VERIFY_FAIL_IF_NO_PEER_CERT and SSL_VERIFY_CLIENT_ONCE flags.

Client mode: the server certificate is verified. If the verification process fails, the TLS/SSL handshake is immediately terminated with an alert message containing the reason for the verification failure. If no server certificate is sent, because an anonymous cipher is used, SSL_VERIFY_PEER is ignored.

SSL_VERIFY_FAIL_IF_NO_PEER_CERT
Server mode: if the client did not return a certificate, the TLS/SSL handshake is immediately terminated with a ``handshake failure'' alert. This flag must be used together with SSL_VERIFY_PEER.

Client mode: ignored

SSL_VERIFY_CLIENT_ONCE
Server mode: only request a client certificate on the initial TLS/SSL handshake. Do not ask for a client certificate again in case of a renegotiation. This flag must be used together with SSL_VERIFY_PEER.

Client mode: ignored

Exactly one of the mode flags SSL_VERIFY_NONE and SSL_VERIFY_PEER must be set at any time.

The actual verification procedure is performed either using the built-in verification procedure or using another application provided verification function set with SSL_CTX_set_cert_verify_callback(). The following descriptions apply in the case of the built-in procedure. An application provided procedure also has access to the verify depth information and the verify_callback() function, but the way this information is used may be different.

SSL_CTX_set_verify_depth() and SSL_set_verify_depth() set the limit up to which depth certificates in a chain are used during the verification procedure. If the certificate chain is longer than allowed, the certificates above the limit are ignored. Error messages are generated as if these certificates would not be present, most likely a X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY will be issued. The depth count is ``level 0:peer certificate'', ``level 1: CA certificate'', ``level 2: higher level CA certificate'', and so on. Setting the maximum depth to 2 allows the levels 0, 1, and 2. The default depth limit is 9, allowing for the peer certificate and additional 9 CA certificates.

The verify_callback function is used to control the behaviour when the SSL_VERIFY_PEER flag is set. It must be supplied by the application and receives two arguments: preverify_ok indicates, whether the verification of the certificate in question was passed (preverify_ok=1) or not (preverify_ok=0). x509_ctx is a pointer to the complete context used for the certificate chain verification.

The certificate chain is checked starting with the deepest nesting level (the root CA certificate) and worked upward to the peer's certificate. At each level signatures and issuer attributes are checked. Whenever a verification error is found, the error number is stored in x509_ctx and verify_callback is called with preverify_ok=0. By applying X509_CTX_store_* functions verify_callback can locate the certificate in question and perform additional steps (see EXAMPLES). If no error is found for a certificate, verify_callback is called with preverify_ok=1 before advancing to the next level.

The return value of verify_callback controls the strategy of the further verification process. If verify_callback returns 0, the verification process is immediately stopped with ``verification failed'' state. If SSL_VERIFY_PEER is set, a verification failure alert is sent to the peer and the TLS/SSL handshake is terminated. If verify_callback returns 1, the verification process is continued. If verify_callback always returns 1, the TLS/SSL handshake will not be terminated with respect to verification failures and the connection will be established. The calling process can however retrieve the error code of the last verification error using SSL_get_verify_result() or by maintaining its own error storage managed by verify_callback.

If no verify_callback is specified, the default callback will be used. Its return value is identical to preverify_ok, so that any verification failure will lead to a termination of the TLS/SSL handshake with an alert message, if SSL_VERIFY_PEER is set.

Bugs

In client mode, it is not checked whether the SSL_VERIFY_PEER flag is set, but whether SSL_VERIFY_NONE is not set. This can lead to unexpected behaviour, if the SSL_VERIFY_PEER and SSL_VERIFY_NONE are not used as required (exactly one must be set at any time).

The certificate verification depth set with SSL[_CTX]_verify_depth() stops the verification at a certain depth. The error message produced will be that of an incomplete certificate chain and not X509_V_ERR_CERT_CHAIN_TOO_LONG as may be expected.

Return Values

The SSL*_set_verify*() functions do not provide diagnostic information.

Examples

The following code sequence realizes an example verify_callback function that will always continue the TLS/SSL handshake regardless of verification failure, if wished. The callback realizes a verification depth limit with more informational output.

All verification errors are printed, information about the certificate chain are printed on request. The example is realized for a server that does allow but not require client certificates.

The example makes use of the ex_data technique to store application data into/retrieve application data from the SSL structure (see SSL_get_ex_new_index(), SSL_get_ex_data_X509_STORE_CTX_idx()).
 ...
 typedef struct {
   int verbose_mode;
   int verify_depth;
   int always_continue;
 } mydata_t;
 int mydata_index;
 ...
 static int verify_callback(int preverify_ok, X509_STORE_CTX *ctx)
 {
    char    buf[256];
    X509   *err_cert;
    int     err, depth;
    SSL    *ssl;
    mydata_t *mydata;
    err_cert = X509_STORE_CTX_get_current_cert(ctx);
    err = X509_STORE_CTX_get_error(ctx);
    depth = X509_STORE_CTX_get_error_depth(ctx);
    /*
     * Retrieve the pointer to the SSL of the connection currently treated
     * and the application specific data stored into the SSL object.
     */
    ssl = X509_STORE_CTX_get_ex_data(ctx, SSL_get_ex_data_X509_STORE_CTX_idx());
    mydata = SSL_get_ex_data(ssl, mydata_index);
    X509_NAME_oneline(X509_get_subject_name(err_cert), buf, 256);
    /*
     * Catch a too long certificate chain. The depth limit set using
     * SSL_CTX_set_verify_depth() is by purpose set to "limit+1" so
     * that whenever the "depth>verify_depth" condition is met, we
     * have violated the limit and want to log this error condition.
     * We must do it here, because the CHAIN_TOO_LONG error would not
     * be found explicitly; only errors introduced by cutting off the
     * additional certificates would be logged.
     */
    if (depth > mydata->verify_depth) {
        preverify_ok = 0;
        err = X509_V_ERR_CERT_CHAIN_TOO_LONG;
        X509_STORE_CTX_set_error(ctx, err);
    }
    if (!preverify_ok) {
        printf("verify error:num=%d:%s:depth=%d:%s\n", err,
                 X509_verify_cert_error_string(err), depth, buf);
    }
    else if (mydata->verbose_mode)
    {
        printf("depth=%d:%s\n", depth, buf);
    }
    /*
     * At this point, err contains the last verification error. We can use
     * it for something special
     */
    if (!preverify_ok && (err == X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT))
    {
      X509_NAME_oneline(X509_get_issuer_name(ctx->current_cert), buf, 256);
      printf("issuer= %s\n", buf);
    }
    if (mydata->always_continue)
      return 1;
    else
      return preverify_ok;
 }
 ...
 mydata_t mydata;
 ...
 mydata_index = SSL_get_ex_new_index(0, "mydata index", NULL, NULL, NULL);
 ...
 SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER|SSL_VERIFY_CLIENT_ONCE,
                    verify_callback);
 /*
  * Let the verify_callback catch the verify_depth error so that we get
  * an appropriate error in the logfile.
  */
 SSL_CTX_set_verify_depth(verify_depth + 1);
 /*
  * Set up the SSL specific data into "mydata" and store it into the SSL
  * structure.
  */
 mydata.verify_depth = verify_depth; ...
 SSL_set_ex_data(ssl, mydata_index, &mydata);

 ...
 SSL_accept(ssl);       /* check of success left out for clarity */
 if (peer = SSL_get_peer_certificate(ssl))
 {
   if (SSL_get_verify_result(ssl) == X509_V_OK)
   {
     /* The client sent a certificate which verified OK */
   }
 }

See Also

ssl(),
SSL_new(),
SSL_CTX_get_verify_mode(),
SSL_get_verify_result(),
SSL_CTX_load_verify_locations(),
SSL_get_peer_certificate(),
SSL_CTX_set_cert_verify_callback(),
SSL_get_ex_data_X509_STORE_CTX_idx(),
SSL_get_ex_new_index()

Feedback

For additional information or queries on this page send feedback


SSL_check_private_key - load certificate and key data

Name

SSL_CTX_use_certificate, SSL_CTX_use_certificate_ASN1, SSL_CTX_use_certificate_file
SSL_use_certificate, SSL_use_certificate_ASN1, SSL_use_certificate_file
SSL_CTX_use_certificate_chain_file, SSL_CTX_use_PrivateKey
SSL_CTX_use_PrivateKey_ASN1, SSL_CTX_use_PrivateKey_file
SSL_CTX_use_RSAPrivateKey, SSL_CTX_use_RSAPrivateKey_ASN1
SSL_CTX_use_RSAPrivateKey_file, SSL_use_PrivateKey_file
SSL_use_PrivateKey_ASN1, SSL_use_PrivateKey, SSL_use_RSAPrivateKey
SSL_use_RSAPrivateKey_ASN1, SSL_use_RSAPrivateKey_file
SSL_CTX_check_private_key, SSL_check_private_key

load certificate and key data

Library

libssl.lib

Synopsis

#include <openssl/ssl.h>
int SSL_CTX_use_certificate(SSL_CTX *ctx, X509 *x);
int SSL_CTX_use_certificate_ASN1(SSL_CTX *ctx, int len, unsigned char *d);
int SSL_CTX_use_certificate_file(SSL_CTX *ctx, const char *file, int type);
int SSL_use_certificate(SSL *ssl, X509 *x);
int SSL_use_certificate_ASN1(SSL *ssl, unsigned char *d, int len);
int SSL_use_certificate_file(SSL *ssl, const char *file, int type);
int SSL_CTX_use_certificate_chain_file(SSL_CTX *ctx, const char *file);
int SSL_CTX_use_PrivateKey(SSL_CTX *ctx, EVP_PKEY *pkey);
int SSL_CTX_use_PrivateKey_ASN1(int pk, SSL_CTX *ctx, unsigned char *d, long len);
int SSL_CTX_use_PrivateKey_file(SSL_CTX *ctx, const char *file, int type);
int SSL_CTX_use_RSAPrivateKey(SSL_CTX *ctx, RSA *rsa);
int SSL_CTX_use_RSAPrivateKey_ASN1(SSL_CTX *ctx, unsigned char *d, long len);
int SSL_CTX_use_RSAPrivateKey_file(SSL_CTX *ctx, const char *file, int type);
int SSL_use_PrivateKey(SSL *ssl, EVP_PKEY *pkey);
int SSL_use_PrivateKey_ASN1(int pk,SSL *ssl, unsigned char *d, long len);
int SSL_use_PrivateKey_file(SSL *ssl, const char *file, int type);
int SSL_use_RSAPrivateKey(SSL *ssl, RSA *rsa);
int SSL_use_RSAPrivateKey_ASN1(SSL *ssl, unsigned char *d, long len);
int SSL_use_RSAPrivateKey_file(SSL *ssl, const char *file, int type);
int SSL_CTX_check_private_key(const SSL_CTX *ctx);
int SSL_check_private_key(const SSL *ssl);

Detailed Description

These functions load the certificates and private keys into the SSL_CTX or SSL object, respectively.

The SSL_CTX_* class of functions loads the certificates and keys into the SSL_CTX object ctx. The information is passed to SSL objects ssl created from ctx with SSL_new() by copying, so that changes applied to ctx do not propagate to already existing SSL objects.

The SSL_* class of functions only loads certificates and keys into a specific SSL object. The specific information is kept, when SSL_clear() is called for this SSL object.

SSL_CTX_use_certificate() loads the certificate x into ctx, SSL_use_certificate() loads x into ssl. The rest of the certificates needed to form the complete certificate chain can be specified using the SSL_CTX_add_extra_chain_cert() function.

SSL_CTX_use_certificate_ASN1() loads the ASN1 encoded certificate from the memory location d (with length len) into ctx, SSL_use_certificate_ASN1() loads the ASN1 encoded certificate into ssl.

SSL_CTX_use_certificate_file() loads the first certificate stored in file into ctx. The formatting type of the certificate must be specified from the known types SSL_FILETYPE_PEM, SSL_FILETYPE_ASN1. SSL_use_certificate_file() loads the certificate from file into ssl. See the NOTES section on why SSL_CTX_use_certificate_chain_file() should be preferred.

SSL_CTX_use_certificate_chain_file() loads a certificate chain from file into ctx. The certificates must be in PEM format and must be sorted starting with the subject's certificate (actual client or server certificate), followed by intermediate CA certificates if applicable, and ending at the highest level (root) CA. There is no corresponding function working on a single SSL object.

SSL_CTX_use_PrivateKey() adds pkey as private key to ctx. SSL_CTX_use_RSAPrivateKey() adds the private key rsa of type RSA to ctx. SSL_use_PrivateKey() adds pkey as private key to ssl; SSL_use_RSAPrivateKey() adds rsa as private key of type RSA to ssl. If a certificate has already been set and the private does not belong to the certificate an error is returned. To change a certificate, private key pair the new certificate needs to be set with SSL_use_certificate() or SSL_CTX_use_certificate() before setting the private key with SSL_CTX_use_PrivateKey() or SSL_use_PrivateKey().

SSL_CTX_use_PrivateKey_ASN1() adds the private key of type pk stored at memory location d (length len) to ctx. SSL_CTX_use_RSAPrivateKey_ASN1() adds the private key of type RSA stored at memory location d (length len) to ctx. SSL_use_PrivateKey_ASN1() and SSL_use_RSAPrivateKey_ASN1() add the private key to ssl.

SSL_CTX_use_PrivateKey_file() adds the first private key found in file to ctx. The formatting type of the certificate must be specified from the known types SSL_FILETYPE_PEM, SSL_FILETYPE_ASN1. SSL_CTX_use_RSAPrivateKey_file() adds the first private RSA key found in file to ctx. SSL_use_PrivateKey_file() adds the first private key found in file to ssl; SSL_use_RSAPrivateKey_file() adds the first private RSA key found to ssl.

SSL_CTX_check_private_key() checks the consistency of a private key with the corresponding certificate loaded into ctx. If more than one key/certificate pair (RSA/DSA) is installed, the last item installed will be checked. If e.g. the last item was a RSA certificate or key, the RSA key/certificate pair will be checked. SSL_check_private_key() performs the same check for ssl. If no key/certificate was explicitly added for this ssl, the last item added into ctx will be checked.

Notes

The internal certificate store of OpenSSL can hold two private key/certificate
pairs at a time: one key/certificate of type RSA and one key/certificate
of type DSA. The certificate used depends on the cipher select, see
also L<SSL_CTX_set_cipher_list()|SSL_CTX_set_cipher_list()>.

When reading certificates and private keys from file, files of type SSL_FILETYPE_ASN1 (also known as DER, binary encoding) can only contain one certificate or private key, consequently SSL_CTX_use_certificate_chain_file() is only applicable to PEM formatting. Files of type SSL_FILETYPE_PEM can contain more than one item.

SSL_CTX_use_certificate_chain_file() adds the first certificate found in the file to the certificate store. The other certificates are added to the store of chain certificates using SSL_CTX_add_extra_chain_cert(). There exists only one extra chain store, so that the same chain is appended to both types of certificates, RSA and DSA! If it is not intended to use both type of certificate at the same time, it is recommended to use the SSL_CTX_use_certificate_chain_file() instead of the SSL_CTX_use_certificate_file() function in order to allow the use of complete certificate chains even when no trusted CA storage is used or when the CA issuing the certificate shall not be added to the trusted CA storage.

If additional certificates are needed to complete the chain during the TLS negotiation, CA certificates are additionally looked up in the locations of trusted CA certificates, see SSL_CTX_load_verify_locations().

The private keys loaded from file can be encrypted. In order to successfully load encrypted keys, a function returning the passphrase must have been supplied, see SSL_CTX_set_default_passwd_cb(). (Certificate files might be encrypted as well from the technical point of view, it however does not make sense as the data in the certificate is considered public anyway.)

Return Values

On success, the functions return 1. Otherwise check out the error stack to find out the reason.

See Also

ssl(), SSL_new(), SSL_clear(),
SSL_CTX_load_verify_locations(),
SSL_CTX_set_default_passwd_cb(),
SSL_CTX_set_cipher_list(),
SSL_CTX_set_client_cert_cb(),
SSL_CTX_add_extra_chain_cert()

History

Support for DER encoded private keys (SSL_FILETYPE_ASN1) in SSL_CTX_use_PrivateKey_file() and SSL_use_PrivateKey_file() was added in 0.9.8 .

Feedback

For additional information or queries on this page send feedback


SSL_do_handshake - perform a TLS/SSL handshake

Name

SSL_do_handshake — perform a TLS/SSL handshake

Library

libssl.lib

Synopsis

#include <openssl/ssl.h>
int SSL_do_handshake(SSL *ssl);

Detailed Description

SSL_do_handshake() will wait for a SSL/TLS handshake to take place. If the connection is in client mode, the handshake will be started. The handshake routines may have to be explicitly set in advance using either SSL_set_connect_state() or SSL_set_accept_state().

Notes

The behaviour of SSL_do_handshake() depends on the underlying BIO.

If the underlying BIO is blocking, SSL_do_handshake() will only return once the handshake has been finished or an error occurred, except for SGC (Server Gated Cryptography). For SGC, SSL_do_handshake() may return with -1, but SSL_get_error() will yield SSL_ERROR_WANT_READ/WRITE and SSL_do_handshake() should be called again.

If the underlying BIO is non-blocking, SSL_do_handshake() will also return when the underlying BIO could not satisfy the needs of SSL_do_handshake() to continue the handshake. In this case a call to SSL_get_error() with the return value of SSL_do_handshake() will yield SSL_ERROR_WANT_READ or SSL_ERROR_WANT_WRITE. The calling process then must repeat the call after taking appropriate action to satisfy the needs of SSL_do_handshake(). The action depends on the underlying BIO. When using a non-blocking socket, nothing is to be done, but select() can be used to check for the required condition. When using a buffering BIO, like a BIO pair, data must be written into or retrieved out of the BIO before being able to continue.

Return Values

The following return values can occur:

  1. The TLS/SSL handshake was successfully completed, a TLS/SSL connection has been established.

  2. The TLS/SSL handshake was not successful but was shut down controlled and by the specifications of the TLS/SSL protocol. Call SSL_get_error() with the return value ret to find out the reason.

    <0
    The TLS/SSL handshake was not successful because a fatal error occurred either at the protocol level or a connection failure occurred. The shutdown was not clean. It can also occur of action is need to continue the operation for non-blocking BIOs. Call SSL_get_error() with the return value ret to find out the reason.

See Also

SSL_get_error(),
SSL_connect(),
SSL_accept(), ssl(),
bio(),
SSL_set_connect_state()

Feedback

For additional information or queries on this page send feedback


SSL_free - free an allocated SSL structure

Name

SSL_free — free an allocated SSL structure

Library

libssl.lib

Synopsis

#include <openssl/ssl.h>
void SSL_free(SSL *ssl);

Detailed Description

SSL_free() decrements the reference count of ssl, and removes the SSL structure pointed to by ssl and frees up the allocated memory if the reference count has reached 0.

Notes

SSL_free() also calls the free()ing procedures for indirectly affected items, if applicable: the buffering BIO, the read and write BIOs, cipher lists specially created for this ssl, the SSL_SESSION. Do not explicitly free these indirectly freed up items before or after calling SSL_free(), as trying to free things twice may lead to program failure.

The ssl session has reference counts from two users: the SSL object, for which the reference count is removed by SSL_free() and the internal session cache. If the session is considered bad, because SSL_shutdown() was not called for the connection and SSL_set_shutdown() was not used to set the SSL_SENT_SHUTDOWN state, the session will also be removed from the session cache as required by RFC2246.

Return Values

SSL_free() does not provide diagnostic information.

See Also

SSL_new(), SSL_clear(),
SSL_shutdown(),
SSL_set_shutdown(),
ssl()

Feedback

For additional information or queries on this page send feedback


SSL_get_cipher_list - get list of available SSL_CIPHERs

Name

SSL_get_ciphers, SSL_get_cipher_list — gets list of available SSL_CIPHERs

Library

libssl.lib

Synopsis

#include <openssl/ssl.h>
STACK_OF(SSL_CIPHER) *SSL_get_ciphers(const SSL *ssl);
const char *SSL_get_cipher_list(const SSL *ssl, int priority);

Detailed Description

SSL_get_ciphers() returns the stack of available SSL_CIPHERs for ssl, sorted by preference. If ssl is NULL or no ciphers are available, NULL is returned.

SSL_get_cipher_list() returns a pointer to the name of the SSL_CIPHER listed for ssl with priority. If ssl is NULL, no ciphers are available, or there are less ciphers than priority available, NULL is returned.

Notes

The details of the ciphers obtained by SSL_get_ciphers() can be obtained using the SSL_CIPHER_get_name() family of functions.

Call SSL_get_cipher_list() with priority starting from 0 to obtain the sorted list of available ciphers, until NULL is returned.

Return Values

See Detailed Description

See Also

ssl(),
SSL_CTX_set_cipher_list(),
SSL_CIPHER_get_name()

Feedback

For additional information or queries on this page send feedback


SSL_CTX_get_client_CA_list - get list of client CAs

Name

SSL_get_client_CA_list, SSL_CTX_get_client_CA_list — get list of client CAs

Library

libssl.lib

Synopsis

#include <openssl/ssl.h>
STACK_OF(X509_NAME) *SSL_get_client_CA_list(const SSL *s);
STACK_OF(X509_NAME) *SSL_CTX_get_client_CA_list(const SSL_CTX *ctx);

Detailed Description

SSL_CTX_get_client_CA_list() returns the list of client CAs explicitly set for ctx using SSL_CTX_set_client_CA_list().

SSL_get_client_CA_list() returns the list of client CAs explicitly set for ssl using SSL_set_client_CA_list() or ssl's SSL_CTX object with SSL_CTX_set_client_CA_list(), when in server mode. In client mode, SSL_get_client_CA_list returns the list of client CAs sent from the server, if any.

Return Values

SSL_CTX_set_client_CA_list() and SSL_set_client_CA_list() do not return diagnostic information.

SSL_CTX_add_client_CA() and SSL_add_client_CA() have the following return values:

STACK_OF(X509_NAMES)
List of CA names explicitly set (for ctx or in server mode) or send by the server (client mode).

NULL
No client CA list was explicitly set (for ctx or in server mode) or the server did not send a list of CAs (client mode).

See Also

ssl(),
SSL_CTX_set_client_CA_list(),
SSL_CTX_set_client_cert_cb()

Feedback

For additional information or queries on this page send feedback


SSL_get_cipher_version - get SSL_CIPHER of a connection

Name

SSL_get_current_cipher, SSL_get_cipher
SSL_get_cipher_name, SSL_get_cipher_bits
SSL_get_cipher_version

get SSL_CIPHER of a connection

Library

libssl.lib

Synopsis

#include <openssl/ssl.h>
SSL_CIPHER *SSL_get_current_cipher(const SSL *ssl);
#define SSL_get_cipher(s) \ SSL_CIPHER_get_name(SSL_get_current_cipher(s))
#define SSL_get_cipher_name(s) \ SSL_CIPHER_get_name(SSL_get_current_cipher(s))
#define SSL_get_cipher_bits(s,np) \ SSL_CIPHER_get_bits(SSL_get_current_cipher(s),np)
#define SSL_get_cipher_version(s) \ SSL_CIPHER_get_version(SSL_get_current_cipher(s))

Detailed Description

SSL_get_current_cipher() returns a pointer to an SSL_CIPHER object containing the description of the actually used cipher of a connection established with the ssl object.

SSL_get_cipher() and SSL_get_cipher_name() are identical macros to obtain the name of the currently used cipher. SSL_get_cipher_bits() is a macro to obtain the number of secret/algorithm bits used and SSL_get_cipher_version() returns the protocol name. See SSL_CIPHER_get_name() for more details.

Return Values

SSL_get_current_cipher() returns the cipher actually used or NULL, when no session has been established.

See Also

ssl(), SSL_CIPHER_get_name()

Feedback

For additional information or queries on this page send feedback


SSL_get_default_timeout - get default session timeout value

Name

SSL_get_default_timeout — get default session timeout value

Library

libssl.lib

Synopsis

#include <openssl/ssl.h>
long SSL_get_default_timeout(const SSL *ssl);

Detailed Description

SSL_get_default_timeout() returns the default timeout value assigned to SSL_SESSION objects negotiated for the protocol valid for ssl.

Notes

Whenever a new session is negotiated, it is assigned a timeout value, after which it will not be accepted for session reuse. If the timeout value was not explicitly set using SSL_CTX_set_timeout(), the hard coded default timeout for the protocol will be used.

SSL_get_default_timeout() return this hard coded value, which is 300 seconds for all currently supported protocols (SSLv2, SSLv3, and TLSv1).

Return Values

See Detailed Description.

See Also

ssl(),
SSL_CTX_set_session_cache_mode(),
SSL_SESSION_get_time(),
SSL_CTX_flush_sessions()

Feedback

For additional information or queries on this page send feedback


SSL_get_error - obtain result code for TLS/SSL I/O operation

Name

SSL_get_error — obtain result code for TLS/SSL I/O operation

Library

libssl.lib

Synopsis

#include <openssl/ssl.h>
int SSL_get_error(const SSL *ssl, int ret);

Detailed Description

SSL_get_error() returns a result code (suitable for the C ``switch'' statement) for a preceding call to SSL_connect(), SSL_accept(), SSL_do_handshake(), SSL_read(), SSL_peek(), or SSL_write() on ssl. The value returned by that TLS/SSL I/O function must be passed to SSL_get_error() in parameter ret.

In addition to ssl and ret, SSL_get_error() inspects the current thread's OpenSSL error queue. Thus, SSL_get_error() must be used in the same thread that performed the TLS/SSL I/O operation, and no other OpenSSL function calls should appear in between. The current thread's error queue must be empty before the TLS/SSL I/O operation is attempted, or SSL_get_error() will not work reliably.

Return Values

The following return values can currently occur:

SSL_ERROR_NONE
The TLS/SSL I/O operation completed. This result code is returned if and only if ret > 0.

SSL_ERROR_ZERO_RETURN
The TLS/SSL connection has been closed. If the protocol version is SSL 3.0 or TLS 1.0, this result code is returned only if a closure alert has occurred in the protocol, i.e. if the connection has been closed cleanly. Note that in this case SSL_ERROR_ZERO_RETURN does not necessarily indicate that the underlying transport has been closed.

SSL_ERROR_WANT_READ, SSL_ERROR_WANT_WRITE
The operation did not complete; the same TLS/SSL I/O function should be called again later. If, by then, the underlying BIO has data available for reading (if the result code is SSL_ERROR_WANT_READ) or allows writing data (SSL_ERROR_WANT_WRITE), then some TLS/SSL protocol progress will take place, i.e. at least part of an TLS/SSL record will be read or written. Note that the retry may again lead to a SSL_ERROR_WANT_READ or SSL_ERROR_WANT_WRITE condition. There is no fixed upper limit for the number of iterations that may be necessary until progress becomes visible at application protocol level.

For socket BIOs (e.g. when SSL_set_fd() was used), select() or poll() on the underlying socket can be used to find out when the TLS/SSL I/O function should be retried.

Caveat: Any TLS/SSL I/O function can lead to either of SSL_ERROR_WANT_READ and SSL_ERROR_WANT_WRITE. In particular, SSL_read() or SSL_peek() may want to write data and SSL_write() may want to read data. This is mainly because TLS/SSL handshakes may occur at any time during the protocol (initiated by either the client or the server); SSL_read(), SSL_peek(), and SSL_write() will handle any pending handshakes.

SSL_ERROR_WANT_CONNECT, SSL_ERROR_WANT_ACCEPT
The operation did not complete; the same TLS/SSL I/O function should be called again later. The underlying BIO was not connected yet to the peer and the call would block in connect()/accept(). The SSL function should be called again when the connection is established. These messages can only appear with a BIO_s_connect() or BIO_s_accept() BIO, respectively. In order to find out, when the connection has been successfully established, on many platforms select() or poll() for writing on the socket file descriptor can be used.

SSL_ERROR_WANT_X509_LOOKUP
The operation did not complete because an application callback set by SSL_CTX_set_client_cert_cb() has asked to be called again. The TLS/SSL I/O function should be called again later. Details depend on the application.

SSL_ERROR_SYSCALL
Some I/O error occurred. The OpenSSL error queue may contain more information on the error. If the error queue is empty (i.e. ERR_get_error() returns 0), ret can be used to find out more about the error: If ret == 0, an EOF was observed that violates the protocol. If ret == -1, the underlying BIO reported an I/O error (for socket I/O on Unix systems, consult errno for details).

SSL_ERROR_SSL
A failure in the SSL library occurred, usually a protocol error. The OpenSSL error queue contains more information on the error.

See Also

ssl(), err()

History

SSL_get_error() was added in SSLeay 0.8.

Feedback

For additional information or queries on this page send feedback


SSL_get_ex_data_X509_STORE_CTX_idx - get ex_data index to access SSL structure from X509_STORE_CTX

Name

SSL_get_ex_data_X509_STORE_CTX_idx — get ex_data index to access SSL structure from X509_STORE_CTX

Library

libssl.lib

Synopsis

#include <openssl/ssl.h>
int SSL_get_ex_data_X509_STORE_CTX_idx(void);

Detailed Description

SSL_get_ex_data_X509_STORE_CTX_idx() returns the index number under which the pointer to the SSL object is stored into the X509_STORE_CTX object.

Notes

Whenever a X509_STORE_CTX object is created for the verification of the peers certificate during a handshake, a pointer to the SSL object is stored into the X509_STORE_CTX object to identify the connection affected. To retrieve this pointer the X509_STORE_CTX_get_ex_data() function can be used with the correct index. This index is globally the same for all X509_STORE_CTX objects and can be retrieved using SSL_get_ex_data_X509_STORE_CTX_idx(). The index value is set when SSL_get_ex_data_X509_STORE_CTX_idx() is first called either by the application program directly or indirectly during other SSL setup functions or during the handshake.

The value depends on other index values defined for X509_STORE_CTX objects before the SSL index is created.

Return Values

>=0
The index value to access the pointer.

<0
An error occurred, check the error stack for a detailed error message.

Examples

The index returned from SSL_get_ex_data_X509_STORE_CTX_idx() allows to access the SSL object for the connection to be accessed during the verify_callback() when checking the peers certificate. Please check the example in SSL_CTX_set_verify().

See Also

ssl(),
SSL_CTX_set_verify(),
CRYPTO_set_ex_data()

Feedback

For additional information or queries on this page send feedback


SSL_get_ex_data - internal application specific data functions

Name

SSL_get_ex_new_index, SSL_set_ex_data
SSL_get_ex_data

internal application specific data functions

Library

libssl.lib

Synopsis

#include <openssl/ssl.h>
int SSL_get_ex_new_index(long argl, void *argp, CRYPTO_EX_new *new_func, CRYPTO_EX_dup *dup_func, CRYPTO_EX_free *free_func);
int SSL_set_ex_data(SSL *ssl, int idx, void *arg);
void *SSL_get_ex_data(const SSL *ssl, int idx);
typedef int new_func(void *parent, void *ptr, CRYPTO_EX_DATA *ad, int idx, long argl, void *argp);
typedef void free_func(void *parent, void *ptr, CRYPTO_EX_DATA *ad, int idx, long argl, void *argp);
typedef int dup_func(CRYPTO_EX_DATA *to, CRYPTO_EX_DATA *from, void *from_d, int idx, long argl, void *argp);

Detailed Description

Several OpenSSL structures can have application specific data attached to them. These functions are used internally by OpenSSL to manipulate application specific data attached to a specific structure.

SSL_get_ex_new_index() is used to register a new index for application specific data.

SSL_set_ex_data() is used to store application data at arg for idx into the ssl object.

SSL_get_ex_data() is used to retrieve the information for idx from ssl.

A detailed description for the *_get_ex_new_index() functionality can be found in RSA_get_ex_new_index(). The *_get_ex_data() and *_set_ex_data() functionality is described in CRYPTO_set_ex_data().

Examples

An example on how to use the functionality is included in the example verify_callback() in SSL_CTX_set_verify().

See Also

ssl(),
RSA_get_ex_new_index(),
CRYPTO_set_ex_data(),
SSL_CTX_set_verify()

Feedback

For additional information or queries on this page send feedback


SSL_get_fd - get file descriptor linked to an SSL object

Name

SSL_get_fd — get file descriptor linked to an SSL object

Library

libssl.lib

Synopsis

#include <openssl/ssl.h>
int SSL_get_fd(const SSL *ssl);
int SSL_get_rfd(const SSL *ssl);
int SSL_get_wfd(const SSL *ssl);

Detailed Description

SSL_get_fd() returns the file descriptor which is linked to ssl. SSL_get_rfd() and SSL_get_wfd() return the file descriptors for the read or the write channel, which can be different. If the read and the write channel are different, SSL_get_fd() will return the file descriptor of the read channel.

Return Values

The following return values can occur:

-1
The operation failed, because the underlying BIO is not of the correct type (suitable for file descriptors).

>=0
The file descriptor linked to ssl.

See Also

SSL_set_fd(), ssl() , bio()

Feedback

For additional information or queries on this page send feedback


SSL_get_peer_cert_chain - get the X509 certificate chain of the peer

Name

SSL_get_peer_cert_chain — get the X509 certificate chain of the peer

Library

libssl.lib

Synopsis

#include <openssl/ssl.h>
STACKOF(X509) *SSL_get_peer_cert_chain(const SSL *ssl);

Detailed Description

SSL_get_peer_cert_chain() returns a pointer to STACKOF(X509) certificates forming the certificate chain of the peer. If called on the client side, the stack also contains the peer's certificate; if called on the server side, the peer's certificate must be obtained separately using SSL_get_peer_certificate(). If the peer did not present a certificate, NULL is returned.

Notes

The peer certificate chain is not necessarily available after reusing a session, in which case a NULL pointer is returned.

The reference count of the STACKOF(X509) object is not incremented. If the corresponding session is freed, the pointer must not be used any longer.

Return Values

The following return values can occur:

NULL
No certificate was presented by the peer or no connection was established or the certificate chain is no longer available when a session is reused.

Pointer to a STACKOF(X509)
The return value points to the certificate chain presented by the peer.

See Also

ssl(), SSL_get_peer_certificate()

Feedback

For additional information or queries on this page send feedback


SSL_get_peer_certificate - get the X509 certificate of the peer

Name

SSL_get_peer_certificate — get the X509 certificate of the peer

Library

libssl.lib

Synopsis

#include <openssl/ssl.h>
X509 *SSL_get_peer_certificate(const SSL *ssl);

Detailed Description

SSL_get_peer_certificate() returns a pointer to the X509 certificate the peer presented. If the peer did not present a certificate, NULL is returned.

Notes

Due to the protocol definition, a TLS/SSL server will always send a certificate, if present. A client will only send a certificate when explicitly requested to do so by the server (see SSL_CTX_set_verify()). If an anonymous cipher is used, no certificates are sent.

That a certificate is returned does not indicate information about the verification state, use SSL_get_verify_result() to check the verification state.

The reference count of the X509 object is incremented by one, so that it will not be destroyed when the session containing the peer certificate is freed. The X509 object must be explicitly freed using X509_free().

Return Values

The following return values can occur:

NULL
No certificate was presented by the peer or no connection was established.

Pointer to an X509 certificate
The return value points to the certificate presented by the peer.

See Also

ssl(),
SSL_get_verify_result(),
SSL_CTX_set_verify()

Feedback

For additional information or queries on this page send feedback


SSL_get_rbio - get BIO linked to an SSL object

Name

SSL_get_rbio — get BIO linked to an SSL object

Library

libssl.lib

Synopsis

#include <openssl/ssl.h>
BIO *SSL_get_rbio(SSL *ssl);
BIO *SSL_get_wbio(SSL *ssl);

Detailed Description

SSL_get_rbio() and SSL_get_wbio() return pointers to the BIOs for the read or the write channel, which can be different. The reference count of the BIO is not incremented.

Return Values

The following return values can occur:

NULL
No BIO was connected to the SSL object

Any other pointer
The BIO linked to ssl.

See Also

SSL_set_bio(),
 ssl() ,
bio()

Feedback

For additional information or queries on this page send feedback


SSL_get_session - retrieve TLS/SSL session data

Name

SSL_get_session — retrieve TLS/SSL session data

Library

libssl.lib

Synopsis

#include <openssl/ssl.h>
SSL_SESSION *SSL_get_session(const SSL *ssl);
SSL_SESSION *SSL_get0_session(const SSL *ssl);
SSL_SESSION *SSL_get1_session(SSL *ssl);

Detailed Description

SSL_get_session() returns a pointer to the SSL_SESSION actually used in ssl. The reference count of the SSL_SESSION is not incremented, so that the pointer can become invalid by other operations.

SSL_get0_session() is the same as SSL_get_session().

SSL_get1_session() is the same as SSL_get_session(), but the reference count of the SSL_SESSION is incremented by one.

Notes

The ssl session contains all information required to re-establish the connection without a new handshake.

SSL_get0_session() returns a pointer to the actual session. As the reference counter is not incremented, the pointer is only valid while the connection is in use. If SSL_clear() or SSL_free() is called, the session may be removed completely (if considered bad), and the pointer obtained will become invalid. Even if the session is valid, it can be removed at any time due to timeout during SSL_CTX_flush_sessions().

If the data is to be kept, SSL_get1_session() will increment the reference count, so that the session will not be implicitly removed by other operations but stays in memory. In order to remove the session SSL_SESSION_free() must be explicitly called once to decrement the reference count again.

SSL_SESSION objects keep internal link information about the session cache list, when being inserted into one SSL_CTX object's session cache. One SSL_SESSION object, regardless of its reference count, must therefore only be used with one SSL_CTX object (and the SSL objects created from this SSL_CTX object).

Return Values

The following return values can occur:

NULL
There is no session available in ssl.

Pointer to an SSL
The return value points to the data of an SSL session.

See Also

ssl(),
SSL_free(),
SSL_clear(),
SSL_SESSION_free()

Feedback

For additional information or queries on this page send feedback


SSL_get_SSL_CTX - get the SSL_CTX from which an SSL is created

Name

SSL_get_SSL_CTX — get the SSL_CTX from which an SSL is created

Library

libssl.lib

Synopsis

#include <openssl/ssl.h>
SSL_CTX *SSL_get_SSL_CTX(const SSL *ssl);

Detailed Description

SSL_get_SSL_CTX() returns a pointer to the SSL_CTX object, from which ssl was created with SSL_new().

Return Values

The pointer to the SSL_CTX object is returned.

See Also

ssl(), SSL_new()

Feedback

For additional information or queries on this page send feedback


SSL_get_verify_result - get result of peer certificate verification

Name

SSL_get_verify_result — get result of peer certificate verification

Library

libssl.lib

Synopsis

#include <openssl/ssl.h>
long SSL_get_verify_result(const SSL *ssl);

Detailed Description

SSL_get_verify_result() returns the result of the verification of the X509 certificate presented by the peer, if any.

Notes

SSL_get_verify_result() can only return one error code while the verification of a certificate can fail because of many reasons at the same time. Only the last verification error that occurred during the processing is available from SSL_get_verify_result().

The verification result is part of the established session and is restored when a session is reused.

Bugs

If no peer certificate was presented, the returned result code is X509_V_OK. This is because no verification error occurred, it does however not indicate success. SSL_get_verify_result() is only useful in connection with SSL_get_peer_certificate().

Return Values

The following return values can currently occur:

X509_V_OK
The verification succeeded or no peer certificate was presented.

Any other value
Documented in verify().

See Also

ssl(),
SSL_set_verify_result(),
 SSL_get_peer_certificate(),
verify()

Feedback

For additional information or queries on this page send feedback


SSL_get_version - get the protocol version of a connection.

Name

SSL_get_version — get the protocol version of a connection

Library

libssl.lib

Synopsis

#include <openssl/ssl.h>
const char *SSL_get_version(const SSL *ssl);

Detailed Description

SSL_get_cipher_version() returns the name of the protocol used for the connection ssl.

Return Values

The following strings can occur:

SSLv2
The connection uses the SSLv2 protocol.

SSLv3
The connection uses the SSLv3 protocol.

TLSv1
The connection uses the TLSv1 protocol.

unknown
This indicates that no version has been set (no connection established).

See Also

ssl()

Feedback

For additional information or queries on this page send feedback


SSLeay_add_ssl_algorithms - initialize SSL library by registering algorithms

Name

SSL_library_init, OpenSSL_add_ssl_algorithms
SSLeay_add_ssl_algorithms

initialize SSL library by registering algorithms

Library

libssl.lib

Synopsis

#include <openssl/ssl.h>
int SSL_library_init(void);
#define OpenSSL_add_ssl_algorithms()    SSL_library_init()
#define SSLeay_add_ssl_algorithms()     SSL_library_init()

Detailed Description

SSL_library_init() registers the available ciphers and digests.

OpenSSL_add_ssl_algorithms() and SSLeay_add_ssl_algorithms() are synonyms for SSL_library_init().

Notes

SSL_library_init() must be called before any other action takes place.

Warning

SSL_library_init() only registers ciphers. Another important initialization is the seeding of the PRNG (Pseudo Random Number Generator), which has to be performed separately.

Examples

A typical TLS/SSL application will start with the library initialization, will provide readable error messages and will seed the PRNG.

 SSL_load_error_strings();                /* readable error messages */
 SSL_library_init();                      /* initialize library */
 actions_to_seed_PRNG();

Return Values

SSL_library_init() always returns ``1'', so it is safe to discard the return value.

See Also

ssl(), SSL_load_error_strings(), RAND_add()

Feedback

For additional information or queries on this page send feedback


SSL_load_client_CA_file - load certificate names from file

Name

SSL_load_client_CA_file — load certificate names from file

Library

libssl.lib

Synopsis

#include <openssl/ssl.h>
STACK_OF(X509_NAME) *SSL_load_client_CA_file(const char *file);

Detailed Description

SSL_load_client_CA_file() reads certificates from file and returns a STACK_OF(X509_NAME) with the subject names found.

Notes

SSL_load_client_CA_file() reads a file of PEM formatted certificates and extracts the X509_NAMES of the certificates found. While the name suggests the specific usage as support function for SSL_CTX_set_client_CA_list(), it is not limited to CA certificates.

Examples

Load names of CAs from file and use it as a client CA list:

 SSL_CTX *ctx;
 STACK_OF(X509_NAME) *cert_names;
 ...
 cert_names = SSL_load_client_CA_file("/path/to/CAfile.pem");
 if (cert_names != NULL)
   SSL_CTX_set_client_CA_list(ctx, cert_names);
 else
   error_handling();
 ...

Return Values

The following return values can occur:

NULL
The operation failed, check out the error stack for the reason.

Pointer to STACK_OF(X509_NAME)
Pointer to the subject names of the successfully read certificates.

See Also

ssl(), SSL_CTX_set_client_CA_list()

Feedback

For additional information or queries on this page send feedback


SSL_new - create a new SSL structure for a connection

Name

SSL_new — create a new SSL structure for a connection

Library

libssl.lib

Synopsis

#include <openssl/ssl.h>
SSL *SSL_new(SSL_CTX *ctx);

Detailed Description

SSL_new() creates a new SSL structure which is needed to hold the data for a TLS/SSL connection. The new structure inherits the settings of the underlying context ctx: connection method (SSLv2/v3/TLSv1), options, verification settings, timeout settings.

Return Values

The following return values can occur:

NULL
The creation of a new SSL structure failed. Check the error stack to find out the reason.

Pointer to an SSL structure
The return value points to an allocated SSL structure.

See Also

SSL_free(),
SSL_clear(),
SSL_CTX_set_options(),
SSL_get_SSL_CTX(),
ssl()

Feedback

For additional information or queries on this page send feedback


SSL_pending - obtain number of readable bytes buffered in an SSL object

Name

SSL_pending — obtain number of readable bytes buffered in an SSL object

Library

libssl.lib

Synopsis

#include <openssl/ssl.h>
int SSL_pending(const SSL *ssl);

Detailed Description

SSL_pending() returns the number of bytes which are available inside ssl for immediate read.

Notes

Data are received in blocks from the peer. Therefore data can be buffered inside ssl and are ready for immediate retrieval with SSL_read().

Return Values

The number of bytes pending is returned.

Bugs

SSL_pending() takes into account only bytes from the TLS/SSL record that is currently being processed (if any). If the SSL object's read_ahead flag is set, additional protocol bytes may have been read containing more TLS/SSL records; these are ignored by SSL_pending().

Up to OpenSSL 0.9.6, SSL_pending() does not check if the record type of pending data is application data.

See Also

SSL_read(), ssl()

Feedback

For additional information or queries on this page send feedback


SSL_read - read bytes from a TLS/SSL connection.

Name

SSL_read — read bytes from a TLS/SSL connection

Library

libssl.lib

Synopsis

#include <openssl/ssl.h>
int SSL_read(SSL *ssl, void *buf, int num);

Detailed Description

SSL_read() tries to read num bytes from the specified ssl into the buffer buf.

Notes

If necessary, SSL_read() will negotiate a TLS/SSL session, if not already explicitly performed by SSL_connect() or SSL_accept(). If the peer requests a re-negotiation, it will be performed transparently during the SSL_read() operation. The behaviour of SSL_read() depends on the underlying BIO.

For the transparent negotiation to succeed, the ssl must have been initialized to client or server mode. This is being done by calling SSL_set_connect_state() or SSL_set_accept_state() before the first call to an SSL_read() or SSL_write() function.

SSL_read() works based on the SSL/TLS records. The data are received in records (with a maximum record size of 16kB for SSLv3/TLSv1). Only when a record has been completely received, it can be processed (decryption and check of integrity). Therefore data that was not retrieved at the last call of SSL_read() can still be buffered inside the SSL layer and will be retrieved on the next call to SSL_read(). If num is higher than the number of bytes buffered, SSL_read() will return with the bytes buffered. If no more bytes are in the buffer, SSL_read() will trigger the processing of the next record. Only when the record has been received and processed completely, SSL_read() will return reporting success. At most the contents of the record will be returned. As the size of an SSL/TLS record may exceed the maximum packet size of the underlying transport (e.g. TCP), it may be necessary to read several packets from the transport layer before the record is complete and SSL_read() can succeed.

If the underlying BIO is blocking, SSL_read() will only return, once the read operation has been finished or an error occurred, except when a renegotiation take place, in which case a SSL_ERROR_WANT_READ may occur. This behaviour can be controlled with the SSL_MODE_AUTO_RETRY flag of the SSL_CTX_set_mode() call.

If the underlying BIO is non-blocking, SSL_read() will also return when the underlying BIO could not satisfy the needs of SSL_read() to continue the operation. In this case a call to SSL_get_error() with the return value of SSL_read() will yield SSL_ERROR_WANT_READ or SSL_ERROR_WANT_WRITE. As at any time a re-negotiation is possible, a call to SSL_read() can also cause write operations! The calling process then must repeat the call after taking appropriate action to satisfy the needs of SSL_read(). The action depends on the underlying BIO. When using a non-blocking socket, nothing is to be done, but select() can be used to check for the required condition. When using a buffering BIO, like a BIO pair, data must be written into or retrieved out of the BIO before being able to continue.

Warning

When an SSL_read() operation has to be repeated because of SSL_ERROR_WANT_READ or SSL_ERROR_WANT_WRITE, it must be repeated with the same arguments.

Return Values

The following return values can occur:

>0
The read operation was successful; the return value is the number of bytes actually read from the TLS/SSL connection.

The read operation was not successful. The reason may either be a clean shutdown due to a ``close notify'' alert sent by the peer (in which case the SSL_RECEIVED_SHUTDOWN flag in the ssl shutdown state is set (see SSL_shutdown(), SSL_set_shutdown()). It is also possible, that the peer simply shut down the underlying transport and the shutdown is incomplete. Call SSL_get_error() with the return value ret to find out, whether an error occurred or the connection was shut down cleanly (SSL_ERROR_ZERO_RETURN).

SSLv2 (deprecated) does not support a shutdown alert protocol, so it can only be detected, whether the underlying connection was closed. It cannot be checked, whether the closure was initiated by the peer or by something else.

<0
The read operation was not successful, because either an error occurred or action must be taken by the calling process. Call SSL_get_error() with the return value ret to find out the reason.

See Also

SSL_get_error(),
SSL_write(),
SSL_CTX_set_mode(), SSL_CTX_new(),
SSL_connect(),
SSL_accept(), SSL_set_connect_state(),
SSL_shutdown(),
SSL_set_shutdown(),
ssl(),
bio()

Feedback

For additional information or queries on this page send feedback


SSL_rstate_string_long - get textual description of state of an SSL object during read operation

Name

SSL_rstate_string, SSL_rstate_string_long — get textual description of state of an SSL object during read operation

Library

libssl.lib

Synopsis

#include <openssl/ssl.h>
const char *SSL_rstate_string(SSL *ssl);
const char *SSL_rstate_string_long(SSL *ssl);

Detailed Description

SSL_rstate_string() returns a 2 letter string indicating the current read state of the SSL object ssl.

SSL_rstate_string_long() returns a string indicating the current read state of the SSL object ssl.

Notes

When performing a read operation, the SSL/TLS engine must parse the record, consisting of header and body. When working in a blocking environment, SSL_rstate_string[_long]() should always return "RD''/"read done''.

This function should only seldom be needed in applications.

Return Values

SSL_rstate_string() and SSL_rstate_string_long() can return the following values:

``RH''/``read header''
The header of the record is being evaluated.

``RB''/``read body''
The body of the record is being evaluated.

``RD''/``read done''
The record has been completely processed.

``unknown''/``unknown''
The read state is unknown. This should never happen.

See Also

ssl()

Feedback

For additional information or queries on this page send feedback


SSL_SESSION_free - free an allocated SSL_SESSION structure

Name

SSL_SESSION_free — frees an allocated SSL_SESSION structure

Library

libssl.lib

Synopsis

#include <openssl/ssl.h>
void SSL_SESSION_free(SSL_SESSION *session);

Detailed Description

SSL_SESSION_free() decrements the reference count of session and removes the SSL_SESSION structure pointed to by session and frees up the allocated memory, if the reference count has reached 0.

Notes

SSL_SESSION objects are allocated, when a TLS/SSL handshake operation is successfully completed. Depending on the settings, see SSL_CTX_set_session_cache_mode(), the SSL_SESSION objects are internally referenced by the SSL_CTX and linked into its session cache. SSL objects may be using the SSL_SESSION object; as a session may be reused, several SSL objects may be using one SSL_SESSION object at the same time. It is therefore crucial to keep the reference count (usage information) correct and not delete a SSL_SESSION object that is still used, as this may lead to program failures due to dangling pointers. These failures may also appear delayed, e.g. when an SSL_SESSION object was completely freed as the reference count incorrectly became 0, but it is still referenced in the internal session cache and the cache list is processed during a SSL_CTX_flush_sessions() operation.

SSL_SESSION_free() must only be called for SSL_SESSION objects, for which the reference count was explicitly incremented (e.g. by calling SSL_get1_session(), see SSL_get_session()) or when the SSL_SESSION object was generated outside a TLS handshake operation, e.g. by using d2i_SSL_SESSION(). It must not be called on other SSL_SESSION objects, as this would cause incorrect reference counts and therefore program failures.

Return Values

SSL_SESSION_free() does not provide diagnostic information.

See Also

ssl(),
SSL_get_session(),
SSL_CTX_set_session_cache_mode(),
SSL_CTX_flush_sessions(),
 d2i_SSL_SESSION()

Feedback

For additional information or queries on this page send feedback


SSL_SESSION_get_ex_data - internal application specific data functions

Name

SSL_SESSION_get_ex_new_index, SSL_SESSION_set_ex_data
SSL_SESSION_get_ex_data

internal application specific data functions

Library

libssl.lib

Synopsis

#include <openssl/ssl.h>
int SSL_SESSION_get_ex_new_index(long argl, void *argp, CRYPTO_EX_new *new_func, CRYPTO_EX_dup *dup_func,
                                 CRYPTO_EX_free *free_func);
int SSL_SESSION_set_ex_data(SSL_SESSION *session, int idx, void *arg);
void *SSL_SESSION_get_ex_data(const SSL_SESSION *session, int idx);
typedef int new_func(void *parent, void *ptr, CRYPTO_EX_DATA *ad, int idx, long argl, void *argp);
typedef void free_func(void *parent, void *ptr, CRYPTO_EX_DATA *ad, int idx, long argl, void *argp);
typedef int dup_func(CRYPTO_EX_DATA *to, CRYPTO_EX_DATA *from, void *from_d, int idx, long argl, void *argp);

Detailed Description

Several OpenSSL structures can have application specific data attached to them. These functions are used internally by OpenSSL to manipulate application specific data attached to a specific structure.

SSL_SESSION_get_ex_new_index() is used to register a new index for application specific data.

SSL_SESSION_set_ex_data() is used to store application data at arg for idx into the session object.

SSL_SESSION_get_ex_data() is used to retrieve the information for idx from session.

A detailed description for the *_get_ex_new_index() functionality can be found in RSA_get_ex_new_index(). The *_get_ex_data() and *_set_ex_data() functionality is described in CRYPTO_set_ex_data().

Warnings

The application data is only maintained for sessions held in memory. The application data is not included when dumping the session with i2d_SSL_SESSION() (and all functions indirectly calling the dump functions like PEM_write_SSL_SESSION() and PEM_write_bio_SSL_SESSION()) and can therefore not be restored.

See Also

ssl(),
RSA_get_ex_new_index(),
CRYPTO_set_ex_data()

Feedback

For additional information or queries on this page send feedback


SSL_SESSION_get_timeout - retrieve and manipulate session time and timeout settings

Name

SSL_SESSION_get_time, SSL_SESSION_set_time
SSL_SESSION_get_timeout, SSL_SESSION_set_timeout
SSL_get_time, SSL_set_time
SSL_get_timeout, SSL_set_timeout

retrieve and manipulate session time and timeout settings

Library

libssl.lib

Synopsis

#include <openssl/ssl.h>
long SSL_SESSION_get_time(const SSL_SESSION *s);
long SSL_SESSION_set_time(SSL_SESSION *s, long tm);
long SSL_SESSION_get_timeout(const SSL_SESSION *s);
long SSL_SESSION_set_timeout(SSL_SESSION *s, long tm);
long SSL_get_time(const SSL_SESSION *s);
long SSL_set_time(SSL_SESSION *s, long tm);
long SSL_get_timeout(const SSL_SESSION *s);
long SSL_set_timeout(SSL_SESSION *s, long tm);

Description

SSL_SESSION_get_time() returns the time at which the session s was established. The time is given in seconds since the Epoch and therefore compatible to the time delivered by the time() call.

SSL_SESSION_set_time() replaces the creation time of the session s with the chosen value tm.

SSL_SESSION_get_timeout() returns the timeout value set for session s in seconds.

SSL_SESSION_set_timeout() sets the timeout value for session s in seconds to tm.

The SSL_get_time(), SSL_set_time(), SSL_get_timeout(), and SSL_set_timeout() functions are synonyms for the SSL_SESSION_*() counterparts.

Notes

Sessions are expired by examining the creation time and the timeout value. Both are set at creation time of the session to the actual time and the default timeout value at creation, respectively, as set by SSL_CTX_set_timeout(). Using these functions it is possible to extend or shorten the lifetime of the session.

Return Values

SSL_SESSION_get_time() and SSL_SESSION_get_timeout() return the currently valid values.

SSL_SESSION_set_time() and SSL_SESSION_set_timeout() return 1 on success.

If any of the function is passed the NULL pointer for the session s, 0 is returned.

See Also

 ssl(),
SSL_CTX_set_timeout(),
SSL_get_default_timeout()


SSL_session_reused - query whether a reused session was negotiated during handshake

Name

SSL_session_reused — query whether a reused session was negotiated during handshake

Library

libssl.lib

Synopsis

#include <openssl/ssl.h>
int SSL_session_reused(SSL *ssl);

Description

Query, whether a reused session was negotiated during the handshake.

Notes

During the negotiation, a client can propose to reuse a session. The server then looks up the session in its cache. If both client and server agree on the session, it will be reused and a flag is being set that can be queried by the application.

Return Values

The following return values can occur:

  1. A new session was negotiated.

    3. A session was reused.

See Also

 ssl(),
SSL_set_session(),
SSL_CTX_set_session_cache_mode()

Feedback

For additional information or queries on this page send feedback


SSL_set_bio - connect the SSL object with a BIO

Name

SSL_set_bio — connect the SSL object with a BIO

Library

libssl.lib

Synopsis

#include <openssl/ssl.h>
void SSL_set_bio(SSL *ssl, BIO *rbio, BIO *wbio);

Detailed Description

SSL_set_bio() connects the BIOs rbio and wbio for the read and write operations of the TLS/SSL (encrypted) side of ssl.

The SSL engine inherits the behaviour of rbio and wbio, respectively. If a BIO is non-blocking, the ssl will also have non-blocking behaviour.

If there was already a BIO connected to ssl, BIO_free() will be called (for both the reading and writing side, if different).

Return Values

SSL_set_bio() cannot fail.

See Also

SSL_get_rbio(),
SSL_connect(),
SSL_accept(),
SSL_shutdown(), ssl(),
bio()

Feedback

For additional information or queries on this page send feedback

©2005-2006 Nokia


SSL_get_accept_state - prepare SSL object to work in client or server mode

Name

SSL_set_connect_state, SSL_get_accept_state — prepares SSL object to work in client or server mode

Library

libssl.lib

Synopsis

#include <openssl/ssl.h>
void SSL_set_connect_state(SSL *ssl);
void SSL_set_accept_state(SSL *ssl);

Detailed Description

SSL_set_connect_state() sets ssl to work in client mode.

SSL_set_accept_state() sets ssl to work in server mode.

Notes

When the SSL_CTX object was created with SSL_CTX_new(), it was either assigned a dedicated client method, a dedicated server method, or a generic method, that can be used for both client and server connections. (The method might have been changed with SSL_CTX_set_ssl_version() or SSL_set_ssl_method().)

When beginning a new handshake, the SSL engine must know whether it must call the connect (client) or accept (server) routines. Even though it may be clear from the method chosen, whether client or server mode was requested, the handshake routines must be explicitly set.

When using the SSL_connect() or SSL_accept() routines, the correct handshake routines are automatically set. When performing a transparent negotiation using SSL_write() or SSL_read(), the handshake routines must be explicitly set in advance using either SSL_set_connect_state() or SSL_set_accept_state().

Return Values

SSL_set_connect_state() and SSL_set_accept_state() do not return diagnostic information.

See Also

ssl(),
SSL_new(),
SSL_CTX_new(),
SSL_connect(),
SSL_accept(),
SSL_write(), SSL_read(),
SSL_do_handshake(),
SSL_CTX_set_ssl_version()

Feedback

For additional information or queries on this page send feedback

©2005-2006 Nokia


SSL_set_fd - connect the SSL object with a file descriptor

Name

SSL_set_fd — connect the SSL object with a file descriptor

Library

libssl.lib

Synopsis

#include <openssl/ssl.h>
int SSL_set_fd(SSL *ssl, int fd);
int SSL_set_rfd(SSL *ssl, int fd);
int SSL_set_wfd(SSL *ssl, int fd);

Detailed Description

SSL_set_fd() sets the file descriptor fd as the input/output facility for the TLS/SSL (encrypted) side of ssl. fd will typically be the socket file descriptor of a network connection.

When performing the operation, a socket BIO is automatically created to interface between the ssl and fd. The BIO and hence the SSL engine inherit the behaviour of fd. If fd is non-blocking, the ssl will also have non-blocking behaviour.

If there was already a BIO connected to ssl, BIO_free() will be called (for both the reading and writing side, if different).

SSL_set_rfd() and SSL_set_wfd() perform the respective action, but only for the read channel or the write channel, which can be set independently.

Return Values

The following return values can occur:

    2. The operation failed. Check the error stack to find out why.

    3. The operation succeeded.

See Also

SSL_get_fd(),
SSL_set_bio(),
SSL_connect(),
SSL_accept(),
SSL_shutdown(), ssl() ,bio()

Feedback

For additional information or queries on this page send feedback

©2005-2006 Nokia


SSL_set_session - set a TLS/SSL session to be used during TLS/SSL connect

Name

SSL_set_session — set a TLS/SSL session to be used during TLS/SSL connect

Library

libssl.lib

Synopsis

#include <openssl/ssl.h>
int SSL_set_session(SSL *ssl, SSL_SESSION *session);

Detailed Description

SSL_set_session() sets session to be used when the TLS/SSL connection is to be established. SSL_set_session() is only useful for TLS/SSL clients. When the session is set, the reference count of session is incremented by 1. If the session is not reused, the reference count is decremented again during SSL_connect(). Whether the session was reused can be queried with the SSL_session_reused() call.

If there is already a session set inside ssl (because it was set with SSL_set_session() before or because the same ssl was already used for a connection), SSL_SESSION_free() will be called for that session.

Notes

SSL_SESSION objects keep internal link information about the session cache list, when being inserted into one SSL_CTX object's session cache. One SSL_SESSION object, regardless of its reference count, must therefore only be used with one SSL_CTX object (and the SSL objects created from this SSL_CTX object).

Return Values

The following return values can occur:

  1. The operation failed; check the error stack to find out the reason.

    3. The operation succeeded.

See Also

ssl(),
SSL_SESSION_free(),
SSL_get_session(),
SSL_session_reused(),
SSL_CTX_set_session_cache_mode()

Feedback

For additional information or queries on this page send feedback


SSL_get_shutdown - manipulate shutdown state of an SSL connection

Name

SSL_set_shutdown, SSL_get_shutdown

manipulate shutdown state of an SSL connection

Library

libssl.lib

Synopsis

#include <openssl/ssl.h>
void SSL_set_shutdown(SSL *ssl, int mode);
int SSL_get_shutdown(const SSL *ssl);

Detailed Description

SSL_set_shutdown() sets the shutdown state of ssl to mode.

SSL_get_shutdown() returns the shutdown mode of ssl.

Notes

The shutdown state of an ssl connection is a bitmask of:

  1. No shutdown setting, yet.

    SSL_SENT_SHUTDOWN
    A ``close notify'' shutdown alert was sent to the peer, the connection is being considered closed and the session is closed and correct.

    SSL_RECEIVED_SHUTDOWN
    A shutdown alert was received form the peer, either a normal ``close notify'' or a fatal error.

SSL_SENT_SHUTDOWN and SSL_RECEIVED_SHUTDOWN can be set at the same time.

The shutdown state of the connection is used to determine the state of the ssl session. If the session is still open, when SSL_clear() or SSL_free() is called, it is considered bad and removed according to RFC2246. The actual condition for a correctly closed session is SSL_SENT_SHUTDOWN (according to the TLS RFC, it is acceptable to only send the ``close notify'' alert but to not wait for the peer's answer, when the underlying connection is closed). SSL_set_shutdown() can be used to set this state without sending a close alert to the peer (see SSL_shutdown()).

If a ``close notify'' was received, SSL_RECEIVED_SHUTDOWN will be set, for setting SSL_SENT_SHUTDOWN the application must however still call SSL_shutdown() or SSL_set_shutdown() itself.

Return Values

SSL_set_shutdown() does not return diagnostic information.

SSL_get_shutdown() returns the current setting.

See Also

ssl(),
SSL_shutdown(),
SSL_CTX_set_quiet_shutdown(),
SSL_clear(), SSL_free()

Feedback

For additional information or queries on this page send feedback


SSL_set_verify_result - override result of peer certificate verification

Name

SSL_set_verify_result — override result of peer certificate verification

Library

libssl.lib

Synopsis

#include <openssl/ssl.h>
void SSL_set_verify_result(SSL *ssl, long verify_result);

Detailed Description

SSL_set_verify_result() sets verify_result of the object ssl to be the result of the verification of the X509 certificate presented by the peer, if any.

Notes

SSL_set_verify_result() overrides the verification result. It only changes the verification result of the ssl object. It does not become part of the established session, so if the session is to be reused later, the original value will reappear.

The valid codes for verify_result are documented in verify().

Return Values

SSL_set_verify_result() does not provide a return value.

See Also

ssl(),
SSL_get_verify_result(),
SSL_get_peer_certificate(),
verify()

Feedback

For additional information or queries on this page send feedback


SSL_shutdown - shut down a TLS/SSL connection

Name

SSL_shutdown — shut down a TLS/SSL connection

Library

libssl.lib

Synopsis

#include <openssl/ssl.h>
int SSL_shutdown(SSL *ssl);

Detailed Description

SSL_shutdown() shuts down an active TLS/SSL connection. It sends the ``close notify'' shutdown alert to the peer.

Notes

SSL_shutdown() tries to send the ``close notify'' shutdown alert to the peer. Whether the operation succeeds or not, the SSL_SENT_SHUTDOWN flag is set and a currently open session is considered closed and good and will be kept in the session cache for further reuse.

The shutdown procedure consists of 2 steps: the sending of the ``close notify'' shutdown alert and the reception of the peer's ``close notify'' shutdown alert. According to the TLS standard, it is acceptable for an application to only send its shutdown alert and then close the underlying connection without waiting for the peer's response (this way resources can be saved, as the process can already terminate or serve another connection). When the underlying connection shall be used for more communications, the complete shutdown procedure (bidirectional ``close notify'' alerts) must be performed, so that the peers stay synchronized.

SSL_shutdown() supports both unidirectional and bidirectional shutdown by its 2 step behaviour.

When the application is the first party to send the ``close notify'' alert, SSL_shutdown() will only send the alert and then set the SSL_SENT_SHUTDOWN flag (so that the session is considered good and will be kept in cache). SSL_shutdown() will then return with 0. If a unidirectional shutdown is enough (the underlying connection shall be closed anyway), this first call to SSL_shutdown() is sufficient. In order to complete the bidirectional shutdown handshake, SSL_shutdown() must be called again. The second call will make SSL_shutdown() wait for the peer's ``close notify'' shutdown alert. On success, the second call to SSL_shutdown() will return with 1.
If the peer already sent the ``close notify'' alert and it was already processed implicitly inside another function (SSL_read()), the SSL_RECEIVED_SHUTDOWN flag is set. SSL_shutdown() will send the ``close notify'' alert, set the SSL_SENT_SHUTDOWN flag and will immediately return with 1. Whether SSL_RECEIVED_SHUTDOWN is already set can be checked using the SSL_get_shutdown() (see also SSL_set_shutdown() call.

It is therefore recommended, to check the return value of SSL_shutdown() and call SSL_shutdown() again, if the bidirectional shutdown is not yet complete (return value of the first call is 0). As the shutdown is not specially handled in the SSLv2 protocol, SSL_shutdown() will succeed on the first call.

The behaviour of SSL_shutdown() additionally depends on the underlying BIO.

If the underlying BIO is blocking, SSL_shutdown() will only return once the handshake step has been finished or an error occurred.

If the underlying BIO is non-blocking, SSL_shutdown() will also return when the underlying BIO could not satisfy the needs of SSL_shutdown() to continue the handshake. In this case a call to SSL_get_error() with the return value of SSL_shutdown() will yield SSL_ERROR_WANT_READ or SSL_ERROR_WANT_WRITE. The calling process then must repeat the call after taking appropriate action to satisfy the needs of SSL_shutdown(). The action depends on the underlying BIO. When using a non-blocking socket, nothing is to be done, but select() can be used to check for the required condition. When using a buffering BIO, like a BIO pair, data must be written into or retrieved out of the BIO before being able to continue.

SSL_shutdown() can be modified to only set the connection to ``shutdown'' state but not actually send the ``close notify'' alert messages, see SSL_CTX_set_quiet_shutdown(). When ``quiet shutdown'' is enabled, SSL_shutdown() will always succeed and return 1.

Return Values

The following return values can occur:

  1. The shutdown was successfully completed. The ``close notify'' alert was sent and the peer's ``close notify'' alert was received.

  2. The shutdown is not yet finished. Call SSL_shutdown() for a second time, if a bidirectional shutdown shall be performed. The output of SSL_get_error() may be misleading, as an erroneous SSL_ERROR_SYSCALL may be flagged even though no error occurred.

    -1
    The shutdown was not successful because a fatal error occurred either at the protocol level or a connection failure occurred. It can also occur if action is need to continue the operation for non-blocking BIOs. Call SSL_get_error() with the return value ret to find out the reason.

See Also

SSL_get_error(),
SSL_connect(),
SSL_accept(),
SSL_set_shutdown(),
SSL_CTX_set_quiet_shutdown(),
SSL_clear(),
SSL_free(),
ssl(),
bio()

Feedback

For additional information or queries on this page send feedback


SSL_state_string_long - get textual description of state of an SSL object

Name

SSL_state_string, SSL_state_string_long — get textual description of state of an SSL object

Library

libssl.lib

Synopsis

#include <openssl/ssl.h>
const char *SSL_state_string(const SSL *ssl);
const char *SSL_state_string_long(const SSL *ssl);

Detailed Description

SSL_state_string() returns a 6 letter string indicating the current state of the SSL object ssl.

SSL_state_string_long() returns a string indicating the current state of the SSL object ssl.

Notes

During its use, an SSL objects passes several states. The state is internally maintained. Querying the state information is not very informative before or when a connection has been established. It however can be of significant interest during the handshake.

When using non-blocking sockets, the function call performing the handshake may return with SSL_ERROR_WANT_READ or SSL_ERROR_WANT_WRITE condition, so that SSL_state_string[_long]() may be called.

For both blocking or non-blocking sockets, the details state information can be used within the info_callback function set with the SSL_set_info_callback() call.

Return Values

Detailed description of possible states to be included later.

See Also

ssl(), SSL_CTX_set_info_callback()

Feedback

For additional information or queries on this page send feedback


SSL_want_x509_lookup - obtain state information TLS/SSL I/O operation

Name

SSL_want, SSL_want_nothing
SSL_want_read, SSL_want_write
SSL_want_x509_lookup

obtain state information TLS/SSL I/O operation

Library

libssl.lib

Synopsis

#include <openssl/ssl.h>
int SSL_want(const SSL *ssl);
int SSL_want_nothing(const SSL *ssl);
int SSL_want_read(const SSL *ssl);
int SSL_want_write(const SSL *ssl);
int SSL_want_x509_lookup(const SSL *ssl);

Detailed Description

SSL_want() returns state information for the SSL object ssl.

The other SSL_want_*() calls are shortcuts for the possible states returned by SSL_want().

Notes

SSL_want() examines the internal state information of the SSL object. Its return values are similar to that of SSL_get_error(). Unlike SSL_get_error(), which also evaluates the error queue, the results are obtained by examining an internal state flag only. The information must therefore only be used for normal operation under non-blocking I/O. Error conditions are not handled and must be treated using SSL_get_error().

The result returned by SSL_want() should always be consistent with the result of SSL_get_error().

Return Values

The following return values can currently occur for SSL_want():

SSL_NOTHING
There is no data to be written or to be read.

SSL_WRITING
There are data in the SSL buffer that must be written to the underlying BIO layer in order to complete the actual SSL_*() operation. A call to SSL_get_error() should return SSL_ERROR_WANT_WRITE.

SSL_READING
More data must be read from the underlying BIO layer in order to complete the actual SSL_*() operation. A call to SSL_get_error() should return SSL_ERROR_WANT_READ.

SSL_X509_LOOKUP
The operation did not complete because an application callback set by SSL_CTX_set_client_cert_cb() has asked to be called again. A call to SSL_get_error() should return SSL_ERROR_WANT_X509_LOOKUP.

SSL_want_nothing(), SSL_want_read(), SSL_want_write(), SSL_want_x509_lookup() return 1, when the corresponding condition is true or 0 otherwise.

See Also

ssl(), err(), SSL_get_error()

Feedback

For additional information or queries on this page send feedback


SSL_write - write bytes to a TLS/SSL connection.

Name

SSL_write

Library

libssl.lib

Synopsis

#include <openssl/ssl.h>
int SSL_write(SSL *ssl, const void *buf, int num);

Detailed Description

SSL_write() writes num bytes from the buffer buf into the specified ssl connection.

Notes

If necessary, SSL_write() will negotiate a TLS/SSL session, if not already explicitly performed by SSL_connect() or SSL_accept(). If the peer requests a re-negotiation, it will be performed transparently during the SSL_write() operation. The behaviour of SSL_write() depends on the underlying BIO.

For the transparent negotiation to succeed, the ssl must have been initialized to client or server mode. This is being done by calling SSL_set_connect_state() or SSL_set_accept_state() before the first call to an SSL_read() or SSL_write() function.

If the underlying BIO is blocking, SSL_write() will only return, once the write operation has been finished or an error occurred, except when a renegotiation take place, in which case a SSL_ERROR_WANT_READ may occur. This behaviour can be controlled with the SSL_MODE_AUTO_RETRY flag of the SSL_CTX_set_mode() call.

If the underlying BIO is non-blocking, SSL_write() will also return, when the underlying BIO could not satisfy the needs of SSL_write() to continue the operation. In this case a call to SSL_get_error() with the return value of SSL_write() will yield SSL_ERROR_WANT_READ or SSL_ERROR_WANT_WRITE. As at any time a re-negotiation is possible, a call to SSL_write() can also cause read operations! The calling process then must repeat the call after taking appropriate action to satisfy the needs of SSL_write(). The action depends on the underlying BIO. When using a non-blocking socket, nothing is to be done, but select() can be used to check for the required condition. When using a buffering BIO, like a BIO pair, data must be written into or retrieved out of the BIO before being able to continue.

SSL_write() will only return with success, when the complete contents of buf of length num has been written. This default behaviour can be changed with the SSL_MODE_ENABLE_PARTIAL_WRITE option of SSL_CTX_set_mode(). When this flag is set, SSL_write() will also return with success, when a partial write has been successfully completed. In this case the SSL_write() operation is considered completed. The bytes are sent and a new SSL_write() operation with a new buffer (with the already sent bytes removed) must be started. A partial write is performed with the size of a message block, which is 16kB for SSLv3/TLSv1.

Warning

When an SSL_write() operation has to be repeated because of SSL_ERROR_WANT_READ or SSL_ERROR_WANT_WRITE, it must be repeated with the same arguments.

When calling SSL_write() with num=0 bytes to be sent the behaviour is undefined.

Return Values

The following return values can occur:

>0
The write operation was successful, the return value is the number of bytes actually written to the TLS/SSL connection.

  • The write operation was not successful. Probably the underlying connection was closed. Call SSL_get_error() with the return value ret to find out, whether an error occurred or the connection was shut down cleanly (SSL_ERROR_ZERO_RETURN).

    SSLv2 (deprecated) does not support a shutdown alert protocol, so it can only be detected, whether the underlying connection was closed. It cannot be checked, why the closure happened.

    <0
    The write operation was not successful, because either an error occurred or action must be taken by the calling process. Call SSL_get_error() with the return value ret to find out the reason.

    See Also

    SSL_get_error(),
SSL_read(),
SSL_CTX_set_mode(),
SSL_CTX_new(),
SSL_connect(),
SSL_accept(),
SSL_set_connect_state(),
ssl(),
bio()

    Feedback

    For additional information or queries on this page send feedback


stat

Name

stat, lstat, fstat, __xstat,__lxstat
- get file status

Library

 libc.lib

Synopsis
#include <sys/types.h>
#include <sys/stat.h>
int stat (const char *path, struct stat *sb);
int lstat (const char *path, struct stat *sb);
int fstat (int fd, struct stat *sb);
int __xstat (int version, const char *path, struct stat *sb);
int __lxstat (int version, const char *path, struct stat *sb);

Return values

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

Detailed description

 The stat system call obtains information about the file pointed to by path. Read, write or execute permission of the named file is not required, but all directories listed in the path name leading to the file must be searchable.

The lstat system call is like stat except in the case where the named file is a symbolic link, in which case lstat returns information about the link, while stat returns information about the file the link references.

The fstat system call obtains the same information about an open file known by the file descriptor fd.

The __xstat and __lxstat system calls are exactly similar to stat and lstat functionality.

The sb argument is a pointer to a stat structure as defined by
#include <sys/stat.h>and into which information is placed concerning the file.

The fields of struct stat related to the file system are as follows:
st_dev | The numeric ID of the device containing the file.
st_ino | The file’s inode number.
st_nlink
 | The number of hard links to the file.

The st_dev and st_ino fields together identify the file uniquely within the system.

The time-related fields of struct stat are as follows:
st_atime | Time when file data last accessed. Changed by the .Xr utimes 2, read and readv system calls.
st_mtime | Time when file data last modified. Changed by the mkdir mkfifo mknod utimes write and writev system calls.
st_ctime | Time when file status was last changed (inode data modification). Changed by the chmod chown creat link mkdir mkfifo mknod rename rmdir symlink truncate unlink utimes write and writev system calls.
st_birthtime
 | Time when the inode was created.

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 the struct stat are as follows:
st_size | The file size in bytes.
st_blksize
 | The optimal I/O block size for the file.
st_blocks | The actual number of blocks allocated for the file in 512-byte units. As short symbolic links are stored in the inode, this number may be zero.

The access-related fields of struct stat are as follows:
st_uid | The user ID of the file’s owner.
st_gid | The group ID of the file.
st_mode
 | Status of the file (see below).

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

#include <sys/stat.h,> access and chmod The following macros are available to test whether a st_mode value passed in the m argument corresponds to a file of the specified type: S_ISBLK (m); S_ISCHR (m); S_ISDIR (m); S_ISFIFO (m); S_ISLNK (m); S_ISREG (m); S_ISSOCK (m); S_ISWHT (m);
Test for a block special file.
Test for a character special file.
Test for a directory.
Test for a pipe or FIFO special file.
Test for a symbolic link. NOTE: Inode structure is not supported by symbian and hence link count updation is not possible. Check for symbolic link would always fail because of this reason.
Test for a regular file.
Test for a socket.
Test for a whiteout.

The macros evaluate to a non-zero value if the test is true or to the value 0 if the test is false.

Note: To obtain correct timestamps of FIFOS use fstat instead of stat call.

Examples

/**
 * Detailed description: Sample usage of stat system call
 * Preconditions: Example.txt file should be present in working directory
**/
#include <fcntl.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
int main()
{
  struct stat buf;
   if(stat("Example.txt"  , &buf) < 0 )
   {
      printf("Failed to stat Example.txt \n");
      return -1;
   }
   printf("Stat system call succeeded \n");
   return 0;
 }
/**
 * Detailed description: Sample usage of fstat system call
 *
**/
#include <fcntl.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
int main()
{
  struct stat buf;
   int fd = open("Example.txt" , O_RDONLY | O_CREAT  , 0666);
   if(fstat(fd  , &buf) < 0 )
   {
      printf("Failed to stat Example.txt \n");
      return -1;
   }
   printf("Stat system call succeeded \n");
   close(fd);
   return 0;
 }

Output

Stat system call succeeded

Output

Stat system call succeeded

Errors

 The stat and lstat system calls will fail if:
[EACCES]
 | Search permission is denied for a component of the path prefix.
[EFAULT]
 | The sb or path argument points to an invalid address.
[EIO] | An I/O error occurred while reading from or writing to the file system.
[ELOOP]
 | Too many symbolic links were encountered in translating the pathname.
[ENAMETOOLONG]
 | A component of a pathname exceeded 255 characters, or an entire path name exceeded 1023 characters.
[ENOENT]
 | The named file does not exist.
[ENOTDIR]
 | A component of the path prefix is not a directory.
[EOVERFLOW]
 | The file size in bytes cannot be represented correctly in the structure pointed to by sb.

The fstat system call will fail if:
[EBADF]
 | The fd argument is not a valid open file descriptor.
[EFAULT]
 | The sb argument points to an invalid address.
[EIO] | An I/O error occurred while reading from or writing to the file system.
[EOVERFLOW]
 | The file size in bytes cannot be represented correctly in the structure pointed to by sb.

See also

 access chmod chown utimes symlink

Feedback

For additional information or queries on this page send feedback


strcasecmp

Name

strcasecmp, strncasecmp
- compare two strings ignoring case

Library

 libc.lib

Synopsis
#include <strings.h>
int strcasecmp (const char *s1, const char *s2);
int strncasecmp (const char *s1, const char *s2, size_t len);

Return values

 The strcasecmp and strncasecmp return an integer greater than, equal to, or less than 0, according as s1 is lexicographically greater than, equal to, or less than s2 after translation of each corresponding character to lower-case. The strings themselves are not modified.

Detailed description

 The strcasecmp and strncasecmp functions compare the null-terminated strings s1 and s2. The strcasecmp() function compares the two strings s1 and s2 , ignoring the case of the characters.

The strncasecmp compares at most len characters.

Examples

#include <string.h>
#include <stdio.h>
int main()
{
    int ret;
    ret = strcasecmp("ABC","abc");
    printf("strcasecmp of \"ABC\" \"abc\" is %d\n",ret);
    ret = strcasecmp("abc","abc");
    printf("strcasecmp of \"abc\" \"abc\" is %d\n",ret);
    return 0;
}

Output

strcasecmp of "ABC" "abc" is 0
strcasecmp of "abc" "abc" is 0

See also

 bcmp, memcmp, strcmp, strcoll, strxfrm, tolower

Feedback

For additional information or queries on this page send feedback


strcat

Name

strcat, strncat
- concatenate two strings

Library

 libc.lib

Synopsis
#include <string.h>
char * strcat (char * restrict s, const char * restrict append);
char * strncat (char * restrict s, const char * restrict append, size_t count);

Return values

 The strcat and strncat functions return the pointer s.

Detailed description

 The strcat and strncat functions append a copy of the null-terminated string append to the end of the null-terminated string s, then add a terminating ‘\0.’ The string s must have sufficient space to hold the result.

The strncat function appends not more than count characters from append, and then adds a terminating ‘\0.’

Examples

#include <string.h>
#include <stdio.h>
int main()
{
    char one[50] = {"\0"};
    strcpy(one,"Hello");
    strcat(one," World");
    printf("Concatenated String %s\n",one);
    return 0;
}

Output

Concatenated String Hello World

Security considerations

 The strcat function is easily misused in a manner which enables malicious users to arbitrarily change a running program’s functionality through a buffer overflow attack.

Avoid using strcat. Instead, use strncat or strlcat and ensure that no more characters are copied to the destination buffer than it can hold.

Note that strncat can also be problematic. It may be a security concern for a string to be truncated at all. Since the truncated string will not be as long as the original, it may refer to a completely different resource and usage of the truncated resource could result in very incorrect behavior. Example:

void
foo(const char *arbitrary_string)
{
        char onstack[8];
#if defined(BAD)
        /*
         * This first strcat is bad behavior.  Do not use strcat!
         */
        (void)strcat(onstack, arbitrary_string);        /* BAD! */
#elif defined(BETTER)
        /*
         * The following two lines demonstrate better use of
         * strncat().
         */
        (void)strncat(onstack, arbitrary_string,
            sizeof(onstack) - strlen(onstack) - 1);
#elif defined(BEST)
        /*
         * These lines are even more robust due to testing for
         * truncation.
         */
        if (strlen(arbitrary_string) + 1 >
            sizeof(onstack) - strlen(onstack))
                err(1, "onstack would be truncated");
        (void)strncat(onstack, arbitrary_string,
            sizeof(onstack) - strlen(onstack) - 1);
#endif
}

See also

 bcopy, memcpy, memmove, strcpy

Feedback

For additional information or queries on this page send feedback


strchr

Name

strchr, strrchr
- locate character in string

Library

 libc.lib

Synopsis
#include <string.h>
char * strchr (const char *s, int c);
char * strrchr (const char *s, int c);

Return values

 The functions strchr and strrchr return a pointer to the located character, or NULL if the character does not appear in the string.

Detailed description

 The strchr function locates the first occurrence of c (converted to a char) in the string pointed to by s. The terminating null character is considered part of the string; therefore if c is ‘\0,’ the functions locate the terminating ‘\0.’

The strrchr function is identical to strchr except it locates the last occurrence of c.

Examples

#include <string.h>
#include <stdio.h>
int main()
{
        char one[50];
        char* ret;
        strcpy(one,"abcd");
        ret = strchr("abcd", 'c');
        if(!strncmp(one+2,ret,1)) printf("\ 'c\ ' found in string \"abcd\"\n");
        ret = strchr(one, 'z');
        if(ret == NULL) printf("\ 'z\ ' not found in string \"abcd\"\n");
        return 0;
}

Output

 ’c’ found in string "abcd"
 ’z’ not found in string "abcd"

See also

 memchr, strcspn, strpbrk, strsep, strspn, strstr, strtok

Feedback

For additional information or queries on this page send feedback


strcmp

Name

strcmp, strncmp
- compare two strings

Library

 libc.lib

Synopsis
#include <string.h>
int strcmp (const char *s1, const char *s2);
int strncmp (const char *s1, const char *s2, size_t len);

Return values

 The strcmp and strncmp return an integer greater than, equal to, or less than 0, according as the string s1 is greater than, equal to, or less than the string s2.

Detailed description

 The strcmp and strncmp functions lexicographically compare the null-terminated strings s1 and s2.

The strncmp function compares not more than len characters. Because strncmp is designed for comparing strings rather than binary data, characters that appear after a ‘\0’ character are not compared.

Examples

#include <string.h>
#include <stdio.h>
int main()
{
   char str1[]  = "abcdefg";
   char str2[] =  "abcdefr";
   int result;
   printf( "Compare '%s' to '%s\n", str1, str2 );
   result = strcmp( str1, str2);
   if( result < 0 )
      printf( "str1 is less than str2.\n" );
   else if( result == 0 )
      printf( "str1 is equal to str2.\n" );
   else if( result > 0 )
      printf( "str1 is greater than str2.\n" );
   printf( "Compare '%.6s' to '%.6s\n", str1, str2 );
   result = strncmp( str1, str2, 6 );
   if( result < 0 )
      printf( "str1 is less than str2.\n" );
   else if( result == 0 )
      printf( "str1 is equal to str2.\n" );
   else if( result > 0 )
      printf( "str1 is greater than str2.\n" );
   return 0;
}

Output

Compare ’abcdefg’ to ’abcdefr
str1 is less than str2.
Compare ’abased’ to ’abcdef
str1 is equal to str2.

See also

 bcmp, memcmp, strcasecmp, strcoll, strxfrm

Feedback

For additional information or queries on this page send feedback


strcoll

Name

strcoll
- compare two strings using the current locale

Library

 libc.lib

Synopsis
#include <string.h>
int strcoll (const char *s1, const char *s2);

Detailed description

 The strcoll function lexicographically compares the null-terminated strings s1 and s2 according to the current locale collation if any, otherwise call strcmp, and returns an integer greater than, equal to, or less than 0, according as s1 is greater than, equal to, or less than s2.

Examples

#include <string.h>
#include <stdio.h>
#include <locale.h>
int main()
{
    int res;
    setlocale(LC_ALL,"ar_AE.ISO-8859-6");
    if(strcoll("abcde","abcde")==0)
       printf("Strings are same\n");
    return 0;
}

Output

Strings are same

Return value

 The strcoll() function returns an integer less than, equal to, or greater than zero if s1 is found, respectively, to be less than, to match, or be greater than s2, when both are interpreted as appropriate for the current locale.

See also

 setlocale, strcmp, strxfrm, wcscoll

Feedback

For additional information or queries on this page send feedback


strcpy

Name

strcpy, strncpy
- copy a string

Library

 libc.lib

Synopsis
#include <string.h>
char * stpcpy (char *dst, const char *src);
char * strcpy (char * restrict dst, const char * restrict src);
char * strncpy (char * restrict dst, const char * restrict src, size_t len);

Return values

 The strcpy and strncpy functions return dst. The stpcpy function returns a pointer to the terminating ‘\0’ character of dst.

Detailed description

 The stpcpy and strcpy functions copy the string src to dst (including the terminating ‘\0’ character.)

The strncpy function copies at most len characters from src into dst. If src is less than len characters long, the remainder of dst is filled with ‘\0’ characters. Otherwise, dst is not terminated.

Examples

#include <string.h>
#include <stdio.h>
int main()
{
    char one[50] = {"abcdefgh"};
    printf("String before strcpy %s\n",one);
    strcpy(one,"Hello");
    printf("String after strcpy %s\n",one);
    strncpy(one + 5, " ",1);
    strncpy(one + 6, "World",5);
    printf("String after strncpy %s\n",one);
    return 0;
}

Output

String before strcpy abcdefgh
String after strcpy Hello
String after strncpy Hello World

Examples

 The following sets chararray to "abc\0\0\0:"
char chararray[6];
(void)strncpy(chararray, "abc", sizeof(chararray));

The following sets chararray to "abcdef:"

char chararray[6];
(void)strncpy(chararray, "abcdefgh", sizeof(chararray));

Note that it does not NULL terminate chararray because the length of the source string is greater than or equal to the length argument.

The following copies as many characters from input to buf as will fit and NULL terminates the result. Because strncpy does not guarantee to NULL terminate the string itself, this must be done explicitly.

char buf[1024];
(void)strncpy(buf, input, sizeof(buf) - 1);
buf[sizeof(buf) - 1] = ’\0’;

Security considerations

 The strcpy function is easily misused in a manner which enables malicious users to arbitrarily change a running program’s functionality through a buffer overflow attack.

See also

 bcopy, memcpy, memmove

Feedback

For additional information or queries on this page send feedback


strcspn

Name

strcspn
- search a string for a set of characters

Library

 libc.lib

Synopsis
#include <string.h>
size_t strcspn (const char *s, const char *charset);

Return values

 The strcspn function returns the number of characters spanned.

Detailed description

 The strcspn function spans the initial part of the null-terminated string s as long as the characters from s do not occur in string charset (it spans the complement of charset). In other words, it computes the string array index in s of the first character of s which is also in charset, else the index of the first null character.

Examples

#include <string.h>
#include <stdio.h>
int main()
{
    printf("Number of characters present in s\n which are not in charset is %d",strcspn("abcde","df"));
    return 0;
}

Output

Number of characters present in s
 which are not in charset is 3

See also

 memchr, strchr, strpbrk, strrchr, strsep, strspn, strstr, strtok

Feedback

For additional information or queries on this page send feedback


strdup

Name

strdup - duplicate a string

Library

 libc.lib

Synopsis
#include <string.h>
char * strdup (const char *str);

Detailed description

 The strdup function allocates sufficient memory for a copy of the string str, does the copy, and returns a pointer to it. The pointer may subsequently be used as an argument to the function free.

If insufficient memory is available, NULL is returned and errno is set to ENOMEM.

Examples

#include <string.h>
#include <stdio.h>
int main()
{
    char* ptr;
    ptr = (char *)strdup("abcde");
    printf("Duplicated string %s\n",ptr);
    ptr = (char *)strdup("Hello Hi");
    printf("Duplicated string %s\n",ptr);
    return 0;
}

Output

Duplicated string abcde
Duplicated string Hello Hi

Return value

 The strdup() function returns a pointer to the duplicated string, or NULL if insufficient memory was available.

See also

 free, malloc

Feedback

For additional information or queries on this page send feedback


strerror

Name

perror, strerror, strerror_r, sys_errlist, sys_nerr
- system error messages

Library

 libc.lib

Synopsis
#include <stdio.h>
void perror (const char *string);
extern const char * const sys_errlist[] ; extern const int sys_nerr ;
#include <string.h>
char * strerror (int errnum);
int strerror_r (int errnum, char *strerrbuf, size_t buflen);

Return values

strerror function returns the appropriate error description string, or an unknown error message if the error code is unknown. The value of errno is not changed for a successful call, and is set to a nonzero value upon error. The strerror_r function returns 0 on success and -1 on failure, setting errno.

Detailed description

 The strerror, strerror_r and perror functions look up the error message string corresponding to an error number.

The strerror function accepts an error number argument errnum and returns a pointer to the corresponding message string.

The strerror_r function renders the same result into strerrbuf for a maximum of buflen characters and returns 0 upon success.

The perror function finds the error message corresponding to the current value of the global variable errno and writes it, followed by a newline, to the standard error file descriptor. If the argument string is non- NULL and does not point to the null character, this string is prepended to the message string and separated from it by a colon and space (": "); otherwise, only the error message string is printed.

If the error number is not recognized, these functions return an error message string containing "Unknown error: " followed by the error number in decimal. The strerror and strerror_r functions return EINVAL as a warning. Error numbers recognized by this implementation fall in the range 0 < errnum < sys_nerr.

If insufficient storage is provided in strerrbuf (as specified in buflen) to contain the error string, strerror_r returns ERANGE and strerrbuf will contain an error message that has been truncated and NUL terminated to fit the length specified by buflen.

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. The use of these variables is deprecated; strerror or strerror_r should be used instead.

Examples

#include <string.h>
#include <stdio.h>
#include <errno.h>
int main()
{
    char *ptr = strerror(ERANGE);
    printf("strerror(ERANGE) = %s\n",ptr);
    return 0;
}

Output

strerror(ERANGE) = Numerical result out of range

See also

 intro,
The perror and strerror functions conform to -isoC-99. The strerror_r function conforms to -p1003.1-2001.
The strerror and perror functions first appeared in BSD 4.4 . The strerror_r function was implemented in 4.4 by Wes Peters Aq wes@FreeBSD.org .

Bugs

 For unknown error numbers, the strerror function will return its result in a static buffer which may be overwritten by subsequent calls.

The return type for strerror is missing a type-qualifier; it should actually be const char * .

Programs that use the deprecated sys_errlist variable often fail to compile because they declare it inconsistently.

Feedback

For additional information or queries on this page send feedback


strfmon

Name

strfmon
- convert monetary value to a string

Library

 libc.lib

Synopsis
#include <monetary.h>
ssize_t strfmon (char * restrict s, size_t maxsize, const char * restrict format, ...);

Return values

 If the total number of resulting bytes including the terminating NULL byte is not more than maxsize, strfmon returns the number of bytes placed into the array pointed to by s, not including the terminating NULL byte. Otherwise, -1 is returned, the contents of the array are indeterminate, and errno is set to indicate the error.

Detailed description

 The strfmon function places characters into the array pointed to by s as controlled by the string pointed to by format. No more than maxsize bytes are placed into the array.

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 conversion specification is introduced by the % character. After the %, the following appear in sequence:

  • Zero or more of the following flags:
    = f A '=' character followed by another character f which is used as the numeric fill character.
    ^ Do not use grouping characters, regardless of the current locale default.
    + Represent positive values by prefixing them with a positive sign, and negative values by prefixing them with a negative sign. This is the default.
    ( Enclose negative values in parentheses.
    ! Do not include a currency symbol in the output.
    - Left justify the result. Only valid when a field width is specified.
  • An optional minimum field width as a decimal number. By default, there is no minimum width.
  • A '#' sign followed by a decimal number specifying the maximum expected number of digits after the radix character.
  • A '.' character followed by a decimal number specifying the number the number of digits after the radix character.
  • One of the following conversion specifiers:
    i | The double argument is formatted as an international monetary amount.
    n | The double argument is formatted as a national monetary amount.
    % A '%' character is written.

Examples

#include <string.h>
#include <stdio.h>
#include <monetary.h>
int main()
{
    char buf[50];
    strfmon(buf, sizeof(buf), "[%^=*#6n] [%=*#6i]",1234.567, 1234.567);
    printf("%s\n",buf);
}

Output

[ **1234.57] [ **1234.57]

Errors

 The strfmon function will fail if:
[E2BIG]
 | Conversion stopped due to lack of space in the buffer.
[EINVAL]
 | The format string is invalid.
[ENOMEM]
 | Not enough memory for temporary buffers.

See also

 localeconv

Feedback

For additional information or queries on this page send feedback


strftime

Name

strftime
- format date and time

Library

 libc.lib

Synopsis
#include <time.h>
size_t strftime (char * restrict buf, size_t maxsize, const char * restrict format, const struct tm * restrict timeptr);

Return values

strftime function returns the number of characters placed in the array s, not including the terminating NULL character, provided the string, including the terminating NULL, fits. Otherwise, it returns 0,and the contents of the array is undefined.

Detailed description

 The strftime function formats the information from timeptr into the buffer buf according to the string pointed to by format.

The format string consists of zero or more conversion specifications and ordinary characters. All ordinary characters are copied directly into the buffer. A conversion specification consists of a percent sign "‘%’" and one other character.

No more than maxsize characters will be placed into the array. If the total number of resulting characters, including the terminating NUL character, is not more than maxsize, strftime returns the number of characters in the array, not counting the terminating NUL. Otherwise, zero is returned and the buffer contents are indeterminate.

The conversion specifications are copied to the buffer after expansion as follows:-
%A | is replaced by national representation of the full weekday name.
%a | is replaced by national representation of the abbreviated weekday name.
%B | is replaced by national representation of the full month name.
%b | is replaced by national representation of the abbreviated month name.
%C | is replaced by (year / 100) as decimal number; single digits are preceded by a zero.
%c | is replaced by national representation of time and date.
%D | is equivalent to "%m/%d/%y".
%d | is replaced by the day of the month as a decimal number (01-31).
%E* %O*
 | POSIX locale extensions. The sequences %Ec %EC %Ex %EX %Ey %EY %Od %Oe %OH %OI %Om %OM %OS %Ou %OU %OV %Ow %OW %Oy are supposed to provide alternate representations. Additionally %OB implemented to represent alternative months names (used standalone, without day mentioned).
%e | is replaced by the day of month as a decimal number (1-31); single digits are preceded by a blank.
%F | is equivalent to "%Y-%m-%d".
%G | is replaced by a year as a decimal number with century. This year is the one that 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 digits are preceded by a blank.
%l | is replaced by the hour (12-hour clock) as a decimal number (1-12); single digits are 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 meridiem" 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).
%T | is equivalent to "%H:%M:%S".
%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 decimal number (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 more days in the new year, then it is week 1; otherwise it is the last week of the previous year, 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 decimal number (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.
%z | is replaced by the time zone offset from UTC; a leading plus sign stands for east of UTC, a minus sign for west of UTC, hours and minutes follow with two digits each and no delimiter between them (common form for RFC 822 date headers).
%+ | is replaced by national representation of the date and time (the format is similar to that produced by date).
%-* | GNU libc extension. Do not do any padding when performing numerical outputs.
%_* | GNU libc extension. Explicitly specify space for padding.
%0* | GNU libc extension. Explicitly specify zero for padding.
%% | is replaced by ‘%’.

Examples

#include <string.h>
#include <stdio.h>
#include <time.h>
#include <locale.h>
int main()
{
   struct tm tm;
   char buf[255];
   char *locale;
   locale = setlocale(LC_TIME,"en_GB.ISO-8859-1");
   if( locale != NULL)
   {
       strptime("2001-11-12 18:31:01", "%Y-%m-%d %H:%M:%S", &tm);
       printf("sec = %d min = %d hours = %d \nYear = %d Month = %d day = %d\n",\
       tm.tm_sec,tm.tm_min,tm.tm_hour,tm.tm_year,tm.tm_mon,tm.tm_mday);
       strftime(buf, sizeof(buf), "%d %B %Y %H:%M:%S", &tm);
       puts(buf);
       strptime("Mon","%a", &tm);
       strftime(buf, sizeof(buf), "%a", &tm);
       puts(buf);
    }
    else
       printf("Failed to set locale\n");
}

Output

sec = 1 min = 31 hours = 18
Year = 101 Month = 10 day = 12
12 November 2001 18:31:01
Mon

See also

 printf, ctime, strptime, wcsftime

Feedback

For additional information or queries on this page send feedback


strlcpy

Name

strlcpy ,strlcat
- size-bounded string copying and concatenation

Library

 libc.lib

Synopsis
#include <string.h>
size_t strlcpy (char *dst, const char *src, size_t size);
size_t strlcat (char *dst, const char *src, size_t size);

Return values

 The strlcpy and strlcat functions return the total length of the string they tried to create. For strlcpy that means the length of src. For strlcat that means the initial length of dst plus the length of src. While this may seem somewhat confusing it was done to make truncation detection simple.

Note however, that if strlcat traverses size characters without finding a NUL, the length of the string is considered to be size and the destination string will not be NUL-terminated (since there was no space for the NUL). This keeps strlcat from running off the end of a string. In practice this should not happen (as it means that either size is incorrect or that dst is not a proper "C" string). The check exists to prevent potential security problems in incorrect code.

Detailed description

 The strlcpy and strlcat functions copy and concatenate strings respectively. They are designed to be safer, more consistent, and less error prone replacements for strncpy and strncat. Unlike those functions, strlcpy and strlcat take the full size of the buffer (not just the length) and guarantee to NUL-terminate the result (as long as size is larger than 0 or, in the case of strlcat, as long as there is at least one byte free in dst). Note:include a byte for the NUL in 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 both src and dst must be NUL-terminated.

The strlcpy function copies up to size - 1 characters from the NUL-terminated string src to dst, NUL-terminating the result.

The strlcat function appends the NUL-terminated string src to the end of dst. It will append at most size - strlen(dst) - 1 bytes, NUL-terminating the result.

Examples

 The following code fragment 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 pathname, something like the following might 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 things up 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 the whole purpose of strlcpy and strlcat. As a matter of fact, the first version of this manual page got it wrong.

Examples

#include <string.h>
#include <stdio.h>
int main()
{
    char one[50] = {"abcdefgh"};
    printf("String before strcpy %s\n",one);
    strlcpy(one,"Hello");
    printf("String after strcpy %s\n",one);
    strlcpy(one + 5, " ",1);
    strlcpy(one + 6, "World",5);
    printf("String after strncpy %s\n",one);
    return 0;
}

See also

 snprintf, strncat, strncpy

Feedback

For additional information or queries on this page send feedback


strlen

Name

strlen - calculate the length of a string

Library

 libc.lib

Synopsis
#include <string.h>
size_t strlen (const char *s);

Return values

 The strlen function returns the number of characters that precede the terminating NULL character.

Detailed description

 The strlen function computes the length of the string s.

Examples

#include <string.h>
#include <stdio.h>
int main()
{
    int ret;
    ret = strlen ("");
    printf("strlen of \"\" is %d\n",ret);
    ret = strlen ("a");
    printf("strlen of \"a\" is %d\n",ret);
    ret = strlen ("abcd");
    printf("strlen of \"abcd\" is %d\n",ret);
    return 0;
}

Output

strlen of "" is 0
strlen of "a" is 1
strlen of "abcd" is 4

Security considerations

 The strlen function can be misused if the user passes a string that is not null terminated.

Feedback

For additional information or queries on this page send feedback


strndup

Name

strndup
- save a copy of a string

Library

 libc.lib

Synopsis
#include <string.h>
char * strndup (const char *str, size_t n);

Detailed description

 The strndup function allocates sufficient memory for a copy of the string str, does the copy of at most n characters, and returns a pointer to it. If str is longer than n, only n characters are copied and a terminating NULL is added. The pointer may subsequently be used as an argument to the function free.

If insufficient memory is available, NULL is returned and errno is set to ENOMEM.

Examples

#include <string.h>
#include <stdio.h>
#include <stdlib.h>
int main()
{
    char* ptr;
    ptr = (char *)strndup("abcde",3);
    printf("Duplicated string %s\n",ptr);
    ptr = (char *)strndup("Hello Hi",5);
    printf("Duplicated string %s\n",ptr);
    free(ptr);
    return 0;
}

Output

Duplicated string abc
Duplicated string Hello

Return value

 The strdup() function returns a pointer to the duplicated string, or NULL if insufficient memory was available.

See also

 free, malloc

Feedback

For additional information or queries on this page send feedback


strnlen

Name

strnlen - determine the length of a fixed-size string

Library

 libc.lib

Synopsis
#include <string.h>
size_t strlen (const char *s, size_t maxlen);

Return values

 The strnlen function returns strlen(s), if that is less than maxlen, or maxlen if there is no "\0" character among the first maxlen characters pointed to by s.

Detailed description

 The strnlen function returns the number of characters in the string pointed to by s, not including the terminating "\0" character, but at most maxlen. In doing this, strnlen looks only at the first maxlen characters at s and never beyond s+maxlen. s.

Examples

#include <string.h>
#include <stdio.h>
int main()
{
    char one[50];
    int ret;
    strcpy(one,"abcdef");
    ret = strnlen(one,5);
    printf("Length obtained using strnlen = %d\n",ret);
    ret = strnlen(one,10);
    printf("Length obtained using strnlen = %d\n",ret);
}

Output

Length obtained using strnlen = 5
Length obtained using strnlen = 6

Feedback

For additional information or queries on this page send feedback


strpbrk

Name

strpbrk - search a string for any of a set of characters

Library

 libc.lib

Synopsis
#include <string.h>
char * strpbrk (const char *s, const char *charset);

Detailed description

 The strpbrk function locates in the null-terminated string s the first occurrence of any character in the string charset and returns a pointer to this character. If no characters from charset occur anywhere in s strpbrk returns NULL.

Examples

#include <string.h>
#include <stdio.h>
int main()
{
    char one[50];
    char *res;
    strcpy(one,"acdb");
    res = strpbrk(one, "bc");
    if(res != NULL)
       printf("%s\n",res);
    return 0;
}

Output

cdb

Return value

 The strpbrk() function returns a pointer to the character in s that matches one of the characters in accept, or NULL if no such character is found.

See also

 memchr, strchr, strcspn, strsep, strspn, strstr, strtok

Feedback

For additional information or queries on this page send feedback


strptime

Name

strptime - convert a string representation of time to a time tm structure

Library

 libc.lib

Synopsis
#include <time.h>
char * strptime (const char *restrict buf, const char *restrict format, struct tm *restrict timeptr);

Return values

 Upon successful completion, strptime returns the pointer to the first character in buf that has not been required to satisfy the specified conversions in format. It returns NULL if one of the conversions failed.

Detailed description

 The strptime function parses the string in the buffer buf according to the string pointed to by format, and fills in the elements of the structure pointed to by timeptr. The resulting values will be relative to the local time zone. Thus, it can be considered the reverse operation of strftime.

The format string consists of zero or more conversion specifications and ordinary characters. All ordinary characters are matched exactly with the buffer, where white space in the format string will match any amount of white space in the buffer. All conversion specifications are identical to those described in strftime.

Two-digit year values, including formats %y and %D, are now interpreted as beginning at 1969 per POSIX requirements. Years 69-00 are interpreted in the 20th century (1969-2000), years 01-68 in the 21st century (2001-2068).

If the format string does not contain enough conversion specifications to completely specify the resulting struct tm , the unspecified members of timeptr are left untouched. For example, if format is "%H:%M:%S", only tm_hour, tm_sec and tm_min will be modified. If time relative to today is desired, initialize the timeptr structure with today’s date before passing it to strptime.

Examples

#include <string.h>
#include <stdio.h>
#include <time.h>
#include <locale.h>
int main()
{
    struct tm tm;
    char buf[255];
    char *locale;
    locale = setlocale(LC_TIME,"en_GB.ISO-8859-1");
    if( locale != NULL)
    {
       strptime("2001-11-12 18:31:01", "%Y-%m-%d %H:%M:%S", &tm);
       printf("sec = %d min = %d hours = %d \nYear = %d Month = %d day = %d\n",
       tm.tm_sec,tm.tm_min,tm.tm_hour,tm.tm_year,tm.tm_mon,tm.tm_mday);
       strftime(buf, sizeof(buf), "%d %B %Y %H:%M:%S", &tm);
       puts(buf);
       strptime("Mon","%a", &tm);
       strftime(buf, sizeof(buf), "%a", &tm);
       puts(buf);
    }
    else
    printf("Failed to set locale");
}

Output

sec = 1 min = 31 hours = 18
Year = 101 Month = 10 day = 12
12 November 2001 18:31:01
Mon

See also

 scanf, strftime

Bugs

 Both the %e and %l format specifiers may incorrectly scan one too many digits if the intended values comprise only a single digit and that digit is followed immediately by another digit. Both specifiers accept zero-padded values, even though they are both defined as taking unpadded values.

The %p format specifier has no effect unless it is parsed after hour-related specifiers. Specifying %l without %p will produce undefined results. Note that 12AM (ante meridiem) is taken as midnight and 12PM (post meridiem) is taken as noon.

The %U and %W format specifiers accept any value within the range 00 to 53 without validating against other values supplied (like month or day of the year, for example).

The %Z format specifier only accepts time zone abbreviations of the local time zone, or the value "GMT". This limitation is because of ambiguity due to of the over loading of time zone abbreviations. One such example is EST which is both Eastern Standard Time and Eastern Australia Summer Time.

The strptime function does not correctly handle multibyte characters in the format argument.

Feedback

For additional information or queries on this page send feedback


strsep

Name

strsep - extract token from string

Library

 libc.lib

Synopsis
#include <string.h>
char * strsep (char **stringp, const char *delim);

Return values

strsep function returns a pointer to the token, i.e it returns the original value of *stringp

Detailed description

 The strsep function locates, in the string referenced by *stringp, the first occurrence 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 delimiter character (or NULL, if the end of the string was reached) is stored in *stringp. The original value of *stringp is returned.

An "empty" field (i.e., a character in the string delim occurs as the first character of *stringp) can be detected by comparing the location referenced by the returned pointer to ‘\0’.

If *stringp is initially NULL, strsep returns NULL.

Examples

#include <string.h>
#include <stdio.h>
int main()
{
    char *one=(char *)malloc(12);
    char *res;
    char **two=&one;
    strcpy(one,"Hello,World");
    res=strsep(two,",");
    if(strcmp(res,"hello"))
    printf("%s\n",res);
    return 0;
}

Output

Hello

See also

 memchr, strchr, strcspn, strpbrk, strspn, strstr, strtok

Feedback

For additional information or queries on this page send feedback


strspn

Name

strspn - search a string for a set of characters

Library

 libc.lib

Synopsis
#include <string.h>
size_t strspn (const char *s, const char *charset);

Return values

strspn function returns the number of characters in the initial segment of s which consists only of characters from accept

Detailed description

 The strspn function spans the initial part of the null-terminated string s as long as the characters from s occur in the null-terminated string charset. In other words, it computes the string array index in s of the first character of s which is not in charset, else the index of the first null character.

Examples

#include <string.h>
#include <stdio.h>
int main()
{
    char one[50];
    int res;
    strcpy(one,"abcba");
    res = strspn(one, "abc");
    printf(" %d times characters found in the string \n",res);
    return 0;
}

Output

5 times characters found in the string

Return values

 The strspn function returns the number of characters spanned.

See also

 memchr, strchr, strpbrk, strsep, strstr, strtok

Feedback

For additional information or queries on this page send feedback


strstr

Name

strstr, strcasestr, strnstr
- locate a substring

Library

 libc.lib

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);

Return values

 The strstr function returns a pointer to the beginning of the substring, or NULL if the substring is not found.

Detailed description

 The strstr function locates the first occurrence of the null-terminated string little in 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 string little in the string big, where not more than len characters are searched. Characters that appear after a ‘\0’ character are not searched. Since the strnstr function is a
specific API, it should only be used when portability is not a concern.

Examples

#include <string.h>
#include <stdio.h>
int main()
{
    char *ptr;
    ptr = strstr("abcd", "z");
    if(ptr == NULL)
       printf("strstr: \"z\" not found in \"abcd\"\n");
    else
       printf("strstr: \"z\" found in \"abcd\"\n");
    ptr = strstr("abcd", "ab");
    if(ptr == NULL)
       printf("strstr: \"ab\" not found in \"abcd\"\n");
    else
       printf("strstr: \"ab\" found in \"abcd\"\n");
    ptr = strstr("abcd", "abcde");
    if(ptr == NULL)
       printf("strstr: \"abcde\" found in \"abcd\"\n");
    else
       printf("strstr: \"abbcde\" not found in \"abcd\"\n");
    return 0;
}

Output

strstr: "z" not found in "abcd"
strstr: "ab" found in "abcd"
strstr: "abcde" found in "abcd"

Return values

 If little is an empty string, big is returned; if little occurs nowhere in big, NULL is returned; otherwise a pointer to the first character of the first occurrence of little is returned.

Examples

 The following sets the pointer ptr to the "Bar Baz" portion of largestring:
const char *largestring = "Foo Bar Baz";
const char *smallstring = "Bar";
char *ptr;
ptr = strstr(largestring, smallstring);

The following sets the pointer ptr to NULL, because only the first 4 characters of largestring are searched:

const char *largestring = "Foo Bar Baz";
const char *smallstring = "Bar";
char *ptr;
ptr = strnstr(largestring, smallstring, 4);

See also

 memchr, strchr, strcspn, strpbrk, strrchr, strsep, strspn, strtok
The strstr function conforms to -isoC.

Feedback

For additional information or queries on this page send feedback


strtod

Name

strtod, strtof, strtold
- extract tokens from strings

Library

 libc.lib

Synopsis
#include <stdlib.h>
double strtod (const char * restrict nptr, char ** restrict endptr);
float strtof (const char * restrict nptr, char ** restrict endptr);
long double strtold (const char * restrict nptr, char ** restrict endptr);

Return values

 The strtod, strtof, and strtold functions return the converted value, if any.

If endptr is not NULL, a pointer to the character after the last character used in the conversion is stored in the location referenced by endptr.

If no conversion is performed, zero is returned and the value of nptr is stored in the location referenced by endptr.

If the correct value would cause overflow, plus or minus HUGE_VAL, HUGE_VALF, or HUGE_VALL is returned (according to the sign and type of the return value), and ERANGE is stored in errno. If the correct value would cause underflow, a value whose magnitude is no greater than the smallest normalized positive number in the return type, ( KMinTReal in case of symbian) shall be returned and ERANGE is stored in errno.

Detailed description

 These conversion functions convert the initial portion of the string pointed to by nptr to double , float , and long double representation, respectively.

The expected form of the string is an optional plus (‘‘+’’) or minus sign (‘‘-’’) followed by either:

  • a decimal significand consisting of a sequence of decimal digits optionally containing a decimal-point character, or
  • a hexadecimal significand consisting of a ‘‘0X’’ or ‘‘0x’’ followed by a sequence of hexadecimal digits optionally containing a decimal-point character.

In both cases, the significand may be optionally followed by an exponent. An exponent consists of an ‘‘E’’ or ‘‘e’’ (for decimal constants) or a ‘‘P’’ or ‘‘p’’ (for hexadecimal constants), followed by an optional plus or minus sign, followed by a sequence of decimal digits. For decimal constants, the exponent indicates the power of 10 by which the significand should be scaled. For hexadecimal constants, the scaling is instead done by powers of 2.

Alternatively, if the portion of the string following the optional plus or minus sign begins with ‘‘INFINITY’’ or ‘‘NAN’’, ignoring case, it is interpreted as an infinity or a quiet NaN, respectively.

In any of the above cases, leading white-space characters in the string (as defined by the isspace function) are skipped. The decimal point character is defined in the program’s locale (category LC_NUMERIC).

Examples

#include <stdlib.h>
#include <stdio.h>

int main( void )
{
 char *endpt = NULL;
 double d = 0.0;

 d = strtod("0x00e123bhduitri", &endpt);

 printf("{Expected: 922171.0} %f\n", d);
 printf("{Expected: \"hduitri\"} %s\n", endpt);

 return 0;
}

Output

{Expected: 922171.0} 922171.0
{Expected: "hduitri"} hduitri

Errors
[ERANGE]
Overflow or underflow occurred.

Limitations

 All these functions don’t support the long double length modifiers.

See also

 atof, atoi, atol, strtol, strtoul, wcstod

Feedback

For additional information or queries on this page send feedback


strtok

Name

strtok, strtok_r
- string tokens

Library

 libc.lib

Synopsis
#include <string.h>
char * strtok (char *str, const char *sep);
char * strtok_r (char *str, const char *sep, char **last);

Return values

strtok function returns a pointer to the next token, or NULL if there are no more tokens.

Detailed description

 This interface is obsoleted by strsep.

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 in sep. The first time that strtok is called, str should be specified; subsequent calls, wishing to obtain further tokens from the same string, should pass a null pointer instead. The separator string, sep, must be supplied each time, and may change between calls.

The implementation will behave as if no library function calls strtok.

The strtok_r function is a reentrant version of strtok. The context pointer last must be provided on each call. The strtok_r function may also be used to nest two parsing loops within one another, as long as separate context pointers are used.

The strtok and strtok_r functions return a pointer to the beginning of each subsequent token in the string, after replacing the token itself with a NUL character. When no more tokens remain, a null pointer is returned.

Examples

#include <string.h>
#include <stdio.h>
int main()
{
    char one[50];
    char *res;
    strcpy(one,"Hello,World,Hi");
    res=strtok(one,",");
    if(!strcmp(res,"Hello"))
    printf("%s\n",res);
    res=strtok(NULL,",");
    if(!strcmp(res,"World"))
    printf("%s\n",res);
    return 0;
}

Output

Hello
World

See also

 memchr, strchr, strcspn, strpbrk, strsep, strspn, strstr, wcstok

Bugs

 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 (or empty) delimiter string may return a non- NULL value. Since this implementation always alters the next starting point, such a sequence of calls would always return NULL.

Feedback

For additional information or queries on this page send feedback


strtol

Name

strtol, strtoll, strtoimax, strtoq
- convert a string to a long integer

Library

 libc.lib

Synopsis
#include <stdlib.h>
#include <limits.h>
long strtol (const char * restrict nptr, char ** restrict endptr, int base);
long long strtoll (const char * restrict nptr, char ** restrict endptr, int base);
#include <inttypes.h>
intmax_t strtoimax (const char * restrict nptr, char ** restrict endptr, int base);
#include <sys/types.h>
#include <stdlib.h>
#include <limits.h>
quad_t strtoq (const char *nptr, char **endptr, int base);

Return values

 The strtol, strtoll, strtoimax and strtoq functions return the result of the conversion, unless the value would underflow or overflow. If no conversion could be performed, 0 is returned and the global variable errno is set to EINVAL (the last feature is not portable across all platforms). If an overflow or underflow occurs, errno is set to ERANGE and the function return value is clamped according to the following table.
Function overflow underflow strtol (Ta, Dv, LONG_MIN, Ta, Dv, LONG_MAX);
strtoll (Ta, Dv, LLONG_MIN, Ta, Dv, LLONG_MAX);
strtoimax (Ta, Dv, INTMAX_MIN, Ta, Dv, INTMAX_MAX);
strtoq (Ta, Dv, LLONG_MIN, Ta, Dv, LLONG_MAX);

Detailed description

 The strtol function converts the string in nptr to a long value. The strtoll function converts the string in nptr to a long long value. The strtoimax function converts the string in nptr to an intmax_t value. The strtoq function converts the string in nptr to a quad_t value. The conversion is done according to the given base, 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 by isspace) followed by a single optional ‘+’ or ‘-’ sign. If base is zero or 16, the string may 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 it is taken as 8 (octal).

The remainder of the string is converted to a long , long long , intmax_t or quad_t value in the obvious manner, stopping at the first character which is not a valid digit in the given base. (In bases above 10, the letter ‘A’ in either upper or lower case represents 10, ‘B’ represents 11, and so forth, with ‘Z’ representing 35.)

If endptr is not NULL, strtol stores the address of the first invalid character in *endptr. If there were no digits at all, however, strtol stores the original value of nptr in *endptr. (Thus, if *nptr is not ‘\0’ but **endptr is ‘\0’ on return, the entire string was valid.)

Examples

#include <stdlib.h>
#include <stdio.h>

int main( void )
{
 char *endpt = NULL;
 long l = 0;

 l = strtol("0x1236nvbi", &endpt, 0);

 printf("{Expected: 4662} %ld\n", l);
 printf("{Expected: \"nvbi\"} %s\n", endpt);

 return 0;
}

Output

{Expected: 4662} 4662
{Expected: "nvbi"} nvbi

Errors

[EINVAL]
 | The value of base is not supported or no conversion could be performed (the last feature is not portable across all platforms).
[ERANGE]
 | The given string was out of range; the value converted has been clamped.

See also

 atof, atoi, atol, strtod, strtoul, wcstol

Feedback

For additional information or queries on this page send feedback


strtoul

Name

strtoul, strtoull, strtoumax, strtouq
- convert a string to an unsigned long integer

Library

 libc.lib

Synopsis
#include <stdlib.h>
#include <limits.h>
unsigned long strtoul (const char * restrict nptr, char ** restrict endptr, int base);
unsigned long long strtoull (const char * restrict nptr, char ** restrict endptr, int base);
#include <inttypes.h>
uintmax_t strtoumax (const char * restrict nptr, char ** restrict endptr, int base);
#include <sys/types.h>
#include <stdlib.h>
#include <limits.h>
u_quad_t strtouq (const char *nptr, char **endptr, int base);

Return values

 The strtoul, strtoull, strtoumax and strtouq functions return either the result of the conversion or, if there was a leading minus sign, the negation of the result of the conversion, unless the original (non-negated) value would overflow; in the latter case, strtoul returns ULONG_MAX, strtoull returns ULLONG_MAX, strtoumax returns UINTMAX_MAX, and strtouq returns ULLONG_MAX. In all cases, errno is set to ERANGE. If no conversion could be performed, 0 is returned and the global variable errno is set to EINVAL (the last feature is not portable across all platforms).

Detailed 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 long value. The strtoumax function converts the string in nptr to an uintmax_t value. The strtouq function converts the string in nptr to a u_quad_t value. The conversion is done according to the given base, 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 by isspace) followed by a single optional ‘+’ or ‘-’ sign. If base is zero or 16, the string may 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 it is taken as 8 (octal).

The remainder of the string is converted to an unsigned long value in the obvious manner, stopping at the end of the string or at the first character that does not produce a valid digit in the given base. (In bases above 10, the letter ‘A’ in either upper or lower case represents 10, ‘B’ represents 11, and so forth, with ‘Z’ representing 35.)

If endptr is not NULL, strtoul stores the address of the first invalid character in *endptr. If there were no digits at all, however, strtoul stores the original value of nptr in *endptr. (Thus, if *nptr is not ‘\0’ but **endptr is ‘\0’ on return, the entire string was valid.)

Examples

#include <stdlib.h>
#include <stdio.h>

int main( void )
{
 char *endpt = NULL;
 unsigned long ul = 0;

 ul = strtoul("435435hmnb", &endpt, 12);

 printf("{Expected: 1066793} %ld\n", ul);
 printf("{Expected: \"hmnb\"} %s\n", endpt);

 return 0;
}

Output

{Expected: 1066793} 1066793
{Expected: "hmnb"} hmnb

Errors

[EINVAL]
 | The value of base is not supported or no conversion could be performed (the last feature is not portable across all platforms).
[ERANGE]
 | The given string was out of range; the value converted has been clamped.

See also

 strtol, wcstoul

Feedback

For additional information or queries on this page send feedback


strxfrm

Name

strxfrm - string transformation

Library

 libc.lib

Synopsis
#include <string.h>
size_t strxfrm (char * restrict dst, const char * restrict src, size_t n);

Return values

 Upon successful completion, strxfrm returns the length of the transformed string not including the terminating null character. If this value is n or more, the contents of dst are indeterminate.

Detailed description

 The strxfrm function transforms a null-terminated string pointed to by src according to the current locale collation if any, then copies the transformed string into dst. Not more than n characters are copied into dst, including the terminating null character added. If n is set to 0 (it helps to determine an actual size needed for transformation), dst is permitted to be a NULL pointer.

Comparing two strings using strcmp after strxfrm is equal to comparing two original strings with strcoll.

Examples

#include <string.h>
#include <stdio.h>
int main()
{
    char src2[20] = "abc";
    char dst1[20] = {’\0’};
    char src1[20] = "abc";
    char dst2[20] = {’\0’};
    int retx1;
    int retx2;
    int retc;
    retx1 = strxfrm(dst1,src1,strlen(src1));
    retx2 = strxfrm(dst2,src2,strlen(src2));
    if((retc = strcmp(dst1,dst2))== 0)
        printf("Strings are same\n");
}

Output

Strings are same

See also

 setlocale, strcmp, strcoll, wcsxfrm
The strxfrm function conforms to -isoC.

Feedback

For additional information or queries on this page send feedback


swab

Name

swab
- swap adjacent bytes

Library

 libc.lib

Synopsis
#include <unistd.h>
void swab (const void * restrict src, void * restrict dst, ssize_t len);

Detailed description

 The function swab copies len bytes from the location referenced by src to the location referenced by dst, swapping adjacent bytes.

The argument len must be an even number.

Examples

#include <string.h>
#include <stdio.h>
int main()
{
    int i=0x00003366,j=0x0;
    swab((void *)&i,(void *)&j,2);
    if(j==0x6633)
       printf("Ouput val = %#x\n",j);
    return 0;
}

Output

Ouput val = 0x6633

See also

 bzero, memset

Feedback

For additional information or queries on this page send feedback


symlink

Name

symlink - make a new name for a file

Library

 libc.lib

Synopsis
#include <unistd.h>
int symlink (const char *name1, const char *name2);

Return values

 Upon successful completion, 0 shall be returned. Otherwise, -1 shall be returned and errno set to indicate the error.

Detailed 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 arbitrary path name; it is expected the files can be on the different file system, but since the platform does not support multiple file system, symlink behaviour is exactly similar to link API and symlink on directories are not supported. symlink on a existing link file is not supported. Creation time stamp of the file is not supported, accesstime stamp is equal to modification time stamp. Newly created file will not alter the time stamp of parent directory.

Examples

/*
* Detailed description  : Example to create symlink to a file.
* Precondition : "Parent.txt" should exist in c: drive.
* Remarks      : Symlink behaviour is exactly similar to link api.
*/
#include <unistd.h>
#include <stdio.h>
int main(void)
 {
    if(symlink("C:\\Parent.txt","C:\\Link") < 0)
    {
         printf("simulated link creation to parent file failed\n");
         return -1  ;
    }
    printf("simulated link to parent file created");
    return 0 ;
 }

Output

simulated link to parent file created.

Errors

 The link system call will fail and no link will be created if:
[ENOENT]
 | A component of either path prefix does not exist.
[ENAMETOOLONG]
 | A component or an entire path name exceeded 255 characters.
[ENOENT]
 | A relative path was encountered in translating name2 and is not supported by the platform.
[EINVAL]
 | A relative path was encountered in translating name1 and is not supported by the platform.
[ENOENT]
 | An empty path was encountered in translating one of the pathnames.
[ELOOP]
 | Too many symbolic links were encountered in translating one of the pathnames.
[ELOOP]
 | name2 itself is a link type file.
[ENOENT]
 | The file named by name1 does not exist.
[EEXIST]
 | The link named by name2 does exist.

See also

 link, lstat, readlink, unlink, symlink

Feedback

For additional information or queries on this page send feedback


sync

Name

sync - commit buffer cache to disk

Library

 libc.lib

Synopsis
#include <unistd.h>
void sync (void);

Detailed description

 The sync system call forces a write of dirty (modified) buffers in the block buffer cache out to disk. The kernel keeps this information in core to reduce the number of disk I/O transfers required by the system. As information in the cache is lost after a system crash, a sync system call is issued frequently by the user process syncer (about every 30 seconds).

The fsync system call may be used to synchronize individual file descriptor attributes.

Examples

/**
 * This sample code demonstrates usage of sync system call
 *
**/
#include <unistd.h>
#include <stdio.h>
int main()
{
  sync()  ;
  printf("sync system call flused all dirty buffers 0) ;
  return 0 ;
}

Output

sync system call flused all dirty buffers

See also

 fsync, syncer, sync

Bugs

 The sync system call may return before the buffers are completely flushed.

Feedback

For additional information or queries on this page send feedback


sysconf

Name

sysconf - Get configuration information at runtime

Library

 libc.lib

Synopsis
#include <unistd.h>
long sysconf (int name);

Return values

 If the call to sysconf is not successful, -1 is returned and errno is set appropriately. Otherwise, if the variable is associated with functionality that is not supported, -1 is returned and errno is not modified. Otherwise, the current variable value is returned.

Detailed description

 This interface is defined by -p1003.1-88. A far more complete interface is available using sysctl.

The sysconf function provides a method for applications to determine the current value of a configurable system limit or option variable. The name argument specifies the system variable to be queried. Symbolic constants for each name value are found in the include file
#include <unistd.h .>Shell programmers who need access to these parameters should use the getconf utility.

The available values are as follows:

_SC_ARG_MAX
 | The maximum number of argument to execve.
_SC_CHILD_MAX
 | The maximum number of simultaneous processes per user id.(Not supported)
_SC_CLK_TCK
 | The frequency of the statistics clock in ticks per second.
_SC_IOV_MAX
 | The maximum number of elements in the I/O vector used by readv, writev, recvmsg, and sendmsg.
_SC_NGROUPS_MAX
 | The maximum number of supplemental groups.(Not supported)
_SC_NPROCESSORS_CONF
 | The number of processors configured.(Not supported)
_SC_NPROCESSORS_ONLN
 | The number of processors currently online.(Not supported)
_SC_OPEN_MAX
 | The maximum number of open files per user id.(Not supported)
_SC_STREAM_MAX
 | The minimum maximum number of streams that a process may have open( Not supported) at any one time.
_SC_TZNAME_MAX
 | The minimum maximum number of types supported for the name of a timezone.(Not supported)
_SC_JOB_CONTROL
 | Return 1 if job control is available on this system, otherwise -1.
_SC_SAVED_IDS
 | Returns 1 if saved set-group and saved set-user ID is available, otherwise -1.(Not supported)
_SC_VERSION
 | The version of -p1003.1 with which the system attempts to comply.(Not supported)
_SC_BC_BASE_MAX
 | The maximum ibase/obase values in the bc utility.(Not supported)
_SC_BC_DIM_MAX
 | The maximum array size in the bc utility.(Not supported)
_SC_BC_SCALE_MAX
 | The maximum scale value in the bc utility.(Not supported)
_SC_BC_STRING_MAX
 | The maximum string length in the bc utility.(Not supported)
_SC_COLL_WEIGHTS_MAX
 | The maximum number of weights that can be assigned to any entry of the LC_COLLATE order keyword in the locale definition file.(Not supported)
_SC_EXPR_NEST_MAX
 | The maximum number of expressions that can be nested within parenthesis by the expr utility.(Not supported)
_SC_LINE_MAX
 | The maximum length in bytes of a text-processing utility’s input line.(Not supported)
_SC_RE_DUP_MAX
 | The maximum number of repeated occurrences of a regular expression permitted when using interval notation.(Not supported)
_SC_2_VERSION
 | The version of -p1003.2 with which the system attempts to comply.( Not supported)
_SC_2_C_BIND
 | Return 1 if the system’s C-language development facilities support the C-Language Bindings Option, otherwise -1.
_SC_2_C_DEV
 | Return 1 if the system supports the C-Language Development Utilities Option, otherwise -1.
_SC_2_CHAR_TERM
 | Return 1 if the system supports at least one terminal type capable of all operations described in -p1003.2, otherwise -1.
_SC_2_FORT_DEV
 | Return 1 if the system supports the FORTRAN Development Utilities Option, otherwise -1.
_SC_2_FORT_RUN
 | Return 1 if the system supports the FORTRAN Runtime Utilities Option, otherwise -1.
_SC_2_LOCALEDEF
 | Return 1 if the system supports the creation of locales, otherwise -1.
_SC_2_SW_DEV
 | Return 1 if the system supports the Software Development Utilities Option, otherwise -1.
_SC_2_UPE
 | Return 1 if the system supports the User Portability Utilities Option, otherwise -1.
_SC_PAGESIZE
 | Returns size of a page in bytes. (Some systems use PAGE_SIZE instead.) Note: Some of the return values may not be posix compliant.

Examples

/**
 *  Detailed description  : This test code demonstrates usage of sysconf system call , here it get max command
    line arguments that can be passed to process.
**/
#include <unistd.h>
int main()
{
  int ret = 0 ;
  ret = sysconf(_SC_ARG_MAX) ;
  if(ret < 0 )  {
    printf("Sysconf call failed \n") ;
    return -1 ;
 }
 printf("Max command line arguments = %d \n" , ret) ;
 return 0 ;
}

Output

max-number of commandline args supproted by system.

Errors

 The sysconf function may fail and set errno for any of the errors specified for the library function sysctl. In addition, the following error may be reported:
[EINVAL]
The value of the name argument is invalid.

See also

 pathconf, confstr,

Bugs

 The value for _SC_STREAM_MAX is a minimum maximum, and required to be the same as ANSI C’s FOPEN_MAX, so the returned value is a ridiculously small and misleading number.

Feedback

For additional information or queries on this page send feedback


system

Name

system - execute a shell command

Library

 libc.lib

Synopsis
#include <stdlib.h>
int system (const char *string);

Return values

 The system function returns the exit status of the child process as returned by process exit reason or -1 if an error occurred when spawning a new process. It returns zero when a NULL is passed as its argument.

Detailed description

 The system function spawns another process with the argument string. The calling process waits for the child process to finish executing.

If string is a NULL pointer, system will return non-zero to indicate that system is suporrted and zero if it is not supported.

The system function returns the exit status of the child process as returned by process’ exit reason or -1 if an error occurred when spawning a new process.

Examples

#include <stdlib.h> //system
#include <stdio.h> //printf

int main( void )
{
   int retVal = -1;

   printf( "Calling system()...\n" );

   /* helloworld.exe is an executable that just prints
    * "Hello world!" and it should be created before
    * executing this example code.
    */
   retVal = system("c:\\sys\\bin\\helloworld.exe");

   /* Print the return value of system() */
   printf( "system() returned: %d", retVal );

   return 0;
}

Output

Calling system()...
system() returned: -1

See also

 popen

Feedback

For additional information or queries on this page send feedback


tan

Name

tan, tanf, tanl
- tangent functions

Library

 libm.lib

Synopsis
#include <math.h>
double tan (double x);
float tanf (float x);
long double tanl (long double x);

Return values

 The tan function returns the tangent value.

Detailed description

 The tan and tanf functions compute the tangent of x (measured in radians). A large magnitude argument may yield a result with little or no significance. The function tanl is an alias to the function tan

Examples

#include <math.h>
int main( )
{
   double pi_by_4 = 0.7853981633974483096156608458198757;
   double y;
   y = tan( pi_by_4 );
   printf( "tan( %f)  = %f\n", pi_by_4,  y );
   y = tanf( pi_by_4);
   printf( "tanf( %f) = %f\n", pi_by_4, y );
   y = tanl( pi_by_4);
   printf( "tanl( %f) = %f\n\n", pi_by_4, y );
}

Output

tan ( 0.7853981633974483096156608458198757 ) = 1.000000
tanf( 0.7853981633974483096156608458198757 ) = 1.000000
tanl( 0.7853981633974483096156608458198757; ) =1.000000

See also

 acos, asin, atan, atan2, cos, cosh, math, sin, sinh, tanh

Feedback

For additional information or queries on this page send feedback


tanh

Name

tanh, tanhf, tanhl
- hyperbolic tangent functions

Library

 libm.lib

Synopsis
#include <math.h>
double tanh (double x);
float tanhf (float x);
long double tanhl (long double x);

Return values

 The tanh, tanhf and tanhl functions return the hyperbolic tangent value.

Detailed description

 The tanh and tanhf functions compute the hyperbolic tangent of x. tanhl is an alias to the function tanh.

Examples

#include <math.h>
int main( )
{
   double inp = 1.0;
   double y;
   y = tanh( inp );
   printf( "tanh( %f)  = %f\n", inp,  y );
   y = tanhf( inp);
   printf( "tanhf( %f) = %f\n", inp, y );
   y = tanhl( inp);
   printf( "tanhl( %f) = %f\n\n", inp, y );
   inp = 2209.0;
   y = sqrt( inp);
   printf( "sqrt( %f)  = %d\n", inp,  y );
   y = sqrtf( inp);
   printf( "sqrtf( %f) = %d\n", inp, y );
   y = sqrtl( inp);
   printf( "sqrtl( %f) = %d\n", inp, y );
}

Output

tanh ( 1.000000 ) = 0.7615941
tanhf( 1.000000 ) = 0.7615941
tanhl( 1.000000 ) = 0.7615941

See also

 acos, asin, atan, atan2, cos, cosh, math, sin, sinh, tan

Feedback

For additional information or queries on this page send feedback


telldir

Name

opendir, readdir, readdir_r, telldir, seekdir, rewinddir, closedir, dirfd
- directory operations

Library

 libc.lib

Synopsis
#include <sys/types.h>
#include <dirent.h>
DIR * opendir (const char *filename);
struct dirent * readdir (DIR *dirp);
int readdir_r (DIR *dirp, struct dirent *entry, struct dirent **result);
long telldir (DIR *dirp);
void seekdir (DIR *dirp, long loc);
void rewinddir (DIR *dirp);
int closedir (DIR *dirp);
int dirfd (DIR *dirp);

Return values

closedir function returns 0 on success or -1 on failure.

Detailed description

 The opendir function opens the directory named by filename, associates a directory stream with it and returns a pointer to be used to identify the directory stream in subsequent operations. The pointer NULL is returned if filename cannot be accessed, or if it cannot malloc enough memory to hold the whole thing.

The readdir function returns a pointer to the next directory entry. It returns NULL upon reaching the end of the directory or detecting an invalid seekdir operation.

The readdir_r function provides the same functionality as readdir, but the caller must provide a directory entry buffer to store the results in. If the read succeeds, result is pointed at the entry; upon reaching the end of the directory result is set to NULL. The readdir_r function returns 0 on success or an error number to indicate failure.

The telldir function returns the current location associated with the named directory stream. Values returned by telldir are good only for the lifetime of the DIR pointer, dirp, from which they are derived. If the directory is closed and then reopened, prior values returned by telldir will no longer be valid.

The seekdir function sets the position of the next readdir operation on the directory stream. The new position reverts to the one associated with the directory stream when the telldir operation was performed.

The rewinddir function resets the position of the named directory stream to the beginning of the directory.

The closedir function closes the named directory stream and frees the structure associated with the dirp pointer, returning 0 on success. On failure, -1 is returned and the global variable errno is set to indicate the error.

The dirfd function returns the integer file descriptor associated with the named directory stream, see open.

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;

Examples

#include <dirent.h>
void  telldirTest()
    {
      //declare the variables for dir pointer and dir position.
      DIR  *dirp;
      long dirpos;
        // Open the directory
        dirp = opendir(“\home\manjus\GETTEXT”);
        if(dirp != NULL)
        {
                //read the directory.
                readdir(dirp);
                readdir(dirp);
                //get the dirp pointer position by calling telldir API.
                dirpos = telldir(dirp);
                //print the position of the dirp pointer.
                Printf(“dirp is pointing at position %ld. \n”,dirpos);
        }
    }

Output

Dirp is pointing at position 2.

See also

 close, lseek, open, read,
The opendir, readdir, telldir, seekdir, rewinddir, closedir, and dirfd functions appeared in BSD 4.2 .

Feedback

For additional information or queries on this page send feedback


textdomain

Name

textdomain - sets the domain for the gettext() calls that follow.

Library

libintl.lib

Synopsis

#include <libintl.h>

char * textdomain(const char *domainname);

Return values

On success, returns the current message domain after changing it. Do not modify or free the returned string as it is valid till the next textdomain call.
On failure, it returns NULL and sets the errno to indicate the error.

Detailed description

The textdomain() function sets or retrieves the current message domain name.

If the argument domainname is not NULL, it sets the argument domainname as the current message domain. Internally, it stores a copy the argument domainname.

If the argument domainname is NULL, it returns the current message domain.

Errors

The following error can occur:

ENOMEM Memory available is insufficient

Feedback

For additional information or queries on this page send feedback

© 2006-2007 Nokia


CRYPTO_lock - OpenSSL thread support

Name

CRYPTO_set_locking_callback, CRYPTO_set_id_callback
CRYPTO_num_locks, CRYPTO_set_dynlock_create_callback
CRYPTO_set_dynlock_lock_callback, CRYPTO_set_dynlock_destroy_callback
CRYPTO_get_new_dynlockid, CRYPTO_destroy_dynlockid
CRYPTO_lock

OpenSSL thread support

Library

libcrypto.lib

Synopsis

#include <openssl/crypto.h>
void CRYPTO_set_locking_callback(void (*locking_function)(int mode, int n, const char *file, int line));
void CRYPTO_set_id_callback(unsigned long (*id_function)(void));
 int CRYPTO_num_locks(void);
/* struct CRYPTO_dynlock_value needs to be defined by the user */
struct CRYPTO_dynlock_value;
void CRYPTO_set_dynlock_create_callback(struct CRYPTO_dynlock_value *
        (*dyn_create_function)(char *file, int line));
void CRYPTO_set_dynlock_lock_callback(void (*dyn_lock_function)(int mode, struct CRYPTO_dynlock_value *l, const char *file, int line));
void CRYPTO_set_dynlock_destroy_callback(void (*dyn_destroy_function)(struct CRYPTO_dynlock_value *l, const char *file, int line));
int CRYPTO_get_new_dynlockid(void);
void CRYPTO_destroy_dynlockid(int i);
void CRYPTO_lock(int mode, int n, const char *file, int line);
#define CRYPTO_w_lock(type)    \ CRYPTO_lock(CRYPTO_LOCK|CRYPTO_WRITE,type,__FILE__,__LINE__)
#define CRYPTO_w_unlock(type)  \ CRYPTO_lock(CRYPTO_UNLOCK|CRYPTO_WRITE,type,__FILE__,__LINE__)
#define CRYPTO_r_lock(type)    \ CRYPTO_lock(CRYPTO_LOCK|CRYPTO_READ,type,__FILE__,__LINE__)
#define CRYPTO_r_unlock(type)  \ CRYPTO_lock(CRYPTO_UNLOCK|CRYPTO_READ,type,__FILE__,__LINE__)
#define CRYPTO_add(addr,amount,type)   \ CRYPTO_add_lock(addr,amount,type,__FILE__,__LINE__)

Detailed Description

OpenSSL can safely be used in multi-threaded applications provided that at least two callback functions are set.

locking_function(int mode, int n, const char *file, int line) is needed to perform locking on shared data structures. (Note that OpenSSL uses a number of global data structures that will be implicitly shared whenever multiple threads use OpenSSL.) Multi-threaded applications will crash at random if it is not set.

locking_function() must be able to handle up to CRYPTO_num_locks() different mutex locks. It sets the n-th lock if mode & CRYPTO_LOCK, and releases it otherwise.

file and line are the file number of the function setting the lock. They can be useful for debugging.

id_function(void) is a function that returns a thread ID, for example pthread_self() if it returns an integer (see NOTES below). It isn't needed on Windows nor on platforms where getpid() returns a different ID for each thread (see NOTES below).

Additionally, OpenSSL supports dynamic locks, and sometimes, some parts of OpenSSL need it for better performance. To enable this, the following is required:

  • Three additional callback function, dyn_create_function, dyn_lock_function and dyn_destroy_function.
  • A structure defined with the data that each lock needs to handle.

struct CRYPTO_dynlock_value has to be defined to contain whatever structure is needed to handle locks.

dyn_create_function(const char *file, int line) is needed to create a lock. Multi-threaded applications might crash at random if it is not set.

dyn_lock_function(int mode, CRYPTO_dynlock *l, const char *file, int line) is needed to perform locking off dynamic lock numbered n. Multi-threaded applications might crash at random if it is not set.

dyn_destroy_function(CRYPTO_dynlock *l, const char *file, int line) is needed to destroy the lock l. Multi-threaded applications might crash at random if it is not set.

CRYPTO_get_new_dynlockid() is used to create locks. It will call dyn_create_function for the actual creation.

CRYPTO_destroy_dynlockid() is used to destroy locks. It will call dyn_destroy_function for the actual destruction.

CRYPTO_lock() is used to lock and unlock the locks. mode is a bitfield describing what should be done with the lock. n is the number of the lock as returned from CRYPTO_get_new_dynlockid(). mode can be combined from the following values. These values are pairwise exclusive, with undefined behaviour if misused (for example, CRYPTO_READ and CRYPTO_WRITE should not be used together):

        CRYPTO_LOCK     0x01
        CRYPTO_UNLOCK   0x02
        CRYPTO_READ     0x04
        CRYPTO_WRITE    0x08

Examples

crypto/threads/mttest.c shows examples of the callback functions on Solaris, Irix and Win32.

Return Values

CRYPTO_num_locks() returns the required number of locks.

CRYPTO_get_new_dynlockid() returns the index to the newly created lock.

The other functions return no values.

Notes

Use the following to find out if OpenSSL was configured with thread support:

 #define OPENSSL_THREAD_DEFINES
 #include <openssl/opensslconf.h>
 #if defined(OPENSSL_THREADS)
   // thread support enabled
 #else
   // no thread support
 #endif

Also, dynamic locks are currently not used internally by OpenSSL, but may do so in the future.

Defining id_function(void) has it's own issues. Generally speaking, pthread_self() should be used, even on platforms where getpid() gives different answers in each thread, since that may depend on the machine the program is run on, not the machine where the program is being compiled. For instance, Red Hat 8 Linux and earlier used LinuxThreads, whose getpid() returns a different value for each thread. Red Hat 9 Linux and later use NPTL, which is Posix-conformant, and has a getpid() that returns the same value for all threads in a process. A program compiled on Red Hat 8 and run on Red Hat 9 will therefore see getpid() returning the same value for all threads.

There is still the issue of platforms where pthread_self() returns something other than an integer. This is a bit unusual, and this manual has no cookbook solution for that case.

History

CRYPTO_set_locking_callback() and CRYPTO_set_id_callback() are available in all versions of SSLeay and OpenSSL. CRYPTO_num_locks() was added in OpenSSL 0.9.4. All functions dealing with dynamic locks were added in OpenSSL 0.9.5b-dev.

See Also

crypto()

Feedback

For additional information or queries on this page send feedback


time

Name

time - time a simple command or give resource usage

Library

 libc.lib

Synopsis
#include <time.h>
time_t time (time_t *tloc);

Return values

 On (success,, the, value, of, time, in, seconds, since, the, Epoch, is, returned., On, error,, ((time_t)-1), is, returned,, and, errno, is, set, appropriately.);

Detailed description

 The time function returns the value of time in seconds since 0 hours, 0 minutes, 0 seconds, January 1, 1970, Coordinated Universal Time. If an error occurs, time returns the value (time_t-1).

The return value is also stored in * tloc, provided that tloc is non-null.

Examples

/**
* Detailed description : sample usage of time system call
**/
#include <time.h>
int main()
{
  time_t Time ;
  if(time(&Time) < 0 )
  {
    printf("Time system call failed \n") ;
    return -1 ;
  }
 printf("Time value is %u \n" , Time) ;
 return 0 ;
}

Output

should print time value since the Epoch (00:00:00 UTC, January 1, 1970),  measured in seconds.

Errors

 The time function may fail for any of the reasons described in gettimeofday.

See also

 gettimeofday, ctime

Bugs

 Neither -isoC-99 nor -p1003.1-2001 requires time to set errno on failure; thus, it is impossible for an application to distinguish the valid time value -1 (representing the last UTC second of 1969) from the error return value.

Systems conforming to earlier versions of the C and POSIX standards (including older versions of ) did not set * tloc in the error case.

Feedback

For additional information or queries on this page send feedback


tmpnam

Name

tempnam, tmpfile, tmpnam
- temporary file routines

Library

 libc.lib

Synopsis
#include <stdio.h>
FILE * tmpfile (void);
char * tmpnam (char *str);
char * tempnam (const char *tmpdir, const char *prefix);

Return values

 The tmpfile function returns a pointer to an open file stream on success, and a NULL pointer on error.

The tmpnam and tempfile functions return a pointer to a file name on success, and a NULL pointer on error.

Detailed description

 The tmpfile function returns a pointer to a stream associated with a file descriptor returned by the routine mkstemp. The created file is unlinked before tmpfile returns, causing the file to be automatically deleted when the last reference to it is closed. The file is opened with the access value ‘w+’. The file is created in the directory determined by the environment variable TMPDIR if set. The default location 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
#include <stdio.h .>If the argument str is non- NULL, the file name is copied to the buffer it references. Otherwise, the file name is copied to 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

#include <stdio.h .>

The tempnam function is similar to tmpnam, but provides the ability to specify 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), the directory P_tmpdir, and the directory /tmp are tried, in the listed order, as directories in which to store the temporary file.

The argument prefix, if non- NULL, is used to specify a file name prefix, which will be the first part of the created file name. The tempnam function allocates memory in which to store the file name; the returned pointer may be used as a subsequent argument to free.

Examples

#include<stdio.h> //SEEK_SET, printf, tmpfile, FILE
#include<sys/stat.h> //S_IWUSR

int main()
{
//create the tmp directory
 mkdir("c:\\tmp", S_IWUSR);

//call tmpfile to create a tempory file
 FILE* fp = tmpfile();
 char buf[10];

 if(fp)
 {
     //write onto the file
     fprintf(fp, "%s", "hello");
     fflush(fp);

     //seek to the beginning of the file
     fseek(fp, SEEK_SET, 0); //beg of the file

     //read from the file
     fscanf(fp, "%s", buf);
     fflush(fp);

     //close the file
     fclose(fp);
 }

 printf("buf read: %s", buf);

 return 0;
}

Output

buf read: hello

#include<stdio.h> //tmpnam, printf, FILE
#include<sys/stat.h> //S_IWUSR
#include<errno.h> //errno

int main()
{
 //create a directory c:\system emp
 mkdir("c:\\system\\temp", S_IWUSR);

 char buf[L_tmpnam];
 char rbuf[10];

 //call tmpnam() to create a file
 char *rval = tmpnam(buf);

 errno = 0;
 //open the file with the name returned by tmpnam()
 FILE *fp = fopen(buf, "w");

 if (fp == NULL)
 {
     printf("fopen of file returned by tmpnam() failed - errno %d ", errno);
     return -1;
 }

 if(fp)
 {
    fprintf(fp, "%s", "check");
    fclose(fp);
 }

 fp = fopen(buf, "r");

 if(fp)
 {
     fscanf(fp, "%s", rbuf);
     fclose(fp);
 }

 printf("read from file: %s\n", rbuf);
 printf("argument buf: %s\n", buf);
 printf("return value: %s\n", rval);

 return 0;
}

Output

read from file: check
argument buf: /System/temp/tmp.0.U9UPTx
return value: /System/temp/tmp.0.U9UPTx

Errors

 The tmpfile function may fail and set the global variable errno for any of the errors specified for the library functions fdopen() or mkstemp().

The tmpnam function may fail and set errno for any of the errors specified for the library function mktemp.

The tempnam function may fail and set errno for any of the errors specified for the library functions malloc or mktemp.

See also

 mktemp

Feedback

For additional information or queries on this page send feedback


toascii

Name

toascii - convert character to ASCII

Library

 libc.lib

Synopsis
#include <ctype.h>
int toascii (int c);

Return values

 The toascii function always returns a valid ASCII character.

Detailed description

 The toascii function strips all the bits except the lower order 7 bits, which will be converted to unsigned character value that fits in the ASCII range.

Examples

#include<ctype.h> //toascii()
#include<stdio.h> //printf()
int test_toascii()
{
   int arr[]={’s’,’9’,’\r’,166, 255};
   int i = 0;
   int size = 5;
   for( i=0; i<size; i++)
   {
     int ret = toascii(arr[i]); //call to the API with the chars in arr[]
     if( (!ret) != 0 )
     {
        printf("\n%d cannot convert", arr[i]);
     }
     else
     {
        printf("\n%c converted", arr[i]);
     }
}
printf("\n");
}

Output

s converted
9 converted
 converted
¦ converted
ÿ converted

See also

 isalnum, isalpha, isascii, iscntrl, isdigit, isgraph, islower, isprint, ispunct, isspace, isupper, isxdigit, tolower, toupper, defns

Feedback

For additional information or queries on this page send feedback


tolower

Name

tolower - convert letter to lower case

Library

 libc.lib

Synopsis
#include <ctype.h>
int tolower (int c);

Return values

 If the argument is an upper-case letter, the tolower function returns the corresponding lower-case letter if there is one; otherwise the argument is returned unchanged. The towlower function should be used instead.

Detailed description

 The tolower function converts an upper-case letter to the corresponding lower-case letter. For single character representations, the value of the argument is representable as an unsigned char or the value of EOF.

The functionality of this API is independent of the program’s current locale.

Examples

#include<ctype.h>  //tolower()
#include<stdio.h> //printf()
int test_tolower ()
{
   struct st
   {
    int input;
    int output;
   };
   struct st  arr[]=
   {
   { ’Q’, ’q’ },
   { ’g’ , ’g’ },
   { ’9’ , ’9’ },
   { ’%’ , ’%’ },
   { ’\t’ , ’\t’ },
   };
   int i = 0;
   int size = 5;
   for( i=0; i<size; i++)
   {
      int ret = tolower(arr[i].input);//call to the API with the chars in the arr[]
      if( ret != arr[i].output )
      {
         printf("\n%c cannot convert ", arr[i].input);
      }
      else
      {
         printf("\n%c ", arr[i].output);
      }
   }
printf("\n");
}

Output

q
g
9
%

See also

 islower, towlower, defns

Feedback

For additional information or queries on this page send feedback


toupper

Name

toupper - convert letter to upper case

Library

 libc.lib

Synopsis
#include <ctype.h>
int toupper (int c);

Return values

 If the argument is a lower-case letter, the toupper function returns the corresponding upper-case letter if there is one; otherwise the argument is returned unchanged. The towupper function should be used instead.

Detailed description

 The toupper function converts a lower-case letter to the corresponding upper-case letter. For single character representations, the value of the argument is representable as an unsigned char or the value of EOF. The functionality of this API is independent of the program’s current locale.

Examples

#include<ctype.h> //toupper()
#include<stdio.h> //printf()
int test_toupper()
{
   struct st
   {
     int input;
     int output;
   };
   struct st  arr[]=
   {
   { ’q’, ’Q’ },
   { ’G’ , ’G’ },
   { ’9’ , ’9’ },
   { ’%’ , ’%’ },
   { ’\t’ , ’\t’ },
   };
   int i = 0;
   int size = 5;
   for( i=0; i<size; i++)
   {
      int ret = toupper(arr[i].input);//call to the API with the chars in arr[]
      if( ret != arr[i].output )
      {
          printf("\n%c cannot convert ", arr[i].input);
      }
      else
      {
          printf("\n%c ", arr[i].output);
      }
   }
printf("\n");
}

Output

q
G
9
%

See also

 isupper, towupper, defns

Feedback

For additional information or queries on this page send feedback


towlower

Name

towlower - convert a wide character to lowercase

Library

 libc.lib

Synopsis
#include <wctype.h>
wint_t towlower (wint_t wc);

Return values

 If the argument is an upper-case letter, the towlower function returns the corresponding lower-case letter if there is one; otherwise the argument is returned unchanged.

Detailed description

 The towlower function converts an upper-case letter to the corresponding lower-case letter.

The behavior of the towlower is affected by LC_CTYPE category of the current locale.

Examples

#include <wchar.h>
/* Illustrates how to use towlower API */
wint_t example_towlower(void)
{
 /* input character */
  wint_t uwc = L’M’;
  wint_t lwc;
  /* convert a wide char from upper case to lower case */
  lwc = towlower(uwc);

 /* return the converted char or error if not */
  return lwc;
}

Limitations

 The current implementation of towlower is dependent on the locale support of SYMBIAN. It doesn’t work for the locales which the SYMBIAN

See also

 iswlower, tolower, towupper, wctrans
The towlower function conforms to -isoC-99.

Feedback

For additional information or queries on this page send feedback


towupper

Name

towupper - convert a wide character to uppercase

Library

 libc.lib

Synopsis
#include <wctype.h>
wint_t towupper (wint_t wc);

Return values

 If the argument is a lower-case letter, the towupper function returns the corresponding upper-case letter if there is one; otherwise the argument is returned unchanged.

Detailed description

 The towupper function converts a lower-case letter to the corresponding upper-case letter.

The behavior of the towupper is affected by LC_CTYPE category of the current locale.

Examples

#include <wchar.h>
/* Illustrates how to use towupper API */
wint_t example_towupper(void)
{
 /* input character */
  wint_t lwc = L’m’;
  wint_t uwc;
  /* convert a wide char from lower case to upper case */
  uwc = towupper(lwc);

 /* return the converted char or error if not */
  return uwc;
}

Limitations

 The current implementation of towupper is dependent on the locale support of SYMBIAN. It doesn’t work for the locales which the SYMBIAN

See also

 iswupper, toupper, towlower, wctrans
The towupper function conforms to -isoC-99.

Feedback

For additional information or queries on this page send feedback


trunc

Name

trunc, truncf, truncl
- round to integer, towards zero

Library

 libm.lib

Synopsis
#include <math.h>
double trunc (double x);
float truncf (float x);
long double truncl (long double x);

Return values

x is integral, infinite or NaN , x itself is returned.

Detailed description

 The trunc, truncf, and truncl functions return the nearest integral value with magnitude less than or equal to | x |. They are equivalent to rint, rintf, and rintl, respectively, in the FE_TOWARDZERO rounding mode.

Examples

#include <math.h>
int main( )
{
   double inp = 1048580.625;
   double y;
   y = trunc( inp );
   printf( "trunc( %f)  = %f\n", inp,  y );
   y = truncf( inp);
   printf( "truncf( %f) = %f\n", inp, y );
   y = truncl( inp);
   printf( "truncl( %f) = %f\n\n", inp, y );
}

Output

trunc ( 1048580.625 ) = 1048580.000000
truncf( 1048580.625 ) = 1048580.000000
truncl( 1048580.625 ) = 1048580.000000

See also

 ceil, fegetround, floor, math, nextafter, rint, round

Feedback

For additional information or queries on this page send feedback


truncate

Name

truncate, ftruncate
- truncate or extend a file to a specified length

Library

 libc.lib

Synopsis
#include <unistd.h>
int truncate (const char *path, off_t length);
int ftruncate (int fd, off_t length);

Return values

 Upon successful completion, both truncate() and ftruncate() shall return 0; otherwise, -1 shall be returned and errno set to indicate the error.

Detailed description

 The truncate system call causes the file named by path or referenced by fd to be truncated to length bytes in size. If the file was larger than this size, the extra data is lost. If the file was smaller than this size, it will be extended as if by writing bytes with the value zero. With ftruncate, the file must be open for writing.

Examples

//example for truncate
#include<unistd.h>
#include<stdio.h>
#include <sys/stat.h>
int test_truncate()
{
        int retVal, retVal2, retSize, retSize2;
        struct stat buf;
        ssize_t size;
        char *buffer = "abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwx";
        int fp = open("c:\test.txt", O_RDWR|O_CREAT);
        size = write(fp,buffer,50);
        close(fp);
        retVal2 = stat("c:\test.txt", &buf );
        if ( !retVal2 )
        {
        retSize = buf.st_size;
        printf("Size before: %d", retSize);
        retVal = truncate("c:\test.txt", retSize/2 );
        }
        else
        {
        printf("Failed");
        }
        retVal2 = stat( "c:\test.txt", &buf );
        if ( !retVal2 )
                {
                retSize2 = buf.st_size;
                if( retSize2 == (retSize/2 ) )
                        {
                        printf("\nSize after: %d\n", retSize2);
                        printf("Truncate passed");
                        return 0;
                        }
                else
                        {
                        printf("Failed");
                        return -1;
                        }
                }
        else
                {
                printf("Failed");
                return -1;
                }
}

Output

Size before: 50
Size after: 25
Ttruncate Passed

//example for ftruncate
#include<unistd.h>
#include<stdio.h>
int test_ftruncate()
{
//assuming that the file exists and has some //data in it
   int fp = open("c:\test.txt", O_RDWR);
   int retVal, retVal2, retSize, retSize2;
   struct stat buf;
   if(fp != -1)
   {
     retVal2 = fstat( fp, &buf );
     if ( !retVal2 )
     {
        retSize = buf.st_size;
        printf("Size before: %d", retSize);
        retVal = ftruncate( fp, retSize/2 );
        close(fp);
     }
     else
     {
        printf("Failed");
     }
     fp = open("c:\test.txt", O_RDONLY);
     if((fp != -1) && (!retVal))
     {
        retVal2 = fstat( fp, &buf );
        if ( !retVal2 )
        {
          retSize2 = buf.st_size;
          if( retSize2 == (retSize/2 ) )
          {
            printf("\nSize after: %d\n", retSize2);
            printf("Ftruncate Passed");
          }
          else
          {
            printf("Failed");
          }
     }
     else
     {
       printf("Failed");
     }
  }
}

Output

Size before: 100
Size after: 50
Ftruncate Passed

Errors

 The truncate and ftruncate succeed unless:
[EBADF]
 | The fd argument is not a valid descriptor for a regular file.
[EINVAL]
 | The fd argument references to an object other than a file.
[EINVAL]
 | The fd descriptor is not open for writing.

See also

 open

Bugs

 These calls should be generalized to allow ranges of bytes in a file to be discarded.

Use of truncate to extend a file is not portable.

Feedback

For additional information or queries on this page send feedback


tzset

Name

tzset
- initialize time conversion information

Library

 libc.lib

Synopsis
#include <time.h>
void tzset (void);

Detailed description

 The tzset function initializes time conversion information used by the library routine localtime. The environment variable TZ specifies how this is done.

If TZ does not appear in the environment, the best available approximation to local wall clock time, is used.

If TZ appears in the environment but its value is a null string, Coordinated Universal Time (UTC) is used (without leap second correction).

Examples

#include <time.h>
#include <stdio.h>
int main(){
        time_t t;
        char* c_time;
        tzset(); //Call tzset
        c_time = ctime (&t); //Get time-string using ctime for Epoc time
        printf ("Time from ctime after tzset: %s", c_time);
        return 0;
}

Output

Time from ctime after tzset: Sun Apr  7 02:24:08 1974

Specification format

 When TZ is used directly as a specification of the time conversion information, it must have the following syntax (spaces inserted for clarity):

 std offset

[

 dst

[offset]

[,rule]

]

Where:
std and dst Three or more bytes that are the designation for the standard (std) or summer (dst) time zone. Only std is required; if dst is missing, then summer time does not apply in this locale. Upper and lowercase letters are explicitly allowed. Any characters except a leading colon (‘:’), digits, comma (‘,’), minus (‘-’), plus (‘+’), and ASCII NUL are allowed.
offset Indicates the value one must add to the local time to arrive at Coordinated Universal Time. The offset has the form:

 hh[

: mm

[:ss]

]

The minutes (mm) and seconds (ss) are optional. The hour (hh) is required 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 ahead of standard time. One or more digits may be used; the value is always interpreted as a decimal number. The hour must be between zero and 24, and the minutes (and seconds) — if present — between zero and 59. If preceded by a (‘-’) the time zone shall be east of the Prime Meridian; otherwise it shall be west (which may be indicated by an optional preceding (‘+’)).

rule Indicates when to change to and back from summer time. The rule has the form:

 date/time,date/time

where the first date describes when the change from standard to summer time occurs and the second date describes when the change back happens. Each time field describes when, in current local time, the change to 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 is day 59 and March 1 is day 60. It is impossible to explicitly refer to the occasional February 29.
n | The zero-based Julian day (0 <= n <= 365 ) . Leap days are counted, and it is possible to refer to February 29.
M m.n.d | The d ’th day (0 <= d <= 6) of week n of month m of the year (1 <= n <= 5), (1 <= m <= 12), where week 5 means " the last d day in month m " which may occur in either the fourth or the fifth week). Week 1 is the first week in which the d ’th day occurs. Day zero is Sunday. The time has the same format as offset except that no leading sign (‘-’) or (‘+’) is allowed. The default, if time is not given, is 02:00:00.

See also

 gettimeofday, ctime, getenv, time

Feedback

For additional information or queries on this page send feedback


ualarm

Name

ualarm - schedule signal after given number of microseconds

Library

 libc.lib

Synopsis
#include <unistd.h>
useconds_t ualarm (useconds_t microseconds, useconds_t interval);

Return values

 When the signal has successfully been caught, ualarm returns the amount of time left on the clock.

Notes

 A microsecond is 0.000001 seconds.

Detailed description

 This is a simplified interface to setitimer.

The ualarm function waits a count of microseconds before asserting the terminating signal SIGALRM. System activity or time used in processing the call may cause a slight delay.

If the interval argument is non-zero, the SIGALRM signal will be sent to the process every interval microseconds after the timer expires (e.g. after microseconds number of microseconds have passed).

Due to setitimer restriction the maximum number of microseconds and interval is limited to 100000000000000 (in case this value fits in the unsigned integer).

See also

 getitimer, signal, sleep, usleep
The ualarm function appeared in BSD 4.3 .

Feedback

For additional information or queries on this page send feedback


ERR_load_UI_strings - New User Interface

Name

UI_new, UI_new_method
UI_free, UI_add_input_string
UI_dup_input_string, UI_add_verify_string
UI_dup_verify_string, UI_add_input_boolean
UI_dup_input_boolean, UI_add_info_string
UI_dup_info_string, UI_add_error_string
UI_dup_error_string, UI_construct_prompt
UI_add_user_data, UI_get0_user_data
UI_get0_result, UI_process
UI_ctrl, UI_set_default_method
UI_get_default_method, UI_get_method
UI_set_method, UI_OpenSSL
ERR_load_UI_strings

New User Interface

Library

libcrypto.lib

Synopsis

#include <openssl/ui.h>
typedef struct ui_st UI;
typedef struct ui_method_st UI_METHOD;
UI *UI_new(void);
UI *UI_new_method(const UI_METHOD *method);
void UI_free(UI *ui);
int UI_add_input_string(UI *ui, const char *prompt, int flags, char *result_buf, int minsize, int maxsize);
int UI_dup_input_string(UI *ui, const char *prompt, int flags, char *result_buf, int minsize, int maxsize);
int UI_add_verify_string(UI *ui, const char *prompt, int flags, char *result_buf, int minsize, int maxsize, const char *test_buf);
int UI_dup_verify_string(UI *ui, const char *prompt, int flags, char *result_buf, int minsize, int maxsize, const char *test_buf);
int UI_add_input_boolean(UI *ui, const char *prompt, const char *action_desc, const char *ok_chars, const char *cancel_chars,
                         int flags, char *result_buf);
int UI_dup_input_boolean(UI *ui, const char *prompt, const char *action_desc, const char *ok_chars, const char *cancel_chars,
                         int flags, char *result_buf);
int UI_add_info_string(UI *ui, const char *text);
int UI_dup_info_string(UI *ui, const char *text);
int UI_add_error_string(UI *ui, const char *text);
int UI_dup_error_string(UI *ui, const char *text);
/* These are the possible flags.  They can be or'ed together. */
#define UI_INPUT_FLAG_ECHO             0x01
#define UI_INPUT_FLAG_DEFAULT_PWD      0x02
char *UI_construct_prompt(UI *ui_method, const char *object_desc, const char *object_name);
void *UI_add_user_data(UI *ui, void *user_data);
void *UI_get0_user_data(UI *ui);
const char *UI_get0_result(UI *ui, int i);
int UI_process(UI *ui);
int UI_ctrl(UI *ui, int cmd, long i, void *p, void (*f)());
#define UI_CTRL_PRINT_ERRORS           1
#define UI_CTRL_IS_REDOABLE            2
void UI_set_default_method(const UI_METHOD *meth);
const UI_METHOD *UI_get_default_method(void);
const UI_METHOD *UI_get_method(UI *ui);
const UI_METHOD *UI_set_method(UI *ui, const UI_METHOD *meth);
UI_METHOD *UI_OpenSSL(void);

Detailed Description

UI stands for User Interface, and is general purpose set of routines to prompt the user for text-based information. Through user-written methods (see ui_create()), prompting can be done in any way imaginable, be it plain text prompting, through dialog boxes or from a cell phone.

All the functions work through a context of the type UI. This context contains all the information needed to prompt correctly as well as a reference to a UI_METHOD, which is an ordered vector of functions that carry out the actual prompting.

The first thing to do is to create a UI with UI_new() or UI_new_method(), then add information to it with the UI_add or UI_dup functions. Also, user-defined random data can be passed down to the underlying method through calls to UI_add_user_data. The default UI method doesn't care about these data, but other methods might. Finally, use UI_process() to actually perform the prompting and UI_get0_result() to find the result to the prompt.

A UI can contain more than one prompt, which are performed in the given sequence. Each prompt gets an index number which is returned by the UI_add and UI_dup functions, and has to be used to get the corresponding result with UI_get0_result().

The functions are as follows:

UI_new() creates a new UI using the default UI method. When done with this UI, it should be freed using UI_free().

UI_new_method() creates a new UI using the given UI method. When done with this UI, it should be freed using UI_free().

UI_OpenSSL() returns the built-in UI method (note: not the default one, since the default can be changed. See further on). This method is the most machine/OS dependent part of OpenSSL and normally generates the most problems when porting.

UI_free() removes a UI from memory, along with all other pieces of memory that's connected to it, like duplicated input strings, results and others.

UI_add_input_string() and UI_add_verify_string() add a prompt to the UI, as well as flags and a result buffer and the desired minimum and maximum sizes of the result. The given information is used to prompt for information, for example a password, and to verify a password (i.e. having the user enter it twice and check that the same string was entered twice). UI_add_verify_string() takes and extra argument that should be a pointer to the result buffer of the input string that it's supposed to verify, or verification will fail.

UI_add_input_boolean() adds a prompt to the UI that's supposed to be answered in a boolean way, with a single character for yes and a different character for no. A set of characters that can be used to cancel the prompt is given as well. The prompt itself is really divided in two, one part being the descriptive text (given through the prompt argument) and one describing the possible answers (given through the action_desc argument).

UI_add_info_string() and UI_add_error_string() add strings that are shown at the same time as the prompt for extra information or to show an error string. The difference between the two is only conceptual. With the builtin method, there's no technical difference between them. Other methods may make a difference between them, however.

The flags currently supported are UI_INPUT_FLAG_ECHO, which is relevant for UI_add_input_string() and will have the users response be echoed (when prompting for a password, this flag should obviously not be used, and UI_INPUT_FLAG_DEFAULT_PWD, which means that a default password of some sort will be used (completely depending on the application and the UI method).

UI_dup_input_string(), UI_dup_verify_string(), UI_dup_input_boolean(),
UI_dup_info_string() and
 UI_dup_error_string() are basically the same
as their UI_add counterparts, except that they make their own copies
of all strings.

UI_construct_prompt() is a helper function that can be used to create a prompt from two pieces of information: an description and a name. The default constructor (if there is none provided by the method used) creates a string ``Enter description for name:''. With the description ``pass phrase'' and the file name ``foo.key'', that becomes ``Enter pass phrase for foo.key:''. Other methods may create whatever string and may include encodings that will be processed by the other method functions.

UI_add_user_data() adds a piece of memory for the method to use at any time. The builtin UI method doesn't care about this info. Note that several calls to this function doesn't add data, it replaces the previous blob with the one given as argument.

UI_get0_user_data() retrieves the data that has last been given to the UI with UI_add_user_data().

UI_get0_result() returns a pointer to the result buffer associated with the information indexed by i.

UI_process() goes through the information given so far, does all the printing and prompting and returns.

UI_ctrl() adds extra control for the application author. For now, it understands two commands: UI_CTRL_PRINT_ERRORS, which makes UI_process() print the OpenSSL error stack as part of processing the UI, and UI_CTRL_IS_REDOABLE, which returns a flag saying if the used UI can be used again or not.

UI_set_default_method() changes the default UI method to the one given.

UI_get_default_method() returns a pointer to the current default UI method.

UI_get_method() returns the UI method associated with a given UI.

UI_set_method() changes the UI method associated with a given UI.

See Also

ui_create(), ui_compat()

History

The UI section was first introduced in OpenSSL 0.9.7.

Author

Richard Levitte (richard@levitte.org) for the OpenSSL project (http://www.openssl.org).

Feedback

For additional information or queries on this page send feedback


des_read_pw - Compatibility user interface functions

Name

des_read_password, des_read_2passwords
des_read_pw_string, des_read_pw

Compatibility user interface functions

Library

libcrypto.lib

Synopsis

int des_read_password(DES_cblock *key,const char *prompt,int verify);
int des_read_2passwords(DES_cblock *key1,DES_cblock *key2, const char *prompt,int verify);
int des_read_pw_string(char *buf,int length,const char *prompt,int verify);
int des_read_pw(char *buf,char *buff,int size,const char *prompt,int verify);

Detailed Description

The DES library contained a few routines to prompt for passwords. These aren't necessarely dependent on DES, and have therefore become part of the UI compatibility library.

des_read_pw() writes the string specified by prompt to standard output turns echo off and reads an input string from the terminal. The string is returned in buf, which must have spac for at least size bytes. If verify is set, the user is asked for the password twice and unless the two copies match, an error is returned. The second password is stored in buff, which must therefore also be at least size bytes. A return code of -1 indicates a system error, 1 failure due to use interaction, and 0 is success. All other functions described here use des_read_pw() to do the work.

des_read_pw_string() is a variant of des_read_pw() that provides a buffer if, verify is set.

des_read_password() calls des_read_pw() and converts the password to a DES key by calling DES_string_to_key(); des_read_2password() operates in the same way as des_read_password() except that it generates two keys by using the DES_string_to_2key() function.

Notes

des_read_pw_string() is available in the MIT Kerberos library as well, and is also available under the name EVP_read_pw_string().

See Also

ui(), ui_create()

Author

Richard Levitte (richard@levitte.org) for the OpenSSL project (http://www.openssl.org).

Feedback

For additional information or queries on this page send feedback


umask

Name

umask - set file creation mask

Library

 libc.lib

Synopsis
#include <sys/stat.h>
mode_t umask (mode_t numask);

Return values

 This function always returns MASK_RWUSR.

Detailed description

 The umask routine sets the process’s file mode creation mask to numask and returns the previous value of the mask. This function belongs to set of APIs which are only build supported and not available functionally. The reason why only build support is extended to these APIs is, symbian operating system does not support creation of multiple users and groups in its environment. More over it may not make sense to have multiple users and groups in the context of a mobile environment.

Errors

 No error values are set.

Feedback

For additional information or queries on this page send feedback


uname

Name

uname - print system information

Library

 libc.lib

Synopsis
#include <sys/utsname.h>
int uname (struct utsname *name);

Return values

 Upon successful completion, a non-negative value shall be returned. Otherwise, -1 shall be returned and errno set to indicate the error.

Detailed description

 The uname function stores NUL -terminated strings of information identifying the current system into the structure referenced by name.

The utsname structure is defined in the
#include <sys/utsname.h>header file, and contains the 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.

Examples

#include <sys/utsname.h>
#include<stdio.h>
int test_uname()
{
    int retVal;
    struct utsname name ;
    retVal = uname( &name );
    if( !retVal )
    {
      printf("Sysname: %s\n Nodename:%s\n Release:
      %s\nVersion: %s\nMachine:%s\n");
      printf("uname passed");
      return 0;
    }
    else
    {
      printf("failed");
      return -1;
    }
}

Output

Sysname: Symbian
Nodename: localhost
Release:
Version: 2:0:1055
Machine:
uname passed

Errors

 No errors defined.

Feedback

For additional information or queries on this page send feedback


ungetc

Name

ungetc - input of characters and strings

Library

 libc.lib

Synopsis
#include <stdio.h>
int ungetc (int c, FILE *stream);

Return values

 The ungetc function returns the character pushed-back after the conversion, or EOF if the operation fails. If the value of the argument c character equals EOF, the operation will fail and the stream will remain unchanged.

Detailed description

 The ungetc function pushes the character c (converted to an unsigned char) back onto the input stream pointed to by stream. The pushed-back characters will be returned by subsequent reads on the stream (in reverse order). A successful intervening call, using the same stream, to one of the file positioning functions (,
fsetpos , or
rewind ) 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 is cleared. The file-position indicator is decremented by each successful call to ungetc; if its value was 0 before a call, its value is unspecified after the call.

Examples

/****************** this pushing character to file stream using ungetc **************/
#include <stdio.h>
int main(void)
{
        int c;
        FILE* fp = fopen("c:\\input.txt", "w");
        fprintf(fp, "%s", "abcdefghijklmn");
        fprintf(fp, "%c", '\n');
        fprintf(fp, "%s", "fdsfdsafsdabcdefghijklmn");
        fclose(fp);
        char * name = "C:\\input.txt";
        fp = fopen(name, "w+");
        if (fp == NULL)
                {
                printf ("fopen failed\n");
                return -1;
                }
        if(ungetc('a',fp)!='a') printf("ungetc failed\n");

        fseek(fp,-1,SEEK_CUR);
        c=getc(fp);
        printf("character read from stream is \"%c\"\n",c);
        fclose(fp);
}

Output

 character read from stream is "a"

See also

 fseek, getc, ungetwc

Feedback

For additional information or queries on this page send feedback


ungetwc

Name

ungetwc - push back a wide character onto a FILE stream

Library

 libc.lib

Synopsis
#include <stdio.h>
#include <wchar.h>
wint_t ungetwc (wint_t wc, FILE *stream);

Return values

 The ungetwc function returns the wide character pushed-back after the conversion, or WEOF if the operation fails. If the value of the argument c character equals WEOF, the operation will fail and the stream will remain unchanged.

Detailed 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 characters will be returned by subsequent reads on the stream (in reverse order). A successful intervening call, using the same stream, to one of the file positioning functions fseek, fsetpos, or rewind will discard the pushed back wide characters.

One wide 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 is cleared.

Examples

#include <stdio.h>
#include <wchar.h>
/* Illustrates how to use ungetwc API */
wint_t example_ungetwc(void)
{
 FILE *fp = NULL;
 wint_t wc1;
 wint_t rval;
 wint_t wc2;
 /* opening the file to write*/
 fp = fopen("input.txt","w");
 if(fp == NULL)
 {
  wprintf(L"Error: File open\n");
  return (-1);
 }
 /* character to written back to the fp */
 wc = (wint_t) L’e’;
 /* write the character into the fp */
 rval = ungetwc(wc, fp);
 /* check for error */
 if(rval == WEOF)
 {
        wprintf(L"ungetwc returned error!!\n");
 }
 /* Read the character from fp */
 /* this char should be the same as the char */
 /* that was written by ungetwc */
 wc2 = getwc(fp);
 /* Close the file opened for writing */
 fclose(fp);
 /* return the value that was written */
 return (rval);
}

See also

 fseek, getwc

Feedback

For additional information or queries on this page send feedback


unlink

Name

unlink - delete a name and possibly the file it refers to

Library

 libc.lib

Synopsis
#include <unistd.h>
int unlink (const char *path);

Return values

 Upon successful completion, 0 shall be returned. Otherwise, -1 shall be returned and errno set to indicate the error.

Detailed description

 The unlink system call removes the link named by path from its file system. It is expected to decrement the link count of the file which was referenced by the link, but since this is a simulated function and not supported by the platform, link count does not get modified. As the parent file to which a link is created itself is unaware about the link, a unlink on the parent file will close the file regardless of weather there existed any link to the file. The path argument may not be a directory.

Examples

/*
* Detailed description  : Example to unlink a link file
* Precondition : A link file by name "Link" should exist in
*                c: drive.
*/
#include <unistd.h>
#include <stdio.h>
int main(void)
{
    char rdbuff[25];
    if(unlink("C:\\Link"))
    {
         printf("unlink on link file failed");
    }
    printf("Unlink on link file succeeded");
}

Output

Unlink on link file succeeded.

Errors

 The unlink succeeds unless:
[ENOENT]
 | The named file does not exist.
[EINVAL]
 | A relative path was encountered in translating path and is not supported by the platform.
[ENOENT]
 | An empty path was encountered while translating the pathname.
[EACCESS]
 | The file named by the path argument cannot be unlinked because it is being used by the system or another process and the implementation considers this an error.

See also

 close, link, rmdir, symlink

Feedback

For additional information or queries on this page send feedback


usleep

Name

usleep - suspend execution for microsecond intervals

Library

 libc.lib

Synopsis
#include <unistd.h>
int usleep (useconds_t microseconds);

Return values

 The usleep function returns the value 0 if successful; otherwise the value -1 is returned and the global variable errno is set to indicate the error.

Detailed description

 The usleep function suspends execution of the calling process until either microseconds microseconds have elapsed or a signal is delivered to the process and its action is to invoke a signal-catching function or to terminate the process. System activity may lengthen the sleep by an indeterminate amount.

This function is implemented using nanosleep by pausing for microseconds microseconds or until a signal occurs. Consequently, in this implementation, sleeping has no effect on the state of process timers, and there is no special handling for SIGALRM.

Examples

#include<unistd.h>
#include<stdio.h>

int main()
{
 unsigned long t = 2;
 int i;

 i = usleep(t);
 printf("Expected: 0 usleep returned: %d", i);

 return 0;
}

Output

Expected: 0 usleep returned: 0

Errors

 The usleep function will fail if:
[EINTR]
A signal was delivered to the process and its action was to invoke a signal-catching function.

Limitations

 The signal related functionaities aren’t applicable to the symbian implementation as there is no support for signals from symbian.

See also

 nanosleep, sleep

Feedback

For additional information or queries on this page send feedback


utime

Name

utime - change access and/or modification times of an inode

Library

 libc.lib

Synopsis
#include <utime.h>
int utime (const char *file, const struct utimbuf *timep);

Return values

errno is set appropriately.

Detailed description

 This interface is obsoleted by utimes.

The utime function sets the access and modification times of the named file from the actime and modtime fields of the struct utimbuf pointed at by timep.

If the times are specified (the timep argument is non- NULL) the caller must be the owner of the file or be the super-user.

If the times are not specified (the timep argument is NULL) the caller must be the owner of the file, have permission to write the file, or be the super-user.

Examples

/**
*  Detailed description:  Sample usage of utime system call
*  Preconditions:  Example.txt file should exist in the working directory
**/
#include <stdio.h>
#include <utime.h>
int main()
{
  struct utimbuf Time ;
  if(utime("Example.txt" , &Time) < 0 )
  {
     printf("Utime call failed \n") ;
     return -1 ;
  }
  printf("Utime call succeded \n") ;
  return 0 ;
}

Output

Utime call succeded

Errors

 The utime function may fail and set errno for any of the errors specified for the library function utimes.

See also

 stat, utimes

Feedback

For additional information or queries on this page send feedback


utimes

Name

utimes, lutimes, futimes
- change access and/or modification times of an inode

Library

 libc.lib

Synopsis
#include <sys/time.h>
int utimes (const char *path, const struct timeval *times);
int lutimes (const char *path, const struct timeval *times);
int futimes (int fd, const struct timeval *times);

Return values

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

Detailed description

 The access and modification times of the file named by path or referenced by fd are changed as specified by the argument times.

If times is NULL, the access and modification times are set to the current time. The caller must be the owner of the file, have permission to write the file, or be the super-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 is set to the value of the second element. For file systems that support file birth (creation) times (such as UFS2), the birth time will be set to the value of the second element if the second element is older than the currently set birth time. To set both a birth time and a modification time, two calls are required; the first to set the birth time and the second to set the (presumably newer) modification time. Ideally a new system call will be added that allows the setting of all three times at once. The caller must be the owner of the file or be the super-user.

In either case, the inode-change-time of the file is set to the current time.

The lutimes system call is like utimes except in the case where the named file is a symbolic link, in which case lutimes changes the access and modification times of the link, while utimes changes the times of the file the link references.

Examples

/**
*  Detailed description: Sample usage of utimes system call.
*  Preconditions: Example.txt file should exist in the working directory
**/
#include <sys/types.h>
#include <utime.h>
#include <sys/time.h>
int main()
{
  struct timeval Tim[1] ;
 Tim[0].tv_sec = 0 ;
 Tim[0].tv_usec = 0 ;
  if(utimes("Example.txt"  , Tim) < 0 )
  {
     printf("Utimes system call failed \n") ;
     return -1 ;
  }
  printf("Utimes call succeded \n") ;
 return 0 ;
}

Errors

 The utimes and lutimes system calls will fail if:
[EACCES]
 | Search permission is denied for a component of the path prefix; or the times argument is NULL and the effective user ID of the process does not match the owner of the file, and is not the super-user, and write access is denied.
[EFAULT]
 | The path or times argument 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 pathname.
[ENAMETOOLONG]
 | A component of a pathname exceeded NAME_MAX characters, or an entire 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 effective user 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.

The futimes system call will fail if:
[EBADF]
The fd argument does not refer to a valid descriptor.

All of the system calls will fail if:
[EACCES]
 | The times argument is NULL and the effective user ID of the process does not match the owner of the file, and is not the super-user, and write access is denied.
[EFAULT]
 | The times argument points outside the process’s allocated address space.
[EIO] | An I/O error occurred while reading or writing the affected inode.
[EPERM]
 | The times argument is not NULL and the calling process’s effective user 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, utime

Feedback

For additional information or queries on this page send feedback


waccess

Name

waccess - checks user's permissions for a file

Library

 libc.lib

Synopsis
#include <unistd.h>
#include <wchar.h>
int waccess (const wchar_t *path, int mode);

Return values

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

Detailed description

 The waccess system call checks the accessibility of the file named by the path argument for the access permissions indicated by the mode argument. The value of mode is either the bitwise-inclusive OR of the access permissions to be checked (R_OK for read permission, W_OK for write permission, and X_OK for execute/search permission), or the existence test (F_OK.)

For additional information, see the File access Permission section of intro . X_OK, the file may not actually have execute permission bits set. Likewise for R_OK and W_OK.

Note that as execute-bit for file is not supported .Hence waccess system call for X_OK is undefined.

Examples

/**
 * Detailed description: This sample code checks read-ok accessibility of file Example.c
 *
 * Precondtions: Example.txt file should be present in working directory.
**/
#include <unistd.h>
#include <wchar.h>
int main()
{
  if(waccess("Example.c" ,R_OK)  < 0)
  {
    printf("Read operation on the file is not permitted \n") ;
    return -1 ;
  }
  printf("Read operation permitted on Example.c file \n") ;
  return 0 ;
}

Output

Read operation permitted on Example.c file

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 entire path name exceeded 1023 characters .
[ENOENT]
 | The named file does not exist.
[EACCES]
 | Permission bits of the file mode do not permit the requested access, or search permission is denied on a component of the path prefix.

See also

 wchmod, wstat

Feedback

For additional information or queries on this page send feedback


wait

Name

wait, waitpid
- wait for process termination

Library

 libc.lib

Synopsis
#include <sys/types.h>
#include <sys/wait.h>
pid_t wait (int *status);
#include <sys/time.h>
#include <sys/resource.h>
pid_t waitpid (pid_t wpid, int *status, int options);

Return values

 If wait returns due to a stopped or terminated child process, the process ID of the child is returned to the calling process. Otherwise, a value of -1 is returned and errno is set to indicate the error.

If wait4, wait3, or waitpid returns due to a stopped or terminated child process, the process ID of the child is returned to the calling process. If there are no children not previously awaited, -1 is returned with errno set to ECHILD. Otherwise, if WNOHANG is specified and there are no stopped or exited children, 0 is returned. If an error is detected or a caught signal aborts the call, a value of -1 is returned and errno is set to indicate the error.

Detailed description

 The wait function suspends execution of its calling process until status information is available for a terminated child process, or a signal is received. On return from a successful wait call, the status area contains termination information about the process that exited as defined below.

The wpid argument specifies the set of child processes for which to wait. If wpid is -1, the call waits for any child process. If wpid is 0, the call waits for 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 call waits for any process whose process group id equals the absolute value of wpid.

The waitpid function is identical to wait4 with an rusage value of zero.

Limitation: The waitpid waits on a pid which obtained using an non-standard api popen3

Errors

 The wait function will fail and return immediately if:
[ECHILD]
 | The calling process has no existing unwaited-for child processes.
[ECHILD]
 | No status from the terminated child process is available because the calling process has asked the system to discard such status by ignoring the signal SIGCHLD or setting the flag SA_NOCLDWAIT for that signal.
[EFAULT]
 | The status or rusage argument points to an illegal address. (May not be detected before exit of a child process.)
[EINTR]
 | The call was interrupted by a caught signal, or the signal did not have the SA_RESTART flag set.

See also

 _exit, exit
The wait and waitpid functions are defined by POSIX; wait4 and wait3 are not specified by POSIX. The WCOREDUMP macro and the ability to restart a pending wait call are extensions to the POSIX interface.
The wait function appeared in AT&T v6 .

Feedback

For additional information or queries on this page send feedback


waitpid

Name

wait, waitpid
- wait for process termination

Library

 libc.lib

Synopsis
#include <sys/types.h>
#include <sys/wait.h>
pid_t wait (int *status);
#include <sys/time.h>
#include <sys/resource.h>
pid_t waitpid (pid_t wpid, int *status, int options);

Return values

 If wait returns due to a stopped or terminated child process, the process ID of the child is returned to the calling process. Otherwise, a value of -1 is returned and errno is set to indicate the error.

If wait4, wait3, or waitpid returns due to a stopped or terminated child process, the process ID of the child is returned to the calling process. If there are no children not previously awaited, -1 is returned with errno set to ECHILD. Otherwise, if WNOHANG is specified and there are no stopped or exited children, 0 is returned. If an error is detected or a caught signal aborts the call, a value of -1 is returned and errno is set to indicate the error.

Detailed description

 The wait function suspends execution of its calling process until status information is available for a terminated child process, or a signal is received. On return from a successful wait call, the status area contains termination information about the process that exited as defined below.

The wpid argument specifies the set of child processes for which to wait. If wpid is -1, the call waits for any child process. If wpid is 0, the call waits for 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 call waits for any process whose process group id equals the absolute value of wpid.

The waitpid function is identical to wait4 with an rusage value of zero.

Limitation: The waitpid waits on a pid which obtained using an non-standard api popen3

Errors

 The wait function will fail and return immediately if:
[ECHILD]
 | The calling process has no existing unwaited-for child processes.
[ECHILD]
 | No status from the terminated child process is available because the calling process has asked the system to discard such status by ignoring the signal SIGCHLD or setting the flag SA_NOCLDWAIT for that signal.
[EFAULT]
 | The status or rusage argument points to an illegal address. (May not be detected before exit of a child process.)
[EINTR]
 | The call was interrupted by a caught signal, or the signal did not have the SA_RESTART flag set.

See also

 _exit, exit
The wait and waitpid functions are defined by POSIX; wait4 and wait3 are not specified by POSIX. The WCOREDUMP macro and the ability to restart a pending wait call are extensions to the POSIX interface.
The wait function appeared in AT&T v6 .

Feedback

For additional information or queries on this page send feedback


wchdir

Name

wchdir - change working directory

Library

 libc.lib

Synopsis
#include <wchar.h>
int wchdir (const wchar_t *path);

Return values

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

Detailed description

 The path argument points to the pathname of a directory which is a wide character string. The wchdir system call causes the named directory to become the current working directory, that is, the starting point for path searches of pathnames not beginning with a slash, ‘/.’

Examples

#include<wchar.h>                       /* wmkdir, wrmdir */
#include <sys/stat.h>                   /* S_IRWXU */
#include <stdio.h>                      /* printf */
int main()
{
        int ret_wmkdir = wmkdir(L"dirName", S_IRWXU);                   /* create directory */
        if(ret_wmkdir < 0)
                {
                printf("error creating directory");
                return -1;
                }
        else
                {
                int ret_wchdir = wchdir(L"dirName");                    /* change directory */
                if(ret_wchdir < 0)
                        {
                        printf("error changing directory");
                        return -1;
                        }
                else
                        {
                        printf("working directory changed");
                        }
                        wrmdir(L"dirname");                             /* remove directory */
                }
        return 0;
}

Output

working directory changed

Errors

 The wchdir system call will fail and the current working directory will be unchanged if one or more of the following are true:
[ENOTDIR]
 | Not a directory.
[ENAMETOOLONG]
 | A component of a pathname exceeded 255 characters.
[ENOENT]
 | The named file does not exist.
[EINVAL]
 | Invalid argument.

See also

 chdir

Feedback

For additional information or queries on this page send feedback


wchmod

Name

wchmod - changes permissions of a file

Library

 libc.lib

Synopsis
#include <wchar.h>
#include <sys/stat.h>
#include <sys/types.h>
int wchmod (const wchar_t *path, mode_t mode);

Return values

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

Detailed description

 The file permission bits of the wide character file-name specified by path are changed to mode. The wchmod system call verifies that the process owner (user) either owns the file specified by path is the super-user.

A mode is created from or’d permission bit masks defined in
#include <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 */
#ifndef __BSD_VISIBLE
#define S_ISTXT 0001000    /* sticky bit */
#endif

Note : sticky bit and setuid on exec bit are not supported, permission values for users is considered while premissions values for group and others are ignored(As there is no concept of group and others). An attempt to change file permission to write-only changes the file permission to read-write. Permissions for directory will be ignored.

Examples

#include <wchar.h>              /* wchmode, wfopen */
#include <sys/stat.h>           /* S_IWUSR */
#include <stdio.h>              /* printf */
int main()
{
        FILE * wfp = wfopen(L"fileName.txt", L"wb");            /* create file */
        if(wfp)
                {
                fclose(wfp);                                    /* close file */
                int ret = wchmod(L"fileName", S_IWUSR);         /* change mode */
                if(ret < 0)
                        {
                        printf("error changing mode");
                        return -1;
                        }
                else
                        {
                        printf("mode changed");
                        }
                }
        else
        {
        printf("error creating file");
        return -1;
        }
        return 0;
}

Output

mode changed

Errors

 The wchmod system call will fail and the file mode will be unchanged if:
[EINVAL]
 | Invalid argument.
[ENAMETOOLONG]
 | A component of a pathname exceeded 255 characters.
[ENOENT]
 | The named file does not exist.
[EACCES]
 | Search permission is denied for a component of the path prefix.

See also

 chmod, chown, open, stat

Feedback

For additional information or queries on this page send feedback


wclosedir

Name

wclosedir - closes the directory stream (directory with wide-character name)

Library

 libc.lib

Synopsis
#include <wchar.h>
#include <dirent.h>
int wclosedir (WDIR *dirp);

Return values

The wclosedir function returns 0 on success and on failure -1 is returned and the global variable errno is set to indicate the error..

Detailed description

The wclosedir function closes the named directory stream and frees the structure associated with the dirp pointer.

Examples

 /**
* Detailed description: This test code demonstrates usage of wclose  system call.
*
* Preconditions: Expects Test directory to be present in current working directory.
**/
 #include <wchar.h>
 #include <dirent.h>
int main()
{
  WDIR *DirHandle;
  if(!(DirHandle = wopendir(L"Test") ) )
  {
     printf("Failed to open directoy Test \n");
     return -1;
  }
  if(wclosedir(DirHandle) < 0 )
  {
     printf("Close dir failed \n");
     return -1;
  }
  printf("Directory Test closed \n");
  return 0;
}

Output

Directory Test closed

Errors

 The wclosedir system call will fail if:
[EBADF]
Invalid directory stream descriptor dir.

See also

 wopendir, wreaddir, opendir, readdir,

Feedback

For additional information or queries on this page send feedback


wcpcpy

Name

wcpcpy
- copy a wide character string, returning a pointer to its end

Library

 libc.lib

Synopsis
#include <wchar.h>
wchar_t * wcpcpy (wchar_t *dst , const wchar_t *src);

Return values

 The wcpcpy() function returns a pointer to the end of the wide-character string dest , that is the return pointer points to the terminating ’\0’.

See also

Detailed description

 The wcpcpy() function copies the wide-character string src to dst (including the terminating ‘\0’ character.)

Examples

#include <stdlib.h>
#include <wchar.h>
/* Illustrates how to use wcpcpy API */
int example_wcpcpy()
{
  /* input string for which length to be found */
 wchar_t *src = L"testcase";
  wchar_t *dest = NULL;
  wchar_t *destEndPtr = NULL;

  /* allocate memory for the destination string */
  dest = (wchar_t *)malloc((wcslen(src)+1)*sizeof(wchar_t));

  /*  perform the operation */
  if(dest != NULL)
   destEndPtr = (wchar_t *)wcpcpy(dest,src);
  else
   return 1;
  if(!wcscmp(dest,src))
  {
   free(dest);
   return 0;
  }
  else
  {
   free(dest);
   return 1;
  }
}

Feedback

For additional information or queries on this page send feedback


wcpncpy

Name

wcpncpy - copy a fixed-size string of wide characters, returning a pointer to its end

Library

 libc.lib

Synopsis
#include <wchar.h>
wchar_t * wcpncpy (wchar_t *dest , const wchar_t *src, size_t n);

Return values

 The wcpncpy() function returns a pointer to the wide character one past the last non-null wide character written.

Detailed description

 The wcpncpy() function copies at most n wide characters from the wide-character string src , including the terminating L’\0’ character, to dest
.Exactly n wide characters are written at dest
.If the length wcslen(src) is lesser than n , the remaining wide characters in the array dest are filled with L’\0’ characters. If the length wcslen(src) is greater than or equal to n , the string dest will not be L’\0’ terminated.

Examples

#include <stdlib.h>
#include <wchar.h>
/* Illustrates how to use wcpncpy API */
int example_wcpncpy(void)
{
  /* input string for which length to be found */
 wchar_t *src = L"testcase";
  wchar_t *dest = NULL;
  wchar_t *destEndPtr = NULL;

  /* allocate memory for the destination string */
  dest = (wchar_t *)malloc((wcslen(src)+1)*sizeof(wchar_t));

  /*  perform the operation */
  if(dest != NULL)
   destEndPtr = (wchar_t *)wcpncpy(dest,src,wcslen(src)+1);
  else
   return -1;
  /* checking for error */
  if(!wcscmp(dest,src))
  {
   wprintf(L"wcpncpy succeeded\n");
   free(dest);
   return 0;
  }
  else
  {
   wprintf(L"wcpncpy failed!!\n");
   free(dest);
   return -1;
  }
}

See also

 wcpcpy

Feedback

For additional information or queries on this page send feedback


wcreat

Name

wcreat - creates a file or device

Library

 libc.lib

Synopsis
#include <fcntl.h>
#include <wchar.h>
int wcreat (const wchar_t *path, mode_t mode);

Return values

wopen and wcreat return the new file descriptor, or -1 if an error occurred(in which case, errno is set appropriately).

Detailed description

 This interface is made obsolete by:
wopen

The wcreat function is the same as:

wopen(path, O_CREAT | O_TRUNC | O_WRONLY, mode);

Limitation :Creating a new file doesn’t alter the time stamp of parent directory, created entry has only two time stamps access and modification timestamps.
Creation time stamp of the file is not supported, here accesstime stamp is equal to modification time stamp.

Examples

/***************************************************************************************
* Detailed description   : This test code demonstrates wcreat api usage, it creates a
* in current working directory(if file exists then it is truncated.
*
* Preconditions : None
***************************************************************************************/
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <wchar.h>
int main()
{
 int fd = 0;
  fd = wcreat(L"Example.txt" , 0666);
  if(fd < 0 )
  {
    printf("File creation failed \n");
    return -1;
  }
  printf("Example.txt file created \n");
  return 0;
}

Output

Example.txt file created

See also

 wopen

Feedback

For additional information or queries on this page send feedback


wcrtomb

Name

wcrtomb - convert a wide character to a multibyte sequence

Library

 libc.lib

Synopsis
#include <wchar.h>
size_t wcrtomb (char * restrict dst, wchar_t src, mbstate_t * restrict ps);
Sh RETURN VALUES The wcrtomb functions returns the length (in bytes) of the multibyte sequence needed to represent wc, or (size_t-1) if wc is not a valid wide character code.

Detailed description

 The wcrtomb function stores a multibyte sequence representing the wide character wc, including any necessary shift sequences, to the character array s, storing a maximum of MB_CUR_MAX bytes.

If s is NULL, wcrtomb behaves as if s pointed to an internal buffer and wc was a null wide character (L’\0’).

The
mbstate_t argument, ps, is used to keep track of the shift state. If it is NULL, wcrtomb uses an internal, static mbstate_t object, which is initialized to the initial conversion state at program startup.

The behavior of the wcrtomb is affected by LC_CTYPE category of the current locale.

Examples

#include <stdio.h>
#include <stdlib.h>
#include <wchar.h>
/* Illustrates how to use wcrtomb API */
int example_wcrtomb(wchar_t wc)
{
  char s[MAX_CUR_MAX];
  size_t len;
  mbstate_t mbs;

  /* represent a wide-char in a single byte*/
  len = wcrtomb(s, wc, &mbs);
  /* return the number of bytes */
  return(len);
}

Errors

 The wcrtomb function will fail if:
[EILSEQ]
 | An invalid wide character code was specified.
[EINVAL]
 | The conversion state is invalid.

Limitations

 The current implementation of wcrtomb is not affected by the LC_CTYPE category of the current locale. It works only for UTF8 character set.

See also

 mbrtowc, setlocale, wctomb

Feedback

For additional information or queries on this page send feedback


wcscasecmp

Name

wcscasecmp - compare two wide-character strings, ignoring case

Library

 libc.lib

Synopsis
#include <wchar.h>
int wcscasecmp (const wchar_t *s1, const wchar_t *s2);
Sh RETURN VALUES The wcscasecmp() returns an integer greater than, equal to, or less than 0, according as s1 is lexicographically greater than, equal to, or less than s2 after translation of each corresponding character to lower-case. The strings themselves are not modified.

Detailed description

 The wcscasecmp() function compares the null-terminated wide-character strings s1 and s2.

Examples

#include <wchar.h>
/* Illustrates how to use wcscasecmp API */
int example_wcscasecmp(void)
{
  /* input strings which needs to be compared */
 wchar_t *ws1=L"testcasecmp";
  wchar_t *ws2=L"TESTCASECMP";

  /* function call to compare the two strings which */
  /* differ in case */
  int retval = wcscasecmp(ws1,ws2);
  /* returns 0 if they are equal or > 1 */
  /* if first string is greater than second string else -1 */
  return retval;
}

See also

 strcasecmp

Feedback

For additional information or queries on this page send feedback


wcscoll

Name

wcscoll - wide-character string comparison using collating information

Library

 libc.lib

Synopsis
#include <wchar.h>
int wcscoll (const wchar_t *s1, const wchar_t *s2);

Return values

 The wcscoll function returns an integer greater than, equal to, or less than 0, if s1 is greater than, equal to, or less than s2.

No return value is reserved to indicate errors; callers should set errno to 0 before calling wcscoll. If it is non-zero upon return from wcscoll, an error has occurred.

Detailed description

 The wcscoll function compares the null-terminated strings s1 and s2 according to the current locale collation order. In the "C" locale, wcscoll is equivalent to wcscmp.

Examples

#include <wchar.h>
/* Illustrates how to use wcscoll API */
int example_wcscoll (void)
{
        /* compares the two strings */
  if( wcscoll(L"abcdef",L"abcdeg") != L’f’-L’g’)
   return -1;
 return 0;
}

Errors

 The wcscoll function will fail if:
[EILSEQ]
 | An invalid wide character code was specified.
[ENOMEM]
 | Cannot allocate enough memory for temporary buffers.

Limitations

 The current implementation of wcscoll is not affected by the LC_CTYPE category of the current locale. It is equivalent to wcscmp in this implementation.

See also

 setlocale, strcoll, wcscmp, wcsxfrm

Bugs

 The current implementation of wcscoll only works in single-byte LC_CTYPE locales, and falls back to using wcscmp in locales with extended character sets.

Feedback

For additional information or queries on this page send feedback


wcsdup

Name

wcsdup - duplicate a wide-character string

Library

 libc.lib

Synopsis
#include <wchar.h>
wchar_t wcsdup (const wchar_t *wcs);

Return values

 The wcsdup function returns a pointer to the new wide-character string, or NULL if sufficient memory was not available.

Detailed description

 The wcsdup() function allocates sufficient memory for a copy of the wide-string wcs , does the copy, and returns a pointer to it. The pointer may subsequently be used as an argument to the function free.

If insufficient memory is available, NULL is returned and errno is set to ENOMEM.

Examples

#include <wchar.h>
/* Illustrates how to use wcsdup API */
int example_wcsdup(void)
{
  /* input string for which length has to be found */
 wchar_t *srcws=L"testwcsdup";
  wchar_t *destws = NULL;

 /* invoke the API wcsdup to duplicate the string */
  destws = wcsdup(srcws);
  /* return no error if src str and dest str are equal else return an error */
  if(!(wcscmp(srcws,destws)))
  {
    free(destws);
   return 1;
  }
  else
  {
    free(destws);
   return -1;
  }
}

See also

 strdup

Feedback

For additional information or queries on this page send feedback


wcserror

Name

wperror,wcserror
- system error messages

Library

 libc.lib

Synopsis
#include <wchar.h>
void wperror (const wchar_t *string);
#include <wchar.h>
wchar_t * wcserror (int errnum);

Return values

 The function wcserror returns the appropriate error description wide char string, or an unknown error message if the error code is unknown. The value of errno is not changed for a successful call, and is set to a nonzero value upon error.

Detailed description

 The functions wcserror and wperror look up the error message string corresponding to an error number.

The function wcserror function accepts an error number argument errnum (error number) and returns a pointer to the corresponding message string.

The function wperror finds the error message corresponding to the current value of the global variable errno and writes it, followed by a newline, to the standard error file descriptor. If the argument string is non- NULL and does not point to the null character, this wide char string is prepended to the message string and separated from it by a colon and space (": "); otherwise, only the error message string is printed.

If the error number is not recognized, these functions return an error message string containing "Unknown error: " followed by the error number in decimal. The wcserror function returns EINVAL as a warning. Error numbers recognized by this implementation fall in the range 0 < errnum < sys_nerr.

If insufficient storage is provided in strerrbuf (as specified in buflen) to contain the error string, wcserror returns ERANGE and strerrbuf will contain an error message that has been truncated and NUL terminated to fit the length specified by buflen.

Examples

#include <string.h>
#include <stdio.h>
#include <errno.h>
#include <wchar.h>
int main()
{
    wchar_t *ptr = wcserror(ERANGE);
    wprintf(L"wcserror(ERANGE) = %s\n",ptr);
    return 0;
}

Output

wcserror(ERANGE) = Numerical result out of range

See also

 perror, strerror,

Bugs

 For unknown error numbers, the function wcserror will return its result in a static buffer which may be overwritten by subsequent calls.

The return type for wcserror is missing a type-qualifier. The type-qualifier must be const wchar_t * .

Feedback

For additional information or queries on this page send feedback


wcsftime

Name

wcsftime - duplicate a wide-character string

Library

 libc.lib

Synopsis
#include <wchar.h>
size_t wcsftime (wchar_t * restrict wcs, size_t maxsize, const wchar_t * restrict format, const struct tm * restrict timeptr);

Return values

wcsftime shall return the number of wide-character codes placed into the array pointed to by wcs , not including the terminating null wide-character code. Otherwise, zero is returned and the contents of the array are unspecified.

Detailed description

 The wcsftime function is equivalent to the strftime function except for the types of its arguments. Refer to strftime for a detailed description.

Examples

#include <wchar.h>
#include <time.h>
/* Illustatrates how to use wcsftime API */
int example_wcsftime()
{
  wchar_t datestring[50];
  int retval;
  struct tm *tm;

  /* get the current time */
  time_t t = time(NULL);

  /* get the local time from the current time */
  tm = localtime(&t);
  /* convert date and time to a wide-character string */
  retval = wcsftime(datestring,15,L"%A",tm);

  /* If the total number of resulting wide-character codes */
  /* including the terminating null wide-character code is */
  /* no more than maxsize, wcsftime() shall return the number */
  /* of wide-character codes placed into the array pointed to */
  /* by wcs, not including the terminating null wide-character */
  /* code. Otherwise, zero is returned and the contents of the */
  /* array are unspecified.*/
  return retval;
}

Feedback

For additional information or queries on this page send feedback


wcsicmp

Name

wcsicmp - compare two wide-character strings, by converting them into lower-case

Library

 libc.lib

Synopsis
#include <wchar.h>
int wcsicmp (const wchar_t *wcs1, const wchar_t *wcs2);

Detailed description

 The wcsicmp() function compares the two null-terminated wide-character strings wcs1 and wcs2, by converting them into lower-case. It returns an integer value indicating the status of the comparision.

Return values

 The wcsicmp() returns an integer greater than, equal to, or less than 0, according as wcs1 is lexicographically greater than, equal to, or less than wcs2 after translation of each corresponding character to lower-case. The strings themselves are not modified.

Examples

#include <wchar.h>
/* Illustrates how to use wcsicmp API */
int example_wcsicmp(void)
{
  /* input strings which needs to be compared */
  wchar_t *ws1=L"testcasecmp";
  wchar_t *ws2=L"TESTCASECMP";

  /* function call to compare the two strings which */
  /* differ in case */
  int retval = wcsicmp(ws1,ws2);
  /* returns 0 if they are equal or > 1 */
  /* if first string is greater than second string else -1 */
  return retval;
}

See also

 strcasecmp, wcscasecmp

Feedback

For additional information or queries on this page send feedback


wcsicoll

Name

wcsicoll - wide-character string comparison using collating information

Library

 libc.lib

Synopsis
#include <wchar.h>
int wcsicoll (const wchar_t *s1, const wchar_t *s2);

Return values

 The wcsicoll function returns an integer greater than, equal to, or less than 0, if s1 is greater than, equal to, or less than s2.

No return value is reserved to indicate errors; callers should set errno to 0 before calling wcsicoll. If it is non-zero upon return from wcsicoll, an error has occurred.

Detailed description

 The wcsicoll function compares the null-terminated strings s1 and s2 according to the current locale collation order, by ignoring the case. In the "C" locale, wcsicoll is equivalent to wcsicmp.

Examples

#include <wchar.h>
/* Illustrates how to use wcsicoll API */
int example_wcsicoll (void)
{
        /* compares the two strings */
  if( wcsicoll(L"abcdef",L"abcdeg") != L’f’-L’g’)
   return -1;
 return 0;
}

Errors

 The wcsicoll function will fail if:
[EILSEQ]
 | An invalid wide character code was specified.
[ENOMEM]
 | Cannot allocate enough memory for temporary buffers.

Limitations

 The current implementation of wcsicoll is not affected by the LC_CTYPE category of the current locale. It is equivalent to wcsicmp in this implementation.

See also

 setlocale, strcoll, wcsicmp, wcsxfrm

Bugs

 The current implementation of wcsicoll only works in single-byte LC_CTYPE locales, and falls back to using wcsicmp in locales with extended character sets.

Feedback

For additional information or queries on this page send feedback


wcslen

Name

wcslen - determine the length of a wide-character string

Library

 libc.lib

Synopsis
#include <wchar.h>
size_t wcslen (const wchar_t *wcs);

Detailed description

 The wcslen() function computes the length of the wide-character string wcs.

Examples

#include <wchar.h>
/* Illustrates how to use wcslen API */
size_t example_wcslen(void)
{
 wchar_t *wcs = L"defqwert";
 size_t len;
 /* compute the length of the wide-char string */
 len = wcslen(wcs);
 /* return the length of the wide-char string */
 return (len);
 .Ed

Return value

 The wcslen() returns the number of wide-characters that precede the terminating NULL character.

Security considerations

 Please refer strlen

See also

 strlen

Feedback

For additional information or queries on this page send feedback


wcslwr

Name

wcslwr - converts the wide-character string to lower-case wide-character string.

Library

 libc.lib

Synopsis
#include <wchar.h>
wchar_t* wcslwr (wchar_t *wcs);

Detailed description

 The wcslwr() function converts each letter from the wide-character string wcs to lower-case. The conversion is determined by the LC_CTYPE category setting of the locale. Other characters are not affected. It returns a pointer to the altered string. Because the modification is done in place, the pointer returned is the same as the pointer passed as the input argument.

Return values

 The wcslwr() returns a pointer to the altered string, on successful conversion of wcs, else it returns NULL pointer.

Examples

#include <wchar.h>
/* Illustrates how to use wcslwr API */
int example_wcslwr(void)
{
  /* input string which needs to be converted to lower-case */
  wchar_t src[9]=L"TESTCASE";

  /* expected result string */
  wchar_t *exp=L"testcase";

  wchar_t *res = NULL;

  /* function call to convert the src to lower-case */
  res = wcslwr(src);
  /* compare res string with exp string, if they are equal then return 0, else return -1 */
  if( res != NULL && !wcscmp(res,exp))
        return 0;
  else
        return -1;
}

See also

 strupr, strlwr, towupper, towlower, wcsupr

Feedback

For additional information or queries on this page send feedback


wcsncasecmp

Name

wcsncasecmp - compare two fixed-size wide-character strings, ignoring case

Library

 libc.lib

Synopsis
#include <wchar.h>
int wcsncasecmp (const wchar_t *s1, const wchar_t *s2, size_t n);

Return values

 The wcsncasecmp() returns an integer greater than, equal to, or less than 0, according as s1 is lexicographically greater than, equal to, or less than s2 after translation of each corresponding character to lower-case. The strings themselves are not modified.

Detailed description

 The wcsncasecmp() function compares atmost n wide-characters from the null-terminated wide-character strings s1 and s2.

Examples

#include <wchar.h>
/* Illustrates how to use wcsncasecmp API */
int example_wcsncasecmp()
{
  /* input strings which need to be compared */
 wchar_t *ws1=L"testcasecmp";
  wchar_t *ws2=L"TESTCASECMP";

  /* function call to compare the two strings which */
  /* differ in case */
  int retval = wcsncasecmp(ws1,ws2,11);
  /* returns 0 if they are equal except the case or >1 */
  /* if first string is greater than second string else -1 */
  return retval;
}

See also

 strncasecmp

Feedback

For additional information or queries on this page send feedback


wcsncoll

Name

wcsncoll - wide-character string comparison using collating information

Library

 libc.lib

Synopsis
#include <wchar.h>
int wcsncoll (const wchar_t *s1, const wchar_t *s2, int n);

Return values

 The wcsncoll function returns an integer greater than, equal to, or less than 0, if s1 is greater than, equal to, or less than s2.

No return value is reserved to indicate errors; callers should set errno to 0 before calling wcsncoll. If it is non-zero upon return from wcsncoll, an error has occurred.

Detailed description

 The wcsncoll function compares the first n chars from the two null-terminated strings s1 and s2 according to the current locale collation order. In the "C" locale, wcsncoll is equivalent to wcscmp.

Examples

#include <wchar.h>
/* Illustrates how to use wcsncoll API */
int example_wcsncoll (void)
{
        /* compares the two strings */
  if( wcsncoll(L"abcdef",L"abcdeg",7) != L’f’-L’g’)
   return -1;
 return 0;
}

Errors

 The wcsncoll function will fail if:
[EILSEQ]
 | An invalid wide character code was specified.
[ENOMEM]
 | Cannot allocate enough memory for temporary buffers.

Limitations

 The current implementation of wcsncoll is not affected by the LC_CTYPE category of the current locale. It is equivalent to wcscoll in this implementation.

See also

 setlocale, strcoll, wcscoll, wcsncmp, wcsxfrm

Bugs

 The current implementation of wcsncoll only works in single-byte LC_CTYPE locales, and falls back to using wcscoll in locales with extended character sets.

Feedback

For additional information or queries on this page send feedback


wcsnicmp

Name

wcsnicmp - compare two wide-character strings, by converting them into lower-case

Library

 libc.lib

Synopsis
#include <wchar.h>
int wcsnicmp (const wchar_t *wcs1, const wchar_t *wcs2, int n);

Detailed description

 The wcsnicmp() function compares the first n characters from two null-terminated wide-character strings wcs1 and wcs2, by converting them into lower-case. It returns an integer value indicating the status of the comparision.

Return values

 The wcsnicmp() returns an integer greater than, equal to, or less than 0, according as wcs1 is lexicographically greater than, equal to, or less than wcs2 after translation of each corresponding character to lower-case. The strings themselves are not modified.

Examples

#include <wchar.h>
/* Illustrates how to use wcsnicmp API */
int example_wcsnicmp(void)
{
  /* input strings which needs to be compared */
  wchar_t *ws1=L"testcasecmp";
  wchar_t *ws2=L"TESTCASECMP";

  /* function call to compare the two strings which */
  /* differ in case */
  int retval = wcsnicmp(ws1,ws2,12);
  /* returns 0 if they are equal or > 1 */
  /* if first string is greater than second string else -1 */
  return retval;
}

See also

 strcasecmp, wcscasecmp, wcsncasecmp

Feedback

For additional information or queries on this page send feedback


wcsnicoll

Name

wcsnicoll - wide-character string comparison using collating information

Library

 libc.lib

Synopsis
#include <wchar.h>
int wcsnicoll (const wchar_t *s1, const wchar_t *s2, int n);

Return values

 The wcsnicoll function returns an integer greater than, equal to, or less than 0, if s1 is greater than, equal to, or less than s2.

No return value is reserved to indicate errors; callers should set errno to 0 before calling wcsnicoll. If it is non-zero upon return from wcsnicoll, an error has occurred.

Detailed description

 The wcsnicoll function compares the null-terminated strings s1 and s2 according to the current locale collation order. In the "C" locale, wcsnicoll is equivalent to wcsncasecmp.

Examples

#include <wchar.h>
/* Illustrates how to use wcsnicoll API */
int example_wcsnicoll (void)
{
        /* compares the two strings */
  if( wcsnicoll(L"abcdef",L"abcdeg",7) != L’f’-L’g’)
   return -1;
 return 0;
}

Errors

 The wcsnicoll function will fail if:
[EILSEQ]
 | An invalid wide character code was specified.
[ENOMEM]
 | Cannot allocate enough memory for temporary buffers.

Limitations

 The current implementation of wcsnicoll is not affected by the LC_CTYPE category of the current locale. It is equivalent to wcsncasecmp in this implementation.

See also

 setlocale, strcoll, wcscmp, wcsxfrm, wcsncasecmp

Bugs

 The current implementation of wcsnicoll only works in single-byte LC_CTYPE locales, and falls back to using wcsncoll in locales with extended character sets.

Feedback

For additional information or queries on this page send feedback


wcsnlen

Name

wcsnlen - determine the length of a fixed-size wide-character string

Library

 libc.lib

Synopsis
#include <wchar.h>
size_t wcsnlen (const wchar_t *wcs, size_t maxlen);

Detailed description

 The wcsnlen() function computes the length of the wide-character string wcs not including the terminating NUL character. It looks at only first maxlen
wide-characters in wcs and never beyond wcs+maxlen.

Examples

#include <wchar.h>
/* Illustrates how to use wcsnlen API */
size_t example_wcsnlen()
{
  /* input string for which length to be found */
 wchar_t *ws=L"testwcsnlen";

  /* find the length of the wide char string by */
  /* calling wcsnlen */
  size_t retval = wcsnlen(ws,14);
 /* return the number of wide chars in the string */
 /* if retval is less than 14 Else return 14 as the */
 /* length of the string */
 return retval;
}

Return value

 The wcsnlen() returns the number of wide-characters that precede the terminating NUL character if it is less than maxlen or maxlen if there is a terminating NUL character among maxlen characters pointed by wcs.

See also

 strnlen

Feedback

For additional information or queries on this page send feedback


wcsnset

Name

wcsnset - sets first n characters of the wide-character string to the specified wide-char.

Library

 libc.lib

Synopsis
#include <wchar.h>
wchar_t* wcsnset (wchar_t *wcs, wchar_t wc, int n);

Detailed description

 The wcsnset() function sets first n characters of the wide-character string wcs to the wide-character specified by wc. If n is greater than the length of wcs, then length of wcs is used instead of n. It returns a pointer to the altered string, which is same as the source string passed to wcsnset as it is modified in place.

Return values

 The wcsnset() returns a pointer to the altered string, on success, else it returns NULL pointer.

Examples

#include <wchar.h>
/* Illustrates how to use wcsnset API */
int example_wcsnset(void)
{
  /* input string which needs to be set to the character specified by wc. */
  wchar_t wcs[9]=L"kohinoor";
  wcgar_t wc = L’K’;
  int n = 3;

  /* expected result string */
  wchar_t *exp=L"KKKinoor";

  wchar_t *res = NULL;

  /* function call to set first n chars in wcs to wc*/
  res = wcsnset(wcs, wc, n);
  /* compare res string with exp string, if they are equal then return 0, else return -1 */
  if( res != NULL && !wcscmp(res,exp))
        return 0;
  else
        return -1;
}

See also

 strset, wcsset

Feedback

For additional information or queries on this page send feedback


wcsrev

Name

wcsrev - reverts the wide-character string.

Library

 libc.lib

Synopsis
#include <wchar.h>
wchar_t* wcsrev (wchar_t *wcs);

Detailed description

 The wcsrev() function reverses the order of the characters in the wide-character string wcs. The terminating null character remains in place.The arguments and return value of wcsrev are wide-character strings; It returns a pointer to the altered string. the pointer returned is the same as the pointer passed as the input argument.

Return values

 The wcsrev() returns a pointer to the reverted string, on success, else it returns NULL pointer.

Examples

#include <wchar.h>
/* Illustrates how to use wcsrev API */
int example_wcsrev(void)
{
  /* input string which needs to be reverted. */
  wchar_t src[9]=L"kohinoor";

  /* expected result string */
  wchar_t *exp=L"roonihok";

  wchar_t *res = NULL;

  /* function call to revert the src */
  res = wcsrev(src);
  /* compare res string with exp string, if they are equal then return 0, else return -1 */
  if( res != NULL && !wcscmp(res,exp))
        return 0;
  else
        return -1;
}

See also

 strrev

Feedback

For additional information or queries on this page send feedback


wcsrtombs

Name

wcsrtombs, wcsnrtombs
- convert a wide character string to a multibyte string

Library

 libc.lib

Synopsis
#include <wchar.h>
size_t wcsrtombs (char * restrict dst, const wchar_t ** restrict src, size_t len, mbstate_t * restrict ps);
size_t wcsnrtombs (char * restrict dst, const wchar_t ** restrict src, size_t nwc, size_t len, ,, mbstate_t, *, restrict, ps);

Return values

 The wcsrtombs and wcsnrtombs functions return the number of bytes stored in the array pointed to by dst (not including any terminating null), if successful, otherwise it returns (size_t-1).

Detailed description

 The wcsrtombs function converts a string of wide characters indirectly pointed to by src to a corresponding multibyte character string stored in the array pointed to by dst. No more than len bytes are written to dst.

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 character after the one that conversion stopped at. If conversion stops because a null character is encountered, *src is set to NULL.

The mbstate_t argument, ps, is used to keep track of the shift state. If it is NULL, wcsrtombs uses an internal, static mbstate_t object, which is initialized to the initial conversion state at program startup.

The wcsnrtombs function behaves identically to wcsrtombs, except that conversion stops after reading at most nwc characters from the buffer pointed to by src. The behavior of the wcsrtombs and wcsrntombs is affected by LC_CTYPE category of the current locale.

Examples

#include <stdlib.h>
#include <wchar.h>
/* Illustrates how to use wcsrtombs API */
size_t example_wcsrtombs(wchar_t *wcs, char *s, size_t n)
{
 size_t len;
 mstate_t mbs;
 /* converting multibyte string to a wide-char string */
 len = wcsrtombs(s, &wcs, n, &mbs);
 /* returning no of bytes that make up the multibyte sequence */
 return (len;);
}

#include <stdlib.h>
#include <wchar.h>
/* Illustrates how to use wcsnrtombs API */
size_t example_wcsnrtombs(wchar_t *wcs, char *s, size_t n, szie_t nmwc)
{
 size_t len;
 mstate_t mbs;
 /* converting multibyte string to a wide-char string */
 len = wcsrtombs(s, &wcs, nwc, n, &mbs);
 /* returning no of bytes that make up the multibyte sequence */
 return (len;);
}

Errors

 The wcsrtombs and wcsnrtombs functions will fail if:
[EILSEQ]
 | An invalid wide character was encountered.
[EINVAL]
 | The conversion state is invalid.

Limitations

 The current implementation of wcsrtombs and wcsnrtombs is not affected by the LC_CTYPE category of the current locale. It works only for UTF8 character set.

See also

 mbsrtowcs, wcrtomb, wcstombs
The wcsrtombs function conforms to -isoC-99.

The wcsnrtombs function is an extension to the standard.

Feedback

For additional information or queries on this page send feedback


wcsset

Name

wcsset - sets all the characters of the wide-character string to the specified wide-char.

Library

 libc.lib

Synopsis
#include <wchar.h>
wchar_t* wcsset (wchar_t *wcs, wchar_t wc);

Detailed description

 The wcsset() function sets all the characters of the wide-character string wcs to the wide-character specified by wc, except the terminating null character. It returns a pointer to the altered string, which is same as the source string passed to wcsset as it is modified in place.

Return values

 The wcsset() returns a pointer to the altered string, on success, else it returns NULL pointer.

Examples

#include <wchar.h>
/* Illustrates how to use wcsset API */
int example_wcsset(void)
{
  /* input string which needs to be set to the character specified by wc. */
  wchar_t wcs[9]=L"kohinoor";
  wcgar_t wc = L’K’;

  /* expected result string */
  wchar_t *exp=L"KKKKKKKK";

  wchar_t *res = NULL;

  /* function call to set all the chars in wcs to wc*/
  res = wcsset(wcs, wc);
  /* compare res string with exp string, if they are equal then return 0, else return -1 */
  if( res != NULL && !wcscmp(res,exp))
        return 0;
  else
        return -1;
}

See also

 strset, wcsnset

Feedback

For additional information or queries on this page send feedback


wcstod

Name

wcstof, wcstod, wcstold
- convert a wide-character string to a double-precision number

Library

 libc.lib

Synopsis
#include <wchar.h>
float wcstof (const wchar_t * restrict src, wchar_t ** restrict endptr);
long double wcstold (const wchar_t * restrict src, wchar_t ** restrict endptr);
double wcstod (const wchar_t * restrict src, wchar_t ** restrict endptr);

Return values

Detailed description

 The wcstof, wcstod and wcstold functions are the wide-character versions of the strtof, strtod and strtold functions. Refer to strtod for details.

Examples

#include <wchar.h>
/* Illustrates how to use wcstof API */
int example_wcstof()
{
  /* src string */
  wchar_t wcs1[21] = L"  1.23abcd";
  wchar_t wcs2[5]=L"abcd";
  wchar_t *eptr;
  float d;

 /* convert wide-char string to float */
  d = wcstof(wcs1, &eptr);

  /* compare the result */
  if((d == 1.23F) && !(wcscmp (eptr, wcs2)))
   return 0;
  else
   return 1;
}

#include <wchar.h>
/* Illustrates how to use wcstold API */
int example_wcstold()
{
  /* src string */
  wchar_t wcs1[21] = L"  1.23abcd";
  wchar_t wcs2[5]=L"abcd";
  wchar_t *eptr;
  double d;

  /* convert wide-char string to double */
  d = wcstod(wcs1, &eptr);

  /* compare the result */
  if((d == 1.23) && !(wcscmp (eptr, wcs2)))
   return 0;
  else
   return 1;
}

#include <wchar.h>
/* Illustrates how to use wcstold API */
int example_wcstold()
{
  /* src string */
  wchar_t wcs1[21] = L"  1.23abcd";
  wchar_t wcs2[5]=L"abcd";
  wchar_t *eptr;
  long double d;

  /* convert wide-char string to long double */
  d = wcstold(wcs1, &eptr);

  /* compare the result *
  if((d == 1.23) && !(wcscmp (eptr, wcs2)))
   return 0;
  else
  return 1;
}

See also

 strtod, wcstol
The wcstof, wcstod and wcstold functions conform to -isoC-99.

Feedback

For additional information or queries on this page send feedback


wcstok

Name

wcstok - split wide-character string into tokens

Library

 libc.lib

Synopsis
#include <wchar.h>
wchar_t * wcstok (wchar_t * restrict str, const wchar_t * restrict sep, wchar_t ** restrict last);

Return values

 The wcstok function returns a pointer to the beginning of each subsequent token in the string, after replacing the token itself with a null wide character (L’\0’). When no more tokens remain, a null pointer is returned.

Detailed description

 The wcstok function is used to isolate sequential tokens in a null-terminated wide character string, str. These tokens are separated in the string by at least one of the characters in sep. The first time that wcstok is called, str should be specified; subsequent calls, wishing to obtain further tokens from the same string, should pass a null pointer instead. The separator string, sep, must be supplied each time, and may change between calls. The context pointer last must be provided on each call.

The wcstok function is the wide character counterpart of the strtok_r function.

Examples

#include <wchar.h>
/* Illustrates how to use wcstok API */
int example_wcstok()
{
  /* source wide character string */
 const wchar_t *seps = L"onetwhr";
 wchar_t *last, *tok, text[] = L"onetwothree";

 tok = wcstok(text, seps, &last);
 if(tok == NULL)
   return 0;
 else
    return 1;
}

Examples

 The following code fragment splits a wide character string on ASCII space, tab and newline characters and writes the tokens to standard output:
const wchar_t *seps = L" \t\n";
wchar_t *last, *tok, text[] = L" \none\ttwo\t\tthree  \n";
for (tok = wcstok(text, seps, &last); tok != NULL;
    tok = wcstok(NULL, seps, &last))
        wprintf(L"%ls\n", tok);

Compatibility

 Some early implementations of wcstok omit the context pointer argument, last, and maintain state across calls in a static variable like strtok does.

See also

 strtok, wcschr, wcscspn, wcspbrk, wcsrchr, wcsspn
The wcstok function conforms to -isoC-99.

Feedback

For additional information or queries on this page send feedback


wcstol

Name

wcstol, wcstoul, wcstoll, wcstoull, wcstoimax, wcstoumax, wcstoq, wcstouq
- convert a wide-character string to a long integer long , unsigned long , long long , unsigned long long , intmax_t or uintmax_t long long , unsigned long long , integer

Library

 libc.lib

Synopsis
#include <wchar.h>
long wcstol (const wchar_t * restrict src, wchar_t ** restrict endptr, int base);
unsigned long wcstoul (const wchar_t * restrict src, wchar_t ** restrict endptr, int base);
long long wcstoll (const wchar_t * restrict src, wchar_t ** restrict endptr, int base);
unsigned long long wcstoull (const wchar_t * restrict src, wchar_t ** restrict endptr, int base);
long long wcstoq (const wchar_t * restrict src, wchar_t ** restrict endptr, int base);
unsigned long long wcstouq (const wchar_t * restrict src, wchar_t ** restrict endptr, int base);
#include <inttypes.h>
intmax_t wcstoimax (const wchar_t * restrict src, wchar_t ** restrict endptr, int base);
uintmax_t wcstoumax (const wchar_t * restrict src, wchar_t ** restrict endptr, int base);

Return values

errno may be set to indicate the error. If the correct value is outside the range of representable values, {LONG_MIN}, {LONG_MAX}, {LLONG_MIN}, or {LLONG_MAX} shall be returned (according to the sign of the value), and errno set to [ERANGE].

Detailed description

 The wcstol, wcstoul, wcstoll, wcstoull, wcstoimax and wcstoumax functions are wide-character versions of the strtol, strtoul, strtoll, strtoull, strtoimax and strtoumax functions, respectively. Refer to their manual pages (for example strtol) for details. The wcstoq and wcstouq are respectively equivalent to wcstoll and wcstoull.

Examples

#include <wchar.h>
/* Illustrates how to use wcstoumax API */
uintmax_t example_wcstoumax()
{
  /* src string */
 wchar_t *src = L"478";
  uintmax_t longVal;

  /* convert the wide character string to uintmax_t */
  longVal = wcstoumax(src,NULL,10);
  /* return the converted long value */
 return longVal;
}

#include <wchar.h>
/* Illustrates how to use wcstoimax API */
intmax_t example_wcstoimax()
{
  /* src string */
 wchar_t *src = L"478";
  intmax_t longVal;

  /* convert the wide character string to intmax_t */
  longVal = wcstoimax(src,NULL,10);
  /* return the converted long value */
 return longVal;
}

#include <wchar.h>
/* Illustrates how to use wcstol API */
long example_wcstol()
{
  /* src string */
 wchar_t *src = L"478";
  long  longVal;

  /* call the API to convert src string to long value */
  longVal = wcstol(src,NULL,10);
  /* return the converted long value */
 return longVal;
}

#include <wchar.h>
/* Illustrates how to use wcstoul API */
unsigned long example_wcstoul()
{
  /* src string */
  wchar_t *src = L"478";
  unsigned long  longVal;

  /* call the API to convert src string to unsigned */
  /* long value */
  longVal = wcstoul(src,NULL,10);
  /* return the converted long value */
 return longVal;
}

#include <wchar.h>
/* Illustatrates how to use wcstoll API */
long long example_wcstoll()
{
  /* input string for which length to be found */
 wchar_t *src = L"478";
 long long  longVal;

  /* perform the conversion operation from wide */
  /* char string to long long value */
  longVal = wcstoll(src,NULL,10);

  return longVal;
}

#include <wchar.h>
/* Illustatrates how to use wcstoull API */
unsigned long long example_wcstoull()
{
  /* input string for which length to be found */
 wchar_t *src = L"478";
  unsigned long long  longVal;

  /* perform the conversion operation from wide */
  /*char string to unsigned long long value */
  longVal = wcstoull(src,NULL,10);

  return longVal;
}

#include <wchar.h>
/* Illustrates how to use wcstoq API */
long long int example_wcstoq()
{
 /* src string that contains decimal digits */
 wchar_t *src = L"478";
 long long int  longVal;
 /* convert the decimal wide char string to long long int value */
 longVal = wcstoq(src,NULL,10);
 /* return longVal and its value should be 478 */
 return longVal;
}

#include <wchar.h>
/* Illustrates how to use wcstouq API */
unsigned long long int example_wcstouq()
{
 /* src string that contains decimal digits */
 wchar_t *src = L"478";
 unsigned long long int  longVal;
 /* convert the decimal wide char string  to unsigned long long int value */
 longVal = wcstouq(src,NULL,10);
 /* return longVal, which should be 478 */
 return longVal;
}

See also

 strtol, strtoul
The wcstol, wcstoul, wcstoll, wcstoull, wcstoimax and wcstoumax functions conform to -isoC-99.

Feedback

For additional information or queries on this page send feedback


wcstombs

Name

wcstombs - convert a wide character string to a multibyte string

Library

 libc.lib

Synopsis
#include <stdlib.h>
size_t wcstombs (char * restrict dst, const wchar_t * restrict src, size_t nbytes);

Return values

 The wcstombs function returns the number of bytes converted (not including any terminating null), if successful, otherwise it returns (size_t-1).

Detailed description

 The wcstombs function converts a wide character string wcstring into a multibyte character string, mbstring, beginning in the initial conversion state. Up to nbytes bytes are stored in mbstring. Partial multibyte characters at the end of the string are not stored. The multibyte character string is null terminated if there is room.

The behavior of the wcstombs is affected by LC_CTYPE category of the current locale.

Examples

#include <stdlib.h>
#include <wchar.h>
/* Illustrates how to use wcstombs API */
size_t example_wcstombs(wchar_t *wcs, char *s, size_t n)
{
 size_t len;
 /* converting multibyte string to a wide-char string */
 len = wcstombs(s, (const wchar_t *)wcs, n);
 /* returning no of bytes that make up the multibyte sequence */
 return (len;);
}

Errors

 The wcstombs function will fail if:
[EILSEQ]
 | An invalid wide character was encountered.
[EINVAL]
 | The conversion state is invalid.

Limitations

 The current implementation of wcstombs is not affected by the LC_CTYPE category of the current locale. It works only for UTF8 character set.

See also

 mbstowcs, wcsrtombs, wctomb

Feedback

For additional information or queries on this page send feedback


wcsupr

Name

wcsupr - converts the wide-character string to upper-case wide-character string.

Library

 libc.lib

Synopsis
#include <wchar.h>
wchar_t* wcsupr (wchar_t *wcs);

Detailed description

 The wcsupr() function converts each letter from the wide-character string wcs to upper-case. The conversion is determined by the LC_CTYPE category setting of the locale. Other characters are not affected. It returns a pointer to the altered string. Because the modification is done in place, the pointer returned is the same as the pointer passed as the input argument.

Return values

 The wcsupr() returns a pointer to the altered string, on successful conversion of wcs, else it returns NULL pointer.

Examples

#include <wchar.h>
/* Illustrates how to use wcsupr API */
int example_wcsupr(void)
{
  /* input string which needs to be converted to upper-case */
  wchar_t src[9]=L"testcase";

  /* expected result string */
  wchar_t *exp=L"TESTCASE";

  wchar_t *res = NULL;

  /* function call to convert the src to upper-case */
  res = wcsupr(src);
  /* compare res string with exp string, if they are equal then return 0, else return -1 */
  if( res != NULL && !wcscmp(res,exp))
        return 0;
  else
        return -1;
}

See also

 strupr, towupper, towlower, wcslwr

Feedback

For additional information or queries on this page send feedback


wcswcs

Name

wcswcs - find a wide substring

Library

 libc.lib

Synopsis
#include <wchar.h>
wchar_t * wcswcs (const wchar_t *wcs1, const wchar_t *wcs2);

Detailed description

 The wcswcs() function locates the first occurrence of the wide-character string pointed by wcs1 (excluding the terminating ’\0’ character in the wide-character string pointed by wcs2.

Examples

#include <wchar.h>
/* Illustrates how to use wcswcs API */
int example_wcswcs()
{
  /* source wide character string */
 wchar_t *buf[20] = { L"fkhsdf%%38",L"rtti123123", };
 wchar_t *str  = wcswcs(buf[0],L"");
 wchar_t *str1 = wcswcs(buf[1],L"\0");
 if(wcscmp(str,buf[0]))
   return 1;
 if(wcscmp(str1,buf[1]))
   return 1
 return 0;
}

Return value

 The wcswcs() on success returns a pointer to the located wide-character string and returns a NULL pointer if the wide-charcter string was not found.

If wcs2 is a wide-character string with length as zero, the function returns wcs1.

See also

 strstr

Feedback

For additional information or queries on this page send feedback


wcswidth

Name

wcswidth - determine columns needed for a fixed-size wide character

Library

 libc.lib

Synopsis
#include <wchar.h>
int wcswidth (const wchar_t *pwcs, size_t n);

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 column positions occupied.

Detailed description

 The wcswidth function determines the number of column positions required for the first n characters of pwcs, or until a null wide character (L’\0’) is encountered.

The behavior of the wcswdith is affected by LC_CTYPE category of the current locale.

Examples

#include <wchar.h>
/* Illustrates how to use wcswidth API */
int example_wcswidth()
{
  /* wide character string for which width has to */
  /* determined */
  wchar_t *ws1 = L"test case";
  int retval;
  /* compute the width of the ws1 */
  retval = wcswidth(ws1,50);
 /* return the result */
  return retval;
}

Limitations

 The current implementation of wcswidth is dependent on the locale support of SYMBIAN. It doesn’t work for the locales which the SYMBIAN doesn’t support.

See also

 iswprint, wcwidth
The wcswidth function conforms to -p1003.1-2001.

Feedback

For additional information or queries on this page send feedback


wcsxfrm

Name

wcsxfrm - wide-character string transformation

Library

 libc.lib

Synopsis
#include <wchar.h>
size_t wcsxfrm (wchar_t * restrict dst, const wchar_t * restrict src, size_t n);

Return values

 Upon successful completion, wcsxfrm returns the length of the transformed string not including the terminating null character. If this value is n or more, the contents of dst are indeterminate.

Detailed description

 The wcsxfrm function transforms a null-terminated wide character string pointed to by src according to the current locale collation order then copies the transformed string into dst. No more than n wide characters are copied into dst, including the terminating null character added. If n is set to 0 (it helps to determine an actual size needed for transformation), dst is permitted to be a NULL pointer.

Comparing two strings using wcscmp after wcsxfrm is equivalent to comparing two original strings with wcscoll.

Examples

#include <stdlib.h>
#include <wchar.h>
/* Illustrates how to use wcpcpy API */
int example_wcpcpy()
{
  /* input string for which length to be found */
 wchar_t *src = L"testcase";
  wchar_t *dest = NULL;
  int      length;

  /* allocate memory for the destination string */
  dest = (wchar_t *)malloc((wcslen(src)+1)*sizeof(wchar_t));

  /*  perform the operation */
  if(dest != NULL)
   length = wcsxfrm(dest,src,9);
  else
  {
   wprintf(L"ERROR : Cannot allocate memory");
  return -1;
  }
  return length;
}

Limitations

 The current implementation of wcsxfrm works only for "C" locale.

See also

 setlocale, strxfrm, wcscmp, wcscoll

Bugs

 The current implementation of wcsxfrm only works in single-byte LC_CTYPE locales, and falls back to using wcsncpy in locales with extended character sets.

Comparing two strings using wcscmp after wcsxfrm is not always equivalent to comparison with wcscoll; wcsxfrm only stores information about primary collation weights into dst, whereas wcscoll compares characters using both primary and secondary weights.

Feedback

For additional information or queries on this page send feedback


wctime

Name

wasctime, wctime
-transforms date and time to a wide char string to the form: Sun Sep 16 01:03:52 1973

Library

 libc.lib

Synopsis
#include <wchar.h>
wchar_t * wctime (const time_t *clock);
wchar_t * wasctime (const struct tm *tm);

Return values

 The functions wasctime and wctime return a pointer to the resulting wide-character string.

Detailed description

 The function wctime, takes a time value representing, the time in seconds since the Epoch (00:00:00 UTC, January 1, 1970); as an argument. See time

The function wctime adjusts the time value for the current time zone in the same manner as localtime, and returns a pointer to a 26-wide character string of the form:

Thu Nov 24 18:22:48 1986\n\0

All the fields have constant width.

The function wasctime converts the broken down time in the structure tm pointed at, by *tm to the form shown in the example above.

External declarations as well as the tm structure definition are in the
#include <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.

Examples

//Example usage of wasctime and wctime:
#include <time.h>
#include <stdio.h>
int main(){
        time_t t;
        struct tm *timeptr;
        wchar_t* wasc_time;
        t = time (NULL); //Get current time in seconds from Epoc
        //Fill tm struct w.r.t localtime using localtime
        timeptr = localtime (&t);
        //Use this to convert it to a string indicating time w.r.t localtime
        wasc_time = wasctime (timeptr);
        wprintf (L"Time from wasctime w.r.t localtime : %s", wasc_time);
                wprintf(L"Time from wctime w.r.t localtime : %s0, wctime(&t) );
         return 0;
}

Output

Time from wasctime w.r.t localtime : Thu Jun 22 10:42:27 2006
Time from wctime w.r.t localtime : Thu Jun 22 10:42:27 2006

See also

 asctime, ctime

Bugs

 These functions leave their result in an internal static object and return a pointer to that object. Subsequent calls to these functions will modify the same object.

The C Standard provides no mechanism for a program to modify its current local timezone 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 subsequent call to tzset )

Feedback

For additional information or queries on this page send feedback


wctomb

Name

wctomb - convert a wide character to a multibyte sequence

Library

 libc.lib

Synopsis
#include <stdlib.h>
int wctomb (char *dst, wchar_t src);

Return values

 If mbchar is NULL, the wctomb function returns nonzero if shift states are supported, zero otherwise. If mbchar is valid, wctomb returns the number of bytes processed in mbchar, or -1 if no multibyte character could be recognized or converted. In this case, wctomb (Ns, ’s);
internal conversion state is undefined.

Detailed description

 The wctomb function converts a wide character wchar into a multibyte character and stores the result in mbchar. The object pointed to by mbchar must be large enough to accommodate the multibyte character, which may be up to MB_LEN_MAX bytes.

A call with a null mbchar pointer returns nonzero if the current locale requires shift states, zero otherwise; if shift states are required, the shift state is reset to the initial state.

The behavior of the wctomb is affected by LC_CTYPE category of the current locale.

Examples

#include <stdlib.h>
#include <wchar.h>
/* Illustrates how to use wctomb API */
int example_wctomb(wchar_t wc)
{
 char s[MAX_CUR_MAX];
  int len;

  /* represent a wide-char in a single byte*/
  len = wctomb(s, wc);
  /* return the number of bytes */
  return(len);
}

Errors

 The wctomb function will fail if:
[EILSEQ]
 | An invalid multibyte sequence was detected.
[EINVAL]
 | The internal conversion state is invalid.

Limitations

 The current implementation of wctomb is not affected by the LC_CTYPE category of the current locale. It works only for UTF8 character set.

See also

 mbtowc, wcrtomb, wcstombs, wctob

Feedback

For additional information or queries on this page send feedback


wctrans

Name

towctrans, wctrans
- wide character translation mapping

Library

 libc.lib

Synopsis
#include <wctype.h>
wint_t towctrans (wint_t wc, wctrans_t desc);
wctrans_t wctrans (const char *charclass);

Return values

 The towctrans function returns the transliterated character if successful, otherwise it returns the character unchanged and sets errno.

The wctrans function returns non-zero if successful, otherwise it returns zero and sets errno.

Detailed description

 The wctrans function returns a value of type wctrans_t which represents the requested wide character mapping operation and may be used as the second argument for calls to towctrans.

The following character mapping names are recognised:
tolower toupper

The towctrans function transliterates the wide character wc according to the mapping described by desc.

The behavior of the wctrans and towtrans is affected by LC_CTYPE category of the current locale.

Examples

#include <wchar.h>
/* Illustrates how to use wctrans API */
wctrans_t example_wctrans()
{
  wctrans_t type;

  /* get the type by passing the operation string to the wctrans API */
 type = wctrans("alnum");

 /* if the operation is successful then it should return non-zero value else returns 0 */
  return type;
}

#include <wchar.h>
#include <wctype.h>
/* Illustrates how to use towctrans API */
TInt example_towctrans(void)
{
 wctrans_t type;
 /* get the type by passing the string */
 type = wctrans("tolower");

 /* if the type is 0 then return an error, else call the API to translate */
 if(type == (wctype_t)0)
  return -1;
  /* translate the input char to specified type */
 wint_t twc = towctrans(L’K’,type);
 /* return no error if conversion is ok else return error */
 if(twc != (wint_t)L’k’)
   return -1;

  return 1;
}

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.

Limitations

 The current implementation of wctrans and towtrans is dependent on the locale support of SYMBIAN. It doesn’t work for the locales which the SYMBIAN doesn’t support.

See also

 tolower, toupper, wctype

Feedback

For additional information or queries on this page send feedback


wctype

Name

iswctype, wctype
- wide character classification

Library

 libc.lib

Synopsis
#include <wctype.h>
int iswctype (wint_t wc, wctype_t charclass);
wctype_t wctype (const char *property);

Return values

 The iswctype function returns non-zero if and only if wc has the property described by charclass, or charclass is zero.

The wctype function returns 0 if property is invalid, otherwise it returns a value of type wctype_t that can be used in subsequent calls to iswctype.

Detailed description

 The wctype function returns a value of type wctype_t which represents the requested wide character class and may be used as the second argument for calls to iswctype.

The following character class names are recognised:
alnum cntrl ideogram print space xdigit
alpha digit lower punct special
blank graph phonogram rune upper

The iswctype function checks whether the wide character wc is in the character class charclass.

The behavior of the iswctype ans wctype is affected by LC_CTYPE category of the current locale.

Examples

 Reimplement iswalpha in terms of iswctype and wctype:
int
myiswalpha(wint_t wc)
{
        return (iswctype(wc, wctype("alpha")));
}

#include <wchar.h>
/* Illustrates how to use wctype API */
wctype_t example_wctype()
{
 wctype_t type;

  /* get the type by passing the operation string to the wctype API */
 type = wctype("alnum");

 /* if the operation is successful then it should return non-zero value */
 /* else returns 0 */
  return type;
}

Limitations

 The current implementation of iswctype and wctype is dependent on the locale support of SYMBIAN. It doesn’t work for the locales which the SYMBIAN

See also
The iswctype and wctype functions conform to -p1003.1-2001. The "ideogram", "phonogram" "special", and "rune" character classes are extensions.
The iswctype and wctype functions first appeared in 5.0 .

Feedback

For additional information or queries on this page send feedback


wcwidth

Name

wcwidth - determine columns needed for a wide character

Library

 libc.lib

Synopsis
#include <wchar.h>
int wcwidth (wchar_t 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 positions the character occupies.

Detailed description

 The wcwidth function determines the number of column positions required to display the wide character wc.

The behavior of the wcwdith is affected by LC_CTYPE category of the current locale.

Examples

#include <wchar.h>
/* Illustrates how to use wcwidth API */
int example_wcwidth()
{
 /* wide character for which width has to be determined */
 wchar_t wc = L’a’;
 int retval;
 /* determine the width of wc */
 retval = wcwidth(wc);
 /* return the determined width */
 return retval;
}

Examples

 This code fragment reads text from standard input and breaks lines that are more than 20 column positions wide, similar to the fold utility:
wint_t ch;
int column, w;
column = 0;
while ((ch = getwchar()) != WEOF) {
        w = wcwidth(ch);
        if (w > 0 && column + w >= 20) {
                putwchar(L’ \en’);
                column = 0;
        }
        putwchar(ch);
        if (ch == L’ \en’)
                column = 0;
        else if (w > 0)
                column += w;
}

Limitations

 The current implementation of wcwidth is dependent on the locale support of SYMBIAN. It doesn’t work for the locales which the SYMBIAN doesn’t support.

See also

 iswprint, wcswidth

Feedback

For additional information or queries on this page send feedback


wfdopen

Name

wfdopen
- stream open function

Library

 libc.lib

Synopsis
#include <wchar.h>
FILE * wfdopen (int fd ,const wchar_t * mode);

Return values

 Upon successful completion wfdopen, returns a FILE pointer. Otherwise, NULL is returned and the global variable errno is set to indicate the error.

Detailed description

 The wfdopen function associates a stream with the existing file descriptor, fd. The mode argument is used just as in the function wfopen.

The mode of the stream must be compatible with the mode of the file descriptor. In other words the type specified by the stream must be allowed by the file access mode of the open file. When the stream is closed via fclose, fd is also closed.

Example

#include <io.h>
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <string.h>
#include <wchar.h>
int main(void)
{
   long length;
   int fh;
   char buffer1="HelloWorld";
   char buffer2[20];
   FILE *fp;
   memset(buffer, ’\0’, 20);                              /* Initialize buffer*/
   if (-1 == (fh = wopen(L"c:\sample.dat", O_WRONLY | O_CREAT | O_TRUNC, 0666))) {
      perror("Unable to open sample.dat");
      return EXIT_FAILURE;
   }
   if (NULL == (fp = wfdopen(fh, L"r"))) {
      perror("fdopen failed");
      close(fh);
      return EXIT_FAILURE;
   }
   if (7 != fwrite(buffer1, 1, 6, fp)) {
      perror("fread failed");
      fclose(fp);
      return EXIT_FAILURE;
   }
   if (7 != fread(buffer2, 1, 6, fp)) {
      perror("fread failed");
      fclose(fp);
      return EXIT_FAILURE;
   }
   buffer2[7]=’\0’;
   printf("Successfully read from the stream the following:\n%s.\n", buffer2);
   fclose(fp);
   return 0;
}

Output:
Successfully read from the stream the following:
Hello.

Errors
[EINVAL]
The mode argument to wfdopen, was invalid.

The function wfdopen may also fail and set errno for any of the errors specified for the routine wopen.

Limitations

 All the limitations that apply to wfopen apply to wfdopen also.

See also

 wopen, wfclose, wfopen

Feedback

For additional information or queries on this page send feedback


wfindfirst

Name

wfindfirst, wfindnext, findclose
- Provides information about the first instance of a file name that matches the file specified in the filespec argument and wfindnext finds the next name.

Library

 libc.lib

Synopsis
#include <wchar.h>
long wfindfirst (const wchar_t* filespec, struct _wfinddata_t* fileinfo);
int wfindnext (intptr_t handle, struct _wfinddata_t * fileinfo);
int findclose (intptr_t handle);

Return values

If successful, wfindfirst return a unique search handle identifying the file or group of files matching the filespec specification, which can be used in a subsequent call to wfindnext or to findclose. Otherwise, wfindfirst returns -1 and sets errno accordingly.

If successful, wfindnext returns 0. Otherwise, returns -1 and sets errno to a value indicating the nature of the failure.

If successful, findclose returns 0. Otherwise, it returns -1 and sets errno to ENOENT

Errors

[EINVAL]
 | Invalid parameter: filespec or fileinfo was NULL. Or, the operating system returned an unexpected error.
[ENOENT]
 | File specification that could not be matched.

Detailed description

 The wfindfirst function provides information about the first instance of a file name that matches the file specified in the filespec argument. Any wildcard combination supported by the host operating system can be used in filespec. File information is returned in a _wfinddata_t structure, defined in wchar.h. The _wfinddata_t structure includes the following elements.

unsigned attrib | File attribute
time_t time_create
 | Time of file creation (-1L for Symbian)
time_t time_access
 | Time of the last file access (-1L for Symbian)
time_t time_write | Time of the last write to file
size_t size | Length of the file in bytes
wchar_t name[260] | Null-terminated name of matched file/directory, without the path

This attribute is returned in the attrib field of the _wfinddata_t structure and can have the following values (defined in wchar.h).
_A_ARCH | Archive.
_A_HIDDEN
 | Hidden file.
_A_NORMAL
 | Normal.
_A_RDONLY
 | Read-only.
_A_SYSTEM
 | System file.

The wfindnext finds the next name, if any, that matches the filespec argument in a previous call to wfindfirst and then alters the fileinfo structure contents accordingly.

The findclose closes the specified search handle and releases the associated resources.

Examples

#include <wchar.h>
int main( void )
{
   struct _wfinddata_t c_file;
   intptr_t hFile;
   // Find  .txt file in current directory
   if( (hFile = wfindfirst( L"*.txt", &c_file )) == -1L )
      printf( "No *.txt files in current directory" );
   else
   {
        int i = 1;
      do {
             wprintf( L" File %d = %s ",i,c_file.name);
             i++;
                     } while( wfindnext( hFile, &c_file ) == 0 );
      findclose( hFile );
   }
   return 0 ;
}

Output

File 1 = test1.txt
File 2 = test2.txt

See also

Bugs

 Does not support any attribute to find out the sub-directories (i.e., attribute _A_SUBDIR not supported).

Feedback

For additional information or queries on this page send feedback


wfopen

Name

wfopen - stream open function

Library

 libc.lib

Synopsis
#include <wchar.h>
FILE * wfopen (const wchar_t * restrict path, const wchar_t * restrict mode);

Return values

 Upon successful completion wfopen, returns a FILE pointer. Otherwise, NULL is returned and the global variable errno is set to indicate the error.

Detailed description

 The wfopen function opens the file whose name is the wide character string pointed to by path and 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 the file.
"r+" | Open for reading and writing. The stream is positioned at the beginning of the file.
"w" | Truncate to zero length or create text file for writing. The stream is positioned at the beginning of the file.
"w+" | Open for reading and writing. The file is created if it does not exist, otherwise it 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 is positioned at the end of the file. Subsequent writes to the file will always end up at the then current end of file, irrespective of any intervening fseek or similar.
"a+" | Open for reading and writing. The file is created if it does not exist. The stream is positioned at the end of the file. Subsequent writes to the file will always end up at the then current end of file, irrespective of any intervening fseek or similar.

The mode string can also include the letter ‘‘b’’ either as a third character or as a character between the characters in any of the two-character strings described above. This is strictly for compatibility with -isoC and has no effect; the ‘‘b’’ is ignored.

Reads and writes may be intermixed on read/write streams in any order, and do not require an intermediate seek as in previous versions of stdio. This is not portable to other systems, however; ANSI C requires that a file positioning function intervene between output and input, unless an input operation encounters end-of-file.

Examples

/****************** this program shows opening  in write mode,write data and close **************/
/****************** again open in append mode and write data***** ******************************/
/***************************** Check file c:\wfopen.txt*****************************************/
#include <stdio.h>
int main(void)
        {
        FILE *fp;
        wchar_t* name = L"c:\wfopen.txt";
        if ((fp = wfopen (name, L"wb")) == NULL)
                {
                printf("Error creating file");
                return -1;
                }
        printf("Opened file \n");
        fprintf(fp, "This is the first line\n");
        printf("Wrote to file\n");
        fclose (fp);
        printf("Closed file\n");
        if ((fp = wfopen (name, L"a")) == NULL)
                {
                printf("Error opening file");
                return -1;
                }
        printf("Opened file for appending\n");
        fprintf(fp, "This is the second line\n");
        fclose (fp);
        printf("closed file, check output in c:\ wfopen.txt file\n");
        wunlink(name);
        return 0;
}

Output

Opened file
Wrote to file
Closed file
Opened file for appending
closed file, check output in c:\ wfopen.txt file

Errors
[EINVAL]
The mode argument to wfopen, was invalid.

The wfopen, functions may also fail and set errno for any of the errors specified for the routine malloc.

The wfopen function may also fail and set errno for any of the errors specified for the routine wopen.

Note

1) Mode values for group and others will be ignored for file creation, execute bit and setuid on exec bit on an file don’t have any effect while file creation.Default working
directoy of a process is initalized to C:\private\UID (UID of the calling application), and any data written into this C:\private\UID directory persists between phone resets.

2) If the specified file is a symbolic link and the file it is pointing to is invalid, the symbolic link file will be automatically removed.

Limitations

 A file in cannot be created with write-only permissions, hence when attempting to create a file in write-only permissions the file will be created with read-write permission. Creating a new file with O_CREAT flag, doesn’t alter the time stamp of parent directory, created entry has only two time stamps access and modification timestamps. Creation time stamp of the file is not supported, here accesstime stamp is equal to modification time stamp. open, fclose and fflush.

See also

 open, fclose, fileno, fseek, fopen

Feedback

For additional information or queries on this page send feedback


wfreopen

Name

wfreopen
- stream open function

Library

 libc.lib

Synopsis
#include <wchar.h>
FILE * wfreopen (const wchar_t * path, const wchar_t * mode, FILE *stream);

Return values

 Upon successful completion wfreopen, returns a FILE pointer. Otherwise, NULL is returned and the global variable errno is set to indicate the error.

Detailed description

 The wfreopen function opens the file whose name is the string pointed to by path and associates the stream pointed to by stream with it. The original stream (if it exists) is closed. The mode argument is used just as in the wfopen function.

If the path argument is NULL, wfreopen attempts to re-open the file associated with stream with a new mode. The new mode must be compatible with the mode that the stream was originally opened with:

  • Streams originally opened with mode "r" can only be reopened with that same mode.
  • Streams originally opened with mode "a" can be reopened with the same mode, or mode "w."
  • Streams originally opened with mode "w" can be reopened with the same mode, or mode "a."
  • Streams originally opened with mode "r+," "w+," or "a+" can be reopened with any mode.

The primary use of the wfreopen function is to change the file associated with a standard text stream (stderr, stdin, or stdout).

Examples

/* wfreopen example: redirecting stdout */
#include <stdio.h>
#include <wchar.h>
int main ()
{
  wfreopen (L"c:\myfile.txt",L"w",stdout);
  printf ("This sentence is redirected to a file.");
  fclose (stdout);
  return 0;
}

Output:
Contents of myfile.txt:This sentence is redirected to a file.
The output here is redirected from stdout to file myfile.txt

Errors
[EINVAL]
The mode argument to wfreopen, was invalid.

The wfreopen function may also fail and set errno for any of the errors specified for the routine wopen.

Limitations

 All the limitations that apply to wfopen apply to wfreopen also.

See also

 wopen, wfclose, wfopen

Feedback

For additional information or queries on this page send feedback


wgetcwd

Name

wgetcwd - gets current working directory

Library

 libc.lib

Synopsis
#include <wchar.h>
wchar_t * wgetcwd (wchar_t *buf, size_t size);

Return values

 Upon successful completion, a pointer to the pathname is returned. Otherwise a NULL pointer is returned and the global variable errno is set to indicate the error. In addition, wgetcwd copies the error message associated with errno into the memory referenced by buf.

Detailed description

 The wgetcwd function copies the absolute pathname of the current working directory into the memory referenced by buf which is a wchar_t pointer and returns a pointer to buf. The size argument is the size, in bytes, of the array referenced by buf.

If buf is NULL, space is allocated as indicated by size to store the pathname and the current working directory is returned as long as the size bytes are sufficient to hold the working directory name. This space may later be free’d.

This routine has traditionally been used by programs to save the name of a working directory for the purpose of returning to it. A much faster and less error-prone method of accomplishing this is to open the current directory (‘.’) and use the fchdir function to return.

Examples

#include<wchar.h>
#include<stdio.h>
#include <stdlib.h>
#define BUF_SIZE 100

int main()
{
 int c;
 long size = BUF_SIZE;
 wchar_t *buf = NULL;
 wchar_t *ptr = NULL;

 c = wchdir("c:\\");            /* change directory to c: */

 buf = (wchar_t *)malloc((size_t)size);

 if (buf != NULL && c == 0)
        {
        ptr = wgetcwd(buf, (size_t)size);               /* call wgetcwd to fetch the current directory */
        printf("wgetcwd returned: %s\n", ptr);
        }
 free(buf);
 return 0;
}

Output

wgetcwd returned: c:\

Errors

 The wgetcwd function will fail if:
[EACCES]
 | Read or search permission was denied for a component of the pathname.
[EINVAL]
 | The size argument is zero and buf is not a null pointer.
[ENOENT]
 | A component of the pathname no longer exists.
[ENOMEM]
 | Insufficient memory is available.
[ERANGE]
 | The size argument is less than the length of the working directory name. Allocate a bigger array and try again.

Notes

 The wgetcwd function returns the default working directory as c:\private\XXXXXXXX (where XXXXXXXX is the UID of the process) as the default session path is initialised to c:\private\current_process’_UID, in case of symbian.

See also

 chdir, malloc, strerror, wgetcwd

Feedback

For additional information or queries on this page send feedback


wmemchr

Name

wmemchr, wmemcmp, wmemcpy, wmemmove, wmemset, wcscat, wcschr, wcscmp, wcscpy, wcscspn, wcslen, wcsncat, wcsncmp, wcsncpy, wcspbrk, wcsrchr, wcsspn, wcsstr, wcslcat,wcslcpy
- searches a wide character in a wide-character array

Library

 libc.lib

Synopsis
#include <wchar.h>
wchar_t * wmemchr (const wchar_t *s, wchar_t c, size_t n);
int wmemcmp (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);
int wcscmp (const wchar_t *s1, const wchar_t *s2);
wchar_t * wcscpy (wchar_t * restrict s1, const wchar_t * restrict s2);
size_t wcscspn (const wchar_t *s1, const wchar_t *s2);
size_t wcslcat (wchar_t *s1, const wchar_t *s2, size_t n);
size_t wcslcpy (wchar_t *s1, const wchar_t *s2, size_t n);
size_t wcslen (const wchar_t *s);
wchar_t * wcsncat (wchar_t * restrict s1, const wchar_t * restrict s2, size_t n);
int wcsncmp (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_t wcsspn (const wchar_t *s1, const wchar_t *s2);
wchar_t * wcsstr (const wchar_t * restrict s1, const wchar_t * restrict s2);

Return values

wmemchr function returns a pointer to the first occurrence of c among the n wide characters starting at s , or NULL if c does not occur among these.

wcslcpy function returns wcslen(src); if retval >= siz, truncation occurred

wcslcat function returns wcslen(initial dst) + wcslen(src); if retval >= sizet,

Detailed description

The function wcslcat() appends a copy of the wide-character string pointed to by s2 (including the terminating null wide-character code) to the end of the wide-character string pointed to by s1. The initial wide-character code of string pointed to by s2 overwrites the null wide-character code at the end of s1. wcslcat() concatenates at most n-1 characters.

The function wcslcpy() copies the wide-character string pointed to by s2 (including the terminating null wide-character code) into the array pointed to by s1. It will copy at most n-1 characters.

The functions implement string manipulation operations over wide character strings. For a detailed description, refer to documents for the respective single-byte counterpart, such as memchr.

Examples

#include <wchar.h>
/* Illustrates how to use wmemcmp API */
int example_wmemcmp()
{
  /* source wide character string */
  wchar_t *ws1 = L"test case",*ws2 = L"test case";
  int retval;
 /* comparing the 2 wide-char strings */
 retval = wmemcmp(ws1,ws2,500);
  /* checking for the return value */
  if(retval != 0)
   return 1;
  else
   return 0;
}

#include <wchar.h>
/* Illustrates how to use wmemcpy API */
int example_wmemcpy()
{
  /* source wide character string */
  wchar_t ws1[50]=L"abcdefghij",*retval,ws2[50]=L"test";
  /* compare the strings */
  retval = wmemcpy(ws1,ws2,6);
  for(int i=0;i<6;i++)
  {
   if(retval[i] != ws2[i] || ws1[i] != ws2[i])
    return 1;
  }
  return 0;
}

#include <wchar.h>
/* Illustrates how to use wmemmove API */
int example_wmemmove()
{
  /* source wide character string */
  wchar_t ws1[50]=L"abcdefghij",*retval,ws2[5] = L"abc";
  int i;

  /* move the contents of ws2 to ws1 */
  retval = wmemmove(ws1,ws2,3);
 /* compare the contents */
  for(i=0;i<3;i++)
  {
   if(ws1[i] != ws2[i])
     return 1;
  }
  return 0;
}

#include <wchar.h>
/* Illustrates how to use wmemset API */
int example_wmemset()
{
  /* source wide character string */
  wchar_t ws1[50]=L"abcdefghij", *retval;
  int i;
  /* setting the wide-string ws1 */
  retval = wmemset(ws1,L’a’,7);
 /* comparing the contents */
  for(i=0;i<7;i++)
  {
   if(ws1[i] != L’a’)
     return 1;
  }
  return 0;
}

#include <wchar.h>
/* Illustrates how to use wmemchr API */
wchar_t *example_wmemchr(void)
{
 wchar_t *wcs = L"lmnopqr";
 size_t n;
 wchar_t wc = L’p’;
 wchar_t *res;
 /* number of wide characters to be searched */
 n = wcslen(wcs);
 /* search for the occurence of wchar wc in wide-char string wcs */
 res = wmemchr(wcs, wc, n);
 /* return the pointer */
 return(res);
}

#include <wchar.h>
/* Illustrates how to use wcslen API */
size_t example_wcslen(void)
{
 wchar_t *wcs = L"defqwert";
 size_t len;
 /* compute the length of the wide-char string */
 len = wcslen(wcs);
 /* return the length of the wide-char string */
 return (len);
}

#include <wchar.h>
/* Illustrates how to use wcscat API */
void example_wcscat(void)
{
 wchar_t wcs[100] = L"abc";
 wchar_t *wcs1 = L"def";
 wchar *res;
 /* concatenate the two strings */
 res = wcscat(wcs, wcs1);
 /* print the string that resulted from concatenation */
 wprintf(L"Output wide-char string is : %ls\n",res);
}

Output

abcdef

#include <wchar.h>
/* Illustrates how to use wcschr API */
int example_ wcschr ()
{
  /* source wide character string */
 wchar_t search_char[15] = L"&&&&$%%%%%TTU";
 wchar_t *wstr;
 int i ;
 for(i = 0 ; search_char[i]; i++)
 {
   wstr = wcschr(L"", search_char[i]);
   if(wstr != NULL)
   {
    return -1;
   }
 }
 return 0;
}

int example_wcscmp()
{
  /* source wide character string */
 wchar_t *wcs1 = "string1";
 wchar_t *wcs2 = "string2";
 int i ;
 i = wcscmp(wcs1, wcs2);
 if( i == 0)
  return -1;

 i = wcscmp(wcs1, L"string1");
 if(i != 0)
  return -1;

 return 0;
}

#include <wchar.h>
/* Illustrates how to use wcscpy API */
int example_wcscpy ()
{
  /* source wide character string */
  wchar_t wcs1[15];
  wchar_t *res;

  /* copy the wide-char string into wcs1*/
  res = wcscpy(wcs1, L"Hello world");

  if(wcscmp(res, L"Hello world") != 0)
   return -1;

  return 0;
}

#include <wchar.h>
/* Illustrates how to use wcslcpy API */
int example_wcslcpy ()
{
  /* source wide character string */
  wchar_t src[25] = L"Source";
  wchar_t dest[20]= L"Destination";

  /* copy the wide-char string into dest*/

        size_t t = wcslcpy(dest,src,4);

                if(wcscmp(dest,L"Sou")!=0)
    return -1;

  return 0;
}

#include <wchar.h>
/* Illustrates how to use wcslcat API */
int example_wcslcat ()
{
  /* source wide character string */
  wchar_t src[25] = L"Source";
  wchar_t dest[20]= L"Destination";

  /* concate the wide-char string into dest*/

        size_t t = wcslcat(dest,src,14);

                if(wcscmp(dest,"DestinationSo")!=0)
    return -1;

  return 0;
}

#include <wchar.h>
/* Illustrates how to use wcscspnAPI */
int example_wcscspn ()
{
  /* source wide character string */
  wchar_t wcs1[30] = L"1234567890ABCDE!@#$$";
  wchar_t *wcs2[20] = { L"abcdefghijkl",
     L":::?>_)+(|{>",
     L"~*(&IUIJJJ",
     L"1234567",
     L":::?>",
     L"1",
     L"as1sd2ds3ds48f5fd"
   };
  int i;

  for( i = 0; i < 3 ; i ++)
  {
   if( wcslen(wcs1) != wcscspn(wcs1,wcs2[i]))
     return -1;
  }

  return 0;
}

#include <wchar.h>
/* Illustrates how to use wcsncat API */
int example_wcsncat ()
{
  /* source wide character string */
  wchar_t *res;
  wchar_t str[50];

  wcscpy(str, L"Hello");
  res = wcsncat(str,L" world",12);
 if(wcscmp(str, L"Hello world") != 0)
  return -1;
 else
  return 0;
}

#include <wchar.h>
/* Illustrates how to use wcsncmp API */
int example_wcsncmp()
{
  /* source wide character string */
  wchar_t *wcs1 = L"Hello world";
  if(wcsncmp(wcs1,wcs1,wcslen(wcs1)))
   return -1;
  else
   return 0;
}

#include <wchar.h>
/* Illustrates how to use wcsncpy API */
int example_wcsncpy ()
{
  /* source wide character string */
  wchar_t wcs1[15] = L"Hello world";
  wchar_t *res;
  res = wcsncpy(wcs1,wcs1,wcslen(wcs1));
  if(wcscmp(res,wcs1))
  return -1;
  return 0;
}

#include <wchar.h>
/* Illustrates how to use wcspbrk API */
int example_wcspbrk ()
{
  /* source wide character string */
 wchar_t *wcs = L"abcdefghijkl";
  wchar_t *res1 = wcspbrk(wcs, L"");
  if(res1 != NULL)
   return -1;

  return 0;
}

#include <wchar.h>
/* Illustrates how to use wcsrchr API */
int example_wcsrchr ()
{
  /* source wide character string */
 wchar_t search_char[15] = L"&&&&$%%%%%TTU";
  wchar_t *wstr;
  int i ;

  for(i = 0 ; search_char[i]; i++)
  {
   wstr = wcsrchr(L"", search_char[i]);
   if(wstr != NULL)
   {
     return -1;
   }
  }
  return 0;
}

#include <wchar.h>
/* Illustrates how to use wcsspn API */
int example_wcsspn()
{
  /* source wide character string */
 wchar_t wcs1[30] = L"1234567890ABCDE!@#$$";
 if(wcslen(wcs1) != wcsspn(wcs1,wcs1))
  return -1;
 return 0;
}

#include <wchar.h>
/* Illustrates how to use wcsstr API */
int example_wcsstr()
{
  /* source wide character string */
 wchar_t *buf[20] = { L"fkhsdf%%38",L"rtti123123", };
 wchar_t *str  = wcsstr(buf[0],L"");
 wchar_t *str1 = wcsstr(buf[1],L"\0");
 if(wcscmp(str,buf[0]))
   return 1;
 if(wcscmp(str1,buf[1]))
   return 1
 return 0;
}

Security considerations

 Please refer strcpy strcat

See also

 memchr, memcmp, memcpy, memmove, memset, strcat, strchr, strcmp, strcpy, strcspn, strlen, strncat, strncmp, strncpy, strpbrk, strrchr, strspn, strstr

Feedback

For additional information or queries on this page send feedback


wmkdir

Name

wmkdir - creates a directory

Library

 libc.lib

Synopsis
#include <sys/types.h>
#include <sys/stat.h>
#include <wchar.h>
int wmkdir (const wchar_t *path, mode_t mode);

Return values

 The wmkdir() function returns the value 0 if successful; otherwise the value -1 is returned and the global variable errno is set to indicate the error.

Detailed description

 The directory with the wide character name path is created with the access permissions specified by mode.

Note: mode values will be ignored while directory creation.Default working directoy of a process is initalized to C:\private\UID (UID of the calling application), and any data written into this C:\private\UID directory persists between phone resets.

Limitation: Parent directory time stamps will not be updated with new directory creation.

Examples

#include <sys/stat.h>
#include <wchar.h>
#include <stdio.h>
int main()
{
  if(wmkdir(L"Example" , 0666) < 0 )
  {
      printf("Directory creation failed \n");
      return -1;
  }
  printf("Directory Example created \n");
  return 0;
}

Output

Directory Example created

Errors

 The wmkdir system call will fail and no directory will be created if:
[ENAMETOOLONG]
 | A component of a pathname exceeded 255 characters.
[ENOENT]
 | The named file does not exist.
[EINVAL]
 | Invalid argument.
[EEXIST]
 | File with the same name already exists.

See also

 chmod, stat, umask, mkdir

Feedback

For additional information or queries on this page send feedback


wopen

Name

wopen - wopen and possibly create a file or device

Library

 libc.lib

Synopsis
#include <wchar.h>
int wopen (const wchar_t *path, int flags, ...);

Return values

 If successful, wopen returns a non-negative integer, termed a file descriptor. It returns -1 on failure, and sets errno to indicate the error.

Detailed description

 The wide character file-name specified by the wide character string path is opened for reading and/or writing as specified by the argument flags and the file descriptor returned to the calling process. The flags argument may indicate the file is to be created if it does not exist (by specifying the O_CREAT flag). In this case wopen requires a third argument mode_t mode, and the file is created with mode mode as described in chmod and modified by the process’ umask value (see umask

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_APPEND        append on each write
O_CREAT         create file if it does not exist
O_TRUNC         truncate size to 0
O_EXCL          error if create and file exists

Opening a file with O_APPEND set causes each write on the file to be appended to the end. 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, wopen returns an error. This may be used to implement a simple exclusive access locking mechanism. If O_EXCL is set and the last component of the pathname is a symbolic link, wopen will fail even if the symbolic link points to a non-existent name.

If successful, wopen returns a non-negative integer, termed a file descriptor. It returns -1 on failure. The file pointer used to mark the current position within the file is set to the beginning of the file.

When a new file is created it is given the group of the directory which contains it.

The new descriptor is set to remain wopen across execve system calls; see close and fcntl.

The system imposes a limit on the number of file descriptors wopen simultaneously by one process. The getdtablesize system call returns the current system limit.

Note: 1) Mode values for group and others will be ignored for file creation, execute bit and setuid on exec bit on an file don’t have any effect while file creation.Default working directoy of a process is initalized to C:\private\UID (UID of the calling application), and any data written into this C:\private\UID directory persists between phone resets. 2) If the specified file is a symbolic link and the file it is pointing to is invalid, the symbolic link file will be automatically removed.

Limitation: A file in cannot be created with write-only permissions, hence when attempting to create a file in write-only permissions the file will be created with read-write permission. Creating a new file with O_CREAT flag, doesn’t alter the time stamp of parent directory, created entry has only two time stamps access and modification timestamps. Creation time stamp of the file is not supported, here accesstime stamp is equal to modification time stamp.

Examples

/************************************************************************
* This example creates a file in the current working directory and
* opens it in read-write mode.
************************************************************************/
#include <sys/types.h>
#include <sys/stat.h>
#include <wchar.h>
int main()
{
  int fd = 0 ;
   fd = wopen(L"Example.txt" , O_CREAT | O_EXCL , 0666) ;
   if(fd < 0 )
   {
      printf("Failed to create and wopen file in current working directory \n") ;
      return -1 ;
   }
   printf("File created and opened in current working directory \n"  ) ;
   return 0 ;
}

Output

File created and opened in current working directory

Errors

 The named file is opened unless:
[ENOTDIR]
 | A component of the path prefix is not a directory.
[ENAMETOOLONG]
 | A component of a pathname exceeded 255 characters, 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 denied for the given flags.
[EACCES]
 | O_CREAT is specified, the file does not exist, and the directory in which it is to be created does not permit writing.
[ELOOP]
 | Too many symbolic links were encountered in translating the pathname(Not supported).
[EISDIR]
 | The named file is a directory, and the arguments specify it is to be opened for writing.
[EROFS]
 | The named file resides on a read-only file system, and the file is to be modified(Not supported).
[EMFILE]
 | The process has already reached its limit for wopen file descriptors.
[ENFILE]
 | The system file table is full.
[EMLINK]
 | O_NOFOLLOW was specified and the target is a symbolic link(Not supported).
[ENXIO]
 | The named file is a character special or block special file, and the device associated with this special file does not exist(Not supported).
[ENXIO]
 | The named file is a fifo, no process has it wopen for reading, and the arguments specify it is to be opened for writing.
[EINTR]
 | The wopen operation was interrupted by a signal(Not supported).
[EOPNOTSUPP]
 | The named file is a special file mounted through a file system that does not support access to it (e.g. NFS)(Not supported).
[ENOSPC]
 | O_CREAT is specified, the file does not exist, and the directory in which the entry for the new file is being placed cannot be extended because there is no space left on the file system containing the directory(Not implemented).
[ENOSPC]
 | O_CREAT is specified, the file does not exist, and there are no free inodes on the file system on which the file is being created.
[EDQUOT]
 | O_CREAT is specified, the file does not exist, and the directory in which the entry for the new file is being placed cannot be extended because the user’s quota of disk blocks on the file system containing the directory has been exhausted(Not supported).
[EDQUOT]
 | O_CREAT is specified, the file does not exist, and the user’s quota of inodes on the file system on which the file is being created has been exhausted(Not supported).
[EIO] | An I/O error occurred while making the directory entry or allocating the inode for O_CREAT.
[ETXTBSY]
 | The file is a pure procedure (shared text) file that is being executed and the wopen system call requests write access(Not supported).
[EFAULT]
 | The path argument 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 wopen a socket (not currently implemented).
[EINVAL]
 | An attempt was made to wopen a descriptor with an illegal combination of O_RDONLY, O_WRONLY, and O_RDWR.

See also

 chmod, close, dup, getdtablesize, lseek, read, umask, write, fopen, open

Feedback

For additional information or queries on this page send feedback


wopendir

Name

wopendir - opening a directory with wide-character name

Library

 libc.lib

Synopsis
#include <wchar.h>
WDIR * wopendir (const wchar_t *dirname);

Return values

The wopendir function returns a pointer to the directory stream or NULL if an error occurred.

Detailed description

 The wopendir function opens the directory given by the wide-character name dirname, associates a directory stream with it and positions it at the first entry and returns a pointer to be used to identify the directory stream in subsequent operations. The pointer NULL is returned if dirname cannot be accessed, or if it cannot malloc enough memory to hold the whole thing.

Examples

/*************************************************************************************************************
* Detailed description: This test code demonstrates usage of wopendir system call, open directory wide name "test".
*
* Preconditions: Expects "test" directory to be present in the current working directory.
**************************************************************************************************************/
 #include <wchar.h>
 #include <stdio.h>
 #include <dirent.h>
int main()
{
  WDIR *WDirHandle;
  if(!(WDirHandle = wopendir(L"test") ) )
  {
     printf("Failed to open directory test\n");
     return -1;
  }
  printf("Directory test opened \n");
  wclosedir(WDirHandle);
  return 0;
}

Output

Directory test opened

Errors

 The wopendir system call will fail if:
[EINVAL]
 | Invalid argument.
[ENAMETOOLONG]
 | A component of a pathname exceeded 255 characters.
[ENOENT]
 | The named file does not exist.
[EMFILE]
 | Too many file descriptors in use by process.
[ENOMEM]
 | Insufficient memory to complete the operation.
[ENOTDIR]
 | dirname is not a directory.

See also

 opendir, close, lseek, open, read

Feedback

For additional information or queries on this page send feedback


wpopen

Name

wpopen - process I/O

Library

 libc.lib

Synopsis
#include <wchar.h>
FILE * wpopen (const wchar_t* command, const wchar_t* type );

Return values

 The wpopen function returns NULL if the fork or pipe calls fail, or if it cannot allocate memory. And returns stream pointer on success.

Detailed description

 The wpopen function opens a process by creating a pipe and invoking the shell (creating a process). Since a pipe is by definition unidirectional, The type argument may specify only reading or writing, not both; the resulting stream is correspondingly read-only ("r") or write-only "w". If type is anything other than this, then the behavior is undefined.

The command argument is a pointer to a null-terminated wide character string containing a shell command line. This command is passed to /bin/sh using the -c flag; interpretation, if any, is performed by the shell.

The return value from wpopen is a normal standard I/O stream in all respects save that it must be closed with pclose rather than fclose. Writing to such a stream writes to the standard input of the command; the command’s standard output is the same as that of the process that called wpopen, unless this is altered by the command itself. Conversely, reading from a "wpopened" stream reads the command’s standard output, and the command’s standard input is the same as that of the process that called wpopen.

Note that output wpopen streams are fully buffered by default.

Errors

 The wpopen function does not reliably set errno.

See also

 popen, pclose, pipe, fclose, fflush, fopen, system

Bugs

 Since the standard input of a command opened for reading shares its seek offset with the process that called wpopen, if the original process has done a buffered read, the command’s input position may not be as expected. Similarly, the output from a command opened for writing may become intermingled with that of the original process. The latter can be avoided by calling fflush before wpopen.

Failure to execute the shell is indistinguishable from the shell’s failure to execute command, or an immediate exit of the command. The only hint is an exit status of 127.

The wpopen function always calls sh, never calls csh.

Feedback

For additional information or queries on this page send feedback


wprintf

Name

wprintf, fwprintf, swprintf, snwprintf, vwprintf, vfwprintf, vswprintf, vsnwprintf
- formatted wide character output conversion

Library

 libc.lib

Synopsis
#include <stdio.h>
#include <wchar.h>
int fwprintf (FILE * restrict stream, const wchar_t * restrict format, ...);
int swprintf (wchar_t * restrict ws, size_t n, const wchar_t * restrict format, ...);
int snwprintf (wchar_t * restrict ws, size_t n, const wchar_t * restrict format, ...);
int vsnwprintf (wchar_t * restrict ws, size_t n, const wchar_t *restrict format, va_list ap);
int wprintf (const wchar_t * restrict format, ...);
#include <stdarg.h>
int vfwprintf (FILE * restrict stream, const wchar_t * restrict, va_list ap);
int vswprintf (wchar_t * restrict ws, size_t n, const wchar_t *restrict format, va_list ap);
int vwprintf (const wchar_t * restrict format, va_list ap);

Return values

The functions return the number of wide characters written, excluding the terminating null wide character in case of the functions swprintf , snwprintf , vswprintf and vsnwprintf.

They return -1 when an error occurs.

Detailed description

 The wprintf family of functions produces output according to a format as described below. The wprintf and vwprintf functions write output to stdout, the standard output stream; fwprintf and vfwprintf write output to the given output stream; swprintf , snwprintf , vswprintf and vsnwprintf write to the wide character string ws.

These functions write the output under the control of a format string that specifies how subsequent arguments (or arguments accessed via the variable-length argument facilities of stdarg) are converted for output.

These functions return the number of characters printed (not including the trailing ‘\0’ used to end output to strings).

The swprintf , snwprintf , vswprintf and vsnwprintf functions will fail if n or more wide characters were requested to be written.

Note :

1. swprintf and snwprintf can be used interchangeably.

2. vswprintf and vsnwprintf can be used interchangeably.

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 conversion specification is introduced by the % character. The arguments must correspond 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 $, specifying the next argument to access. If this field is not provided, the argument following the last argument accessed will be used. Arguments are numbered starting at 1. If unaccessed arguments in the format string are interspersed with 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. For o conversions, the precision of the number is increased to force the first character of the output string to a zero (except if a zero value is printed with an explicit precision of zero). For x and X conversions, a non-zero result has the string ‘0x’ (or ‘0X’ for X conversions) prepended to it. For a, A, e, E, f, F, g, and G conversions, the result will always contain a decimal point, even if no digits follow it (normally, a decimal point appears in the results of those conversions only if a digit follows). For g and G conversions, trailing zeros are not removed from the result as they would otherwise be.
    '0(zero)' | 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; the converted value is to be left adjusted on the field boundary. Except for n conversions, the converted value is padded on the right with blanks, rather than on the left with blanks or zeros. A - overrides a 0 if both are given.
    ' (space)' | A blank should be left before a positive number produced by a signed conversion ( a, A, d, e, E, f, F, g, G, or i).
    '+' A sign must always be placed before a number produced by a signed conversion. A + overrides a space if both are used.
    '’' Decimal conversions ( d, u, or i) or the integral portion of a floating point conversion ( f or F) should be grouped and separated by thousands using the non-monetary separator returned by localeconv.
  • An optional decimal digit string specifying a minimum field width. If the converted value has fewer characters than the field width, it will be padded with spaces on the left (or right, if the left-adjustment flag has been given) to fill out the field width.
  • An optional precision, in the form of a period . followed by an optional digit 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 X conversions, 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 G conversions, or the maximum number of characters to be printed from a string for s conversions.
  • An optional length modifier, that specifies the size of the argument. The following length modifiers are valid for the d, i, n, o, u, x, or X conversion:
    Modifier d, i o, u, x, X n
    hh 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 that the argument is of an unsigned type equivalent in size to a ptrdiff_t . The z modifier, when applied to a d or i conversion, indicates that the argument is of a signed type equivalent in size to a size_t . Similarly, when applied to an n conversion, it indicates that the argument is a pointer to a signed type equivalent 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, G
    L long double

    The following length modifier is valid for the c or s conversion:
    Modifier c s
    l (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 asterisk followed by one or more decimal digits and a ‘$’ instead of a digit string. In this case, an int argument supplies the field width or precision. A negative field width is treated as a left adjustment flag followed by a positive field width; a negative precision is treated as though it were missing. If a single format directive mixes positional (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 decimal ( d and i), unsigned octal (o), unsigned decimal (u), or unsigned hexadecimal ( x and X) notation. The letters "abcdef" are used for x conversions; the letters "ABCDEF" are used for X conversions. The precision, if any, gives the minimum number of digits that must appear; if the converted value requires fewer digits, it is padded on the left with zeros.
DOU | The long int argument is converted to signed decimal, unsigned octal, or unsigned decimal, as if the format had been ld, lo, or lu respectively. These conversion characters are deprecated, and will eventually disappear.
eE The double argument is rounded and converted in the style [-d . ddd e \*[Pm] dd] where there is one digit before the decimal-point character and the number 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 appears. An E conversion uses the letter ‘E’ (rather than ‘e’) to introduce the exponent. The exponent always contains at least two digits; if the value is zero, the exponent is 00.

For a, A, e, E, f, F, g, and G conversions, positive and negative infinity are represented as inf and -inf respectively when using the lowercase conversion character, and INF and -INF respectively when using the uppercase conversion character. Similarly, NaN is represented as nan when using the lowercase conversion, and NAN when using the uppercase conversion.

fF | The double argument is rounded and converted to decimal notation in the style [-ddd . ddd], where the number of digits after the decimal-point character is equal to the precision specification. If the precision is missing, it is taken as 6; if the precision is explicitly zero, no decimal-point character appears. If a decimal point appears, at least one digit appears before it.
gG | The double argument is converted in style f or e (or F or E for G conversions). The precision specifies the number of significant digits. If the precision is missing, 6 digits are given; if the precision is zero, it is treated as 1. Style e is used if the exponent from its conversion is less than -4 or greater than or equal to the precision. Trailing zeros are removed from the fractional part of the result; a decimal point appears only if it is followed by at least one digit.
aA | The double argument is converted to hexadecimal notation in the style [-0x h . hhhp[\*[Pm]d]], where the number of digits after the hexadecimal-point character is equal to the precision specification. If the precision is missing, it is taken as enough to exactly represent the floating-point number; if the precision is explicitly zero, no hexadecimal-point character appears. This is an exact conversion of the mantissa+exponent internal floating point representation; the [-0x h . hhh] portion represents exactly the mantissa; only denormalized mantissas have a zero value to the left of the hexadecimal point. The p is a literal character ‘p’; the exponent is preceded by a positive or negative sign and is represented in decimal, using only enough characters to represent the exponent. The A conversion uses the prefix "0X" (rather than "0x"), the letters "ABCDEF" (rather than "abcdef") to represent the hex digits, and the letter ‘P’ (rather than ‘p’) to separate the mantissa and exponent.
C | Treated as c with the l (ell) modifier.
c The int argument is converted to an unsigned char , then to a wchar_t as if by btowc, and the resulting character is written.

If the l (ell) modifier is used, the wint_t argument is converted to a wchar_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 character type (pointer to a string) containing a multibyte sequence. Characters from the array are converted to wide characters and written up to (but not 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 is greater than the size of the array, the array must contain a terminating NUL character.

If the l (ell) modifier is used, the wchar_t * argument is expected to be a pointer to an array of wide characters (pointer to a wide string). Each wide character in the string is written. Wide characters from the array are 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 need be present; if the precision is not specified, or is greater than the number of characters in the string, the array must contain a terminating wide 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 indicated by the int * (or variant) pointer argument. No argument is converted.
% A ‘%’ is written. No argument is converted. The complete conversion specification is ‘%%’.

The decimal point character is defined in the program’s locale (category LC_NUMERIC).

In no case does a non-existent or small field width cause truncation of a numeric field; if the result of a conversion is wider than the field width, the field is expanded to contain the conversion result.

Examples

#include <stdio.h>
#include <wchar.h>
/* Illustrates how to use wprintf API */
int example_wprintf(void)
{
 int input = 12345;
 int rval;
 /* prints the integers on the standard output */
 rval = wprintf(L"%d", input);
 /* return the number of wide characters that were written */
 return(rval);
}

Output

12345

#include <stdio.h>
#include <wchar.h>
/* Illustrates how to use fwprintf API */
int example_fwprintf(void)
{
 FILE *fp = NULL;
 int retval;
 wchar_t *wcs = L"abc";
 /* open the file for writing*/
 fp = fopen("write.txt","w");
 if(fp == NULL)
 {
  wprintf(L"Error: File open\n");
  return (-1);
 }
 /* print the characters into the file */
 retval = fwprintf(fp, L"%s", wcs);
 /* Close the file opened for writing */
 fclose(fp);
 /* return the number of wide characters that were written */
 return (retval);
}

#include <stdio.h>
#include <wchar.h>
/* Illustrates how to use swprintf API */
int example_swprintf(wchar_t *buf, int maxlen)
{
 wchar_t *wcs = L"abcdef";
 int rval;
 /* prints the wide char string into the buffer buf */
 rval = swprintf(buf, maxlen, L"%s", wcs);
 /* return the number of wide characters that were written */
 return(rval);
}

#include <stdio.h>
#include <wchar.h>
/* Illustrates how to use vwprintf API */
int example_vwprintf(va_list input)
{
 int rval;
 /* prints the integers on the standard output */
 rval = vwprintf(L"%d", input);
 /* return the number of wide characters that were written */
 return(rval);
}

#include <stdio.h>
#include <wchar.h>
/* Illustrates how to use vfwprintf API */
int example_vfwprintf(va_list input)
{
  FILE *fp = NULL;
  int retval;

  /* open the file for writing*/
  fp = fopen("write.txt","w");
  if(fp == NULL)
  {
    wprintf(L"Error: File open\n");
    return (-1);
  }
  /* print the characters into the file */
  retval = vfwprintf(fp, L"%s", input);
  /* Close the file opened for writing */
  fclose(fp);
  /* return the number of wide characters that were written */
  return (retval);
}

#include <stdio.h>
#include <wchar.h>
/* Illustrates how to use vswprintf API */
int example_vswprintf(wchar_t *buf, int maxlen, va_list input)
{
 int rval;
 /* prints the wide char string into the buffer buf */
 rval = vswprintf(buf, maxlen, L"%s", input);
 /* return the number of wide characters that were written */
 return(rval);
}

Security considerations

 Refer to printf.

Limitations

 All these functions don’t support the long double length modifiers. All the floating point format specifiers supports maximum precision of 15 digits as this is the maximum that is supported in SYMBIAN.

See also

 btowc, fputws, printf, putwc, setlocale, wcsrtombs, wscanf

Feedback

For additional information or queries on this page send feedback


wreaddir

Name

wreaddir - reading a directory with wide-character name

Library

 libc.lib

Synopsis
#include <wchar.h>
#include <dirent.h>
struct wdirent * wreaddir (WDIR *dirp);

Return values

The wreaddir function returns a pointer to a wdirent structure, or NULL if an error occurs or end-of-file is reached.

Detailed description

The wreaddir function returns a wdirent pointer to the next directory entry. It returns NULL upon reaching the end of the directory or detecting an invalid wreaddir operation on the directory stream. The new position reverts to the one associated with the directory stream when the wtelldir operation was performed.

Note:
Any changes happening to directory after wopendir call, will not be reflected by subsequent wreaddir calls.

Examples

 /**
  * Detailed description: Sample usage of wreaddir call
  * Preconditions:  Example Directory should be present in current working directory and should contain atleast one file/directory.
**/
#include <dirent.h>
#include <unistd.h>
#include <wchar.h>
int main()
{
  WDIR *dirName;
  struct wdirent *Dir;
  dirName = wopendir(L"Example");
  if(dirName == NULL )  {
     printf("Failed to open directory \n");
     return -1;
  }
  if(!(Dir = wreaddir(dirName))  )  {
    printf("Read dir failed  \n");
    return -1;
  }
 printf("Directory Example read \n");
 wclosedir(dirName);
 return 0;
}

Output

Directory Example read

Errors

 The wreaddir system call will fail if:
[EINVAL]
 | Invalid argument.
[ENOENT]
 | The named file does not exist.
[ENOTDIR]
 | dirname is not a directory.
[EBADF]
 | Invalid file descriptor fd.
[EFAULT]
 | Argument points outside the calling processâs address space.
[EINVAL]
 | Result buffer is too small.

See also

 wopendir, wreaddir, wrewinddir, wtelldir, wseekdir, wclosedir, opendir, readdir, rewinddir, telldir, seekdir, closedir, close, lseek, open, read, dir

Feedback

For additional information or queries on this page send feedback


wrealpath

Name

wrealpath - returns the canonicalized absolute pathname

Library

 libc.lib

Synopsis
#include <sys/param.h>
#include <wchar.h>
wchar_t * wrealpath (const wchar_t *pathname, wchar_t resolved_path[PATH_MAX]);

Return values

 The wrealpath function returns resolved_path on success. If an error occurs, wrealpath returns NULL, and resolved_path contains the pathname which caused the problem.

Detailed description

 The wrealpath function resolves all extra "/" characters and references to /./ and /../ in pathname, and copies the resulting absolute pathname into the memory referenced by resolved_path. The resolved_path argument must refer to a buffer capable of storing at least PATH_MAX characters.

The wrealpath function will resolve both absolute and relative paths and return the absolute pathname corresponding to pathname. All but the last component of pathname must exist when wrealpath is called.

Examples

#include<stdlib.h>
#include<stdio.h> //printf
#include<sys/stat.h> //S_IWUSR
#include<sys/syslimits.h> //PATH_MAX
#include<unistd.h> //chdir
#inlclude<wchar.h>

int main()
{
 wchar_t resolvepath[PATH_MAX];
 FILE *fp = NULL;
 wchar_t *rpath = NULL;

 fp = wfopen(L"c:\\xyz.txt", L"w");
 if(!fp)
 {
     printf("wfopen failed!!");
     return -1;
 }

 wmkdir(L"c:\\tmdir", S_IWUSR);

 int c = wchdir(L"c:\\");
 if(c == -1)
 {
     printf("wchdir failed!!");
     return -1;
 }

 rpath = wrealpath(L".\\tmdir\\..\\xyz.txt", resolvepath);
 printf("resolvepath: L%s\n", resolvepath);
 if(rpath != NULL)
    printf("rpath: L%s\n\n", rpath);

 fclose(fp);
 wrmdir(L"c:\\tmdir");
 wunlink(L"c:\\xyz.txt");
 return 0;
}

Output

resolvepath: C:\xyz.txt
rpath: C:\xyz.txt

Errors

 The function wrealpath may fail and set the external variable errno for any of the errors specified for the library functions readlink and getcwd.

See also

 getcwd

Feedback

For additional information or queries on this page send feedback


wremove

Name

wremove - delete a wide character name and possibly the file it refers to path

Library

 libc.lib

Synopsis
#include <wchar.h>
int wremove (const wchar_t *path);

Return values

Upon successful completion, wremove return 0. Otherwise, -1 is returned and the global variable errno is set to indicate the error.

Detailed description

 The wremove function removes the file or directory specified by the wide character name referred by path.

If path specifies a directory, wremove (path);
is the equivalent of wrmdir (path);
Otherwise, it is the equivalent of wunlink (path);

Examples

/****************** this program shows deleting a file using wremove **************/
#include <stdio.h>
int main()
{
        wchar_t* name = L"C:\\input.txt";
        FILE *fp = wfopen(name, L"w+");
        if (fp == NULL)
                {
                printf ("fopen failed\n");
                return -1;
                }
        fprintf(fp,"hello world");
        fclose(fp);

        wremove(name);
        fp=wfopen(name,L"r");
        if (fp == NULL)
                {
                printf ("file has been deleted already\n");
                }
        else
                {
                printf("wremove failed\n");
                return -1;
                }
        return 0;
}

Output

file has been deleted already

Errors

 The wremove function may fail and set errno for any of the errors specified for the routines wstat, wrmdir or wunlink.

See also

 wrmdir, wunlink

Feedback

For additional information or queries on this page send feedback


wrename

Name

wrename - wrename files

Library

 libc.lib

Synopsis
#include <wchar.h>
int wrename (const wchar_t *from, const wchar_t *to);

Return values

 The wrename() function returns the value 0 if successful; otherwise the value -1 is returned and the global variable errno is set to indicate the error.

Detailed description

 The wrename system call causes the link with the wide character name from to be renamed with the wide character name to. If to exists, it is first removed. Both from and to must be of the same type (that is, both directories or both non-directories), and must reside on the same file system.

If the final component of from is a symbolic link, the symbolic link is renamed, not the file or directory to which it points.

If a file with a symbolic link pointing to it is renamed, then a subsequent open call on the symbolic link file would automatically remove the link file, i.e consider a symbolic file link.x pointing to a file abc.x. If the file abc.x is renamed to abcd.x then, a subsequent open call on link.x file would automatically remove link.x file.

Limitation: wrename call fails if from and to are files, and are in use(i.e., if any one of these files is kept open by a process). Parent directory time stamps remain uneffected if wrename creates a new entry in the directory, this new entry has only two time stamps, modification and access time stamps, here access time stamp is equal to modification time stamp.

Examples

/****************************************************************************************
* Detailed description  : This sample code demonstrates usage of wrename system call.
*
* Preconditions : Example.cfg file should be present in the current working directory.
****************************************************************************************/
#include <wchar.h>
#include <stdio.h>
int main()
{
  if(wrename(L"Example.txt" , L"Example2.txt") < 0 )  {
     printf("Failed to wrename Example.txt\n");
     return -1;
  }
  printf("wrename successful \n");
  return 0;
}

Output:

wrename successful

Errors

 The wrename system call will fail and neither of the argument files will be affected if:
[EINVAL]
 | Invalid argument.
[ENAMETOOLONG]
 | A component of a pathname exceeded 255 characters.
[ENOENT]
 | The named file does not exist.
[EACCES]
 | Search permission is denied for a component of the path prefix.
[EACCES]
 | The from argument is a parent directory of to, or an attempt is made to wrename ‘.’ or ‘..’.

See also

 open, symlink, rename

Feedback

For additional information or queries on this page send feedback


wrewinddir

Name

wrewinddir - resets the position of the directory stream (directory with wide-character name)

Library

 libc.lib

Synopsis
#include <wchar.h>
#include <dirent.h>
void wrewinddir (WDIR *dirp);

Return values

The wrewinddir function returns no value.

Detailed description

The wrewinddir function function resets the position of the named directory stream pointed by ‘dirp’ to the beginning of the directory.

Examples

 /**
  * Detailed description: Sample usage of wreaddir call
  * Preconditions:  Example Directory should be present in current working directory and should contain say 4 files/directories.
**/
#include <dirent.h>
#include <unistd.h>
#include <wchar.h>
int main()
{
  WDIR *dirName;
  off_t offset;
  struct wdirent *Dir;
  dirName = wopendir(L"Example");
  if(dirName == NULL )  {
     printf("Failed to open directory \n");
     return -1;
  }
  wseekdir(dirName, 3)
  if((offset = wtelldir(dirName))!= 3)  {
    printf("failed  \n");
    return -1;
  }
  wrewindir(dirName);
  if((offset = wtelldir(dirName))!= 0)  {
    printf("failed  \n");
    return -1;
  }
 printf("Successful\n");
 wclosedir(dirName);
 return 0;
}

Output

Successful

See also

 wreaddir, wtelldir, wseekdir, readdir, rewinddir, telldir, seekdir,

Feedback

For additional information or queries on this page send feedback


write

Name

write, writev, pwrite
- write to a file descriptor

Library

 libc.lib

Synopsis
#include <sys/types.h>
#include <sys/uio.h>
#include <unistd.h>
ssize_t write (int d, const void *buf, size_t nbytes);
ssize_t pwrite (int d, const void *buf, size_t nbytes, off_t offset);
ssize_t writev (int d, const struct iovec *iov, int iovcnt);
ssize_t pwritev (int d, const struct iovec *iov, int iovcnt, off_t offset);

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.

Detailed description

 The write system call attempts to write nbytes of data to the object referenced by the descriptor d from the buffer pointed to by buf. The writev system call performs the same action, but gathers the output data from the iovcnt buffers specified by the members of the iov array: iov[0], iov[1], ..., iov[iovcnt-1]. The pwrite and pwritev system calls perform the same functions, but write to the specified position in the file without modifying the file pointer.

For writev and pwritev, the iovec structure is defined as:

struct iovec {
        void   *iov_base;  /* Base address. */
        size_t iov_len;    /* Length. */
};

Each iovec entry specifies the base address and length of an area in memory from which data should be written. The writev system call will always write a complete area before proceeding to the next.

On objects capable of seeking, the write starts at a position given by the pointer associated with d, see lseek. Upon return from write, the pointer is incremented by the number of bytes which were written.

Objects that are not capable of seeking always write from the current position. The value 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 flow control, write and writev may write fewer bytes than requested; the return value must be noted, and the remainder of the operation should be retried when possible.

Examples

/*************************************************************************************
* Detailed description: This sample code creates an Example.txt file in the current working
* directory(if file existes then it is truncated) and writes "Hello World" string
* to the file.
*
* Preconditions: Example.txt if present, it should not be read-only.
***************************************************************************************/
int main()
{
 int fd = 0 ;
 char Buf[] = "Hello World" ;
 fd = open("Example.txt" , O_CREAT | O_TRUNC | O_RDWR  ,0666) ;
 if(fd < 0 )
 {
    printf("Failed to open file Example.txt") ;
    return -1 ;
 }
 if(write(fd , Buf , sizeof(Buf)) < sizeof(Buf))
  {
    printf("Failed to write string %s to file\n" , Buf) ;
    return -1 ;
  }
  printf("String %s written to file \n" , Buf) ;
  return 0 ;
 }

Output

String Hello World written to file

 /**
  * Detailed description  : Sample usage of readv system call
  *
  *
**/
#include <stdio.h>
#include <sys/types.h>
#include <sys/uio.h>
#include <fcntl.h>
int main()
{
  int fd = 0 ;
  struct iovec io_vec[1] ;
  char Buf[12] = "Hello world" ;
  io_vec[0].iov_base  = Buf ;
  io_vec[0].iov_len = 11 ;
  fd = open("Example.txt" , O_CREAT | O_RDWR , 0666 ) ;
  if(fd < 0 )  {
    printf("File open failed  \n") ;
    return -1 ;
  }
  if(writev(fd , io_vec , 1) <  11 )   {
    printf("Failed to read fron Example.txt file \n") ;
    return -1 ;
  }
  printf("writev succes %s written \n"  , io_vec[0].iov_base) ;
  return 0 ; }

Output

writev succes Hello world written

Errors

 The write, writev, pwrite and pwritev system calls will fail and the file pointer will remain unchanged if:
[EBADF]
 | The d argument is not a valid descriptor open for writing.
[EPIPE]
 | An attempt is made to write to a pipe that is not open for reading by any process.
[EPIPE]
 | An attempt is made to write to a socket of type SOCK_STREAM that is not connected to a peer socket.
[EFBIG]
 | An attempt was made to write a file that exceeds the process’s file size limit or the maximum file size(Currently not supported).
[EFAULT]
 | Part of iov or data to be written to the file points outside the process’s allocated address space (currently not supported).
[EINVAL]
 | The pointer associated with d was negative.
[ENOSPC]
 | There is no free space remaining on the file system containing the file(currently not supported).
[EDQUOT]
 | The user’s quota of disk blocks on the file system containing the file has been exhausted(currently not supported)..
[EIO] | An I/O error occurred while reading from or writing to the file system(Not supported).
[EINTR]
 | A signal interrupted the write before it could be completed(currently not supported)..
[EAGAIN]
 | The file was marked for non-blocking I/O, and no data could be written immediately.
[EROFS]
 | An attempt was made to write over a disk label area at the beginning of a slice. Use disklabel -W to enable writing on the disk label area(Not supported).
[EINVAL]
 | The value nbytes is greater than INT_MAX.

In addition, writev and pwritev may return one of the following errors:
[EDESTADDRREQ]
 | The destination is no longer available when writing to a Unix domain datagram socket on which connect had been used to set a destination address.
[EINVAL]
 | The iovcnt argument was less than or equal to 0, or greater than IOV_MAX.
[EINVAL]
 | One of the iov_len values in the iov array was negative.
[EINVAL]
 | The sum of the iov_len values in the iov array overflowed a 32-bit integer.
[ENOBUFS]
 | The mbuf pool has been completely exhausted when writing to a socket.

The pwrite and pwritev system calls may also return the following errors:
[EINVAL]
 | The offset value was negative.
[ESPIPE]
 | The file descriptor is associated with a pipe, socket, or FIFO.

See also

 fcntl, lseek, open, pipe, select
The write system call is expected to conform to -p1003.1-90. The writev and pwrite system calls are expected to conform to -xpg4.2.
The pwritev system call appeared in 6.0 . The pwrite function appeared in AT&T V.4 . The writev system call appeared in BSD 4.2 . The write function appeared in AT&T v6 .

Feedback

For additional information or queries on this page send feedback


wrmdir

Name

wrmdir - delete a directory

Library

 libc.lib

Synopsis
#include <wchar.h>
int wrmdir (const wchar_t *path);

Return values

 The wrmdir() function returns the value 0 if successful; otherwise the value -1 is returned and the global variable errno is set to indicate the error.

Detailed description

 The wrmdir system call removes a directory file whose name is given by path. The directory must not have any entries other than ‘.’ and ‘..’.

Examples

/**
 *  Detailed description: This test code demonstrates usage of wrmdir systemcall, it removes directory
 *  Example from the current working directory.
 *
 *  Preconditions: Expects empty directoy "Example" in current working directory.
**/
#include  <wchar.h>
int main()
{
  if(wrmdir(L"Example") < 0 )
  {
     printf("wrmdir failed \n");
     return -1;
  }
  printf("Directory Example removed \n");
  return 0;
}

Output Directory Example removed

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 entire path name exceeded 1023 characters.(Not supported)
[ENOENT]
 | The named directory does not exist.
[ENOTEMPTY]
 | The named directory contains files other than ‘.’ and ‘..’ in it.
[EACCES]
 | Search permission is denied for a component of the path prefix.(Not supported).
[EACCES]
 | Write permission is denied on the directory containing the link to be removed.
[EPERM]
 | The directory containing the directory to be removed is marked sticky, and neither the containing directory nor the directory to be removed are owned by the effective user ID.(Not supported)
[EBUSY]
 | The directory to be removed is the mount point for a mounted file system.(Not supported).
[EIO] | An I/O error occurred while deleting the directory entry or deallocating the inode.(Not supported).
[EROFS]
 | The directory entry to be removed resides on a read-only file system.(Not supported)
[EFAULT]
 | The path argument points outside the process’s allocated address space.(Not supported).

Feedback

For additional information or queries on this page send feedback


wscanf

Name

wscanf, fwscanf, swscanf, vwscanf, vswscanf, vfwscanf
- convert formatted wide-character input

Library

 libc.lib

Synopsis
#include <stdio.h>
#include <wchar.h>
int wscanf (const wchar_t * restrict format, ...);
int fwscanf (FILE * restrict stream, const wchar_t * restrict format, ...);
int swscanf (const wchar_t * restrict str, const wchar_t * restrict format, ...);
#include <stdarg.h>
int vwscanf (const wchar_t * restrict format, va_list ap);
int vswscanf (const wchar_t * restrict str, const wchar_t * restrict format, va_list ap);
int vfwscanf (FILE * restrict stream, const wchar_t * restrict format, va_list ap);

Return values

 These functions return the number of input items assigned, which can be fewer than provided 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 due to 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 as an 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.

Detailed description

 The wscanf family of functions scans input according to a format as described below. This format may contain conversion specifiers; the results from such conversions, if any, are stored through the pointer arguments. The wscanf function reads input from the standard input stream stdin, fwscanf reads input from the stream pointer stream, and swscanf reads its input from the wide character string pointed to by str. The vfwscanf function is analogous to vfwprintf and reads input from the stream pointer stream using a variable argument list of pointers. The vwscanf function scans a variable argument list from the standard input and the vswscanf function scans it from a wide character string; these are analogous to the vwprintf and vswprintf functions respectively. Each successive pointer argument must correspond properly with each successive conversion specifier (but see the * conversion below). All conversions are introduced by the % (percent sign) character. The format 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 input character does not match such a format character. Scanning also stops when an input conversion cannot be made (see below).

Conversions

 Following the % character introducing a conversion there may be a number of flag characters, as follows:
* | Suppresses assignment. The conversion that follows occurs as usual, but no 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 pointer is a pointer to a char (rather than int ) .
h | Indicates that the conversion will be one of dioux or n and the next pointer 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 next pointer is a pointer to a long int (rather than int ) , that the conversion will 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 the next 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 next pointer 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 next pointer is a pointer to long double .
j | Indicates that the conversion will be one of dioux or n and the next pointer is a pointer to a intmax_t (rather than int ) .
t | Indicates that the conversion will be one of dioux or n and the next pointer is a pointer to a ptrdiff_t (rather than int ) .
z | Indicates that the conversion will be one of dioux or n and the next pointer is a pointer to a size_t (rather than int ) .
q | (deprecated.) Indicates that the conversion will be one of dioux or n and the 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, expressed as a decimal integer, between the % and the conversion. If no width is given, a default of "infinity" is used (with one exception, below); otherwise at most this many characters are scanned in processing the conversion. Before conversion begins, most conversions skip white space; this white space is not counted against the field width.

The following conversions are available:
% Matches a literal ‘%’. That is, "%%" in the format string matches a single input ‘%’ character. No conversion is done, and assignment does not occur.
d | Matches an optionally signed decimal integer; the next pointer must be a pointer to int .
i | Matches an optionally signed integer; the next pointer must be a pointer to int . The integer is read in base 16 if it begins with ‘0x’ or ‘0X’, in base 8 if it begins with ‘0’, and in base 10 otherwise. Only characters that correspond to the base are used.
o | Matches an octal integer; the next pointer must be a pointer to unsigned int .
u | Matches an optionally signed decimal integer; the next pointer must be a pointer to unsigned int .
x, X | Matches an optionally signed hexadecimal integer; the next pointer must be a pointer to unsigned int .
a, A, e, E, f, F, g, G
Matches a floating-point number in the style of wcstod. The next 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 pointer must be a pointer to char , and the array must be large enough to accept the multibyte representation of all the sequence and the terminating NUL character. The input string stops at white space or at the maximum field width, 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 next pointer must be a pointer to char , and there must be enough room for the multibyte representation of all the characters (no terminating NUL is added). The usual skip of leading white space is suppressed. To skip white space first, use an explicit space in the format.

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 accepted characters; the next pointer must be a pointer to char , and there must be enough room for the multibyte representation of all the characters in the string, plus a terminating 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 [ character and a close bracket ] character. The set excludes those 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 after the 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 final close bracket; some implementations of wscanf use "A-Z" to represent the range of characters between ‘A’ and ‘Z’. The string ends with the appearance of a character not in the (or, with a circumflex, in) set or when the 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); the next pointer must be a pointer to void .
n | Nothing is expected; instead, the number of characters consumed thus far from the input is stored through the next pointer, which must be a pointer to 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 (category LC_NUMERIC).

For backwards compatibility, a "conversion" of ‘%\0’ causes an immediate return of EOF.

Examples

#include <stdio.h>
#include <wchar.h>
/* Illustrates how to use wscanf API */
int example_wscanf(void)
{
  int rval;
  int input;
 /* Display a message to the user to input an integer */
 wprintf(L"Enter an integer : ");
  /* Read an integer from the standard input */
  rval = wscanf(L"%d", &input);

  /* return the number of inputs that were read */
  return(rval);
}

#include <stdio.h>
#include <wchar.h>
/* Illustrates how to use swscanf API */
int example_swscanf(void)
{
  int rval;
  wchar_t wcs[100];
  wchar_t *bufptr = L"abcdefg";
 /* Read a string from the buffer bufptr*/
  rval = swscanf(bufptr, L"%s", wcs);

  /* The string that was read into wcs is printed */
  wprintf(L"%s",wcs);

  /* return the number of inputs that were read */
  return(rval);
}

#include <stdio.h>
#include <wchar.h>
/* Illustrates how to use fwscanf API */
int example_fwscanf(void)
{
  FILE *fp = NULL;
  int retval;
  wchar_t wcs[100];

  /* open the file for writing*/
  fp = fopen("write.txt","w");
  if(fp == NULL)
  {
    wprintf(L"Error: File open\n");
    return (-1);
  }
 /* Read a string from fp*/
  rval = fwscanf(fp, L"%s", wcs);

 /* Close the file that was opened */
  fclose(fp);

  /* return the number of inputs that were read */
  return(rval);
}

#include <stdio.h>
#include <wchar.h>
/* Illustrates how to use vwscanf API */
int example_vwscanf(va_list arg)
{
  int retval;

 /* Read a string from standard input */
  rval = vwscanf(L"%s", arg);

  /* return the number of inputs that were read */
  return(rval);
}

#include <stdio.h>
#include <wchar.h>
/* Illustrates how to use vswscanf API */
int example_vswscanf(va_list arg)
{
  int retval;
  wchar_t bufptr = L"abc";

 /* Read a string from bufptr */
  rval = vswscanf(bufptr, L"%s", arg);

  /* return the number of inputs that were read */
  return(rval);
}

#include <stdio.h>
#include <wchar.h>
/* Illustrates how to use vfwscanf API */
int example_vfwscanf(va_list arg)
{
  FILE *fp = NULL;
  int retval;

  /* open the file for writing*/
  fp = fopen("write.txt","w");
  if(fp == NULL)
  {
    wprintf(L"Error: File open\n");
    return (-1);
  }
 /* Read a string */
  rval = vfwscanf(fp, L"%s", arg);

  /* Close the file that was opened */
  fclose(fp);

  /* return the number of inputs that were read */
  return(rval);
}

Security considerations

 Please refer scanf

Limitations

 All these API’s don’t support long double length modifiers.

See also

 fgetwc, scanf, wcrtomb, wcstod, wcstol, wcstoul, wprintf
The fwscanf, wscanf, swscanf, vfwscanf, vwscanf and vswscanf functions conform to -isoC-99.

Bugs

 In addition to the bugs documented in scanf, wscanf does not support the "A-Z" notation for specifying character ranges with the character class conversion ('%[').

Feedback

For additional information or queries on this page send feedback


wsetlocale

Name

wsetlocale
- sets the current locale

Library

 libc.lib

Synopsis
#include <wchar.h>
wchar_t * wsetlocale (int category, const wchar_t *locale);

Return values

 Upon successful completion, wsetlocale returns the wide char string associated with the specified category for the requested locale. The wsetlocale function returns NULL and fails to change the locale if the given combination of category and locale make no sense.

Detailed description

 The wsetlocale function sets the C library’s notion of natural language formatting style for particular sets of routines. Each such style is called a 'locale' and is invoked using an appropriate name passed as a wide char string.

The wsetlocale function can recognise several categories of routines. The categories and the sets of routines recognised by wsetlocale are listed below:

LC_ALL | Set the entire locale generically.
LC_COLLATE | Set a locale for string collation routines. Currently locale setting does not have effect on this category.
LC_CTYPE | This controls recognition of upper and lower case, alphabetic or non-alphabetic characters, and so on. Currently locale setting does not have effect on this category.
LC_MESSAGES
 | Set a locale for message catalogs. Currently this category is not supported.
LC_MONETARY
 | Set a locale for formatting monetary values; this affects the localeconv function.
LC_NUMERIC | Set a locale for formatting numbers. This controls the formatting of decimal points in input and output of floating point numbers in functions such as printf and scanf, as well as values returned by localeconv.
LC_TIME | Set a locale for formatting dates and times using the strftime function.

Only three locales are defined by default, the empty string which denotes the native environment, the C and the POSIX locales, which denote the C language environment. A locale argument of NULL causes wsetlocale to return the current locale. By default, C programs start in the C locale. The only functions in the library that set the locale are wsetlocale and setlocale; the locale is never changed as a side effect of some other routine.

Examples

#include<stdio.h>
#include<wchar.h>
int main()
{
        //Set the locale to UK English
        wchar_t* locale = wsetlocale(LC_ALL,L"en_GB.ISO-8859-1");
        //Check whether locale setting is succesful or not
        if(NULL != locale)
        {
                wprintf(L"Locale setting is successful\n");
                wprintf(L"Locale is set to %s\n", locale);
        }
        else
        {
                wprintf(L"Locale setting failed\n");
        }
        return 0;
}

Output

Locale setting is successful
Locale is set to en_GB.ISO-8859-1

Errors

 No errors are defined.

See also

 setlocale, localeconv, nl_langinfo

Feedback

For additional information or queries on this page send feedback


wstat

Name

wstat
- get wide-character file status

Library

 libc.lib

Synopsis
#include <sys/types.h>
#include <sys/stat.h>
#include <wchar.h>
int wstat (const wchar_t *path, struct stat *sb);

Return values

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

Detailed description

 The wstat system call obtains information about the file pointed to by path. Read, write or execute permission of the named file is not required, but all directories listed in the path name leading to the file must be searchable.

The sb argument is a pointer to a stat structure as defined by
#include <sys/stat.h>and into which information is placed concerning the file.

The fields of struct stat related to the file system are as follows:
st_dev | The numeric ID of the device containing the file.
st_ino | The file’s inode number.
st_nlink
 | The number of hard links to the file.

The st_dev and st_ino fields together identify the file uniquely within the system.

The time-related fields of struct stat are as follows:
st_atime | Time when file data last accessed. Changed by the .Xr utimes 2, read and readv system calls.
st_mtime | Time when file data last modified.
st_ctime | Time when file status was last changed (inode data modification).
st_birthtime
 | Time when the inode was created.

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 the struct stat are as follows:
st_size | The file size in bytes.
st_blksize
 | The optimal I/O block size for the file.
st_blocks | The actual number of blocks allocated for the file in 512-byte units. As short symbolic links are stored in the inode, this number may be zero.

The access-related fields of struct stat are as follows:
st_uid | The user ID of the file’s owner.
st_gid | The group ID of the file.
st_mode
 | Status of the file (see below).

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

#include <sys/stat.h,>The following macros are available to test whether a st_mode value passed in the m argument corresponds to a file of the specified type: S_ISBLK (m); S_ISCHR (m); S_ISDIR (m); S_ISFIFO (m); S_ISLNK (m); S_ISREG (m); S_ISSOCK (m); S_ISWHT (m);
Test for a block special file.
Test for a character special file.
Test for a directory.
Test for a pipe or FIFO special file.
Test for a symbolic link. NOTE: Inode structure is not supported by symbian and hence link count updation is not possible. Check for symbolic link would always fail because of this reason.
Test for a regular file.
Test for a socket.
Test for a whiteout.

The macros evaluate to a non-zero value if the test is true or to the value 0 if the test is false.

Examples

/**
 * Detailed description: Sample usage of wstat system call
 * Preconditions: Example.txt file should be present in working directory
**/
#include <fcntl.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <wchar.h>
int main()
{
  struct stat buf;
   if(wstat(L"Example.txt"  , &buf) < 0 )
   {
      printf("Failed to wstat Example.txt \n");
      return -1;
   }
   printf("wstat system call succeded \n");
   return 0;
 }

Output

wstat system call succeded

Errors

 The wstat system call will fail if:
[EACCES]
 | Search permission is denied for a component of the path prefix.
[EFAULT]
 | The sb or path argument points to an invalid address.
[EIO] | An I/O error occurred while reading from or writing to the file system.
[ENAMETOOLONG]
 | A component of a pathname exceeded 255 characters, or an entire path name exceeded 1023 characters.
[ENOENT]
 | The named file does not exist.
[ENOTDIR]
 | A component of the path prefix is not a directory.

See also

 access, wchmod, chown

Feedback

For additional information or queries on this page send feedback


wstrdate

Name

wstrdate - gets the system date in wide-character format.

Library

 libc.lib

Synopsis
#include <wchar.h>
wchar_t* wstrdate (const wchar_t *datestr);

Detailed description

 The wstrdate() function gets the system date and converts it into wide-character string. This copies the current system date into the string pointed by datestr in the format dd/mm/yyyy, the datestr buffer must be atleast 11 bytes long.It returns a pointer to the datestr string. Because the modification is done in place, the pointer returned is the same as the pointer passed as the input argument.

Return values

 The wstrdate() returns a pointer to the date string, on success else it returns NULL pointer and sets the errno accordingly.

Examples

#include <wchar.h>
/* Illustrates how to use wstrdate API */
int example_wstrdate(void)
{
  /* input string which is updated with the system date. */
  wchar_t datestr[20];

  wchar_t *res = NULL;

  /* function call to get the system date in wide-char format */
  res = wstrdate(datestr);
  if( !res && !datestr)
  {
        printf(" res - %s and datestr - %s",res, datestr);
        return 0;
  }
  else
        return -1;
}

Output

 res - 21/11/2006 and datestr - 21/11/2006

Errors

 The wstrdate function will fail if:
[EFAULT]
The supplied argument datestr is invalid.

See also

 strdate, strftime, strptime, wstrtime.

Feedback

For additional information or queries on this page send feedback


wstrtime

Name

wstrtime - gets the system time in wide-character format.

Library

 libc.lib

Synopsis
#include <wchar.h>
wchar_t* wstrtime (const wchar_t *timestr);

Detailed description

 The wstrtime() function gets the system time and converts it into wide-character string. This copies the current system time into the string pointed by timestr in the format hh:mm:ss, the timestr buffer must be atleast 9 bytes long.It returns a pointer to the timestr string. Because the modification is done in place, the pointer returned is the same as the pointer passed as the input argument.

Return values

 The wstrtime() returns a pointer to the time string, on success else it returns NULL pointer and sets the errno accordingly.

Examples

#include <wchar.h>
/* Illustrates how to use wstrtime API */
int example_wstrtime(void)
{
  /* input string which is updated with the system time. */
  wchar_t timestr[20];

  wchar_t *res = NULL;

  /* function call to get the system time in wide-char format */
  res = wstrtime(timestr);
  if( !res && !timestr)
  {
        printf(" res - %s and timestr - %s",res, timestr);
        return 0;
  }
  else
        return -1;
}

Output

 res - 15:46:36 and timestr - 15:46:36

Errors

 The wstrtime function will fail if:
[EFAULT]
The supplied argument timestr is invalid.

See also

 strtime, strftime, strptime.

Feedback

For additional information or queries on this page send feedback


wsystem

Name

wsystem - execute a shell command

Library

 libc.lib

Synopsis
#include <wchar.h>
int wsystem (const wchar_t *string);

Return values

 The wsystem function returns the exit status of the child process as returned by process’ exit reason or -1 if an error occurred when spawning a new process.

Detailed description

 The wsystem function spawns another process with the argument string. The calling process waits for the child process to finish executing.

If string is a NULL pointer, wsystem will return non-zero to indicate that wsystem is suporrted and zero if it is not supported.

Examples

#include <stdlib.h>
#include <stdio.h> //printf
#include <wchar.h>

int main( void )
{
   int retVal = -1;

   printf( "Calling wsystem()...\n" );

   /* helloworld.exe is an executable that just prints
    * "Hello world!" and it should be created before
    * executing this example code.
    */
   retVal = wsystem(L"c:\\sys\\bin\\helloworld.exe");

   /* Print the return value of wsystem() */
   printf( "wsystem() returned: %d", retVal );

   return 0;
}

Output

Calling wsystem()...
wsystem() returned: -1

See also

 wpopen

Feedback

For additional information or queries on this page send feedback


wtelldir

Name

wtelldir, wseekdir
- directory operations

Library

 libc.lib

Synopsis
#include <wchar.h>
#include <dirent.h>

off_t wtelldir (WDIR *dirp);
void wseekdir (WDIR *dirp, long loc);

Return values

wtelldir function returns current location associated with the named directory stream on success or -1 on failure.

Detailed description

 The wtelldir function returns the current location associated with the named directory stream. Values returned by wtelldir are good only for the lifetime of the DIR pointer, dirp, from which they are derived. If the directory is closed and then reopened, prior values returned by wtelldir will no longer be valid.

The wseekdir function sets the position of the next wreaddir operation on the directory stream. The new position reverts to the one associated with the directory stream when the wtelldir operation was performed.

Examples

#include <dirent.h>
#include<wchar.h>
#include<stdio.h>
#include<unistd.h>
#include<sys/types.h>
void  wTest()
    {
      //declare the variables for dir pointer and dir position.
      wchar_t *dirName  =L"c:\test_wseekdir";
      off_t dirpos;
        // Open the directory
        WDIR *dirp = wopendir (dirName);

        if(dirp != NULL)
        {
                //read the directory.
                wreaddir(dirp);
                wreaddir(dirp);
                //get the dirp pointer position by calling telldir API.
                dirpos = wtelldir(dirp);
                //print the position of the dirp pointer.
                printf(“dirp is pointing at position %ld. \n”,dirpos);

                wseekdir(dirp , 0) ;
                wreaddir(dirp);
                dirpos = wtelldir(dirp);
                //print the position of the dirp pointer.
                printf(“dirp is pointing at position %ld. \n”,dirpos);
        }
    }

Output

Dirp is pointing at position 2.
Dirp is pointing at position 1.

Errors
[EFAULT]
A directory pointer dirp is not valid.

See also

 wclosedir, wopendir, wreaddir

Feedback

For additional information or queries on this page send feedback


wtmpnam

Name

wtmpnam - generate temporary file name.

Library

 libc.lib

Synopsis
#include <wchar.h>
wchar_t * wtmpnam (wchar_t *str);

Return values

 The wtmpnam function return a pointer to a file name on success, and a NULL pointer on error.

Detailed description

 The wtmpnam 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 copied to a static buffer. In either case, wtmpnam 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 environment variable TMPDIR (if set), the argument tmpdir (if non-NULL), the directory P_tmpdir, and the directory /tmp are tried, in the listed order, as directories in which to store the temporary file.

Examples

#include<stdio.h> //wtmpnam
#include<sys/stat.h> //S_IWUSR
#include<errno.h> //errno

int main()
{
 //create a directory c:\system emp
 wmkdir(L"c:\\system\\temp", S_IWUSR);

 wchar_t wbuf[L_tmpnam];
 wchar_t rbuf[10];

 //call wtmpnam() to create a file
 wchar_t *rval = wtmpnam(wbuf);

 errno = 0;
 //open the file with the name returned by wtmpnam()
 FILE *fp = wfopen(buf, L"w");

 if (fp == NULL)
 {
     printf("fopen of file returned by wtmpnam() failed - errno %d ", errno);
     return -1;
 }

 if(fp)
 {
    fwprintf(fp, L"%ls", L"check");
    fclose(fp);
 }

 fp = wfopen(buf, L"r");

 if(fp)
 {
     fwscanf(fp, L"%ls", rbuf);
     fclose(fp);
 }

 printf("read from file: %ls\n", rbuf);
 printf("argument buf: %ls\n", buf);
 printf("return value: %ls\n", rval);

 return 0;
}

Output

read from file: check
argument buf: /System/temp/tmp.0.U9UPTx
return value: /System/temp/tmp.0.U9UPTx

Errors

 The wtmpnam function may fail and set errno for any of the errors specified for the library function mktemp.

See also

 mktemp, tmpnam

Feedback

For additional information or queries on this page send feedback


wunlink

Name

wunlink - delete a name and possibly the file it refers to

Library

 libc.lib

Synopsis
#include <wchar.h>
int wunlink (const wchar_t *path);

Return values

 Upon successful completion, 0 shall be returned. Otherwise, -1 shall be returned and errno set to indicate the error.

Detailed description

 The wunlink system call removes the link named by path from its file system. It is expected to decrement the link count of the file which was referenced by the link, but since this is a simulated function and not supported by the platform, link count does not get modified. As the parent file to which a link is created itself is unaware about the link, a wunlink on the parent file will close the file regardless of weather there existed any link to the file. The path argument may not be a directory.

Examples

/*
* Detailed description: Example to wunlink a link file
* Precondition: A file by name "Link" should exist in
*                c: drive.
*/
#include <wchar.h>
#include <stdio.h>
int main(void)
{
    if(wunlink(L"C:\\Link"))
    {
         printf("wunlink on link file failed");
    }
    printf("wunlink on link file succeeded");
}

Output

wunlink on link file succeeded.

Errors

 The wunlink succeeds unless:
[ENOENT]
 | The named file does not exist.
[EINVAL]
 | A relative path was encountered in translating path and is not supported by the platform.
[ENOENT]
 | An empty path was encountered while translating the pathname.
[EINVAL]
 | File mentioned in the path is open.

Errors

 The function wunlink may fail to update the timestamp of the parent directory.

See also

 close, rmdir

Feedback

For additional information or queries on this page send feedback


x509 - X.509 certificate handling

Name

x509 — X.509 certificate handling

Library

libcrypto.lib

Synopsis

#include <openssl/x509.h>

Detailed Description

A X.509 certificate is a structured grouping of information about an individual, a device, or anything one can imagine. A X.509 CRL (certificate revocation list) is a tool to help determine if a certificate is still valid. The exact definition of those can be found in the X.509 document from ITU-T, or in RFC3280 from PKIX. In OpenSSL, the type X509 is used to express such a certificate, and the type X509_CRL is used to express a CRL.

A related structure is a certificate request, defined in PKCS#10 from RSA Security, Inc, also reflected in RFC2896. In OpenSSL, the type X509_REQ is used to express such a certificate request.

To handle some complex parts of a certificate, there are the types X509_NAME (to express a certificate name), X509_ATTRIBUTE (to express a certificate attributes), X509_EXTENSION (to express a certificate extension) and a few more.

Finally, there's the supertype X509_INFO, which can contain a CRL, a certificate and a corresponding private key.

X509_..., d2i_X509_... and i2d_X509_... handle X.509 certificates, with some exceptions, shown below.

X509_CRL_..., d2i_X509_CRL_... and i2d_X509_CRL_... handle X.509 CRLs.

X509_REQ_..., d2i_X509_REQ_... and i2d_X509_REQ_... handle PKCS#10 certificate requests.

X509_NAME_... handle certificate names.

X509_ATTRIBUTE_... handle certificate attributes.

X509_EXTENSION_... handle certificate extensions.

See Also

X509_NAME_ENTRY_get_object(),
X509_NAME_add_entry_by_txt(),
X509_NAME_add_entry_by_NID(),
X509_NAME_print_ex(),
X509_NAME_new(),
d2i_X509(),
d2i_X509_ALGOR(),
d2i_X509_CRL(),
d2i_X509_NAME(),
d2i_X509_REQ(),
d2i_X509_SIG(),
crypto(),
x509v3()

Feedback

For additional information or queries on this page send feedback


X509_NAME_delete_entry - X509_NAME modification functions

Name

X509_NAME_add_entry_by_txt, X509_NAME_add_entry_by_OBJ
X509_NAME_add_entry_by_NID, X509_NAME_add_entry
X509_NAME_delete_entry

X509_NAME modification functions

Library

libcrypto.lib

Synopsis

int X509_NAME_add_entry_by_txt(X509_NAME *name, const char *field, int type, const unsigned char *bytes, int len, int loc, int set);
int X509_NAME_add_entry_by_OBJ(X509_NAME *name, ASN1_OBJECT *obj, int type, unsigned char *bytes, int len, int loc, int set);
int X509_NAME_add_entry_by_NID(X509_NAME *name, int nid, int type, unsigned char *bytes, int len, int loc, int set);
int X509_NAME_add_entry(X509_NAME *name,X509_NAME_ENTRY *ne, int loc, int set);
X509_NAME_ENTRY *X509_NAME_delete_entry(X509_NAME *name, int loc);

Detailed Description

X509_NAME_add_entry_by_txt(), X509_NAME_add_entry_by_OBJ() and X509_NAME_add_entry_by_NID() add a field whose name is defined by a string field, an object obj or a NID nid respectively. The field value to be added is in bytes of length len. If len is -1 then the field length is calculated internally using strlen(bytes).

The type of field is determined by type which can either be a definition of the type of bytes (such as MBSTRING_ASC) or a standard ASN1 type (such as V_ASN1_IA5STRING). The new entry is added to a position determined by loc and set.

X509_NAME_add_entry() adds a copy of X509_NAME_ENTRY structure ne to name. The new entry is added to a position determined by loc and set. Since a copy of ne is added ne must be freed up after the call.

X509_NAME_delete_entry() deletes an entry from name at position loc. The deleted entry is returned and must be freed up.

Notes

The use of string types such as MBSTRING_ASC or MBSTRING_UTF8 is strongly recommended for the type parameter. This allows the internal code to correctly determine the type of the field and to apply length checks according to the relevant standards. This is done using ASN1_STRING_set_by_NID().

If instead an ASN1 type is used no checks are performed and the supplied data in bytes is used directly.

In X509_NAME_add_entry_by_txt() the field string represents the field name using OBJ_txt2obj(field, 0).

The loc and set parameters determine where a new entry should be added. For almost all applications loc can be set to -1 and set to 0. This adds a new entry to the end of name as a single valued RelativeDistinguishedName (RDN).

loc actually determines the index where the new entry is inserted: if it is -1 it is appended.

set determines how the new type is added. If it is zero a new RDN is created.

If set is -1 or 1 it is added to the previous or next RDN structure respectively. This will then be a multivalued RDN: since multivalues RDNs are very seldom used set is almost always set to zero.

Examples

Create an X509_NAME structure:

"C=UK, O=Disorganized Organization, CN=Joe Bloggs''

 X509_NAME *nm;
 nm = X509_NAME_new();
 if (nm == NULL)
        /* Some error */
 if (!X509_NAME_add_entry_by_txt(nm, MBSTRING_ASC, "C", "UK", -1, -1, 0))
        /* Error */
 if (!X509_NAME_add_entry_by_txt(nm, MBSTRING_ASC, "O", "Disorganized Organization", -1, -1, 0))
        /* Error */
 if (!X509_NAME_add_entry_by_txt(nm, MBSTRING_ASC, "CN", "Joe Bloggs", -1, -1, 0))
        /* Error */

Return Values

X509_NAME_add_entry_by_txt(), X509_NAME_add_entry_by_OBJ(), X509_NAME_add_entry_by_NID() and X509_NAME_add_entry() return 1 for success of 0 if an error occurred.

X509_NAME_delete_entry() returns either the deleted X509_NAME_ENTRY structure of NULL if an error occurred.

Bugs

type can still be set to V_ASN1_APP_CHOOSE to use a different algorithm to determine field types. Since this form does not understand multicharacter types, performs no length checks and can result in invalid field types its use is strongly discouraged.

See Also

ERR_get_error(), d2i_X509_NAME()

History

Feedback

For additional information or queries on this page send feedback


X509_NAME_ENTRY_create_by_OBJ - X509_NAME_ENTRY utility functions

Name

X509_NAME_ENTRY_get_object, X509_NAME_ENTRY_get_data
X509_NAME_ENTRY_set_object, X509_NAME_ENTRY_set_data
X509_NAME_ENTRY_create_by_txt, X509_NAME_ENTRY_create_by_NID
X509_NAME_ENTRY_create_by_OBJ

X509_NAME_ENTRY utility functions

Library

libcrypto.lib

Synopsis

ASN1_OBJECT * X509_NAME_ENTRY_get_object(X509_NAME_ENTRY *ne); ASN1_STRING * X509_NAME_ENTRY_get_data(X509_NAME_ENTRY *ne);
int X509_NAME_ENTRY_set_object(X509_NAME_ENTRY *ne, ASN1_OBJECT *obj);
int X509_NAME_ENTRY_set_data(X509_NAME_ENTRY *ne, int type, const unsigned char *bytes, int len);
X509_NAME_ENTRY *X509_NAME_ENTRY_create_by_txt(X509_NAME_ENTRY **ne, const char *field, int type, const unsigned char *bytes,
                                               int len);
X509_NAME_ENTRY *X509_NAME_ENTRY_create_by_NID(X509_NAME_ENTRY **ne, int nid, int type,unsigned char *bytes, int len);
X509_NAME_ENTRY *X509_NAME_ENTRY_create_by_OBJ(X509_NAME_ENTRY **ne, ASN1_OBJECT *obj, int type, const unsigned char *bytes,
                                               int len);

Detailed Description

X509_NAME_ENTRY_get_object() retrieves the field name of ne in and ASN1_OBJECT structure.

X509_NAME_ENTRY_get_data() retrieves the field value of ne in and ASN1_STRING structure.

X509_NAME_ENTRY_set_object() sets the field name of ne to obj.

X509_NAME_ENTRY_set_data() sets the field value of ne to string type type and value determined by bytes and len.

X509_NAME_ENTRY_create_by_txt(),
X509_NAME_ENTRY_create_by_NID()
and  X509_NAME_ENTRY_create_by_OBJ() create and return an
X509_NAME_ENTRY structure.

Notes

X509_NAME_ENTRY_get_object() and X509_NAME_ENTRY_get_data() can be used to examine an X509_NAME_ENTRY function as returned by X509_NAME_get_entry() for example.

X509_NAME_ENTRY_create_by_txt(), X509_NAME_ENTRY_create_by_NID(), and X509_NAME_ENTRY_create_by_OBJ() create and return an

X509_NAME_ENTRY_create_by_txt(), X509_NAME_ENTRY_create_by_OBJ(), X509_NAME_ENTRY_create_by_NID() and X509_NAME_ENTRY_set_data() are seldom used in practice because X509_NAME_ENTRY structures are almost always part of X509_NAME structures and the corresponding X509_NAME functions are typically used to create and add new entries in a single operation.

The arguments of these functions support similar options to the similarly named ones of the corresponding X509_NAME functions such as X509_NAME_add_entry_by_txt(). So for example type can be set to MBSTRING_ASC but in the case of X509_set_data() the field name must be set first so the relevant field information can be looked up internally.

Return Values

See Also

ERR_get_error(),
d2i_X509_NAME(),
OBJ_nid2obj(),

History

TBA

Feedback

For additional information or queries on this page send feedback


X509_NAME_get_text_by_OBJ - X509_NAME lookup and enumeration functions

Name

X509_NAME_get_index_by_NID, X509_NAME_get_index_by_OBJ
X509_NAME_get_entry, X509_NAME_entry_count
X509_NAME_get_text_by_NID, X509_NAME_get_text_by_OBJ

X509_NAME lookup and enumeration functions

Library

libcrypto.lib

Synopsis

int X509_NAME_get_index_by_NID(X509_NAME *name,int nid,int lastpos);
int X509_NAME_get_index_by_OBJ(X509_NAME *name,ASN1_OBJECT *obj, int lastpos);
int X509_NAME_entry_count(X509_NAME *name); X509_NAME_ENTRY *X509_NAME_get_entry(X509_NAME *name, int loc);
int X509_NAME_get_text_by_NID(X509_NAME *name, int nid, char *buf,int len);
int X509_NAME_get_text_by_OBJ(X509_NAME *name, ASN1_OBJECT *obj, char *buf,int len);

Detailed Description

These functions allow an X509_NAME structure to be examined. The X509_NAME structure is the same as the Name type defined in RFC2459 (and elsewhere) and used for example in certificate subject and issuer names.

X509_NAME_get_index_by_NID() and X509_NAME_get_index_by_OBJ() retrieve the next index matching nid or obj after lastpos. lastpos should initially be set to -1. If there are no more entries -1 is returned.

X509_NAME_entry_count() returns the total number of entries in name.

X509_NAME_get_entry() retrieves the X509_NAME_ENTRY from name corresponding to index loc. Acceptable values for loc run from 0 to (X509_NAME_entry_count(name) - 1). The value returned is an internal pointer which must not be freed.

X509_NAME_get_text_by_NID(), X509_NAME_get_text_by_OBJ() retrieve the ``text'' from the first entry in name which matches nid or obj, if no such entry exists -1 is returned. At most len bytes will be written and the text written to buf will be null terminated. The length of the output string written is returned excluding the terminating null. If buf is <NULL> then the amount of space needed in buf (excluding the final null) is returned.

Examples

Process all entries:
 int i;
 X509_NAME_ENTRY *e;
 for (i = 0; i < X509_NAME_entry_count(nm); i++)
        {
        e = X509_NAME_get_entry(nm, i);
        /* Do something with e */
        }

Process all commonName entries:

 int loc;
 X509_NAME_ENTRY *e;
 loc = -1;
 for (;;)
        {
        lastpos = X509_NAME_get_index_by_NID(nm, NID_commonName, lastpos);
        if (lastpos == -1)
                break;
        e = X509_NAME_get_entry(nm, lastpos);
        /* Do something with e */
        }

Notes

X509_NAME_get_text_by_NID() and X509_NAME_get_text_by_OBJ() are legacy functions which have various limitations which make them of minimal use in practice. They can only find the first matching entry and will copy the contents of the field verbatim: this can be highly confusing if the target is a muticharacter string type like a BMPString or a UTF8String.

For a more general solution X509_NAME_get_index_by_NID() or X509_NAME_get_index_by_OBJ() should be used followed by X509_NAME_get_entry() on any matching indices and then the various X509_NAME_ENTRY utility functions on the result.

Return Values

X509_NAME_get_index_by_NID() and X509_NAME_get_index_by_OBJ() return the index of the next matching entry or -1 if not found.

X509_NAME_entry_count() returns the total number of entries.

X509_NAME_get_entry() returns an X509_NAME pointer to the requested entry or NULL if the index is invalid.

See Also

ERR_get_error(), d2i_X509_NAME()

History

TBA

Feedback

For additional information or queries on this page send feedback


X509_NAME_oneline - X509_NAME printing routines.

Name

X509_NAME_print_ex, X509_NAME_print_ex_fp
X509_NAME_print, X509_NAME_oneline

X509_NAME printing routines

Library

libcrypto.lib

Synopsis

#include <openssl/x509.h>
int X509_NAME_print_ex(BIO *out, X509_NAME *nm, int indent, unsigned long flags);
int X509_NAME_print_ex_fp(FILE *fp, X509_NAME *nm, int indent, unsigned long flags);
char * X509_NAME_oneline(X509_NAME *a,char *buf,int size);
int X509_NAME_print(BIO *bp, X509_NAME *name, int obase);

Detailed Description

X509_NAME_print_ex() prints a human readable version of nm to BIO out. Each line (for multiline formats) is indented by indent spaces. The output format can be extensively customized by use of the flags parameter.

X509_NAME_print_ex_fp() is identical to X509_NAME_print_ex() except the output is written to FILE pointer fp.

X509_NAME_oneline() prints an ASCII version of a to buf. At most size bytes will be written. If buf is NULL then a buffer is dynamically allocated and returned, otherwise buf is returned.

X509_NAME_print() prints out name to bp indenting each line by obase characters. Multiple lines are used if the output (including indent) exceeds 80 characters.

Notes

The functions X509_NAME_oneline() and X509_NAME_print() are legacy functions which produce a non standard output form, they don't handle multi character fields and have various quirks and inconsistencies. Their use is strongly discouraged in new applications.

Although there are a large number of possible flags for most purposes XN_FLAG_ONELINE, XN_FLAG_MULTILINE or XN_FLAG_RFC2253 will suffice. As noted on the ASN1_STRING_print_ex() manual page for UTF8 terminals the ASN1_STRFLGS_ESC_MSB should be unset: so for example XN_FLAG_ONELINE & ~ASN1_STRFLGS_ESC_MSB would be used.

The complete set of the flags supported by X509_NAME_print_ex() is listed below.

Several options can be ored together.

The options XN_FLAG_SEP_COMMA_PLUS, XN_FLAG_SEP_CPLUS_SPC, XN_FLAG_SEP_SPLUS_SPC and XN_FLAG_SEP_MULTILINE determine the field separators to use. Two distinct separators are used between distinct RelativeDistinguishedName components and separate values in the same RDN for a multi-valued RDN. Multi-valued RDNs are currently very rare so the second separator will hardly ever be used.

XN_FLAG_SEP_COMMA_PLUS uses comma and plus as separators. XN_FLAG_SEP_CPLUS_SPC uses comma and plus with spaces: this is more readable that plain comma and plus. XN_FLAG_SEP_SPLUS_SPC uses spaced semicolon and plus. XN_FLAG_SEP_MULTILINE uses spaced new line and plus respectively.

If XN_FLAG_DN_REV is set the whole DN is printed in reversed order.

The fields XN_FLAG_FN_SN, XN_FLAG_FN_LN, XN_FLAG_FN_OID, XN_FLAG_FN_NONE determine how a field name is displayed. It will use the short name (e.g. CN) the long name (e.g. commonName) always use OID numerical form (normally OIDs are only used if the field name is not recognized) and no field name respectively.

If XN_FLAG_SPC_EQ is set then spaces will be placed around the '=' character separating field names and values.

If XN_FLAG_DUMP_UNKNOWN_FIELDS is set then the encoding of unknown fields is printed instead of the values.

If XN_FLAG_FN_ALIGN is set then field names are padded to 20 characters: this is only of use for multiline format.

Additionally all the options supported by ASN1_STRING_print_ex() can be used to control how each field value is displayed.

In addition a number options can be set for commonly used formats.

XN_FLAG_RFC2253 sets options which produce an output compatible with RFC2253 it is equivalent to: ASN1_STRFLGS_RFC2253 | XN_FLAG_SEP_COMMA_PLUS | XN_FLAG_DN_REV | XN_FLAG_FN_SN | XN_FLAG_DUMP_UNKNOWN_FIELDS

XN_FLAG_ONELINE is a more readable one line format it is the same as: ASN1_STRFLGS_RFC2253 | ASN1_STRFLGS_ESC_QUOTE | XN_FLAG_SEP_CPLUS_SPC | XN_FLAG_SPC_EQ | XN_FLAG_FN_SN

XN_FLAG_MULTILINE is a multiline format is the same as: ASN1_STRFLGS_ESC_CTRL | ASN1_STRFLGS_ESC_MSB | XN_FLAG_SEP_MULTILINE | XN_FLAG_SPC_EQ | XN_FLAG_FN_LN | XN_FLAG_FN_ALIGN

XN_FLAG_COMPAT uses a format identical to X509_NAME_print(): in fact it calls X509_NAME_print() internally.

See Also

ASN1_STRING_print_ex()

History

TBA

Feedback

For additional information or queries on this page send feedback


X509_free - X509 certificate ASN1 allocation functions

Name

X509_new, X509_free — X509 certificate ASN1 allocation functions

Library

libcrypto.lib

Synopsis

X509 *X509_new(void);
void X509_free(X509 *a);

Detailed Description

The X509 ASN1 allocation routines, allocate and free an X509 structure, which represents an X509 certificate.

X509_new() allocates and initializes a X509 structure.

X509_free() frees up the X509 structure a.

Return Values

If the allocation fails, X509_new() returns NULL and sets an error code that can be obtained by ERR_get_error(). Otherwise it returns a pointer to the newly allocated structure.

X509_free() returns no value.

See Also

ERR_get_error(), d2i_X509()

History

X509_new() and X509_free() are available in all versions of SSLeay and OpenSSL.

Feedback

For additional information or queries on this page send feedback


compress2

Name

compress2 — Compresses data at a specified level.

Library

Libz.lib

Synopsis

#include <zlib.h>
int compress2(Bytef * dest, uLongf * destLen, const Bytef * source, uLong sourceLen, int level);

Return Value

On success, compress2( ) shall return Z_OK. Otherwise, compress2( ) shall return a value to indicate the error.

Detailed Description

The compress2( ) function shall attempt to compress sourceLen bytes of data in the buffer source, placing the result in the buffer dest, at the level described by level. The level supplied shall be a value between 0 and 9, or the value Z_DEFAULT_COMPRESSION. A level of 1 requests the highest speed, while a level of 9 requests the highest compression. A level of 0 indicates that no compression should be used, and the output shall be the same as the input.

On entry, destLen should point to a value describing the size of the dest buffer. The application should ensure that this value be at least (sourceLen × 1.001) + 12. On successful exit, the variable referenced by destLen shall be updated to hold the length of compressed data in dest.

The compress( ) function is equivalent to compress2( ) with a level of Z_DEFAULT_LEVEL.

Examples

To compress string "hello":

#include <stdio.h>
#include <zlib.h>
void test_compress(Byte * compr,uLong comprLen)
{
    const char hello[] = "hello, hello!";
    uLong len = (uLong)strlen(hello)+1;
    compress(compr, &comprLen, (const Bytef*)hello, len);
}

Output
compr contains the compressed data.

Errors

On error, compress2( ) shall return a value as described below:

Z_BUF_ERROR | The buffer dest was not large enough to hold the compressed data.
Z_MEM_ERROR | Insufficient memory.
Z_STREAM_ERROR | The level was not Z_DEFAULT_LEVEL, or was not between 0 and 9.

Feedback

For additional information or queries on this page send feedback


compress

Name

compress — Attempts to compress sourceLen bytes of data in the buffer source, placing the result in the buffer dest.

Library

Libz.lib

Synopsis

#include <zlib.h>
int compress(Bytef * dest, uLongf * destLen, const Bytef * source, uLong sourceLen);

Return Value

On success, compress() shall return Z_OK, otherwise compress() returns a value to indicate the error.

Detailed Description

The compress() function attempts to compress sourceLen bytes of data in the buffer source, placing the result in the buffer dest.

On entry, destLen points to a value describing the size of the dest buffer. The application should ensure that this value should atleast be (sourceLen × 1.001) + 12. On successful exit, the variable referenced by destLen shall be updated to hold the length of compressed data in dest.

The compress() function is equivalent to compress2() with a level of Z_DEFAULT_LEVEL.

Examples

To compress string "hello" with level value 6:

#include <stdio.h>
#include <zlib.h>
void Compress2()
{
    uLong len = (uLong)strlen(hello)+1;
    const char hello[] = "hello, hello!";
    Byte *compr, *uncompr;
    uLong comprLen = 20*sizeof(int);
    compr = (Byte*)calloc((uInt)comprLen, 1);
    compress2(compr, &comprLen, (const Bytef*)hello, len,6);
    free(compr);
}

Output
compr contains the compressed data.

Errors

On error, compress() shall return a value as described below:

Z_BUF_ERROR | The buffer dest was not large enough to hold the compressed data.
Z_MEM_ERROR | Insufficient memory.

Feedback

For additional information or queries on this page send feedback


compressBound

Name

compressBound — Estimates the size of buffer required to compress sourceLen bytes of data using the compress() or compress2() functions.

Library

Libz.lib

Synopsis

#include <zlib.h>
int compressBound(uLong sourceLen);

Return Value

The compressBound() shall return a value representing the upper bound of an array to allocate to hold the compressed data in a single call to compress() or compress2(). This function may return a conservative value that may be larger than sourceLen.

Detailed Description

The compressBound() function shall estimate the size of buffer required to compress sourceLen bytes of data using the compress() or compress2( ) functions. If successful, the value returned shall be an upper bound for the size of buffer required to compress sourceLen bytes of data, using the parameters stored in stream, in a single call to compress() or compress2().

Examples

To estimate the size of buffer required to compress 6 bytes of data:

#include <stdio.h>
#include <zlib.h>
void test_compressbound(Byte * compr,uLong comprLen)
{
    uLong sourceLen = (uLong)strlen(hello)+1;
    const char hello[] = "hello, hello!";
    compress(compr, &comprLen, (const Bytef*)hello, 6);
    int x =  compressBound(sourceLen);
    printf("size of buffer required is %d",x);
}

Output

size of buffer required is 25.

Errors

None defined.

Feedback

For additional information or queries on this page send feedback


crc32

Name

crc32 — Computes a running Cyclic Redundancy Check checksum.

Library

Libz.lib

Synopsis

#include <zlib.h>
uLong crc32(uLong crc, const Bytef * buf, uInt len);

Return Value

The crc32() function shall return the new checksum value.

Detailed Description

The crc32() function shall compute a running Cyclic Redundancy Check checksum. On entry, crc is the previous value for the checksum, and buf shall point to an array of len bytes of data to be added to this checksum. The crc32() function shall return the new checksum.

If buf is NULL (or Z_NULL), crc32() shall return the initial checksum.

Examples

To compute a running Cyclic Redundancy Check checksum for "1234":

#include <stdio.h>
#include <zlib.h>
void Crc( )
{
     unsigned char  buffer[5]="1234";
     unsigned int i=4;
     unsigned long j=0L;
     const char hello[] = "hello, hello!";
     long crc1 = crc32(j,0, 0);
     long crc = crc32(crc1, &buffer[0], i);
     printf("crc checksum is  %x",crc);
}

Output

crc checksum is  9be3e0a3.

Errors

None defined.

Feedback

For additional information or queries on this page send feedback


deflate

Name

deflate — Attempts to compress data until either the input buffer is empty or the output buffer is full.

Library

Libz.lib

Synopsis

#include <zlib.h>
int deflate(z_streamp stream, int flush);

Return Value

On success, deflate() shall return Z_OK, unless flush was set to Z_FINISH and there was sufficient space in the output buffer to compress all of the input data. In this case, deflate() shall return Z_STREAM_END. On error, deflate() shall return a value to indicate the error.

Note

Note: If deflate() returns Z_OK and has set avail_out to zero, the function should be called again with the same value for flush, and with updated next_out and avail_out until deflate() returns with Z_OK (or Z_STREAM_END if flush is set to Z_FINISH) and a non-zero avail_out.

Detailed Description

The deflate() function attempts to compress data until either the input buffer is empty or the output buffer is full. The stream references a z_stream structure. Before the first call to deflate(), this structure should have been initialized by a call to deflateInit2_().

Note

Note: deflateInit2_() is only in the binary standard; source level applications should initialize stream via a call to deflateInit() or deflateInit2().

In addition, the stream input and output buffers should have been initialized as follows:
next_in | should point to the data to be compressed.
avail_in | should contain the number of bytes of data in the buffer referenced by next_in.
next_out | should point to a buffer where compressed data may be placed.
avail_out | should contain the size in bytes of the buffer referenced by next_out.

The deflate() function shall perform one or both of the following actions:

  1. Compress input data from next_in and update next_in, avail_in and total_in to reflect the data that has been compressed.

  2. Fill the output buffer referenced by next_out, and update next_out, avail_out and total_out to reflect the compressed data that has been placed there. If flush is not Z_NO_FLUSH, and avail_out indicates that there is still space in output buffer, this action shall always occur (see below for further details).

The deflate() function shall return when either avail_in reaches zero (indicating that all the input data has been compressed), or avail_out reaches zero (indicating that the output buffer is full).

On success, the deflate() function shall set the adler field of the stream to the adler32() checksum of all the input data compressed so far (represented by total_in).

If the deflate() function shall attempt to determine the type of input data, and set field data_type in stream to Z_ASCII if the majority of the data bytes fall within the ASCII (ISO 646) printable character range. Otherwise, it shall set data_type to Z_BINARY. This data type is informational only, and does not affect the compression algorithm.

Note

Note: Future versions of the LSB may remove this requirement, since it is based on an outdated character set that does not support Internationalization, and does not affect the algorithm. It is included for information only at this release. Applications should not depend on this field.

Examples

To compress data "hello" until either the input buffer is empty or the output buffer is full:

#include <stdio.h>
#include <zlib.h>
To compress data "hello" until either the input buffer is empty or the output buffer is full
void Deflate( )
{
    z_stream c_stream; /* compression stream */
    Byte * compr;
    uLong comprLen = 20*sizeof(int);
    compr    = (Byte*)calloc((uInt)comprLen, 1);
    const char hello[] = "hello, hello!";
    uLong len = (uLong)strlen(hello)+1;

    c_stream.zalloc = (alloc_func)0;
    c_stream.zfree = (free_func)0;
    c_stream.opaque = (voidpf)0;

    err = deflateInit(&c_stream, Z_DEFAULT_COMPRESSION);
    c_stream.next_in  = (Bytef*)hello;
    c_stream.next_out = compr;

    while (c_stream.total_in != len && c_stream.total_out < comprLen)
    {
        c_stream.avail_in = c_stream.avail_out = 1; /* force small buffers */
        err = deflate(&c_stream, Z_NO_FLUSH);
    }
    /* Finish the stream, still forcing small buffers: */
    deflateEnd(&c_stream);
    free(compr);
}

Flush Operation

The parameter flush determines when compressed bits are added to the output buffer in next_out. If flush is Z_NO_FLUSH, deflate() may return with some data pending output, and not yet added to the output buffer.

If flush is Z_SYNC_FLUSH, deflate() shall flush all pending output to next_out and align the output to a byte boundary. A synchronization point is generated in the output.

If flush is Z_FULL_FLUSH, all output shall be flushed, as for Z_SYNC_FLUSH, and the compression state shall be reset. A synchronization point is generated in the output.

Note

Rationale: Z_SYNC_FLUSH is intended to ensure that the compressed data contains all the data compressed so far, and allows a decompressor to reconstruct all of the input data. Z_FULL_FLUSH allows decompression to restart from this point if the previous compressed data has been lost or damaged. Flushing is likely to degrade the performance of the compression system, and should only be used where necessary.

If flush is set to Z_FINISH, all pending input shall be processed and deflate() shall return with Z_STREAM_END if there is sufficient space in the output buffer at next_out, as indicated by avail_out. If deflate() is called with flush set to Z_FINISH and there is insufficient space to store the compressed data, and no other error has occurred during compression, deflate() shall return Z_OK, and the application should call deflate() again with flush unchanged, and having updated next_out and avail_out.

If all the compression is to be done in a single step, deflate() may be called with flush set to Z_FINISH immediately after the stream has been initialized if avail_out is set to at least the value returned by deflateBound().

Errors

On error, deflate() shall return a value as described below, and set the msg field of stream to point to a string describing the error:

Z_BUF_ERROR | No progress is possible; either avail_in or avail_out was zero.
Z_MEM_ERROR | Insufficient memory.
Z_STREAM_ERROR | The state (as represented in stream) is inconsistent, or stream was NULL.

Feedback

For additional information or queries on this page send feedback


deflatebound

Name

deflateBound — Estimates the size of buffer required to compress sourceLen bytes of data.

Library

Libz.lib

Synopsis

#include <zlib.h>
int deflateBound(z_streamp stream, uLong sourceLen);

Return Value

The deflateBound() shall return a value representing the upper bound of an array to allocate to hold the compressed data in a single call to deflate(). If the stream is not correctly initialized, or is NULL, then deflateBound() may return a conservative value that may be larger than sourceLen.

Detailed Description

The deflateBound() function estimates the size of buffer required to compress sourceLen bytes of data. If successful, the value returned shall be an upper bound for the size of buffer required to compress sourceLen bytes of data, using the parameters stored in stream, in a single call to deflate() with flush set to Z_FINISH.

On entry, stream should have been initialized via a call to deflateInit_() or deflateInit2_().

Examples

Size of buffer required to compress sourceLength bytes of data:

#include <stdio.h>
#include <zlib.h>

void Deflatebound( )
{
    uLong len = (uLong)strlen(hello)+1;
    Byte *compr, *uncompr;
    uLong comprLen = 20*sizeof(int);
    uLong uncomprLen = comprLen;
    const char hello[] = "hello, hello!";
    compr    = (Byte*)calloc((uInt)comprLen, 1);
    uncompr  = (Byte*)calloc((uInt)uncomprLen, 1);
    stream.next_in = (Bytef*)hello;
    stream.avail_in = (uInt)comprLen;
    stream.next_out = dest;
    stream.avail_out = (uInt)*len;
    deflateInit(&stream, level);
    int y= deflateBound(&stream, sourceLen);
    deflateEnd(&stream);
    printf("size of buffer required is %d",x);
}

Output

Size of buffer required is 28.

Errors

None defined.

Feedback

For additional information or queries on this page send feedback


deflatecopy

Name

deflateCopy — Copies the compression state information in source to the uninitialized z_stream structure referenced by dest.

Library

Libz.lib

Synopsis

#include <zlib.h>
 int deflateCopy(z_streamp dest, z_streamp source);

Return Value

On success, deflateCopy() shall return Z_OK. Otherwise it shall return a value less than zero to indicate the error.

Detailed Description

The deflateCopy() function shall copy the compression state information in source to the uninitialized z_stream structure referenced by dest.

On successful return, dest will be an exact copy of the stream referenced by source. The input and output buffer pointers in next_in and next_out will reference the same data.

Examples

To copy the compression state information in source to the uninitialized z_stream structure referenced by dest.

#include <stdio.h>
#include <zlib.h>
void Deflatecopy( )
{
    uLong sourceLen = (uLong)strlen(hello)+1;
    z_stream stream;
    z_stream stream1;
    Byte *compr, *uncompr;
    Bytef *dest,  uLongf *destLen ;
    uLong comprLen = 20*sizeof(int);
    uLong uncomprLen = comprLen;
    int level=Z_DEFAULT_COMPRESSION;
    const char hello[] = "hello, hello!";
    compr = (Byte*)calloc((uInt)comprLen, 1);
    uncompr = (Byte*)calloc((uInt)uncomprLen, 1);

    stream.zalloc = (alloc_func)0;
    stream.zfree = (free_func)0;
    stream.opaque = (voidpf)0;
    stream.next_in = (Bytef*)hello;
    stream.avail_in = (uInt)sourceLen;
    stream.next_out = dest;
    stream.avail_out = (uInt)*destLen;

    deflateInit(&stream, level);
    deflateCopy(&stream1 , &stream);
    deflateEnd(&stream);
}

Output

Now stream1 and stream are in same state.

Errors

On error, deflateCopy() shall return a value as described below:
Z_STREAM_ERROR | The state in source is inconsistent, or either source or dest was NULL.
Z_MEM_ERROR | Insufficient memory available.

Feedback

For additional information or queries on this page send feedback


deflateEnd

Name

deflateEnd — Frees all allocated state information referenced by stream .

Library

Libz.lib

Synopsis

#include <zlib.h>
int deflateEnd(z_streamp stream);

Return Value

On success, deflateEnd() shall return Z_OK, or Z_DATA_ERROR if there was pending output discarded or input unprocessed. Otherwise it shall return Z_STREAM_ERROR to indicate the error.

Detailed Description

The deflateEnd() function shall free all allocated state information referenced by stream. All pending output is discarded, and unprocessed input is ignored.

Examples

To free all allocated state information referenced by c_stream:

#include <stdio.h>
#include <zlib.h>
void Deflateend( )
{
    z_stream c_stream; /* compression stream */
    uLong len = (uLong)strlen(hello)+1;
    Byte *compr, *uncompr;
    uLong comprLen = 20*sizeof(int);
    uLong uncomprLen = comprLen;
    compr    = (Byte*)calloc((uInt)comprLen, 1);
    uncompr  = (Byte*)calloc((uInt)uncomprLen, 1);
    const char hello[] = "hello, hello!";
    c_stream.zalloc = (alloc_func)0;
    c_stream.zfree = (free_func)0;
    c_stream.opaque = (voidpf)0;
    compress(compr, &comprLen, (const Bytef*)hello, len);
    err = deflateInit(&c_stream, Z_DEFAULT_COMPRESSION);
    c_stream.next_in  = (Bytef*)hello;
    c_stream.next_out = compr;

    while (c_stream.total_in != len && c_stream.total_out < comprLen)
     {
        c_stream.avail_in = c_stream.avail_out = 1; /* force small buffers */
        err = deflate(&c_stream, Z_NO_FLUSH);
     }
    /* Finish the stream, still forcing small buffers: */
    for (;;)
     {
        c_stream.avail_out = 1;
        err = deflate(&c_stream, Z_FINISH);
        if (err == Z_STREAM_END) break;
     }
   deflateEnd(&c_stream);
   free(compr);
   free(uncompr);
}

Errors

On error, deflateEnd() shall return Z_STREAM_ERROR. The following conditions shall be treated as an error:
  • The state in stream is inconsistent or inappropriate.
  • stream is Null.

Feedback

For additional information or queries on this page send feedback

<


deflateInit_

Name

deflateInit_ — Initializes the compression system.

Library

Libz.lib

Synopsis

#include <zlib.h>

int deflateInit_(z_streamp stream, int level, const char * version, int stream_size);

Return Value

On success, the deflateInit_() function shall return Z_OK. Otherwise, deflateInit_() shall return a value as described below to indicate the error.

Detailed Description

The deflateInit_() function shall initialize the compression system. On entry, stream shall refer to a user supplied z_stream object (a z_stream_s structure). The following fields shall be set on entry:

zalloc | a pointer to an alloc_func function, used to allocate state information. If this is NULL, a default allocation function will be used.
zfree | a pointer to a free_func function, used to free memory allocated by the zalloc function. If this is NULL a default free function will be used.
opaque | If alloc_func is not NULL, opaque is a user supplied pointer to data that will be passed to the alloc_func and free_func functions.

If the version requested is not compatible with the version implemented, or if the size of the z_stream_s structure provided in stream_size does not match the size in the library implementation, deflateInit_() shall fail, and return Z_VERSION_ERROR.

The level supplied shall be a value between 0 and 9, or the value Z_DEFAULT_COMPRESSION. A level of 1 requests the highest speed, while a level of 9 requests the highest compression. A level of 0 indicates that no compression should be used, and the output shall be the same as the input.

The deflateInit_() function is not in the source standard; it is only in the binary standard. Source applications should use the deflateInit() macro.

The deflateInit_() function is equivalent to deflateInit2_(stream, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY, version, stream_size).

Examples

To initialize the compression system:

#include <stdio.h>
#include <zlib.h>
void DeflateInit_( )
{
    z_stream stream;
    uLong sourceLen = (uLong)strlen(hello)+1;
    Byte *compr;
    uLong comprLen = 10*sizeof(int);
    uLong uncomprLen = comprLen;
    compr    = (Byte*)calloc((uInt)comprLen, 1);
    const char hello[] = "hello, hello!";
    stream.zalloc = (alloc_func)0;
    stream.zfree = (free_func)0;
    stream.opaque = (voidpf)0;
    deflateInit_(&stream, Z_DEFAULT_COMPRESSION,  zlibVersion(), sizeof(z_stream));
    deflateEnd(&stream);
    free(compr);
}

Errors

On error, deflateInit_() shall return one of the following error indicators:

Z_STREAM_ERROR | Invalid parameter.
Z_MEM_ERROR | Insufficient memory available.
Z_VERSION_ERROR | The version requested is not compatible with the library version, or the z_stream size differs from that used by the library.

In addition, the msg field of the stream may be set to an error message.

Feedback

For additional information or queries on this page send feedback


deflateInit2_

Name

deflateInit2_ — Initializes the compression system.

Library

Libz.lib

Synopsis

#include <zlib.h>

int deflateInit2_ (z_streamp strm, int level, int method, int windowBits, int memLevel, int strategy, char * version, int stream_size);

Return Value

On success, the deflateInit2_() function shall return Z_OK. Otherwise, deflateInit2_() shall return a value as described below to indicate the error.

Detailed Description

The deflateInit2_() function shall initialize the compression system. On entry, strm shall refer to a user supplied z_stream object (a z_stream_s structure). The following fields shall be set on entry:
zalloc | a pointer to an alloc_func function, used to allocate state information. If this is NULL, a default allocation function will be used.
zfree | a pointer to a free_func function, used to free memory allocated by the zalloc function. If this is NULL a default free function will be used.
opaque | If alloc_func is not NULL, opaque is a user supplied pointer to data that will be passed to the alloc_func and free_func functions.

If the version requested is not compatible with the version implemented, or if the size of the z_stream_s structure provided in stream_size does not match the size in the library implementation, deflateInit2_() shall fail, and return Z_VERSION_ERROR.

The level supplied shall be a value between 0 and 9, or the value Z_DEFAULT_COMPRESSION. A level of 1 requests the highest speed, while a level of 9 requests the highest compression. A level of 0 indicates that no compression should be used, and the output shall be the same as the input.

The method selects the compression algorithm to use. LSB conforming implementation shall support the Z_DEFLATED method, and may support other implementation defined methods.

The windowBits parameter shall be a base 2 logarithm of the window size to use, and shall be a value between 8 and 15. A smaller value will use less memory, but will result in a poorer compression ratio, while a higher value will give better compression but utilize more memory.

The memLevel parameter specifies how much memory to use for the internal state. The value of memLevel shall be between 1 and MAX_MEM_LEVEL. Smaller values use less memory but are slower, while higher values use more memory to gain compression speed.

The strategy parameter selects the compression strategy to use:
Z_DEFAULT_STRATEGY | use the system default compression strategy. Z_DEFAULT_STRATEGY is particularly appropriate for text data.
Z_FILTERED | use a compression strategy tuned for data consisting largely of small values with a fairly random distribution. Z_FILTERED uses more Huffman encoding and less string matching than Z_DEFAULT_STRATEGY.
Z_HUFFMAN_ONLY | force Huffman encoding only, with no string match.

The deflateInit2_() function is not in the source standard; it is only in the binary standard. Source applications should use the deflateInit2() macro.

Examples

To initialize the compression system with method=8 ,windowBits =15 ,memlevel=8:

include <stdio.h>
#include <zlib.h>
void DeflateInit2_( )
{
    z_stream stream;
    int level=Z_DEFAULT_COMPRESSION;
    const char hello[] = "hello, hello!";
    uLong sourceLen = (uLong)strlen(hello)+1;
    Byte *compr;
    uLong comprLen = 10*sizeof(int);
    uLong uncomprLen = comprLen;
    compr = (Byte*)calloc((uInt)comprLen, 1);
    stream.zalloc = (alloc_func)0;
    stream.zfree = (free_func)0;
    stream.opaque = (voidpf)0;

    deflateInit2_(&stream, level, 8, 15, 8, 0, zlibVersion(), sizeof(z_stream));
    deflateEnd(&stream);
    free(compr);
}

Errors

On error, deflateInit2_() shall return one of the following error indicators:
Z_STREAM_ERROR | Invalid parameter.
Z_MEM_ERROR | Insufficient memory available.
Z_VERSION_ERROR | The version requested is not compatible with the library version, or the z_stream size differs from that used by the library.

In addition, the msg field of the strm may be set to an error message.

Feedback

For additional information or queries on this page send feedback


deflateParams

Name

deflateParams — Alters the compression parameters for the compression stream object stream..

Library

Libz.lib

Synopsis

#include <zlib.h>

int deflateParams(z_streamp stream, int level, int strategy);

Return Value

On success, the deflateParams() function shall return Z_OK. Otherwise, deflateParams() shall return a value as described below to indicate the error.

Detailed Description

The deflateParams() function shall dynamically alter the compression parameters for the compression stream object stream. On entry, stream shall refer to a user supplied z_stream object (a z_stream_s structure), already initialized via a call to deflateInit_() or deflateInit2_().

The level supplied shall be a value between 0 and 9, or the value Z_DEFAULT_COMPRESSION. A level of 1 requests the highest speed, while a level of 9 requests the highest compression. A level of 0 indicates that no compression should be used, and the output shall be the same as the input. If the compression level is altered by deflateParams(), and some data has already been compressed with this stream (i.e. total_in is not zero), and the new level requires a different underlying compression method, then stream shall be flushed by a call to deflate().

The strategy parameter selects the compression strategy to use:
Z_DEFAULT_STRATEGY | use the system default compression strategy. Z_DEFAULT_STRATEGY is particularly appropriate for text data.
Z_FILTERED | use a compression strategy tuned for data consisting largely of small values with a fairly random distribution. Z_FILTERED uses more Huffman encoding and less string matching than Z_DEFAULT_STRATEGY.
Z_HUFFMAN_ONLY | force Huffman encoding only, with no string match.

Examples

To alter the compression parameters for the compression stream object stream to level=Z_NO_COMPRESSION and strategy = Z_DEFAULT_STRATEGY:

#include <stdio.h>
#include <zlib.h>
void Deflateparams( )
{
    z_stream c_stream; /* compression stream */
    Byte * compr;
    uLong comprLen = 20*sizeof(int);
    compr    = (Byte*)calloc((uInt)comprLen, 1);
    const char hello[] = "hello, hello!";
    uLong len = (uLong)strlen(hello)+1;

    c_stream.zalloc = (alloc_func)0;
    c_stream.zfree = (free_func)0;
    c_stream.opaque = (voidpf)0;

    deflateInit(&c_stream, Z_DEFAULT_COMPRESSION);
    c_stream.next_in  = (Bytef*)hello;
    c_stream.next_out = compr;
    deflateParams(&c_stream, Z_NO_COMPRESSION, Z_DEFAULT_STRATEGY);
    deflateEnd(&c_stream);
    free(compr);
}

Errors

On error, deflateParams() shall return one of the following error indicators:
Z_STREAM_ERROR | Invalid parameter.
Z_MEM_ERROR | Insufficient memory available.
Z_BUF_ERROR | Insufficient space in stream to flush the current output.

In addition, the msg field of the strm may be set to an error message.

Application Usage (Informative)

Applications should ensure that the stream is flushed, e.g. by a call to deflate(stream, Z_SYNC_FLUSH) before calling deflateParams(), or ensure that there is sufficient space in next_out (as identified by avail_out) to ensure that all pending output and all uncompressed input can be flushed in a single call to deflate().
Note

Rationale: Although the deflateParams() function should flush pending output and compress all pending input, the result is unspecified if there is insufficient space in the output buffer. Applications should only call deflateParams() when the stream is effectively empty (flushed).
The deflateParams() can be used to switch between compression and straight copy of the input data, or to switch to a different kind of input data requiring a different strategy.

Feedback

For additional information or queries on this page send feedback


deflateReset

Name

deflateReset — Resets all state associated with stream.

Library

Libz.lib

Synopsis

#include <zlib.h>

int deflateReset(z_streamp stream);

Return Value

On success, deflateReset() shall return Z_OK. Otherwise it shall return Z_STREAM_ERROR to indicate the error.

Detailed Description

The deflateReset() function shall reset all state associated with stream. All pending output shall be discarded, and the counts of processed bytes (total_in and total_out) shall be reset to zero.

Examples

To reset all the states associated with the stream:

#include <stdio.h>
#include <zlib.h>

void DeflateReset( )
{
    z_stream stream;
    int level = Z_DEFAULT_COMPRESSION ;
    uLong sourceLen = (uLong)strlen(hello)+1;
    Byte *compr, *uncompr;
    Bytef *dest = compr ;
    uLongf *destLen = &comprLen;
    const char hello[] = "hello, hello!";
    const Bytef *source = (const Bytef*)hello;
    uLong sourceLen = len;
    stream.next_in = (Bytef*)source;
    stream.avail_in = (uInt)sourceLen;
    uLong comprLen = 20*sizeof(int);
    uLong uncomprLen = comprLen;
    compr    = (Byte*)calloc((uInt)comprLen, 1);
    uncompr  = (Byte*)calloc((uInt)uncomprLen, 1);

    stream.zalloc = (alloc_func)0;
    stream.zfree = (free_func)0;
    stream.opaque = (voidpf)0;

    deflateInit(&stream, level);
    deflateReset(&stream);
    deflateEnd(&stream);
    free(compr);
    free(uncompr);
}

Errors

On error, deflateReset() shall return Z_STREAM_ERROR. The following conditions shall be treated as an error:

  • The state in stream is inconsistent or inappropriate.

  • stream is NULL

Feedback

For additional information or queries on this page send feedback


deflateSetDictionary

Name

deflateSetDictionary — Initializes the compression dictionary associated with stream using the dictlen bytes referenced by dictionary.

Library

Libz.lib

Synopsis

#include <zlib.h>
int deflateSetDictionary(z_streamp stream, const Bytef * dictionary, uInt dictlen);

Return Value

On success, deflateSetDictionary() shall return Z_OK. Otherwise it shall return Z_STREAM_ERROR to indicate an error.

Detailed Description

The deflateSetDictionary() function shall initialize the compression dictionary associated with stream using the dictlen bytes referenced by dictionary.

The implementation may silently use a subset of the provided dictionary if the dictionary cannot fit in the current window associated with stream (see deflateInit2_()). The application should ensure that the dictionary is sorted such that the most commonly used strings occur at the end of the dictionary.

If the dictionary is successfully set, the Adler32 checksum of the entire provided dictionary shall be stored in the adler member of stream. This value may be used by the decompression system to select the correct dictionary. The compression and decompression systems must use the same dictionary.

stream shall reference an initialized compression stream, with total_in zero (i.e. no data has been compressed since the stream was initialized).

Examples

To initialize the compression dictionary associated with stream using the dictlen bytes referenced by dictionary:

#include <stdio.h>
#include <zlib.h>

void DeflateSetDictionary( )
{
    Byte *compr, *uncompr;
    uLong comprLen = 20*sizeof(int);
    uLong uncomprLen = comprLen;
    const char dictionary[] = "hello";
    compr    = (Byte*)calloc((uInt)comprLen, 1);
    uncompr  = (Byte*)calloc((uInt)uncomprLen, 1);
    const char hello[] = "hello, hello!";
    compress(compr, &comprLen, (const Bytef*)hello, len);
    z_stream c_stream; /* compression stream */
    int err;
    c_stream.zalloc = (alloc_func)0;
    c_stream.zfree = (free_func)0;
    c_stream.opaque = (voidpf)0;

    err = deflateInit(&c_stream, Z_BEST_COMPRESSION);
    err = deflateSetDictionary(&c_stream, (const Bytef*)dictionary, sizeof(dictionary));
    dictId = c_stream.adler;
    c_stream.next_out = compr;
    c_stream.avail_out = (uInt)comprLen;

    c_stream.next_in = (Bytef*)hello;
    c_stream.avail_in = (uInt)strlen(hello)+1;

    err = deflate(&c_stream, Z_FINISH);
    if (err != Z_STREAM_END)
    printf("error");
    deflateEnd(&c_stream);
    free(compr);
    free(uncompr);
}

Errors

On error, deflateSetDictionary() shall return a value as described below:

Z_STREAM_ERROR

The state in stream is inconsistent, or stream was NULL.

Feedback

For additional information or queries on this page send feedback


get_crc_table

Name

get_crc_table — Generates tables for a byte-wise 32-bit CRC calculation based on the polynomial.

Library

Libz.lib

Synopsis

#include <zlib.h>
const uLongf * get_crc_table(void);

Return Value

The get_crc_table() function shall return a pointer to the first of a set of tables used internally to calculate CRC-32 values (see crc32()).

Detailed Description

Generate tables for a byte-wise 32-bit CRC calculation based on the polynomial: x32+x26+x23+x22+x16+x12+x11+x10+x8+x7+x5+x4+x2+x+1

In a multi-threaded application, get_crc_table() should be called by one thread to initialize the tables before any other thread calls any libz function.

Examples

To generate tables for a byte-wise 32-bit CRC calculation based on the polynomial:

#include <stdio.h>
#include <zlib.h>

void Get_crc_table( )

{
    const unsigned long* pcrc_32_tab;
    pcrc_32_tab = get_crc_table();
}

Errors

None defined.

Feedback

For additional information or queries on this page send feedback


gzclose

Name

gzclose — Closes the compressed file stream file.

Library

Libz.lib

Synopsis

#include <zlib.h>
int gzclose (gzFile file );

Return Value

On success, gzclose() shall return Z_OK. Otherwise, gzclose() shall return an error value as described below.

Detailed Description

The gzclose() function shall close the compressed file stream file. If file was open for writing, gzclose() shall first flush any pending output. Any state information allocated shall be freed.

Examples

To close the compressed file stream:

#include <stdio.h>
#include <zlib.h>

void Gzclose( )
{
    const char hello[] = "hello, hello!";
    int len = (int)strlen(hello)+1;
    gzFile file;
    const char * fname = TESTFILE;
    file = gzopen(fname, "wb");
    gzputc(file, 'h');
    err= gzclose(file);
}

Errors

On error, gzclose() may set the global variable errno to indicate the error. The gzclose() shall return a value other than Z_OK on error.

Z_STREAM_ERROR | file was NULL (or Z_NULL), or did not refer to an open compressed file stream.
Z_ERRNO | An error occurred in the underlying base libraries, and the application should check errno for further information.
Z_BUF_ERROR | no compression progress is possible during buffer flush (see deflate()).

Feedback

For additional information or queries on this page send feedback


gzdopen

Name

gzdopen — Attempts to associate the open file referenced by fd with a gzFile object.

Library

Libz.lib

Synopsis

#include <zlib.h>
gzFile gzdopen ( int fd, const char *mode );

Return Value

On success, gzdopen() shall return a gzFile object. On failure, gzdopen() shall return Z_NULL and may set errno accordingly.

Note

Note: At version 1.2.2, zlib does not set errno for several error conditions.
Applications may not be able to determine the cause of an error.

Detailed Description

The gzdopen() function shall attempt to associate the open file referenced by fd with a gzFile object. The mode argument is based on that of fopen(), but the mode parameter may also contain the following characters:

digit | set the compression level to digit. A low value (e.g. 1) means high speed, while a high value (e.g. 9) means high compression. A compression level of 0 (zero) means no compression. See defaultInit2_() for further details.
[fhR] | set the compression strategy to [fhR]. The letter f corresponds to filtered data, the letter h corresponds to Huffman only compression, and the letter R corresponds to Run Length Encoding. See defaultInit2_() for further details.

If fd refers to an uncompressed file, and mode refers to a read mode, gzdopen() shall attempt to open the file and return a gzFile object suitable for reading directly from the file without any decompression.

If mode is NULL, or if mode does not contain one of r, w, or a, gzdopen() shall return Z_NULL, and need not set any other error condition.

Examples

To associate the open file referenced by fd with a gzFile object:

#include <stdio.h>
#include <zlib.h>
void Gzdopen( )
{
   int len = (int)strlen(hello)+1;
   const char hello[] = "hello, hello!";
   gzFile file;
   const char * fname = TESTFILE ;

   FILE*  fp = fopen(fname, "rb");
   file = gzdopen(fileno(fp), "rb");
  gzclose(file);
}

Errors

On error, gzdopen() may set the global variable errno to indicate the error.

Feedback

For additional information or queries on this page send feedback


gzeof

Name

gzeof — Tests the compressed file stream file for end of file.

Library

Libz.lib

Synopsis

#include <zlib.h>
int gzeof (gzFile file );

Return Value

If file was open for reading and end of file has been reached, gzeof() shall return 1. Otherwise, gzeof() shall return 0.

Detailed Description

The gzeof() function shall test the compressed file stream file for end of file.

Examples

#include <stdio.h>
#include <zlib.h>

void Gzeof( )
{
    gzFile file;
    const char * fname = TESTFILE ;
    file = gzopen(fname, "wb");

    if (gzputs(file, "ello") != 4)
    {
       printf("error");
    }
    int x=gzeof(file);
    if(x!=0)
    {
    printf("error");
    }

    err=  gzclose(file);
}

Errors

None defined.

Feedback

For additional information or queries on this page send feedback


gzerror

Name

gzerror — Returns a string describing the last error occurred, associated with the open compressed file stream referred to by file.

Library

Libz.lib

Synopsis

#include <zlib.h>
const char * gzerror (gzFile file, int * errnum);

Return Value

The gzerror() function shall return a string that describes the last error associated with the given file compressed file stream. This string shall have the format "%s: %s", with the name of the file, followed by a colon, a space, and the description of the error. If the compressed file stream was opened by a call to gzdopen(), the format of the filename is unspecified.

Note

Rationale: Although in all current implementations of libz file descriptors are named "<fd:%d>", the code suggests that this is for debugging purposes only, and may change in a future release.

It is unspecified if the string returned is determined by the setting of the LC_MESSAGES category in the current locale.

Detailed Description

The gzerror() function shall return a string describing the last error to have occurred associated with the open compressed file stream referred to by file. It shall also set the location referenced by errnum to an integer value that further identifies the error.

Examples

#include <stdio.h>
#include <zlib.h>

void Gzerror( )
{
    int len = (int)strlen(hello)+1;
    gzFile file;
    const char * fname = TESTFILE ;
    file = gzopen(fname, "wb");
    gzputc(file, 'h');
    if (gzputs(file, "ello") != 5)
    {
        fprintf(stderr, "gzputs err: %s\n", gzerror(file, &err));
    }
    gzclose(file);
}

Errors

None defined.

Feedback

For additional information or queries on this page send feedback


gzflush

Name

gzflush — The gzflush() function shall flush pending output to the compressed file stream identified by file, which must be open for writing.

Library

Libz.lib

Synopsis

#include <zlib.h>
int gzflush(gzFile file, int flush);

Return Value

On success, gzflush() shall return the value Z_OK. Otherwise gzflush() shall return a value to indicate the error, and may set the error number associated with the compressed file stream file.

Note

Note: If flush is set to Z_FINISH and the flush operation is successful, gzflush() will return Z_OK, but the compressed file stream error value may be set to Z_STREAM_END.

Detailed Description

The gzflush() function shall flush pending output to the compressed file stream identified by file, which must be open for writing.

Examples

#include <stdio.h>
#include <zlib.h>

void Gzflush( )
{
    gzFile file;
    const char *s="ritesh";
    const char * fname = TESTFILE ;
    file = gzopen(fname, "wb");
    int l= gzflush(file,Z_FULL_FLUSH);
    int err=  gzclose(file);
}

Flush Operation

The parameter flush determines which compressed bits are added to the output file. If flush is Z_NO_FLUSH, gzflush() may return with some data pending output, and not yet written to the file.

If flush is Z_SYNC_FLUSH, gzflush() shall flush all pending output to file and align the output to a byte boundary. There may still be data pending compression that is not flushed.

If flush is Z_FULL_FLUSH, all output shall be flushed, as for Z_SYNC_FLUSH, and the compression state shall be reset. There may still be data pending compression that is not flushed.

Note

Note: Z_SYNC_FLUSH is intended to ensure that the compressed data contains all the data compressed so far, and allows a de-compressor to reconstruct all of the input data. Z_FULL_FLUSH allows decompression to restart from this point if the previous compressed data has been lost or damaged. Flushing is likely to degrade the performance of the compression system, and should only be used where necessary.

If flush is set to Z_FINISH, all pending uncompressed data shall be compressed and all output shall be flushed.

Errors

On error, gzflush() shall return an error value, and may set the error number associated with the stream identified by file to indicate the error. Applications may use gzerror() to access this error value.

Z_ERRNO | An underlying base library function has indicated an error. The global variable errno may be examined for further information.
Z_STREAM_ERROR | The stream is invalid, is not open for writing, or is in an invalid state.
Z_BUF_ERROR | no compression progress is possible (see deflate()).
Z_MEM_ERROR | Insufficient memory available to compress.

Feedback

For additional information or queries on this page send feedback


gzgetc

Name

gzgetc — Reads the next single character from the compressed file stream referenced by file.

Library

Libz.lib

Synopsis

#include <zlib.h>
 int gzgetc (gzFile file);

Return Value

On success, gzgetc() shall return the uncompressed character read, otherwise, on end of file or error, gzgetc() shall return -1.

Detailed Description

The gzgetc() function shall read the next single character from the compressed file stream referenced by file, which shall have been opened in a read mode (see gzopen() and gzdopen()).

Examples

#include <stdio.h>
#include <zlib.h>

void Gzgetc( )
{
    gzFile file;
    const char *s="ritesh";
    const char * fname = TESTFILE ;
    file = gzopen(fname, "rb");
    int l=  gzgetc(file);
    gzclose(file);
}

Errors

On end of file or error, gzgetc() shall return -1. Further information can be found by calling gzerror() with a pointer to the compressed file stream.

Feedback

For additional information or queries on this page send feedback


gzgets

Name

gzgets — Reads a string from a compressed file.

Library

Libz.lib

Synopsis

#include <zlib.h>
 char * gzgets (gzFile file, char * buf, int len);

Return Value

On success, gzgets() shall return a pointer to buf. Otherwise, gzgets() shall return Z_NULL. Applications may examine the cause using gzerror().

Detailed Description

The gzgets() function shall attempt to read data from the compressed file stream file, uncompressing it into buf until either len-1 bytes have been inserted into buf, or until a newline character has been uncompressed into buf. A null byte shall be appended to the uncompressed data. The file shall have been opened in for reading (see gzopen() and gzdopen()).

Examples

#include <stdio.h>
#include <zlib.h>
void Gzgets( )
{
    Byte *compr, *uncompr;
    uLong comprLen = 20*sizeof(int);
    uLong uncomprLen = comprLen;
    compr    = (Byte*)calloc((uInt)comprLen, 1);
    uncompr  = (Byte*)calloc((uInt)uncomprLen, 1);
    compress(compr, &comprLen, (const Bytef*)hello, len);

    file = gzopen(fname, "rb");
    strcpy((char*)uncompr, "garbage");

    gzread(file, uncompr, (unsigned)uncomprLen) != len
    gzseek(file, -8L, SEEK_CUR);
    gzgets(file, (char*)uncompr, (int)uncomprLen);
    int outlen = strlen((char*)uncompr);
    printf("length of the output is %d",outlen);
    gzclose(file);

    free(compr);
    free(uncompr);
}

Output

length of the output is 7.

Errors

On error, gzgets() shall return Z_NULL. The following conditions shall always be treated as an error:

file is NULL, or does not refer to a file open for reading;
buf is NULL;
len is less than or equal to zero.

Feedback

For additional information or queries on this page send feedback


gzopen

Name

gzopen — Opens the compressed file named by path.

Library

Libz.lib

Synopsis

#include <zlib.h>
 gzFile gzopen (const char *path , const char *mode );

Return Value

On success, gzopen() shall return a gzFile object (also known as a compressed file stream). On failure, gzopen() shall return Z_NULL and may set errno accordingly.

Note

Note: At version 1.2.2, zlib does not set errno for several error conditions. Applications may not be able to determine the cause of an error.

Detailed Description

The gzopen() function shall open the compressed file named by path. The mode argument is based on that of fopen(), but the mode parameter may also contain the following characters:

digit | Set the compression level to digit. A low value (e.g. 1) means high speed, while a high value (e.g. 9) means high compression. A compression level of 0 (zero) means no compression. See defaultInit2_() for further details.
[fhR] | Set the compression strategy to [fhR]. The letter f corresponds to filtered data, the letter h corresponds to Huffman only compression, and the letter R corresponds to Run Length Encoding. See defaultInit2_() for further details.

If path refers to an uncompressed file, and mode refers to a read mode, gzopen() shall attempt to open the file and return a gzFile object suitable for reading directly from the file without any decompression.

If path or mode is NULL, or if mode does not contain one of r, w, or a, gzopen() shall return Z_NULL, and need not set any other error condition.

The gzFile object is also referred to as a compressed file stream.

Examples

#include <stdio.h>
#include <zlib.h>

void Gzopen( )
{
    gzFile file;
    const char * fname = TESTFILE ;
    file = gzopen(fname, "rb");
    gzclose(file);
}

Errors

On error, gzopen() may set the global variable errno to indicate the error.

Feedback

For additional information or queries on this page send feedback


gzprintf

Name

gzprintf — Formats and compresses the data.

Library

Libz.lib

Synopsis

#include <zlib.h>
int gzprintf (gzFile file, const char * fmt, ...);

Return Value

The gzprintf() function shall return the number of uncompressed bytes actually written, or a value less than or equal to 0 in the event of an error.

Detailed Description

The gzprintf() function shall format data as for fprintf(), and write the resulting string to the compressed file stream file.

Examples

#include <stdio.h>
#include <zlib.h>

void Gzprintf( )
{
    gzFile file;
    const char * fname = TESTFILE ;
    file = gzopen(fname, "wb");
    int outlen = gzprintf(file, ", %s!", "hello");
    printf("length of the output is %d",outlen);
    gzclose(file);
}

Output

Length of the output is 8.

Errors

If file is NULL, or refers to a compressed file stream that has not been opened for writing, gzprintf() shall return Z_STREAM_ERROR. Otherwise, errors are as for gzwrite().

Feedback

For additional information or queries on this page send feedback


gzputc

Name

gzputc — Writes character to a compressed file.

Library

Libz.lib

Synopsis

#include <zlib.h>
int gzputc (gzFile file, int c);

Return Value

On success, gzputc() shall return the value written, otherwise gzputc() shall return -1.

Detailed Description

The gzputc() function shall write the single character c, converted from integer to unsigned character, to the compressed file referenced by file, which shall have been opened in a write mode (see gzopen() and gzdopen()).

Examples

To write the character 'r' to a compressed file:

#include <stdio.h>
#include <zlib.h>

void Gzputc( )
{
     gzFile file;
     const char * fname = TESTFILE ;
     file = gzopen(fname, "wb");
     gzputc(file, 'r');
     gzclose(file);
}

Errors

On error, gzputc() shall return -1.

Feedback

For additional information or queries on this page send feedback


gzputs

Name

gzputs — Writes to a compressed file.

Library

Libz.lib

Synopsis

#include <zlib.h>
int gzputs (gzFile file, const char * s);

Return Value

On success, gzputs() shall return the number of uncompressed bytes actually written to file. On error gzputs() shall return a value less than or equal to 0. Applications may examine the cause using gzerror().

Detailed Description

The gzputs() function shall write the null terminated string s to the compressed file referenced by file, which shall have been opened in a write mode (see gzopen() and gzdopen()). The terminating null character shall not be written. The gzputs() function shall return the number of uncompressed bytes actually written.

Examples

To write the null terminated string s="ello" to the compressed file referenced by file:

#include <stdio.h>
#include <zlib.h>

void Gzputs( )
{
    gzFile file;
    const char * fname = TESTFILE ;
    file = gzopen(fname, "wb");
    int x = gzputs(file, "ello");
    printf("number of character written is %d",x);
    gzclose(file);

}

Output

Number of character written is 4.

Errors

On error, gzputs() shall set the error number associated with the stream identified by file to indicate the error. Applications should use gzerror() to access this error value. If file is NULL, gzputs() shall return Z_STREAM_ERR.

Z_ERRNO | An underlying base library function has indicated an error. The global variable errno may be examined for further information.
Z_STREAM_ERROR | The stream is invalid, is not open for writing, or is in an invalid state.
Z_BUF_ERROR | no compression progress is possible (see deflate()).
Z_MEM_ERROR | Insufficient memory available to compress.

Feedback

For additional information or queries on this page send feedback


gzread

Name

gzread — Reads from a compressed file.

Library

Libz.lib

Synopsis

#include <zlib.h>
int gzread (gzFile file, voidp buf, unsigned int len);

Return Value

On success, gzread() shall return the number of bytes decompressed into buf. If gzread() returns 0, either the end-of-file has been reached or an underlying read error has occurred. Applications should use gzerror() or gzeof() to determine which occurred. On other errors, gzread() shall return a value less than 0 and and applications may examine the cause using gzerror().

Detailed Description

The gzread() function shall read data from the compressed file referenced by file, which shall have been opened in a read mode (see gzopen() and gzdopen()). The gzread() function shall read data from file, and uncompress it into buf. At most, len bytes of uncompressed data shall be copied to buf. If the file is not compressed, gzread() shall simply copy data from file to buf without alteration.

Examples

To read from a compressed file:

#include <stdio.h>
#include <zlib.h>

void Gzread( )
{

    char * buf1 = (char*)malloc(1024);
    int len1;
    char  *file=FILETESTGZ;
    char *infile;
    gzFile in;
    infile = file;
    in = gzopen(infile, "rb");
    for (;;)
    {
        len1 = gzread(in, buf1, sizeof(buf1));
        if (len1 == 0) break;
    }
    free(buf1);
}

Errors

On error, gzread() shall set the error number associated with the stream identified by file to indicate the error. Applications should use gzerror() to access this error value.

Z_ERRNO | An underlying base library function has indicated an error. The global variable errno may be examined for further information.
Z_STREAM_END | End of file has been reached on input.
Z_DATA_ERROR | A CRC error occurred when reading data; the file is corrupt.
Z_STREAM_ERROR | The stream is invalid, or is in an invalid state.
Z_NEED_DICT | A dictionary is needed (see inflateSetDictionary()).
Z_MEM_ERROR | Insufficient memory available to decompress.

Feedback

For additional information or queries on this page send feedback


gzrewind

Name

gzrewind — Resets the file-position on a compressed file stream.

Library

Libz.lib

Synopsis

#include <zlib.h>
int gzrewind (gzFile file);

Return Value

On success, gzrewind() shall return 0. On error, gzrewind() shall return -1, and may set the error value for file accordingly.

Detailed Description

The gzrewind() function shall set the starting position for the next read on compressed file stream file to the beginning of file. file must be open for reading.

gzrewind() is equivalent to (int) gzseek (file, 0L, SEEK_SET).

Examples

To reset the file-position on a compressed file stream:

#include <stdio.h>
#include <zlib.h>
void Gzrewind( )
{
    int len = (int)strlen(hello)+1;
    gzFile file;
    const char * fname = TESTFILE;
    file = gzopen(fname, "rb");
    gzputc(file, 'h');
    gzrewind(file);
    gzclose(file);
}

Errors

On error, gzrewind() shall return -1, indicating that file is NULL, or does not represent an open compressed file stream, or represents a compressed file stream that is open for writing and is not currently at the beginning of file.

Feedback

For additional information or queries on this page send feedback


gzseek

Name

gzseek — Sets the file-position indicator for the compressed file stream file.

Library

Libz.lib

Synopsis

#include <zlib.h>
 z_off_t gzseek(gzFile file, z_off_t offset, int whence);

Return Value

On success, gzseek() shall return the resulting offset in the file expressed as a byte position in the uncompressed data stream. On error, gzseek() shall return -1, and may set the error value for file accordingly.

Detailed Description

The gzseek() function shall set the file-position indicator for the compressed file stream file. The file-position indicator controls where the next read or write operation on the compressed file stream shall take place. The offset indicates a byte offset in the uncompressed data. The whence parameter may be one of:

SEEK_SET | the offset is relative to the start of the uncompressed data.
SEEK_CUR | the offset is relative to the current positition in the uncompressed data.

Note

Note: The value SEEK_END need not be supported.

If the file is open for writing, the new offset must be greater than or equal to the current offset. In this case, gzseek() shall compress a sequence of null bytes to fill the gap from the previous offset to the new offset.

Examples

To set the file-position indicator for the compressed file stream file:

#include <stdio.h>
#include <zlib.h>

void Gzseek( )
{
    Byte *compr, *uncompr;
    uLong comprLen = 20*sizeof(int);
    uLong uncomprLen = comprLen;
    static const char* myVersion = ZLIB_VERSION;
    const char hello[] = "hello, hello!";
    compr    = (Byte*)calloc((uInt)comprLen, 1);
    uncompr  = (Byte*)calloc((uInt)uncomprLen, 1);
    compress(compr, &comprLen, (const Bytef*)hello, len);

    int len = (int)strlen(hello)+1;
    gzFile file;
    file = gzopen(TESTFILE, "wb");
    gzputc(file, 'h');
    gzputs(file, "ello");

    gzseek(file, 1L, SEEK_CUR); /* add one zero byte */
    free(compr);
    free(uncompr);
}

Errors

On error, gzseek() shall return -1. The following conditions shall always result in an error:

  • file is NULL

  • file does not represent an open compressed file stream.

  • file refers to a compressed file stream that is open for writing, and the newly computed offset is less than the current offset.

  • The newly computed offset is less than zero.

  • whence is not one of the supported values.

Application Usage (informative)

If file is open for reading, the implementation may still need to uncompress all of the data up to the new offset. As a result, gzseek() may be extremely slow in some circumstances.

Feedback

For additional information or queries on this page send feedback


gzsetparams

Name

gzsetparams — Sets the compression level and compression strategy on the compressed file stream referenced by file.

Library

Libz.lib

Synopsis

#include <zlib.h>

int gzsetparams (gzFile file, int level, int strategy);

Return Value

On success, the gzsetparams() function shall return Z_OK.

Detailed Description

The gzsetparams() function shall set the compression level and compression strategy on the compressed file stream referenced by file. The compressed file stream shall have been opened in a write mode. The level and strategy are as defined in deflateInit2_. If there is any data pending writing, it shall be flushed before the parameters are updated.

Examples

To set the compression level=Z_BEST_SPEED and compression strategy=Z_DEFAULT_STRATEGY on the compressed file stream referenced by file:

#include <stdio.h>
#include <zlib.h>

void Gzsetparams( )
{
    const char hello[] = "hello, hello!";
    int len = (int)strlen(hello)+1;
    gzFile file;
    const char * fname = TESTFILE;
    file = gzopen(fname, "wb");
    gzputc(file, 'h');
    int u = gzsetparams(file, Z_BEST_SPEED, Z_DEFAULT_STRATEGY);
    int err=  gzclose(file);
}

Errors

On error, gzsetparams() shall return one of the following error indications:

Z_STREAM_ERROR | Invalid parameter, or file not open for writing.
Z_BUF_ERROR | An internal inconsistency was detected while flushing the previous buffer.

Feedback

For additional information or queries on this page send feedback


gztell

Name

gztell — Returns the starting position for the next read or write operation on compressed file stream file.

Library

Libz.lib

Synopsis

#include <zlib.h>

z_off_t gztell(gzFile file );

Return Value

gztell() shall return the current offset in the file expressed as a byte position in the uncompressed data stream. On error, gztell() shall return -1, and may set the error value for file accordingly.

Detailed Description

The gztell() function shall return the starting position for the next read or write operation on compressed file stream file. This position represents the number of bytes from the beginning of file in the uncompressed data.

gztell() is equivalent to gzseek(file, 0L, SEEK_SET).

Examples

To return the starting position for the next read or write operation on compressed file stream file:

#include <stdio.h>
#include <zlib.h>

void Gztell( )
{
    Byte *compr, *uncompr;
    uLong comprLen = 20*sizeof(int);
    uLong uncomprLen = comprLen;
    const char hello[] = "hello, hello!";
    int len = (int)strlen(hello)+1;
    gzFile file;
    z_off_t pos;
    static const char* myVersion = ZLIB_VERSION;
    compr    = (Byte*)calloc((uInt)comprLen, 1);
    uncompr  = (Byte*)calloc((uInt)uncomprLen, 1);
    compress(compr, &comprLen, (const Bytef*)hello, len);
    file = gzopen(fname, "rb");
    strcpy((char*)uncompr, "garbage");

    gzread(file, uncompr, (unsigned)uncomprLen);
    pos = gzseek(file, -8L, SEEK_CUR);
    if (pos != 6 || gztell(file) != pos)
    {
    printf("error");
    }
    gzclose(file);
    free(compr);
    free(uncompr);
  }

Errors

On error, gztell() shall return -1, indicating that file is NULL, or does not represent an open compressed file stream.

Feedback

For additional information or queries on this page send feedback


gzwrite

Name

gzwrite — Writes data to the compressed file referenced by file, opened in a write mode.

Library

Libz.lib

Synopsis

#include <zlib.h>
int gzwrite (gzFile file, voidpc buf, unsigned int len);

Return Value

On success, gzwrite() shall return the number of uncompressed bytes actually written to file. On error gzwrite() shall return a value less than or equal to 0. Applications may examine the cause using gzerror().

Detailed Description

The gzwrite() function shall write data to the compressed file referenced by file, which shall have been opened in a write mode (see gzopen() and gzdopen()). On entry, buf shall point to a buffer containing lenbytes of uncompressed data. The gzwrite() function shall compress this data and write it to file. The gzwrite() function shall return the number of uncompressed bytes actually written.

Examples

To write data to the compressed file referenced by file, which shall have been opened in a write mode:

#include <stdio.h>
#include <zlib.h>
void Gzwrite( )
  {

    gzFile file;
    uInt size ,len;
    const char *s="ritesh";
    len=strlen(s);
    const char * fname = TESTFILE ;
    file = gzopen(fname, "wb");
    size = gzwrite(file, (char*)s, (unsigned)strlen(s));
    printf("size is %d",size);
    gzclose(file);
  }

Output

Size is 6.

Errors

On error, gzwrite() shall set the error number associated with the stream identified by file to indicate the error. Applications should use gzerror() to access this error value.

Z_ERRNO | An underlying base library function has indicated an error. The global variable errno may be examined for further information.
Z_STREAM_ERROR | The stream is invalid, is not open for writing, or is in an invalid state.
Z_BUF_ERROR | no compression progress is possible (see deflate()).
Z_MEM_ERROR | Insufficient memory available to compress.

Feedback

For additional information or queries on this page send feedback


inflate

Name

inflate — Attempts to decompress data until either the input buffer is empty or the output buffer is full.

Library

Libz.lib

Synopsis

#include <zlib.h>
int inflate(z_streamp stream, int flush);

Return Value

On success, inflate() shall return Z_OK if decompression progress has been made, or Z_STREAM_END if all of the input data has been decompressed and there was sufficient space in the output buffer to store the uncompressed result. On error, inflate() shall return a value to indicate the error.

Note

Note: If inflate() returns Z_OK and has set avail_out to zero, the function should be called again with the same value for flush, and with updated next_out and avail_out until inflate() returns with either Z_OK or Z_STREAM_END and a non-zero avail_out.

On success, inflate() shall set the adler to the Adler-32 checksum of the output produced so far (i.e. total_out bytes).

Detailed Description

The inflate() function shall attempt to decompress data until either the input buffer is empty or the output buffer is full. The stream references a z_stream structure. Before the first call to inflate(), this structure should have been initialized by a call to inflateInit2_().

Note

Note: inflateInit2_() is only in the binary standard; source level applications should initialize stream via a call to inflateInit() or inflateInit2().

In addition, the stream input and output buffers should have been initialized as follows:
next_in | should point to the data to be decompressed.
avail_in | should contain the number of bytes of data in the buffer referenced by next_in.
next_out | should point to a buffer where decompressed data may be placed.
avail_out | should contain the size in bytes of the buffer referenced by next_out.

The inflate() function shall perform one or both of the following actions:

  1. Decompress input data from next_in and update next_in, avail_in and total_in to reflect the data that has been decompressed.

  2. Fill the output buffer referenced by next_out, and update next_out, avail_out, and total_out to reflect the decompressed data that has been placed there. If flush is not Z_NO_FLUSH, and avail_out indicates that there is still space in output buffer, this action shall always occur (see below for further details).

The inflate() function shall return when either avail_in reaches zero (indicating that all the input data has been compressed), or avail_out reaches zero (indicating that the output buffer is full).

On success, the inflate() function shall set the adler field of the stream to the Adler-32 checksum of all the input data compressed so far (represented by total_in).

Examples

To decompress data until either the input buffer is empty or the output buffer is full:

#include <stdio.h>
#include <zlib.h>
void Inflate( )
  {
    Byte *compr, *uncompr;
    uLong comprLen = 20*sizeof(int);
    uLong uncomprLen = comprLen;
    compr    = (Byte*)calloc((uInt)comprLen, 1);
    uncompr  = (Byte*)calloc((uInt)uncomprLen, 1);
    z_stream d_stream; /* decompression stream */
    strcpy((char*)uncompr, "garbage");

    d_stream.zalloc = (alloc_func)0;
    d_stream.zfree = (free_func)0;
    d_stream.opaque = (voidpf)0;
    d_stream.next_in  = compr;
    d_stream.avail_in = 0;
    d_stream.next_out = uncompr;
    err = inflateInit(&d_stream);

    while (d_stream.total_out < uncomprLen && d_stream.total_in < comprLen)
    {
        d_stream.avail_in = d_stream.avail_out = 1; /* force small buffers */
        err = inflate(&d_stream, Z_NO_FLUSH);
        if (err == Z_STREAM_END) break;
    }
    //inflate() should normally be called until it returns Z_STREAM_END
    inflateEnd(&d_stream);
    free(compr);
    free(uncompr);
}

Flush Operation

The parameter flush determines when uncompressed bytes are added to the output buffer in next_out. If flush is Z_NO_FLUSH, inflate() may return with some data pending output, and not yet added to the output buffer.

If flush is Z_SYNC_FLUSH, inflate() shall flush all pending output to next_out, and update next_out and avail_out accordingly.

If flush is set to Z_BLOCK, inflate() shall stop adding data to the output buffer if and when the next compressed block boundary is reached.

If flush is set to Z_FINISH, all of the compressed input shall be decompressed and added to the output. If there is insufficient output space (i.e. the compressed input data uncompresses to more than avail_out bytes), then inflate() shall fail and return Z_BUF_ERROR.

Errors

On error, inflate() shall return a value as described below, and may set the msg field of stream to point to a string describing the error:

Z_BUF_ERROR | No progress is possible; either avail_in or avail_out was zero.
Z_MEM_ERROR | Insufficient memory.
Z_STREAM_ERROR | The state (as represented in stream) is inconsistent, or stream was NULL.
Z_NEED_DICT | A preset dictionary is required. The adler field shall be set to the Adler-32 checksum of the dictionary chosen by the compressor.

Feedback

For additional information or queries on this page send feedback


inflateEnd

Name

inflateEnd — Frees all allocated state information referenced by stream..

Library

Libz.lib

Synopsis

#include <zlib.h>
int inflateEnd(z_streamp stream);

Return Value

On success, inflateEnd() shall return Z_OK. Otherwise it shall return Z_STREAM_ERROR to indicate the error.

Detailed Description

The inflateEnd() function shall free all allocated state information referenced by stream. All pending output is discarded, and unprocessed input is ignored.

Examples

To free all the allocated state information referenced by stream:

#include <stdio.h>
#include <zlib.h>

void Inflateend( )
{
    const char hello[] = "hello, hello!";
    Byte *compr, *uncompr;
    uLong comprLen = 20*sizeof(int);
    uLong uncomprLen = comprLen;
    compr    = (Byte*)calloc((uInt)comprLen, 1);
    uncompr  = (Byte*)calloc((uInt)uncomprLen, 1);
    compress(compr, &comprLen, (const Bytef*)hello, len);
    uLong len = (uLong)strlen(hello)+1;
    z_stream d_stream; // decompression stream

    compress(compr, &comprLen, (const Bytef*)hello, len);
    strcpy((char*)uncompr, "garbage");

    d_stream.zalloc = (alloc_func)0;
    d_stream.zfree = (free_func)0;
    d_stream.opaque = (voidpf)0;
    d_stream.next_in  = compr;
    d_stream.avail_in = 0;
    d_stream.next_out = uncompr;
    err = inflateInit(&d_stream);

    while (d_stream.total_out < uncomprLen && d_stream.total_in < comprLen)
    {
        d_stream.avail_in = d_stream.avail_out = 1; // force small buffers
        err = inflate(&d_stream, Z_NO_FLUSH);
        if (err == Z_STREAM_END) break;
    }
    inflateEnd(&d_stream);
    free(compr);
    free(uncompr);
}

Errors

On error, inflateEnd() shall return Z_STREAM_ERROR. The following conditions shall be treated as an error:

  • The state in stream is inconsistent.

  • stream is NULL.

  • The zfree function pointer is NULL.

Feedback

For additional information or queries on this page send feedback


inflateInit_

Name

inflateInit_ — Initializes the decompression system.

Library

Libz.lib

Synopsis

#include <zlib.h>

int inflateInit_(z_streamp stream, const char * version, int stream_size);

Return Value

On success, the inflateInit_() function shall return Z_OK. Otherwise, inflateInit_() shall return a value as described below to indicate the error.

Detailed Description

The inflateInit_() function shall initialize the decompression system. On entry, stream shall refer to a user supplied z_stream object (a z_stream_s structure). The following fields shall be set on entry:

zalloc | a pointer to an alloc_func function, used to allocate state information. If this is NULL, a default allocation function will be used.
zfree | a pointer to a free_func function, used to free memory allocated by the zalloc function. If this is NULL a default free function will be used.
opaque | If alloc_func is not NULL, opaque is a user supplied pointer to data that will be passed to the alloc_func and free_func functions.

If the version requested is not compatible with the version implemented, or if the size of the z_stream_s structure provided in stream_size does not match the size in the library implementation, inflateInit_() shall fail, and return Z_VERSION_ERROR.

The inflateInit_() function is not in the source standard; it is only in the binary standard. Source applications should use the inflateInit() macro.

The inflateInit_() shall be equivalent to inflateInit2_(strm, DEF_WBITS, version, stream_size);

Examples

To initialize the decompression system:

#include <stdio.h>
#include <zlib.h>
void InflateInit_( )
{
    z_stream d_stream;
    const char * version;
    d_stream.zalloc = (alloc_func)0;
    d_stream.zfree = (free_func)0;
    d_stream.opaque = (voidpf)0;
    const char hello[] = "hello, hello!";
    Byte *compr, *uncompr;
    uLong comprLen = 20*sizeof(int);
    uLong uncomprLen = comprLen;
    compr    = (Byte*)calloc((uInt)comprLen, 1);
    uncompr  = (Byte*)calloc((uInt)uncomprLen, 1);
    uLong len = (uLong)strlen(hello)+1;
    compress(compr, &comprLen, (const Bytef*)hello, len);
    d_stream.next_in  = compr;
    d_stream.avail_in = 0;
    d_stream.next_out = uncompr;
    version=zlibVersion();
    int ret = inflateInit_(&d_stream,(char*)version, sizeof(d_stream));
    inflateEnd(&d_stream);
    free(compr);
    free(uncompr);
}

Errors

On error, inflateInit_() shall return one of the following error indicators:

Z_STREAM_ERROR | Invalid parameter.
Z_MEM_ERROR | Insufficient memory available.
Z_VERSION_ERROR | The version requested is not compatible with the library version, or the z_stream size differs from that used by the library.

In addition, the msg field of the strm may be set to an error message.

Feedback

For additional information or queries on this page send feedback


inflateInit2_

Name

inflateInit2_ — Initializes the decompression system.

Library

Libz.lib

Synopsis

#include <zlib.h>
int inflateInit2_ (z_streamp strm, int windowBits, char * version,int stream_size);

Return Value

On success, the inflateInit2_() function shall return Z_OK. Otherwise, inflateInit2_() shall return a value as described below to indicate the error.

Detailed Description

The inflateInit2_() function shall initialize the decompression system. On entry, strm shall refer to a user supplied z_stream object (a z_stream_s structure). The following fields shall be set on entry:

zalloc | a pointer to an alloc_func function, used to allocate state information. If this is NULL, a default allocation function will be used.
zfree | a pointer to a free_func function, used to free memory allocated by the zalloc function. If this is NULL a default free function will be used.
opaque | If alloc_func is not NULL, opaque is a user supplied pointer to data that will be passed to the alloc_func and free_func functions.

If the version requested is not compatible with the version implemented, or if the size of the z_stream_s structure provided in stream_size does not match the size in the library implementation, inflateInit2_() shall fail, and return Z_VERSION_ERROR.

The windowBits parameter shall be a base 2 logarithm of the maximum window size to use, and shall be a value between 8 and 15. If the input data was compressed with a larger window size, subsequent attempts to decompress this data will fail with Z_DATA_ERROR, rather than try to allocate a larger window.

The inflateInit2_() function is not in the source standard; it is only in the binary standard. Source applications should use the inflateInit2() macro.

Examples

To initialize the decompression system with windowBits=15:

#include <stdio.h>
#include <zlib.h>

void InflateInit2_( )
{
    z_stream d_stream; // decompression stream
    const char * version;
    d_stream.zalloc = (alloc_func)0;
    d_stream.zfree = (free_func)0;
    d_stream.opaque = (voidpf)0;
    version = zlibVersion();
    int ret =  inflateInit2_(&d_stream,15,version, sizeof(d_stream));
    inflateEnd(&d_stream);
}

Errors

On error, inflateInit2_() shall return one of the following error indicators:

Z_STREAM_ERROR | Invalid parameter.
Z_MEM_ERROR | Insufficient memory available.
Z_VERSION_ERROR | The version requested is not compatible with the library version, or the z_stream size differs from that used by the library.

In addition, the msg field of the strm may be set to an error message.

Feedback

For additional information or queries on this page send feedback


inflateReset

Name

inflateReset — Resets all state associated with stream..

Library

Libz.lib

Synopsis

#include <zlib.h>
int inflateReset(z_streamp stream);

Return Value

On success, inflateReset() shall return Z_OK. Otherwise it shall return Z_STREAM_ERROR to indicate the error.

Detailed Description

The inflateReset() function shall reset all state associated with stream. All pending output shall be discarded, and the counts of processed bytes (total_in and total_out) shall be reset to zero.

Examples

To reset all the states associated with stream:

#include <stdio.h>
#include <zlib.h>

void InflateReset( )
{
    z_stream d_stream; /* decompression stream */
    const char * version;
    d_stream.zalloc = (alloc_func)0;
    d_stream.zfree = (free_func)0;
    d_stream.opaque = (voidpf)0;
    uLong len = (uLong)strlen(hello)+1;
    Byte *compr, *uncompr;
    uLong comprLen = 20*sizeof(int);
    uLong uncomprLen = comprLen;
    compr    = (Byte*)calloc((uInt)comprLen, 1);
    uncompr  = (Byte*)calloc((uInt)uncomprLen, 1);
    compress(compr, &comprLen, (const Bytef*)hello, len);
    d_stream.next_in  = compr;
    d_stream.avail_in = 0;
    d_stream.next_out = uncompr;
    version=zlibVersion();
    inflateInit_(&d_stream,(char*)version, sizeof(d_stream));
    inflateReset(&d_stream);
    inflateEnd(&d_stream);
}

Errors

On error, inflateReset() shall return Z_STREAM_ERROR. The following conditions shall be treated as an error:

  • The state in stream is inconsistent or inappropriate.

  • stream is NULL.

Feedback

For additional information or queries on this page send feedback


inflateSetDictionary

Name

inflateSetDictionary — Initializes the decompression dictionary.

Library

Libz.lib

Synopsis

#include <zlib.h>

int inflateSetDictionary(z_streamp stream, const Bytef * dictionary, uInt dictlen);

Return Value

On success, inflateSetDictionary() shall return Z_OK. Otherwise it shall return a value as indicated below.

Detailed Description

The inflateSetDictionary() function shall initialize the decompression dictionary associated with stream using the dictlen bytes referenced by dictionary.

The inflateSetDictionary() function should be called immediately after a call to inflate() has failed with return value Z_NEED_DICT. The dictionary must have the same Adler-32 checksum as the dictionary used for the compression (see deflateSetDictionary()).

stream shall reference an initialized decompression stream, with total_in zero (i.e. no data has been decompressed since the stream was initialized).

Examples

To initialize the decompression dictionary:

#include <stdio.h>
#include <zlib.h>

void InflateSetDictionary( )
{
    Byte *compr, *uncompr;
    uLong comprLen = 100*sizeof(int);
    uLong uncomprLen = comprLen;
    compr    = (Byte*)calloc((uInt)comprLen, 1);
    uncompr  = (Byte*)calloc((uInt)uncomprLen, 1);
    compress(compr, &comprLen, (const Bytef*)hello, len);
    const char dictionary[] = "hello";
    z_stream d_stream; /* decompression stream */
    strcpy((char*)uncompr, "garbage");

    d_stream.zalloc = (alloc_func)0;
    d_stream.zfree = (free_func)0;
    d_stream.opaque = (voidpf)0;
    d_stream.next_in  = compr;
    d_stream.avail_in = (uInt)comprLen;
    inflateInit(&d_stream);
    d_stream.next_out = uncompr;
    d_stream.avail_out = (uInt)uncomprLen;

    for (;;)
       {
        err = inflate(&d_stream, Z_NO_FLUSH);
        if (err == Z_STREAM_END) break;
        if (err == Z_NEED_DICT)
          {
            if (d_stream.adler != dictId)
            {
                fprintf(stderr, "unexpected dictionary");
                exit(1);
            }
            inflateSetDictionary(&d_stream, (const Bytef*)dictionary,
                                       sizeof(dictionary));
          }
      }
    inflateEnd(&d_stream);
    free(compr);
    free(uncompr);
}

Errors

On error, inflateSetDictionary() shall return a value as described below:

Z_STREAM_ERROR | The state in stream is inconsistent, or stream was NULL.
Z_DATA_ERROR | The Adler-32 checksum of the supplied dictionary does not match that used for the compression.

Application Usage (informative)

The application should provide a dictionary consisting of strings {{{ed note: do we really mean "strings"? Null terminated?}}} that are likely to be encountered in the data to be compressed. The application should ensure that the dictionary is sorted such that the most commonly used strings occur at the end of the dictionary.

The use of a dictionary is optional; however if the data to be compressed is relatively short and has a predictable structure, the use of a dictionary can substantially improve the compression ratio.

Feedback

For additional information or queries on this page send feedback


inflateSync

Name

inflateSync — Advances compression stream to next sync point.

Library

Libz.lib

Synopsis

#include <zlib.h>

int inflateSync(z_streamp stream);

Return Value

On success, inflateSync() shall return Z_OK, and update the next_in,, avail_in, and, total_in fields of stream to reflect the number of bytes of compressed data that have been skipped. Otherwise, inflateSync() shall return a value as described below to indicate the error.

Detailed Description

The inflateSync() function shall advance through the compressed data in stream, skipping any invalid compressed data, until the next full flush point is reached, or all input is exhausted. See the description for deflate() with flush level Z_FULL_FLUSH. No output is placed in next_out.

Examples

To advance the compression stream to next sync point:

#include <stdio.h>
#include <zlib.h>

void inflateSync( )
{
    z_stream d_stream; /* decompression stream */
    uLong len = (uLong)strlen(hello)+1;
    const char hello[] = "hello, hello!";
    Byte *compr, *uncompr;
    uLong comprLen = 20*sizeof(int);
    uLong uncomprLen = comprLen;
    compr    = (Byte*)calloc((uInt)comprLen, 1);
    uncompr  = (Byte*)calloc((uInt)uncomprLen, 1);
    uLong len = (uLong)strlen(hello)+1;
    compress(compr, &comprLen, (const Bytef*)hello, len);
    deflateInit(&c_stream, Z_DEFAULT_COMPRESSION);

    c_stream.next_in  = (Bytef*)hello;
    c_stream.next_out = compr;
    c_stream.avail_in = 3;
    c_stream.avail_out = (uInt)*comprLen;
    err = deflate(&c_stream, Z_FULL_FLUSH);
    int h=inflateSyncPoint(&c_stream);
    compr[3]++; /* force an error in first compressed block */
    c_stream.avail_in = len - 3;

    deflate(&c_stream, Z_FINISH);
    deflateEnd(&c_stream);
    strcpy((char*)uncompr, "garbage");
    d_stream.zalloc = (alloc_func)0;
    d_stream.zfree = (free_func)0;
    d_stream.opaque = (voidpf)0;
    d_stream.next_in  = compr;
    d_stream.avail_in = 2; /* just read the zlib header */
    inflateInit(&d_stream);
    d_stream.next_out = uncompr;
    d_stream.avail_out = (uInt)uncomprLen;
    inflate(&d_stream, Z_NO_FLUSH);
    d_stream.avail_in = (uInt)comprLen-2;   /* read all compressed data */
    err = inflateSync(&d_stream);           /* but skip the damaged part */
    inflate(&d_stream, Z_FINISH);
    inflateEnd(&d_stream);
    free(compr);
    free(uncompr);
}

Errors

On error, inflateSync() shall return a value as described below:

Z_STREAM_ERROR | The state (as represented in stream) is inconsistent, or stream was NULL.
Z_BUF_ERROR | There is no data available to skip over.
Z_DATA_ERROR | No sync point was found.

Feedback

For additional information or queries on this page send feedback


inflateSyncPoint

Name

inflateSyncPoint — Tests for synchronization point.

Library

Libz.lib

Synopsis

#include <zlib.h>
int inflateSyncPoint(z_streamp stream);

Return Value

If the compressed data in stream is at a synchronization point (see deflate() with a flush level of Z_SYNC_FLUSH or Z_FULL_FLUSH), inflateSyncPoint() shall return a non-zero value, other than Z_STREAM_ERROR. Otherwise, if the stream is valid, inflateSyncPoint() shall return 0. If stream is invalid, or in an invalid state, inflateSyncPoint() shall return Z_STREAM_ERROR to indicate the error.

Detailed Description

The inflateSyncPoint() function shall return a non-zero value if the compressed data stream referenced by stream is at a synchronization point.

Examples

To test for synchronization point:

#include <stdio.h>
#include <zlib.h>

void InflateSyncPoint( )
{
    uLong len = (uLong)strlen(hello)+1;
    Byte *compr, *uncompr;
    uLong comprLen = 20*sizeof(int);
    uLong uncomprLen = comprLen;
    compr    = (Byte*)calloc((uInt)comprLen, 1);
    uncompr  = (Byte*)calloc((uInt)uncomprLen, 1);
    z_stream stream;
    const char hello[] = "hello, hello!";
    stream.next_in = (Bytef*)hello;
    stream.avail_in = (uInt)sourceLen;
    stream.next_out = dest;
    stream.avail_out = (uInt)*destLen;
    stream.zalloc = (alloc_func)0;
    stream.zfree = (free_func)0;
    stream.opaque = (voidpf)0;
    err = deflateInit(&stream, level);
    err = deflate(&stream, Z_FINISH);
    *destLen = stream.total_out;
    int h=inflateSyncPoint(&stream);
    deflateEnd(&stream);
    free(compr);
    free(uncompr);
}

Output

A non-zero value of h , other than Z_STREAM_ERROR is indication of synchronization point.

Errors

On error, inflateSyncPoint() shall return a value as described below:

Z_STREAM_ERROR

The state (as represented in stream) is inconsistent, or stream was NULL.

Feedback

For additional information or queries on this page send feedback


uncompress

Name

uncompress — Un-compresses the data.

Library

Libz.lib

Synopsis

#include <zlib.h>
int uncompress(Bytef * dest, uLongf * destLen, const Bytef * source, uLong sourceLen);

Return Value

On success, uncompress() shall return Z_OK. Otherwise, uncompress() shall return a value to indicate the error.

Detailed Description

The uncompress() function shall attempt to uncompress sourceLen bytes of data in the buffer source, placing the result in the buffer dest.

On entry, destLen should point to a value describing the size of the dest buffer. The application should ensure that this value is large enough to hold the entire uncompressed data.

Note

Note: The LSB does not describe any mechanism by which a compressor can communicate the size required to the uncompressor.

On successful exit, the variable referenced by destLen shall be updated to hold the length of uncompressed data in dest.

Examples

To uncompress the compressed string in compr:

#include <stdio.h>
#include <zlib.h>

void Uncompress( )
{
    Byte *compr, *uncompr;
    uLong comprLen = 20*sizeof(int);
    uLong uncomprLen = comprLen;
    compr    = (Byte*)calloc((uInt)comprLen, 1);
    uncompr  = (Byte*)calloc((uInt)uncomprLen, 1);
    int err;
    const char hello[] = "hello, hello!";
    uLong len = (uLong)strlen(hello)+1;
    compress(compr, &comprLen, (const Bytef*)hello, len);
    strcpy((char*)uncompr, "garbage");
    uncompress(uncompr, &uncomprLen, compr, comprLen);
    free(compr);
    free(uncompr);
}

Output

uncompr contains uncompressed string.

Errors

On error, uncompress() shall return a value as described below:

Z_BUF_ERROR | The buffer dest was not large enough to hold the uncompressed data.
Z_MEM_ERROR | Insufficient memory.
Z_DATA_ERROR | The compressed data (referenced by source) was corrupted.

Feedback

For additional information or queries on this page send feedback


zError

Name

zError — Translates error number to string.

Library

Libz.lib

Synopsis

#include <zlib.h>
const char * zError(int err);

Return Value

The zError() function shall return a the string identifying the error associated with err, or NULL if err is not a valid error code.

It is unspecified if the string returned is determined by the setting of the LC_MESSAGES category in the current locale.

Detailed Description

The zError() function shall return the string identifying the error associated with err. This allows for conversion from error code to string for functions such as compress() and uncompress(), that do not always set the string version of an error.

Examples

To translate error number to string:

#include <stdio.h>
#include <zlib.h>

void Zerror( )
{
    const char * str = zError(1);
    printf("error message is %s",str);
}

Output

error message is "stream end".

Errors

None defined.

Feedback

For additional information or queries on this page send feedback


zlibVersion

Name

zlibVersion — Locates library version at run time.

Library

Libz.lib

Synopsis

#include <zlib.h>
 const char * zlibVersion (void);

Return Value

The zlibVersion() function shall return a the string identifying the version of the library currently implemented.

Detailed Description

The zlibVersion() function shall return the string identifying the interface version at the time the library was built.

Applications should compare the value returned from zlibVersion() with the macro constant ZLIB_VERSION for compatibility.

Examples

To discover library version at run time:

#include <stdio.h>
#include <zlib.h>

void Zlibversion( )
{
    printf("version is %s",  zlibVersion());
}

Output

version is 1.2.3

Errors

None defined.

Feedback

For additional information or queries on this page send feedback