标签:style class blog code http ext
三种IPC被称作XSI IPC,分别是:struct mest_t { long type; // 消息类型 char text[512]; // 消息内容 };
#include <stdio.h> #include <sys/msg.h> #include <sys/types.h> #include <string.h> #include <errno.h> struct mest_t { long type; char text[512]; }; int main(void) { pid_t pid; int mq_id; struct mest_t msg; /* IPC_PRIVATE用于创建一个新队列 * 设置了IPC_EXCL并且设置了IPC_CREAT,当文件存在时返回错误 */ mq_id = msgget(IPC_PRIVATE, IPC_CREAT | IPC_EXCL); if (mq_id == EEXIST) return -1; /* 返回EEXIST表示IPC已存在 */ if ((pid = fork()) < 0) return -1; else if (pid == 0) { /* 子进程 */ msg.type = 123; /* 消息类型 */ strcpy(msg.text, "Hello world!"); /* 消息内容 */ /* 非阻塞方式将消息放入消息队列 * 队列已满则返回EAGAIN */ while (msgsnd(mq_id, (long *)&msg, 512, IPC_NOWAIT) == EAGAIN) sleep(1); } else { /* 非阻塞方式从队列中取消息 * 如果没有指定类型的消息,函数返回-1,errno设置为ENOMSG */ while (msgrcv(mq_id, (long *)&msg, 512, 123, IPC_NOWAIT) == -1) { if (errno == ENOMSG) { printf("There is no this type message!\n"); sleep(1); } } printf("%s\n", msg.text); } return 0; }
#include <stdio.h> #include <unistd.h> #include <stdlib.h> #include <sys/shm.h> #define SHM_SIZE 100 #define SHM_MODE (SHM_W | SHM_R | IPC_CREAT) int main() { int shmid; char *shmptr; pid_t pid; /* 获得共享存储标识符 */ if ((shmid = shmget(IPC_PRIVATE, SHM_SIZE, SHM_MODE)) < 0) return -1; if ((pid = fork()) < 0) return -1; else if (pid == 0) { shmptr = shmat(shmid, 0, 0); /* 参数2为0表示由内核分配共享空间 */ printf("Child attached shared memory is : %lx\n", (unsigned long)shmptr); shmdt(shmptr); /* 使进程脱离该共享空间 */ } else { waitpid(pid, NULL, 0); shmptr = shmat(shmid, 0, 0); printf("Parent attached shared memory is : %lx\n", (unsigned long)shmptr); shmdt(shmptr); shmctl(shmid, IPC_RMID, 0); /* 删除该共享存储段 */ } return 0; }
【Linux编程】XSI IPC,布布扣,bubuko.com
标签:style class blog code http ext
原文地址:http://blog.csdn.net/nestler/article/details/33362385