openSUSE 11.4 - 2.6.37.1-1.2@x64編譯通過
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <unistd.h>
void str_ser(int sockfd);
int main(void)
{
int sockfd = 0;
int con_fd = 0;
int new_fd = 0;
int numbytes = 0;
int ret = 0;
int pid = 0;
struct sockaddr_in my_addr = {0};
struct sockaddr_in their_addr = {0};
int sin_size = 0;
char * buf = NULL;
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if(0 > sockfd)
{
printf("error in socket!\n");
return 0;
}
//
my_addr.sin_family = AF_INET;
my_addr.sin_port = htons(33333);
my_addr.sin_addr.s_addr = htonl(INADDR_ANY);
bzero(&(my_addr.sin_zero), 8);
ret = bind(sockfd, (struct sockaddr *)&my_addr, sizeof(struct sockaddr));
if(0 > ret)
{
printf("bind error!\n");
return 0;
}
ret = listen(sockfd, 10);
if(0 > ret)
{
printf("listen error!\n");
return 0;
}
//
while(1)
{
sin_size = sizeof(struct sockaddr_in);
con_fd = accept(sockfd, (struct sockaddr *)&their_addr, &sin_size);
if(0 > con_fd)
{
printf("accept error!\n");
return 0;
}
pid = fork(); //派生子進程
printf("forked!\n");
if(0 > pid)
{
printf("fork error!\n");
return 0;
}
//子進程
if(0 == pid)
{
printf("0 == pid\n");
close(sockfd);
str_ser(con_fd);
//
close(con_fd);
exit(0);
//return 0;
}
//父進程
printf("0 != pid\n");
close(con_fd);
}//end while
printf("line = %u\n", __LINE__);
close(sockfd);
return 0;
}
void str_ser(int sockfd)
{
char recvs[100] = {0};
int n = 0;
while(1)
{
n = recv(sockfd, recvs, 100, 0);
if(0 == n)
{
return;
}
send(sockfd, recvs, n, 0);
}
return;
}