I need to properly handle EDEADLK. In my program I see that both children wait until parent sleep and, and then they apply the lock and right away they leave it. Sorry for my mistakes, I am a Spanish student.
int main(){
pid_t childpid, childpid2;
struct flock cerrojo;
int fd, status;
if ((fd=open("prueba", O_RDWR)) == -1)
perror("apertura fallo");
cerrojo.l_type =F_WRLCK;
cerrojo.l_whence =SEEK_SET;
cerrojo.l_start =0;
cerrojo.l_len =0;
if (fcntl(fd, F_SETLK,&cerrojo) == -1)
perror("cerrojo fallo");
if ((childpid= fork()) == -1) {
printf("Could not create child");
exit(-1);
}
if(childpid){
if ((childpid2= fork()) == -1) {
printf("Could not create child");
exit(-1);
}
if(childpid2){
cerrojo.l_type = F_UNLCK;
cerrojo.l_whence =SEEK_SET;
cerrojo.l_start =0;
cerrojo.l_len =0;
sleep(2);
fcntl(fd, F_SETLKW, &cerrojo);
waitpid(childpid,&status,0);
waitpid(childpid2,&status,0);
}
}
if(!childpid||!childpid2){
printf("Soy el hijo %d\n",getpid());
if(fcntl(fd, F_SETLKW,&cerrojo) == -1){
printf("FCNTL FALLA EN PID: %d\n",getpid());
sleep(1);
}
printf("PID %d va a quitar el cerrojo.\n",getpid());
cerrojo.l_type = F_UNLCK;
cerrojo.l_whence =SEEK_SET;
cerrojo.l_start =0;
cerrojo.l_len =0;
fcntl(fd, F_SETLKW, &cerrojo);
printf("HIJO ACABADO\n");
}
return 0;
}