Laendor86

File_esercitation v2

Apr 20th, 2021
531
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #include<fcntl.h>
  2. #include<stdio.h>
  3. #include<stdlib.h>
  4. #include<string.h>
  5. #include<unistd.h>
  6. #include<sys/wait.h>
  7.  
  8. void forked_process();
  9. void error(char *mess_err);
  10. void debug(char* db);
  11.  
  12. int main(int argc, char* argv[])
  13. {char *file_name;
  14.  int forked;
  15.  char *file_message;
  16.  int fd,status;
  17.  size_t len;
  18.    
  19.  printf("Insert the name of new file: ");
  20.  scanf("%m[^\n]%*c",&file_name);
  21.  fd = open(file_name, O_CREAT|O_RDWR|O_TRUNC, S_IRWXU|S_IRWXG|S_IRWXO);
  22.  if (fd==-1)
  23.   error("open the file!");
  24.  forked = fork();
  25.  if(forked==-1)
  26.   error("fork process");
  27.  if(forked==0){
  28.     printf("Insert a message for file:");
  29.     scanf("%m[^\n]%*c",&file_message);
  30.     len = strlen(file_message);  
  31.     if (write(fd,file_message,len) == -1)
  32.     error(" write on file!");
  33.     free(file_message);
  34.    exit (len);
  35.   }  
  36.  else{
  37.  int lenght;
  38.   if(wait(&status)==-1)
  39.     error("wait child");
  40.   else if((lenght=WEXITSTATUS(status))==-1)
  41.     error("terminate child without error!");
  42.   len = (size_t) lenght;  
  43.   char *message = malloc(len);
  44.   if(lseek(fd,0,0)==-1)
  45.     error("return at start of the file!");
  46.  debug("1");
  47.   if(read(fd,message,len)==-1)
  48.     error("read file!");
  49.  debug("2");  
  50.   if(close(fd)==-1)
  51.     error("close file!");
  52.  debug("3");  
  53.   printf("The message read from file %d is : %s\n", fd, message);
  54.   free(message);
  55.   return 0;
  56.   }
  57.  
  58. }
  59.  
  60. void forked_process(int file_d)
  61. {char *message;
  62.  int strl;  
  63.  printf("Insert a message for file:");
  64.  scanf("%m[^\n]", &message);  
  65.  strl = strlen(message);  
  66.  if (write(file_d,message,strl) == -1)
  67.   error(" write on file!");
  68. }
  69.  
  70. void error(char *mes_err)
  71. {
  72.     fprintf(stderr,"Error unable to %s\n", mes_err);
  73.     exit(1);
  74. }
  75.  
  76. void debug(char* db)
  77. {
  78.     printf("Debug point %s \n", db);
  79. }
RAW Paste Data

Adblocker detected! Please consider disabling it...

We've detected AdBlock Plus or some other adblocking software preventing Pastebin.com from fully loading.

We don't have any obnoxious sound, or popup ads, we actively block these annoying types of ads!

Please add Pastebin.com to your ad blocker whitelist or disable your adblocking software.

×