03
2014
05

UC编程9-管道pipe操作和共享内存段shm操作

//myuc.h

#include<stdio.h>//io流
#include<stdlib.h>//标准库
#include<unistd.h>//uc标准头文件
#include<fcntl.h>//文件控制
#include<string.h>//c字符串
#include<sys/types.h>
#include<sys/mman.h>//内存映射
#include<sys/stat.h>//文件状态信息
#include<sys/wait.h>//进程等等
#include<dirent.h>//目录操作
#include<signal.h>//信号
#include<sys/time.h>//时间,计时器
#include<sys/ipc.h>//ipc进程间通信
#include<sys/shm.h>//共享内存段
#include<sys/msg.h>//消息队列


//9piperead.c

/*
 创建管道文件命令:mkfifo 9.pipe
管理文件只是进程间通信的一个媒介,它不会存储数据,必须是一边写一边读
 */
#include "myuc.h"
//从管道读取内容
void test1()
{
int fd=open("9.pipe",O_RDONLY);
if(fd==-1) perror("open read"),exit(-1);
int i;
for(i=0;i<50;i++){
int t;
read(fd,&t,4);printf("read:%d\n",t);
//usleep(100000);
}
close(fd);
}
int main(){
test1();
return 0;
}


//9pipewrite.c

#include "myuc.h"
//写内容到管道,必须有读文件对应,不然会一直阻塞进程。
void test1()
{
int fd=open("9.pipe",O_WRONLY);
if(fd==-1) perror("open write"),exit(-1);
int i;
for(i=0;i<50;i++){
write(fd,&i,4);printf("write:%d\n",i);
usleep(300000);
}
close(fd);
}
int main(){
test1();
return 0;
}


//9shma.c

#include "myuc.h"
int main(){//共享内存段操作-创建和存入数据
key_t key=ftok(".",10);
if(key==-1) perror("ftok"),exit(-1);
printf("key=%x\n",key);
int sid=shmget(key,4,IPC_CREAT|IPC_EXCL|0666);
if(sid==-1) perror("shmget"),exit(-2);
void*p=shmat(sid,0,0);
if(p==(void*)-1) perror("shmat"),exit(-3);
printf("id=%d,挂接成功\n",sid);
int* pi=p;
*pi=100;
printf("写入成功\n");
shmdt(p);
return 0;
}


//9shmb.c

#include "myuc.h"
int main(){//共享内存段操作-挂接和取出数据
key_t key=ftok(".",10);
if(key==-1) perror("ftok"),exit(-1);
printf("key=%x\n",key);
int sid=shmget(key,0,0);
if(sid==-1) perror("shmget"),exit(-2);
void*p=shmat(sid,0,0);
if(p==(void*)-1) perror("shmat"),exit(-3);
printf("id=%d,挂接成功\n",sid);
int *pi=p;
printf("取出数据%d\n",*pi);
sleep(10);
shmdt(p);
return 0;
}


//9shmctl.c

#include "myuc.h"
int main()
{//共享内存段操作-获取状态和修改权限/删除操作
key_t key=ftok(".",10);
int sid=shmget(key,0,0);//获取id
//创建 shmget(key,4,IPC_CREAT|IPC_EXCL|0666);
if(sid==-1) perror("shmget"),exit(-1);
struct shmid_ds ds;
shmctl(sid,IPC_STAT,&ds);//状态存入ds
printf("key=%x,mode=%o\n",
ds.shm_perm.__key,(int)ds.shm_perm.mode);
printf("size=%d,nattch=%d\n",
(int)ds.shm_segsz,(int)ds.shm_nattch);
ds.shm_perm.mode=0660;//能修改权限
ds.shm_segsz=8;//不能修改大小
shmctl(sid,IPC_SET,&ds);
shmctl(sid,IPC_RMID,0);//删除
return 0;
}





版权声明:
作者:真爱无限 出处:http://www.pukuimin.top 本文为博主原创文章版权归作者所有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文链接.
« 上一篇下一篇 »

相关文章:

评论列表:

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。