Reputation: 4508
Can I pass a file socket descriptor as a function argument, i.e.
void mysend(int fd, uint8_t *data, size_t len)
{
...
sendto(fd, ...);
...
}
int main()
{
int fd = socket(...);
uint8_t data[5] = {1, 2, 3, 4, 5};
mysend(fd, data, 5);
return 0;
}
I have existing API that does that. I was wondering if there could be issues that are hidden by writing code in this manner
Upvotes: 1
Views: 467
Reputation: 2814
You can absolutely do that. For example the libc does it:
ssize_t write(int fd, const void *buf, size_t count);
ssize_t read(int fd, void *buf, size_t count);
ssize_t sendto(int sockfd, const void *buf, size_t len, ...);
These functions can take a socket descriptor as first argument.
A remark on your code: before the return
, do not forget to close(fd)
.
It is recommended that you cleanly separate the functions that create, use and close the file descriptor.
Upvotes: 1