Advanced Programming in UNIX Environment Episode 116

本文详细介绍了如何在 C 语言中实现 POSIX.1 的 ctermid 函数,该函数用于获取进程的控制终端名称,同时讨论了其在不同操作系统中的应用,以及如何测试 isatty 和 ttyname 函数。通过这些函数,开发者可以提高代码的移植性和可读性。
摘要由CSDN通过智能技术生成
Terminal Identification

Historically, the name of the controlling terminal in most versions of the UNIX System has been /dev/tty. POSIX.1 provides a runtime function that we can call to determine the name of the controlling terminal.

#include <stdio.h>
char *ctermid(char *ptr);

If ptr is non-null, it is assumed to point to an array of at least L_ctermid bytes, and the name of the controlling terminal of the process is stored in the array. The constant L_ctermid is defined in <stdio.h>. If ptr is a null pointer, the function allocates room for the array (usually as a static variable). Again, the name of the controlling terminal of the process is stored in the array.

In both cases, the starting address of the array is returned as the value of the function. Since most UNIX systems use /dev/tty as the name of the controlling terminal, this function is intended to aid portability to other operating systems.

All four platforms described in this text return the string /dev/tty when we call ctermid.

#include <stdio.h>
#include <string.h>

static char ctermid_name[L_ctermid];

char * ctermid(char *str)
{
    if(str==NULL)
        str=ctermid_name;
    return strcpy(str, "dev'tty"));
}

Implementation of POSIX.1 ctermid function

#include <unistd.h>

int isatty(int fd);
char *ttyname(int fd);
#include <termios.h>

int isatty(int fd)
{
	struct termios ts;
	return (tcgetattr(fd, &ts)!=-1);
}

Implementation of POSIX.1 isatty function

#include "apue.h"

int main(void)
{
    printf("fd 0: %s\n", isatty(0)?"tty": "not a tty");
    printf("fd 1: %s\n", isatty(1)?"tty": "not a tty");
    printf("fd 2: %s\n", isatty(2)?"tty": "not a tty");
    return 0;
}

Test the isatty function

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值