fopen does not return

Souvik picture Souvik · Dec 20, 2010 · Viewed 7k times · Source

I used 'fopen' in a C program to open a file in readonly mode (r). But in my case I observed that fopen call does not return. It does not return NULL or valid pointer - execution gets blocked at fopen call. The patch of file is absolutely correct (I have already verified that) and there is no permission related issues. Can anybody please tell what could be the reason for this kind if behavior. Any kind of help is really appreciable. Is there anything related to gcc or glibc?

EDIT

Here is the sample code

printf("%s %d\n",__FUNCTION__,__LINE__);
if ((fp = fopen(argv[1], "r")) == NULL) {
   printf("%s %d\n",__FUNCTION__,__LINE__);
   return;
}
printf("%s %d\n",__FUNCTION__,__LINE__);

When I run this code, I only get the first print (before calling fopen) and after that program just halts. So fopen does not complete it's operation. The file is a simple configuration file with '.conf' extension and this file can be opened by all other means like vi, cat etc. There should not be any NFS related issue. Filesystem is ext3.

Thanks in advance, Souvik

Answer

nos picture nos · Dec 20, 2010

Here's a few reasons:

  • You've corrupted memory somewhere, and all bets are off as to what's happening (run your program through valgrind)
  • You're calling this code inside a signal handler, fopen() is not signal async safe, so really anything could happen (a deadlock due to the FILE* internal mutex is common though)
  • The file is a fifo , in which cases opening the file will block until someone opens the file at the other end(read/writing)
  • The file is on a stale NFS mount.
  • The file is a character/block special file with semantics that open blocks until something interesting happens,