O_NONBLOCK管道问题

时间:2009-10-08 15:16:29

标签: pipe nonblocking

我正在尝试使用管道发送和接收:

send.cpp

struct
{
        long a;
        long b;
}T;
cout << "1" << endl;
if ( access ( FIFO_NAME, F_OK ) == -1 ) {
            res = mkfifo ( FIFO_NAME, 0755 );
            if ( res != 0 )
                    cout << " Can't make fifo" << endl;
}

cout << "2" << endl;
pipe_fd = open ( FIFO_NAME, O_WRONLY);
cout << "3: " << pipe_fd << endl;
a=b=1;
res = write ( pipe_fd, &T, sizeof ( T ) );
cout << "4" << endl;
close(pipe_fd);

recv.cpp

cout << "1" << endl;
pipe_fd = open(FIFO_NAME, O_RDONLY | O_NONBLOCK);
cout << "2" << endl;
res = read(pipe_fd, &T, sizeof(T));
cout << T.a << T.b << endl;
close(pipe_fd);

./发送 ./recv

open是正确的,但是当send.cpp执行“write”时程序终止并且“4”不显示!!!!我认为T.a和T.b不正确!

我的节目有什么问题?! (我必须说当我删除O_NONBLOCK falg时程序正常工作)

感谢

1 个答案:

答案 0 :(得分:1)

您必须检查read()和write()的返回值,尤其是在使用非阻塞I / O时。它们可能会失败,因为您想要读取的数据尚未存在,它们可能会返回一些但不是全部数据,因为它们并未全部写入,并且可能会因错误代码EINTR或EAGAIN而失败。您通常希望在循环中使用它们,直到您拥有所需的所有数据,或者您得到的错误无法像EINTR / EAGAIN那样恢复。

相关问题