服务器端、
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<unistd.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include<ctype.h>
#include<signal.h>
void handler(int sig)
{
printf("recv a sig=%d\n",sig);
exit(EXIT_SUCCESS);
}
int main()
{
int listenfd;
listenfd = socket(AF_INET, SOCK_STREAM, 0);
struct sockaddr_in servaddr;
memset(&servaddr, 0, sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_port = htons(5188);
servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
int on = 1;
setsockopt(listenfd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));
bind(listenfd, (struct sockaddr*)&servaddr, sizeof(servaddr));
listen(listenfd, 20);
while (1)
{
struct sockaddr_in cliaddr;
socklen_t cliaddr_len;
int connfd = accept(listenfd, (struct sockaddr*)&cliaddr, &cliaddr_len);
printf("ip=%s port=%d\n", inet_ntoa(cliaddr.sin_addr), ntohs(cliaddr.sin_port));
pid_t pid = fork();
if (pid < 0)
{
printf("error\n");
}
if (pid == 0)
{
close(listenfd);
char sendbuf[1024] = { 0 };
while (fgets(sendbuf, sizeof(sendbuf), stdin) != NULL)
{
write(connfd, sendbuf, strlen(sendbuf));
memset(sendbuf, 0, sizeof(sendbuf));
}
printf("server child close\n");
kill(pid,SIGUSR1);
exit(EXIT_SUCCESS);
}
else if (pid > 0)
{
char recvbuf[1024];
signal(SIGUSR1,handler);
while (1)
{
memset(recvbuf, 0, sizeof(recvbuf));
int ret = read(connfd, recvbuf, sizeof(recvbuf));
if (ret == -1)
{
printf("error\n");
exit(0);
}
if (ret == 0)
{
printf("client close\n");
break;
}
fputs(recvbuf, stdout);
}
printf("server parent close\n");
exit(EXIT_SUCCESS);
}
}
close(listenfd);
}
客户端
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<unistd.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include<ctype.h>
#include<signal.h>
const int MAX = 128;
void handler(int sig)
{
printf("recv a sig=%d\n",sig);
exit(EXIT_SUCCESS);
}
int main()
{
int sockfd;
sockfd = socket(AF_INET, SOCK_STREAM, 0);
struct sockaddr_in servaddr;
memset(&servaddr, 0, sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_port = htons(5188);
servaddr.sin_addr.s_addr = inet_addr("127.0.0.1");
connect(sockfd, (struct sockaddr*)&servaddr, sizeof(servaddr));
pid_t pid = fork();
if (pid < 0)
{
printf("error\n");
}
else if (pid == 0)
{
char sendbuf[MAX] = { 0 };
while (fgets(sendbuf, sizeof(sendbuf), stdin))
{
write(sockfd, sendbuf, strlen(sendbuf));
memset(sendbuf, 0, MAX);
}
printf("client child close\n");
kill(getpid(),SIGUSR1);
exit(EXIT_SUCCESS);
}
else if (pid > 0)
{
signal(SIGUSR1,handler);
char recvbuf[MAX] = { 0 };
while (1)
{
int n = read(sockfd, recvbuf, MAX);
if (n == -1)
{
printf("error\n");
exit(0);
}
else if (n == 0)
{
printf("server close\n");
break;
}
fputs(recvbuf, stdout);
memset(recvbuf, 0, MAX);
}
printf("client paretn close\n");
exit(EXIT_SUCCESS);
}
close(sockfd);
}