免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 1333 | 回复: 0
打印 上一主题 下一主题

[C] Linux终端间通信 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2014-03-17 16:21 |只看该作者 |倒序浏览
    自己编写了一个小程序,想实现将一个程序的从一个终端的标准输入获取数据,并将标准输出在同一终端上输出。
    现在遇到的问题是:在新打开的终端中输入的数据时并不会完全被程序接受,而且所输入的内容还有可能被shell解释执行,导致程序无法从新打开的终端上正确获取数据。
以下是程序代码:
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <unistd.h>
  4. #include <errno.h>
  5. #include <string.h>
  6. #include <sys/un.h>
  7. #include <sys/socket.h>
  8. #include <stddef.h>
  9. #include <fcntl.h>

  10. #define MAXLINE 1024

  11. int main(void)
  12. {
  13.     pid_t pid;
  14.     int ptsfd;
  15.     int rc, a;
  16.     char result_buf[MAXLINE], command[MAXLINE];
  17.     FILE *fp;

  18.     sprintf(command, "gnome-terminal -x bash -c \"tty > a\";gnome-terminal;cat a; rm a");
  19.     fp = popen(command, "r");
  20.     if (fp == NULL) {
  21.         fprintf(stderr, "popen error! \n");
  22.         exit (errno);
  23.     }
  24.     while (fgets(result_buf, sizeof(result_buf), fp) != NULL) {
  25.         if (result_buf[strlen(result_buf) - 1] == '\n')
  26.             result_buf[strlen(result_buf) - 1] = '\0';
  27.         printf("command: %s \noutput: %s\n", command, result_buf);
  28.     }
  29.     rc = pclose(fp);
  30.     if (rc == -1) {
  31.         fprintf(stderr, "pclose error\n");
  32.         exit (-1);
  33.     }
  34.     else
  35.         printf("command %s's child terminal code is %d %d\n", command, rc, WEXITSTATUS(rc));

  36.     ptsfd = open(result_buf, O_RDWR);
  37.     int len;
  38.     char tmp[10] = {0};
  39.     bzero(command, MAXLINE);
  40.     while ((len = read(ptsfd, tmp, 10)) > 0) {
  41. //      printf("read %d successfully, totally %d bytes\n", tmp, len);
  42.         strcat(command, tmp);
  43.         if (tmp[0] != 13) {
  44.             continue;
  45.         }
  46.         if((len = write(ptsfd, "----test----", 13)) == -1)
  47.             break;
  48.         printf("write command is %s, totally %d bytes\n", command, strlen(command));
  49.         fflush(NULL);
  50.         bzero(command, MAXLINE);
  51.     }
  52.     close(ptsfd);
  53.     return 0;
  54. }
复制代码
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP