9月3日
2.
发送端
#include <myhead.h>
struct msgbuf {
long mtype; // 消息类型,必须 > 0
char mtext[128]; // 消息正文
};
int main() {
key_t key = ftok("/", 65);
if (key == -1) {
perror("ftok");
exit(1);
}
int msgid = msgget(key, IPC_CREAT | 0666);
if (msgid == -1) {
perror("msgget");
exit(1);
}
struct msgbuf msg;
msg.mtype = 1;
while (1) {
printf("输入要发送的消息:");
fgets(msg.mtext, 128, stdin);
if (strncmp(msg.mtext, "exit", 4) == 0) break;
if (msgsnd(msgid, &msg, strlen(msg.mtext) + 1, 0) == -1) {
perror("msgsnd");
}
}
return 0;
}
接收端
#include <myhead.h>
struct msgbuf {
long mtype; // 消息类型,必须 > 0
char mtext[128]; // 消息正文
};
int main() {
key_t key = ftok("/", 65);
if (key == -1) {
perror("ftok");
exit(1);
}
int msgid = msgget(key, IPC_CREAT | 0666);
if (msgid == -1) {
perror("msgget");
exit(1);
}
struct msgbuf msg;
while (1) {
if (msgrcv(msgid, &msg, 128, 0, 0) == -1) {
perror("msgrcv");
exit(1);
}
printf("接收到消息: %s", msg.mtext);
if (strncmp(msg.mtext, "exit", 4) == 0) {
printf("收到退出指令,关闭消息队列。\n");
msgctl(msgid, IPC_RMID, NULL); // 删除队列
break;
}
}
return 0;
}
编译运行:
gcc sender.c -o sender
gcc receiver.c -o receiver
# 开两个终端:
./receiver
./sender
3.
#include <myhead.h>
void handler(int signum)
{
if(signum==SIGUSR1)
{
printf("逆子没想到吧,防着你呢\n");
}
}
int main(int argc, const char *argv[])
{
if(signal(SIGUSR1,handler)==SIG_ERR)
{
perror("signal error\n");
return -1;
}
signal(SIGCHLD, SIG_IGN);//忽略子进程退出信号,系统启用自动回收
pid_t pid=fork();
if(pid>0)
{
//非阻塞回收
waitpid(pid,NULL,WNOHANG);
while(1)
{
printf("我真的还想再活500年\n");
sleep(1);
}
}else if(pid==0)
{
printf("活着没啥意思,寻思寻思\n");
sleep(5);
kill(getppid(),SIGUSR1);
exit(EXIT_SUCCESS);
}
return 0;
}