我需要妥善处理 EDEADLK。在我的程序中,我看到两个孩子都等到父母睡觉,然后他们应用锁并立即离开。抱歉我的错误,我是一名西班牙学生。
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;
}