flock
#include "head.h"
struct data{
int now;
int sum;
};
void getnum(struct data *num){
int fd;
if((fd = open(".data", O_RDONLY)) < 0) {
perror("get_open");
exit(1);
}
read(fd, (void *)num, sizeof(struct data));
close(fd);
}
void setnum(struct data *num){
int fd;
if((fd = open(".data", O_RDWR | O_CREAT, 0600)) < 0) {
perror("set_open");
exit(1);
}
write(fd, (void *)num, sizeof(struct data));
close(fd);
}
void do_sum(int i, struct data *num, int max) {
int fd_lock;
if((fd_lock = open(".lock", O_RDONLY )) < 0){
perror("lock_open");
exit(1);
}
while(1) {
flock(fd_lock, LOCK_EX);
getnum(num);
if(num->now >= max) break;
num->now++;
num->sum += num->now;
setnum(num);
printf("<i am the %d child> now = %d, sum = %d\n", i, num->now, num->sum);
flock(fd_lock, LOCK_UN);
}
close(fd_lock);
}
int main(int argc, char **argv){
int opt;
int ins = 1, max = 100;
struct data num;
num.now = 0;
num.sum = 0;
setnum(&num);
while((opt = getopt(argc, argv, "i:n:")) != -1) {
switch(opt){
case 'i':
ins = atoi(optarg);
break;
case 'n':
max = atoi(optarg);
break;
default:
fprintf(stderr, "Usage : %s -i num1 -n num2", argv[0]);
exit(1);
}
}
pid_t pid;
int i;
for(i = 0; i < ins; i++) {
if((pid = fork()) < 0) {
perror("fork()");
exit(1);
}
if(pid == 0) break;
}
if(pid == 0) {
do_sum(i, &num, max);
} else {
for(int i = 0; i < ins; i++) {
wait(NULL);
}
}
return 0;
}
ftok
#include "head.h"
int main(){
key_t key;
if((key = ftok("1.ftok.c", 123)) < 0){
perror("ftok");
exit(1);
}
printf("key = 0x%x\n", key);
printf("123 = 0x%x\n", 123);
return 0;
}
![请添加图片描述](https://i-blog.csdnimg.cn/blog_migrate/d97b9299b3c20fc6e66eac9bb46e374b.png)
![请添加图片描述](https://i-blog.csdnimg.cn/blog_migrate/5bb51d1ca8abd1a23a29acc3fd046eca.png)