プロが教えるわが家の防犯対策術!

read関数をノンブロッキングで実行する方法がわかりません。

O_NONBLOCKを使用して、readがEAGAINを返したらどうのこうのと、マニュアルにありましたが
その辺の一連をどのように書けばよいのかを教えてください。

unix上でTCPでやりたいです。

A 回答 (3件)

No.2 です。

間違えました。No.2 は TCP のバッファリングを無効にする(バンド幅は小さくなるが、遅延が減る)ものでした。正しくは、以下の関数を fd に適用してください。

int set_nonblock_mode( int fd ) {
return( fcntl( fd, F_SETFL, O_NONBLOCK ) );
}
    • good
    • 0
この回答へのお礼

ありがとうございました。ノンブロッキングできました。

お礼日時:2006/04/21 17:12

TCP のソケット(fd)に対して、以下の関数を呼べば OK です。

inlcude の指定と、エラー処理は適当に書いてください。このコードは Linux で動作確認済みです。

void set_tcp_nodelay( int fd ) {
struct protoent *protoent;
int tmp;
if( ( protoent = getprotobyname ("tcp") ) == NULL ) return;
tmp = 1;
(void) setsockopt( fd,
protoent->p_proto,
TCP_NODELAY,
(char*) &tmp,
sizeof(int) );
}
    • good
    • 0

tcpの例文は手間がかかるので、ttyの例を書きます。


-- 8< -- 8< -- 8< -- 8< -- 8< -- 8< -- 8< -- 8< -- 8< -- 8< --
#include <stdio.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>

int main(void)
{

char buf[BUFSIZ];
int fd, n;

fd = open("/dev/tty", O_NONBLOCK);
while (1) {
sleep(1);
n = read(fd, buf, BUFSIZ);
if (n < 0) {
if (errno == EAGAIN) {
fprintf(stderr, "No input\n");
continue;
}
else {
perror("I/O error");
return errno;
}
}
else {
buf[n] = 0;
printf("read = %s", buf);
}
}
return 0;
}
    • good
    • 0

お探しのQ&Aが見つからない時は、教えて!gooで質問しましょう!

このQ&Aを見た人はこんなQ&Aも見ています