[英]Can I call bind() with a temp addr struct?
The bind()
function gets const struct sockaddr *addr
as one of parameters. bind()
函数获取const struct sockaddr *addr
作为参数之一。 Can I pass a temp sockaddr
structure, that will be deleted immediately after bind()
calling?我可以传递一个临时sockaddr
结构,它将在调用bind()
后立即删除吗?
void bindMe(int socket) {
struct sockaddr_in addr = {...};
bind(socket, (struct sockaddr_in*)&addr, sizeof(sockaddr_in));
}
// addr is no more exist after function calling,
// but I still want to work with the socket.
Also, there is a lot of function in POSIX take pointer to structs.此外,POSIX 中有很多函数都带有指向结构的指针。 How can I determine if I can free the struct after function calling?如何确定在函数调用后是否可以释放结构?
Yes, you can do that.是的,你可以这样做。 bind
is a synchronous system call, so once it returns, the kernel is all done with the parameters. bind
是一个同步系统调用,所以一旦它返回,内核就完成了所有参数。
If the socket is non-blocking and bind
returns EINPROGRESS
to indicate that the bind is happening asynchronously, it's still safe to free the struct.如果套接字是非阻塞的并且bind
返回EINPROGRESS
以指示绑定是异步发生的,那么释放结构仍然是安全的。 The kernel copies the struct internally while the operation completes asynchronously.当操作异步完成时,内核会在内部复制结构。
How can I determine if I can free the struct after function calling?如何确定在函数调用后是否可以释放结构?
Read the documentation.阅读文档。 Most POSIX functions are synchronous, and the parameters can safely be deallocated after the function returns, but that's not always true.大多数 POSIX 函数都是同步的,并且可以在函数返回后安全地释放参数,但这并不总是正确的。 If you're unsure, read the documentation.如果您不确定,请阅读文档。 And obviously if you have multiple threads in your program, you shouldn't be concurrently modifying the data from another thread while an API call is in progress.很明显,如果您的程序中有多个线程,则在 API 调用正在进行时,您不应该同时修改来自另一个线程的数据。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.