#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <unistd.h>
#define MSGKEY 1234
struct msgbuf {
long mtype; /* message type, must be > 0 /
char mtext[128]; / message data */
};
int main()
{
int msgid, ret;
struct msgbuf m;
pid_t pid;
msgid = msgget(MSGKEY, 0); //获取消息队列
if (-1 == msgid)
{
perror("msgget");
exit(1);
}
pid = fork();
if (-1 == pid)
{
perror("fork");
exit(1);
}
else if (0 == pid) //子进程发送
{
while (1)
{
scanf("%s", m.mtext);
m.mtype = 1;
ret = msgsnd(msgid, &m, sizeof(m.mtext), 0);
if (-1 == ret)
{
perror("msgsnd");
}
if (!strcmp(m.mtext, "bye"))
{
m.mtype = 2;
msgsnd(msgid, &m, sizeof(m.mtext), 0);
break;
}
bzero(m.mtext, sizeof(m.mtext));
}
}
else //父进程接收
{
while (1)
{
ret = msgrcv(msgid, &m, sizeof(m.mtext), 2, 0);
if (-1 == ret)
{
perror("msgrcv");
}
if (!strcmp(m.mtext, "bye"))
{
kill(pid, 9);
break;
}
printf("\t\t%s\n", m.mtext);
bzero(m.mtext, sizeof(m.mtext));
}
int status;
wait(&status);
}
return 0;
}
#include <unistd.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
int main()
{
int ret, fd[2] = {0};
pid_t pid;
char buf[32] = {0};
ret = pipe(fd); //创建无名管道
if (-1 == ret)
{
perror("pipe");
exit(1);
}
pid = fork();
if (-1 == pid)
{
perror("fork");
exit(1);
}
else if (0 == pid)
{
while (1)
{
scanf("%s", buf);
ret = write(fd[1], buf, strlen(buf)); //写管道 fd[1]
if (-1 == ret)
{
perror("write");
}
if (!strcmp(buf, "bye")) //输入关键字bye 退出循环
{
break;
}
memset(buf, 0, sizeof(buf));
}
}
else //父进程,读管道
{
while (1)
{
ret = read(fd[0], buf, sizeof(buf)); //fd[0]用于读管道
if (-1 == ret)
{
perror("read");
}
if (!strcmp(buf, "bye"))
{
break;
}
printf("\t\t\t%s\n", buf);
memset(buf, 0, sizeof(buf));
}
int status;
waitpid(pid, &status, 0);
}
return 0;
}