• truncate, ftruncate - set a file to a specified length

  • #include <sys/types.h>

    int truncate(char *path, off_t length)

    int ftruncate(int fd, off_t length)


  • truncate() causes the file referred to by path (or for ftruncate() the object referred to by fd ) to have a size equal to length bytes. If the file was previously longer than length , the extra bytes are removed from the file. If it was shorter, bytes between the old and new lengths are read as zeroes. With ftruncate(), the file must be open for writing.

  • truncate() returns:

    0 on success.

    -1 on failure and sets errno to indicate the error.


  • truncate() may set errno to:

    EACCES Search permission is denied for a component of the path prefix of path.

    Write permission is denied for the file referred to by path .

    EIO An I/O error occurred while reading from or writing to the file system.

    EISDIR The file referred to by path is a directory.

    ENAMETOOLONG The length of the path argument exceeds {PATH_MAX}.

    A pathname component is longer than {NAME_MAX} (see sysconf (2V)) while {_POSIX_NO_TRUNC} is in effect (see pathconf (2V)).

    ENOENT The file referred to by path does not exist.

    ENOTDIR A component of the path prefix of path is not a directory.

    EROFS The file referred to by path resides on a read-only file system.

    ftruncate() may set errno to:

    EINVAL fd is not a valid descriptor of a file open for writing.

    fd refers to a socket, not to a file.

    EIO An I/O error occurred while reading from or writing to the file system.


  • open (2)
  • BUGS

  • These calls should be generalized to allow ranges of bytes in a file to be discarded.

  • NAME

  • wait, WIFSTOPPED, WIFSIGNALED, WIFEXITED - wait for process to terminate or stop

  • #include <sys/wait.h>

    int wait(union wait *statusp);

    WIFSTOPPED(union wait status);

    WIFSIGNALED(union wait status);

    WIFEXITED(union wait status);


  • wait blocks the caller until a signal is received or one of its child processes terminates. If any child has died and this has not been reported using wait, return is immediate, returning the process ID and exit status of one of those children. If that child had died, it is discarded. If there are no children, return is immediate with the value -1 returned. If there are processes that have not been reported by wait, the caller is blocked.

    If status is not a NULL pointer, then on return from a successful wait call the status of the child process whose process ID is the return value of wait is stored in the wait union pointed to by status. The wstatus member of that union is an int; it indicates the cause of termination and other information about the terminated process in the following manner:

    • If the low-order 8 bits of wstatus are equal to 0177 (hex 0xFF), the child process has stopped; the high-order 8 bits of wstatus contain the number of the signal that caused the process to stop. See signal(2).

    • If the low-order 8 bits of wstatus are non-zero and are not equal to 0177, the child process terminated due to a signal; the low-order 7 bits of wstatus contain the number of the signal that terminated the process.

    • Otherwise, the child process terminated due to an exit() call; the high-order 8 bits of wstatus contain the low-order 8 bits of the argument that the child process passed to exit or GS/OS Quit.

    Other members of the wait union can be used to extract this information more conveniently:

    • If the wstopval member has the value WSTOPPED, the child process has stopped; the value of the wstopsig member is the signal that stopped the process.

    • If the wtermsig member is non-zero, the child process terminated due to a signal; the value of the wtermsig member is the number of the signal that terminated the process.

    • Otherwise, the child process terminated due to an exit() call; the value of the wretcode member is the low-order 8 bits of the argument that the child process passed to exit().

    The other members of the wait union merely provide an alternate way of analyzing the status. The value stored in the wstatus field is compatible with the values stored by versions of the UNIX system, and an argument of type int * may be provided instead of an argument of type union wait * for compatibility with those versions.

    WIFSTOPPED, WIFSIGNALED, WIFEXITED, are macros that take an argument status, of type `union wait', as returned by wait(). WIFSTOPPED evaluates to true (1) when the process for which the wait call was made is stopped, or to false (0) otherwise. WIFSIGNALED evaluates to true when the process was terminated with a signal. WIFEXITED evaluates to true when the process exited by using an exit(2) call.

    If wait returns due to a stopped or terminated child process, the process ID of the child is returned to the calling process. Otherwise, a value of -1 is returned and errno is set to indicate the error.


  • wait will fail and return immediately if one or more of the following are true:

    [ECHILD] The calling process has no existing unwaited-for child processes.

    [EFAULT] The status or rusage arguments point to an illegal address.

    [EINTR] The wait call was interrupted by a caught signal.


  • signal(2), exit(3), rexit(3), execve(2)

  • If a parent process terminates without waiting on its children, the Kernel Null Process (process ID = 0) inherits the children.

    wait is automatically restarted when a process receives a signal while awaiting termination of a child process, if the signal is not caught; i.e. signal() handler value is SIG_DFL or SIG_IGN.

  • GSString255Ptr __C2GSMALLOC(char *s)

    Converts a C-style string to a Class 1 GS/OS string, allocating space for the GS/OS string from C's malloc() routine. You must specifically deallocate the string with free() when you're through with it.


    char *__GS2CMALLOC(GSString255Ptr g)

    Converts a Class 1 GS/OS string to a C-style string, allocating space for the C string from C's malloc() routine. You must specifically deallocate the string with free() when you're through with it.


    char *__GS2C(char *s, GSString255Ptr g)

    Converts a Class 1 GS/OS string to a C string; the buffer space for the C string must be allocated beforehand by the caller. The return value is the address of the C string passed as argument s.


    int _mapErr(int err)

    Tries to map a GS/OS error code (err) to a UNIX errno code (return value). If there is no direct mapping, EIO is returned.




    #include <unistd.h>

    int access(char *name, int mode)


    Returns TRUE (1) if the file specified by name can be acessed according to mode by the calling process. Values of mode are declared in <unistd.h> and are as follows:

  • F_OK - returns true if the file exists

    X_OK - returns true if the process has execution permissions for the file

    W_OK - returns true if the process has write permissions for the file

    R_OK - returns true if the process has read permissions for the file

  • bcopy bzero


    #include <string.h>

    void bcopy(char *b1, char *b2, size_t n)

    void bzero(char *buf, size_t n)


    bcopy() copies n bytes from memory address b1 to memory address b2. bcopy() is functionally similar to memcpy(), except that bcopy copies from the first argument to the second argument, whereas memcpy() copies from the second argument to the first argument. If the memory areas overlap, the results are unpredictable. bcopy() is provided for compatibility with BSD source code.


    bzero() clears n bytes of memory starting at buf to 0 (zero). This call is functionally equivalent to memset(buf,0,n) and is included for BSD source code compatibilty.

    See Also: memcpy, memset, ORCA/C 2.0 Manual







    #include <unistd.h>

    int chdir(const char *pathname)

    Changes the current working directory (GS/OS prefix 0) to the pathname specified by pathname. If an error occurs changing the prefix, -1 is returned and the error code is placed in errno.




    char *crypt(char *pw,char *salt)


    crypt is used to encrypt passwords for storage in the /etc/passwd file, and also to validate passwords entered in the login and passwd programs. pw is the password to encrypt, a NUL- terminated string. salt is a two- character encryption key that should be randomly generated by the caller in the case of encrypting a new password, or should be taken as the first two characters of the /etc/passwd password entry in the case of validating a password.


    crypt returns a pointer to the encrypted password, which is formatted as printable ASCII characters and is NUL terminated. A static buffer is used to hold the result, so to be sure the encrypted password is not overwritten by a subsequent call to crypt copy it before use.

    See also: getpass, getpwent


    errno strerror perror


    char *strerror(int errnum)

    void perror(char *s)

    extern int errno;


    These routines are as documented in the ORCA/C manual, except that they support the full range of GNO's errno codes. errno is the variable that most library and kernel calls place their return status in. The codes are defined symbolically in <errno.h> and are listed here:

    EDOM domain error

    ERANGE number too large, too small, or illegal

    ENOMEM Not enough memory

    ENOENT No such file or directory

    EIO I/O error

    EINVAL Invalid argument

    EBADF bad file descriptor

    EMFILE too many files are open

    EACCESS access bits prevent the operation

    EEXIST the file exists

    ENOSPC the file is too large

    EPERM Not owner

    ESRCH No such process

    EINTR Interrupted system call

    E2BIG Arg list too long

    ENOEXEC Exec format error

    ECHILD No children

    EAGAIN No more processes

    ENOTDIR Not a directory

    ENOTTY Not a terminal

    EPIPE Broken pipe

    ESPIPE Illegal seek

    ENOTBLK not a block device

    EISDIR not a plain file




    int fsync(int fd)


    Causes the operating system to flush any I/O buffers associated with the file referenced by file descriptor fd to disk. This ensures that all information is up to date, in the event of a system crash. This call is only needed in special circumstances, as when several daemon processes are all modifying the same file simultaneously (currently impossible with existing IIGS filesystems). This call is basically a FlushGS.




    int ftruncate(int fd, off_t length)


    Causes the EOF marker for the file specified by file descriptor fd to be set to length. In the event of an error, ftruncate returns -1 and sets errno.


    getgrnam getgrgid getgrent setgrent setgroupent endgrent


    #include <sys/types.h>

    #include <grp.h>

    struct group *getgrnam(const char *name);

    struct group *getgrgid(gid_t gid);

    struct group *getgrent(void);

    int setgrent(void);

    int setgroupent(int stayopen);

    void endgrent(void);



    This family of functions should be used to access the groups database; applications should never read /etc/groups directly, as the implementation of the groups database is subject to change.


    getgrnam() reads the group database based on group name. It looks up the supplied group name and returns a pointer to a struct group (see below), or NULL on an error.


    getgrgid() is similar to getgrnam(), except that instead of looking up group information based on group name, a group ID is passed.


    To scan the groups database linearly, start the scan with either setgrent() or setgroupent(). The two functions are identical for pure scanning operations, but have different behavior when mixing scan calls with getgrnam() or getgrgid().


    After calling setgrent or setgroupent, the scan is set to the first entry in the database. getgrent returns a pointer to the current entry and moves the scan to the next entry. In the event of an error, getgrent returns NULL. When the program is done with the database, endgrent should be called.


    If getgrnam or getgrgid is called while scanning the group database, the database will be closed unless it was opened by calling setgroupent with an argument of 1. This indicates "keep open" mode, and allows fast random access of the database with the getgrnam and getgrgid functions (which would otherwise open and close the database for every call).


    getopt getopt_restart


    #include <getopt.h>

    int getopt(int argc, char * const *argv, const char *optstring)

    int getopt_restart(void)

    extern char *optarg;

    extern int optind;


    Getopt helps parse command line options as are often used by UNIX utilities. It handles simple flags (such as "ls -l") and also flags with arguments ("cc -o prog prog.c").


    Getopt returns the next option letter in argv that matches a letter in optstring. Optstring is a string of recognized option letters; if a letter is followed by a colon, the option is expected to have an argument that may or may not be separated from it by white space. Optarg is set to point to the start of the option argument on return from getopt.


    Getopt places in optind the argv index of the next argument to be processed. Because optind is external, it is normally initialized to zero automatically before the first call to getopt.


    When all options have been processed (i.e., up to the first non-option argument), getopt returns EOF. The special option -- may be used to delimit the end of the options; EOF will be returned, and -- will be skipped.


    Getopt prints an error message on stderr and returns a question mark (?) when it encounters an option letter not included in optstring.


    The following code fragment shows how one might process the arguments for a command that can take the mutually exclusive options a and b, and the options f and o, both of which require arguments:


    main(int argc, char **argv)


    int c;

    extern int optind;

    extern char *optarg;


    while ((c = getopt(argc, argv, "abf:o:")) != EOF)

    switch (c) {

    case `a':

    if (bflg)





    case `b':

    if (aflg)





    case `f':

    ifile = optarg;


    case `o':

    ofile = optarg;


    case `?':





    if (errflg) {

    fprintf(stderr, "Usage: ...");



    for (; optind < argc; optind++) {






    It is not obvious how `-' standing alone should be treated; this version treats it as a non-option argument, which is not always right. Option arguments are allowed to begin with `-'; this is reasonable but reduces the amount of error checking possible.


    getopt_restart should be used in restartable programs, before the first call to getopt, to reinitialize the optind and optarg variables.




    char *getpass(const char *prompt)



    Prompts the user for a password, and returns a pointer to a NUL-terminated string which contains the password the user typed. A password may be up to 8 characters long, and if the string the user

    types is longer than that the returned string is truncated to 8 characters. Argument prompt is the string to print before requesting input. Input characters are obscured - that is, not echoed - as the user types them. The backspace and delete keys may be used to edit input, although in practice this is difficult to use because the user cannot see what he types.


    A static buffer is used to to hold the password, so to be sure the password is not overwritten by a subsequent call to getpass, copy it before use.

    See also: crypt, getpwent


    getpwnam getpwuid endpwent setpwent


    #include <pwd.h>

    struct passwd *getpwnam(const char *name);

    struct passwd *getpwuid(uid_t uid);

    void endpwent(void);

    struct passwd *getpwent(void);

    int setpwent(void);


    The family of functions defined in <pwd.h> are used for accessing the /etc/passwd user database. Programs should never access this database directly, as the file format or other implementation details may change in the future.


    getpwnam() reads the user database based on user name. The argument name is a pointer to the user name to lookup. getpwnam() returns a pointer to a passwd structure or NULL on an error.


    getpwuid() reads the user database based on a user ID code. Argument uid is the user ID to return information on. getpwuid() returns a pointer to a passwd structure or NULL on an error.


    The remaining three functions are used for scanning the user database. The database is initialized by using the setpwent() function; an internal access marker is set to the first entry in the database.


    getpwent() is used to retrieve the current entry, returning a pointer to a passwd structure, and moving the marker to the next entry. If there are no more entries to scan, getpwent() returns a NULL pointer. If the database should be scanned again, setpwent() may be called again to reset the marker to the first entry. In the event of an error accessing the database, NULL is returned.


    When the application is through with the database, it should call endpwent().


    struct passwd { /* see getpwent(3) */

    char *pw_name; /* pointer to user name */

    char *pw_passwd; /* pointer to encrypted password */

    int pw_uid; /* user ID */

    int pw_gid; /* group ID */

    int pw_quota; /* 'quota' field - not used */

    char *pw_comment; /* pointer Comment field */

    char *pw_gecos; /* not used */

    char *pw_dir; /* pointer to user's '$home' directory name */

    char *pw_shell; /* pointer to path of user's login shell */



    Not all of the string entries in struct passwd are used in GNO/ME, but those that are are all NUL- terminated strings.




    #include <unistd.h>

    char *getwd(char *pathname)


    Gets the current working directory (GS/OS prefix 0) and copies it to the string space pointed to by pathname. pathname must point to a buffer large enough to hold the largest conceivable pathname. In practice, a 256 byte buffer works well, but with the plethora of GS/OS file systems now available 256 may be much too small. Due to this problem, we recommend you use getwd carefully, and with a future GNO release switch to getcwd (not yet available).

    If an error occurs during the operation, getwd returns NULL and places the error code in errno. Otherwise, getwd returns the prefix in pathname.


    gtty stty


    #include <sgtty.h>

    int gtty(int filedes, struct sgttyb *argp)

    int stty(int filedes, struct sgttyb *argp)


    Set and get TTY status information in the sgttyb structures pointed to by the argument argp. See ioctl(2) and tty(4) for more details. These routines are basically short-cuts to

    ioctl(filedes, TIOCSETP, &structure) and ioctl(filedes, TIOCGETP, &structure).


    index rindex


    char *index(char *a, int b)

    char *rindex(char *a, int b)



    These functions are identical to strchr() and strrchr(), respectively. See your C compiler manual for more information. These functions are provided only for compatibility with BSD source code.




    #include <sgtty.h>

    int isatty(int filedes)


    This function returns true (1) if the file descriptor refers to a TTY (this includes PTYs) file. For all other types of descriptors, false (0) is returned.




    #include <utmp.h>

    void login(struct utmp *ut)


    Writes the /etc/utmp structure pointed to by ut to the utmp file. The slot in /etc/utmp actually written to depends on the return value of the ttyslot() function, which maps each tty device to a unique slot number, based on the contents of /etc/ttys.


    This function should not generally be used by application code.




    int mkdir(char *dirname)


    Creates a subdirectory (folder) with the name specified by dirname. Similar to the shell 'mkdir' command.


    mktemp mkstemp


    char *mktemp(char *path)

    int mkstemp(char *path)


    Creates a filename based on the string path that is guaranteed to be unique. The string path must have the following format:


    "/volume/dir1/.../dirX/fileXXXXXX" (Colons are also accepted as delimiters)


    The 'XXXXX' at the end of path is filler space that will be replaced with a string that will make path a unique filename.


    The unique string is generated by using the current process ID and a single character ASCII value; this may change in the future, and as such this behavior should not be relied upon.


    mktemp() does not actually create any files, as compared with tmpfile() in the C library.


    mkstemp() does create a file by calling open() on a unique pathname generated with mktemp().


    mktemp() returns a pointer to the new pathname (path), and mkstemp() returns a file descriptor to the new file, as would be returned by open().


    open creat close read write lseek


    #include <fcntl.h>

    int creat(const char *path, int mode)

    int open(const char *path, int oflag, ...)

    int close(int filds)

    int read(int filds, void *buf, size_t count)

    int write(int filds, void *buf, size_t count)

    long lseek(int filds, long offset, int whence)


    These are similar to the low-level I/O routines provided by ORCA/C. However, the GNO versions of these routines deal with actual GS/OS refNums for filds. (ORCA/C's versions use a special library-maintained definition of file descriptor in order to fake the UNIX dup() system call. Here they revert to standard UNIX usage because GNO provides a real dup(2) handled within the kernel).


    open() uses vararg (variable argument) parameters. The third parameter is only expected (and is required) if O_CREAT is one of the flags specified in 'mode', and specifies the access permissions to be given the new file.


    IMPORTANT NOTE: GNO's read()/write() functions take a size_t count, whereas ORCA's only take unsigned count. When recompiling code with the new GNO libraries, make very certain that any programs that use read()/write() do a #include <fcntl.h>, or it is likely that your programs will crash.


    opendir readdir rewinddir closedir


    #include <dirent.h>

    DIR *opendir(char *filename)

    struct dirent *readdir(DIR *dirp)

    void rewinddir(DIR *dirp)

    closedir(DIR *dirp)

    (POSIX 1)


    This family of functions provides a machine-independent way to read a list of files (and information about them) from directories.


    opendir() opens the directory specified by filename and prepares it for the scan operation. opendir() returns a pointer to a structure which is used in the other dirent calls.


    readdir() takes a DIR * as argument and returns information about the next file in the directory. The return value is a pointer to a dirent structure (described below).


    If you wish to scan the directory again without closing and then reopening the directory, use rewinddir(). It resets the scan to the beginning of the directory.


    When finished with the directory, call closedir().


    #define MAXNAMLEN 32 /* maximum filename length */


    struct dirent /* data from getdents()/readdir() */


    long d_ino; /* inode number of entry */

    off_t d_off; /* offset of disk directory entry */

    unsigned short d_reclen; /* length of this record */

    char d_name[MAXNAMLEN]; /* name of file */

    unsigned short d_namlen; /* length of filename */



    dirent is the structure returned by readdir() that contains information about the file. d_ino is not used on the Apple IIGS because neither ProDOS nor HFS have the concept of an "inode", but to simulate its use a unique d_ino value is returned for each readdir() call. d_off is the offset in the directory of the current file; the first entry is number 1, the second 2, etc. d_reclen specifies the length of the entire dirent structure. d_name is a short array containing the filename of the current file read from the directory. d_namlen is the length of the string in d_name.


    More specific information can be obtained by passing d_name to the stat() system call.

    See also: stat(2)




    int needsgno(void)


    This function returns 1 if GNO is operating, and 0 if it is not. Use this function to abort programs that use GNO-specific features, or to allow them to enable non-GNO environment dependent code.




    ~GNO_PARSEARG subroutine (4:commandline,4:argptr)

    ~GNO_PARSEARG(char *commandline, char **argptr)


    This function will take the command-line passed to a utility and parse it into an argv,argc structure like those used in C programs. This was written NOT as a replacement for a C parser, but for use by assembly language programmers writing shell commands.


    commandline is the raw command line string as passed by the shell in the X & Y registers. argptr is a pointer to an argv[]-style array. parsearg returns the number of arguments found in the accumulator.


    This function ASSUMES that the ByteWorks Memory Manager has been started up and is usable.


    This function is based on actual GNO/ME shell (gsh) parsing code.


    pcreate pbind pgetport psend preceive pdelete preset pgetcount


    #include <sys/ports.h>

    int pcreate(int count)

    int pbind(int portid, char *name)

    int pgetport(char *name)

    int psend(int portid, long int msg)

    long preceive(int portid)

    int pdelete(int portid, int (*dispose)())

    int preset(int portid, int (*dispose)())

    int pgetcount(int portid)


    The Ports IPC mechanism is a very flexible, powerful and efficient method of interprocess communication. A port is a queue that can contain a number of 32-bit values. The size of the port (how many messages it can contain) is specified in the pcreate() call.


    Creation of a port is done with pcreate(). You must specify the size of the port in this call, which must be at least 1 (one). The larger the port, the more data it can hold without blocking a process sending data to the port. pcreate() returns a port ID value that must be used in subsequent calls to the Port IPC routines.


    A name may be associated with a port; this allows totally unrelated processes to access a port without having to communicate the port ID through some other method, and without knowing the process ID of the other. To bind a name to a port, call pbind(). The name argument may be any length, but at most 32 characters are significant. If a name has already been bound to the chosen portid, an error is returned. To get the portid of a port by its name, use the pgetport() call. Pass in the name of the port whose port ID you wish to obtain. If no port has that name, an error is returned. Names are only unbound from a port when a port is deleted.


    psend() is used to send a 32-bit datum to a port. If the port is full (that is, if there are more unread messages in the port than are specified in the pcreate() call) then the sending process blocks until a message is read from the port. Messages are retrieved from a port using the preceive() call. pgetcount() returns the number of messages in the port that have not been received; this may be used to avoid blocking on a psend() call.


    If you wish to clear the contents of a port, say to synchronize communication after an error condition, use the preset() call. The arguments to this call are the port ID and the address of a 'dispose' function. Each message in the port, before being cleared, is passed to the dispose function so that appropriate clean-up action may be taken on the data. For example, if the messages correspond to the address of memory blocks obtained with malloc(), you could pass 'free()' as the dispose function to automatically deallocate that memory. If you don't wish to take any special action on the data being cleared, pass NULL for the dispose argument.


    To destroy a port, make the pdelete() call. It accepts the same arguments as preset() and they operate as described above. The difference between preset() and pdelete() is that the latter totally destroys a port; it may no longer be used. preset() clears a port's data but leaves the port open for more data transmission.


    For an example of the use of ports, see the source code to the print spooling utilities (lpr, lpd, FilePort). These are available from Procyon upon request.




    Compile and execute regular-expression programs. Use 'man regexp' for details.


    send receive recvtim recvclr


    #include <gno/gno.h>

    int send(int pid, unsigned long msg);

    unsigned long receive(void);

    unsigned long recvtim(int timeout);

    unsigned long recvclr(void);


    These kernel functions comprise GNO's message-passing IPC system. Messages are unsigned 32-bit data values. A process sends a message to another by using the send() call. You must specify the process ID of the recipient and the message to pass. To receive a message, a process makes the receive() call. If no message has been sent to the process, the process sleeps until a message arrives. recvclr() is used to clear any pending message a process may have waiting. recvtim() is similar to receive() but takes a timeout argument, specified in 1/10ths of a second. If no message has been received in timeout/10 seconds, recvtim() fails and returns -1. The message buffer for a process is only one message deep; any attempt to send() a message to a process that already has one queued results in an error. For an IPC system with a deeper queue, see the Ports IPC section.


    A receive() that is interrupted by a signal will abort and return -1, with errno set to EINTR.


    setenv unsetenv


    #include <unistd.h>

    int setenv(const char *name, const char *value, int rewrite)

    void unsetenv(const char *name)


    Set the value of the environmental variable name to be value. If rewrite is set, setenv replaces any current value. The variable is considered 'exported', according to the shell convention for variables. No errors are possible, and the only return code is 0.


    unsetenv removes the environmental variable specified by name from the variable table. The variable is no longer accessible, and any value that was assigned to that variable is deallocated. No errors are possible, and there is no return value.




    int statfs(char *path, struct statfs *buf)


    Returns information on the filesystem that the file path resides on. The information is placed in a structure pointed to by the input argument buf. Read statfs(3) for more information.




    #include <string.h>

    char *strdup(const char *str)


    strdup() creates a copy of the NUL-terminated string pointed to by str. It allocates a piece of memory exactly large enough to hold the string with the malloc() library function. When you no longer need the copy, dispose of it with free().

    See also: strcpy(), malloc(), free()




    #include <string.h>

    char *strsep(char **stringp, const char *delim)


    Gets a token from string *stringp, where tokens are nonempty strings separated by characters from delim.


    strsep writes NULs into *stringp to end tokens. delim need not remain constant from call to call. On return, *stringp points past the last NUL written (if there might be further tokens), or is NULL (if there are definitely no more tokens). If *stringp is NULL, strsep returns NULL.




    The termcap library accesses the /etc/termcap database, which is used to provide terminal- independent support for advanced terminal features, such as various text modes, scrolling regions, cursor movement, and more. Use 'man termcap' for more details.




    #include <unistd.h>

    char *ttyname(int fd)


    Returns the filename of the tty referenced by file descriptor fd. If fd does not refer to a tty file, NULL is returned. Otherwise, a pointer to the filename (NUL-terminated string) is returned.


    tty filenames are in the format ".ttyXX", where XX is a device designator. When porting existing BSD code, take care to watch for code that depends on the existence of a '/' character in the string, as UNIX tty files are in the form "/dev/ttyXX".


    The string pointer returned points to a static buffer, and will be overwritten on any further calls to ttyname. Copy the string if you wish to preserve it.




    int unlink(char *fname)


    Causes the link file specified by fname to be removed. Since GNO/ME does not yet support symbolic or hard file links, this function operates the same as the remove() (or DestroyGS) routine.


  • tty - general terminal interface

  • #include <sgtty.h>

  • This file documents the special file .tty and the terminal drivers used for user-oriented I/O.
  • The Controlling Terminal

  • Every process has associated with it a controlling terminal, which is the terminal the process was invoked from. In some versions of Unix, the controlling terminal association is responsible for job control; this is not so under GNO. A process' controlling terminal is inherited from its parent. By opening the special file .tty, a process can access its controlling terminal. This is useful where the input and output of a process was redirected and the process wants to be sure of outputting or getting input from the user at the terminal.

    A process can remove the association it has with its controlling terminal by opening the file .tty and issuing an

    ioctl(f, TIOCNOTTY, 0);

    This is often desirable in server processes.

  • Process Groups

  • Every terminal has an associated process group. Any time a signal-generating special character is typed at the terminal, the terminal's process group is sent that signal. Unix systems set process groups using ioctl() calls, but under GNO a new interface method is used; process group assignments are controlled with the JOB CONTROL(2) routines.
  • Modes

  • There are four modes in which terminal drivers operate. These modes control how the driver deals with I/O.

    cooked This is the default mode of the terminal driver. If an incoming character is one of the special characters defined in sgttyb, tchars, or ltchars, the appropriate action is performed (see below). This mode also allows for input editing, as input is internally buffered line by line, and data is returned to a reading process only when CR is entered.

    cbreak Input is returned on a per-character basis, instead of line by line as in cooked mode. If no data is available, a read will block the calling process. If data is available, a number of characters up to but not exceeding the requested number will be returned. Special characters such as t_intrc are not handled, but are passed on to the caller as data.

    raw Like cbreak mode, except that no input or output processing whatsoever is performed.

  • Summary of terminal control modes


  • Due to the colorful history of Unix systems, the data structures used to manipulate terminal modes and settings are separated into four groups. Future revisions of GNO will implement the POSIX termio interface, which consolidates these structures into one place.
  • sgtty

  • The basic ioctls use the structure defined in <sgtty.h>:

    struct sgttyb {

    char sg_ispeed;

    char sg_ospeed;

    char sg_erase;

    char sg_kill;

    short sg_flags;


    sg_ispeed and sg_ospeed indicate the baud rates for input and output according to the following table. Speed changes that do not apply to a particular piece of hardware are ignored (for instance, the console driver does not access a serial port so all baud rate settings are, in effect, impossible). Also, not all the baud rates supported by a particular device are allowed to be set from this interface.

    These symbolic names for the baud rate settings are defined in <sgtty.h>.

    B0 0 (hang up dataphone)

    B50 1 50 baud

    B75 2 75 baud

    B110 3 110 baud

    B134 4 134.5 baud

    B150 5 150 baud

    B300 7 300 baud

    B600 8 600 baud

    B1200 9 1200 baud

    B1800 10 1800 baud

    B2400 11 2400 baud

    B4800 12 4800 baud

    B9600 13 9600 baud

    B19200 and

    EXTA 14 19200 baud

    B38400 and

    EXTB 15 38400 baud

    B57600 6 57600 baud

    The sg_erase and sg_kill fields specify the line-editing erase and kill characters. sg_erase is 0x7F (delete) by default, and sg_kill is not currently used.

    sg_flags is a bitmapped value that indicates various state settings for the terminal driver (values are in hex).

    EVENP 0x80 Use Even parity (serial devices only)

    ODDP 0x40 Use Odd parity (serial devices only)

    RAW 0x20 Raw mode: wake up on all characters, 8-bit interface

    CRMOD 0x10 Map CR into LF; output LF as CR-LF

    ECHO 0x08 Echo (full duplex)

    CBREAK 0x02 Return each character as soon as typed

    TANDEM 0x01 Automatic flow control

    RAW and CBREAK modes were described above, in Modes.

    If the CRMOD bit is set, a line feed character is appended to any echoed or ouputted carriage return.

    The ECHO bit controls input echoing; if enabled, any characters read from the terminal are echoed. This behavior differs slightly from Unix, where input characters are echoed as soon as typed.

    TANDEM mode enables automatic software flow control utilizing the special characters t_startc and t_stopc in tchars (below). Whenever the input queue is in danger of overflowing, the system sends t_stopc; when the queue has drained sufficiently, t_startc is sent. This mode has no effect on the console driver.

    Note: t_startc and t_stopc are used for both directions of flow control; when t_stopc is received from a remote system (or user), the terminal stops output, and when t_startc is received output resumes. Certain drivers may also require t_stopc and t_startc to be the same character, in which case one or the other setting will be ignored. See the driver's documentation for details.

    Basic Ioctls

    Most ioctl() calls apply to terminals. They have the form

    #include <sgtty.h>

    ioctl(int filedes, unsigned long code, void *arg)

    arg is usually a pointer to a structure or int. The ioctl codes that apply to sgtty are:

    TIOCGETP Fetch the basic parameters associated with the terminal, and store in the sgttyb structure pointed to by arg.

    TIOCSETP Set the terminal's basic parameters according to the sgttyb structure pointed to by arg. The input queue is flushed, and the call waits for the output queue to drain before the parameters are changed.

    TIOCSETN This is like TIOCSETP, except there is no delay and the input queue is not flushed.

    With the following codes arg is ignored.

    TIOCEXCL Set "exclusive-use" mode. The terminal may not be opened again by any process until all existing references are closed.

    TIOCNXCL Turns off "exclusive-use" mode.

    TIOCHPCL When the last reference to the terminal is closed, the terminal line is forced to hang up. This applies only to modem drivers.

    With the following codes, arg is a pointer to an int.

    TIOCGETD The current line discipline number is stored in the int pointed to by arg. This value is currently ignored.

    TIOCSETD The line discipline is set according to the int pointed to by arg.

    TIOCFLUSH The specified queue is flushed. If the value pointed to by arg is zero, both the input and output queues are flushed. If the value is FREAD (defined in <sys/file.h>), the input queue is flushed. If the value is FWRITE, the output queue is flushed.

    The last few calls permit detailed control of the driver. In cases where an argument is required, it is described. Otherwise, arg should be a NULL pointer.

    TIOCSTI The character pointed to by the argument is placed in the input queue as if it had been typed on the terminal.

    TIOCSBRK Begins a break sequence on the terminal.

    TIOCCBRK Ends a break sequence.

    TIOCSDTR The DTR line is turned on

    TIOCCDTR The DTR line is turned off

    TIOCSTOP Output is stopped as if t_stopc had been typed on the terminal.

    TIOCSTART If output is stopped, it is resumed as if t_startc had been typed on the terminal.

    TIOCOUTQ The number of characters in the output queue is returned in the int pointed to by arg.

    FIONREAD The number of characters immediately available for input from the terminal is returned in the int pointed to by arg. This is the preferred method of non-blocking I/O (checking for the presence of characters without waiting for them).

  • Tchars

  • The second structure associated with a terminal defines special characters. The structure is defined in <sys/ioctl.h> which is automatically included by <sgtty.h>.

    struct tchars {

    char t_intrc; /* interrupt */

    char t_quitc; /* quit */

    char t_startc; /* start output */

    char t_stopc; /* stop output */

    char t_eofc; /* end-of-file */

    char t_brkc; /* input delimiter (like nl) */


    The default values for these characters are ^C, ^\, ^Q, ^S, ^D and -1 respectively. A value of -1 for any of the characters means that the effect of that character is ignored. The stop and start characters may be the same to produce a 'toggle' effect. It is not recommended to set any of the other characters to the same values; the order in which the special characters are checked is not defined, and the results you get may not be what was expected.

    The ioctl calls that apply to tchars are:

    TIOCGETC Returns the special characters settings in the tchars structure pointed to by arg.

    TIOCSETC The special characters are set according to the given structure.

  • Local mode


  • The third structure in the terminal interface is a local mode word. The various bitfields in this word are as follows (values are in hex):

    LCRTBS 0x0001 Backspace on erase rather than echoing erase

    LPRTERA 0x0002 Printing terminal erase mode

    LCRTERA 0x0004 Erase character echoes as backspace-space-backspace

    LTILDE 0x0008 Convert ~ to ` on output (for Hazeltine terminals)

    LMDMBUF 0x0010 Stop/start output when carrier drops

    LLITOUT 0x0020 Suppress output translations

    LTOSTOP 0x0040 Send SIGTTOU for background output (not implemented)

    LFLUSHO 0x0080 Output is being flushed

    LNOHANG 0x0100 Don't send hangup when carrier drops

    LPASSOUT 0x0200 Cooked mode with 8-bit output

    LCRTKIL 0x0400 BS-space-BS erase entire line on line kill

    LPASS8 0x0800 Pass all 8 bits through on input, in any mode

    LCTLECH 0x1000 Echo input control chars as ^?

    LPENDIN 0x2000 Retype pending input at next read or input character

    LDECCTQ 0x4000 Only ^Q restarts output after ^S

    LNOFLSH 0x8000 Inhibit flushing of pending I/O when intr char is typed

    The ioctl's used to access the local mode follow. arg in all cases is a pointer to an int.

    TIOCLBIS The bits of the local mode word specified by `1' bits in the argument are set; this operation is a bit-wise OR.

    TIOCLBIC The bits of the local mode word specified by `1' bits in the argument are cleared; this operation ANDs the local mode with the bitwise negation of the argument.

    TIOCLSET Sets the local mode word to the value of the argument.

    TIOCLGET Returns the local mode word in the int pointed to by arg.

  • Local Special Characters

  • The fourth terminal structure is another set of special characters. The structure is named ltchars and is again defined in <ioctl.h>.

    struct ltchars {

    char t_suspc; /* stop process signal */

    char t_dsuspc; /* delayed stop process signal */

    char t_rprntc; /* reprint line */

    char t_flushc; /* flush output (toggles) */

    char t_werasc; /* word erase */

    char t_lnextc; /* literal next character */


    Defaults for these characters are ^Z, ^Y, ^R, ^O, ^W, and ^V. As with tchars, a value of -1 disables the effect of that character. Only t_suspc is currently implemented for the console driver.

    The applicable ioctl functions are:

    TIOCSLTC sets the local characters according to the ltchars structure pointed to by arg.

    TIOCGLTC retreives the local characters, storing them in the argument.

  • Window/terminal sizes


  • Provision is made for storage of the current window or terminal size along with the other terminal information. This info is recorded in a winsize structure, and is defined in <ioctl.h>:

    struct winsize {

    unsigned short ws_row; /* rows, in characters */

    unsigned short ws_col; /* columns, in characters */

    unsigned short ws_xpixel; /* horizontal size, pixels */

    unsigned short ws_ypixel; /* vertical size, pixels */


    A '0' in a field indicates that the field value is undefined. '0' is the default when a terminal is first opened. These values are not used by the terminal driver itself; rather, they are for the benefit of applications. The ioctl calls for winsize are:

    TIOCGWINSZ Returns the window size parameters in the provided winsize structure.

    TIOCSWINSZ Sets the window size parameters. If any of the values differ from the old ones, a SIGWINCH signal is sent to the terminal's process group.


  • .tty

    .ttyco (console driver)

    .tty* (user-installed drivers)


  • GNO Shell Reference Manual, stty(1), ioctl(2), signal(2)