This commit is contained in:
2024-08-05 20:57:09 +08:00
commit 46d9ee7795
3020 changed files with 1725767 additions and 0 deletions

View File

@@ -0,0 +1,39 @@
menu "Interprocess Communication (IPC)"
config RT_USING_POSIX_PIPE
bool "Enable pipe and FIFO"
select RT_USING_POSIX_FS
select RT_USING_POSIX_DEVIO
select RT_USING_POSIX_POLL
select RT_USING_RESOURCE_ID
default n
config RT_USING_POSIX_PIPE_SIZE
int "Set pipe buffer size"
depends on RT_USING_POSIX_PIPE
default 512
# We have't implement of 'systemv ipc', so hide it firstly.
#
# config RT_USING_POSIX_IPC_SYSTEM_V
# bool "Enable System V IPC"
# default n
# help
# System V supplies an alternative form of interprocess communication consisting of thress
# features: shared memory, message, and semaphores.
config RT_USING_POSIX_MESSAGE_QUEUE
bool "Enable posix message queue <mqueue.h>"
select RT_USING_POSIX_CLOCK
select RT_USING_MESSAGEQUEUE_PRIORITY
select RT_USING_DFS_MQUEUE
default n
config RT_USING_POSIX_MESSAGE_SEMAPHORE
bool "Enable posix semaphore <semaphore.h>"
select RT_USING_POSIX_CLOCK
default n
comment "Socket is in the 'Network' category"
endmenu

View File

@@ -0,0 +1,20 @@
from building import *
cwd = GetCurrentDir()
src = []
inc = [cwd]
# We have't implement of 'systemv ipc', so hide it firstly.
# if GetDepend('RT_USING_POSIX_IPC_SYSTEM_V'):
# src += Glob('system-v/*.c')
# inc += [cwd + '/system-v']
if GetDepend(['RT_USING_POSIX_MESSAGE_QUEUE', 'RT_USING_DFS_MQUEUE']):
src += ['mqueue.c']
if GetDepend('RT_USING_POSIX_MESSAGE_SEMAPHORE'):
src += ['semaphore.c']
group = DefineGroup('POSIX', src, depend = [''], CPPPATH = inc)
Return('group')

View File

@@ -0,0 +1,441 @@
/*
* Copyright (c) 2006-2023, RT-Thread Development Team
*
* SPDX-License-Identifier: Apache-2.0
*
* Change Logs:
* Date Author Notes
* 2023-07-20 zmq810150896 first version
* 2024-04-30 TroyMitchell Add comments for all functions
*/
#include <dfs_file.h>
#include <unistd.h>
#include "mqueue.h"
/**
* @brief Sets the attributes of a message queue.
* @param id Identifier of the message queue.
* @param mqstat Pointer to a struct mq_attr containing the new attributes (ignored).
* @param omqstat Pointer to a struct mq_attr where the old attributes will be stored.
* @return Upon successful completion, returns 0; otherwise, returns -1 and sets errno to indicate the error.
*
* @note This function sets the attributes of the message queue specified by id.
* The new attributes are provided in the mqstat parameter, but this implementation ignores it.
* Instead, the function calls mq_getattr() to retrieve the current attributes of the message queue
* and stores them in the struct mq_attr pointed to by omqstat.
* If mqstat is RT_NULL, the function behaves as a query and retrieves the attributes without setting new values.
* If an error occurs during the operation, errno is set to indicate the error, and the function returns -1.
*/
int mq_setattr(mqd_t id,
const struct mq_attr *mqstat,
struct mq_attr *omqstat)
{
if (mqstat == RT_NULL)
return mq_getattr(id, omqstat);
else
rt_set_errno(-RT_ERROR);
return -1;
}
RTM_EXPORT(mq_setattr);
/**
* @brief Gets the attributes of a message queue.
* @param id Identifier of the message queue.
* @param mqstat Pointer to a struct mq_attr where the attributes will be stored.
* @return Upon successful completion, returns 0; otherwise, returns -1 and sets errno to indicate the error.
*
* @note This function retrieves the attributes of the message queue specified by id.
* The attributes include the maximum number of messages that can be queued (mq_maxmsg),
* the maximum size of each message (mq_msgsize), the number of messages currently in the queue (mq_curmsgs),
* and the flags associated with the queue (mq_flags).
* The attributes are stored in the struct mq_attr pointed to by mqstat.
* If the message queue identified by id does not exist or if mqstat is a null pointer, errno is set to EBADF,
* indicating a bad file descriptor, and the function returns -1.
* Otherwise, the function retrieves the attributes from the message queue and stores them in mqstat, returning 0 to indicate success.
*/
int mq_getattr(mqd_t id, struct mq_attr *mqstat)
{
rt_mq_t mq;
struct mqueue_file *mq_file;
mq_file = fd_get(id)->vnode->data;
mq = (rt_mq_t)mq_file->data;
if ((mq == RT_NULL) || mqstat == RT_NULL)
{
rt_set_errno(EBADF);
return -1;
}
mqstat->mq_maxmsg = mq->max_msgs;
mqstat->mq_msgsize = mq->msg_size;
mqstat->mq_curmsgs = 0;
mqstat->mq_flags = 0;
return 0;
}
RTM_EXPORT(mq_getattr);
/**
* @brief Opens or creates a message queue.
* @param name Name of the message queue.
* @param oflag Flags indicating the access mode and creation options (O_CREAT, O_EXCL, etc.).
* @param ... Additional arguments for creation options (mode, attr) (ignored).
* @return Upon successful completion, returns a message queue descriptor (mqd_t);
* otherwise, returns (mqd_t)(-1) and sets errno to indicate the error.
*
* @note This function opens or creates a message queue specified by name with the specified flags.
* If the name starts with '/', the leading '/' is ignored.
* The function then checks the length of the name and verifies if it exceeds the maximum allowed length.
* If the name is too long, errno is set to ENAMETOOLONG, indicating a name too long error.
* Next, the function attempts to find the message queue file corresponding to the name.
* If the file exists and O_CREAT and O_EXCL flags are both set, indicating exclusive creation,
* errno is set to EEXIST, indicating that the file already exists.
* If the file does not exist and O_CREAT flag is set, the function checks the message queue attributes.
* If the maximum number of messages (mq_maxmsg) in the attributes is less than or equal to 0,
* errno is set to EINVAL, indicating an invalid argument for the maximum number of messages.
* If the file does not exist and O_CREAT flag is not set, errno is set to ENOENT, indicating no such file or directory.
* If the message queue needs to be created (O_CREAT flag set), a new mqueue_file structure is allocated and initialized
* with the specified message queue attributes, and it is inserted into the message queue filesystem.
* Finally, the function constructs the path to the message queue device file, opens it with the specified flags,
* and returns the file descriptor as a message queue descriptor (mqd_t).
*/
mqd_t mq_open(const char *name, int oflag, ...)
{
int mq_fd;
va_list arg;
mode_t mode;
struct mq_attr *attr = RT_NULL;
va_start(arg, oflag);
mode = (mode_t)va_arg(arg, unsigned int);
mode = (mode_t)mode; /* self-assignment avoids compiler optimization */
attr = (struct mq_attr *)va_arg(arg, struct mq_attr *);
attr = (struct mq_attr *)attr; /* self-assignment avoids compiler optimization */
va_end(arg);
if(*name == '/')
{
name++;
}
int len = rt_strlen(name);
if (len > RT_NAME_MAX)
{
rt_set_errno(ENAMETOOLONG);
return (mqd_t)(-1);
}
rt_size_t size;
struct mqueue_file *mq_file;
mq_file = dfs_mqueue_lookup(name, &size);
if(mq_file != RT_NULL)
{
if (oflag & O_CREAT && oflag & O_EXCL)
{
rt_set_errno(EEXIST);
return (mqd_t)(-1);
}
}
else if (oflag & O_CREAT)
{
if (attr->mq_maxmsg <= 0)
{
rt_set_errno(EINVAL);
return (mqd_t)(-1);
}
struct mqueue_file *mq_file;
mq_file = (struct mqueue_file *) rt_malloc (sizeof(struct mqueue_file));
if (mq_file == RT_NULL)
{
rt_set_errno(ENFILE);
return (mqd_t)(-1);
}
mq_file->msg_size = attr->mq_msgsize;
mq_file->max_msgs = attr->mq_maxmsg;
mq_file->data = RT_NULL;
strncpy(mq_file->name, name, RT_NAME_MAX);
dfs_mqueue_insert_after(&(mq_file->list));
}
else
{
rt_set_errno(ENOENT);
return (mqd_t)(-1);
}
const char* mq_path = "/dev/mqueue/";
char mq_name[RT_NAME_MAX + 12] = {0};
rt_sprintf(mq_name, "%s%s", mq_path, name);
mq_fd = open(mq_name, oflag);
return (mqd_t)(mq_fd);
}
RTM_EXPORT(mq_open);
/**
* @brief Receives a message from a message queue.
* @param id Message queue descriptor.
* @param msg_ptr Pointer to the buffer where the received message will be stored.
* @param msg_len Maximum size of the message buffer.
* @param msg_prio Pointer to an unsigned integer where the priority of the received message will be stored (ignored).
* @return Upon successful completion, returns the number of bytes received;
* otherwise, returns -1 and sets errno to indicate the error.
*
* @note This function receives a message from the message queue identified by id.
* The received message is stored in the buffer pointed to by msg_ptr, with a maximum size of msg_len bytes.
* The priority of the received message is stored in the unsigned integer pointed to by msg_prio (ignored in this implementation).
* If either the message queue identified by id or the msg_ptr buffer is a null pointer, errno is set to EINVAL,
* indicating an invalid argument, and the function returns -1.
* The function then attempts to receive a message from the message queue using the rt_mq_recv_prio() function
* with an infinite timeout and uninterruptible mode.
* If a message is successfully received, the function returns the number of bytes received.
* If an error occurs during the receive operation, errno is set to EBADF, indicating a bad file descriptor,
* and the function returns -1.
*/
ssize_t mq_receive(mqd_t id, char *msg_ptr, size_t msg_len, unsigned *msg_prio)
{
rt_mq_t mq;
rt_err_t result;
struct mqueue_file *mq_file;
mq_file = fd_get(id)->vnode->data;
mq = (rt_mq_t)mq_file->data;
if ((mq == RT_NULL) || (msg_ptr == RT_NULL))
{
rt_set_errno(EINVAL);
return -1;
}
result = rt_mq_recv_prio(mq, msg_ptr, msg_len, (rt_int32_t *)msg_prio, RT_WAITING_FOREVER, RT_UNINTERRUPTIBLE);
if (result >= 0)
return result;
rt_set_errno(EBADF);
return -1;
}
RTM_EXPORT(mq_receive);
/**
* @brief Sends a message to a message queue.
* @param id Message queue descriptor.
* @param msg_ptr Pointer to the buffer containing the message to be sent.
* @param msg_len Size of the message to be sent.
* @param msg_prio Priority of the message to be sent.
* @return Upon successful completion, returns 0;
* otherwise, returns -1 and sets errno to indicate the error.
*
* @note This function sends a message to the message queue identified by id.
* The message to be sent is contained in the buffer pointed to by msg_ptr, with a size of msg_len bytes.
* The priority of the message is specified by the msg_prio parameter.
* If either the message queue identified by id or the msg_ptr buffer is a null pointer, errno is set to EINVAL,
* indicating an invalid argument, and the function returns -1.
* The function then attempts to send the message to the message queue using the rt_mq_send_wait_prio() function
* with zero timeout and uninterruptible mode.
* If the message is successfully sent, the function returns 0.
* If an error occurs during the send operation, errno is set to EBADF, indicating a bad file descriptor,
* and the function returns -1.
*/
int mq_send(mqd_t id, const char *msg_ptr, size_t msg_len, unsigned msg_prio)
{
rt_mq_t mq;
rt_err_t result;
struct mqueue_file *mq_file;
mq_file = fd_get(id)->vnode->data;
mq = (rt_mq_t)mq_file->data;
if ((mq == RT_NULL) || (msg_ptr == RT_NULL))
{
rt_set_errno(EINVAL);
return -1;
}
result = rt_mq_send_wait_prio(mq, (void *)msg_ptr, msg_len, msg_prio, 0, RT_UNINTERRUPTIBLE);
if (result == RT_EOK)
return 0;
rt_set_errno(EBADF);
return -1;
}
RTM_EXPORT(mq_send);
/**
* @brief Receives a message from a message queue with a timeout.
* @param id Message queue descriptor.
* @param msg_ptr Pointer to the buffer where the received message will be stored.
* @param msg_len Maximum size of the message buffer.
* @param msg_prio Pointer to an unsigned integer where the priority of the received message will be stored.
* @param abs_timeout Pointer to a struct timespec specifying the absolute timeout value (ignored if null).
* @return Upon successful completion, returns the number of bytes received;
* otherwise, returns -1 and sets errno to indicate the error.
*
* @note This function receives a message from the message queue identified by id with a specified timeout.
* The received message is stored in the buffer pointed to by msg_ptr, with a maximum size of msg_len bytes.
* The priority of the received message is stored in the unsigned integer pointed to by msg_prio.
* If either the message queue identified by id or the msg_ptr buffer is a null pointer, errno is set to EINVAL,
* indicating an invalid argument, and the function returns -1.
* The function then converts the absolute timeout value specified by abs_timeout to system ticks,
* or sets the timeout to RT_WAITING_FOREVER if abs_timeout is null.
* It attempts to receive a message from the message queue using the rt_mq_recv_prio() function
* with the specified timeout and uninterruptible mode.
* If a message is successfully received, the function returns the number of bytes received.
* If the receive operation times out, errno is set to ETIMEDOUT, indicating a timeout error.
* If the received message is too large for the specified buffer, errno is set to EMSGSIZE, indicating a message too large error.
* If an unknown error occurs during the receive operation, errno is set to EBADMSG, indicating a bad message error,
* and the function returns -1.
*/
ssize_t mq_timedreceive(mqd_t id,
char *msg_ptr,
size_t msg_len,
unsigned *msg_prio,
const struct timespec *abs_timeout)
{
rt_mq_t mq;
rt_err_t result;
int tick = 0;
struct mqueue_file *mq_file;
mq_file = fd_get(id)->vnode->data;
mq = (rt_mq_t)mq_file->data;
/* parameters check */
if ((mq == RT_NULL) || (msg_ptr == RT_NULL))
{
rt_set_errno(EINVAL);
return -1;
}
if (abs_timeout != RT_NULL)
tick = rt_timespec_to_tick(abs_timeout);
else
tick = RT_WAITING_FOREVER;
result = rt_mq_recv_prio(mq, msg_ptr, msg_len, (rt_int32_t *)msg_prio, tick, RT_UNINTERRUPTIBLE);
if (result >= 0)
return result;
if (result == -RT_ETIMEOUT)
rt_set_errno(ETIMEDOUT);
else if (result == -RT_ERROR)
rt_set_errno(EMSGSIZE);
else
rt_set_errno(EBADMSG);
return -1;
}
RTM_EXPORT(mq_timedreceive);
/**
* @brief Sends a message to a message queue with a timeout (not supported).
* @param id Message queue descriptor.
* @param msg_ptr Pointer to the buffer containing the message to be sent.
* @param msg_len Size of the message to be sent.
* @param msg_prio Priority of the message to be sent.
* @param abs_timeout Pointer to a struct timespec specifying the absolute timeout value (ignored).
* @return Upon successful completion, returns 0;
* otherwise, returns -1 and sets errno to indicate the error.
*
* @note This function attempts to send a message to the message queue identified by id with a specified timeout,
* but timed send is not supported in the RT-Thread environment.
* Therefore, the function simply delegates the message sending operation to the mq_send() function,
* which does not involve a timeout.
* The abs_timeout parameter is ignored, and the message is sent without waiting for a timeout to occur.
* The function returns the result of the mq_send() function, which indicates whether the message was successfully sent.
*/
int mq_timedsend(mqd_t id,
const char *msg_ptr,
size_t msg_len,
unsigned msg_prio,
const struct timespec *abs_timeout)
{
/* RT-Thread does not support timed send */
return mq_send(id, msg_ptr, msg_len, msg_prio);
}
RTM_EXPORT(mq_timedsend);
/**
* @brief Registers for notification when a message is available in a message queue (not supported).
* @param id Message queue descriptor.
* @param notification Pointer to a struct sigevent specifying the notification settings (ignored).
* @return Upon successful completion, returns 0;
* otherwise, returns -1 and sets errno to indicate the error.
*
* @note This function attempts to register for notification when a message is available in the message queue identified by id.
* However, message queue notification is not supported in the RT-Thread environment.
* Therefore, this function simply sets errno to EBADF, indicating a bad file descriptor,
* and returns -1 to indicate that the operation is not supported.
*/
int mq_notify(mqd_t id, const struct sigevent *notification)
{
rt_mq_t mq;
struct mqueue_file *mq_file;
mq_file = fd_get(id)->vnode->data;
mq = (rt_mq_t)mq_file->data;
if (mq == RT_NULL)
{
rt_set_errno(EBADF);
return -1;
}
rt_set_errno(-RT_ERROR);
return -1;
}
RTM_EXPORT(mq_notify);
/**
* @brief Closes a message queue descriptor.
* @param id Message queue descriptor to be closed.
* @return Upon successful completion, returns 0;
* otherwise, returns -1 and sets errno to indicate the error.
*
* @note This function closes the message queue descriptor specified by id.
* It delegates the closing operation to the close() function, which closes the file descriptor associated with the message queue.
* If the close operation is successful, the function returns 0.
* If an error occurs during the close operation, errno is set to indicate the error, and the function returns -1.
*/
int mq_close(mqd_t id)
{
return close(id);
}
RTM_EXPORT(mq_close);
/**
* @brief This function will remove a message queue (REALTIME).
*
* @note The mq_unlink() function shall remove the message queue named by the string name.
* If one or more processes have the message queue open when mq_unlink() is called,
* destruction of the message queue shall be postponed until all references to the message queue have been closed.
* However, the mq_unlink() call need not block until all references have been closed; it may return immediately.
*
* After a successful call to mq_unlink(), reuse of the name shall subsequently cause mq_open() to behave as if
* no message queue of this name exists (that is, mq_open() will fail if O_CREAT is not set,
* or will create a new message queue if O_CREAT is set).
*
* @param name is the name of the message queue.
*
* @return Upon successful completion, the function shall return a value of zero.
* Otherwise, the named message queue shall be unchanged by this function call,
* and the function shall return a value of -1 and set errno to indicate the error.
*
* @warning This function can ONLY be called in the thread context, you can use RT_DEBUG_IN_THREAD_CONTEXT to
* check the context.
* The mq_unlink() function shall fail if:
* [EACCES]
* Permission is denied to unlink the named message queue.
* [EINTR]
* The call to mq_unlink() blocked waiting for all references to the named message queue to be closed and a signal interrupted the call.
* [ENOENT]
* The named message queue does not exist.
* The mq_unlink() function may fail if:
* [ENAMETOOLONG]
* The length of the name argument exceeds {_POSIX_PATH_MAX} on systems that do not support the XSI option
* or exceeds {_XOPEN_PATH_MAX} on XSI systems,or has a pathname component that is longer than {_POSIX_NAME_MAX} on systems that do
* not support the XSI option or longer than {_XOPEN_NAME_MAX} on XSI systems.A call to mq_unlink() with a name argument that contains
* the same message queue name as was previously used in a successful mq_open() call shall not give an [ENAMETOOLONG] error.
*/
int mq_unlink(const char *name)
{
if(*name == '/')
{
name++;
}
const char *mq_path = "/dev/mqueue/";
char mq_name[RT_NAME_MAX + 12] = {0};
rt_sprintf(mq_name, "%s%s", mq_path, name);
return unlink(mq_name);
}
RTM_EXPORT(mq_unlink);

View File

@@ -0,0 +1,52 @@
/*
* Copyright (c) 2006-2021, RT-Thread Development Team
*
* SPDX-License-Identifier: Apache-2.0
*
* Change Logs:
* Date Author Notes
*/
#ifndef __MQUEUE_H__
#define __MQUEUE_H__
#include <rtthread.h>
#include <sys/signal.h>
#ifdef RT_USING_DFS_MQUEUE
#include "dfs_mqueue.h"
#endif
typedef int mqd_t;
struct mq_attr
{
long mq_flags; /* Message queue flags. */
long mq_maxmsg; /* Maximum number of messages. */
long mq_msgsize; /* Maximum message size. */
long mq_curmsgs; /* Number of messages currently queued. */
};
int mq_close(mqd_t mqdes);
int mq_getattr(mqd_t mqdes, struct mq_attr *mqstat);
int mq_notify(mqd_t mqdes, const struct sigevent *notification);
mqd_t mq_open(const char *name, int oflag, ...);
ssize_t mq_receive(mqd_t mqdes, char *msg_ptr, size_t msg_len, unsigned *msg_prio);
int mq_send(mqd_t mqdes, const char *msg_ptr, size_t msg_len, unsigned msg_prio);
int mq_setattr(mqd_t mqdes,
const struct mq_attr *mqstat,
struct mq_attr *omqstat);
ssize_t mq_timedreceive(mqd_t mqdes,
char *msg_ptr,
size_t msg_len,
unsigned *msg_prio,
const struct timespec *abs_timeout);
int mq_timedsend(mqd_t mqdes,
const char *msg_ptr,
size_t msg_len,
unsigned msg_prio,
const struct timespec *abs_timeout);
int mq_unlink(const char *name);
#endif

View File

@@ -0,0 +1,558 @@
/*
* Copyright (c) 2006-2021, RT-Thread Development Team
*
* SPDX-License-Identifier: Apache-2.0
*
* Change Logs:
* Date Author Notes
* 2010-10-26 Bernard the first version
*/
#include <rtthread.h>
#include <string.h>
#include <fcntl.h>
#include <sys/errno.h>
#include "semaphore.h"
static sem_t *posix_sem_list = RT_NULL;
static struct rt_semaphore posix_sem_lock;
/* initialize posix semaphore */
static int posix_sem_system_init(void)
{
rt_sem_init(&posix_sem_lock, "psem", 1, RT_IPC_FLAG_FIFO);
return 0;
}
INIT_COMPONENT_EXPORT(posix_sem_system_init);
/**
* @brief Inserts a semaphore into the linked list of semaphores.
* @param psem Pointer to the semaphore structure to be inserted.
*
* @note This function inserts the specified semaphore into a linked list of semaphores.
* The newly inserted semaphore becomes the head of the list.
* It updates the 'next' pointer of the semaphore structure to link it to the
* current head of the list and then sets the head of the list to point to the
* newly inserted semaphore.
*/
rt_inline void posix_sem_insert(sem_t *psem)
{
psem->next = posix_sem_list;
posix_sem_list = psem;
}
/**
* @brief Deletes a semaphore from the linked list of semaphores.
* @param psem Pointer to the semaphore structure to be deleted.
*
* @note This function deletes the specified semaphore from a linked list of semaphores.
* If the semaphore to be deleted is the head of the list, it updates the head of the list
* to point to the next semaphore. Otherwise, it traverses the list to find the semaphore
* to be deleted and updates the 'next' pointer of the preceding semaphore to skip over
* the semaphore to be deleted.
* After deleting the semaphore, it also deletes the underlying RT-Thread semaphore if it exists
* and frees the memory associated with the semaphore structure if it's not unnamed.
*/
static void posix_sem_delete(sem_t *psem)
{
sem_t *iter;
if (posix_sem_list == psem)
{
posix_sem_list = psem->next;
rt_sem_delete(psem->sem);
if(psem->unamed == 0)
rt_free(psem);
return;
}
for (iter = posix_sem_list; iter->next != RT_NULL; iter = iter->next)
{
if (iter->next == psem)
{
/* delete this mq */
if (psem->next != RT_NULL)
iter->next = psem->next;
else
iter->next = RT_NULL;
/* delete RT-Thread mqueue */
rt_sem_delete(psem->sem);
if(psem->unamed == 0)
rt_free(psem);
return ;
}
}
}
/**
* @brief Finds a semaphore by name in the linked list of semaphores.
* @param name Pointer to the name of the semaphore to be found.
* @return Pointer to the semaphore structure if found; otherwise, RT_NULL.
*
* @note This function searches for a semaphore with the specified name in the linked list of semaphores.
* It iterates through the list and compares the name of each semaphore with the given name.
* If a semaphore with a matching name is found, a pointer to its structure is returned.
* Otherwise, RT_NULL is returned to indicate that no semaphore with the given name was found.
*/
static sem_t *posix_sem_find(const char* name)
{
sem_t *iter;
rt_object_t object;
for (iter = posix_sem_list; iter != RT_NULL; iter = iter->next)
{
object = (rt_object_t)iter->sem;
if (strncmp(object->name, name, RT_NAME_MAX) == 0)
{
return iter;
}
}
return RT_NULL;
}
/**
* @brief Closes a POSIX semaphore.
* @param sem Pointer to the semaphore to be closed.
* @return Upon successful completion, returns 0; otherwise, returns -1 and sets errno to indicate the error.
*
* @note This function decreases the reference count of the specified semaphore.
* If the reference count reaches zero, the semaphore is removed from the list
* of POSIX semaphores if it was unlinked. The memory associated with the semaphore
* is not immediately freed; instead, it will be freed when the last reference to
* the semaphore is released.
*/
int sem_close(sem_t *sem)
{
if (sem == RT_NULL)
{
rt_set_errno(EINVAL);
return -1;
}
/* lock posix semaphore list */
rt_sem_take(&posix_sem_lock, RT_WAITING_FOREVER);
sem->refcount --;
if (sem->refcount == 0)
{
/* delete from posix semaphore list */
if (sem->unlinked)
posix_sem_delete(sem);
sem = RT_NULL;
}
rt_sem_release(&posix_sem_lock);
return 0;
}
RTM_EXPORT(sem_close);
/**
* @brief Destroys a POSIX semaphore.
* @param sem Pointer to the semaphore to be destroyed.
* @return Upon successful completion, returns 0; otherwise, returns -1 and sets errno to indicate the error.
*
* @note This function destroys an unnamed POSIX semaphore.
* It first checks if the semaphore pointer is valid and if the semaphore is unnamed.
* If the semaphore is still in use (i.e., there are threads waiting on it),
* the function returns with an error code (EBUSY) without destroying the semaphore.
* Otherwise, it removes the semaphore from the list of POSIX semaphores and frees
* the memory associated with the semaphore structure.
*/
int sem_destroy(sem_t *sem)
{
if ((!sem) || !(sem->unamed))
{
rt_set_errno(EINVAL);
return -1;
}
/* lock posix semaphore list */
rt_sem_take(&posix_sem_lock, RT_WAITING_FOREVER);
if(rt_list_len(&sem->sem->parent.suspend_thread) != 0)
{
rt_sem_release(&posix_sem_lock);
rt_set_errno(EBUSY);
return -1;
}
/* destroy an unamed posix semaphore */
posix_sem_delete(sem);
rt_sem_release(&posix_sem_lock);
return 0;
}
RTM_EXPORT(sem_destroy);
/**
* @brief Unlinks a named POSIX semaphore.
* @param name Pointer to the name of the semaphore to be unlinked.
* @return Upon successful completion, returns 0; otherwise, returns -1 and sets errno to indicate the error.
*
* @note This function unlinks a named POSIX semaphore identified by the given name.
* It first searches for the semaphore with the specified name in the list of
* POSIX semaphores. If the semaphore is found, it marks the semaphore as unlinked.
* If the reference count of the semaphore is zero, indicating that no threads are
* currently using the semaphore, it removes the semaphore from the list and frees
* the associated memory. Otherwise, the semaphore is not immediately removed; it
* will be removed when its reference count reaches zero.
*/
int sem_unlink(const char *name)
{
sem_t *psem;
/* lock posix semaphore list */
rt_sem_take(&posix_sem_lock, RT_WAITING_FOREVER);
psem = posix_sem_find(name);
if (psem != RT_NULL)
{
psem->unlinked = 1;
if (psem->refcount == 0)
{
/* remove this semaphore */
posix_sem_delete(psem);
}
rt_sem_release(&posix_sem_lock);
return 0;
}
rt_sem_release(&posix_sem_lock);
/* no this entry */
rt_set_errno(ENOENT);
return -1;
}
RTM_EXPORT(sem_unlink);
/**
* @brief Retrieves the value of a POSIX semaphore.
* @param sem Pointer to the semaphore.
* @param sval Pointer to an integer where the semaphore value will be stored.
* @return Upon successful completion, returns 0; otherwise, returns -1 and sets errno to indicate the error.
*
* @note This function retrieves the current value of the specified POSIX semaphore.
* It copies the semaphore value into the memory location pointed to by sval.
* If either sem or sval is a null pointer, the function sets errno to EINVAL
* to indicate an invalid argument and returns -1.
*/
int sem_getvalue(sem_t *sem, int *sval)
{
if (!sem || !sval)
{
rt_set_errno(EINVAL);
return -1;
}
*sval = sem->sem->value;
return 0;
}
RTM_EXPORT(sem_getvalue);
/**
* @brief Initializes a POSIX semaphore.
* @param sem Pointer to the semaphore structure to be initialized.
* @param pshared Flag indicating whether the semaphore is to be shared between processes.
* @param value Initial value of the semaphore.
* @return Upon successful completion, returns 0; otherwise, returns -1 and sets errno to indicate the error.
*
* @note This function initializes a POSIX semaphore with the specified initial value.
* If sem is a null pointer, the function sets errno to EINVAL to indicate an invalid argument and returns -1.
* The pshared parameter is not used in this implementation, as all semaphores are created as local (unshared).
* The value parameter specifies the initial value of the semaphore.
* The semaphore is given a unique name using a static counter, and it is created using the RT-Thread semaphore
* creation function rt_sem_create(). If memory allocation fails during semaphore creation, errno is set to ENOMEM.
* After successful initialization, the semaphore structure is inserted into the linked list of POSIX semaphores.
*/
int sem_init(sem_t *sem, int pshared, unsigned int value)
{
char name[RT_NAME_MAX];
static rt_uint16_t psem_number = 0;
if (sem == RT_NULL)
{
rt_set_errno(EINVAL);
return -1;
}
rt_snprintf(name, sizeof(name), "psem%02d", psem_number++);
sem->sem = rt_sem_create(name, value, RT_IPC_FLAG_FIFO);
if (sem->sem == RT_NULL)
{
rt_set_errno(ENOMEM);
return -1;
}
/* initialize posix semaphore */
sem->refcount = 1;
sem->unlinked = 0;
sem->unamed = 1;
/* lock posix semaphore list */
rt_sem_take(&posix_sem_lock, RT_WAITING_FOREVER);
posix_sem_insert(sem);
rt_sem_release(&posix_sem_lock);
return 0;
}
RTM_EXPORT(sem_init);
/**
* @brief Opens or creates a POSIX semaphore.
* @param name Pointer to the name of the semaphore.
* @param oflag Bitwise OR of flags indicating the operation mode.
* @param ... Additional arguments (optional).
* @return Upon successful completion, returns a pointer to the semaphore;
* otherwise, returns RT_NULL and sets errno to indicate the error.
*
* @note This function opens or creates a POSIX semaphore specified by the name argument.
* If the oflag argument includes O_CREAT, the semaphore is created if it does not already exist.
* Additional arguments may include the mode (not used in this implementation) and the initial value of the semaphore.
* If the oflag argument includes O_EXCL along with O_CREAT, the function fails if the semaphore already exists.
* If memory allocation fails during semaphore creation, errno is set to ENFILE.
* After successful creation or opening, the semaphore's reference count is incremented, and it is inserted into
* the linked list of POSIX semaphores. If the semaphore already exists and is successfully opened, its reference
* count is incremented. If the semaphore cannot be opened or created for any reason, errno is set to indicate the error,
* and the function returns RT_NULL.
*/
sem_t *sem_open(const char *name, int oflag, ...)
{
sem_t* sem;
va_list arg;
mode_t mode;
unsigned int value;
sem = RT_NULL;
/* lock posix semaphore list */
rt_sem_take(&posix_sem_lock, RT_WAITING_FOREVER);
if (oflag & O_CREAT)
{
va_start(arg, oflag);
mode = (mode_t) va_arg( arg, unsigned int); mode = mode;
value = va_arg( arg, unsigned int);
va_end(arg);
if (oflag & O_EXCL)
{
if (posix_sem_find(name) != RT_NULL)
{
rt_set_errno(EEXIST);
goto __return;
}
}
sem = (sem_t*) rt_malloc (sizeof(struct posix_sem));
if (sem == RT_NULL)
{
rt_set_errno(ENFILE);
goto __return;
}
/* create RT-Thread semaphore */
sem->sem = rt_sem_create(name, value, RT_IPC_FLAG_FIFO);
if (sem->sem == RT_NULL) /* create failed */
{
rt_set_errno(ENFILE);
goto __return;
}
/* initialize reference count */
sem->refcount = 1;
sem->unlinked = 0;
sem->unamed = 0;
/* insert semaphore to posix semaphore list */
posix_sem_insert(sem);
}
else
{
/* find semaphore */
sem = posix_sem_find(name);
if (sem != RT_NULL)
{
sem->refcount ++; /* increase reference count */
}
else
{
rt_set_errno(ENOENT);
goto __return;
}
}
rt_sem_release(&posix_sem_lock);
return sem;
__return:
/* release lock */
rt_sem_release(&posix_sem_lock);
/* release allocated memory */
if (sem != RT_NULL)
{
/* delete RT-Thread semaphore */
if (sem->sem != RT_NULL)
rt_sem_delete(sem->sem);
rt_free(sem);
}
return RT_NULL;
}
RTM_EXPORT(sem_open);
/**
* @brief Posts (increments) a POSIX semaphore.
* @param sem Pointer to the semaphore.
* @return Upon successful completion, returns 0; otherwise, returns -1 and sets errno to indicate the error.
*
* @note This function increments the value of the specified POSIX semaphore by one.
* If sem is a null pointer, errno is set to EINVAL to indicate an invalid argument, and the function returns -1.
* The semaphore is released using the RT-Thread semaphore release function rt_sem_release().
* If the semaphore release operation succeeds, the function returns 0; otherwise, errno is set to EINVAL,
* indicating an error, and the function returns -1.
*/
int sem_post(sem_t *sem)
{
rt_err_t result;
if (!sem)
{
rt_set_errno(EINVAL);
return -1;
}
result = rt_sem_release(sem->sem);
if (result == RT_EOK)
return 0;
rt_set_errno(EINVAL);
return -1;
}
RTM_EXPORT(sem_post);
/**
* @brief Waits for a POSIX semaphore with a timeout.
* @param sem Pointer to the semaphore.
* @param abs_timeout Pointer to the absolute timeout value.
* @return Upon successful completion, returns 0; otherwise, returns -1 and sets errno to indicate the error.
*
* @note This function waits for the specified POSIX semaphore to become available within the specified timeout.
* If either sem or abs_timeout is a null pointer, the function returns EINVAL, indicating an invalid argument.
* The abs_timeout parameter specifies an absolute timeout value based on the CLOCK_REALTIME clock.
* The timeout is converted to RT-Thread ticks using the rt_timespec_to_tick() function.
* The semaphore is waited upon using the RT-Thread semaphore take function rt_sem_take().
* If the semaphore is successfully acquired within the specified timeout, the function returns 0.
* If the timeout expires before the semaphore becomes available, errno is set to ETIMEDOUT,
* and the function returns -1. If the semaphore wait operation is interrupted by a signal,
* errno is set to EINTR, and the function returns -1.
*/
int sem_timedwait(sem_t *sem, const struct timespec *abs_timeout)
{
rt_err_t result;
rt_int32_t tick;
if (!sem || !abs_timeout)
return EINVAL;
/* calculate os tick */
tick = rt_timespec_to_tick(abs_timeout);
result = rt_sem_take(sem->sem, tick);
if (result == -RT_ETIMEOUT)
{
rt_set_errno(ETIMEDOUT);
return -1;
}
if (result == RT_EOK)
return 0;
rt_set_errno(EINTR);
return -1;
}
RTM_EXPORT(sem_timedwait);
/**
* @brief Attempts to wait for a POSIX semaphore without blocking.
* @param sem Pointer to the semaphore.
* @return Upon successful completion, returns 0 if the semaphore was acquired;
* otherwise, returns -1 and sets errno to indicate the error.
*
* @note This function attempts to acquire the specified POSIX semaphore without blocking.
* If sem is a null pointer, errno is set to EINVAL to indicate an invalid argument, and the function returns -1.
* The semaphore is waited upon using the RT-Thread semaphore take function rt_sem_take() with a timeout of 0,
* meaning that the function does not block if the semaphore is not available.
* If the semaphore is successfully acquired, the function returns 0. If the semaphore is not available,
* errno is set to EAGAIN to indicate that the operation would result in blocking, and the function returns -1.
* If the semaphore wait operation is interrupted by a signal, errno is set to EINTR, and the function returns -1.
*/
int sem_trywait(sem_t *sem)
{
rt_err_t result;
if (!sem)
{
rt_set_errno(EINVAL);
return -1;
}
result = rt_sem_take(sem->sem, 0);
if (result == -RT_ETIMEOUT)
{
rt_set_errno(EAGAIN);
return -1;
}
if (result == RT_EOK)
return 0;
rt_set_errno(EINTR);
return -1;
}
RTM_EXPORT(sem_trywait);
/**
* @brief Waits indefinitely for a POSIX semaphore to become available.
* @param sem Pointer to the semaphore.
* @return Upon successful completion, returns 0; otherwise, returns -1 and sets errno to indicate the error.
*
* @note This function waits indefinitely for the specified POSIX semaphore to become available.
* If sem is a null pointer, errno is set to EINVAL to indicate an invalid argument, and the function returns -1.
* The semaphore is waited upon using the RT-Thread semaphore take function rt_sem_take() with a timeout
* value of RT_WAITING_FOREVER, indicating an infinite wait time.
* If the semaphore is successfully acquired, the function returns 0. If the semaphore wait operation is interrupted
* by a signal, errno is set to EINTR, and the function returns -1.
*/
int sem_wait(sem_t *sem)
{
rt_err_t result;
if (!sem)
{
rt_set_errno(EINVAL);
return -1;
}
result = rt_sem_take(sem->sem, RT_WAITING_FOREVER);
if (result == RT_EOK)
return 0;
rt_set_errno(EINTR);
return -1;
}
RTM_EXPORT(sem_wait);

View File

@@ -0,0 +1,43 @@
/*
* Copyright (c) 2006-2021, RT-Thread Development Team
*
* SPDX-License-Identifier: Apache-2.0
*
* Change Logs:
* Date Author Notes
* 2010-10-26 Bernard the first version
*/
#ifndef __POSIX_SEMAPHORE_H__
#define __POSIX_SEMAPHORE_H__
#include <rtdef.h>
#include <sys/time.h>
struct posix_sem
{
/* reference count and unlinked */
rt_uint16_t refcount;
rt_uint8_t unlinked;
rt_uint8_t unamed;
/* RT-Thread semaphore */
rt_sem_t sem;
/* next posix semaphore */
struct posix_sem* next;
};
typedef struct posix_sem sem_t;
int sem_close(sem_t *sem);
int sem_destroy(sem_t *sem);
int sem_getvalue(sem_t *sem, int *sval);
int sem_init(sem_t *sem, int pshared, unsigned int value);
sem_t *sem_open(const char *name, int oflag, ...);
int sem_post(sem_t *sem);
int sem_timedwait(sem_t *sem, const struct timespec *abs_timeout);
int sem_trywait(sem_t *sem);
int sem_unlink(const char *name);
int sem_wait(sem_t *sem);
#endif

View File

@@ -0,0 +1,16 @@
/*
* Copyright (c) 2006-2021, RT-Thread Development Team
*
* SPDX-License-Identifier: Apache-2.0
*
* Change Logs:
* Date Author Notes
* 2021-12-07 Meco Man First version
*/
#ifndef __SYS_IPC_H__
#define __SYS_IPC_H__
#endif

View File

@@ -0,0 +1,16 @@
/*
* Copyright (c) 2006-2021, RT-Thread Development Team
*
* SPDX-License-Identifier: Apache-2.0
*
* Change Logs:
* Date Author Notes
* 2021-12-07 Meco Man First version
*/
#ifndef __SYS_MSG_H__
#define __SYS_MSG_H__
#endif

View File

@@ -0,0 +1,14 @@
/*
* Copyright (c) 2006-2021, RT-Thread Development Team
*
* SPDX-License-Identifier: Apache-2.0
*
* Change Logs:
* Date Author Notes
* 2021-12-07 Meco Man First version
*/
#ifndef __SYS_SEM_H__
#define __SYS_SEM_H__
#endif

View File

@@ -0,0 +1,16 @@
/*
* Copyright (c) 2006-2021, RT-Thread Development Team
*
* SPDX-License-Identifier: Apache-2.0
*
* Change Logs:
* Date Author Notes
* 2021-12-07 Meco Man First version
*/
#ifndef __SYS_SHM_H__
#define __SYS_SHM_H__
#endif