Chinaunix首页 | 论坛 | 博客
  • 博客访问: 8053536
  • 博文数量: 594
  • 博客积分: 13065
  • 博客等级: 上将
  • 技术积分: 10324
  • 用 户 组: 普通用户
  • 注册时间: 2008-03-26 16:44
个人简介

推荐: blog.csdn.net/aquester https://github.com/eyjian https://www.cnblogs.com/aquester http://blog.chinaunix.net/uid/20682147.html

文章分类

全部博文(594)

分类: LINUX

2015-04-23 14:00:54

最常见于使用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. }

阅读(2783) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~