通过文件锁实现,程序开始运行时,先判断文件是否存在,若存在则表明该程序已经在运行了,如果不存在就用open函数创建该文件,程序退出时关闭文件并删除文件

转自:http://blog.csdn.net/tanyouliang/article/details/6922135

 

    通过文件锁实现,程序开始运行时,先判断文件是否存在,若存在则表明该程序已经在运行了,如果不存在就用open函数创建该文件,程序退出时关闭文件并删除文件。  

      

    #include <stdio.h>  

    #include <unistd.h>  

    #include <sys/types.h>  

    #include <sys/stat.h>  

    #include <fcntl.h>  

    #include <errno.h>  

      

    int main(int argc,char **argv)  

    {  

        int fd,n;  

      

        if((fd = open("/home/tanyouliang/shujujiegou/ceshi.c",O_EXCL | O_CREAT,0777)) < 0)  

        {  

            if(errno = EEXIST)  

            {  

                printf("the program is running!\n");  

                return -1;  

            }  

            else  

            {  

                perror("open");  

                return -1;  

            }  

        }  

      

        flock(fd,LOCK_EX);  

        printf("input n:\n");  

        scanf("%d",&n);  

        flock(fd,LOCK_UN);  

      

        close(fd);  

        execlp("rm","rm","-rf","/home/tanyouliang/shujujiegou/ceshi.c",(char *)0);  

        return 0;  

    }  

 

你可能感兴趣的:(open)