How to change stdio of a given process (i.e. not current process)?

Viewed 36

Here is a way to change stdio of a given process by external tools such as gdb:

https://www.baeldung.com/linux/redirect-output-of-running-process

My question is, how can I do this programatically? I am using Go, bug example in C is also OK.

EDIT

My go program starts a bash instance inside a pty. User can run any command inside the pty. After the user types exit inside the terminal, bash will quit, but any background process will prevent the session from close cleanly.

I want to modify the stdio of any (grand) child processes of the bash, so that in its process' /proc/*/fd/, its 0, 1, 2 fd points to /dev/null, just like the nohup program do when it starts a program.

Obvioulsy it is impossible to let user always use nohup when run a command. So I want to do the clean up inside my go service program, so that the terminal does not hang.

1 Answers

so, I am making some assumptions to answer your questions which are as follows:

  1. the process you are taking about is a linux process.

  2. the program/process is perhaps being triggered using a go program.

    OR

  3. if not, you are rather proposing writing a demon of sorts in go that can intercept processed that are actively outputting to console in attempt to redirect it while its running.

if process is being triggered using a go program:

  • Why don't you redirect output while triggering the process?

if you want Go program to intercept a running process:

  • checkout https://pkg.go.dev/os/exec
  • you can use it to trigger shell commands.
  • you can use shell commands to invoke tools mentioned in the article you linked.
Related