|
使用命名管道,可是没有成功,源代码如下:
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <fcntl.h>
#include <termios.h>
#include <term.h>
#include <curses.h>
#define FIFO_NAME "/tmp/my_fifo"
static struct termios initial_settings,new_settings;
static int peek_character=-1;
void init_keyboard();
void close_keyboard();
int kbhit();
int readch();
int main(int argc, char* argv[])
{
int pipe_fd;
pid_t pid_listener, pid_writer;
if(access (FIFO_NAME,F_OK)==-1)
{
mkfifo(FIFO_NAME,0766);
}
pid_listener = fork();
if(pid_listener<0)
{
perror("fork");
exit(1);
}
else if(pid_listener>0)/*the parent process*/
{
pid_writer = fork();
if(pid_writer<0)
{
perror("fork");
exit(1);
}
if(pid_writer == 0) /*the writer process*/
{
/*read data from pipe, then store the data to data.out*/
int fout;
fout = open("data.out",O_WRONLY|O_CREAT|O_APPEND);
int ch;
pipe_fd = open(FIFO_NAME,O_RDONLY);
if(pipe_fd!=-1)
{
while(read(pipe_fd,&ch,1))
{
write(fout ,&ch,1);
}
}
close(pipe_fd);
}
}
else/*the listener process*/
{
/*detect the keyboard hit and send the characher to writer through pipe.*/
init_keyboard();
pipe_fd = open(FIFO_NAME,O_WRONLY);
int ch = 0;
while(ch!='~')
{
if(kbhit())
{
ch = readch();
printf("you hit %c\n",ch);
write(pipe_fd,&ch,1);
}
}
close(pipe_fd);
close_keyboard();
exit(0);
}
wait(NULL);
return 0;
}
void init_keyboard()
{
tcgetattr(0,&initial_settings);
new_settings=initial_settings;
new_settings.c_lflag &= ~ICANON;
new_settings.c_lflag &= ~ECHO;
new_settings.c_lflag &= ~ISIG;
new_settings.c_cc[VMIN] = 1;
new_settings.c_cc[VTIME] = 0;
tcsetattr(0,TCSANOW,&new_settings);
}
void close_keyboard()
{
tcsetattr(0,TCSANOW,&initial_settings);
}
int kbhit()
{
char ch;
int nread;
if(peek_character!=-1)
return 1;
new_settings.c_cc[VMIN]=0;
tcsetattr(0,TCSANOW,&new_settings);
nread=read(0,&ch,1);
new_settings.c_cc[VMIN]=1;
tcsetattr(0,TCSANOW,&new_settings);
if(nread==1){
peek_character=ch;
return 1;
}
return 0;
}
int readch()
{
char ch;
if(peek_character!=-1)
{
ch=peek_character;
peek_character=-1;
return ch;
}
read(0,&ch,1);
return ch;
}
|
|