1. 程式人生 > >Linux socket通訊(多程序Linux socket通訊(TCP))

Linux socket通訊(多程序Linux socket通訊(TCP))

#include<stdio.h>
#include <sys/socket.h>
#include<string.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <netinet/in.h>
#define TCP_PORT 9999

int main()
{
    char ipbuf[32];
    char recbuf[0x1000];
    pid_t pid;
    int socket_ser,socket_accept;
    socket_ser = socket(AF_INET,SOCK_STREAM,0);
    struct sockaddr_in addr,addr_c;
    bzero(&addr,sizeof(addr));
    addr.sin_family = AF_INET;
    addr.sin_port = htons(TCP_PORT);
    addr.sin_addr.s_addr = htonl(INADDR_ANY);
    bind(socket_ser,(struct sockaddr *)&addr,sizeof(addr));
    listen(socket_ser,128);
    while(1)
    {


        bzero(ipbuf, sizeof(ipbuf));
        bzero(&addr_c,sizeof(addr_c));
        bzero(recbuf,sizeof(recbuf));
        int len_c;
        socket_accept = accept(socket_ser,(struct sockaddr *)&addr_c,(socklen_t *)&len_c);
        inet_ntop(AF_INET,&addr_c.sin_addr.s_addr,ipbuf,sizeof(ipbuf));
        pid = fork();
        if (pid>0)
        {
            close(socket_accept);
        }
        else
        {
            close(socket_ser);
            int len = read(socket_accept,recbuf,sizeof(recbuf));
            printf("%s\n",recbuf);
            write(socket_accept,recbuf,len);
            close(socket_accept);
            return 0;
        }

    }
    close(socket_ser);
    return 0;
}

跟普通的多程序相比沒有多少區別,父程序通過fork建立子程序,然後父程序和子程序釋放掉跟自己無關的資源即可。