进程互斥----ttylock()类似原理实现
之前帮朋友看了一下代码,他想用ttylock(),ttyunlock()系列函数去锁定/dev/ttyS0,但是编译时找不到这些函数,后来我发现这个函数是AIX上的,后来看了一下他的原理。
故按其原理实了如下函数:用以在进程启动时杀掉已经启动的相同进程。
int check_lock(char*file){ FILE*fd; int bpid; fd=fopen(file,"r"); if(fd==NULL){ if(errno==2){ fd=fopen(file,"w+"); if(fd==NULL){ return -1;} } return -1; } fscanf(fd," %d",&bpid); fclose(fd); if(bpid!=getpid()){ if(kill(bpid,0)==0){ return bpid; 有进程已经运行 } return 0; //no locked } return 1; //our locked } int write_lock(char*file){ FILE*fd; int bpid=check_lock(file); if(bpid>1){ if(0!=kill(bpid,9)){ //强制杀死进程 return -1; } sleep(1); //进程消失还要延迟一会 } fd=fopen(file,"w"); if(fd==NULL){ return -1; } fprintf(fd," %10d ",getpid()); fclose(fd); return 0; }