POSIX Compatibility Layer
Overview
The FreeWorld OS POSIX Compatibility Layer provides a comprehensive implementation of POSIX (Portable Operating System Interface) standards, enabling POSIX-compliant applications to run on FreeWorld OS. The layer wraps FreeWorld OS system calls and provides standard POSIX interfaces for file operations, process management, signals, threading, IPC, and more.
File Operations
Complete POSIX file I/O operations:
unistd.h
- open/close - Open and close files
- read/write - Read from and write to file descriptors
- lseek - Reposition file offset
- fsync/fdatasync - Synchronize file data
- truncate/ftruncate - Truncate files
- access - Check file permissions
- dup/dup2 - Duplicate file descriptors
- pipe - Create pipe
- chdir/getcwd - Change and get working directory
- symlink/readlink - Symbolic link operations
- link/unlink - Hard link operations
- mkdir/rmdir - Directory operations
- chmod/fchmod - Change file permissions
- chown/fchown/lchown - Change file ownership
fcntl.h
- fcntl - File descriptor control
- creat - Create and open file
- File locking - flock structure and operations
sys/stat.h
- stat/fstat/lstat - Get file status
- File type macros - S_ISREG, S_ISDIR, etc.
- umask - Set file mode creation mask
- mkfifo/mknod - Create special files
#include <unistd.h>
#include <fcntl.h>
#include <sys/stat.h>
int fd = open("file.txt", O_RDWR | O_CREAT, S_IRUSR | S_IWUSR);
char buffer[256];
ssize_t n = read(fd, buffer, sizeof(buffer));
write(fd, "Hello", 5);
close(fd);
Process Management
Complete POSIX process control:
Process Creation and Execution
- fork - Create child process
- execve/execv/execvp/execl/execlp - Execute programs
- getpid/getppid - Get process IDs
Process Waiting
- wait/waitpid - Wait for process to change state
- waitid - Wait for process (extended)
- Wait macros - WIFEXITED, WEXITSTATUS, etc.
Process Groups and Sessions
- getpgid/setpgid - Process group operations
- setsid/getsid - Session operations
User and Group IDs
- getuid/geteuid - Get user IDs
- getgid/getegid - Get group IDs
- setuid/setgid - Set user/group IDs
- seteuid/setegid - Set effective IDs
#include <unistd.h>
#include <sys/wait.h>
pid_t pid = fork();
if (pid == 0) {
// Child process
execl("/bin/program", "program", NULL);
} else {
// Parent process
int status;
waitpid(pid, &status, 0);
}
Signal Handling
Complete POSIX signal management:
Signal Functions
- signal - Set signal handler
- sigaction - Examine and change signal action
- kill/killpg - Send signal to process
- raise - Send signal to current process
- pause - Wait for signal
- alarm - Set alarm clock
Signal Sets
- sigemptyset/sigfillset - Initialize signal sets
- sigaddset/sigdelset - Add/remove signals from set
- sigismember - Test if signal is in set
- sigprocmask - Change signal mask
- sigpending - Get pending signals
- sigsuspend - Wait for signal
Supported Signals
- SIGINT - Interrupt (Ctrl+C)
- SIGTERM - Termination signal
- SIGKILL - Kill signal (cannot be caught)
- SIGSEGV - Segmentation fault
- SIGCHLD - Child process terminated
- And 26 more - Complete signal set
#include <signal.h>
#include <unistd.h>
void handler(int sig) {
// Handle signal
}
signal(SIGINT, handler);
kill(getpid(), SIGINT);
Threading (pthread)
POSIX threads implementation:
Thread Management
- pthread_create - Create new thread
- pthread_join - Join with terminated thread
- pthread_detach - Detach thread
- pthread_self - Get thread ID
- pthread_exit - Terminate calling thread
- pthread_cancel - Send cancellation request
Thread Attributes
- pthread_attr_init/destroy - Thread attributes
- pthread_attr_setdetachstate - Set detach state
- pthread_attr_setscope - Set contention scope
- pthread_attr_setstacksize - Set stack size
Mutexes
- pthread_mutex_init/destroy - Mutex operations
- pthread_mutex_lock/trylock/unlock - Lock operations
- pthread_mutex_timedlock - Lock with timeout
- Mutex types - Normal, errorcheck, recursive
Condition Variables
- pthread_cond_init/destroy - Condition variable operations
- pthread_cond_wait/timedwait - Wait on condition
- pthread_cond_signal/broadcast - Signal condition
Read-Write Locks
- pthread_rwlock_init/destroy - Read-write lock operations
- pthread_rwlock_rdlock/wrlock - Lock for reading/writing
- pthread_rwlock_unlock - Unlock
Thread-Specific Data
- pthread_key_create/delete - Thread-specific data keys
- pthread_getspecific/setspecific - Get/set thread data
- pthread_once - One-time initialization
#include <pthread.h>
void *thread_func(void *arg) {
// Thread code
return NULL;
}
pthread_t thread;
pthread_create(&thread, NULL, thread_func, NULL);
pthread_join(thread, NULL);
Directory Operations
POSIX directory traversal:
- opendir - Open directory
- readdir - Read directory entry
- readdir_r - Read directory entry (reentrant)
- closedir - Close directory
- rewinddir - Reset directory stream
- seekdir/telldir - Set/get directory position
- dirfd - Get file descriptor from directory stream
#include <dirent.h>
DIR *dir = opendir("/path/to/dir");
struct dirent *entry;
while ((entry = readdir(dir)) != NULL) {
printf("%s\n", entry->d_name);
}
closedir(dir);
Time Functions
POSIX time and timer operations:
- clock_gettime - Get time from specified clock
- clock_settime - Set time for specified clock
- clock_getres - Get clock resolution
- clock_nanosleep - High-resolution sleep
- timer_create/delete - Per-process timers
- timer_settime/gettime - Timer operations
- Supported clocks - CLOCK_REALTIME, CLOCK_MONOTONIC, CLOCK_PROCESS_CPUTIME_ID, CLOCK_THREAD_CPUTIME_ID
#include <time.h>
struct timespec ts;
clock_gettime(CLOCK_REALTIME, &ts);
printf("Time: %ld.%09ld\n", ts.tv_sec, ts.tv_nsec);
Environment Variables
POSIX environment variable management:
- getenv - Get environment variable
- setenv - Set environment variable
- unsetenv - Remove environment variable
- putenv - Add or change environment variable
- clearenv - Clear environment
- environ - External environment array
#include <stdlib.h>
char *value = getenv("PATH");
setenv("MY_VAR", "value", 1);
unsetenv("MY_VAR");
System Information
POSIX system information functions:
uname
- uname - Get system name
- utsname structure - sysname, nodename, release, version, machine, domainname
sysconf
- sysconf - Get system configuration
- pathconf - Get path configuration
- fpathconf - Get file path configuration
- Configuration names - _SC_ARG_MAX, _SC_CHILD_MAX, _SC_OPEN_MAX, etc.
#include <sys/utsname.h>
#include <unistd.h>
struct utsname info;
uname(&info);
printf("OS: %s\n", info.sysname);
long max_open = sysconf(_SC_OPEN_MAX);
Inter-Process Communication (IPC)
POSIX IPC mechanisms:
Semaphores
- sem_open/close - Named semaphores
- sem_unlink - Remove named semaphore
- sem_init/destroy - Unnamed semaphores
- sem_wait/trywait/timedwait - Lock semaphore
- sem_post - Unlock semaphore
- sem_getvalue - Get semaphore value
Shared Memory
- shm_open - Create/open shared memory object
- shm_unlink - Remove shared memory object
- mmap/munmap - Map/unmap memory
- mprotect - Set memory protection
- msync - Synchronize memory
- mlock/munlock - Lock/unlock memory
Message Queues
- mq_open/close - Message queue operations
- mq_unlink - Remove message queue
- mq_send/receive - Send/receive messages
- mq_timedsend/timedreceive - Timed operations
- mq_notify - Register for notification
- mq_getattr/setattr - Get/set attributes
#include <semaphore.h>
#include <sys/mman.h>
sem_t *sem = sem_open("/mysem", O_CREAT, 0644, 1);
sem_wait(sem);
// Critical section
sem_post(sem);
sem_close(sem);
Error Handling
POSIX error number definitions:
- errno - Thread-local error number
- Error codes - 122+ standard POSIX error codes
- __errno_location - Get pointer to thread-local errno
Common error codes include EPERM, ENOENT, EINTR, EIO, ENOMEM, EACCES, EINVAL, and many more.
Build System
The POSIX compatibility layer is built using the Makefile in libposix/:
cd libposix
make
This produces lib64/libposix.a, a static library containing all POSIX functions.
Header files are organized by component:
libposix/file/- File operations (unistd.h, fcntl.h, sys/stat.h)libposix/process/- Process management (sys/wait.h)libposix/signal/- Signal handling (signal.h)libposix/thread/- Threading (pthread.h)libposix/directory/- Directory operations (dirent.h)libposix/time/- Time functions (time.h)libposix/env/- Environment variableslibposix/sysinfo/- System information (sys/utsname.h)libposix/ipc/- IPC (semaphore.h, sys/mman.h, sys/msg.h)
Usage Example
Complete example demonstrating POSIX compatibility:
#include <unistd.h>
#include <sys/wait.h>
#include <signal.h>
#include <pthread.h>
#include <dirent.h>
#include <sys/utsname.h>
int main() {
// Process management
pid_t pid = fork();
if (pid == 0) {
execl("/bin/program", "program", NULL);
} else {
int status;
waitpid(pid, &status, 0);
}
// Signal handling
signal(SIGINT, handler);
// Threading
pthread_t thread;
pthread_create(&thread, NULL, thread_func, NULL);
pthread_join(thread, NULL);
// Directory operations
DIR *dir = opendir("/");
struct dirent *entry;
while ((entry = readdir(dir)) != NULL) {
printf("%s\n", entry->d_name);
}
closedir(dir);
// System information
struct utsname info;
uname(&info);
printf("OS: %s\n", info.sysname);
return 0;
}
Integration with FreeWorld OS
The POSIX compatibility layer integrates with FreeWorld OS through:
- System Calls - Wraps FreeWorld OS system calls
- C Library - Uses C library functions where applicable
- Kernel APIs - Direct kernel integration for process, signal, and thread management
This ensures compatibility and efficient resource sharing between POSIX applications and FreeWorld OS.
POSIX Compliance
The implementation follows POSIX.1-2017 standards and provides:
- ✅ File operations (Base Definitions, System Interfaces)
- ✅ Process management (Process Primitives)
- ✅ Signal handling (Signals)
- ✅ Threading (Threads)
- ✅ IPC (Semaphores, Shared Memory, Message Queues)
- ✅ Time functions (Timers)
- ✅ Directory operations (Directory Operations)
- ✅ System information (System Information)