Loading... # 简介 本代码只示例通过pipe 管道向pty发送命令执行后,返回管道读取,之后向socket发送,所有显示的效果和控制台一样 # 代码 ```cpp #include <fcntl.h> #include <sys/types.h> //old UNIX flag must be add sys/types.h before /sys header files #include <sys/socket.h> #include <arpa/inet.h> #include <stdlib.h> #include <stdio.h> #include <sys/ioctl.h> #include <termios.h> #include <unistd.h> #include <sys/epoll.h> #include <sys/wait.h> #include <string.h> #include <pty.h> #include <utmp.h> #include <errno.h> #define MAXBUF 1024 void sys_err(const char* str) { perror(str); exit(1); } void sig_child(int signo) { int status; pid_t pid = wait(&status); printf("child %d terminated.\r\n", pid); exit(0); } int swap(int InPutPipe, int InOutPipe, int master); int main(void) { int fdIn[2],fdOut[2]; pipe(fdIn); pipe(fdOut); char ptsname[32] = { 0 }; int master = -1; pid_t pid = -1; signal(SIGCHLD, sig_child); //fork and open pty pid = forkpty(&master, ptsname, NULL, NULL); //child open bash shell if (pid == 0) execlp("/bin/bash", "-i", NULL); //创建子进程 pid_t apid = fork(); if (apid == 0) { //parent swap data printf("[%s][PID=%d]\r\n", ptsname, (int)pid); swap(fdIn[0], fdOut[1], master); } else { char buf[12] = { "ls -al\r\n"}; char Pop[12] = {"pwd\r\n"}; char Buff[0x200]{ "" }; write(fdIn[1], buf, sizeof(buf)); while (true) { read(fdOut[0], Buff, sizeof(Buff)); printf("%s", Buff); } } return 0; } int swap(int InPutPipe,int InOutPipe, int master) { int epfd, nfds, nb; struct epoll_event ev[2], events[5]; unsigned char buf[MAXBUF]; epfd = epoll_create(2); ev[0].data.fd = InPutPipe; ev[0].events = EPOLLIN | EPOLLET; epoll_ctl(epfd, EPOLL_CTL_ADD, InPutPipe, &ev[0]); ev[1].data.fd = master; ev[1].events = EPOLLIN | EPOLLET; epoll_ctl(epfd, EPOLL_CTL_ADD, master, &ev[1]); for (;;) { nfds = epoll_wait(epfd, events, 5, -1); for (int i = 0; i < nfds; i++) { if (events[i].data.fd == InPutPipe) { nb = read(InPutPipe, buf, MAXBUF); if (!nb) goto __LABEL_EXIT; write(master, buf, nb); } if (events[i].data.fd == master) { nb = read(master, buf, MAXBUF); if (!nb) goto __LABEL_EXIT; write(InOutPipe, buf, nb); //外部输出 } } } __LABEL_EXIT: close(master); close(epfd); return 0; } //---------------------SOCKET转发 int swap(int sockfd, int master) { int epfd, nfds, nb; struct epoll_event ev[2], events[5]; unsigned char buf[MAXBUF]; epfd = epoll_create(2); ev[0].data.fd = sockfd; ev[0].events = EPOLLIN | EPOLLET; epoll_ctl(epfd, EPOLL_CTL_ADD, sockfd, &ev[0]); ev[1].data.fd = master; ev[1].events = EPOLLIN | EPOLLET; epoll_ctl(epfd, EPOLL_CTL_ADD, master, &ev[1]); for (;;) { nfds = epoll_wait(epfd, events, 5, -1); for (int i = 0; i < nfds; i++) { if (events[i].data.fd == sockfd) { nb = read(sockfd, buf, MAXBUF); if (!nb) goto __LABEL_EXIT; write(master, buf, nb); } if (events[i].data.fd == master) { nb = read(master, buf, MAXBUF); if (!nb) goto __LABEL_EXIT; write(sockfd, buf, nb); } } } __LABEL_EXIT: close(sockfd); close(master); close(epfd); return 0; } ``` 最后修改:2022 年 01 月 10 日 © 允许规范转载 赞 0 如果觉得我的文章对你有用,请随意赞赏