Initial import to Tizen
[profile/ivi/python-twisted.git] / doc / core / howto / listings / sendmsg / copy_descriptor.py
1 # Copyright (c) Twisted Matrix Laboratories.
2 # See LICENSE for details.
3
4 """
5 Demonstration of copying a file descriptor over an AF_UNIX connection using
6 sendmsg.
7 """
8
9 from os import pipe, read, write
10 from socket import SOL_SOCKET, socketpair
11 from struct import unpack, pack
12
13 from twisted.python.sendmsg import SCM_RIGHTS, send1msg, recv1msg
14
15 def main():
16     foo, bar = socketpair()
17     reader, writer = pipe()
18
19     # Send a copy of the descriptor.  Notice that there must be at least one
20     # byte of normal data passed in.
21     sent = send1msg(
22         foo.fileno(), "\x00", 0,
23         [(SOL_SOCKET, SCM_RIGHTS, pack("i", reader))])
24
25     # Receive the copy, including that one byte of normal data.
26     data, flags, ancillary = recv1msg(bar.fileno(), 1024)
27     duplicate = unpack("i", ancillary[0][2])[0]
28
29     # Demonstrate that the copy works just like the original
30     write(writer, "Hello, world")
31     print "Read from original (%d): %r" % (reader, read(reader, 6))
32     print "Read from duplicate (%d): %r" % (duplicate, read(duplicate, 6))
33
34 if __name__ == '__main__':
35     main()