zl程序教程

您现在的位置是:首页 >  后端

当前栏目

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

编程 操作 管道 共享内存 pipe UC
2023-09-27 14:29:33 时间
创建管道文件命令: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 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 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;

}



详解linux进程间通信-管道 popen函数 dup2函数 前言:进程之间交换信息的唯一方法是经由f o r k或e x e c传送打开文件,或通过文件系统。本章将说明进程之间相互通信的其他技术—I P C(InterProcess Communication)。