Hi,

the program in this mail creates a directory and a file in it.
After checking that the file exists, it gets unlinked.
Then the program forks and the child checks for the existence of the
file, while the parent waits.
The parent checks for file existence after the child has finished.
Finally it deletes the directory.

I see:

  $ cc -g -Wall -o test_tmp_unlink_delay test_tmp_unlink_delay.c
  $ ./test_tmp_unlink_delay
  Test file name : /tmp/test_tmp_unlink_delay_dir/x.mo~
  Sub process    : File does not exist
  Main process   : File does not exist
  $

If your /tmp is weird enough you might see

  Sub process    : FILE STILL EXISTS

Begin of C code:
-----------------------------------------------------------------------

/*
  cc -g -Wall -o test_tmp_unlink_delay test_tmp_unlink_delay.c
*/

#include <sys/stat.h>
#include <sys/types.h>
#include <stdio.h>
#include <errno.h>
#include <unistd.h>
#include <sys/wait.h>


int main(int argc, char **argv)
{
 FILE *fp;
 pid_t pid;
 int status;
 struct stat stbuf;
 char *dir_path= "/tmp/test_tmp_unlink_delay_dir";
 char *file_path= "/tmp/test_tmp_unlink_delay_dir/x.mo~";

 fprintf(stderr, "Test file name : %s\n", file_path);
 if(mkdir(dir_path, 0777) == -1) {
   perror("Directory creation failed");
   return(1);
 }
 fp= fopen(file_path, "w");
 if(fp == NULL) {
   perror("File creation failed");
   return(2);
 }
 fprintf(fp, "content of %s\n", file_path);
 fclose(fp);
 if(stat(file_path, &stbuf) == -1) {
   fprintf(stderr, "File does not exist before unlink\n");
   return(3);
 }
 if(unlink(file_path) == -1) {
   perror("File unlink failed");
   return(4);
 }

 pid= fork();

 if(pid == 0) {
   fprintf(stderr, "Sub process    : ");
 } else {
   if(wait(&status) == -1) {
     perror("Main process wait(2) failed");
     return(5);
   }
   fprintf(stderr, "Main process   : ");
 }
 if(stat(file_path, &stbuf) == -1) {
   fprintf(stderr, "File does not exist\n");
 } else {
   fprintf(stderr, "FILE STILL EXISTS\n");
 }
 if(pid != 0) {
   if(rmdir(dir_path) == -1) {
     perror("Directory removal failed");
     return(6);
   }
 }
 return(0);
}

-----------------------------------------------------------------------
End of C code.


Have a nice day :)

Thomas


Reply via email to