Python os.dup2() Method



The Python os.dup2() method duplicates the given file descriptor to another. The original file descriptor is closed if necessary.

The new file descriptor obtained is inheritable. By inheritable, we mean that the created file descriptor can be inherited by the child processes. If the parent process is using file descriptor 3 for a specific file and the parent creates a child process, the child process will also be using file descriptor 3 for the same file. This is known as an inheritable file descriptor.

Note − New file description would be assigned only when it is available.

Syntax

Following is the syntax of Python os.dup2() method −

os.dup2(fd, fd2);

Parameters

  • fd − This is File descriptor to be duplicated.

  • fd2 − This is Duplicate file descriptor.

Return Value

This method returns a duplicate of file descriptor.

Example

The following example shows the usage of Python os.dup2() method. Here, 1000 would be assigned as a duplicate fd in case when 1000 is available.

import os, sys
# Open a file
fd = os.open( "code.txt", os.O_RDWR|os.O_CREAT )
# Write one string
string = "This is test"
x = str.encode(string)
os.write(fd, x)
# Now duplicate this file descriptor as 1000
fd2 = 1000
os.dup2(fd, fd2);
# Now read this file from the beginning using fd2.
os.lseek(fd2, 0, 0)
str = os.read(fd2, 100)
print ("Read String is : ", str)
# Close opened file
os.close( fd )
print ("Closed the file successfully!!")

When we run above program, it produces following result −

Read String is :  b'This is test'
Closed the file successfully!!

Example

In here we are checking whether the given two file descriptors are different. This is done using the sameopenfile() method. This method returns a Boolean value.

import os
filepath = "code.txt"
fd1 = os.open(filepath, os.O_RDONLY)
fd2 = os.open("python.txt", os.O_RDONLY)
print("Before duplicating file descriptor:", os.path.sameopenfile(fd1, fd2))
fd2 = os.dup2(fd1, fd2)
print("After duplicating file descriptor:", os.path.sameopenfile(fd1, fd2))
os.close(fd1)
os.close(fd2)

While executing the above code we get the following output −

Before duplicating file descriptor: False
After duplicating file descriptor: True
python_file_methods.htm
Advertisements