代码中创建新终端

最常见于使用SecureCRT等工具远程创建打开终端,下面的代码演示在代码中创建打开终端:

  1. // filename: term.cpp
  2. // g++ -g -o term term.cpp -lutil
  3. // login_tty()等在-lutil中
  4. #include fcntl.h>
  5. #include pty.h> // openpty and forkpty
  6. #include signal.h>
  7. #include stdio.h>
  8. #include stdlib.h>
  9. #include string.h>
  10. #include stropts.h> // ioctl
  11. #include sys/prctl.h> // prctl
  12. #include unistd.h>
  13. #include utmp.h> // login_tty

  14. static void on_signal(int signo)
  15. {
  16.     printf("[%d]signal: %s\n", getpid(), strsignal(signo));
  17. }

  18. int main()
  19. {
  20.     int amaster = 0;
  21.     char name[100];
  22.     struct termios termp; // termios.h (bits/termios.h)
  23.     struct winsize winp; // term.h(bits/ioctl-types.h)
  24.     
  25.     // forkpty的实现调用了openpty()、fork()和login_tty()
  26.     pid_t pid = forkpty(&amaster, name, &termp, &winp);
  27.     if (pid 0)
  28.     {
  29.         perror("forkpty");
  30.         exit(1);
  31.     }
  32.     else if (0 == pid)
  33.     {
  34.         // 子进程隶属于新的终端
  35.         // 子进程中的printf()在父进程隶属的终端上看不见
  36.         
  37.         // 父进程被中断或挂掉时,会向子进程发送SIGHUP
  38.         signal(SIGHUP, on_signal);
  39.         printf("child: %d\n", getpid());

  40.         while (true)
  41.         {
  42.             sleep(1);
  43.         }

  44.         exit(0);
  45.     }
  46.     else if (pid > 0)
  47.     {
  48.         // 父进程仍然使用之前的终端
  49.         // 如果中断会向了进程发送SIGHUP

  50.         printf("pid: %d/%d\n", getpid(), pid);
  51.         printf("name: %s\n", name);
  52.         printf("amaster: %d\n", amaster);
  53.         printf("win.row: %d\n", winp.ws_row);
  54.         printf("win.col: %d\n", winp.ws_col);
  55.         printf("win.xpixel: %d\n", winp.ws_xpixel);
  56.         printf("win.ypixel: %d\n", winp.ws_ypixel);
  57.         
  58.         getchar();
  59.     }

  60.     return 0;
  61. }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值