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
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!
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!
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
Set Wordpress Featured Image Using Javascript
How To Fix PHP Random Being The Same
Why no WebP Support with Wordpress
Replace Wordpress Cron With Linux Cron
Customize Yoast Canonical URL Programmatically
[Centos] Delete All Files And Folders That Contain a String