I need to run bin/psql on the command line (or script) and print its pg_backend_pid out, so that the pg_backend_pid can be passed to another process (run by root) as command line argument. The problem for me is that the other process needs to run after it obtains the pid. The psql (with same pid session) then runs a query after the other process has started.
The trick is that Psql needs to wait until the other process gets the pg_backend_pid and it has to remain the same session.
Can this be done through shell script or perl?
You’ll want to use a coprocess in bash, or in perl with some kind of two-way pipe. In Python you can use the os.popen2 command; perl also has facilities for interacting with subprocesses over pipes. However, it’s much better to use native language database drivers like
DBD::Pgorpsycopg2if at all possible.If you must do this in the shell, see “info bash” and search for “coprocess”.
Here’s a quick demo bash script to get you started.
The arguments to psql are to ensure it doesn’t pause for input, doesn’t interpret tabs or metachars as readline commands, and doesn’t pretty-print output so it’s easier to interact with on the shell.
Alternately, it’s possible you don’t really need psql at all, you just need to talk to the PostgreSQL server via some kind of script. If that’s the case, it’ll be MUCH easier to just use a scripting language with a PostgreSQL database interface. In Python, for example:
In Perl you can use DBI and DBD::Pg to achieve a similar effect.