port_write
lib callCapy
function port_write(handle : u64, data : string) bool
Description
port_write() queues bytes for a port and returns without waiting. The loop writes them as the descriptor accepts them, so a handler never blocks on a slow child or peer. The queue is bounded at 8 MiB per port; a write that would exceed it returns false and queues nothing, so a child or peer that stops reading cannot grow memory. For a spawned child the bytes go to its standard input.
Parameters
handle : a child port from port_spawn(), a socket from port_connect(), or an accepted connection
data : the bytes to send
Return Values
true when the bytes were queued; false when the port is closed or the write would take its queue past 8 MiB
Errors
A closed or unknown handle, an exited child, or a listening port yields false. Write to the accepted connection, not the listener. A true result only means queued bytes, not delivery or a reply. A later peer failure arrives through SERVICE:EXIT. Outside a service worker the call traps.
Example
Capy
var idle := {}
function SERVICE:START(props : any)
{
var agent := port_spawn(["pi", "--mode", "rpc"], cwd: "workspace", env: { "HOME": "/srv/agents" })
if agent != 0
{
idle[string(agent)] = agent
}
}
function SERVICE:STATE(props : any)
{
for agent := idle
{
var command := json_encode(id: string(props.id), type: "get_state")
if !port_write(u64(agent), command + "\n")
{
print("state request not queued\n")
}
return
}
print("no idle agent\n")
}
function SERVICE:DATA(props : any)
{
print(props.data)
}
function SERVICE:EXIT(props : any)
{
delete(idle, string(props.port))
}
function SERVICE:STOP(props : any)
{
for agent := idle
{
port_close(u64(agent))
}
}