POSIX Support

Basic Concepts

The OpenHarmony kernel uses the musl libc library and self-developed APIs and supports the Portable Operating System Interface (POSIX). You can develop components and applications working on the kernel based on the POSIX.

Development Guidelines

Available APIs

Table 1 Available APIs

Type

Header File

API

Description

process

#include <stdlib.h>

void abort(void);

Terminates the execution of a thread.

#include <assert.h>

void assert(scalar expression);

Terminates the thread if the assertion is false.

#include <pthread.h>

int pthread_cond_destroy(pthread_cond_t *cond);

Destroys a condition variable.

#include <pthread.h>

int pthread_cond_init(pthread_cond_t *restrict cond, const pthread_condattr_t *restrict attr);

Initializes a condition variable.

#include <pthread.h>

int pthread_cond_timedwait(pthread_cond_t *restrict cond, pthread_mutex_t *restrict mutex, const struct timespec *restrict abstime);

Waits for the condition.

#include <pthread.h>

int pthread_condattr_init(pthread_condattr_t *attr);

Initializes a condition variable attribute object.

#include <pthread.h>

int pthread_mutex_unlock(pthread_mutex_t *mutex);

Unlocks a mutex.

#include <pthread.h>

int pthread_create(pthread_t *thread, const pthread_attr_t *attr, void *(*start_routine)(void *), void *arg);

Creates a thread.

#include <pthread.h>

int pthread_join(pthread_t thread, void **retval);

Waits for a thread to terminate.

#include <pthread.h>

pthread_t pthread_self(void);

Obtains the ID of the current thread.

#include <pthread.h>

int pthread_getschedparam(pthread_t thread, int *policy, struct sched_param *param);

Obtains the scheduling policy and parameters of a thread.

#include <pthread.h>

int pthread_setschedparam(pthread_t thread, int policy, const struct sched_param *param);

Sets a scheduling policy and parameters for a thread.

#include <pthread.h>

int pthread_mutex_init(pthread_mutex_t *__restrict m, const pthread_mutexattr_t *__restrict a);

Initializes a mutex.

#include <pthread.h>

int pthread_mutex_lock(pthread_mutex_t *m);

Locks a mutex.

#include <pthread.h>

int pthread_mutex_trylock(pthread_mutex_t *m);

Attempts to lock a mutex.

#include <pthread.h>

int pthread_mutex_destroy(pthread_mutex_t *m);

Destroys a mutex.

#include <pthread.h>

int pthread_attr_init(pthread_attr_t *attr);

Initializes a thread attribute object.

#include <pthread.h>

int pthread_attr_destroy(pthread_attr_t *attr);

Destroys a thread attribute object.

#include <pthread.h>

int pthread_attr_getstacksize(const pthread_attr_t *attr, size_t *stacksize);

Obtains the stack size of a thread attribute object.

#include <pthread.h>

int pthread_attr_setstacksize(pthread_attr_t *attr, size_t stacksize);

Sets the stack size for a thread attribute object.

#include <pthread.h>

int pthread_attr_getschedparam(const pthread_attr_t *attr, struct sched_param *param);

Obtains scheduling parameter attributes of a thread attribute object.

#include <pthread.h>

int pthread_attr_setschedparam(pthread_attr_t *attr, const struct sched_param *param);

Sets scheduling parameter attributes for a thread attribute object.

#include <pthread.h>

int pthread_getname_np(pthread_t pthread, char *name, size_t len);

Obtains the name of a thread.

#include <pthread.h>

int pthread_setname_np(pthread_t pthread, const char *name);

Set the thread name.

#include <pthread.h>

int pthread_cond_broadcast(pthread_cond_t *c);

Unblocks the threads that are currently blocked on the condition variable.

#include <pthread.h>

int pthread_cond_signal(pthread_cond_t *c);

Unblocks a thread.

#include <pthread.h>

int pthread_cond_wait(pthread_cond_t *__restrict c, pthread_mutex_t *__restrict m);

Waits for the condition.

fs

#include <libgen.h>

char *dirname(char *path);

Obtains the folder name.

#include <dirent.h>

struct dirent *readdir(DIR *dirp);

Reads a directory.

#include <sys/stat.h>

int stat(const char *restrict path, struct stat *restrict buf);

Obtains file information.

#include <unistd.h>

int unlink(const char *pathname);

Deletes a file.

#include <fcntl.h

int open(const char *path, int oflags, ...);

Opens a file. If the file does not exist, create a file and open it.

#include <nistd.h>

int close(int fd);

Closes a file.

#include <stdio.h>

int rename(const char *oldpath, const char *newpath);

Rename the specified file.

#include <dirent.h>

DIR *opendir(const char *dirname);

Opens the specified directory.

#include <dirent.h>

int closedir(DIR *dir);

Closes the specified directory.

#include <sys/mount.h>

int mount(const char *source, const char *target, const char *filesystemtype, unsigned long mountflags, const void *data);

Mounts a file system.

#include <sys/mount.h>

int umount(const char *target);

Unmounts a file system.

#include <sys/mount.h>

int umount2(const char *target, int flag);

Unmounts a file system.

#include <sys/stat.h>

int fsync(int fd);

Synchronizes the files associated with a specified file descriptor to a storage device.

#include <sys/stat.h>

int mkdir(const char *pathname, mode_t mode);

Creates a directory.

#include <unistd.h>

int rmdir(const char *path);

Deletes a directory.

#include <sys/stat.h>

int fstat(int fd, struct stat *buf);

Obtains file status information.

#include <sys/statfs.h>

int statfs(const char *path, struct statfs *buf);

Obtains the file system information of a file in the specified path.

time

#include <sys/time.h>

int gettimeofday(struct timeval *tv, struct timezone *tz);

Obtains the time. Time zone is not supported. The return value of tz is empty.

#include <time.h>

struct tm *gmtime(const time_t *timep);

Converts a date and time to broken-down time or ASCII.

#include <time.h>

struct tm *localtime(const time_t *timep);

Obtains the time.

#include <time.h>

struct tm *localtime_r(const time_t *timep, struct tm *result);

Obtains the time.

#include <time.h>

time_t mktime(struct tm *tm);

Converts a date and time to broken-down time or ASCII.

#include <time.h>

size_t strftime(char *s, size_t max, const char *format,const struct tm *tm);

Formats the date and time string.

#include <time.h>

time_t time(time_t *tloc);

Obtains the calendar time.

#include <sys/times.h>

clock_t times(struct tms *buf);

Obtains the thread time.

#include <unistd.h>

int usleep(useconds_t usec);

Goes to hibernation (in μs).

#include <time.h>

int nanosleep(const struct timespec *tspec1, struct timespec *tspec2);

Pauses the calling thread till the specified time.

#include <time.h>

int clock_gettime(clockid_t id, struct timespec *tspec);

Obtains the clock time.

#include <time.h>

int timer_create(clockid_t id, struct sigevent *__restrict evp, timer_t *__restrict t);

Creates a timer for a thread.

#include <time.h>

int timer_delete(timer_t t);

Deletes a thread timer.

#include <time.h>

int timer_settime(timer_t t, int flags, const struct itimerspec *__restrict val, struct itimerspec *__restrict old);

Sets a timer for a thread.

#include <time.h>

time_t time (time_t *t);

Obtains the time.

#include <time.h>

char *strptime(const char *s, const char *format, struct tm *tm);

Converts the time string into the time tm structure.

util

#include <stdlib.h>

int atoi(const char *nptr);

Converts the character string into an integer (int).

#include <stdlib.h>

long atol(const char *nptr);

Converts the character string into an integer (long).

#include <stdlib.h>

long long atoll(const char *nptr);

Converts the character string into an integer (long long).

#include <ctype.h>

int isalnum(int c);

Checks for alphanumeric characters.

#include <ctype.h>

int isascii(int c);

Checks for ASCII.

#include <ctype.h>

int isdigit(int c);

Checks for numeric characters.

#include <ctype.h>

int islower(int c);

Checks for lowercase letters.

#include <ctype.h>

int isprint(int c);

Checks for printable characters, including spaces.

#include <ctype.h>

int isspace(int c);

Checks for a space.

#include <ctype.h>

int isupper(int c);

Checks for uppercase letters.

#include <ctype.h>

int isxdigit(int c);

Checks for hexadecimal digits.

#include <stdlib.h>

long int random (void);

Generates a random number.

#include <stdlib.h>

void srandom(unsigned int seed);

Initializes the random number generator.

#include <ctype.h>

int tolower(int c);

Converts letters to lowercase letters.

#include <ctype.h>

int toupper(int c);

Converts letters to uppercase letters.

#include <stdarg.h>

type va_arg(va_list ap, type);

Obtains the current parameter of a variable parameter, returns the value of the specified type, and moves the pointer to the next parameter.

#include <stdarg.h>

void va_copy(va_list dest, va_list src);

Copies parameters.

#include <stdarg.h>

void va_end(va_list ap);

Clears the va_list variable parameter list.

#include <stdarg.h>

void va_start(va_list ap, last);

Defines the start position of the variable-length parameter list.

#include <string.h>

char *strchr(const char *s, int c);

Locates the last occurrence of a character in a string.

#include <string.h>

int strcmp(const char *s1, const char *s2);

Compares strings.

#include <string.h>

size_t strcspn(const char *s, const char *reject);

Obtains the length of the initial segment of a string.

#include <string.h>

char *strdup(const char *s);

Copies a string to a new position.

#include <string.h>

size_t strlen(const char *s);

Calculates the length of a string.

#include <strings.h>

int strncasecmp(const char *s1, const char *s2, size_t n);

Compares fixed-length strings (case-insensitive).

#include <strings.h>

int strcasecmp(const char *s1, const char *s2);

Compares strings (case-insensitive).

#include <string.h>

int strncmp(const char *s1, const char *s2, size_t n);

Compares strings of the specified length.

#include <string.h>

char *strrchr(const char *s, int c);

Locates the last occurrence of a character in a string.

#include <string.h>

char *strstr(const char *haystack, const char *needle);

Searches for the specified string needle.

#include <stdlib.h>

long int strtol(const char *nptr, char **endptr, int base);

Converts a string into a long int value.

#include <stdlib.h>

unsigned long int strtoul(const char *nptr, char **endptr, int base);

Converts a string into an unsigned long int value.

#include <stdlib.h>

unsigned long long int strtoull(const char *nptr, char **endptr,int base);

Converts a string into an unsigned long long int value.

#include <regex.h>

int regcomp(regex_t *preg, const char *regex, int cflags);

Compiles a regular expression.

#include <regex.h>

int regexec(const regex_t *preg, const char *string, size_t nmatch,regmatch_t pmatch[], int eflags);

Matches a regular expression.

#include <regex.h>

void regfree(regex_t *preg);

Releases a regular expression.

#include <string.h>

char *strerror(int errnum);

Returns an error description string of the specified error code.

math

#include <stdlib.h>

int abs(int i);

Returns the absolute value.

#include <math.h>

double log(double x);

Returns the natural logarithm (base-e logarithm) of x.

#include <math.h>

double pow(double x, double y);

Returns x raised to the power of y.

#include <math.h>

double round(double x);

Rounds off the value from zero to the nearest integer.

#include <math.h>

double sqrt(double x);

Returns the square root of x.

IO

#include <stdio.h>

void clearerr(FILE *stream);

Clears the file end and error indication of a stream.

#include <stdio.h>

int fclose(FILE *stream);

Closes a file stream.

#include <stdio.h>

FILE *fdopen(int fd, const char *mode);

Opens a file stream by using a file descriptor.

#include <stdio.h>

int feof(FILE *stream);

Tests the end-of-file indicator for the specified stream.

#include <stdio.h>

int fflush(FILE *stream);

Refreshes a stream.

#include <stdio.h>

char *fgets(char *s, int size, FILE *stream);

Reads the next line of the stream.

#include <stdio.h>

int fileno(FILE *stream);

Returns the file descriptor of a stream.

#include <stdio.h>

FILE *fopen(const char *path, const char *mode);

Open a stream.

#include <stdio.h>

int fputs(const char *s, FILE *stream);

Writes a line to a specified stream.

#include <stdio.h>

size_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream);

Reads a stream.

#include <stdio.h>

int fseek(FILE *stream, long offset, int whence);

Sets the position of a stream pointer.

#include <stdio.h>

long ftell(FILE *stream);

Obtains the position of a stream pointer.

#include <stdio.h>

size_t fwrite(const void *ptr, size_t size, size_t nmemb,FILE *stream);

Writes data to a stream.

#include <stdio.h>

void perror(const char *s);

Prints system error information.

#include <stdio.h>

void rewind(FILE *stream);

Re-positions a stream.

#include <unistd.h>

ssize_t write(int fd, const void *buf, size_t size);

Writes data to a file.

#include <unistd.h>

ssize_t read(int fd, void *buf, size_t size);

Reads data from a file.

net

#include <sys/socket.h>

void freeaddrinfo(struct addrinfo *res);

Releases the dynamic memory allocated by calling getaddrinfo.

#include <sys/socket.h>

int getaddrinfo(const char *restrict nodename,const char *restrict servname,const struct addrinfo *restrict hints,struct addrinfo **restrict res);

Performs network address translation.

#include <sys/socket.h>

int getnameinfo(const struct sockaddr *restrict sa, socklen_t salen,char *restrict node, socklen_t nodelen, char *restrict service,socklen_t servicelen, int flags);

Performs address-to-name translation in a protocol-independent manner.

#include <net/if.h>

unsigned int if_nametoindex(const char *ifname);

Obtains the index based on the network interface name.

#include <arpa/inet.h>

in_addr_t inet_addr(const char *cp);

Converts the network host address from dotted decimal notation to binary format.

#include <arpa/inet.h>

char *inet_ntoa(struct in_addr in);

Converts the network host address from binary format to dotted decimal notation.

#include <arpa/inet.h>

const char *inet_ntop(int af, const void *src,char *dst, socklen_t size);

Performs network address translation.

#include <arpa/inet.h>

int inet_pton(int af, const char *src, void *dst);

Performs network address translation.

#include <sys/socket.h>

int listen(int sockfd, int backlog);

Listens for sockets.

#include <sys/socket.h>

ssize_t recvmsg(int sockfd, struct msghdr *msg, int flags);

Receives a message from a socket. Note that the IOV size can be 1 only, and the ancillary message is not supported.

#include <sys/socket.h>

ssize_t send(int sockfd, const void *buf, size_t len, int flags);

Sends messages from a socket.

#include <sys/socket.h>

ssize_t sendmsg(int sockfd, const struct msghdr *msg, int flags);

Sends messages from a socket. Ancillary messages are not supported.

#include <sys/socket.h>

ssize_t sendto(int sockfd, const void *buf, size_t len, int flags,const struct sockaddr *dest_addr, socklen_t addrlen);

Sends messages from a socket.

#include <sys/socket.h>

int setsockopt(int sockfd, int level, int optname,const void *optval, socklen_t optlen);

Sets the options associated with a socket.

mem

#include <string.h>

int memcmp(const void *s1, const void *s2, size_t n);

Compares memory areas.

#include <string.h>

void *memcpy(void *dest, const void *src, size_t n);

Copies memory content.

#include <string.h>

void *memset(void *s, int c, size_t n);

Initializes memory.

#include <stdlib.h>

void *realloc(void *ptr, size_t size);

Reallocates memory.

#include <stdlib.h>

void *malloc(size_t size);

Dynamically allocates memory blocks.

#include <stdlib.h>

void free(void *ptr);

Releases the memory space to which the PTR pointer points.

IPC

#include <semaphore.h>

int sem_timedwait(sem_t *sem, const struct timespec *abs_timeout);

Locks a semaphore for a specified period of time.

#include <semaphore.h>

int sem_destroy(sem_t *sem);

Destroys a specified anonymous semaphore.

#include <semaphore.h>

int sem_init(sem_t *sem, int pshared, unsigned int value);

Creates and initializes an anonymous semaphore.

#include <semaphore.h>

int sem_post(sem_t *sem);

Increments the semaphore count.

#include <semaphore.h>

int sem_wait(sem_t *sem);

Obtains the semaphore.

#include <mqueue.h>

mqd_t mq_open(const char *mqName, int openFlag, ...);

Opens an existing message queue with the specified name or creates a message queue.

#include <mqueue.h>

int mq_close(mqd_t personal);

Closes the message queue with the specified descriptor.

#include <mqueue.h>

int mq_unlink(const char *mqName);

Deletes a specified message queue.

#include <mqueue.h>

int mq_send(mqd_t personal, const char *msg, size_t msgLen, unsigned int msgPrio);

Puts a message with the specified content and length into a message queue with the specified descriptor.

#include <mqueue.h>

ssize_t mq_receive(mqd_t personal, char *msg, size_t msgLen, unsigned int *msgPrio);

Deletes the oldest message from the message queue with the specified descriptor and places it in the buffer pointed to by msg_ptr.

#include <mqueue.h>

int mq_timedsend(mqd_t personal, const char *msg, size_t msgLen, unsigned int msgPrio, const struct timespec *absTimeout)

Puts a message with the specified content and length into a message queue identified by the specified descriptor within specified time.

#include <mqueue.h>

ssize_t mq_timedreceive(mqd_t personal, char *msg, size_t msgLen, unsigned int *msgPrio, const struct timespec *absTimeout);

Obtains a message with the specified content and length from a message queue specified by the descriptor.

#include <mqueue.h>

int mq_setattr(mqd_t mqdes, const struct mq_attr *__restrict newattr, struct mq_attr *__restrict oldattr);

Sets the attributes of the message queue specified by the descriptor.

version

#include <libc.h>

const char *libc_get_version_string(void);

Obtains the libc version string.

#include <libc.h>

int libc_get_version(void);

Obtains the libc version.

Important Notes

Error codes

C Name

Value

Description

Description

ENOERR

0

Success

Successful

EPERM

1

Operation not permitted

The operation is not allowed.

ENOENT

2

No such file or directory

The file or directory does not exist.

ESRCH

3

No such process

There is no such process (not supported currently).

EINTR

4

Interrupted system call

The system call is interrupted.

EIO

5

I/O error

An I/O error occurs.

ENXIO

6

No such device or address

The device or address does not exist.

E2BIG

7

Arg list too long

The parameter list is too long.

ENOEXEC

8

Exec format error

The execution format is incorrect.

EBADF

9

Bad file number

The file descriptor is invalid.

ECHILD

10

No child processes

There is no child process (not supported currently).

EAGAIN

11

Try again

The resource is temporarily unavailable.

ENOMEM

12

Out of memory

The memory overflows.

EACCES

13

Permission denied

The permission is rejected.

EFAULT

14

Bad address

The address is incorrect.

ENOTBLK

15

Block device required

A block device is required.

EBUSY

16

Device or resource busy

The device or resource is engaged.

EEXIST

17

File exists

The file already exists.

EXDEV

18

Cross-device link

The cross-device link is invalid.

ENODEV

19

No such device

The device does not exist.

ENOTDIR

20

Not a directory

It is not a directory.

EISDIR

21

Is a directory

It is a directory.

EINVAL

22

Invalid argument

The parameter is invalid.

ENFILE*

23

File table overflow

The number of file systems opened exceeds the limit.

EMFILE

24

Too many open files

The number of files opened exceeds the limit.

EFBIG

27

File too large

The file is too large.

ENOSPC

28

No space left on device

There is no space on the device.

ESPIPE

29

Illegal seek

Illegal shift

EROFS

30

Read-only file system

The file system is read-only.

EMLINK

31

Too many links

There are too many links.

EDOM

33

Math argument out of domain

The value is out of range.

ERANGE

34

Math result not representable

The result is not representative.

EDEADLK

35

Resource deadlock would occur

Resource deadlock occurs.

ENAMETOOLONG

36

Filename too long

The file name is too long.

ENOLCK

37

No record locks available

There is no lock available.

ENOSYS

38

Function not implemented

The function is not implemented.

ENOTEMPTY

39

Directory not empty

The directory is not empty.

ELOOP

40

Too many symbolic links encountered

There are too many symbolic link layers.

ENOMSG

42

No message of desired type

There is no message of the expected type.

EIDRM

43

Identifier removed

The identifier is removed.

ELNRNG

48

Link number out of range

The number of links exceeds the limit.

EBADR

53

Invalid request descriptor

The requested descriptor is invalid.

EBADRQC

56

Invalid request code

The requested code is invalid.

ENOSTR

60

Device not a stream

The device is not a character stream.

ENODATA

61

No data available

No data is available.

ETIME

62

Timer expired

The timer has expired.

EPROTO

71

Protocol error

Protocol error.

EBADMSG

74

Not a data message

It is not a data message.

EOVERFLOW

75

Value too large for defined data type

The value is too large for the data type.

EMSGSIZE

90

Message too long

The message is too long.

Development Example

Demo:

Creates a thread, transfers the information in the parent thread to the child thread, and prints the transferred information and the thread ID in the child thread.

#include <stdio.h>
#include <pthread.h>

pthread_t ntid;

void *ThreadFn(void *arg)
{
    pthread_t tid;
    while(1) {
        tid = pthread_self();
        printf("\n++++++++++++++  %s  %s  tid = %d ++++++++++++++\n", (char*)arg, __FUNCTION__, tid);
    }
    return ((void *)0);
}

void DemoForTest()
{
    int err;
    char* str = "Hello world";
    err = pthread_create(&ntid, NULL, ThreadFn, (void*)str);
    if(err != 0) {
        printf("can't create thread\n");
    }
}

The execution result of DemoForTest is as follows:

++++++++++++++  Hello world  ThreadFn  tid = 48 ++++++++++++++

++++++++++++++  Hello world  ThreadFn  tid = 48 ++++++++++++++

++++++++++++++  Hello world  ThreadFn  tid = 48 ++++++++++++++