PHP - C 共享内存

问题描述 投票:0回答:1

我正在尝试从 PHP 写入内存地址并从 C 读取。我可以使用此从 PHP 成功写入并从 PHP 端再次读取;

$key = ftok("shmfile", 't');
$shm_id = shmop_open($key, "c", 0666, 100);
if (!$shm_id) {
    echo "Couldn't create shared memory segment.";
}
$data = "Hello, World!";
$bytes_written = shmop_write($shm_id, $data, 0);
if ($bytes_written != strlen($data)) {
    echo "Couldn't write the entire data to shared memory.";
} else {
    echo "Successfully wrote {$bytes_written} bytes to shared memory.\n";
}
$data_read = shmop_read($shm_id, 0, 100);
if (!$data_read) {
    echo "Couldn't read from shared memory segment.";
} else {
    echo "Data read from shared memory: " . $data_read . "\n";
}
shmop_close($shm_id);
echo "Shared memory segment closed.";

我的C代码如下;

int main()
{
    // ftok to generate unique key
    key_t key = ftok("shmfile", 65);

    // shmget returns an identifier in shmid
    int shmid = shmget(key, 1024, 0666 | IPC_CREAT);

    // shmat to attach to shared memory
    char* str = (char*)shmat(shmid, (void*)0, 0);

    cout << "Data read from memory:" << str;

    // detach from shared memory
    shmdt(str);

    // destroy the shared memory
    shmctl(shmid, IPC_RMID, NULL);

    return 0;
}

但是当我运行 C 代码时,我遇到了段错误。我想我需要对我的 C 代码进行一些修改才能阅读 PHP 编写的内容。

有什么想法吗?

php c shared-memory
1个回答
1
投票

您对 C 和 PHP 使用

shm_open()

© www.soinside.com 2019 - 2024. All rights reserved.