php案例 PHP POSIX扩展的完整案例(Linux、macOS、Unix)。Windows系统不支持POSIX扩展。

安装# 更新包列表

sudo apt update

# 安装POSIX扩展
sudo apt install php-posix

# 或者根据PHP版本安装
sudo apt install php8.1-posix  # PHP 8.1
sudo apt install php8.0-posix  # PHP 8.0
sudo apt install php7.4-posix  # PHP 7.4

# 重启Apache/Nginx
sudo systemctl restart apache2
# 或
sudo systemctl restart nginx
<?php
/**
 * PHP POSIX 扩展功能演示
 * 纯PHP代码,无HTML输出
 */

// 检查 POSIX 扩展是否可用
if (!extension_loaded('posix')) {
    die("错误:POSIX 扩展未安装或未启用\n");
}

echo "=== PHP POSIX 扩展功能演示 ===\n\n";

/**
 * 1. 进程信息获取
 */
echo "1. 进程信息获取\n";
echo str_repeat("-", 30) . "\n";

$process_info = [
    '当前进程ID' => posix_getpid(),
    '父进程ID' => posix_getppid(),
    '进程组ID' => posix_getpgrp(),
    '会话ID' => posix_getsid(0),
    '真实用户ID' => posix_getuid(),
    '有效用户ID' => posix_geteuid(),
    '真实组ID' => posix_getgid(),
    '有效组ID' => posix_getegid()
];

foreach ($process_info as $key => $value) {
    printf("%-15s: %d\n", $key, $value);
}
echo "\n";

/**
 * 2. 用户信息获取
 */
echo "2. 用户信息获取\n";
echo str_repeat("-", 30) . "\n";

$current_uid = posix_getuid();
$user_info = posix_getpwuid($current_uid);

if ($user_info) {
    printf("用户名: %s\n", $user_info['name']);
    printf("用户ID: %d\n", $user_info['uid']);
    printf("主组ID: %d\n", $user_info['gid']);
    printf("主目录: %s\n", $user_info['dir']);
    printf("Shell: %s\n", $user_info['shell']);
    printf("备注信息: %s\n", $user_info['gecos']);
} else {
    echo "无法获取用户信息\n";
}
echo "\n";

/**
 * 3. 组信息获取
 */
echo "3. 组信息获取\n";
echo str_repeat("-", 30) . "\n";

$current_gid = posix_getgid();
$group_info = posix_getgrgid($current_gid);

if ($group_info) {
    printf("组名: %s\n", $group_info['name']);
    printf("组ID: %d\n", $group_info['gid']);
    printf("组成员: %s\n", implode(', ', $group_info['members']));
} else {
    echo "无法获取组信息\n";
}
echo "\n";

/**
 * 4. 文件访问权限检查
 */
echo "4. 文件访问权限检查\n";
echo str_repeat("-", 30) . "\n";

$test_file = __FILE__;
echo "检查文件: $test_file\n";

$access_checks = [
    'POSIX_F_OK' => '文件存在',
    'POSIX_R_OK' => '可读',
    'POSIX_W_OK' => '可写',
    'POSIX_X_OK' => '可执行'
];

foreach ($access_checks as $const => $desc) {
    if (defined($const)) {
        $result = posix_access($test_file, constant($const));
        printf("%-10s: %s\n", $desc, $result ? '是' : '否');
    }
}

// 获取文件详细信息
$file_stat = stat($test_file);
if ($file_stat) {
    printf("文件权限: %o\n", $file_stat['mode'] & 0777);
    printf("文件大小: %d 字节\n", $file_stat['size']);
    printf("所有者UID: %d\n", $file_stat['uid']);
    printf("所有者GID: %d\n", $file_stat['gid']);
    printf("修改时间: %s\n", date('Y-m-d H:i:s', $file_stat['mtime']));
}
echo "\n";

/**
 * 5. 系统信息获取
 */
echo "5. 系统信息获取\n";
echo str_repeat("-", 30) . "\n";

$uname_info = posix_uname();
if ($uname_info) {
    foreach ($uname_info as $key => $value) {
        printf("%-15s: %s\n", ucfirst($key), $value);
    }
}

// 获取系统时间信息
$times = posix_times();
if ($times) {
    echo "\n进程时间信息:\n";
    printf("用户时间: %d ticks\n", $times['utime']);
    printf("系统时间: %d ticks\n", $times['stime']);
    printf("子进程用户时间: %d ticks\n", $times['cutime']);
    printf("子进程系统时间: %d ticks\n", $times['cstime']);
}
echo "\n";

/**
 * 6. 系统资源限制
 */
echo "6. 系统资源限制\n";
echo str_repeat("-", 30) . "\n";

$limits = posix_getrlimit();
if ($limits) {
    $resource_names = [
        'core' => '核心转储文件大小',
        'totalmem' => '总内存',
        'virtualmem' => '虚拟内存',
        'data' => '数据段大小',
        'stack' => '栈大小',
        'rss' => '常驻内存大小',
        'maxproc' => '最大进程数',
        'memlock' => '内存锁定',
        'cpu' => 'CPU时间',
        'filesize' => '文件大小',
        'openfiles' => '打开文件数'
    ];
    
    foreach ($limits as $resource => $limit) {
        $name = isset($resource_names[$resource]) ? $resource_names[$resource] : $resource;
        if (is_array($limit)) {
            printf("%-15s: 软限制=%s, 硬限制=%s\n", 
                   $name, 
                   $limit['soft'] == -1 ? '无限制' : $limit['soft'],
                   $limit['hard'] == -1 ? '无限制' : $limit['hard']);
        }
    }
}
echo "\n";

/**
 * 7. 实用函数演示
 */
echo "7. 实用函数演示\n";
echo str_repeat("-", 30) . "\n";

// 检查是否为root用户
function isRoot() {
    return posix_getuid() === 0;
}

echo "是否为root用户: " . (isRoot() ? '是' : '否') . "\n";

// 获取用户名
function getCurrentUsername() {
    $uid = posix_getuid();
    $user = posix_getpwuid($uid);
    return $user ? $user['name'] : '未知';
}

echo "当前用户名: " . getCurrentUsername() . "\n";

// 检查进程是否存在
function processExists($pid) {
    return posix_kill($pid, 0);
}

$current_pid = posix_getpid();
echo "进程 $current_pid 是否存在: " . (processExists($current_pid) ? '是' : '否') . "\n";

// 安全的文件操作检查
function safeFileOperation($file, $operation) {
    switch ($operation) {
        case 'read':
            return posix_access($file, POSIX_R_OK);
        case 'write':
            return posix_access($file, POSIX_W_OK);
        case 'execute':
            return posix_access($file, POSIX_X_OK);
        default:
            return false;
    }
}

echo "当前文件可读: " . (safeFileOperation(__FILE__, 'read') ? '是' : '否') . "\n";
echo "当前文件可写: " . (safeFileOperation(__FILE__, 'write') ? '是' : '否') . "\n";
echo "\n";

/**
 * 8. 错误处理演示
 */
echo "8. 错误处理演示\n";
echo str_repeat("-", 30) . "\n";

// 故意触发一个错误(访问不存在的文件)
$non_existent_file = '/non/existent/file/path';
$result = posix_access($non_existent_file, POSIX_R_OK);

if (!$result) {
    $errno = posix_get_last_error();
    $error_msg = posix_strerror($errno);
    printf("错误代码: %d\n", $errno);
    printf("错误信息: %s\n", $error_msg);
}
echo "\n";

/**
 * 9. 高级功能演示
 */
echo "9. 高级功能演示\n";
echo str_repeat("-", 30) . "\n";

// 获取所有用户信息的函数
function getAllUsers() {
    $users = [];
    $passwd_file = '/etc/passwd';
    
    if (file_exists($passwd_file) && is_readable($passwd_file)) {
        $lines = file($passwd_file, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
        foreach ($lines as $line) {
            $parts = explode(':', $line);
            if (count($parts) >= 3) {
                $users[] = [
                    'name' => $parts[0],
                    'uid' => (int)$parts[2],
                    'gid' => (int)$parts[3]
                ];
            }
        }
    }
    
    return $users;
}

// 显示系统用户数量
$users = getAllUsers();
echo "系统用户总数: " . count($users) . "\n";

// 显示前5个用户
echo "前5个系统用户:\n";
foreach (array_slice($users, 0, 5) as $user) {
    printf("  %s (UID: %d, GID: %d)\n", $user['name'], $user['uid'], $user['gid']);
}
echo "\n";

/**
 * 10. 性能监控函数
 */
echo "10. 性能监控函数\n";
echo str_repeat("-", 30) . "\n";

// 获取内存使用情况
function getMemoryUsage() {
    $memory_limit = ini_get('memory_limit');
    $memory_usage = memory_get_usage(true);
    $memory_peak = memory_get_peak_usage(true);
    
    return [
        'limit' => $memory_limit,
        'current' => $memory_usage,
        'peak' => $memory_peak
    ];
}

$memory = getMemoryUsage();
printf("内存限制: %s\n", $memory['limit']);
printf("当前内存使用: %s\n", formatBytes($memory['current']));
printf("峰值内存使用: %s\n", formatBytes($memory['peak']));

// 格式化字节数
function formatBytes($bytes, $precision = 2) {
    $units = ['B', 'KB', 'MB', 'GB', 'TB'];
    
    for ($i = 0; $bytes > 1024 && $i < count($units) - 1; $i++) {
        $bytes /= 1024;
    }
    
    return round($bytes, $precision) . ' ' . $units[$i];
}
echo "\n";

/**
 * 11. 信号处理演示(需要PCNTL扩展)
 */
echo "11. 信号处理演示\n";
echo str_repeat("-", 30) . "\n";

if (extension_loaded('pcntl')) {
    echo "PCNTL扩展已加载,可以进行信号处理\n";
    
    // 定义信号处理函数
    function signalHandler($signo) {
        switch ($signo) {
            case SIGTERM:
                echo "收到SIGTERM信号\n";
                break;
            case SIGUSR1:
                echo "收到SIGUSR1信号\n";
                break;
            case SIGUSR2:
                echo "收到SIGUSR2信号\n";
                break;
        }
    }
    
    // 安装信号处理器
    pcntl_signal(SIGTERM, 'signalHandler');
    pcntl_signal(SIGUSR1, 'signalHandler');
    pcntl_signal(SIGUSR2, 'signalHandler');
    
    echo "信号处理器已安装\n";
    echo "可以使用 posix_kill() 发送信号给进程\n";
    
    // 演示发送信号给自己
    echo "向自己发送SIGUSR1信号...\n";
    posix_kill(posix_getpid(), SIGUSR1);
    pcntl_signal_dispatch(); // 处理待处理的信号
} else {
    echo "PCNTL扩展未加载,无法演示信号处理\n";
}
echo "\n";

/**
 * 12. 实用工具集合
 */
echo "12. 实用工具集合\n";
echo str_repeat("-", 30) . "\n";

// 检查文件所有权
function checkFileOwnership($file) {
    if (!file_exists($file)) {
        return false;
    }
    
    $stat = stat($file);
    $current_uid = posix_getuid();
    $current_gid = posix_getgid();
    
    return [
        'owned_by_user' => $stat['uid'] === $current_uid,
        'owned_by_group' => $stat['gid'] === $current_gid,
        'file_uid' => $stat['uid'],
        'file_gid' => $stat['gid'],
        'current_uid' => $current_uid,
        'current_gid' => $current_gid
    ];
}

$ownership = checkFileOwnership(__FILE__);
echo "文件所有权检查:\n";
printf("  当前用户拥有: %s\n", $ownership['owned_by_user'] ? '是' : '否');
printf("  当前组拥有: %s\n", $ownership['owned_by_group'] ? '是' : '否');
printf("  文件UID: %d, 当前UID: %d\n", $ownership['file_uid'], $ownership['current_uid']);
printf("  文件GID: %d, 当前GID: %d\n", $ownership['file_gid'], $ownership['current_gid']);

echo "\n";

/**
 * 13. POSIX常量信息
 */
echo "13. POSIX常量信息\n";
echo str_repeat("-", 30) . "\n";

$posix_constants = [
    'POSIX_F_OK' => 'POSIX_F_OK',
    'POSIX_R_OK' => 'POSIX_R_OK', 
    'POSIX_W_OK' => 'POSIX_W_OK',
    'POSIX_X_OK' => 'POSIX_X_OK'
];

foreach ($posix_constants as $const => $name) {
    if (defined($const)) {
        printf("%-12s = %d\n", $name, constant($const));
    }
}
echo "\n";

/**
 * 14. 系统兼容性检查
 */
echo "14. 系统兼容性检查\n";
echo str_repeat("-", 30) . "\n";

$posix_functions = [
    'posix_access', 'posix_getpid', 'posix_getppid', 'posix_getuid',
    'posix_geteuid', 'posix_getgid', 'posix_getegid', 'posix_getpgrp',
    'posix_getsid', 'posix_getpwuid', 'posix_getpwnam', 'posix_getgrgid',
    'posix_getgrnam', 'posix_getrlimit', 'posix_uname', 'posix_times',
    'posix_kill', 'posix_get_last_error', 'posix_strerror'
];

$available_functions = 0;
foreach ($posix_functions as $func) {
    if (function_exists($func)) {
        $available_functions++;
    }
}

printf("POSIX函数支持: %d/%d\n", $available_functions, count($posix_functions));

if ($available_functions === count($posix_functions)) {
    echo "✓ 完整的POSIX支持\n";
} else {
    echo "⚠ 部分POSIX功能不可用\n";
    echo "不可用的函数:\n";
    foreach ($posix_functions as $func) {
        if (!function_exists($func)) {
            echo "  - $func\n";
        }
    }
}

echo "\n=== 演示结束 ===\n";
?>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

贵哥的编程之路(热爱分享 为后来者)

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值