I have this code provided by my teacher, it opens a file, maps into the memory with mmap and then write a string using gets. The problem is that it writes only the first 2 characters of the string into the file even if the printf prints all the string. Any advice?
#include <stdlib.h>
#include <stdio.h>
#include <sys/mman.h>
#include <fcntl.h>
#include <unistd.h>
#define PAGE_SIZE (8192)
int main(int argc, char** argv){
pid_t pid;
int fd;
char* buffer;
if (argc!= 2) {
printf("Syntax: prog file_name\n");
return -1;
}
fd=open(argv[1], O_RDWR);
if (fd== -1) {
printf("open error");
return -2;
}
buffer = (char*)mmap(NULL,PAGE_SIZE,PROT_READ|PROT_WRITE,MAP_SHARED,fd,0);
close(fd);
if (buffer == NULL){
printf("mmap error\n");
return -3;
}
pid = fork();
if(pid == -1){
printf("fork error\n");
return -4;
}
if(pid == 0){
gets(buffer);
return 0;
}
waitpid(pid, NULL);
printf("%s\n",buffer);
return 0;
}