The exercise is simple. The father process lets me write my name and surname in a file. The son process waits 5 seconds, then reads and displays it. I can't use the #wait()
function.
#include <cstdlib>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
int main(int argc, char** argv) {
char name[20];
char surname[20];
char outp[50];
// The file pointer
FILE *file;
// Open the file in write mode
file = fopen("dati.txt", "w+");
pid_t pid;
pid=fork();
if(pid>0){
printf("Father");
printf("Insert name: ");
scanf("%s",name);
for (int i=0; i<strlen(name); i++) {
if (i==0) {
if (name[i]>='a' && name[i]<='z')
name[i]-=32;
} else {
if (name[i]>='A' && name[i]<='Z')
name[i]+=32;
}
}
printf("Insert surname: ");
scanf("%s", surname);
for (int i=0; i<strlen(name); i++){
if (i==0){
if (surname[i]>='a' && surname[i]<='z')
surname[i]-=32;
} else {
if (surname[i]>='A' && surname[i]<='Z')
surname[i]+=32;
}
}
fputs(name, file);
fputs(" ",file);
fputs(surname, file);
printf("Father exits");
fclose(file);
exit(0);
}else{
sleep(5);
// position to the start of the file
rewind(file);
fgets(outp, 50, file);
printf("Read string: %s", outp);
fclose(file);
exit(0);
}
return 0;
}
If I insert name and surname before the 5th second, the program writes them, but doesn't display them. Otherwise, if I write the name and "accidentally" wait for the 5th second, it displays the file content (which are basically random characters).