Share to: share facebook share twitter share wa share telegram print page

File descriptor

In Unix and Unix-like computer operating systems, a file descriptor (FD, less frequently fildes) is a process-unique identifier (handle) for a file or other input/output resource, such as a pipe or network socket.

File descriptors typically have non-negative integer values, with negative values being reserved to indicate "no value" or error conditions.

File descriptors are a part of the POSIX API. Each Unix process (except perhaps daemons) should have three standard POSIX file descriptors, corresponding to the three standard streams:

Integer value Name <unistd.h> symbolic constant[1] <stdio.h> file stream[2]
0 Standard input STDIN_FILENO stdin
1 Standard output STDOUT_FILENO stdout
2 Standard error STDERR_FILENO stderr

Overview

File descriptors for a single process, file table and inode table. Note that multiple file descriptors can refer to the same file table entry (e.g., as a result of the dup system call[3]: 104 ) and that multiple file table entries can in turn refer to the same inode (if it has been opened multiple times; the table is still simplified because it represents inodes by file names, even though an inode can have multiple names). File descriptor 3 does not refer to anything in the file table, signifying that it has been closed.

In the traditional implementation of Unix, file descriptors index into a per-process file descriptor table maintained by the kernel, that in turn indexes into a system-wide table of files opened by all processes, called the file table. This table records the mode with which the file (or other resource) has been opened: for reading, writing, appending, and possibly other modes. It also indexes into a third table called the inode table that describes the actual underlying files.[3] To perform input or output, the process passes the file descriptor to the kernel through a system call, and the kernel will access the file on behalf of the process. The process does not have direct access to the file or inode tables.

On Linux, the set of file descriptors open in a process can be accessed under the path /proc/PID/fd/, where PID is the process identifier. File descriptor /proc/PID/fd/0 is stdin, /proc/PID/fd/1 is stdout, and /proc/PID/fd/2 is stderr. As a shortcut to these, any running process can also access its own file descriptors through the folders /proc/self/fd and /dev/fd.[4]

In Unix-like systems, file descriptors can refer to any Unix file type named in a file system. As well as regular files, this includes directories, block and character devices (also called "special files"), Unix domain sockets, and named pipes. File descriptors can also refer to other objects that do not normally exist in the file system, such as anonymous pipes and network sockets.

The FILE data structure in the C standard I/O library usually includes a low level file descriptor for the object in question on Unix-like systems. The overall data structure provides additional abstraction and is instead known as a file handle.

Operations on file descriptors

The following lists typical operations on file descriptors on modern Unix-like systems. Most of these functions are declared in the <unistd.h> header, but some are in the <fcntl.h> header instead.

Creating file descriptors

  • open()
  • creat()[5]
  • socket()
  • accept()
  • socketpair()
  • pipe()
  • epoll_create() (Linux)
  • signalfd() (Linux)
  • eventfd() (Linux)
  • timerfd_create() (Linux)
  • memfd_create() (Linux)
  • userfaultfd() (Linux)
  • fanotify_init() (Linux)
  • inotify_init() (Linux)
  • clone() (with flag CLONE_PIDFD, Linux)
  • pidfd_open() (Linux)
  • open_by_handle_at() (Linux)
  • kqueue() (BSD)
  • pdfork() (kFreeBSD)

Deriving file descriptors

  • dirfd()
  • fileno()

Operations on a single file descriptor

  • read(), write()
  • readv(), writev()
  • pread(), pwrite()
  • recv(), send()
  • recvfrom(), sendto()
  • recvmsg(), sendmsg() (also used for sending FDs to other processes over a Unix domain socket)
  • recvmmsg(), sendmmsg()
  • lseek(), llseek()
  • fstat()
  • fstatvfs()
  • fchmod()
  • fchown()
  • ftruncate()
  • fsync()
  • fdatasync()
  • fdopendir()
  • fgetxattr(), fsetxattr() (Linux)
  • flistxattr(), fremovexattr() (Linux)
  • statx (Linux)
  • setns (Linux)
  • vmsplice() (Linux)
  • pidfd_send_signal() (Linux)
  • pdkill() (kFreeBSD)
  • waitid() (with P_PIDFD ID type, Linux)
  • fdopen() (stdio function:converts file descriptor to FILE*)
  • dprintf() (stdio function: prints to file descriptor)

Operations on multiple file descriptors

  • select(), pselect()
  • poll(), ppoll()
  • epoll_wait(), epoll_pwait(), epoll_pwait2() (Linux, takes a single epoll filedescriptor to wait on many other file descriptors)
  • epoll_ctl() (for Linux)
  • kqueue() (for BSD-based systems).
  • sendfile()
  • splice(), tee() (for Linux)
  • copy_file_range() (for Linux)

Operations on the file descriptor table

The fcntl() function is used to perform various operations on a file descriptor, depending on the command argument passed to it. There are commands to get and set attributes associated with a file descriptor, including F_GETFD, F_SETFD, F_GETFL and F_SETFL.

  • close()
  • closefrom() (BSD and Solaris only; deletes all file descriptors greater than or equal to specified number)
  • close_range() (for Linux)[6]
  • dup() (duplicates an existing file descriptor guaranteeing to be the lowest number available file descriptor)
  • dup2(), dup3() (Close fd1 if necessary, and make file descriptor fd1 point to the open file of fd2)
  • fcntl (F_DUPFD)

Operations that modify process state

  • fchdir() (sets the process's current working directory based on a directory file descriptor)
  • mmap() (maps ranges of a file into the process's address space)

File locking

  • flock()
  • fcntl() (F_GETLK, F_SETLK and F_SETLKW)
  • lockf()

Sockets

  • connect()
  • bind()
  • listen()
  • accept() (creates a new file descriptor for an incoming connection)
  • getsockname()
  • getpeername()
  • getsockopt()
  • setsockopt()
  • shutdown() (shuts down one or both halves of a full duplex connection)

Miscellaneous

  • ioctl() (a large collection of miscellaneous operations on a single file descriptor, often associated with a device)

Upcoming operations

A series of new operations on file descriptors has been added to many modern Unix-like systems, as well as numerous C libraries, to be standardized in a future version of POSIX.[7] The at suffix signifies that the function takes an additional first argument supplying a file descriptor from which relative paths are resolved, the forms lacking the at suffix thus becoming equivalent to passing a file descriptor corresponding to the current working directory. The purpose of these new operations is to defend against a certain class of TOCTOU attacks.

  • openat()
  • faccessat()
  • fchmodat()
  • fchownat()
  • fstatat()
  • futimesat()
  • linkat()
  • mkdirat()
  • mknodat()
  • readlinkat()
  • renameat()
  • symlinkat()
  • unlinkat()
  • mkfifoat()
  • fdopendir()

File descriptors as capabilities

Unix file descriptors behave in many ways as capabilities. They can be passed between processes across Unix domain sockets using the sendmsg() system call. Note, however, that what is actually passed is a reference to an "open file description" that has mutable state (the file offset, and the file status and access flags). This complicates the secure use of file descriptors as capabilities, since when programs share access to the same open file description, they can interfere with each other's use of it by changing its offset or whether it is blocking or non-blocking, for example.[8][9] In operating systems that are specifically designed as capability systems, there is very rarely any mutable state associated with a capability itself.

A Unix process' file descriptor table is an example of a C-list.

See also

References

  1. ^ The Open Group. "The Open Group Base Specifications Issue 7, IEEE Std 1003.1-2008, 2016 Edition". Retrieved 2017-09-21.
  2. ^ The Open Group. "The Open Group Base Specifications Issue 7, IEEE Std 1003.1-2008, 2016 Edition". <stdio.h>. Retrieved 2017-09-21.
  3. ^ a b Bach, Maurice J. (1986). The Design of the UNIX Operating System (8 ed.). Prentice-Hall. pp. 92–96. ISBN 9780132017992.
  4. ^ "Devices - What does the output of 'll /Proc/Self/Fd/' (From 'll /Dev/Fd') mean?".
  5. ^ The Open Group. "The Open Group Base Specifications Issue 7, IEEE Std 1003.1-2008, 2018 Edition – creat". Retrieved 2019-04-11.
  6. ^ Stephen Kitt, Michael Kerrisk. "close_range(2) — Linux manual page". Retrieved 2021-03-22.
  7. ^ Extended API Set, Part 2. The Open Group. October 2006. ISBN 1931624674.
  8. ^ Brinkmann, Marcus (2009-02-04). "Building a bridge: library API's and file descriptors?". cap-talk. Archived from the original on 2012-07-30. Retrieved 2017-09-21.
  9. ^ de Boyne Pollard, Jonathan (2007). "Don't set shared file descriptors to non-blocking I/O mode". Retrieved 2017-09-21.

Read other articles:

يفتقر محتوى هذه المقالة إلى الاستشهاد بمصادر. فضلاً، ساهم في تطوير هذه المقالة من خلال إضافة مصادر موثوق بها. أي معلومات غير موثقة يمكن التشكيك بها وإزالتها. (ديسمبر 2018) هذه المقالة يتيمة إذ تصل إليها مقالات أخرى قليلة جدًا. فضلًا، ساعد بإضافة وصلة إليها في مقالات متعلقة بها...

OPC UA TSN или OPC UA over TSN — технология передачи данных в режиме реального времени, объединяющая два стандарта: спецификация OPC UA определяет передачу данных в промышленных сетях, а технология TSN описывает работу сетей, требующих строгой синхронизации времени и детерминирован

Карта Яшчилана Одна из пирамид на верхней террасе Яшчилана В список включены все правители Яшчилана, столицы государства Пачан. Яшчилан (от юкатек. Yaxchilán — букв. «зелёные камни»)[комм. 1] представляет собой городище классического периода, находится в западной части

Perang ToyotaBagian dari the Konflik Chad-LibyaTentara Chad di mobil pengangkut Toyota Land Cruiser tahun 2008.Tanggal16 Desember 1986 – 11 September 1987LokasiBorkou-Ennedi-Tibesti, ChadHasil Kemenangan ChadPihak terlibat  Libya  Chad PrancisTokoh dan pemimpin Muammar al-Gaddafi Hissène Habré Hassan DjamousKekuatan 90.000 800+ Tank dan APC 29,500[1]Korban 7.000+ terbunuh1.000 tawanan perang392+ tank dan APC28 pesawat tempur[2] 1.000+ terbunuh[2] Per...

PT Panin Sekuritas TbkSebelumnyaPT Panin Sekuritasindo (1989 - 1991)PT Nusamas Panin (1991 - 1995)JenisPerusahaan publikKode emitenIDX: PANSIndustriJasa keuanganDidirikan27 Juli 1989; 34 tahun lalu (1989-07-27)KantorpusatJakarta, IndonesiaWilayah operasiIndonesiaTokohkunciIndra Christanto[1](Direktur Utama)Mu'min Ali Gunawan[2](Komisaris Utama)JasaTransaksi sekuritasPembiayaan nasabahKeuangan korporasiRisetManajemen asetPendapatanRp 424,23 milyar (2021)[3]Laba ber...

Вілла-Ада 41°55′55″ пн. ш. 12°30′05″ сх. д. / 41.93203900002777829° пн. ш. 12.501497000027779194° сх. д. / 41.93203900002777829; 12.501497000027779194Координати: 41°55′55″ пн. ш. 12°30′05″ сх. д. / 41.93203900002777829° пн. ш. 12.501497000027779194° сх. д. / 41.93203900002777829; 12.501497000027779194...

Мирний воїнPeaceful Warrior Жанр драматичний фільм[1][2][3], екранізація літературного твору[d] і кіноромантикаРежисер Віктор СалваПродюсер Robin SchorrMark AminDavid WelchCami WinikoffСценарист Kevin BernhardtДен Мілман (novel)На основі Way of the Peaceful WarriordУ головних ролях Скотт МекловіцНік Н

Crescent City Connection Localización geográficaCruza Río MisisipiCoordenadas 29°56′19″N 90°03′27″O / 29.9386, -90.0575Localización administrativaPaís Estados UnidosLocalidad Nueva OrleansCaracterísticasTipo en ménsulaUso 8 carriles de la US 90 2 carriles reversibles HOVLargo 4093 mAncho 16 m (oeste) 28 m (92 pies) (este)Vano mayor 480 metrosTráfico 180,000[1]​Mantenido por LA DOTD, Crescent City Connection DivisiónHistoriaInauguración Abril...

Subsidiary of Prada Italian fashion house For the French actress, see Miou-Miou. Miu MiuTypeSubsidiaryIndustryFashionFounded1993; 30 years ago (1993) in ItalyFoundersMiuccia Prada[1]HeadquartersMilan, ItalyRevenue 166 million euros (2021)[2]ParentPradaWebsitemiumiu.com Miu Miu is an Italian high fashion women's clothing and accessory brand and a fully owned subsidiary of Prada. It is headed by Miuccia Prada and headquartered in Milan, Italy. History Miu Miu s...

The Blind SidePoster film The Blind SideSutradara John Lee Hancock Produser Broderick Johnson Andrew Kosove Gil Netter Ditulis oleh John Lee Hancock BerdasarkanThe Blind Side: Evolution of a Gameoleh Michael LewisPemeranSandra BullockTim McGrawQuinton AaronJae HeadLily CollinsKathy BatesPenata musikCarter BurwellSinematograferAlar KiviloPenyuntingMark LivolsiPerusahaanproduksiAlcon EntertainmentDistributorWarner Bros PicturesTanggal rilis 17 November 2009 (2009-11-17) (New York...

سمو الشيخ مكتوم بن محمد بن راشد آل مكتوم   النائب الأول لحاكم دبي في المنصب28 أبريل 2023 – حتى الأن الحاكم محمد بن راشد آل مكتوم نائب رئيس مجلس الوزراء في المنصب25 سبتمبر 2021 – حتى الآن الرئيس خليفة بن زايد آل نهيانمحمد بن زايد آل نهيان رئيس الوزراء محمد بن راشد آل مكتوم وزير ا...

This article is about the island. For the region, see Cabugao. Cabugao IslandNative name: Cabugao GamayCabugao IslandLocation within the PhilippinesGeographyLocationVisayan SeaCoordinates11°34′5″N 123°20′52″E / 11.56806°N 123.34778°E / 11.56806; 123.34778ArchipelagoIslas de GigantesHighest elevation357 ft (108.8 m)[1]AdministrationPhilippinesRegionWestern VisayasProvinceIloiloMunicipalityCarlesDemographicsPopulationuninhabited Cabugao...

Not to be confused with O05 or 005 (disambiguation). This article is in list format but may read better as prose. You can help by converting this article, if appropriate. Editing help is available. (October 2015) Airport in Unincorporated Yolo County near Davis, CaliforniaUniversity AirportIATA: noneICAO: KEDUFAA LID: EDUSummaryAirport typePublicOwnerUniversity of CaliforniaLocationUnincorporated Yolo County near Davis, CaliforniaElevation AMSL69 ft / 21 mCoordinates38°31′53...

Low-cost airline of the United Arab Emirates Wizz Air Abu Dhabi IATA ICAO Callsign 5W WAZ WIZZ SKY[1] Founded12 December 2019; 3 years ago (2019-12-12)Operating basesAbu Dhabi International AirportFleet size11Destinations31[2]HeadquartersAbu Dhabi, United Arab EmiratesWebsitewww.wizzair.com Wizz Air Abu Dhabi is an Emirati low-cost airline based at Abu Dhabi International Airport, UAE. The airline is a joint venture with state-owned ADQ[3] (formerly, ...

Stephan, John J. (1978). The Russian Fascists: Tragedy and Farce in Exile, 1925-1945. Harper & Row. pp. 337–340. ISBN 978-0-06-014099-1. This article has multiple issues. Please help improve it or discuss these issues on the talk page. (Learn how and when to remove these template messages) This article needs additional citations for verification. Please help improve this article by adding citations to reliable sources. Unsourced material may be challenged and removed.Find sour...

Artikel ini sebatang kara, artinya tidak ada artikel lain yang memiliki pranala balik ke halaman ini.Bantulah menambah pranala ke artikel ini dari artikel yang berhubungan atau coba peralatan pencari pranala.Tag ini diberikan pada Januari 2023. Menesia longipes Klasifikasi ilmiah Kerajaan: Animalia Filum: Arthropoda Kelas: Insecta Ordo: Coleoptera Famili: Cerambycidae Genus: Menesia Spesies: Menesia longipes Menesia longipes adalah spesies kumbang tanduk panjang yang tergolong famili Cerambyc...

This article does not cite any sources. Please help improve this article by adding citations to reliable sources. Unsourced material may be challenged and removed.Find sources: Cyprus–Finland relations – news · newspapers · books · scholar · JSTOR (October 2021) (Learn how and when to remove this template message) The topic of this article may not meet Wikipedia's general notability guideline. Please help to demonstrate the notability of the topic by...

Untuk aktor dan penyanyi Indonesia dengan nama yang mirip secara homofonik, lihat Ari Wibowo. Untuk penyanyi Indonesia dengan nama yang mirip secara homofonik, lihat Arie Wibowo. Tungki AriwibowoMenteri Perindustrian dan Perdagangan Indonesia ke-15Masa jabatan17 Maret 1993 – 16 Maret 1998PresidenSoehartoPendahuluHartarto Sastrosoenarto Satrio BudihardjoPenggantiMuhammad Bob Hasan Informasi pribadiLahir(1936-12-13)13 Desember 1936Malang, Hindia BelandaMeninggal3 Maret 2007(2007-...

Private university in Metro Manila, Philippines This article needs additional citations for verification. Please help improve this article by adding citations to reliable sources. Unsourced material may be challenged and removed.Find sources: AMA University – news · newspapers · books · scholar · JSTOR (January 2023) (Learn how and when to remove this template message) AMA UniversityPamantasang AMAFormer namesAMA Institute of Computer Studies (1980-200...

This is a list of people and topics appearing on the cover of Time magazine in the 1990s. Time was first published in 1923. As Time became established as one of the United States' leading news magazines, an appearance on the cover of Time became an indicator of notability, fame or notoriety. Such features were accompanied by articles. For other decades, see Lists of covers of Time magazine. 1990 Date Names or topics January 1 Mikhail Gorbachev, Man of the Decade January 8 Rumania & Panama...

Kembali kehalaman sebelumnya