乐趣区

php进程之间共享socket资源

  • receive.php
<?php
$path = __DIR__ . "/unix_sock";
@unlink($path);
$rs = socket_create(AF_UNIX, SOCK_DGRAM, 0) or die("socket_create err");
socket_bind($rs, $path) or die("socket_bind err");

$data = ["name"        => [],
    "buffer_size" => 2000,
    "controllen"  => socket_cmsg_space(SOL_SOCKET, SCM_RIGHTS, 3)
];
print_r($data);
$r = socket_recvmsg($rs, $data, 0);
if ($r) {print_r($data);
    $ret = fwrite($data['control'][0]['data'][0], date('Y-m-d H:i:s') . "receive \n");
    if ($ret) {echo "write success {$ret} \n";
    } else {echo "write fail \n";}
} else {echo 'receive fail';}
  • send.php
<?php
$path = __DIR__ . "/unix_sock";
$sends1 = socket_create(AF_UNIX, SOCK_DGRAM, 0) or die("socket_create err");

$f = fopen(__DIR__.'/s.txt','aw+');


fwrite($f,date('Y-m-d H:i:s')."send \n");

$data = ["name"    => ["path" => $path],
    "iov"     => ["info"],
    "control" => [
        [
            "level" => SOL_SOCKET,
            "type"  => SCM_RIGHTS,
            "data"  => [$f]
        ]
    ]
];
print_r($data);
$r = socket_sendmsg($sends1, $data, 0);

运行

- php receive.php 
- php send.php
退出移动版