client1.c
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/un.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <fcntl.h>
#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
#include <signal.h>
#define BUFF_SIZE 1024
int main(void)
{
int sockfd;
struct sockaddr_in server_addr, client_addr;
int ret;
int pd;
char buff[BUFF_SIZE];
sockfd = socket (AF_INET, SOCK_STREAM, 0);
server_addr.sin_addr.s_addr = inet_addr("10.10.0.9");
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(9000);
ret = connect(sockfd, (struct sockaddr*)&server_addr, sizeof(server_addr));
if (ret == -1) {
perror("connect");
exit(errno);
}
sprintf(buff, "process(%u) send msg", getpid());
ret = write(sockfd, buff, strlen(buff)+1);
if (ret == -1) {
perror("client write");
exit(errno);
}
ret = read(sockfd, buff, sizeof(buff));
if (ret == -1) {
perror("client read");
exit(errno);
}
printf("received: %s\n", buff);
exit(0);
}
server1.c
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/un.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <fcntl.h>
#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
#include <signal.h>
#define BUFF_SIZE 1024
void handle_sigchld(int sig)
{
printf("catch a sig(%d)\n", sig);
wait(NULL);
}
static void str2up(char *p)
{
while (*p) {
if (*p >= 'a' && *p <= 'z') {
*p = *p - 'a' + 'A';
}
p++;
}
}
int main(void)
{
int sockfd, clientfd;
struct sockaddr_in server_addr, client_addr;
int ret;
int pd;
char buff[BUFF_SIZE];
//socklen_t len = sizeof(struct sockaddr_in);
socklen_t len= sizeof(struct sockaddr);
sockfd = socket (AF_INET, SOCK_STREAM, 0);
server_addr.sin_addr.s_addr = htons(INADDR_ANY);
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(9000);
ret = bind(sockfd, (struct sockaddr*)&server_addr, sizeof(server_addr));
if (ret == -1) {
perror("bind");
exit(errno);
}
ret = listen(sockfd, 5);
if (ret == -1) {
perror("listen");
exit(errno);
}
signal(SIGCHLD, handle_sigchld);
while (1) {
clientfd = accept(sockfd, (struct sockaddr*)&server_addr, &len);
if (clientfd == -1) {
perror("accept");
exit(errno);
}
printf("clientfd=%d\n", clientfd);
pd = fork();
if (pd == -1) {
perror("fork");
exit(errno);
} else if (pd == 0) {
close(sockfd);
ret = read(clientfd, buff, sizeof(buff));
printf("Process(%d),ret=%d, received: %s\n", getpid(), ret, buff);
str2up(buff);
ret = write(clientfd, buff, strlen(buff)+1);
printf("ret=%d\n", ret);
close(clientfd);
exit(0);
}
}
exit(0);
}