Question

I have a situation where disk becomes full and my program hangs because of fflush being used on stdout. I have put down a small code to mimic the problem. We have to redirect this programs stdout to a file in a disk whose size is full already.

while(1){
            cout << "a big data to be written here";
            int ret = fflush(stdout);
            if(ret != 0){
                    cerr << "get error : " << strerror(errno) << endl;
                    exit(1);
            }
}

And this code hangs forever. I tried to use fcntl with O_NONBLOCK for stdout. Even that doesn`t work somehow. Please note I can not use write system call here though that avoids this kinda hang problem when disk is full. As my system widely uses library calls in many places if I use write system call only in this place it would create output in mixed manner. Can anyone suggest how to avoid hanging ? I have tried fsync, fdatasync also. Same hanging with those functions too.

Update: fcntl fixed this problem even with cout and fflush  combination.
Was it helpful?

Solution

You are mixing C++ stream I/O and C stdio functions. Instead of using fflush(stdout), use cout.flush() if needed. Instead of checking the return code from fflush, you should instead check cout.good() or use cout.rdstate(). I assume the cout operations are failing but fflush is not the part seeing the failure.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top