client.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/socket.h> #define BUF_SIZE 30
void error_handling(char* message);
void read_routine(int sock,char* buf);
void write_routine(int sock,char* buf); int main(int argc,char* argv[])
{
int sock;
pid_t pid;
char buf[BUF_SIZE];
struct sockaddr_in serv_addr;
if(argc != )
{
printf("usage: %s <ip><port>\n",argv[]);
exit();
} sock = socket(PF_INET,SOCK_STREAM,);
memset(&serv_addr,,sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = inet_addr(argv[]);
serv_addr.sin_port = htons(atoi(argv[])); if(connect(sock,(struct sockaddr*)&serv_addr,sizeof(serv_addr)) == -)
error_handling("connect error"); pid = fork();
if(pid == )
write_routine(sock,buf);
else
read_routine(sock,buf); close(sock);
return ;
} void read_routine(int sock,char* buf)
{
while()
{
int str_len;
str_len = read(sock,buf,BUF_SIZE);
if(str_len == )
return;
buf[str_len] = ;
printf("message from server;%s",buf);
}
} void write_routine(int sock,char* buf)
{
while()
{
fgets(buf,BUF_SIZE,stdin);
if(!strcmp(buf,"q\n") || !strcmp(buf,"Q\n"))
{
shutdown(sock,SHUT_WR);
return;
}
write(sock,buf,strlen(buf));
}
} void error_handling(char* message)
{
fputs(message,stderr);
fputc('\n',stderr);
exit();
}
server.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <signal.h>
#include <sys/wait.h>
#include <arpa/inet.h>
#include <sys/socket.h> #define BUF_SIZE 30
void error_handling(char* message);
void read_childproc(int sig); int main(int argc,char* argv[])
{
int serv_sock,clnt_sock;
struct sockaddr_in serv_addr,clnt_addr;
struct sigaction act;
pid_t pid;
socklen_t adr_sz;
int str_len ,state;
char buf[BUF_SIZE]; if(argc != )
{
printf("usage:%s <port>\n",argv[]);
exit();
} act.sa_handler = read_childproc;
sigemptyset(&act.sa_mask);
act.sa_flags = ;
state = sigaction(SIGCHLD,&act,); serv_sock = socket(AF_INET,SOCK_STREAM,);
memset(&serv_addr,,sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = htonl(INADDR_ANY);
serv_addr.sin_port = htons(atoi(argv[])); if(bind(serv_sock,(struct sockaddr*)&serv_addr,sizeof(serv_addr)) == -)
error_handling("bind error");
if(listen(serv_sock,) == -)
error_handling("listen error"); while()
{
adr_sz = sizeof(clnt_addr);
clnt_sock = accept(serv_sock,(struct sockaddr*)&clnt_addr,&adr_sz);
if(clnt_sock == -)
continue;
else
puts("connecting......"); pid = fork();
if(pid == -)
{
close(clnt_sock);
continue;
}
if(pid == )
{
close(serv_sock);
while((str_len = read(clnt_sock,buf,BUF_SIZE)) != )
write(clnt_sock,buf,str_len); close(clnt_sock);
return ;
}
else
close(clnt_sock);
}
close(serv_sock);
return ;
} void read_childproc(int sig)
{
pid_t pid;
int status;
pid = waitpid(-,&status,WNOHANG);
printf("removed proc id:%d\n",pid);
} void error_handling(char* message)
{
fputs(message,stderr);
fputc('\n',stderr);
exit();
}