How can I run psql in the background and interact with it?

0
0
Asked By MaverickDancer92 On

Hey everyone! I'm working on a script that connects to PostgreSQL using psql, and I need to run several commands and get their responses without blocking everything. I want to keep psql running in the background and still have access to its stdin and stdout. I tried using file descriptors with a command like `psql -U user ... &>5 <&4 &` but it doesn't seem to be working since fd 4 and fd 5 don't exist. I'm looking for alternatives—should I use mkfifo, or is there a way to handle file descriptors without actually creating files? I'd appreciate any advice, especially since I'm running this on a Mac, where procfs isn't available.

3 Answers

Answered By TechieTinkerer On

Using bash coproc is a smart option! It allows you to create a subprocess that you can communicate with easily. Here's a simple example using coproc:

```bash
coproc mycoproc { sed -u 's/function/coprocess/g' }

echo "Hello, function!" >&${mycoproc[1]}
read -r line <&${mycoproc[0]}
printf '%sn' "${line}"
kill "${mycoproc_PID}"
```
This way, you can keep the communication open without worrying about fd limitations!

Answered By ScriptSlinger89 On

Honestly, bash isn't the best choice for what you're trying to do. If you want something cleaner and more manageable, consider using Python or Perl. They can handle database interactions much more smoothly and give you more robust error handling. Save yourself the headache of dealing with file descriptors like this!

Answered By PipingGuru55 On

You definitely need a named pipe for this! When you start a background process, the parent and child have separate address spaces, so they can't see each other's stdin and stdout directly. However, be cautious when using named pipes in shell—you might run into performance issues if there's a lot of I/O. That said, if you're determined to use bash, you could try implementing a solution using bash coproc to manage your task instead. It'll handle everything without needing named pipes.

Related Questions

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.