多进程tcp服务端程序
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <signal.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/socket.h>
int create_worker(int cli_fd)
{
int pid = fork();
if (pid < 0)
{
return -1;
}
else if (pid == 0)
{
while(1)
{
char buff[1024] = {0};
int ret = recv(cli_fd, buff, 1024, 0);
if (ret <= 0) {
close(cli_fd);
exit(-1);
}
printf("client say:[%s]\n", buff);
send(cli_fd, "what\?\?!!", 8, 0);
}
}else {
close(cli_fd);
}
return 0;
}
void sigcb(int signo)
{
while(waitpid(-1, NULL, WNOHANG) > 0);
}
int main(int argc, char *argv[])
{
signal(SIGCHLD, sigcb);
int lst_fd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (lst_fd < 0) {
perror("socket error");
return -1;
}
struct sockaddr_in lst_addr;
lst_addr.sin_family = AF_INET;
lst_addr.sin_port = htons(9000);
lst_addr.sin_addr.s_addr = inet_addr("192.168.122.132");
socklen_t len = sizeof(struct sockaddr_in);
int ret = bind(lst_fd, (struct sockaddr*)&lst_addr, len);
if (ret < 0) {
perror("bind error");
return -1;
}
if (listen(lst_fd, 5) < 0) {
perror("listen error");
return -1;
}
while(1) {
struct sockaddr_in cli_addr;
int cli_fd = accept(lst_fd, (struct sockaddr*)&cli_addr, &len);
if (cli_fd < 0) {
perror("accept error");
continue;
}
create_worker(cli_fd);
}
close(lst_fd);
return 0;
}
多线程tcp服务端程序
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <pthread.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/socket.h>
void *thr_start(void *arg)
{
int clifd = (int)arg;
while(1) {
char buff[1024] = {0};
ssize_t ret = recv(clifd, buff, 1024, 0);
if (ret < 0) {
perror("recv error");
close(clifd);
break;
}else if (ret == 0) {
printf("peer shutdown!!\n");
}
printf("client say:[%s]\n", buff);
send(clifd, "what!!", 6, 0);
}
return NULL;
}
int create_worker(int clifd)
{
pthread_t tid;
int ret;
ret = pthread_create(&tid, NULL, thr_start, (void*)clifd);
if (ret != 0) {
printf("create pthread error\n");
return -1;
}
return 0;
}
int main(int argc, char *argv[])
{
int lstfd, clifd, ret;
socklen_t len;
struct sockaddr_in lst_addr;
struct sockaddr_in cli_addr;
if (argc != 3) {
printf("Usage: ./ttcp_server ip port\n");
return -1;
}
lstfd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (lstfd < 0) {
perror("socket error");
return -1;
}
lst_addr.sin_family = AF_INET;
lst_addr.sin_port = htons(atoi(argv[2]));
lst_addr.sin_addr.s_addr = inet_addr(argv[1]);
len = sizeof(struct sockaddr_in);
ret = bind(lstfd, (struct sockaddr*)&lst_addr, len);
if (ret < 0) {
perror("bind error");
return -1;
}
if (listen(lstfd, 5) < 0) {
perror("listen error");
return -1;
}
while(1) {
clifd = accept(lstfd, (struct sockaddr*)&cli_addr, &len);
if (clifd < 0) {
perror("accept error");
continue;
}
create_worker(clifd);
}
return 0;
}