open()
fails with ENOENT (no such file or directory) on first attempt but works fine in subsequent attempts.
My program forks a child process and and waits for the child to finish using waitpid()
. The child process creates a copy of a file path received from user in specific directory using execl()
.
Once the child exits, the parent process opens this newly created copy using open()
. However it fails with ENOENT (no such file or directory) on the first attempt. I can see that child process creates a file in the specified directory.
If I run this program again by supplying the same file name, then it works fine. My question is: Why isn't it opening the file on the first attempt? Do I need to refresh directory or what is it?
I am on redhat
HERE IS A QUICK N DIRTY CODE SNIPPETS
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
.............
............
............
}