C语言(socket)close()函数(关闭文件描述符,使其不再引用任何文件并且可以重用)
Posted Dontla
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了C语言(socket)close()函数(关闭文件描述符,使其不再引用任何文件并且可以重用)相关的知识,希望对你有一定的参考价值。
man 2 close
CLOSE(2) Linux Programmer's Manual CLOSE(2)
NAME
close - close a file descriptor
SYNOPSIS
#include <unistd.h>
int close(int fd);
DESCRIPTION
close() closes a file descriptor, so that it no longer refers to any file and may be reused. Any record locks (see fcntl(2)) held on the file it was asso‐
ciated with, and owned by the process, are removed (regardless of the file descriptor that was used to obtain the lock).
//close() 关闭文件描述符,使其不再引用任何文件并且可以重用。 任何记录锁(参见 fcntl(2))在与它相关联并由进程拥有的文件上,都将被删除(无论用于获取锁的文件描述符是什么)。
If fd is the last file descriptor referring to the underlying open file description (see open(2)), the resources associated with the open file description
are freed; if the descriptor was the last reference to a file which has been removed using unlink(2), the file is deleted.
//如果 fd 是引用底层打开文件描述的最后一个文件描述符(参见 open(2)),则释放与打开文件描述相关的资源; 如果描述符是对已使用 unlink(2) 删除的文件的最后引用,则删除该文件。
RETURN VALUE
close() returns zero on success. On error, -1 is returned, and errno is set appropriately.
//close() 成功时返回零。 出错时,返回 -1,并适当设置 errno。
ERRORS
EBADF fd isn't a valid open file descriptor. //fd 不是有效的打开文件描述符。
EINTR The close() call was interrupted by a signal; see signal(7). //close() 调用被信号中断; 见信号(7)。
EIO An I/O error occurred. //发生 I/O 错误。
CONFORMING TO
POSIX.1-2001, POSIX.1-2008, SVr4, 4.3BSD.
NOTES
Not checking the return value of close() is a common but nevertheless serious programming error. It is quite possible that errors on a previous write(2)
operation are first reported at the final close(). Not checking the return value when closing the file may lead to silent loss of data. This can espe‐
cially be observed with NFS and with disk quota. Note that the return value should be used only for diagnostics. In particular close() should not be
retried after an EINTR since this may cause a reused descriptor from another thread to be closed.
//不检查 close() 的返回值是一个常见但严重的编程错误。 上一次 write(2) 操作的错误很有可能在最后的 close() 中首先报告。 关闭文件时不检查返回值可能会导致数据无声丢失。 这在 NFS 和磁盘配额中尤其明显。 请注意,返回值应仅用于诊断。 特别是 close() 不应该在 EINTR 之后重试,因为这可能会导致来自另一个线程的重用描述符被关闭。
A successful close does not guarantee that the data has been successfully saved to disk, as the kernel defers writes. It is not common for a filesystem to
flush the buffers when the stream is closed. If you need to be sure that the data is physically stored, use fsync(2). (It will depend on the disk hard‐
ware at this point.)
//成功关闭并不保证数据已成功保存到磁盘,因为内核会延迟写入。文件系统在流关闭时刷新缓冲区并不常见。如果需要确保数据是物理存储的,请使用fsync(2)。(此时将取决于磁盘硬盘。)
It is probably unwise to close file descriptors while they may be in use by system calls in other threads in the same process. Since a file descriptor may
be reused, there are some obscure race conditions that may cause unintended side effects.
//当同一进程中的其他线程中的系统调用可能正在使用文件描述符时,关闭文件描述符可能是不明智的。 由于可以重用文件描述符,因此存在一些可能导致意外副作用的模糊竞争条件。
SEE ALSO
fcntl(2), fsync(2), open(2), shutdown(2), unlink(2), fclose(3)
COLOPHON
This page is part of release 4.04 of the Linux man-pages project. A description of the project, information about reporting bugs, and the latest version
of this page, can be found at http://www.kernel.org/doc/man-pages/.
Linux 2015-08-08 CLOSE(2)
man 3 close
CLOSE(3POSIX) POSIX Programmer's Manual CLOSE(3POSIX)
PROLOG
This manual page is part of the POSIX Programmer's Manual. The Linux implementation of this interface may differ (consult the corresponding Linux manual
page for details of Linux behavior), or the interface may not be implemented on Linux.
NAME
close — close a file descriptor
SYNOPSIS
#include <unistd.h>
int close(int fildes);
DESCRIPTION
The close() function shall deallocate the file descriptor indicated by fildes. To deallocate means to make the file descriptor available for return by
subsequent calls to open() or other functions that allocate file descriptors. All outstanding record locks owned by the process on the file associated with
the file descriptor shall be removed (that is, unlocked).
If close() is interrupted by a signal that is to be caught, it shall return −1 with errno set to [EINTR] and the state of fildes is unspecified. If an I/O
error occurred while reading from or writing to the file system during close(), it may return −1 with errno set to [EIO]; if this error is returned, the
state of fildes is unspecified.
When all file descriptors associated with a pipe or FIFO special file are closed, any data remaining in the pipe or FIFO shall be discarded.
When all file descriptors associated with an open file description have been closed, the open file description shall be freed.
If the link count of the file is 0, when all file descriptors associated with the file are closed, the space occupied by the file shall be freed and the
file shall no longer be accessible.
If a STREAMS-based fildes is closed and the calling process was previously registered to receive a SIGPOLL signal for events associated with that STREAM,
the calling process shall be unregistered for events associated with the STREAM. The last close() for a STREAM shall cause the STREAM associated with
fildes to be dismantled. If O_NONBLOCK is not set and there have been no signals posted for the STREAM, and if there is data on the module's write queue,
close() shall wait for an unspecified time (for each module and driver) for any output to drain before dismantling the STREAM. The time delay can be
changed via an I_SETCLTIME ioctl() request. If the O_NONBLOCK flag is set, or if there are any pending signals, close() shall not wait for output to drain,
and shall dismantle the STREAM immediately.
If the implementation supports STREAMS-based pipes, and fildes is associated with one end of a pipe, the last close() shall cause a hangup to occur on the
other end of the pipe. In addition, if the other end of the pipe has been named by fattach(), then the last close() shall force the named end to be
detached by fdetach(). If the named end has no open file descriptors associated with it and gets detached, the STREAM associated with that end shall also
be dismantled.
If fildes refers to the master side of a pseudo-terminal, and this is the last close, a SIGHUP signal shall be sent to the controlling process, if any, for
which the slave side of the pseudo-terminal is the controlling terminal. It is unspecified whether closing the master side of the pseudo-terminal flushes
all queued input and output.
If fildes refers to the slave side of a STREAMS-based pseudo-terminal, a zero-length message may be sent to the master.
When there is an outstanding cancelable asynchronous I/O operation against fildes when close() is called, that I/O operation may be canceled. An I/O opera‐
tion that is not canceled completes as if the close() operation had not yet occurred. All operations that are not canceled shall complete as if the close()
blocked until the operations completed. The close() operation itself need not block awaiting such I/O completion. Whether any I/O operation is canceled,
and which I/O operation may be canceled upon close(), is implementation-defined.
If a memory mapped file or a shared memory object remains referenced at the last close (that is, a process has it mapped), then the entire contents of the
memory object shall persist until the memory object becomes unreferenced. If this is the last close of a memory mapped file or a shared memory object and
the close results in the memory object becoming unreferenced, and the memory object has been unlinked, then the memory object shall be removed.
If fildes refers to a socket, close() shall cause the socket to be destroyed. If the socket is in connection-mode, and the SO_LINGER option is set for the
socket with non-zero linger time, and the socket has untransmitted data, then close() shall block for up to the current linger interval until all data is
transmitted.
RETURN VALUE
Upon successful completion, 0 shall be returned; otherwise, −1 shall be returned and errno set to indicate the error.
ERRORS
The close() function shall fail if:
EBADF The fildes argument is not a open file descriptor.
EINTR The close() function was interrupted by a signal.
The close() function may fail if:
EIO An I/O error occurred while reading from or writing to the file system.
The following sections are informative.
EXAMPLES
Reassigning a File Descriptor
The following example closes the file descriptor associated with standard output for the current process, re-assigns standard output to a new file descrip‐
tor, and closes the original file descriptor to clean up. This example assumes that the file descriptor 0 (which is the descriptor for standard input) is
not closed.
#include <unistd.h>
...
int pfd;
...
close(1);
dup(pfd);
close(pfd);
...
Incidentally, this is exactly what could be achieved using:
dup2(pfd, 1);
close(pfd);
Closing a File Descriptor
In the following example, close() is used to close a file descriptor after an unsuccessful attempt is made to associate that file descriptor with a stream.
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#define LOCKFILE "/etc/ptmp"
...
int pfd;
FILE *fpfd;
...
if ((fpfd = fdopen (pfd, "w")) == NULL)
close(pfd);
unlink(LOCKFILE);
exit(1);
...
APPLICATION USAGE
An application that had used the stdio routine fopen() to open a file should use the corresponding fclose() routine rather than close(). Once a file is
closed, the file descriptor no longer exists, since the integer corresponding to it no longer refers to a file.
Implementations may use file descriptors that must be inherited into child processes for the child process to remain conforming, such as for message cata‐
log or tracing purposes. Therefore, an application that calls close() on an arbitrary integer risks non-conforming behavior, and close() can only portably
be used on file descriptor values that the application has obtained through explicit actions, as well as the three file descriptors corresponding to the
standard file streams. In multi-threaded parent applications, the practice of calling close() in a loop after fork() and before an exec call in order to
avoid a race condition of leaking an unintended file descriptor into a child process, is therefore unsafe, and the race should instead be combatted by
opening all file descriptors with the FD_CLOEXEC bit set unless the file descriptor is intended to be inherited across exec.
RATIONALE
The use of interruptible device close routines should be discouraged to avoid problems with the implicit closes of file descriptors by exec and exit().
This volume of POSIX.1‐2008 only intends to permit such behavior by specifying the [EINTR] error condition.
Note that the requirement for close() on a socket to block for up to the current linger interval is not conditional on the O_NONBLOCK setting.
The standard developers rejected a proposal to add closefrom() to the standard. Because the standard permits implementations to use inherited file descrip‐
tors as a means of providing a conforming environment for the child process, it is not possible to standardize an interface that closes arbitrary file
descriptors above a certain value while still guaranteeing a conforming environment.
FUTURE DIRECTIONS
None.
SEE ALSO
Section 2.6, STREAMS, exec, fattach(), fclose(), fdetach(), fopen(), ioctl(), open(), unlink()
The Base Definitions volume of POSIX.1‐2008, <unistd.h>
COPYRIGHT
Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2013 Edition, Standard for Information Technology -- Portable
Operating System Interface (POSIX), The Open Group Base Specifications Issue 7, Copyright (C) 2013 by the Institute of Electrical and Electronics Engi‐
neers, Inc and The Open Group. (This is POSIX.1-2008 with the 2013 Technical Corrigendum 1 applied.) In the event of any discrepancy between this version
and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be
obtained online at http://www.unix.org/online.html .
Any typographical or formatting errors that appear in this page are most likely to have been introduced during the conversion of the source files to man
page format. To report such errors, see https://www.kernel.org/doc/man-pages/reporting_bugs.html .
IEEE/The Open Group 2013 CLOSE(3POSIX)
以上是关于C语言(socket)close()函数(关闭文件描述符,使其不再引用任何文件并且可以重用)的主要内容,如果未能解决你的问题,请参考以下文章
如何使用c语言的sc_close禁用messageboxa win32函数中的关闭按钮?
为啥在c++编程中,用close()关闭socket 的端口号时,提示close找不到标识符,我