Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why we cannot accept() a socket on some process and recv() data from its child?

I'm trying to implement a simple web server on Linux that connects to the client (the browser) ,receives some requests from the client (e.g GET), and then sends back the response with desired file. I am using a socket communication. I want to create a pool of worker processes (children) at server startup whose job is to deal with the incoming requests. The parent process has to accept() the incoming request and sends their file-desciptor to one of the worker processes to deal with it and sends the response to the client with the requested file.

The problem that I have faced is that when I accept() the request and send it to the worker process, recv() or read() functions return -1 which means an error occurs:

Socket operation on non-socket

But when I try to use recv() or read() functions at the parent process, they work very well and return the number of received bytes.

How can I solve this issue?

PS: I am using the shared memory to pass the file-desciptor from the parent process to the worker process (the child process), and I am using semaphores to manage which worker process will handle the request


EDIT:

Actually, it's a project assignment and one of the specification is to send the file-descriptor via the shared memory. However, can I send a pointer of the file-descriptor?

like image 978
Eng.Fouad Avatar asked Feb 04 '26 12:02

Eng.Fouad


1 Answers

You can't send file descriptors via shared memory, AFAIK. So what your're doing is essentially sending a small integer to a worker process.

What you can do, is send the file descriptor over a Unix domain socket, using sendmsg and ancilliary data. It sounds a bit like magic (heck, it is a bit like magic) but it's pretty standard among Unixes so it should work.

like image 142
cnicutar Avatar answered Feb 06 '26 02:02

cnicutar