user782220
user782220

Reputation: 11187

How to do async read/write Beast websockets alongside read/write of files?

I have my C++ program that forks into two processes, 1 (the original) and 2 (the forked process).

In the forked process (2), it execs program A that does a lot of computation.

The original process (1) communicates with that program A through standard input and output redirected to pipes.

I am trying to add a websocket connection to my code in the original process (1). I would like my original process to effectively select or epoll on whether there is data to be read from the pipe to program A or there is data to be read from the websocket connection.

Given that a beast websocket is not a file descriptor how can I do the effect of select or epoll?

Upvotes: 3

Views: 1534

Answers (2)

Abhijit Pritam Dutta
Abhijit Pritam Dutta

Reputation: 5581

you can make little change in your code. Replace the pipe with two Message Queue. For example out_q and response_q. Now your child process A will continuously read out_q and whenever your main process drop a message to out_q your main process will not wait for any response from child and your child will consume that message. Communication through message queue is asynchronous. But if you still need a kind of reply like any success or failure message from the child you can get it through response_q which will be read by your parent process. To know the response from child against a specific message originally sent from parent, you can use correlation id. (Read little about correlation id). Now in parent process implement two 2 threads one will continuously read to web call and other one will read to standard input. And one method (probably static) which will be connected to out_q to drop message. Use mutex so that only one thread can call it and drop message to the out_q. Your main thread or process will read the response_q . In this way you can make everything parallel and asynchronous. If you don’t want to use thread still you have option for you fork() and create two child process for the same. Hope this will help you.

Upvotes: 1

v1bri
v1bri

Reputation: 1428

Which version of Boost are you using? If it is relatively recent it should include support for boost::process::async_pipe which allows you to use I/O Objects besides sockets asynchronously with Asio. Examples are provided in the tutorials for the boost::process library. Since Beast uses the Asio library to perform I/O under the hood, you can combine the two quite easily.

Given that a beast websocket is not a file descriptor...

The Beast WebSocket is not a file descriptor, but it does use TCP sockets to perform I/O (see the linked examples above), and Asio is very good at using select/epoll with TCP sockets. Just make sure you are doing the async_read, async_write and io_service::run operations as usual.

Upvotes: 3

Related Questions