1.要求实现AB进程对话
A进程先发送一句话给B进程,B进程接收后打印
B进程再回复一句话给A进程,A进程接收后打印
重复1.2步骤,当收到quit后,要结束AB进程
提示:两根管道
提示:用一个消息队列,两种类型即可
当对方输入quit后,退出AB进程删除消息队列;
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include<sys/ipc.h>
#include<sys/msg.h>
struct msgp
{
long mytype;
char mtext[128];
};
int main(int argc, const char *argv[])
{
key_t key=ftok("./02.c",1);
if(key<0)
{
perror("ftok");
return -1;
}
int msqid=msgget(key,IPC_CREAT|0664);
if(msqid<0)
{
perror("msgget");
return -1;
}
struct msgp buf;
while(1)
{
if(0==buf.mytype)
break;
printf("please puts mtext:");
scanf("%s",buf.mtext);
buf.mytype=1;
if(msgsnd(msqid,&buf,sizeof(buf.mtext),0)<0)
{
perror("msgsnd");
return -1;
}
if(0==strcmp(buf.mtext,"quit"))
break;
msgrcv(msqid,&buf,sizeof(buf.mtext),2,0);
printf("%ld: %s\n",buf.mytype,buf.mtext);
if(0==strcmp(buf.mtext,"quit"))
break;
}
return 0;
}
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include<sys/ipc.h>
#include<sys/msg.h>
#include<sys/types.h>
struct msgp
{
long mytype;
char mtext[128];
};
int main(int argc, const char *argv[])
{
key_t key=ftok("./02.c",1);
if(key<0)
{
perror("ftok");
return -1;
}
int msqid=msgget(key,IPC_CREAT|0664);
if(msqid<0)
{
perror("msgget");
return -1;
}
struct msgp rec;
while(1)
{
if(msgrcv(msqid,&rec,sizeof(rec.mtext),1,0)<0)
{
perror("msgrcv");
break;
}
printf("%ld: %s\n",rec.mytype,rec.mtext);
if(0==strcmp(rec.mtext,"quit"))
break;
printf("please puts mtext:");
scanf("%s",rec.mtext);
rec.mytype=2;
if(msgsnd(msqid,&rec,sizeof(rec.mtext),0)<0)
{
perror("msgsnd");
return -1;
}
if(0==strcmp(rec.mtext,"quit"))
break;
}
return 0;
}
2.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
int main(int argc, const char *argv[])
{
key_t key = ftok("./01signal.c", 1);
int shmid = shmget(key, 32, IPC_CREAT | 0664);
printf("shmid=%d\n", shmid);
void *addr = shmat(shmid, NULL, 0);
int *flag = (int *)addr;
*flag = 0;
char *str = (char *)((int *)addr + 1);
strcpy(str, "123456789");
while (1)
{
int i = 0, j = strlen(str) - 1;
if (1 == *flag)
{
while (i < j)
{
str[i] = str[i] + str[j];
str[j] = str[i] - str[j];
str[i] = str[i] - str[j];
i++;
j--;
}
*flag = 0;
}
}
return 0;
}
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
int main(int argc, const char *argv[])
{
key_t key = ftok("./01signal.c", 1);
int shmid = shmget(key, 32, IPC_CREAT | 0664);
printf("shmid=%d\n", shmid);
void *addr = shmat(shmid, NULL, 0);
int *flag = (int *)addr;
char *str = (char *)((int *)addr + 1);
while (1)
{
if (0 == *flag)
{
printf("%s\n", str);
*flag=1;
}
}
return 0;
}