一、要求实现AB进程随时对话
- A进程发送一句话给B进程,B进程接收后打印
- B进程回复一句话给A进程,A进程接收后打印
随机重复1,2步骤,当收到quit后,要结束AB进程
A进程:
#include <stdio.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <unistd.h>
#include <string.h>
#include <signal.h>
struct msgbuf
{
long mtype;
char mtext[128];
};
int main(int argc, const char *argv[])
{
key_t key = ftok("./",1);
if(ftok < 0)
{
perror("ftok");
return -1;
}
int msqid = msgget(key,IPC_CREAT|0664);
if(msqid < 0)
{
perror("msgget");
return -1;
}
struct msgbuf sndbuf;
pid_t cpid = fork();
if(cpid > 0)
{
while(1)
{
sndbuf.mtype = 1;
scanf("%s",sndbuf.mtext);
msgsnd(msqid,&sndbuf,sizeof(sndbuf.mtype),0);
if(strcmp(sndbuf.mtext,"quit") == 0)
break;
}
}
else if(0 == cpid)
{
while(1)
{
msgrcv(msqid,&sndbuf,sizeof(sndbuf.mtext),2,0);
if(strcmp(sndbuf.mtext,"quit") == 0)
break;
printf("%s\n",sndbuf.mtext);
}
kill(getppid(),2);
}
else
{
perror("fork");
return -1;
}
return 0;
}
B进程
#include <stdio.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <unistd.h>
#include <string.h>
#include <signal.h>
struct msgbuf
{
long mtype;
char mtext[128];
};
int main(int argc, const char *argv[])
{
key_t key = ftok("./",1);
if(ftok < 0)
{
perror("ftok");
return -1;
}
int msqid = msgget(key,IPC_CREAT|0664);
if(msqid < 0)
{
perror("msgget");
return -1;
}
struct msgbuf sndbuf;
pid_t cpid = fork();
if(cpid > 0)
{
while(1)
{
sndbuf.mtype = 2;
scanf("%s",sndbuf.mtext);
msgsnd(msqid,&sndbuf,sizeof(sndbuf.mtype),0);
if(strcmp(sndbuf.mtext,"quit") == 0)
break;
}
}
else if(0 == cpid)
{
while(1)
{
msgrcv(msqid,&sndbuf,sizeof(sndbuf.mtext),1,0);
if(strcmp(sndbuf.mtext,"quit") == 0)
break;
printf("%s\n",sndbuf.mtext);
}
kill(getppid(),2);
}
else
{
perror("fork");
return -1;
}
return 0;
}
二、要求在共享内存中存入字符串"1234567",A进程循环打印,B进程循环逆置,要求不出现乱序
#include <stdio.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
int main(int argc, const char *argv[])
{
key_t key = ftok("./",10);
if(key < 0)
{
perror("ftok");
return -1;
}
int shmid = shmget(key,16,IPC_CREAT|0664);
if(shmid < 0)
{
perror("shmget");
return -1;
}
void *addr = shmat(shmid,NULL,0);
if((void *)-1 == addr)
{
perror("shmat");
return -1;
}
*(int *)addr = 0;
char *ptr = (char *)addr+4;
strcpy(ptr,"1234567");
pid_t cpid = fork();
if(cpid > 0)
{
while(1)
{
if(*(int *)addr == 0)
{
printf("%s\n",(char *)addr+4);
*(int *)addr = 1;
}
}
}
else if(0 == cpid)
{
while(1)
{
if(*(int *)addr == 1)
{
char *star = (char *)addr+4;
char *end = (char*)addr+4+strlen(ptr)-1;
while(star<end)
{
char temp = *star;
*star = *end;
*end = temp;
star++;
end--;
}
*(int *)addr = 0;
}
}
}
else
{
perror("fork");
return -1;
}
return 0;
}