#include <stdio.h>
#include <ctype.h>
#include <signal.h>
#include <stdlib.h>
#include <unistd.h>
#include <termios.h>
static struct termios old, new;
/* Initialize new terminal i/o settings */
void initTermios(int echo)
{
tcgetattr(0, &old); /* grab old terminal i/o settings */
new = old; /* make new settings same as old settings */
new.c_lflag &= ~ICANON; /* disable buffered i/o */
new.c_lflag &= echo ? ECHO : ~ECHO; /* set echo mode */
tcsetattr(0, TCSANOW, &new); /* use these new terminal i/o settings now */
}
/* Restore old terminal i/o settings */
void resetTermios(void)
{
tcsetattr(0, TCSANOW, &old);
}
/* Read 1 character - echo defines echo mode */
char getch_(int echo)
{
char ch;
initTermios(echo);
ch = getchar();
resetTermios();
return ch;
}
/* Read 1 character without echo */
char getch(void)
{
return getch_(0);
}
/* Read 1 character with echo */
char getche(void)
{
return getch_(1);
}
void INThandler(int);
void INThandler(int sig)
{
char c;
signal(sig, SIG_IGN);
printf("\n Ctrl+c foi detetado, clique y para confirmar \n");
c = getchar();
if(c == 'y' || c == 'Y')
exit(0);
else
signal(SIGINT, INThandler);
getchar();
}
int main()
{
signal(SIGINT, INThandler);
int fd[2];
char readbuffer[80];
pipe(fd);
int pid = fork();
char ch;
if(pid < 0)
{
printf("\n Erro");
exit(1);
}
else if(pid == 0)
{
close(fd[0]);
do
{
ch = getch();
write(fd[1], &ch, sizeof(ch));
} while(ch != '\n');
getchar();
}
else
{
close(fd[1]);
while(1)
{
read(fd[0], readbuffer, sizeof(readbuffer));
char upper = toupper(readbuffer[0]);
char down = tolower(readbuffer[0]);
if(readbuffer[0] != upper)
{
printf("%c \n", upper);
}
else
{
printf("%c \n", down);
}
}
}
return(0);
}
所以基本上这是一个任务:使用进程之间的通信,自动将大写字母转换为小写字母,将小写字母转换为大写字母,而不将它们显示在输入中。基本上我没有看到我的输入只是输出。当CTRL + C被击中时,程序应该识别它并通过要求用户键入&#34; y&#34;来要求确认。 我的程序运行,但当我从&#34; printf(&#34;%c \ n&#34;,upper)中删除\ n时;&#34;并且来自&#34; printf(&#34;%c \ n&#34;,down);&#34;该程序开始表现得很奇怪...当我删除它时,我必须按Enter键才能看到输出,但是它会自动出现,就像我想要的那样......有人可以解释一下为什么吗?
我正在使用ubuntu。
答案 0 :(得分:0)
printf
实际上并不会立即打印到stdout - 它只是将字符放入输出缓冲区,以便稍后将其刷新到stdout。如果输出是终端,那么“后来的点”通常是每当打印换行符时,你可以用setbuf更改它:
setbuf(stdout, 0); // set stdout to unbuffered
之后每次调用printf都会立即刷新缓冲区。或者,您可以使用fflush(stdout)
在程序中的任何特定点刷新缓冲区。