2006-7-15 18:33
chb_412
如何设置消息队列的超时?
--------------------------------------------------------------------------------
想用select 但运行不起 大家帮我看看好麻?
void *function1( void *ptr );
void *function2( void *ptr );
int readable_time (long fd, int sec);
struct msg_send
{
long mtype; /* 消息类型 */
int fd;//相关套接口
char mtext[350]; /* 消息的文本 */
}msend, mrecv;
key_t sendkey = 0x1212;
main( )
{
long msgid;
msgid = msgget(sendkey, IPC_CREAT | 0666);
if (msgid < 0)
perror ("msgget_send:");
printf ("MSGID_SEND is %ld\n", msgid);
pthread_t thread1;
pthread_create( &thread1, NULL, function1, NULL);
while (true)
{
sleep (1);
msend.mtype = 2;
msend.fd = 1;
printf ("11111111111111111\n");
memcpy(msend.mtext, "12345423", sizeof ("12345423"));
if (!msgsnd (msgid, &msend, sizeof (msend.mtext), IPC_NOWAIT) == 0){
perror ("msgsnd:\n");
}
sleep (10);
}
exit( 0 ) ;
}
void *function1( void *ptr )
{
int sec = 20, a;
long msgid;
msgid = msgget(sendkey, IPC_CREAT | 0666);
long fd = msgid;
while (1)
{
a = readable_time (fd, sec);
switch (a)
{
case 0:
printf ("select overtime! \n");
break;
case -1:
printf ("select return an error\n");
break;
default:
printf ("there an msg come!\n");
if (msgrcv(msgid, &mrecv,sizeof (mrecv.mtext), 0, MSG_NOERROR) == -1){
perror ("msgrcv\n");
}
struct msg_send msg;
msg.mtype = mrecv.mtype;
msg.fd = mrecv.fd;
memcpy (msg.mtext, mrecv.mtext, sizeof(mrecv.mtext));
printf ("type = %d, fd = %d, mtext = %s\n", msg.mtype, msg.fd, msg.mtext);
}// endof swhitch
}//endof while(1)
}
int readable_time (long fd, int sec)
{
fd_set fdrset;
struct timeval tv;
FD_ZERO (&fdrset);
FD_SET (fd, &fdrset);
tv.tv_sec = sec;
tv.tv_usec = 0;
return (select(fd + 1, &fdrset, NULL, NULL, &tv));
}
执行到 FD_SET (fd, &fdrset);时候出现段错误 是否select不能用来设置消息队列超时? 如果这样 怎么达到这个目的呢?
2006-7-18 14:29
jxppp
我机器上的运行结果,一切正常。除非你的是64位机器:lu2:
[code]
MSGID_SEND is 0
11111111111111111
11111111111111111
select overtime!
11111111111111111
11111111111111111
select overtime!
11111111111111111
11111111111111111
select overtime!
11111111111111111
11111111111111111
select overtime!
11111111111111111
select overtime!
11111111111111111
11111111111111111
select overtime!
11111111111111111
11111111111111111
select overtime!
11111111111111111
11111111111111111
select overtime!
11111111111111111
11111111111111111
select overtime!
11111111111111111
11111111111111111
select overtime!
11111111111111111
[/code]
2006-7-18 21:33
jxppp
[code]
long msgid; ---> int msgid
int readable_time (long fd, int sec) ---> int readable_time (int fd, int sec)
int msgget(key_t key, int msgflg);
void FD_SET(int fd, fd_set *fdset);
[/code]
注意32bit和64位机的long int的不同 :lol