Advertisement
Guest User

Untitled

a guest
Apr 29th, 2017
50
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.26 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <unistd.h>
  3. #include <sys/types.h>
  4.  
  5. int write_file ()
  6. {
  7.     FILE *file = fopen( "./testfile.txt", "w" );
  8.     fprintf(file, "testtext\n123456");
  9.     fclose( file );
  10.     return 0;
  11. }
  12.  
  13. int read_file ()
  14. {
  15.     FILE *file = fopen( "./testfile.txt", "r" );
  16.     int character;
  17.     while  ( ( character = fgetc( file ) ) != EOF )
  18.     {
  19.         printf( "%c", character );
  20.     }
  21.     printf("\n");
  22.     fclose( file );
  23.     return 0;
  24. }
  25.  
  26. int lock()
  27. {
  28.     FILE *lockfile = fopen( "./lock.lck", "w" );
  29.     fclose( lockfile );
  30.     return 0;
  31. }
  32.  
  33. int unlock()
  34. {
  35.     remove("./lock.lck");
  36.     return 0;
  37. }
  38.  
  39. int exist_file()
  40. {
  41.     FILE *fp = fopen ( "./lock.lck", "r");
  42.     if (fp == NULL) { // file does not exist
  43.         return 0;
  44.     }
  45.     else{
  46.         return 1;
  47.     }
  48. }
  49.  
  50. int main ( int argc, char *argv[] )
  51. {
  52.     int i=0;
  53.     pid_t npid; //variable for PID
  54.  
  55. npid = fork(); //fork parent process
  56.  
  57. //while(1){
  58.  
  59.     if(npid > 0){ //if parent process
  60.     lock();
  61.     write_file();
  62.     i = exist_file();
  63.     printf("return status = %d", i);
  64.     printf("test");
  65.     unlock();
  66.     i = exist_file();
  67.     }
  68.     else if(npid == 0){ //if child process
  69.     read_file();
  70.        
  71.     }
  72.     else if(npid == -1){
  73.         printf("ERROR");
  74.     }
  75.    
  76. //  }
  77. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement