- 论坛徽章:
- 0
|
自己编写了一个小程序,想实现将一个程序的从一个终端的标准输入获取数据,并将标准输出在同一终端上输出。
现在遇到的问题是:在新打开的终端中输入的数据时并不会完全被程序接受,而且所输入的内容还有可能被shell解释执行,导致程序无法从新打开的终端上正确获取数据。
以下是程序代码:- #include <stdio.h>
- #include <stdlib.h>
- #include <unistd.h>
- #include <errno.h>
- #include <string.h>
- #include <sys/un.h>
- #include <sys/socket.h>
- #include <stddef.h>
- #include <fcntl.h>
- #define MAXLINE 1024
- int main(void)
- {
- pid_t pid;
- int ptsfd;
- int rc, a;
- char result_buf[MAXLINE], command[MAXLINE];
- FILE *fp;
- sprintf(command, "gnome-terminal -x bash -c \"tty > a\";gnome-terminal;cat a; rm a");
- fp = popen(command, "r");
- if (fp == NULL) {
- fprintf(stderr, "popen error! \n");
- exit (errno);
- }
- while (fgets(result_buf, sizeof(result_buf), fp) != NULL) {
- if (result_buf[strlen(result_buf) - 1] == '\n')
- result_buf[strlen(result_buf) - 1] = '\0';
- printf("command: %s \noutput: %s\n", command, result_buf);
- }
- rc = pclose(fp);
- if (rc == -1) {
- fprintf(stderr, "pclose error\n");
- exit (-1);
- }
- else
- printf("command %s's child terminal code is %d %d\n", command, rc, WEXITSTATUS(rc));
- ptsfd = open(result_buf, O_RDWR);
- int len;
- char tmp[10] = {0};
- bzero(command, MAXLINE);
- while ((len = read(ptsfd, tmp, 10)) > 0) {
- // printf("read %d successfully, totally %d bytes\n", tmp, len);
- strcat(command, tmp);
- if (tmp[0] != 13) {
- continue;
- }
- if((len = write(ptsfd, "----test----", 13)) == -1)
- break;
- printf("write command is %s, totally %d bytes\n", command, strlen(command));
- fflush(NULL);
- bzero(command, MAXLINE);
- }
- close(ptsfd);
- return 0;
- }
复制代码 |
|