Fstat взять статус файла


Содержание

OpenSource в заметках

В предыдущей статье мы с вами знакомились с термином ‘inode’ и о роли индексных дескрипторов в жизни файловой системы. Однако мы не рассмотрели того, как получить подробную информацию о том, сколько всего inode доступно в файловой системе, а также сколько свободных осталось. Это и многое другое можно узнать при помощи утилиты stat.

Утилита stat является частью GNU Coreutils, а значит должна быть доступна в любом современном Linux-дистрибутиве. Задачей stat является вывод информации об одном или более файлов, а также о файловых системах. При помощи утилиты вы сможете узнать, например, сколько блоков диска выделено для хранения файла, сколько индексных дескрипторов доступно на той или иной ФС, а также многое другое. Основным преимуществом stat является то, что вы можете получать информацию в любом удобном для вас виде, что даёт возможность очень легко получать нужные данные и манипулировать ими в сценариях оболочки.

В общем случае формат вызова stat таков:

Давайте, например, посмотрим на вывод информации о /etc/passwd:

Из полученного вывода можно определить следующее:

  • файл имеет размер 2154 байта, занимает восемь 512-байтных блоков ;
  • размер блока ФС, на которой расположен файл, при операциях ввода/вывода составляет 4 килобайта;
  • идентификатор устройства, на котором расположен файл: 802h (шестнадцатеричный) или 2050d (десятичный);
  • номер индексного дескриптора файла — 786548;
  • файл не имеет жёстких ссылок (одна ссылка в отчёте stat — и есть сам файл);
  • режим доступа к файлу: 0644;
  • владелец файла — root, группа-владелец — root;
  • время последнего доступа к файлу: 2011-06-20 19:00:01;
  • время последнего изменения файла: 2011-05-24 20:39:21;
  • время последнего изменения индексного дескриптора файла: 2011-05-24 20:39:21;

Как уже говорилось, вы можете явно определять, какую информацию нужно выводить, а какую нет. Для этих целей в программе предусмотрена опция ‘—printf’, после которой необходимо указать нужный вам формат вывода. Например, следующая команда выведет, разделив знаком табуляции: имя файла, его размер в байтах, размер в блоках, номер его inode и тип файла с точки зрения ОС. Вывод будет завершён символом новой строки:

Подобным образом вы можете выводить информацию сразу о нескольких файлах, перечислив пути к ним в качестве аргументов:

или же, естественно, вы можете использовать wildcards оболочки:

Подробную информацию обо всех возможных параметрах, которые можно перечислять в опции ‘—format‘ можно получить на странице руководства утилиты.

stat может быть использована также для получения информации о файловых системах. Для этого программе нужно передать опцию ‘-f’:

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

  • идентификатор файловой системы: 5d2e58a2f8a69ac2;
  • максимальная длина имени файла: 255 символов;
  • тип ФС: ext2/ext3;
  • размер блока: 4 килобайта;
  • общее количество блоков: 3844964, свободных: 1684534, доступных не суперпользователю: 1489222;
  • общее количество индексных дескрипторов: 977280, свободных: 510081.

Так же, как и при выводе информации о файлах, в случае с данными о файловой системе вы можете указать программе желаемый формат при выводе. Например, следующая команда выедет, разделив табуляцией, идентификатор ФС, количество свободных inode и количество свободных блоков, завершив вывод символом новой строки:

BSDPORTAL.RU

На этом сайте обсуждаются вопросы использования ОС FreeBSD

Часовой пояс: UTC + 4 часа

Как посмотреть список открытых файлов? fstat не предлагать

Страница 1 из 1 [ Сообщений: 5 ]
Автор Сообщение
100chuk
Зарегистрирован: Ср 18 фев, 2009 4:09 pm
Сообщения: 9

Надеюсь что в форуме для новичков смогут ответить на этот вопрос. )

Необходимо посмотреть, что именно грузит диски сервера (по gstat периодически загрузка 100%). Apache и mysql прооптимизированы (кэши, nginx, eaccelerator).
fstat никакой ценной информации не дает, т.к. не показываются имена файлов, а перебирать список из нескольких сот записей нереально.

Может кто-нибудь знает утилиты, которыми можно нормально промониторить?

Вернуться к началу
Зарегистрирован: Сб 26 июн, 2004 2:21 pm
Сообщения: 3567
Откуда: Рига

это поподробнее fstat

Port: lsof-4.82A,3
Path: /usr/ports/sysutils/lsof
Info: Lists information about open files (similar to fstat(1))
Maint: ler@lerctr.org
B-deps:
R-deps:
WWW: http://people.freebsd.org/

Вернуться к началу Зарегистрирован: Ср 18 фев, 2009 4:09 pm
Сообщения: 9

Спасибо, это уже лучше.

Правда пока утилита отрабатывает на большом числе каталогов, теряется динамическая картинка. В идеале было бы иметь что-то работающее в режиме gstat или top (т.е. непрерывно) и показывающее какие в данную секунду файлы открываются. Но я так понимаю я уже слишком многого хочу.

Fstat взять статус файла

НАЗВАНИЕ
stat, fstat — получение статуса файла

ОПИСАНИЕ
Аргумент path указывает на маршрутное имя файла. Не требуется наличие прав доступа на чтение, запись и выполнение заданного файла, но все каталоги, перечисленные перед именем файла в маршрутном имени, должны быть доступны на поиск. Системный вызов stat предоставляет информацию о поименованном файле.

Системный вызов fstat предоставляет информацию об открытом файле, задаваемом с помощью дескриптора файла fildes, который возвращается успешно завершенными системными вызовами open, creat, dup, fcntl или pipe.

Аргумент buf является указателем на стуктуру типа stat, в которую помещается информация о файле.

Структура, на которую указывает buf, содержит следующие поля: st_mode Режим файла согласно определению, данному при описании системного вызова mknod(2). st_ino Это поле однозначно определяет файл в данной файловой системе. Пара (st_ino, st_dev) однозначно определяет обычные файлы. st_dev Это поле однозначно определяет файловую систему, содержащую файл. Значение поля может использоваться в качестве входного аргумента системного вызова ustat(2) при получении дополнительной информации об этой файловой системе. Никакого другого смысла это поле не имеет. st_rdev Это поле следует использовать только для команд администратора. Оно имеет смысл лишь для специальных блочных и символьных файлов и только в той системе, где файл был сконфигурирован. st_nlink Это поле следует использовать только для команд администратора. st_uid Идентификатор владельца файла. st_gid Идентификатор группы владельца файла. st_size Для обычных файлов это адрес конца файла. Для каналов это текущее количество данных в файле. Для специальных блочных и символьных файлов значение поля не определено. st_atime Время последнего доступа к данным. Это поле изменяется следующими системными вызовами: creat(2), mknod(2), pipe(2), utime(2) и read(2). st_mtime Время последней модификации данных. Это поле изменяется следующими системными вызовами: creat(2), mknod(2), pipe(2), utime(2) и write(2). st_ctime Время последнего изменения статуса файла. Это поле изменяется следующими системными вызовами: chmod(2), chown(2), creat(2), link(2), mknod(2), pipe(2), unlink(2), utime(2) и write(2).

Системный вызов stat завершается неудачей, если выполнено хотя бы одно из следующих условий: [ENOTDIR] Компонент маршрута не является каталогом. [ENOENT] Заданный файл не существует. [EACCES] Нет права на поиск для компонента маршрута. [EFAULT] Аргументы buf или path указывают за пределы отведенного процессу адресного пространства. [EINTR] Во время выполнения системного вызова перехвачен сигнал. [ENOLINK] Маршрутное имя path указывает на удаленный компьютер, связи с которым в данный момент нет. [EMULTIHOP] Компоненты path требуют многократного обращения к удаленным компьютерам.

Системный вызов fstat завершается неудачей, если выполнено хотя бы одно из следующих условий: [EBADF] Аргумент fildes не является корректным дескриптором открытого файла. [EFAULT] Аргументы buf или path указывают за пределы отведенного процессу адресного пространства. [ENOLINK] Дескриптор файла fildes указывает на удаленный компьютер, связи с которым в данный момент нет.

Формат файла .STATUS

Как открыть файл .STATUS?

Если файл .STATUS известен Вашей системе, то открыть его можно двойным нажатием мышкой или клавишей ENTER. Эта операция запустит ассоциируемые с файлом .STATUS аппликации, установленные в системе. Если система встречает файл впервые и отсутствуют соответствующие ассоциации, то акция закончится предложением системы, найти соответствующее программное обеспечение в компьютере либо сети интернет.

Иногда случается, что для обслуживания типа файлов .STATUS приписана неправильная программа. Это случается в следствии действия враждебных программ, таких как вирусы или вредоносные программы, но чаще всего это результат ошибочного совмещения аппликации с расширением файла .STATUS. Если во время обслуживания нового типа файлов .STATUS мы укажем системе неправильную программу, то система ошибочно будет рекомендовать ее использование всякий раз, когда будет встречаться файл этого типа. В таком случае следует попробовать повторно выбрать соответствующую аппликацию. Нажмите правой кнопкой мышки на файл .STATUS, а затем выберите из меню опцию «Открыть с помощью. » затем «Выбрать программу по умолчанию» . Сейчас выберите одну из установленных аппликаций из вышеуказанного списка и попробуйте снова.

Windows

Ручное редактирование Реестра Windows

Если наша система не справляется с расширением .STATUS и подвели все автоматические и полуавтоматические методы обучения его этому искусству, остается ручное редактирование реестра Windows. Этот реестр хранит всю информацию, касающуюся рабоы нашей операционной системы, в том числе соединения расширений файлов с программами для их обслуживания. Команда REGEDIT вписанная в окне „поиск программ и файлов” или „запустить в случае старших версий операционной системы, предоставляет нам доступ к реестру нашей операционной системы. Все операции, проведенные в реестре (даже не очень сложные, касающееся расширения файла .STATUS) имеют значительное влияние на работу нашей системы, поэтому прежде чем проводить какие-либо модификации следует убедится, что сделана копия актуального реестра. Интересующий нас раздел — это ключ HKEY_CLASSES_ROOT. Следующая инструкция показывает, шаг за шагом, как модифицировать реестр, а конкретно запись в реестре, содержащую информацию о файле .STATUS.

Программирование C — Как получить размер файла?

Как оказалось, узнать размер файла в языке C — совсем нетривиальная задача. В процессе её решения как минимум вы обязательно столкнетесь с переполнением целочисленного типа данных. В данной статье я приведу 4 способа получения размера файла с использованием функций из стандартной библиотеки C, функций из библиотеки POSIX и функций из библиотек Windows.
Способ 1: решение «в лоб» (скомпилируется везде, но работает очень долго)
Мы просто откроем файл в бинарном режиме и в цикле считаем из него байт за байтом.

Очевидным недостатком способа является скорость работы. Если у нас файл будет на много гигабайт, то только размер файла будет считаться относительно долго (это сколько байт то надо считать?), а надо же еще остальную программу выполнять.
Достоинство такого способа — работать должен на любой платформе. Ну и конечно можно ускорить процесс за счет считывания бОльшего количества байт.

Способ 2: с использованием функций fseek и ftell (ограничен для объемных файлов и работает не всегда верно)

Данный способ основан на использовании функций стандартной библиотеки C: fseek и ftell. Что происходит — открываем файл в бинарном режиме, перемещаем внутренний указатель положения в файле сразу в конец с помощью fseek, получаем номер последнего байта с помощью ftell.

Проблем у данного способа несколько.
Первое — это возвращаемый тип функции ftell. У разных компиляторов на разных платформах по разному. Если у вас 32х битная система, то данный способ будет работать только для файлов, размером меньше 2048 Мб, поскольку максимальное значение для возвращаемого функцией типа long там будет 2147483647. На системах с большей разрядностью будет работать лучше, из-за большего значения максимума для long. Но подобная нестабильность будет мешать. Хотя у меня на 64х битой системе на компиляторе gcc данный способ для файлов больше 8 Гб выводил некорректные значения.
Второе — гарантированность работы fseek и ftell. Коротко говоря, на разных платформах работает по-разному. Где то будет точно возвращать значение положения последнего байта, где то будет возвращать неверное значение. То есть точность данного способа негарантированна.

Плюсом является то, что эти функции из стандартной библиотеки — скомпилируется почти везде.

Стоит сказать, что хитрые инженеры из Microsoft придумали функции _fseeki64 и _ftelli64, которые, как понятно из их названия, работают с int64, что решает проблему с размером файла в MSVC под Windows.

Способ 3: (под Linux (POSIX))

Данный способ основан на использовании системном вызове fstat с использованием специальной структуры struct stat. Как работает: открываем файл через open() или fopen(), вызываем fstat для дескриптора файла (если открыли через fopen, то в fstat надо положить результат fileno от указателя потока FILE), указав на буферную структуру для результатов, и получаем значения поля буферной структуры st_size.

fstat(2) — Linux man page

stat, fstat, lstat — get file status

Synopsis

int stat(const char *path, struct stat *buf);
int fstat(int
fd, struct stat *buf);
int lstat(const char *
path, struct stat *buf);

Feature Test Macro Requirements for glibc (see feature_test_macros(7)): lstat(): _BSD_SOURCE || _XOPEN_SOURCE >= 500 || _XOPEN_SOURCE && _XOPEN_SOURCE_EXTENDED
|| /* Since glibc 2.10: */ _POSIX_C_SOURCE >= 200112L

Description

These functions return information about a file. No permissions are required on the file itself, but-in the case of stat() and lstat() — execute (search) permission is required on all of the directories in path that lead to the file.

stat() stats the file pointed to by path and fills in buf.

lstat() is identical to stat(), except that if path is a symbolic link, then the link itself is stat-ed, not the file that it refers to.

fstat() is identical to stat(), except that the file to be stat-ed is specified by the file descriptor fd.

All of these system calls return a stat structure, which contains the following fields: The st_dev field describes the device on which this file resides. (The major(3) and minor(3) macros may be useful to decompose the device ID in this field.)

The st_rdev field describes the device that this file (inode) represents.

The st_size field gives the size of the file (if it is a regular file or a symbolic link) in bytes. The size of a symbolic link is the length of the pathname it contains, without a terminating null byte.

The st_blocks field indicates the number of blocks allocated to the file, 512-byte units. (This may be smaller than st_size/512 when the file has holes.)

The st_blksize field gives the «preferred» blocksize for efficient file system I/O. (Writing to a file in smaller chunks may cause an inefficient read-modify-rewrite.)

Not all of the Linux file systems implement all of the time fields. Some file system types allow mounting in such a way that file and/or directory accesses do not cause an update of the st_atime field. (See noatime, nodiratime, and relatime in mount(8), and related information in mount(2).) In addition, st_atime is not updated if a file is opened with the O_NOATIME; see open(2).

The field st_atime is changed by file accesses, for example, by execve(2), mknod(2), pipe(2), utime(2) and read(2) (of more than zero bytes). Other routines, like mmap(2), may or may not update st_atime.

The field st_mtime is changed by file modifications, for example, by mknod(2), truncate(2), utime(2) and write(2) (of more than zero bytes). Moreover, st_mtime of a directory is changed by the creation or deletion of files in that directory. The st_mtime field is not changed for changes in owner, group, hard link count, or mode.

The field st_ctime is changed by writing or by setting inode information (i.e., owner, group, link count, mode, etc.).

The following POSIX macros are defined to check the file type using the st_mode field: S_ISREG(m)

is it a regular file?

FIFO (named pipe)?

symbolic link? (Not in POSIX.1-1996.)

socket? (Not in POSIX.1-1996.) The following flags are defined for the st_mode field: The set-group-ID bit (S_ISGID) has several special uses. For a directory it indicates that BSD semantics is to be used for that directory: files created there inherit their group ID from the directory, not from the effective group ID of the creating process, and directories created there will also get the S_ISGID bit set. For a file that does not have the group execution bit (S_IXGRP) set, the set-group-ID bit indicates mandatory file/record locking.

The sticky bit (S_ISVTX) on a directory means that a file in that directory can be renamed or deleted only by the owner of the file, by the owner of the directory, and by a privileged process.

Return Value

On success, zero is returned. On error, -1 is returned, and errno is set appropriately.

Errors

Search permission is denied for one of the directories in the path prefix of path. (See also path_resolution(7).)

Too many symbolic links encountered while traversing the path. ENAMETOOLONG path is too long. ENOENT

A component of path does not exist, or path is an empty string.

Out of memory (i.e., kernel memory). ENOTDIR A component of the path prefix of path is not a directory. EOVERFLOW path or fd refers to a file whose size, inode number, or number of blocks cannot be represented in, respectively, the types off_t, ino_t, or blkcnt_t. This error can occur when, for example, an application compiled on a 32-bit platform without -D_FILE_OFFSET_BITS=64 calls stat() on a file whose size exceeds (1

Conforming To

These system calls conform to SVr4, 4.3BSD, POSIX.1-2001.

According to POSIX.1-2001, lstat() on a symbolic link need return valid information only in the st_size field and the file-type component of the st_mode field of the stat structure. POSIX.-2008 tightens the specification, requiring lstat() to return valid information in all fields except the permission bits in st_mode.

Use of the st_blocks and st_blksize fields may be less portable. (They were introduced in BSD. The interpretation differs between systems, and possibly on a single system when NFS mounts are involved.) If you need to obtain the definition of the blkcnt_t or blksize_t types from , then define _XOPEN_SOURCE with the value 500 or greater (before including any header files).

POSIX.1-1990 did not describe the S_IFMT, S_IFSOCK, S_IFLNK, S_IFREG, S_IFBLK, S_IFDIR, S_IFCHR, S_IFIFO, S_ISVTX constants, but instead demanded the use of the macros S_ISDIR(), etc. The S_IF* constants are present in POSIX.1-2001 and later.

The S_ISLNK() and S_ISSOCK() macros are not in POSIX.1-1996, but both are present in POSIX.1-2001; the former is from SVID 4, the latter from SUSv2.

UNIX V7 (and later systems) had S_IREAD, S_IWRITE, S_IEXEC, where POSIX prescribes the synonyms S_IRUSR, S_IWUSR, S_IXUSR.

Other systems Values that have been (or are) in use on various systems: A sticky command appeared in Version 32V AT&T UNIX.

Notes

Since kernel 2.5.48, the stat structure supports nanosecond resolution for the three file timestamp fields. Glibc exposes the nanosecond component of each field using names of the form st_atim.tv_nsec if the _BSD_SOURCE or _SVID_SOURCE feature test macro is defined. These fields are specified in POSIX.1-2008, and, starting with version 2.12, glibc also exposes these field names if _POSIX_C_SOURCE is defined with the value 200809L or greater, or _XOPEN_SOURCE is defined with the value 700 or greater. If none of the aforementioned macros are defined, then the nanosecond values are exposed with names of the form st_atimensec. On file systems that do not support subsecond timestamps, the nanosecond fields are returned with the value 0.

On Linux, lstat() will generally not trigger automounter action, whereas stat() will (but see fstatat(2)).

For most files under the /proc directory, stat() does not return the file size in the st_size field; instead the field is returned with the value 0.

Underlying kernel interface Over time, increases in the size of the stat structure have led to three successive versions of stat(): sys_stat() (slot __NR_oldstat), sys_newstat() (slot __NR_stat), and sys_stat64() (new in kernel 2.4; slot __NR_stat64). The glibc stat() wrapper function hides these details from applications, invoking the most recent version of the system call provided by the kernel, and repacking the returned information if required for old binaries. Similar remarks apply for fstat() and lstat().

Example

The following program calls stat() and displays selected fields in the returned stat structure.

Chapter 1

This chapter describes the Fortran library routines alphabetically. See the FORTRAN 77 Language Reference for details on Fortran 77 and VMS intrinsic functions. All the routines described in this chapter have corresponding man pages in section 3F of the man library. For example, man -s 3F access will display the man page entry for the library routine access .

See also the Numerical Computation Guide for additional math routines that are callable from Fortran and C. These include the standard math library routines in libm and libsunmath (see Intro (3M)), optimized versions of these libraries, the SPARC vector math library, libmvec , and others.

Data Type Considerations

Unless otherwise indicated, the function routines listed here are not intrinsics. That means that the type of data a function returns may conflict with the implicit typing of the function name, and require explicit type declaration by the user. For example, getpid() returns INTEGER*4 and would require an INTEGER*4 getpid declaration to ensure proper handling of the result. (Without explicit typing, a REAL result would be assumed by default because the function name starts with g .) As a reminder, explicit type statements appear in the function summaries for these routines.

Be aware that IMPLICIT statements and the -r8 , -i2 , -dbl and -xtypemap compiler options also alter the data typing of arguments and the treatment of return values. A mismatch between the expected and actual data types in calls to these library routines could cause unexpected behavior. Options -r8 and -dbl promote the data type of INTEGER functions to INTEGER*8 , REAL functions to REAL*8 , and DOUBLE functions to REAL*16 . To protect against these problems, function names and variables appearing in library calls should be explicitly typed with their expected sizes, as in:

Explicit typing in the example protects the library calls from any data type promotion when the -r8 and -dbl compiler options are used. Without explicit typing, these options could produce unexpected results. See the Fortran User’s Guide and the f77 (1) and f95 (1) man pages for details on these options.

The more flexible -xtypemap compiler option is recommended over the obsolete
-i2, -r8, and -dbl options and should be used instead.

You can catch many issues related to type mismatches over library calls by using the Fortran compilers’ global program checking option, -Xlist . Global program checking by the f77 and f95 compilers is described in the Fortran User’s Guide, the Fortran Programming Guide, and the f77 (1) and f95 (1) man pages.

64-Bit Environments

Compiling a program to run in a 64-bit operating environment (that is, compiling with -xarch=v9 or v9a and running the executable on a SPARC platform running the 64-bit enabled Solaris operating environment) changes the return values of certain functions. These are usually functions that interface standard system-level routines, such as malloc (3F) (see page 76), and may take or return 32-bit or 64-bit values depending on the environment. To provide portability of code between 32-bit and 64-bit environments, 64-bit versions of these routines have been provided that always take and/or return 64-bit values. The following table identifies library routine provided for use in 64-bit environments:

Allocate memory and return a pointer page 76
Reposition a large file page 40
Determine position of a large file page 40
Determine status of a file page 95
Get system time, convert to character or dissected page 96
Sort the elements of an array page 83

Fortran Math Functions

The following functions and subroutines are part of the Fortran math libraries. They are available to all programs compiled with f77 and f95 . Some routines are intrinsics and return the same data type (single precision, double precision, or quad precision) as their argument. The rest are non-intrinsics that take a specific data type as an argument and return the same. These non-intrinsics do have to be declared in the routine referencing them.

Many of these routines are «wrappers», Fortran interfaces to routines in the C language library, and as such are non-standard Fortran. They include IEEE recommended support functions, and specialized random number generators. See the Numerical Computation Guide and the man pages libm_single (3F), libm_double (3F), libm_quadruple (3F), for more information about these libraries.

Intrinsic Math Functions

Here is a list of intrinsic math functions. You need not put them in a type statement. These functions take single, double, or quad precision data as arguments and return the same.

The functions sind(x), cosd(x), asind(x), acosd(x), atand(x), atan2d(x,y) are not part of the Fortran standard.

Single-Precision Functions

These subprograms are single-precision math functions and subroutines.

In general, the functions below provide access to single-precision math functions that do not correspond to standard Fortran generic intrinsic functions—data types are determined by the usual data typing rules.

These functions need not be explicitly typed with a REAL statement as long as default typing holds. (Variables beginning with » r » are REAL , with » i » are INTEGER .)

For details on these routines, see the C math library man pages (3M). For example, for r_acos(x) see the acos (3M) man page.

TABLE 1-2 Single-Precision Math Functions

  • Variables c , l , p , s , u , x , and y are of type REAL .
  • Type these functions as explicitly REAL if an IMPLICIT statement is in effect that types names starting with » r » to some other date type.
  • sind(x) , asind(x), . take degrees rather than radians.

See also: intro (3M) and the Numerical Computation Guide.

Double-Precision Functions

The following subprograms are double-precision math functions and subroutines.

In general, these functions do not correspond to standard Fortran generic intrinsic functions—data types are determined by the usual data typing rules.

These DOUBLE PRECISION functions need to appear in a DOUBLE PRECISION statement.

Refer to the C library man pages for details: the man page for d_acos(x) is acos (3M)

TABLE 1-3 Double Precision Math Functions

  • Variables c , l , p , s , u , x , and y are of type DOUBLE PRECISION .
  • Explicitly type these functions on a DOUBLE PRECISION statement or with an appropriate IMPLICIT statement).
  • sind(x) , asind(x), . take degrees rather than radians.

See also: intro (3M) and the Numerical Computation Guide.

Quad-Precision Functions

These subprograms are quadruple -precision ( REAL*16 ) math functions and subroutines (SPARC only).

In general, these do not correspond to standard generic intrinsic functions; data types are determined by the usual data typing rules.

The quadruple precision functions must appear in a REAL*16 statement

TABLE 1-4 Quadruple-Precision libm Functions

  • The variables c , l , p , s , u , x , and y are of type quadruple precision.
  • Explicitly type these functions with a REAL*16 statement or with an appropriate IMPLICIT statement.
  • sind(x) , asind(x), . take degrees rather than radians.

If you need to use any other quadruple-precision libm function, you can call it using $PRAGMA C( fcn ) before the call. For details, see the chapter on the C-Fortran interface in the Fortran Programming Guide.

abort : Terminate and Write Core File

The subroutine is called by:

abort flushes the I/O buffers and then aborts the process, possibly producing a core file memory dump in the current directory. See limit (1) about limiting or suppressing core dumps.

access : Check File Permissions or Existence

The function is called by:

INTEGER*4 access status = access ( name, mode )
name Input File name
mode Input Permissions
Return value Output status=0: OK
status>0: Error code

access determines if you can access the file name with the permissions specified by mode. access returns zero if the access specified by mode would be successful. See also gerror (3F) to interpret error codes.

Set mode to one or more of r , w , x , in any order or combination, or blank, where r , w , x have the following meanings:

‘r’ Test for read permission
‘w’ Test for write permission
‘x’ Test for execute permission
‘ ‘ Test for existence of the file

Example 1: Test for read/write permission:

Example 2: Test for existence:

alarm : Call Subroutine After a Specified Time

The function is called by:

time Input Number of seconds to wait (0=do not call) sbrtn Routine name Input Subprogram to execute must be listed in an external statement. Return value Output Time remaining on the last alarm

Example: alarm —wait 9 seconds then call sbrtn :

See also: alarm (3C), sleep (3F), and signal (3F). Note the following restrictions:

  • A subroutine cannot pass its own name to alarm .
  • The alarm routine generates signals that could interfere with any I/O. The called subroutine, sbrtn, must not do any I/O itself.
  • Calling alarm() from a parallelized or multi-threaded Fortran program may have unpredictable results.

bit : Bit Functions: and , or , . bit , setbit , .

The definitions are:

and( word1, word2 ) Computes bitwise and of its arguments.
or( word1, word2 ) Computes bitwise inclusive or of its arguments.
xor( word1, word2 ) Computes bitwise exclusive or of its arguments.
not( word ) Returns bitwise complement of its argument.
lshift( word, nbits ) Logical left shift with no end around carry.
rshift( word, nbits ) Arithmetic right shift with sign extension.
call bis( bitnum , word ) Sets bit bitnum in word to 1.
call bic( bitnum , word ) Clears bit bitnum in word to 0.
bit( bitnum , word ) Tests bit bitnum in word and returns .true. if the bit is 1, .false. if it is 0.
call setbit( bitnum , word , state ) Sets bit bitnum in word to 1 if state is nonzero, and clears it otherwise.

The alternate external versions for MIL-STD-1753 are:

Computes the bitwise and of its arguments.
Computes the bitwise inclusive or of its arguments.
Computes the bitwise exclusive or of its arguments.
Is a logical shift with no end around carry (left if k>0, right if k .true. if the bit is 1, and .false. if it is 0.

See also mvbits: Move a Bit Field, and the chapter on Intrinsic Functions in the FORTRAN 77 Reference Manual.

Usage: and , or , xor , not , rshift , lshift


For the intrinsic functions:

word, word1, word2, nbits are integer input arguments. These are intrinsic functions expanded inline by the compiler. The data type returned is that of the first argument.

No test is made for a reasonable value of nbits.

Example: and, or, xor, not :

Example: lshift , rshift :

Usage: bic , bis , bit , setbit

bitnum, state, and word are INTEGER*4 input arguments. Function bit () returns a logical value.

Bits are numbered so that bit 0 is the least significant bit, and bit 31 is the most significant.

bic , bis , and setbit are external subroutines. bit is an external function.

Example 3: bic , bis , setbit , bit :

chdir : Change Default Directory

The function is called by:

dirname Input Directory name Return value Output n=0: OK, n>0: Error code

Example: chdir —change cwd to MyDir :

See also: chdir (2), cd (1), and gerror (3F) to interpret error codes.

Path names can be no longer than MAXPATHLEN as defined in . They can be relative or absolute paths.

Use of this function can cause inquire by unit to fail.

Certain Fortran file operations reopen files by name. Using chdir while doing I/O can cause the runtime system to lose track of files created with relative path names. including the files that are created by open statements without file names.

chmod : Change the Mode of a File

The function is called by:

name Input Path name mode Input Anything recognized by chmod(1), such as o-w , 444 , etc. Return value Output n = 0: OK; n>0: System error number

Example: chmod —add write permissions to MyFile :

See also: chmod (1), and gerror (3F) to interpret error codes.

Path names cannot be longer than MAXPATHLEN as defined in . They can be relative or absolute paths.

date : Get Current Date as a Character String

Note – This routine is not «Year 2000 Safe» because it returns only a two-digit value for the year. Programs that compute differences between dates using the output of this routine may not work properly after 31 December, 1999. Programs using this date() routine will see a runtime warning message the first time the routine is called to alert the user. See date_and_time() as a possible alternate routine.

The subroutine is called by:

c CHARACTER*9 Output Variable, array, array element, or character substring

The form of the returned string c is dd-mmm-yy, where dd is the day of the month as a 2-digit number, mmm is the month as a 3-letter abbreviation, and yy is the year as a 2-digit number (and is not year 2000 safe!).

See also idate() and date_and_time() .

date_and_time : Get Date and Time

This is a FORTRAN 77 version of the Fortran 95 intrinsic routine, and is Year 2000 safe.

The date_and_time subroutine returns data from the real-time clock and the date. Local time is returned, as well as the difference between local time and Universal Coordinated Time (UTC) (also known as Greenwich Mean Time, GMT).

The date_and_time () subroutine is called by:

date Output Date, in form CCYYMMDD, where CCYY is the four-digit year, MM the two-digit month, and DD the two-digit day of the month. For example: 19980709 time Output The current time, in the form hhmmss.sss, where hh is the hour, mm minutes, and ss.sss seconds and milliseconds. zone Output The time difference with respect to UTC, expressed in hours and minutes, in the form hhmm values INTEGER*4 VALUES(8) Output An integer array of 8 elements described below.

The eight values returned in the INTEGER*4 values array are

The year, as a 4-digit integer. For example, 1998.
The month, as an integer from 1 to 12.
The day of the month, as an integer from 1 to 31.
The time difference, in minutes, with respect to UTC.
The hour of the day, as an integer from 1 to 23.
The minutes of the hour, as an integer from 1 to 59.
The seconds of the minute, as an integer from 0 to 60.
The milliseconds of the second, in range 0 to 999.

An example using date_and_time:

When run on a computer in California, USA on February 16, 2000, it generated the following output:

dtime , etime : Elapsed Execution Time

Both functions have return values of elapsed time (or -1.0 as error indicator).
The time returned is in seconds.

The versions of dtime and etime used by Fortran 77 return times produced by the runtime system’s high resolution clock. The actual resolution depends on the system platform. The resolutions of the clocks on current platforms range between one nanosecond and one microsecond.

Versions of dtime and etime used by Fortran 95 use the system’s low resolution clock by default. The resolution is one hundreth of a second. However, if the program is run under the Sun OS TM operating system utility ptime (1), ( /usr/proc/bin/ptime) , the high resolution clock is used.

dtime : Elapsed Time Since the Last dtime Call

For dtime , the elapsed time is:

  • First call: elapsed time since start of execution
  • Subsequent calls: elapsed time since the last call to dtime
  • Single processor: time used by the CPU
  • Multiple Processor: the sum of times for all the CPUs, which is not useful data; use etime instead.

Note – Calling dtime from within a parallelized loop gives non-deterministic results, since the elapsed time counter is global to all threads participating in the loop

The function is called by:

tarray Output e= -1.0: Error: tarray values are undefined e -1.0: User time in tarray(1) if no error. System time in tarray(2) if no error Return value Output e= -1.0: Error e -1.0: The sum of tarray(1) and tarray(2)

Example: dtime() , single processor:

etime : Elapsed Time Since Start of Execution

For etime , the elapsed time is:

  • Single ProcessorCPU time for the calling process
  • Multiple Processors—wallclock time while processing your program

Here is how Fortran decides single processor or multiple processor:

For a parallelized Fortran program linked with libF77_mt , if the environment variable PARALLEL is:

  • Undefined, the current run is single processor.
  • Defined and in the range 1, 2, 3, . the current run is multiple processor.
  • Defined, but some value other than 1, 2, 3, . the results are unpredictable.

The function is called by:

tarray Output e= -1.0: Error: tarray values are undefined. e -1.0: Single Processor: User time in tarray(1). System time in tarray(2) Multiple Processor: Wall clock time in tarray(1), 0.0 in tarray(2) Return value Output e= -1.0: Error e -1.0: The sum of tarray (1) and tarray (2)

Take note that the initial call to etime will be inaccurate. It merely enables the system clock. Do not use the value returned by the initial call to etime.

Example: etime() , single processor:

See also times (2), f77 (1), and the Fortran Programming Guide.

exit : Terminate a Process and Set the Status

The subroutine is called by:

status INTEGER*4 Input

exit flushes and closes all the files in the process, and notifies the parent process if it is executing a wait .

The low-order 8 bits of status are available to the parent process. These 8 bits are shifted left 8 bits, and all other bits are zero. (Therefore, status should be in the range of 256 — 65280). This call will never return.

The C function exit can cause cleanup actions before the final system ‘ exit ‘.

Calling exit without an argument causes a compile-time warning message, and a zero will be automatically provided as an argument. See also: exit (2), fork (2), fork (3F), wait (2), wait (3F).

fdate : Return Date and Time in an ASCII String

The subroutine or function is called by:

string Output
CHARACTER fdate*24 string = fdate() If used as a function, the calling routine must define the type and size of fdate .
Return value Output

Example 1: fdate as a subroutine:

Example 2: fdate as a function, same output:

See also: ctime (3), time (3F), and idate (3F).

flush : Flush Output to a Logical Unit

The function is called by:

lunit Input Logical unit Return value Output n = 0 no error
n > 0 error number

The flush function flushes the contents of the buffer for the logical unit, lunit , to the associated file. This is most useful for logical units 0 and 6 when they are both associated with the console terminal. The function returns a positive error number if an error was encountered; zero otherwise.

See also fclose (3S).

fork : Create a Copy of the Current Process

The function is called by:

Return value Output n>0: n=Process >

The fork function creates a copy of the calling process. The only distinction between the two processes is that the value returned to one of them, referred to as the parent process, will be the process ID of the copy. The copy is usually referred to as the child process. The value returned to the child process will be zero.

All logical units open for writing are flushed before the fork to avoid duplication of the contents of I/O buffers in the external files.

A corresponding exec routine has not been provided because there is no satisfactory way to retain open logical units across the exec routine. However, the usual function of fork/exec can be performed using system (3F). See also: fork (2), wait (3F), kill (3F), system (3F), and perror (3F).

free : Deallocate Memory Allocated by Malloc

The subroutine is called by:

ptr pointer Input

free deallocates a region of memory previously allocated by malloc . The region of memory is returned to the memory manager; it is no longer available to the user’s program.

fseek , ftell : Determine Position and Reposition a File

fseek and ftell are routines that permit repositioning of a file. ftell returns a file’s current position as an offset of so many bytes from the beginning of the file. At some later point in the program, fseek can use this saved offset value to reposition the file to that same place for reading.

fseek : Reposition a File on a Logical Unit

The function is called by:

lunit Input Open logical unit offset or Input Offset in bytes relative to position specified by from An INTEGER*8 offset value is required when compiled for a 64-bit environment, such as Solaris 7, with -xarch=v9 . If a literal constant is supplied, it must be a 64-bit constant, for example: 100_8 from Input 0=Beginning of file 1=Current position 2=End of file Return value Output n=0: OK; n>0: System error code

Note – On sequential files, following a call to fseek by an output operation (for example, WRITE ) causes all data records following the fseek position to be deleted and replaced by the new data record (and an end-of-file mark). Rewriting a record in place can only be done with direct access files.

Example: fseek() —Reposition MyFile to two bytes from the beginning

Example: Same example in a 64-bit environment and compiled with -xarch=v9 :

ftell : Return Current Position of File

The function is called by:

lunit Input Open logical unit Return value INTEGER*4 or INTEGER*8 Output n>=0: n=Offset in bytes from start of file n INTEGER*8 offset value is returned when compiling for a 64-bit environment, such as Solaris 7, with -xarch=v9 . ftell and variables receiving this return value should be declared INTEGER*8 .

Example: Same example in a 64-bit environment and compiled with -xarch=v9 :

See also fseek (3S) and perror (3F); also fseeko64 (3F) ftello64 (3F).

fseeko64 , ftello64 : Determine Position and Reposition a Large File

fseeko64 and ftello64 are «large file» versions of fseek and ftell. They take and return INTEGER*8 file position offsets on Solaris 2.6 and Solaris 7. (A «large file» is larger than 2 Gigabytes and therefore a byte-position must be represented by a 64-bit integer.) Use these versions to determine and/or reposition large files.

fseeko64 : Reposition a File on a Logical Unit

The function is called by:

lunit Input Open logical unit offset64 Input 64-bit offset in bytes relative to position specified by from from Input 0=Beginning of file 1=Current position 2=End of file Return value Output n=0: OK; n>0: System error code

Note – On sequential files, following a call to fseeko64 by an output operation (for example, WRITE ) causes all data records following the fseek position to be deleted and replaced by the new data record (and an end-of-file mark). Rewriting a record in place can only be done with direct access files.

Example: fseeko64() —Reposition MyFile to two bytes from the beginning:

ftello64 : Return Current Position of File

The function is called by:

lunit Input Open logical unit Return value Output n 0: n=Offset in bytes from start of file n

getarg , iargc : Get Command-Line Arguments

getarg and iargc access arguments on the command line (after expansion by the command-line preprocessor.

getarg : Get a Command-Line Argument

The subroutine is called by:

k Input Index of argument (0=first=command name) arg character* n Output kth argument n Size of arg Large enough to hold longest argument

iargc : Get the Number of Command-Line Arguments

The function is called by:

Return value Output Number of arguments on the command line

Example: iargc and getarg , get argument count and each argument:

See also execve (2) and getenv (3F).

getc , fgetc : Get Next Character

getc and fgetc get the next character from the input stream.Do not mix calls to these routines with normal Fortran I/O on the same logical unit.

getc : Get Next Character from stdin

The function is called by:

char Output Next character Return value Output status=0: OK status=-1: End of file status>0: System error code or
f77 I/O error code

Example: getc gets each character from the keyboard; note the Control-D ( ^D ):

After compiling, a sample run of the above source is:

For any logical unit, do not mix normal Fortran input with getc() .

fgetc : Get Next Character from Specified Logical Unit

The function is called by:

lunit Input Logical unit char Output Next character Return value Output status=-1: End of File status>0: System error code or f77 I/O error code

Example: fgetc gets each character from tfgetc.data ; note the linefeeds (Octal 012):

After compiling, a sample run of the above source is:

For any logical unit, do not mix normal Fortran input with fgetc() .

See also: getc (3S), intro (2), and perror (3F).

getcwd : Get Path of Current Working Directory

The function is called by:

dirname character* n Output The path of the current directory is returned Path name of the current working directory. n must be large enough for longest path name Return value Output status=0: OK status>0: Error code

See also: chdir (3F), perror (3F), and getwd (3).

Note: the path names cannot be longer than MAXPATHLEN as defined in .

getenv : Get Value of Environment Variables

The subroutine is called by:

ename character* n Input Name of the environment variable sought evalue character* n Output Value of the environment variable found; blanks if not successful

The size of ename and evalue must be large enough to hold their respective character strings.

The getenv subroutine searches the environment list for a string of the form ename=evalue and returns the value in evalue if such a string is present; otherwise, it fills evalue with blanks.

Example: Use getenv() to print the value of $SHELL :

See also: execve(2) and environ(5).

getfd : Get File Descriptor for External Unit Number

The function is called by:

unitn Input External unit number Return value INTEGER*4
-or-
INTEGER*8 Output File descriptor if file is connected;
-1 if file is not connected
An INTEGER*8 result is returned when compiling for 64-bit environments

See also open (2).

getfilep : Get File Pointer for External Unit Number

The function is:

c_read C function Input User’s own C function. See example. unitn Input External unit number. Return value File pointer if the file is connected; -1 if the file is not connected.
An INTEGER*8 value is returned when compiling for 64-bit environments

This function is used for mixing standard Fortran I/O with C I/O. Such a mix is nonportable, and is not guaranteed for subsequent releases of the operating system or Fortran. Use of this function is not recommended, and no direct interface is provided. You must create your own C routine to use the value returned by getfilep . A sample C routine is shown below.

Example: Fortran uses getfilep by passing it to a C function:

Sample C function actually using getfilep :

A sample compile-build-run is:

For more information, read the chapter on the C-Fortran interface in the Fortran Programming Guide. See also open (2).

getlog : Get User’s Login Name

The subroutine is called by:

name Output User’s login name, or all blanks if the process is running detached from a terminal. n should be large enough to hold the longest name.

See also getlogin (3).

getpid : Get Process ID

The function is called by:

Return value Output Process ID of the current process

See also getpid (2).

getuid , getgid : Get User or Group ID of Process

getuid and getgid get the user or group ID of the process, respectively.


getuid : Get User ID of the Process

The function is called by:

Return value Output User ID of the process

getgid : Get Group ID of the Process

The function is called by:

Return value Output Group ID of the process

Example: getuid() and getpid() :

See also: getuid (2).

hostnm : Get Name of Current Host

The function is called by:

name character* n Output Name of current host system. n must be large enough to hold the host name. Return value Output status=0: OK status>0: Error

See also gethostname (2).

idate : Return Current Date

idate has two versions:

  • Standard—Put the current system date into an integer array: day, month, and year.
  • VMS—Put the current system date into three integer variables: month, day, and year. This version is not «Year 2000 Safe».

The -lV77 compiler option request the VMS library and links the VMS versions of both time() and idate() ; otherwise, the linker accesses the standard versions. (VMS versions of library routines are only available with f77 through the -lV77 library option, and not with f95 ).

The standard version puts the current system date into one integer array: day, month, and year.

The subroutine is called by:

iarray Output Three-element array: day, month, year.

Example: idate (standard version):

The VMS idate() subroutine is called by:

m Output Month (1 — 12) d Output Day (1 — 7) y Output Year (1 — 99) Not year 2000 safe!

Using the VMS idate() routine will cause a warning message at link time and the first time the routine is called in execution.

Note – The VMS version of the idate() routine is not «Year 2000 Safe» because it returns only a two-digit value for the year. Programs that compute differences between dates using the output of this routine may not work properly after 31 December, 1999. Programs using this idate() routine will see a runtime warning message the first time the routine is called to alert the user. See date_and_time() as a possible alternate.

Example: idate (VMS version):

ieee_flags,ieee_handler,
sigfpe : IEEE Arithmetic

These subprograms provide modes and status required to fully exploit ANSI/IEEE Standard 754-1985 arithmetic in a Fortran program. They correspond closely to the functions ieee_flags (3M), ieee_handler (3M), and sigfpe (3).

Here is a summary:

TABLE 1-5 IEEE Arithmetic Support Routines

action Input
code Input
mode Input
in Input
exception Input
hdl Input
out Output
Return value Output

See the Sun Numerical Computation Guide for details on how these functions can be used strategically.

If you use sigfpe , you must do your own setting of the corresponding trap-enable-mask bits in the floating-point status register. The details are in the SPARC architecture manual. The libm function ieee_handler sets these trap-enable-mask bits for you.

The character keywords accepted for mode and exception depend on the value of action.

TABLE 1-6 ieee_flags(action,mode,in,out) Parameters and Actions

mode, in, out, unused; returns 0
action = ‘clear’ clear mode, in out is unused; returns 0
action = ‘set’ set floating-point mode,in out is unused; returns 0
action = ‘get’ test mode settings in, out may be blank or one of the settings to test returns the current setting depending on mode, or ‘ not available ‘
The function returns 0 or the current exception flags if mode = ‘ exception ‘

TABLE 1-7 ieee_handler(action,in,out) Parameters

action = ‘clear’ clear user exception handing of in; out is unused
action = ‘set’ set user exception handing of in; out is address of handler routine, or SIGFPE_DEFAULT , or SIGFPE_ABORT , or SIGFPE_IGNORE defined in f77/f77_floating point.h

Example 1: Set rounding direction to round toward zero, unless the hardware does not support directed rounding modes:

Example 2: Clear rounding direction to default (round toward nearest):

Example 3: Clear all accrued exception-occurred bits:

Example 4: Detect overflow exception as follows:

The above code sets out to overflow and ieeer to 25 (this value is platform dependent). Similar coding detects exceptions, such as invalid or inexact .

Example 5: hand1.f , write and use a signal handler ( f77 ):

Change the declarations for address and function hand to INTEGER*8 to enable Example 5 in a 64-bit, SPARC V9 environment ( -xarch=v9 )

See the Numerical Computation Guide. See also: floatingpoint (3), signal (3), sigfpe (3), f77_floatingpoint (3F), ieee_flags (3M), and ieee_handler (3M).

f77 _floatingpoint.h : Fortran IEEE Definitions

The header file f77 _floatingpoint.h defines constants and types used to implement standard floating-point according to ANSI/IEEE Std 754-1985.

Include the file in a FORTRAN 77 source program as follows:

Use of this include file requires preprocessing prior to Fortran compilation. The source file referencing this include file will automatically be preprocessed if the name has a .F , .F90 or .F95 extension.

Fortran 95 programs should include the file floatingpoint.h instead.

IEEE Rounding Mode:

The type of the IEEE rounding direction mode. The order of enumeration varies according to hardware.
The type of a SIGFPE code.
The type of a user-definable SIGFPE exception handler called to handle a particular SIGFPE code.
A macro indicating default SIGFPE exception handling: IEEE exceptions to continue with a default result and to abort for other SIGFPE codes.
A macro indicating an alternate SIGFPE exception handling, namely to ignore and continue execution.
A macro indicating an alternate SIGFPE exception handling, namely to abort with a core dump.

IEEE Exception Handling:

The number of distinct IEEE floating-point exceptions.
The type of the N_IEEE_EXCEPTION exceptions. Each exception is given a bit number.
The type intended to hold at least N_IEEE_EXCEPTION bits corresponding to the IEEE exceptions numbered by fp_exception_type . Thus, fp_inexact corresponds to the least significant bit and fp_invalid to the fifth least significant bit. Some operations can set more than one exception.
A list of the classes of IEEE floating-point values and symbols.

Refer to the Numerical Computation Guide. See also ieee_environment (3M) and f77_ieee_environment (3F).

index,rindex,lnblnk : Index or Length of Substring

These functions search through a character string:

Index of first occurrence of string a2 in string a1
Index of last occurrence of string a2 in string a1
Index of last nonblank in string a1

index has the following forms:

index : First Occurrence of a Substring in a String

The index is an intrinsic function called by:

a1 Input Main string a2 Input Substring Return value Output n>0: Index of first occurrence of a2 in a1 n=0: a2 does not occur in a1.

If declared INTEGER*8 , index() will return an INTEGER*8 value when compiled for a 64-bit environment and character variable a1 is a very large character string (greater than 2 Gigabytes).

rindex : Last Occurrence of a Substring in a String

The function is called by:

a1 Input Main string a2 Input Substring Return value Output n>0: Index of last occurrence of a2 in a1 n=0: a2 does not occur in a1
INTEGER*8 returned in 64-bit environments

lnblnk : Last Nonblank in a String

The function is called by:

a1 Input String Return value Output n>0: Index of last nonblank in a1 n=0: a1 is all nonblank
INTEGER*8 returned in 64-bit environments

Example: index() , rindex() , lnblnk() :

Note – Programs compiled to run in a 64-bit environment must declare index, rindex and lnblnk (and their receiving variables) INTEGER*8 to handle very large character strings.

inmax : Return Maximum Positive Integer

The function is called by:

Return value Output The maximum positive integer

See also libm_single (3F) and libm_double (3F). See also the intrinsic function ephuge( ) described in the FORTRAN 77 Language Reference Manual.

ioinit : Initialize I/O Properties

The IOINIT routine (FORTRAN 77 only) establishes properties of file I/O for files opened after the call to IOINIT . The file I/O properties that IOINIT controls are as follows:

  • Carriage control: Recognize carriage control on any logical unit.
  • Blanks/zeroes: Treat blanks in input data fields as blanks or zeroes.
  • File position: Open files at beginning or at end-of-file.
  • Prefix: Find and open files named prefixNN, 0 NN 19.

IOINIT does the following:

  • Initializes global parameters specifying f77 file I/O properties
  • Opens logical units 0 through 19 with the specified file I/O properties—attaches externally defined files to logical units at runtime

Persistence of File I/O Properties

The file I/O properties apply as long as the connection exists. If you close the unit, the properties no longer apply. The exception is the preassigned units 5 and 6, to which carriage control and blanks/zeroes apply at any time.

Internal Flags

IOINIT uses labeled common to communicate with the runtime I/O system. It stores internal flags in the equivalent of the following labeled common block:

In earlier releases (prior to 3.0.1) the labeled common block was named IOIFLG . The name changed subsequently to __IOIFLG to prevent conflicts with any user-defined common blocks.

Source Code

Some user needs are not satisfied with a generic version of IOINIT , so we provide the source code. It is written in Fortran 77. The location is:

where is usually /opt for a standard installation of the Sun WorkShop software packages, and path changes with every release of the compilers.

Usage: ioinit

The ioinit subroutine is called by:

cctl Input True: Recognize carriage control, all formatted output (except unit 0) bzro Input True: Treat trailing and imbedded blanks as zeroes. apnd Input True: Open files at EoF. Append. prefix Input Nonblank: For unit NN, seek and open file prefixNN vrbose Input True: Report ioinit activity as it happens

See also getarg (3F) and getenv (3F).

Restrictions

Note the following restrictions:

  • prefix can be no longer than 30 characters.
  • A path name associated with an environment name can be no longer than 255 characters.

Description of Arguments

These are the arguments for ioinit .

cctl (Carriage Control)

By default, carriage control is not recognized on any logical unit. If cctl is .TRUE. , then carriage control is recognized on formatted output to all logical units, except unit 0, the diagnostic channel. Otherwise, the default is restored.

bzro (Blanks)

By default, trailing and embedded blanks in input data fields are ignored. If bzro is .TRUE. , then such blanks are treated as zeros. Otherwise, the default is restored.

apnd (Append)

By default, all files opened for sequential access are positioned at their beginning. It is sometimes necessary or convenient to open at the end-of-file, so that a write will append to the existing data. If apnd is .TRUE. , then files opened subsequently on any logical unit are positioned at their end upon opening. A value of .FALSE. restores the default behavior.

prefix (Automatic File Connection)

If the argument prefix is a nonblank string, then names of the form prefixNN are sought in the program environment. The value associated with each such name found is used to open the logical unit NN for formatted sequential access.

This search and connection is prov >> 19, nothing is done; see Source Code.

vrbose ( IOINIT Activity)

If the argument vrbose is .TRUE. , then IOINIT reports on its own activity.

Example: The program myprogram has the following ioinit call:

You can assign file name in at least two ways.

With either shell, the ioinit call in the above example gives these results:

  • Open logical unit 1 to the file, mydata .
  • Open logical unit 12 to the file, myresults .
  • Both files are positioned at their beginning.
  • Any formatted output has column 1 removed and interpreted as carriage control.
  • Embedded and trailing blanks are to be ignored on input.

Example: ioinit() —list and compile:

You can set environment variables as follows, using either sh or csh :

ioinit() —Run and test:

itime : Current Time

itime puts the current system time into an integer array: hour, minute, and second. The subroutine is called by:

iarray Output 3-element array: iarray(1) = hour iarray(2) = minute iarray(3) = second

See also time (3F), ctime (3F), and fdate (3F).

kill : Send a Signal to a Process

The function is called by:

pid Input Process ID of one of the user’s processes signum Input Valid signal number. See signal(3). Return value Output status=0: OK status>0: Error code

Example (fragment): Send a message using kill() :

The function sends signal signum, and integer signal number, to the process pid. Valid signal numbers are listed in the C include file /usr/include/sys/signal.h

See also: kill (2), signal (3), signal (3F), fork (3F), and perror (3F).

link creates a link to an existing file. symlink creates a symbolic link to an existing file.

The functions are called by:

status = symlnk( name1 , name2 ) name1 character* n Input Path name of an existing file name2 character* n Input Path name to be linked to the file, name1. name2 must not already exist. Return value Output status=0: OK status>0: System error code

Example 1: link : Create a link named data1 to the file, tlink.db.data.1 :

Example 2: symlnk : Create a symbolic link named data1 to the file, tlink.db.data.1 :

See also: link (2), symlink (2), perror (3F), and unlink (3F).

Note: the path names cannot be longer than MAXPATHLEN as defined in .

loc : Return the Address of an Object

This intrinsic function is called by:

arg Any type Input Variable or array Return value INTEGER*4
-or- INTEGER*8 Output Address of arg Returns an INTEGER*8 pointer when compiled to run in a 64-bit environment with -xarch=v9 . See Note below.

Note – Programs compiled to run in a 64-bit environment should declare INTEGER*8 the variable receiving output from the loc() function.

long , short : Integer Object Conversion

long and short handle integer object conversions between INTEGER*4 and INTEGER*2 , and is especially useful in subprogram call lists.

long : Convert a Short Integer to a Long Integer

The function is called by:

int2 Input Return value Output

short : Convert a Long Integer to a Short Integer

The function is:

int4 Input Return value Output

Example (fragment): long() and short() :

ExpecLong is some subroutine called by the user program that expects a long ( INTEGER*4 ) integer argument. Similarly, ExpecShort expects a short ( INTEGER*2 ) integer argument.

long is useful if constants are used in calls to library routines and the code is compiled with the -i2 option.

short is useful in similar context when an otherwise long object must be passed as a short integer. Passing an integer to short that is too large in magnitude does not cause an error, but will result in unexpected behavior.

longjmp , isetjmp : Return to Location Set by isetjmp

isetjmp sets a location for longjmp ; longjmp returns to that location.

isetjmp : Set the Location for longjmp

This intrinsic function is called by:

env Output env is a 12-element integer array.
In 64-bit environments it must be declared INTEGER*8 Return value Output ival = 0 if isetjmp is called explicitly ival 0 if isetjmp is called through longjmp

longjmp : Return to the Location Set by isetjmp

The subroutine is called by:

env Input env is the 12-word integer array initialized by isetjmp .
In 64-bit environments it must be declared INTEGER*8 ival Output ival = 0 if isetjmp is called explicitly ival 0 if isetjmp is called through longjmp

Description

The isetjmp and longjmp routines are used to deal with errors and interrupts encountered in a low-level routine of a program. They are f77 intrinsics.

These routines should be used only as a last resort. They require discipline, and are not portable. Read the man page, setjmp (3V), for bugs and other details.

isetjmp saves the stack environment in env. It also saves the register environment.

longjmp restores the environment saved by the last call to isetjmp , and returns in such a way that execution continues as if the call to isetjmp had just returned the value ival.

The integer expression ival returned from isetjmp is zero if longjmp is not called, and nonzero if longjmp is called.

Example: Code fragment using isetjmp and longjmp :

Restrictions

  • You must invoke isetjmp before calling longjmp .
  • The env integer array argument to isetjmp and longjmp must be at least 12 elements long.
  • You must pass the env variable from the routine that calls isetjmp to the routine that calls longjmp , either by common or as an argument.

  • longjmp attempts to clean up the stack. longjmp must be called from a lower call-level than isetjmp .
  • Passing isetjmp as an argument that is a procedure name does not work.

malloc, malloc64 : Allocate Memory and Get Address

The malloc() function is called by:

n Input Number of bytes of memory Return value Output k>0: k=address of the start of the block of memory allocated k=0: Error An INTEGER*8 pointer value is returned when compiled for a 64-bit environment with -xarch=v9 . See Note below.

Note – Programs compiled to run on 64-bit environments such as Solaris 7 must declare the malloc() function and the variables receiving its output as INTEGER*8 . Portability issues can be solved by using malloc64() instead of malloc() in programs that must run in both 32-bit or 64-bit environments.

The function malloc64 (3F) is provided to make programs portable between 32-bit and 64-bit environments:

n Input Number of bytes of memory Return value Output k>0: k=address of the start of the block of memory allocated k=0: Error

These functions allocate an area of memory and return the address of the start of that area. (In a 64-bit environment, this returned byte address may be outside the INTEGER*4 numerical range—the receiving variables must be declared INTEGER*8 to avoid truncation of the memory address.) The region of memory is not initialized in any way, and it should not be assumed to be preset to anything, especially zero!

Example: Code fragment using malloc() :

In the above example, we acquire 4,000 bytes of memory, pointed to by p1, and initialize it to zero.

mvbits : Move a Bit Field

The subroutine is called by:

src Input Source ini1 Input Initial bit position in the source nbits Input Number of bits to move des Output Destination ini2 Input Initial bit position in the destination

Note the following:

  • Bits are numbered 0 to 31, from least significant to most significant.
  • mvbits changes only bits ini2 through ini2 + nbits -1 of the des location, and no bits of the src location.
  • The restrictions are:
    • ini1 + nbits 32
    • ini2 + nbits 32

perror , gerror , ierrno : Get System Error Messages

These routines perform the following functions:

perror Print a message to Fortran logical unit 0, stderr .
Get a system error message (of the last detected system error)
Get the error number of the last detected system error.

perror : Print Message to Logical Unit 0, stderr

The subroutine is called by:

string Input The message. It is written preceding the standard error message for the last detected system error.

gerror : Get Message for Last Detected System Error

The subroutine or function is called by:

string Output Message for the last detected system error

Example 2: gerror() as a subroutine:

Example 3: gerror () as a function; string not used:

ierrno : Get Number for Last Detected System Error

The function is called by:

Return value Output Number of last detected system error

This number is updated only when an error actually occurs. Most routines and I/O statements that might generate such errors return an error code after the call; that value is a more reliable indicator of what caused the error condition.

Example 4: ierrno() :

See also intro (2) and perror (3).

  • string in the call to perror cannot be longer than 127 characters.
  • The length of the string returned by gerror is determined by the calling program.
  • Runtime I/O error codes for f77 and f95 are listed in the Fortran User’s Guide.

putc , fputc : Write a Character to a Logical Unit

putc writes to logical unit 6, normally the control terminal output.

fputc writes to a logical unit.

These functions write a character to the file associated with a Fortran logical unit bypassing normal Fortran I/O.

Do not mix normal Fortran output with output by these functions on the same unit.

putc : Write to Logical Unit 6

The function is called by:

char Input The character to write to the unit Return value Output status=0: OK status>0: System error code

fputc : Write to Specified Logical Unit

The function is called by:

lunit Input The unit to write to char Input The character to write to the unit Return value Output status=0: OK status>0: System error code

See also putc (3S), intro (2), and perror (3F).

qsort,qsort64 : Sort the Elements of a One-Dimensional Array

The subroutine is called by:

array Input Contains the elements to be sorted len Input Number of elements in the array. len8 Input Number of elements in the array isize Input Size of an element, typically: 4 for integer or real 8 for double precision or complex 16 for double complex Length of character object for character arrays isize8 Input Size of an element, typically: 4_8 for integer or real 8_8 for double precision or complex 16_8 for double complex Length of character object for character arrays compar function name Input Name of a user-supplied INTEGER*2 function. Determines sorting order: compar(arg1,arg2)

Use qsort64 in 64-bit environments with arrays larger than 2 Gbytes. Be sure to specify the array length, len8, and the element size, isize8, as INTEGER*8 data. Use the Fortran 95 style constants to explicitly specify INTEGER*8 constants.

The compar( arg1 , arg2 ) arguments are elements of array, returning:

Negative If arg1 is considered to precede arg2
Zero If arg1 is equivalent to arg2
Positive If arg1 is considered to follow arg2

ran : Generate a Random Number Between 0 and 1

Repeated calls to ran generate a sequence of random numbers with a uniform distribution.

i Input Variable or array element r Output Variable or array element

Note the following:

  • The range includes 0.0 and excludes 1.0.
  • The algorithm is a multiplicative, congruential type, general random number generator.
  • In general, the value of i is set once during execution of the calling program.
  • The initial value of i should be a large odd integer.
  • Each call to RAN gets the next random number in the sequence.
  • To get a different sequence of random numbers each time you run the program, you must set the argument to a different initial value for each run.
  • The argument is used by RAN to store a value for the calculation of the next random number according to the following algorithm:
  • SEED contains a 32-bit number, and the high-order 24 bits are converted to floating point, and that value is returned.
  • rand , drand , irand : Return Random Values

    rand returns real values in the range 0.0 through 1.0.

    drand returns double precision values in the range 0.0 through 1.0.

    irand returns positive integers in the range 0 through 2147483647.

    These functions use random (3) to generate sequences of random numbers. The three functions share the same 256 byte state array. The only advantage of these functions is that they are widely available on UNIX systems. For better random number generators, compare lcrans , addrans , and shufrans . See also random (3), and the Numerical Computation Guide

    k Input k=0: Get next random number in the sequence k=1: Restart sequence, return first number k>0: Use as a seed for new sequence, return first number Output Output Output

    rename : Rename a File

    The function is called by:

    from Input Path name of an existing file to Input New path name for the file Return value Output status=0: OK status>0: System error code

    If the file specified by to exists, then both from and to must be the same type of file, and must reside on the same file system. If to exists, it is removed first.

    Example: rename() —Rename file trename.old to trename.new

    See also rename (2) and perror (3F).

    Note: the path names cannot be longer than MAXPATHLEN as defined in .

    secnds : Get System Time in Seconds, Minus Argument

    t0 Input Constant, variable, or array element Return Value Output Number of seconds since midnight, minus t0
    • The returned value from SECNDS is accurate to 0.01 second.
    • The value is the system time, as the number of seconds from midnight, and it correctly spans midnight.
    • Some precision may be lost for small time intervals near the end of the day.

    sh : Fast Execution of an sh Command

    The function is called by:

    string Input String containing command to do Return value Output Exit status of the shell executed. See wait(2) for an explanation of this value.

    The function sh passes string to the sh shell as input, as if the string had been typed as a command.

    The current process waits until the command terminates.

    The forked process flushes all open files:

    • For output files, the buffer is flushed to the actual file.
    • For input files, the position of the pointer is unpredictable.

    The sh() function is not MT-safe. Do not call it from multithreaded or parallelized programs.

    See also: execve (2), wait (2), and system (3).

    Note: string cannot be longer than 1,024 characters.

    signal : Change the Action for a Signal

    The function is called by:

    INTEGER*4 signal or INTEGER*8 signal n = signal( signum , proc , flag )
    signum Input Signal number; see signal(3)
    proc Routine name Input Name of user signal handling routine; must be in an external statement
    flag Input flag 0: Use proc as the signal handler flag 0: Ignore proc; pass flag as the action: flag = 0 : Use the default action flag = 1: Ignore this signal
    Return value Output n = -1: System error n > 0: Definition of previous action n > 1: n=Address of routine that would have been called n -1: If signum is a val >
    INTEGER*8 On 64-bit environments, signal and the variables receiving its output must be declared INTEGER*8

    If proc is called, it is passed the signal number as an integer argument.

    If a process incurs a signal, the default action is usually to clean up and abort. A signal handling routine provides the capability of catching specific exceptions or interrupts for special processing.

    The returned value can be used in subsequent calls to signal to restore a previous action definition.

    You can get a negative return value even though there is no error. In fact, if you pass a valid signal number to signal() , and you get a return value less than -1, then it is OK.

    f77 arranges to trap certain signals when a process is started. The only way to restore the default f77 action is to save the returned value from the first call to signal .

    f77_floatingpoint.h defines proc values SIGFPE_DEFAULT , SIGFPE_IGNORE , and SIGFPE_ABORT . See page 59. (Use floatingpoint.h with f95 ).

    In 64-bit environments, signal must be declared INTEGER*8 , along with the variables receiving its output, to avoid truncation of the address that may be returned.

    See also kill (1), signal (3), and kill (3F), and Numerical Computation Guide.

    sleep : Suspend Execution for an Interval

    The subroutine is called by:

    itime Input Number of seconds to sleep

    The actual time can be up to 1 second less than itime due to granularity in system timekeeping.

    See also sleep (3).

    stat , lstat , fstat : Get File Status

    These functions return the following information:

    • device,
    • inode number,
    • protection,
    • number of hard links,
    • user ID,
    • group ID,
    • device type,
    • size,
    • access time,
    • modify time,
    • status change time,
    • optimal blocksize,
    • blocks allocated

    Both stat and lstat query by file name. fstat queries by logical unit.

    stat : Get Status for File, by File Name

    The function is called by:

    ierr = stat ( name , statb )
    name Input Name of the file
    statb Output Status structure for the file, 13-element array
    Return value Output ierr=0: OK ierr>0: Error code

    fstat : Get Status for File, by Logical Unit

    ierr = fstat ( lunit , statb )
    lunit Input Logical unit number
    statb Output Status for the file: 13-element array
    Return value Output ierr=0: OK ierr>0: Error code

    Example 2: fstat() :

    lstat : Get Status for File, by File Name

    The function is called by:

    name Input File name
    statb Output Status array of file, 13 elements
    Return value Output ierr=0: OK ierr>0: Error code

    Example 3: lstat() :

    Detail of Status Array for Files

    The meaning of the information returned in the INTEGER*4 array statb is as described for the structure stat under stat (2).

    Spare values are not included. The order is shown in the following table:

    statb (1)
    statb (2)
    statb (3)
    statb (4)
    statb (5)
    statb (6)
    statb (7)
    statb (8)
    statb (9)
    statb (10)
    statb (11)
    statb (12)
    statb (13)
    Device inode resides on
    This inode’s number
    Protection
    Number of hard links to the file
    User ID of owner
    Group ID of owner
    Device type, for inode that is device
    Total size of file
    File last access time
    File last modify time
    File last status change time
    Optimal blocksize for file system I/O ops
    Actual number of blocks allocated

    See also stat (2), access (3F), perror (3F), and time (3F).

    Note: the path names can be no longer than MAXPATHLEN as defined in .

    stat64 , lstat64 , fstat64 : Get File Status

    64-bit «long file» versions of stat , lstat , fstat . These routines are identical to the non-64-bit routines, except that the 13-element array statb must be declared INTEGER*8 .

    system : Execute a System Command

    The function is called by:

    string Input String containing command to do Return value Output Exit status of the shell executed. See wait(2) for an explanation of this value.

    The function system passes string to your shell as input, as if the string had been typed as a command. Note: string cannot be longer than 1024 characters.

    If system can find the environment variable SHELL , then system uses the value of SHELL as the command interpreter (shell); otherwise, it uses sh (1).

    The current process waits until the command terminates.

    Historically, cc and f77 developed with different assumptions:

    • If cc calls system , the shell is always the Bourne shell.
    • If f77 calls system , then which shell is called depends on the environment variable SHELL .

    The system function flushes all open files:

    • For output files, the buffer is flushed to the actual file.
    • For input files, the position of the pointer is unpredictable.

    See also: execve (2), wait (2), and system (3).

    The system() function is not MT-safe. Do not call it from multithreaded or parallelized programs.

    time , ctime , ltime , gmtime : Get System Time

    These routines have the following functions:

    Standard version: Get system time as integer (seconds since 0 GMT 1/1/70) VMS Version: Get the system time as character (hh:mm:ss)
    Convert a system time to an ASCII string.
    Dissect a system time into month, day, and so forth, local time.
    Dissect a system time into month, day, and so forth, GMT.

    time : Get System Time

    For time() , there are two versions, a standard version and a VMS version. If you use the f77 command-line option -lV77 , then you get the VMS version for time() and for idate() ; otherwise, you get the standard versions. (The VMS versions of certain library routines is only available with f77 through the -lV77 library option, and not with f95 .)

    The standard function is called by:

    Return value Output Time, in seconds, since 0:0:0, GMT, 1/1/70 Output In 64-bit environments, time returns an INTEGER*8 value

    The function time () returns an integer with the time since 00:00:00 GMT,
    January 1, 1970, measured in seconds. This is the value of the operating system clock.

    Example: time() , version standard with the operating system:

    The VMS version of time is a subroutine that gets the current system time as a character string.

    The VMS subroutine is called by:

    t Output Time, in the form hh:mm:ss
    hh
    , mm, and ss are each two digits: hh is the hour; mm is the minute; ss is the second

    Example: time( t ) , VMS version, ctime —convert the system time to ASCII:

    ctime : Convert System Time to Character

    The function ctim e converts a system time, stime, and returns it as a 24-character ASCII string.

    The function is called by:

    stime Input System time from time() (standard version) Return value Output System time as character string. Declare ctime and string as character*24 .

    The format of the ctime returned value is shown in the following example. It is described in the man page ctime (3C).

    ltime : Split System Time to Month, Day. (Local)

    This routine dissects a system time into month, day, and so forth, for the local time zone.

    The subroutine is called by:

    stime Input System time from time() (standard version) tarray Output System time, local, as day, month, year, .

    For the meaning of the elements in tarray , see the next section.

    gmtime : Split System Time to Month, Day, . (GMT)

    This routine dissects a system time into month, day, and so on, for GMT.

    The subroutine is:

    stime Input System time from time() (standard version) tarray Output System time, GMT, as day, month, year, .


    Here are the tarray() values for ltime and gmtime : index, units, and range:

    1
    2
    3
    4
    5
    Seconds (0 — 61)
    Minutes (0 — 59)
    Hours (0 — 23)
    Day of month (1 — 31)
    Months since January (0 — 11)
    6
    7
    8
    9
    Year — 1900
    Day of week (Sunday = 0)
    Day of year (0 — 365)
    Daylight Saving Time,
    1 if DST in effect

    These values are defined by the C library routine ctime (3C), which explains why the system may return a count of seconds greater than 59. See also: idate (3F), and fdate (3F).

    ctime64, gmtime64, ltime64: System Time Routines for 64-bit Environments

    These are versions of the corresponding routines ctime , gmtime , and ltime , to provide portability on 64-bit environments. They are identical to these routines except that the input variable stime must be INTEGER*8 .

    When used in a 32-bit environment with an INTEGER*8 stime, if the value of stime is beyond the INTEGER*4 range ctime64 returns all asterisks, while gmtime and ltime fill the tarray array with -1.

    topen , tclose , tread . tstate : Tape I/O

    (FORTRAN 77 Only) These routines provide an alternative way to manipulate magnetic tape:

    Associate a device name with a tape logical unit.
    Write EOF, close tape device channel, and remove association with tlu.
    Read next physical record from tape into buffer.
    Write the next physical record from buffer to tape.
    Rewind the tape to the beginning of the first data file.
    Skip forward over files and/or records, and reset EOF status.
    Determine the logical state of the tape I/O channel.

    On any one unit, do not mix these functions with standard Fortran I/O.

    You must first use topen () to open a tape logical unit, tlu, for the specified device. Then you do all other operations on the specified tlu. tlu has no relationship at all to any normal Fortran logical unit.

    Before you use one of these functions, its name must be in an INTEGER*4 type statement.

    topen : Associate a Device with a Tape Logical Unit

    The function is called by:

    tlu Input Tape logical unit, in the range 0 to 7. devnam Input Device name; for example: ‘/dev/rst0’ islabeled Input True=the tape is labeled A label is the first file on the tape. Return value Output n=0: OK n

    This function does not move the tape. See perror (3F) for details.

    Example: topen() —open a 1/4-inch tape file:

    tclose : Write EOF, Close Tape Channel, Disconnect tlu

    The function is called by:

    tlu Input Tape logical unit, in range 0 to 7 n Return value n=0: OK n

    Caution – tclose( ) places an EOF marker immediately after the current location of the unit pointer, and then closes the unit. So if you trewin() a unit before you tclose() it, its contents are discarded.

    Example: tclose() —close an opened 1/4-inch tape file:

    twrite : Write Next Physical Record to Tape

    The function is called by:

    tlu Input Tape logical unit, in range 0 to 7 buffer Input Must be sized at a multiple of 512 n Return value n > 0: OK, and n = the number of bytes written n=0: End of Tape n

    The physical record length is the size of buffer .

    Example: twrite() —write a 2-record file:

    The function is called by:

    tlu Input Tape logical unit, in range 0 to 7. buffer Input Must be sized at a multiple of 512, and must be large enough to hold the largest physical record to be read. n Return value n>0: OK, and n is the number of bytes read. n

    If the tape is at EOF or EOT, then tread does a return; it does not read tapes.

    Example: tread() —read the first record of the file written above:

    trewin : Rewind Tape to Beginning of First Data File

    The function is called by:

    tlu Input Tape logical unit, in range 0 to 7 n Return value n=0: OK n

    If the tape is labeled, then the label is skipped over after rewinding.

    Example 1: trewin() —typical fragment:

    Example 2: trewin() —in a two-record file, try to read three records, rewind, read one record:

    tskipf : Skip Files and Records; Reset EoF Status

    The function is called by:

    tlu Input Tape logical unit, in range 0 to 7 nf Input Number of end-of-file marks to skip over first nr Input Number of physical records to skip over after skipping files n Return value n=0: OK n

    This function does not skip backward.

    First, the function skips forward over nf end-of-file marks. Then, it skips forward over nr physical records. If the current file is at EOF, this counts as one file to skip. This function also resets the EOF status.

    Example: tskipf() —typical fragment: skip four files and then skip one record:

    Compare with tstate () .

    tstate : Get Logical State of Tape I/O Channel

    The function is called by:

    tlu Input Tape logical unit, in range 0 to 7 fileno Output Current file number recno Output Current record number errf Output True=an error occurred eoff Output True=the current file is at EOF eotf Output True=tape has reached logical end-of-tape tcsr Output True=hardware errors on the device. It contains the tape drive control status register. If the error is software, then tcsr is returned as zero. The values returned in this status register vary grossly with the brand and size of tape drive.

    For details, see st (4s).

    While eoff is true, you cannot read from that tlu. You can set this EOF status flag to false by using tskipf() to skip one file and zero records:

    Then you can read any valid record that follows.

    End-of-tape (EOT) is indicated by an empty file, often referred to as a double EOF mark. You cannot read past EOT, but you can write past it.

    Example: Write three files of two records each:

    The next example uses tstate() to trap EOF and get at all files.

    Example: Use tstate() in a loop that reads all records of the 3 files written in the previous example:

    A summary of EOF and EOT follows:

    • If you are at either EOF or EOT, then:
      • Any tread() just returns; it does not read the tape.
      • A successful tskipf(tlu,1,0) resets the EOF status to false, and returns; it does not advance the tape pointer.
    • A successful twrite() resets the EOF and EOT status flags to false.
    • A successful tclose() resets all those flags to false.
    • tclose() truncates; it places an EOF marker immediately after the current location of the unit pointer, and then closes the unit. So, if you use trewin() to rewind a unit before you use tclose() to close it, its contents are discarded. This behavior of tclose( ) is inherited from the Berkeley code.

    See also: ioctl (2), mtio (4s), perror (3F), read (2), st (4s), and write (2).

    ttynam , isatty : Get Name of a Terminal Port

    ttynam and isatty handle terminal port names.

    ttynam : Get Name of a Terminal Port

    The function ttynam returns a blank padded path name of the terminal device associated with logical unit lunit.

    The function is called by:

    lunit Input Logical unit Return value Output If nonblank returned: name=path name of device on lunit. Size n must be large enough for the longest path name. If empty string (all blanks) returned: lunit is not associated with a terminal device in the directory, /dev

    isatty : Is this Unit a Terminal?

    lunit Input Logical unit Return value Output terminal=true: It is a terminal device terminal=false: It is not a terminal device

    Example: Determine if lunit is a tty:

    The function is called by:

    patnam Input File name Return value Output n=0: OK n>0: Error

    The function unlink removes the file specified by path name patnam. If this is the last link to the file, the contents of the file are lost.

    Example: unlink() —Remove the tunlink.data file:

    See also: unlink (2), link (3F), and perror (3F). Note: the path names cannot be longer than MAXPATHLEN as defined in .

    wait : Wait for a Process to Terminate

    The function is:

    status Output Termination status of the child process Return value Output n>0: Process >wait (2).

    wait suspends the caller until a signal is received, or one of its child processes terminates. If any child has terminated since the last wait , return is immediate. If there are no children, return is immediate with an error code.

    Example: Code fragment using wait() :

    See also: wait (2), signal (3F), kill (3F), and perror (3F).

    Fstat взять статус файла

    НАЗВАНИЕ
    stat, fstat — получение статуса файла

    ОПИСАНИЕ
    Аргумент path указывает на маршрутное имя файла. Не требуется наличие прав доступа на чтение, запись и выполнение заданного файла, но все каталоги, перечисленные перед именем файла в маршрутном имени, должны быть доступны на поиск. Системный вызов stat предоставляет информацию о поименованном файле.

    Системный вызов fstat предоставляет информацию об открытом файле, задаваемом с помощью дескриптора файла fildes, который возвращается успешно завершенными системными вызовами open, creat, dup, fcntl или pipe.

    Аргумент buf является указателем на стуктуру типа stat, в которую помещается информация о файле.

    Структура, на которую указывает buf, содержит следующие поля: st_mode Режим файла согласно определению, данному при описании системного вызова mknod(2). st_ino Это поле однозначно определяет файл в данной файловой системе. Пара (st_ino, st_dev) однозначно определяет обычные файлы. st_dev Это поле однозначно определяет файловую систему, содержащую файл. Значение поля может использоваться в качестве входного аргумента системного вызова ustat(2) при получении дополнительной информации об этой файловой системе. Никакого другого смысла это поле не имеет. st_rdev Это поле следует использовать только для команд администратора. Оно имеет смысл лишь для специальных блочных и символьных файлов и только в той системе, где файл был сконфигурирован. st_nlink Это поле следует использовать только для команд администратора. st_uid Идентификатор владельца файла. st_gid Идентификатор группы владельца файла. st_size Для обычных файлов это адрес конца файла. Для каналов это текущее количество данных в файле. Для специальных блочных и символьных файлов значение поля не определено. st_atime Время последнего доступа к данным. Это поле изменяется следующими системными вызовами: creat(2), mknod(2), pipe(2), utime(2) и read(2). st_mtime Время последней модификации данных. Это поле изменяется следующими системными вызовами: creat(2), mknod(2), pipe(2), utime(2) и write(2). st_ctime Время последнего изменения статуса файла. Это поле изменяется следующими системными вызовами: chmod(2), chown(2), creat(2), link(2), mknod(2), pipe(2), unlink(2), utime(2) и write(2).

    Системный вызов stat завершается неудачей, если выполнено хотя бы одно из следующих условий: [ENOTDIR] Компонент маршрута не является каталогом. [ENOENT] Заданный файл не существует. [EACCES] Нет права на поиск для компонента маршрута. [EFAULT] Аргументы buf или path указывают за пределы отведенного процессу адресного пространства. [EINTR] Во время выполнения системного вызова перехвачен сигнал. [ENOLINK] Маршрутное имя path указывает на удаленный компьютер, связи с которым в данный момент нет. [EMULTIHOP] Компоненты path требуют многократного обращения к удаленным компьютерам.

    Системный вызов fstat завершается неудачей, если выполнено хотя бы одно из следующих условий: [EBADF] Аргумент fildes не является корректным дескриптором открытого файла. [EFAULT] Аргументы buf или path указывают за пределы отведенного процессу адресного пространства. [ENOLINK] Дескриптор файла fildes указывает на удаленный компьютер, связи с которым в данный момент нет.

    Использование fstat для определения типа файла

    Итак, у меня есть задание, которое в основном представляет собой упражнение для сравнения скорости системных вызовов, противоположных библиотечным функциям. Мы сортируем строку, которую мы извлекаем из файла через stdin. Мы должны определить, является ли файл обычным файлом или не использует fstat. Я прочитал страницу руководства, и пока я знаю, ЧТО это делает, у меня проблемы с выяснением того, как ее использовать.

    Я знаю, что он возвращает структуру stat, поэтому я могу буквально просто создать переменную и сохранить ее так? Пример:

    Так вы получаете структуру? Вернется ли он где-то еще? Мне нужен доступ к переменной off_t st_size, поэтому я знаю, сколько байтов находится в файле. И может ли это быть применено к int?

    Кроме того, видимо, вы можете использовать поле st_mode, чтобы проверить, является ли файл регулярным (с использованием макросов S_ISREG), но . как? Верно ли это для ложного или что-то еще? Это раздражает, потому что я могу найти все эти документы, рассказывающие мне, что такое поля, но не как их использовать.

    Если у меня есть обычный файл, я должен выделить достаточно памяти, чтобы сохранить его перед вызовом любой функции. Если нет, то я перераспределяю память, когда читаю. У меня есть вторая часть, я просто не знаю, как правильно использовать fstat.

    stat man page

    stat, fstat, lstat, fstatat — get file status

    Synopsis

    Feature Test Macro Requirements for glibc (see feature_test_macros(7)):

    lstat():

    /* glibc 2.19 and earlier */ _BSD_SOURCE
    || /* Since glibc 2.20 */ _DEFAULT_SOURCE
    || _XOPEN_SOURCE >= 500
    || /* Since glibc 2.10: */ _POSIX_C_SOURCE >= 200112L

    fstatat(): Since glibc 2.10:

    _POSIX_C_SOURCE >= 200809L Before glibc 2.10:

    Description

    These functions return information about a file, in the buffer pointed to by statbuf. No permissions are required on the file itself, but—in the case of stat(), fstatat(), and lstat()—execute (search) permission is required on all of the directories in pathname that lead to the file.

    stat() and fstatat() retrieve information about the file pointed to by pathname; the differences for fstatat() are described below.

    lstat() is identical to stat(), except that if pathname is a symbolic link, then it returns information about the link itself, not the file that it refers to.

    fstat() is >

    The stat structure

    All of these system calls return a stat structure, which contains the following fields:

    Note: the order of fields in the stat structure varies somewhat across architectures. In addition, the definition above does not show the padding bytes that may be present between some fields on various architectures. Consult the glibc and kernel source code if you need to know the details.

    Note: for performance and simplicity reasons, different fields in the stat structure may contain state information from different moments during the execution of the system call. For example, if st_mode or st_uid is changed by another process by calling chmod(2) or chown(2), stat() might return the old st_mode together with the new st_uid, or the old st_uid together with the new st_mode.

    The fields in the stat structure are as follows: st_dev

    This field describes the device on which this file resides. (The major(3) and minor(3) macros may be useful to decompose the device ID in this field.) st_ino

    This field contains the file’s inode number. st_mode

    This field contains the file type and mode. See inode(7) for further information. st_nlink

    This field contains the number of hard links to the file. st_uid

    This field contains the user ID of the owner of the file. st_gid

    This field contains the ID of the group owner of the file. st_rdev

    This field describes the device that this file (inode) represents. st_size

    This field gives the size of the file (if it is a regular file or a symbolic link) in bytes. The size of a symbolic link is the length of the pathname it contains, without a terminating null byte. st_blksize

    This field gives the «preferred» block size for efficient filesystem I/O. st_blocks

    This field indicates the number of blocks allocated to the file, in 512-byte units. (This may be smaller than st_size/512 when the file has holes.) st_atime

    This is the file’s last access timestamp. st_mtime

    This is the file’s last modification timestamp. st_ctime

    This is the file’s last status change timestamp.

    For further information on the above fields, see inode(7).

    fstatat()

    The fstatat() system call is a more general interface for accessing file information which can still provide exactly the behavior of each of stat(), lstat(), and fstat().

    If the pathname given in pathname is relative, then it is interpreted relative to the directory referred to by the file descriptor dirfd (rather than relative to the current working directory of the calling process, as is done by stat() and lstat() for a relative pathname).

    If pathname is relative and dirfd is the special value AT_FDCWD, then pathname is interpreted relative to the current working directory of the calling process (like stat() and lstat()).

    If pathname is absolute, then dirfd is ignored.

    flags can either be 0, or include one or more of the following flags ORed: AT_EMPTY_PATH (since Linux 2.6.39)

    If pathname is an empty string, operate on the file referred to by dirfd (which may have been obtained using the open(2) O_PATH flag). In this case, dirfd can refer to any type of file, not just a directory, and the behavior of fstatat() is similar to that of fstat(). If dirfd is AT_FDCWD, the call operates on the current working directory. This flag is Linux-specific; define _GNU_SOURCE to obtain its definition. AT_NO_AUTOMOUNT (since Linux 2.6.38)

    Don’t automount the terminal («basename») component of pathname if it is a directory that is an automount point. This allows the caller to gather attributes of an automount point (rather than the location it would mount). Since Linux 4.14, also don’t instantiate a nonexistent name in an on-demand directory such as used for automounter indirect maps. This flag can be used in tools that scan directories to prevent mass-automounting of a directory of automount points. The AT_NO_AUTOMOUNT flag has no effect if the mount point has already been mounted over. This flag is Linux-specific; define _GNU_SOURCE to obtain its definition. Both stat() and lstat() act as though AT_NO_AUTOMOUNT was set. AT_SYMLINK_NOFOLLOW

    If pathname is a symbolic link, do not dereference it: instead return information about the link itself, like lstat(). (By default, fstatat() dereferences symbolic links, like stat().)

    See openat(2) for an explanation of the need for fstatat().

    Return Value

    On success, zero is returned. On error, -1 is returned, and errno is set appropriately.

    Errors

    Search permission is denied for one of the directories in the path prefix of pathname. (See also path_resolution(7).) EBADF

    fd is not a valid open file descriptor. EFAULT

    Too many symbolic links encountered while traversing the path. ENAMETOOLONG

    A component of pathname does not exist or is a dangling symbolic link. ENOENT

    pathname is an empty string and AT_EMPTY_PATH was not specified in flags. ENOMEM

    A component of the path prefix of pathname is not a directory. EOVERFLOW

    pathname or fd refers to a file whose size, inode number, or number of blocks cannot be represented in, respectively, the types off_t, ino_t, or blkcnt_t. This error can occur when, for example, an application compiled on a 32-bit platform without -D_FILE_OFFSET_BITS=64 calls stat() on a file whose size exceeds (1

    The following additional errors can occur for fstatat(): EBADF

    dirfd is not a valid file descriptor. EINVAL

    pathname is relative and dirfd is a file descriptor referring to a file other than a directory.

    Versions

    fstatat() was added to Linux in kernel 2.6.16; library support was added to glibc in version 2.4.

    Conforming to

    stat(), fstat(), lstat(): SVr4, 4.3BSD, POSIX.1-2001, POSIX.1.2008.

    fstatat(): POSIX.1-2008.

    According to POSIX.1-2001, lstat() on a symbolic link need return valid information only in the st_size field and the file type of the st_mode field of the stat structure. POSIX.1-2008 tightens the specification, requiring lstat() to return valid information in all fields except the mode bits in st_mode.

    Use of the st_blocks and st_blksize fields may be less portable. (They were introduced in BSD. The interpretation differs between systems, and possibly on a single system when NFS mounts are involved.)

    Notes

    Timestamp fields

    Older kernels and older standards did not support nanosecond timestamp fields. Instead, there were three timestamp fields—st_atime, st_mtime, and st_ctime—typed as time_t that recorded timestamps with one-second precision.

    Since kernel 2.5.48, the stat structure supports nanosecond resolution for the three file timestamp fields. The nanosecond components of each timestamp are available via names of the form st_atim.tv_nsec, if suitable feature test macros are defined. Nanosecond timestamps were standardized in POSIX.1-2008, and, starting with version 2.12, glibc exposes the nanosecond component names if _POSIX_C_SOURCE is defined with the value 200809L or greater, or _XOPEN_SOURCE is defined with the value 700 or greater. Up to and including glibc 2.19, the definitions of the nanoseconds components are also defined if _BSD_SOURCE or _SVID_SOURCE is defined. If none of the aforementioned macros are defined, then the nanosecond values are exposed with names of the form st_atimensec.

    C library/kernel differences

    Over time, increases in the size of the stat structure have led to three successive versions of stat(): sys_stat() (slot __NR_oldstat), sys_newstat() (slot __NR_stat), and sys_stat64() (slot __NR_stat64) on 32-bit platforms such as i386. The first two versions were already present in Linux 1.0 (albeit with different names); the last was added in Linux 2.4. Similar remarks apply for fstat() and lstat().

    The kernel-internal versions of the stat structure dealt with by the different versions are, respectively: __old_kernel_stat

    The original structure, with rather narrow fields, and no padding. stat

    Larger st_ino field and padding added to various parts of the structure to allow for future expansion. stat64

    Even larger st_ino field, larger st_uid and st_gid fields to accommodate the Linux-2.4 expansion of UIDs and GIDs to 32 bits, and various other enlarged fields and further padding in the structure. (Various padding bytes were eventually consumed in Linux 2.6, with the advent of 32-bit device IDs and nanosecond components for the timestamp fields.)

    The glibc stat() wrapper function hides these details from applications, invoking the most recent version of the system call provided by the kernel, and repacking the returned information if required for old binaries.

    On modern 64-bit systems, life is simpler: there is a single stat() system call and the kernel deals with a stat structure that contains fields of a sufficient size.

    The underlying system call employed by the glibc fstatat() wrapper function is actually called fstatat64() or, on some architectures, newfstatat().

    Example

    The following program calls lstat() and displays selected fields in the returned stat structure.

    See Also

    Colophon

    This page is part of release 5.03 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 https://www.kernel.org/doc/man-pages/.

    Referenced By

    The man pages fstat(2), fstat64(2), fstatat(2), lstat(2), lstat64(2), oldfstat(2), oldlstat(2), oldstat(2) and stat64(2) are aliases of stat(2).

    Илон Маск рекомендует:  Что такое код openssl_pkcs7_verify
    Понравилась статья? Поделиться с друзьями:
    Кодинг, CSS и SQL