2

I'm new to python :) I would like to create persistent socket. I tried to do this using file descriptors. What I tried is:

  1. Open a socket socket connection s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

  2. Get it's file descriptor number fd = s.fileno()

  3. Open the file descriptor as I/O os.open(fd)

But I get OSError: [Errno 9] Bad file descriptor

I said I'm new to python and maybe I'm wrong with the implementation. But I tried a simpler example os.close(s.fileno()) and I get the same error OSError: [Errno 9] Bad file descriptor

I found an example written in ruby and I tested it, it works. How do I make persistent network sockets on Unix in Ruby?

Can any one write this into python for me, what I want to achieve is: socket_start.py google.com (thie will print the fd number) sleep 10 socket_write.py fd_number 'something' sleep 10 socket_read.py fd_number 1024

I hope you understand what I want to do. Thanks in advice!


After your responses I tried next code:

1

#!/usr/bin/python

import socket

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(('google.com', 80))
s.send('GET /\n')
print s.fileno()

2

#!/usr/bin/python

import os
import sys

fd = int(sys.argv[1])
os.read(fd, 1024)

And the error is OSError: [Errno 9] Bad file descriptor

I'm sure what the problem is (I'm a php developer). I think same as php, python deletes garbage after closing a script. How to solve this in python ?

1
  • Andrew, note that the ruby example that you post does not do what you want. It catches SIGINT and then immediately respawns itself. This is different than dying, waiting ten seconds and then expecting that the python (if not the OS) has not reclaimed the file descriptor. This is not to mention that the process that the ruby example passes the file descriptor to is a subprocess of the file that opens the socket. Commented Sep 19, 2010 at 22:48

2 Answers 2

1

You use os.fdopen() to open file descriptors.

I'm actually surprised that you got that far because os.open requires a filename and flags stating which mode to open the file in. for example fd = os.open('foo.txt', os.O_RONLY). As my example indicates, it returns a file descriptor rather than accepting one.

Sign up to request clarification or add additional context in comments.

Comments

0

If you want to re-create the socket by a parameter received on the commandline (i.e., the socket), use socket.fromfd

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.