欢迎关注博主 Mindtechnist 或加入【Linux C/C++/Python社区】一起探讨和分享Linux C/C++/Python/Shell编程、机器人技术、机器学习、机器视觉、嵌入式AI相关领域的知识和技术。
专栏:《Linux从小白到大神》 | 系统学习Linux开发、VIM/GCC/GDB/Make工具、Linux文件IO、进程管理、进程通信、多线程等,请关注专栏免费学习。
进程间也可以通过互斥锁来达到同步的目的。在pthread_mutex_init初始化之前需要修改属性为进程间共享。
#include
int pthread_mutexattr_destroy(pthread_mutexattr_t *attr);
int pthread_mutexattr_init(pthread_mutexattr_t *attr);
函数描述
函数参数
函数返回值
Upon successful completion, pthread_mutexattr_destroy() and pthread_mutexattr_init() shall return zero; otherwise, an error number shall be returned to indicate the error.
#include
int pthread_mutexattr_getpshared(const pthread_mutexattr_t *restrict attr, int *restrict pshared);
int pthread_mutexattr_setpshared(pthread_mutexattr_t *attr, int pshared);
函数描述
函数参数
函数返回值
Upon successful completion, pthread_mutexattr_setpshared() shall return zero; otherwise, an error number shall be returned to indicate the error. Upon successful completion, pthread_mutexattr_getpshared() shall return zero and store the value of the process-shared attribute of attr into the object referenced by the pshared parameter. Otherwise, an error number shall be returned to indicate the error.
借助fcntl()函数来实现锁机制,操作文件的进程没有获得锁时,可以打开,但无法执行read和write操作。文件锁具有读写锁的特点,写独占,读共享,写优先级高。
#include
#include
int fcntl(int fd, int cmd, ... /* arg */ );
函数描述
fcntl() performs one of the operations described below on the open file descriptor fd. The operation is determined by cmd. 获取、设置文件访问控制属性。
函数参数
struct flock {
...
short l_type; /* Type of lock: F_RDLCK, F_WRLCK, F_UNLCK 锁的类型 */
short l_whence; /* How to interpret l_start: SEEK_SET, SEEK_CUR, SEEK_END 偏移位置 */
off_t l_start; /* Starting offset for lock 起始偏移 */
off_t l_len; /* Number of bytes to lock 长度,0表示整个文件加锁 */
pid_t l_pid; /* PID of process blocking our lock (F_GETLK only) 持有该锁的进程ID */
...
};
函数返回值
For a successful call, the return value depends on the operation:
F_DUPFD The new descriptor.
F_GETFD Value of flags.
F_GETFL Value of flags.
F_GETLEASE Type of lease held on file descriptor.
F_GETOWN Value of descriptor owner.
F_GETSIG Value of signal sent when read or write becomes possible, or zero for traditional SIGIO behavior.
All other commands Zero.
On error, -1 is returned, and errno is set appropriately.
用法示例:
#include
#include
#include
#include
#include
#include
#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;
}
编译运行
此时我们再开一个终端运行上面的程序