设为首页 加入收藏

TOP

Linux进程同步机制-Futex(二)
2014-11-24 07:26:12 来源: 作者: 【 】 浏览:4
Tags:Linux 进程 同步 机制 -Futex
;


struct namelist
{
int id;
char name[20];
};


int
main(void)
{
int fd, pid, status;
int *ptr;
struct stat stat;

// create a Posix shared memory
int flags = O_RDWR | O_CREAT;
fd = shm_open(shmfile, flags, FILE_MODE);
if (fd < 0)
{
printf("shm_open failed, errormsg=%s errno=%d", strerror(errno), errno);
return 0;
}
ftruncate(fd, size);
ptr = (int *)mmap(NULL, size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);


pid = fork();
if (pid == 0) { // child process
sleep(5);
printf("Child %d: start\n", getpid());

fd = shm_open(shmfile, flags, FILE_MODE);
fstat(fd, &stat);
ptr = (int *)mmap(NULL, size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
close(fd);
struct namelist tmp;


// store total num in ptr[0];
*ptr = 3;

namelist *cur = (namelist *)(ptr+1);


// store items
tmp.id = 1;
strcpy(tmp.name, "Nellson");
*cur++ = tmp;
tmp.id = 2;
strcpy(tmp.name, "Daisy");
*cur++ = tmp;
tmp.id = 3;
strcpy(tmp.name, "Robbie");
*cur++ = tmp;


printf("wake up parent\n");
syscall(__NR_futex ,ptr, FUTEX_WAKE, 1, NULL );


exit(0);
} else{ // parent process
printf("parent start waiting\n");
syscall(__NR_futex , ptr, FUTEX_WAIT, *(int *)ptr, NULL );
printf("parent end waiting\n");


struct namelist tmp;


int total = *ptr;
printf("\nThere is %d item in the shm\n", total);

ptr++;
namelist *cur = (namelist *)ptr;


for (int i = 0; i< total; i++) {
tmp = *cur;
printf("%d: %s\n", tmp.id, tmp.name);
cur++;
}


printf("\n");
waitpid(pid, &status, 0);
}


// remvoe a Posix shared memory from system
printf("Parent %d get child status:%d\n", getpid(), status);
return 0;
}


------------------分割线------------------


root:/home/ftpuser/ipc#g++ -o futex -lrt futex.cc
root:/home/ftpuser/ipc#./futex
parent start waiting
Child 2825: start
wake up parent
parent end waiting


There is 3 item in the shm
1: Nellson
2: Daisy
3: Robbie


Parent 2824 get child status:0


首页 上一页 1 2 下一页 尾页 2/2/2
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇Linux下获得本机IP及网卡状态的函.. 下一篇Linux模块的一点事情

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容:

·Redis 分布式锁全解 (2025-12-25 17:19:51)
·SpringBoot 整合 Red (2025-12-25 17:19:48)
·MongoDB 索引 - 菜鸟 (2025-12-25 17:19:45)
·What Is Linux (2025-12-25 16:57:17)
·Linux小白必备:超全 (2025-12-25 16:57:14)