#How to send specific stdin to a process with os.process_exec

1 messages · Page 1 of 1 (latest)

glacial sun
#

How do I launch a process with os.process_exec, and send a specific string to it's stdin stream?

steel bridge
#

Simple example using pipes.

package main

import "core:os"

main :: proc() {
  // Create the pipe, with a reader and writer handle.
  rpipe, wpipe, _pipe_err := os.pipe()

  // Spawn the process.
  cat, _cat_err := os.process_start({
    // Simplest program. Will output whatever it receives on stdin.
    command = {"cat"},

    // Pass the reader end of our pipe as the child process's stdin.
    stdin = rpipe,

    // Set the childs process's stdout to our stdout, so we can see the output. This is just for
    // demonstration.
    stdout = os.stdout
  })

  // Write the data you want.
  os.write_string(wpipe, "hello\n")

  // Close the pipe. Otherwise the child process will hang forever waiting for more input.
  os.close(wpipe)

  // Wait for the child to terminate.
  _status, _wait_err := os.process_wait(cat)
}
#

Pipe can be used for long-running two-way text communication between the parent and child processes. Depending on what you want to do exactly, there might be simpler ways to do it.

For example, if you just want to pass one short string and you are the author of the child program, consider receiving it as an argument.

#

This snippet just works for me on macOS, but from my experience with pipes across platforms is that there are always some gotchas around the order of things and when you can start writing, and when you need to flush etc 😵‍💫