C/S模式程序

昨天晚上学习写了一个C/S架构的程序。这个程序服务器端程序以产生子进程的方式为每个客户端服务,主进程始终监听客户端请求。但是有一个问题,子进程在结束通信时,进程始终结束不了。郁闷中···

 

server:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <netinet/in.h>
#include <sys/types.h>
#include <sys/socket.h>

#define PORT 4242
#define BACKLOG 2

typedef struct server_and_client
{
        int socket;
        struct sockaddr_in addr;
}sercli;

int main(int argc,char *argv[])
{
        sercli ss;
        sercli sc;
        int err;
        pid_t pid;
        char buffer[1024]="aaa";
        int addrlen = sizeof(struct sockaddr);
        ss.socket=socket(AF_INET, SOCK_STREAM, 0);
        if (ss.socket < 0)
        {
                printf("socket error.\n");
                return -1;
        }
        ss.addr.sin_family = AF_INET;
        ss.addr.sin_addr.s_addr = htonl(INADDR_ANY);
        ss.addr.sin_port = htons(PORT);
        bzero(&ss.addr.sin_zero,8);
        err = bind(ss.socket, (struct sockaddr*)&ss.addr, sizeof(ss.addr));
        if (err < 0)
        {
                printf("bind error.\n");
                return -1;
        }
        err = listen(ss.socket, BACKLOG);
        if (err < 0)
        {
                printf("listen error.\n");
                return -1;
        }
        while(1)
        {
                sc.socket = accept(ss.socket, (struct sockaddr*)&sc.addr, &addrlen);
                if (sc.socket < 0)
                {
                        continue;
                }
                pid = fork();
                if (pid == 0)
                {
                        close(ss.socket);
                        pid = getpid();
                        write(sc.socket, &pid, sizeof(pid_t));
                        close(sc.socket);
                        break;
                }
                else
                {
                        close(sc.socket);
                }
        }
        return 0;
}

 

client:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <netinet/in.h>
#include <sys/types.h>
#include <sys/socket.h>

#define PORT 4242

int main(int argc,char *argv[])
{
        int s;
        struct sockaddr_in server_addr;
        int err;
        pid_t pid=1;
        s = socket(AF_INET, SOCK_STREAM, 0);
        if (s < 0)
        {
                printf("socket error.\n");
                return -1;
        }
        bzero(&server_addr,sizeof(server_addr));
        server_addr.sin_family = AF_INET;
        server_addr.sin_addr.s_addr = htonl(INADDR_ANY);
        server_addr.sin_port = htons(PORT);
        inet_pton(AF_INET, argv[1], &server_addr.sin_addr);
        connect(s, (struct sockaddr*)&server_addr, sizeof(struct sockaddr));
        read(s, &pid, sizeof(pid_t));
        printf("%d\n",pid);
        sleep(5);
        close(s);
        return 0;
}

 

你可能感兴趣的:(职场,C/S,休闲)