您的位置:首页 > 运维架构 > Linux

linux高级编程day11 笔记

2012-07-31 19:16 344 查看
回顾:
多进程的问题:数据共享。
多进程的问题: 进程的上下文环境(context)
文件描述符号是整数以及对应上下文环境
多进程的问题:上下文环境共享

一.SELECT TCP服务器编程模式
1.select函数
int select(
int fds,//建议是监控的文件描述符号的最大值+1
fd_set *readfds,//读文件描述符号集合
//该参数既是输入,也是输出
//输入:被监控的描述符号
//输出:有数据的描述符号
fd_set *writefds,
fd_set *errfds,
struct timeval*timeout);//指定阻塞时间限制
//为NULL,永久
返回:
>0:发生改变的文件描述符号个数
=0:时间限制过期
=-1:异常

View Code

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <signal.h>
#include <fcntl.h>
#include <string.h>
int fd,cfd;
main()
{
char buf[1024];
int r;
struct sockaddr_in dr;
char strres[1024];

fd=socket(PF_INET,SOCK_STREAM,0);
if(fd==-1) printf("1:%m\n"),exit(-1);
printf("1\n");
dr.sin_family=AF_INET;
dr.sin_port=htons(10000);
dr.sin_addr.s_addr=inet_addr("192.168.180.92");

r=bind(fd,(struct sockaddr*)&dr,sizeof(dr));
if(r==-1) printf("2:%m\n"),exit(-1);
printf("2\n");
r=listen(fd,10);
if(r==-1) printf("3:%m\n"),exit(-1);
printf("3\n");
cfd=accept(fd,0,0);
if(cfd==-1) printf("4:%m\n"),exit(-1);
printf("4\n");
sprintf(strres,
"HTTP/1.1 200 OK\r\n"
"Server: tarena2.0\r\n"
"Content-Type: text/html\r\n"
"Content-Length: 28\r\n"
"Connection: keep-alive\r\n"
"\r\n"
"<font color=red>靓崽!</font>");
while(1)
{
r=recv(cfd,buf,1024,0);
if(r>0)
{
buf[r]=0;
printf("接收数据:%s\n",buf);
send(cfd,strres,strlen(strres),0);
}
else
{
break;
}

}
close(cfd);
close(fd);
}


五.ioctl函数
实现ifconfig工具

总结:
重点:
select
广播

了解:
OOB数据
HTTP协议

应用:
独立编写TCP服务器端的select模式
编写广播
能够请求一个网页,并且解析响应
作业:
1.把聊天程序使用poll实现
2.使用UDP的广播,发送一个文件
3.随意挑选网站,把主页下载并保存成html文件
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: