I did something sort of like this recently. What I ended up doing was writing a simple forking TCP server using
Socket::IO::Inet which used
expect to control the actual program. Then my second program, the cgi, just opened a tcp connection to whatever port my server was listening on, sent commands and read data.