views:

263

answers:

1

Hi, I'm trying to send and receive using pipes:

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);

./send ./recv

open is correct, but when send.cpp executes "write" the program terminates and "4" is not displayed!!!! I recv side the T.a and T.b are not correct !

What's wrong with my programs?! (I have to say that programs are working correct when I remove O_NONBLOCK falg)

thanks

A: 

You have to check the return values of read() and write(), especially when you're using non-blocking I/O. They might fail because the data you want to read isn't there yet, they might return some but not all of your data because it hasn't all been written, and they might fail with error code EINTR or EAGAIN. You generally want to use them in a loop, reading until you either have all the data you want or you get an error that isn't recoverable like EINTR/EAGAIN.

jimrandomh