I'm building a program similar to strace
which shows some basic information about syscalls used by an executable.
It accepts an executable name and some arguments, and then to run it I create a child process using os.fork
and within it I run the process using os.execvp
. The problem is that I want to suppress the output of the child process, but I can't get it to work for all cases.
Currently I use os.dup2(os.open('/dev/null', os.O_WRONLY), 1)
to suppress the output, which works for most cases, but for example if I try running python3
with os.execvp
, the output is not suppressed.
This is how I currently run the process:
import os
import shutil
def run_process(name, *args, show_output='0'):
"""
Start a process with arguments.
- `name` - the name of the process.
- `args` - the arguments to pass to the process.
- `show_output` - whether to show the output of the process or not.
"""
if (shutil.which(name) is None) and (not os.path.isfile(name)) and (not os.path.exists(name)):
os.kill(os.getppid(), 9)
print('Command/File `{}` not found.'.format(name))
ptrace(PTRACE_TRACEME, 0, 0, 0)
if show_output.lower() not in ['1', 'true', 'yes', 'y']:
# redirect output to /dev/null
os.dup2(os.open('/dev/null', os.O_WRONLY), 1)
try:
os.execvp(name, [name] + list(args))
except Exception as e:
# redirect output back to stdout:
os.dup2(os.open('/dev/tty', os.O_WRONLY), 1)
os.kill(os.getppid(), 9)
print(f'An error occured when running the process: {e}')
pid = os.fork()
if pid == 0:
run_process('python3', show_output='0') # output is shown
# output is not shown:
# run_process('ls', show_output='0')
else:
# ptrace stuff...
Any idea on how can I get the output to fully disappear?