What is os.pidfd_open() in Python?

Overview

The os.pidfd_open() function creates a file descriptor that refers to the ID of a process specified as PID an argument. The returned file descriptor can be used to perform process management without any external signal.

It also set close-on-exec flag on file descriptor. The set flag value means a child process does not inherit the file descriptor.

Syntax

os.pidfd_open(pid, flags=0)

Parameters

It takes the following argument values.

  • pid: This is the process identifier.
  • flags: This is the flag argument that can have either 0 or PIDFD_NONBLOCK flag. Its default is 0.

flag= PIDFD_NONBLOCK means os.pidfd_open() will return a non-blocking file descriptor. The non-blocking file descriptor means returning data quickly even if file reading is slow.

Return value

It returns either a positive integer or -1.

  • On successful execution, it returns a positive integer value.
  • On failure, it returns -1.

Example

from os import fork, pidfd_open
# fork the current process
pid = fork();
# if child process is in execution
if pid > 0:
  pidfd = pidfd_open(pid, 0)
  print("Child Process")
else:
  print("Parent Process")

Explanation

  • Line 1: We import the fork and pidpf_open methods from the os module.
  • Line 3: We invoke fork() to make a copy of the current process.
  • Line 5: If pid is greater than 0, it means the child process is under execution.
  • Line 6: pidfd_open(pid, 0) is used to get the file descriptor for the current process.
  • Line 7: We print the message, "Child Process".
  • Line 8: We start the parent section.
  • Line 9: We print the message, "Parent Process".

Free Resources