Run 2 executables simultaneously (ping & pong) best practices?

As a training, I wrote two simple programs using this mqtt library. One sends "ping", the other responds with "pong". I plan on writing similar ones in an asynchronous mode, so four programs, in a same project.

I guess I could put them next to each other in the same project, in src/ or lib/, however I wish to run them simultaneously. Is that do-able with cargo ? If not, what are the best practices ?

Will share the code (2 * 500 lines) here if needed. But I need to organize it properly before pushing it on github.

You can create three binaries:

  1. ping
  2. pong
  3. run - which can spawn ping & pong.

You can add this to Cargo.toml:

[package]
name = "mycrate"
version = "0.1.0"
authors = ["you"]
edition = "2018"
default-run = "run"

[[bin]]
path = "src/ping.rs"
name = "ping"

[[bin]]
path = "src/pong.rs"
name = "pong"

[[bin]]
path = "src/run.rs"
name = "run"

If you write this one as a test instead, then cargo 1.43 will set CARGO_BIN_EXE_ping/pong environment variables so you know where to find them.

1 Like

Thanks a lot to both of you.
I didn't know you could do that. I took over your Cargo.toml example, only without the run binary. Spawning several executables from a third one looks very interesting but goes beyond the scope of my exercise.

This is my Cargo.toml :

 [package]
name = "mqtt_ping_pong"
version = "0.1.0"
authors = ["Emmanuel Bosquet <bjokac@gmail.com>"]
edition = "2018"

[[bin]]
path = "src/sync_ping.rs"
name = "sync_ping"

[[bin]]
path = "src/sync_pong.rs"
name = "sync_pong"

[dependencies]
paho-mqtt = "0.6.0"

I'll ask my teacher to run in two terminals:

cargo run --bin sync_ping
cargo run --bin sync_pong

That works for me and it all fits nicely in one project. Thank you!

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.