进程间也可以通过互斥锁来达到同步的目的。在pthread_mutex_init初始化之前需要修改属性为进程间共享。
#include <pthread.h>
int pthread_mutexattr_destroy(pthread_mutexattr_t *attr);
int pthread_mutexattr_init(pthread_mutexattr_t *attr);
#include <pthread.h>
int pthread_mutexattr_getpshared(const pthread_mutexattr_t *restrict attr, int *restrict pshared);
int pthread_mutexattr_setpshared(pthread_mutexattr_t *attr, int pshared);
借助fcntl()函数来实现锁机制,操作文件的进程没有获得锁时,可以打开,但无法执行read和write操作。文件锁具有读写锁的特点,写独占,读共享,写优先级高。
#include <unistd.h>
#include <fcntl.h>
int fcntl(int fd, int cmd, ... /* arg */ );
用法示例:
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdlib.h>
#define _FILE_PATH_ "/home/qq/dm/daemon/test.lock"
int main(int argc, char* argv[])
{
int fd = open(_FILE_PATH_, O_RDWR | O_CREAT, 0644);
if(fd < 0)
{
perror("open err");
return -1;
}
struct flock lk;
lk.l_type = F_WRLCK;
lk.l_whence = SEEK_SET;
lk.l_start = 0;
lk.l_len = 0;
if(fcntl(fd, F_SETLK, &lk) < 0)
{
perror("lock err");
exit(1);
}
while(1)
{
printf("pid: %d\n", getpid());
sleep(1);
}
return 0;
}
编译运行
此时我们再开一个终端运行上面的程序