#include <signal.h>
#include <unistd.h>
#include <sys/socket.h>
#include <fcntl.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <errno.h>
static int fd;
void show(int sig)
{
char buf[1024] = {0};
int n = read(fd,buf,sizeof(buf));
buf[n] = 0;
write(1,"MSG:",strlen("MSG:"));
write(1,buf,strlen(buf));
}
int main()
{
struct sigaction act;
sigemptyset(&act.sa_mask);
act.sa_handler = show;
//This is necessary,in last loop read() counld be interrupt;
act.sa_flags = SA_RESTART;
sigaction(SIGIO,&act,0);
fd = socket(AF_INET,SOCK_STREAM,0);
if(fd == -1) {
printf("Cannot get socketfd!:%m\n");
exit(-1);
}
struct sockaddr_in addr;
addr.sin_family = AF_INET;
addr.sin_port = htons(9999);
inet_pton(AF_INET,"127.0.0.1",&addr.sin_addr);
if(connect(fd,(struct sockaddr*)&addr,sizeof(addr)) != -1)
printf("connect success!\n");
else
exit(-1);
int flag = fcntl(fd,F_GETFL);
flag |= O_ASYNC;
fcntl(fd,F_SETFL,flag);
fcntl(fd,F_SETOWN,getpid());
char buffer[1024]={0};
for(;;)
{
int n = read(0,buffer,sizeof(buffer));
if(n==-1)
break;
send(fd,buffer,n,0);
}
write(1,"Closed.",strlen("Closed."));
}