为梦 前行hua.blog.chinaunix.net
huazaicola
全部博文(128)
2012年(2)
2011年(51)
2010年(75)
sabrisu
xhb8413
小雅贝贝
浪花小雨
格伯纳
cynthia
Vizard
renlong_
zhjiado
f_c_g_
zhilinwa
镇水铁牛
分类: LINUX
2010-08-26 10:32:58
#include <sys/types.h>#include <sys/msg.h>#include <unistd.h>#include<errno.h>#include<stdio.h>#include<stdlib.h>#include<string.h>#include<sys/ipc.h>#include<signal.h>struct msg_buf{ long mtype; char mtext[255];};/* * signal handle funciton*/void func(int sign_no){ if(sign_no == SIGBUS) { printf("get the signal!\n"); }}main(void){ key_t key; int msgid; struct msg_buf msgbuf; key = ftok("./msg", 'a'); if((msgid = msgget(key, IPC_CREAT | 0666)) < 0) //create the same queue with reading process { printf("msgget error"); exit(1); } msgbuf.mtype = getpid(); //getpid for sending to reading process strcpy(msgbuf.mtext, "hello hua zai"); if(msgsnd(msgid, &msgbuf, sizeof(msgbuf), IPC_NOWAIT) < 0) { printf("msgsnd error:%s\n", strerror(errno)); exit(1); } printf("send %s to queue\n", msgbuf.mtext); signal(SIGBUS, func); //register the signal pause(); //waiting for signal// printf("process waked up!\n");}
接受进程代码:
#include <sys/types.h>#include <sys/msg.h>#include <unistd.h>#include<errno.h>#include<stdio.h>#include<stdlib.h>#include<string.h>#include<sys/ipc.h>#include<signal.h>struct msg_buf{ long mtype; char mtext[255];};main(void){ key_t key; int msgid; struct msg_buf msgbuf; key = ftok("./msg", 'a'); //use ftok to get the key if((msgid = msgget(key, IPC_CREAT | 0666)) < 0) { printf("msgget error\n"); exit(1); } if(msgrcv(msgid, &msgbuf, sizeof(msgbuf), 0, IPC_NOWAIT) < 0) //get address of struct, &msgbuf { printf("msgrcv error:%s\n", strerror(errno)); exit(1); } printf("reveive %s from queue\n", msgbuf.mtext); kill(msgbuf.mtype, SIGBUS); //seng message to another process sleep(5); if(msgctl(msgid, IPC_RMID, 0) < 0) { printf("msgctl error\n"); exit(1); } printf("queue is cancle!\n");}
上一篇:指向指针的指针 **p
下一篇:多线程
chinaunix网友2010-08-28 08:59:25
Download More than 1000 free IT eBooks: http://free-ebooks.appspot.com
登录 注册