[파이썬] os 터미널 제어: `os.tcgetpgrp()`, `os.tcsetpgrp()`

When working with terminal applications in Python, you may often come across situations where you need to control the terminal process group. Python’s os module provides two functions os.tcgetpgrp() and os.tcsetpgrp() that allow you to interact with the terminal’s process group.

os.tcgetpgrp()

The os.tcgetpgrp() function is used to get the process group ID of the foreground terminal associated with the controlling terminal of the calling process.

import os

# Get the process group ID of the foreground terminal
pgid = os.tcgetpgrp(fd)

Here, fd is the file descriptor associated with the controlling terminal. It can be obtained using os.open() or os.dup().

os.tcsetpgrp()

The os.tcsetpgrp() function is used to set the process group ID of the foreground terminal associated with the controlling terminal of the calling process.

import os

# Set the process group ID of the foreground terminal
os.tcsetpgrp(fd, pgid)

Here, fd is the file descriptor associated with the controlling terminal, and pgid is the new process group ID to be set.

Example Usage

Let’s see an example of how these functions can be used together to control the terminal process group.

import os
import signal
import subprocess

# Start a subprocess and get its process group ID
process = subprocess.Popen(["python", "script.py"])
pgid = os.getpgid(process.pid)

# Get the file descriptor of the controlling terminal
fd = os.open("/dev/tty", os.O_RDWR)

# Set the process group of the subprocess as the foreground terminal
os.tcsetpgrp(fd, pgid)

# Resume the execution of the subprocess
os.killpg(pgid, signal.SIGCONT)

In this example, we are starting a subprocess using the subprocess module and obtaining its process group ID. We then open the controlling terminal and use os.tcsetpgrp() to set the subprocess’s process group as the foreground terminal. Finally, we resume the execution of the subprocess using os.killpg() and the SIGCONT signal.

Using these functions, you can have more control over terminal processes in your Python applications and perform actions like bringing a background process to the foreground or sending signals to specific process groups.

Remember to handle any exceptions that may be raised by these functions, especially when dealing with file descriptors and process IDs.