C – open() failed on first attempt

open() failed on first attempt… here is a solution to the problem.

open() failed on first attempt

open() fails on the first attempt and shows ENOENT (no such file or directory), but works fine on subsequent attempts.
My program forks a child process and waits for the child process to finish using waitpid(). The child process uses execl() to create a copy of the file path received from the user in a specific directory.
After the child process exits, the parent process uses open() to open the newly created copy. HOWEVER, IT FAILS ON THE FIRST ATTEMPT WITH ENOENT (NO SUCH FILE OR DIRECTORY). I can see that the child process creates a file in the specified directory.
If I run this program again by providing the same file name, then it works fine. My question is: why doesn’t it open the file on the first try? Do I need to refresh the catalog or what?

I’m on Red Hat

This is a quick N dirty snippet

my_function()
{
char *src = "TEST.txt";  
char *dest = "./Output/";  
char *fp = "/Output/TEST.txt";  
int fd;  
struct fstat file_stat;  

pid_t PID = fork();  

if(PID == -1)  
      exit(1);   

if(PID == 0)  
{
       execl("/bin/cp", "/bin/cp", src, dest);   
       exit(1);   
}   

if(PID > 0)  
{  
       int chldstat;
       pid_t ws = waitpid(PID,&chldstat,WNOHANG);  
}  

if(stat(fp,&file_stat) == -1)  
{  
       perror("stat");  
       exit(1);  
}  

if((fd = open(dest,O_RDWR)) == -1)  
{  
       perror("open");
       exit(1);
}  

if((fp=mmap(0,file_stat.st_size,PROT_READ | PROT_WRITE,fd,0)) == -1)  
{  
       perror("mmap");
       exit(1);
}  

OTHER ROUTINES      
.............  
............    
............  

}  

Solution

As others have said, it is difficult to answer such a question without source code. But:

You seem to have a racial problem. The file is created, but a little later than your first opening attempt. On the second try, you’re lucky enough to have the file created.
The fact that running again works properly supports this theory – the file existed even before the program started, so it can be opened at any time.

How can you have a race condition? If the child is created and the father tries to open it only after confirming the child, there should be no problem.
It’s hard to speculate what went wrong. Maybe you’re waiting for the wrong process. Maybe child creates another process that creates a file, and parent just waits for the first child. There are a million more possibilities.

Related Problems and Solutions