- 論壇徽章:
- 0
|
自己編寫了一個小程序,想實現(xiàn)將一個程序的從一個終端的標準輸入獲取數(shù)據(jù),并將標準輸出在同一終端上輸出。
現(xiàn)在遇到的問題是:在新打開的終端中輸入的數(shù)據(jù)時并不會完全被程序接受,而且所輸入的內(nèi)容還有可能被shell解釋執(zhí)行,導(dǎo)致程序無法從新打開的終端上正確獲取數(shù)據(jù)。
以下是程序代碼:- #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;
- }
復(fù)制代碼 |
|