Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Memory handling with struct epoll_event

Tags:

c

linux

epoll

I'm developing a server in C with the epoll library and I have a question as to how memory is handled for struct epoll_event. I've noticed in some online examples that, when making epoll_ctl calls, the events argument is allocated on the stack and then the pointer is passed, like so:

struct epoll_event ev;
ev.events = EPOLLIN;
epoll_ctl(epfd, EPOLL_CTL_ADD, sockfd, &ev);

Now we all know what happens to ev when the function returns. My question is: does the epoll library make copies of these values internally or does it rely on the struct you passed to be heap allocated? Will the above example totally break my reactor implementation? If so, what is the best way of keeping track of my heap allocated epoll_event structs?

Thanks for your time.

like image 736
Blake Beaupain Avatar asked Oct 19 '12 20:10

Blake Beaupain


2 Answers

Everything is fine. The epoll_ctl function is a simple wrapper around a system call which will be entirely complete when the function returns. No further data from userspace is required. The struct is simply a way to package the arguments.

like image 127
Kerrek SB Avatar answered Oct 09 '22 17:10

Kerrek SB


It's absolutely fine to immediately throw away or reuse your epoll_event struct.

The kernel will copy the parameters out of the epoll_event struct.

This is exactly the same as if you used an ioctl which takes a struct as a parameter, or a socket operation (e.g. bind) which takes a struct sockaddr_in.

The kernel takes what it needs, and it's immediately ok for you to free it.

The only thing you need to worry about is the "user data", which is only relevant to you. The kernel will store it, but you need to know what it means when you get an event.

like image 42
MarkR Avatar answered Oct 09 '22 17:10

MarkR