android
--------------------------------------------------------------------------------------------------------------
linux
1、信号
signal()函数:
#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <linux/sched.h>
/*
signal() ---->
//linux/kernel/signal.c
SYSCALL_DEFINE2(signal, int, sig, __sighandler_t, handler)---->
do_sigaction();--->
*/
void signal_handler(int signum)
{
printf("signum=%d\n",signum);
}
int main(void)
{
signal(16, signal_handler);
while(1)
sleep(5);
return 0;
}
发送信号:kill -s 16 pid
2、消息队列
(进程1)发送消息
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <unistd.h>
#include <string.h>
#include "def.h"
int main(void)
{
int qid;
key_t key;
int ret;
struct msgmbuf msg;
//利用ftok产生标准的key
key = ftok(KEY_ID,PROJ_ID);
if (key == -1){
printf("ftok err!\n");
return -1;
}
printf("key:%d\n",key);
//创建打开一个消息队列
qid = msgget(key,IPC_CREAT|0777);
if (qid == -1){
printf("msgget err!\n");
return -1;
}
printf("qid:%d\n",qid);
msg.msg_type = getpid();
//memcpy(msg.msg_buf,"ni hao hhhhhhhhh",strlen("ni hao hhhhhhhhh"));
printf("pid:%ld", msg.msg_type);
while (1)
{
printf("send.....\n");
//发送消息
ret = msgsnd(qid, &msg, sizeof(struct msgmbuf), 0);
if (ret < 0){
printf("msgsnd err!\n");
return -1;
}
sleep(1);
}
/*
//删除消息队列
ret = msgctl(qid, IPC_RMID,NULL);
if (ret < 0){
printf("msgctl err!\n");
return -1;
}
*/
return 0;
}
进程2(接收消息)
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <unistd.h>
#include <string.h>
#include "def.h"
int main(void)
{
int qid;
key_t key;
int ret;
struct msgmbuf msg;
//利用ftok产生标准的key
key = ftok(KEY_ID,PROJ_ID);
if (key == -1){
printf("ftok err!\n");
return -1;
}
printf("key:%d\n",key);
//创建打开一个消息队列
qid = msgget(key,IPC_CREAT|0777);
if (qid == -1){
printf("msgget err!\n");
return -1;
}
printf("qid:%d\n",qid);
while (1)
{
//接收消息
ret = msgrcv(qid, &msg, sizeof(struct msgmbuf),0, 0);
if (ret < 0){
printf("msgrcv err!\n");
return -1;
}
printf("msgrcv:ret:%d,pid:%ld\n", ret,msg.msg_type);
}
/*
//删除消息队列
ret = msgctl(qid, IPC_RMID,NULL);
if (ret < 0){
printf("msgctl err!\n");
return -1;
}
*/
return 0;
}
公共头文件
#ifndef __DEF_H__
#define __DEF_H__
#define KEY_ID "/home/"
#define PROJ_ID 'A'
struct msgmbuf{
long msg_type;
char msg_buf[512];
};
#endif
因篇幅问题不能全部显示,请点此查看更多更全内容