小编C C*_*der的帖子

如何在 C 中可靠地找到与进程关联的终端名称?

请参阅以下代码。

#include <stdio.h>
#include <unistd.h>

int main()
{
    printf("ttyname(0): %s\n", ttyname(0));
    printf("ttyname(1): %s\n", ttyname(1));
    printf("ttyname(2): %s\n", ttyname(2));
    printf("ctermid(NULL): %s\n", ctermid(NULL));

    /* Sleep for sometime so that we can manually run the ps command to
     * see the terminal associated with the process. */
    sleep(10);

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

我按如下方式编译并运行它。

$ gcc foo.c
$ ./a.out 
ttyname(0): /dev/pts/3
ttyname(1): /dev/pts/3
ttyname(2): /dev/pts/3
ctermid(NULL): /dev/tty
Run Code Online (Sandbox Code Playgroud)

在另一个终端中,我运行ps命令来确认终端名称。

$ ps -ef | grep a.out | grep -v grep
coder     1498  1473  0 19:19 pts/3 …
Run Code Online (Sandbox Code Playgroud)

c terminal posix

3
推荐指数
1
解决办法
1964
查看次数

标签 统计

c ×1

posix ×1

terminal ×1