Posted on 2008-08-26 16:06
Prayer 閱讀(450)
評論(1) 編輯 收藏 引用 所屬分類:
LINUX/UNIX/AIX
其他的不管,只是關注一下alarm的用法,設定了msgrcv超時。
環境是redhat9
當把發送緩沖中寫入大于8位數據時 可以成功發送但只能收到8位信息
代碼如下
//定義
struct msgbuf //消息結構
{
long mtype;
char mtext[100];
}msgbuf;
//創建消息隊列
void creatque()
{
static int msg_que_id=-1;
struct sigaction action;
/*檢查是否存在的要創建的消息隊列,如果存在到 就刪除它*/
msg_que_id=msgget(BOOKING_KEY,0);
if(msg_que_id!=-1){
if(msgctl(msg_que_id,IPC_RMID,0)==-1){
perror("remove old message");
exit(1);
}
}
/*創建消息隊列*/
msg_que_id=msgget(BOOKING_KEY,IPC_CREAT|0666);
if(msg_que_id==-1){
perror("creat new message list");
exit(1);
}
/*忽略其它一些參數*/
action.sa_handler=SIG_IGN;
action.sa_flags=0;
sigemptyset(&action.sa_mask);
sigaction(SIGINT,&action,NULL);
sigaction(SIGQUIT,&action,NULL);
sigaction(SIGHUP,&action,NULL);
}
//發消息
void control(char *c)
{
int send_len;
int msg_que_id=-1;
struct msgbuf send_msg;
memset(send_msg.mtext,'\0',sizeof(send_msg.mtext));
send_len=sizeof(long)+sizeof(int);
msg_que_id=msgget(BOOKING_KEY,0);
if(msg_que_id==-1){
perror("get message list id");
exit(1);
}
if(!strncasecmp(c,"lk",2)){/*連接狀態信號*/
send_msg.mtype=httpd_stoped;
sprintf(send_msg.mtext,"linking");
if(msgsnd(msg_que_id,&send_msg,send_len,0)<0){
perror("send message");
exit(1);
}
}
}
//接收消息
void *other_key(void *data)
{
int msg_que_id=-1;
int rece_len,send_len;
struct msgbuf rece_msg;
memset(rece_msg.mtext,'\0',sizeof(rece_msg.mtext));
send_len=sizeof(long)+sizeof(int);
msg_que_id=msgget(BOOKING_KEY,0);
if(msg_que_id==-1){
perror("get message list id");
exit(1);
}
while(1){
/*定時器定時LKTIMEOUTs來接收30s一次的連接狀態信號,*/
/*如果時間到而沒有接收到信號則判斷接收方關閉了監視端,服務器將中斷此次連接*/
alarm(35);
rece_len=msgrcv(msg_que_id,&rece_msg,sizeof(msgbuf)-sizeof(long),(int)httpd_stoped,0);
if(rece_len<0){
perror("receive message");
exit(1);
}
if(!strcmp(rece_msg.mtext,"linking")){
alarm(0);
}
else if(!strcmp(rece_msg.mtext,"q")){
if(msgsnd(msg_que_id,&rece_msg,send_len,0)<0){/*把取出的結束信息再寫回去(因為一條信息只能被取一次)*/
perror("send message"); /*而取出一次只能結束一個進程*/
exit(1);
}
exit(1);
}
}
}