前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >代码中创建新终端

代码中创建新终端

作者头像
一见
发布2018-08-10 17:55:58
6520
发布2018-08-10 17:55:58
举报
文章被收录于专栏:蓝天蓝天蓝天

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

 // filename: term.cpp
  
 // g++ -g -o term term.cpp -lutil
 
 // login_tty()等在-lutil中
 
 			#include <fcntl.h>
 
 			#include <pty.h> // openpty and forkpty
 
 			#include <signal.h>
 
 			#include <stdio.h>
 
 			#include <stdlib.h>
 
 			#include <string.h>
 
 			#include <stropts.h> // ioctl
 
 			#include <sys/prctl.h> // prctl
 
 			#include <unistd.h>
 
 			#include <utmp.h> // login_tty
 
 
 
 			static void on_signal(int signo)
 
 {
 
 			    printf("[%d]signal: %s\n", getpid(), strsignal(signo));
 
 }
 
 
 
 int main()
 
 {
 
 int amaster = 0;
 
 			    char name[100];
 
 			    struct termios termp; // termios.h (bits/termios.h)
 
 			    struct winsize winp; // term.h(bits/ioctl-types.h)
 
 
 
 // forkpty的实现调用了openpty()、fork()和login_tty()
 
 			    pid_t pid = forkpty(&amaster, name, &termp, &winp);
 
 if (pid < 0)
 
 {
 
 			        perror("forkpty");
 
 exit(1);
 
 }
 
 else if (0 == pid)
 
 {
 
 // 子进程隶属于新的终端
 
 // 子进程中的printf()在父进程隶属的终端上看不见
 
 
 
 // 父进程被中断或挂掉时,会向子进程发送SIGHUP
 
 			        signal(SIGHUP, on_signal);
 
 			        printf("child: %d\n", getpid());
 
 
 
 while (true)
 
 {
 
 			            sleep(1);
 
 }
 
 
 
 exit(0);
 
 }
 
 else if (pid > 0)
 
 {
 
 // 父进程仍然使用之前的终端
 
 // 如果中断会向了进程发送SIGHUP
 
 
 
 			        printf("pid: %d/%d\n", getpid(), pid);
 
 			        printf("name: %s\n", name);
 
 			        printf("amaster: %d\n", amaster);
 
 			        printf("win.row: %d\n", winp.ws_row);
 
 			        printf("win.col: %d\n", winp.ws_col);
 
 			        printf("win.xpixel: %d\n", winp.ws_xpixel);
 
 			        printf("win.ypixel: %d\n", winp.ws_ypixel);
 
 
 
 			        getchar();
 
 }
 
 
 
 			    return 0;
 
 } 
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2015-04-23 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档