linux c伪终端函数,C编程 - 伪终端(PTY)的一个例子

a32703b00f44?utm_campaign=maleskine&utm_content=note&utm_medium=seo_notes&utm_source=recommendation

image.png

/*

* An example of pseudo terminal

*/

#define _GNU_SOURCE

#include //xxxpt()

#include //O_RDWR

#include //fprintf()

#include //perror(),errno

#include //read(),write(),fork(),open(),close()

#include

int main(void)

{

int fdm, fds, rc;

char input[150];

fdm = posix_openpt(O_RDWR);

if (fdm < 0) {

perror("when posix_openpt() pty-master");

return 1;

}

rc = unlockpt(fdm);

if (rc != 0) {

perror("when unlockpt() pty-master");

return 1;

}

fds = open(ptsname(fdm), O_RDWR);

if (fds < 0) {

perror("when open() pty-slave");

return 1;

}

if (fork()) { // Father

close(fds);

while (1) {

write(1, "Input : ", sizeof("Input : "));

rc = read(0, input, sizeof(input)-1);

if (rc > 0) {

write(fdm, input, rc);

rc = read(fdm, input, sizeof(input)-1);

if (rc > 0) {

fprintf(stdout, "111-%s", input);

}

else

break;

}

else

break;

}

}

else { // Child

close(fdm);

struct termios settings;

rc = tcgetattr(fds, &settings);

cfmakeraw (&settings);

tcsetattr (fds, TCSANOW, &settings);

dup2(fds, 0);

dup2(fds, 1);

dup2(fds, 2);

while (1)

{

rc = read(0, input, sizeof(input) - 1);

if (rc > 0) {

input[rc - 1] = '\0';

fprintf(stdout, "222-%s\n", input);

}

else

break;

}

}

return 0;

}

$ gcc a.c && ./a.out

Input : aaa

111-222-aaa

Input : bbb

111-222-bbb

参考

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值