- 论坛徽章:
- 0
|
环境:RedHat Enterprise Linux AS 4
服务端代码如下(svr.c):
#include <fcntl.h>
#include <sys/select.h>
#include <string.h>
#include <time.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <errno.h>
#define TMOUT_SEC 5
int
mkfifo_by_proc()
{
int fd;
char name[44];
sprintf( name,"myfifo", getenv( "HOME" ) );
unlink( name );
mkfifo( name, 0666 );
fd = open( name, O_RDONLY );
return fd;
}
main()
{
int ret;
int procfd;
char buff[512];
fd_set readfds;
int maxfd;
struct timeval tmout;
procfd = mkfifo_by_proc();
while( 1 ) {
FD_ZERO( &readfds );
FD_SET( procfd, &readfds );
tmout.tv_sec = TMOUT_SEC;
tmout.tv_usec = 0;
ret = select( 1024, &readfds, NULL, NULL, &tmout );
if ( -1 == ret && EINTR == errno ) {
continue;
}
if ( ret < 0 ) {
printf( "select error: %d", errno );
continue;
}
if( ret == 0 ) { /* time out */
continue; /* SERVER CONTINUE */
}
if( FD_ISSET( procfd, &readfds ) ) {
if( read( procfd, buff, 1024 ) < 0 ) {
printf( "read err[%d]", errno );
sleep( 1 );
continue;
}
printf( "buff=[%s]\n", buff );
}
// sleep( 1 );
}
close( procfd );
exit ( 0 );
}
|
客户端代码如下(cli.c):
#include <fcntl.h>
#include <sys/select.h>
#include <string.h>
#include <time.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <errno.h>
#define TMOUT_SEC 5
main()
{
int ret;
int procfd;
char buff[512];
fd_set writefds;
int maxfd;
int wrfd;
struct timeval tmout;
char file_name[256];
strcpy( file_name, "myfifo" );
wrfd = open( file_name, O_WRONLY );
#if 0
if( write( wrfd, file_name, strlen(file_name) ) < 0 ) {
printf( "write err[%d]", errno );
sleep( 1 );
return -1;
}
printf( "Send msg=[%s]", buff );
#endif
FD_ZERO( &writefds );
FD_SET( wrfd, &writefds );
tmout.tv_sec = TMOUT_SEC;
tmout.tv_usec = 0;
ret = select( wrfd+1, NULL,&writefds, NULL, &tmout );
if ( -1 == ret && EINTR == errno ) {
return -1;
}
if ( ret < 0 ) {
printf( "select error: %d", errno );
return -1;
}
if( ret == 0 ) { /* time out */
return -1; /* SERVER CONTINUE */
}
if( FD_ISSET( wrfd, &writefds ) ) {
if( write( wrfd, file_name, strlen(file_name) ) < 0 ) {
printf( "write err[%d]", errno );
sleep( 1 );
return -1;
}
printf( "Send msg=[%s]", buff );
}
sleep( 1 );
FD_CLR( wrfd, &writefds );
close( wrfd );
exit ( 0 );
}
|
cc -o cli cli.c
cc -o svr svr.c
问题:
当我用向myfifo写入数据时,用客户端cli向svr发送消息,或者直接使用shell命令:echo MSG > myfifo
服务端的结果都是无限循环的输出结果,比如我发送的消息是字符串为:MSG,服务端屏幕循环输出:buf=MSG
请各位老师支招,看下程序是哪里的原因?mkfifo? or select? |
|