日期:2014-05-16  浏览次数:20610 次

问个简单问题
#include <stdio.h>
#include <sys/msg.h>

struct   msgform
{
long   type;
int   text;
};

main()
{
struct   msgform   msg;
char   input[20];
char   output[20];
int   fd[2],msgid,pid,i,j;
while(pipe(fd)=fork())==-1);
while((pid=fork())==-1);
if(pid> 0)
{
for(i=0;i <5;i++)
{
printf( "\n   parent   input:   \n ");
scanf( "%s ",input);
write(fd[1],input,5);
msg.type=1;
msg.text=i;
msgsnd(msgid,&msg,sizeof(int),0);
do
{
msgrcv(msgid,&msg,sizeof(int),2,0);
}
while(msg.text==i);
}
wait(0);
}
else   if(pid==0)
{
for(j=0;j <5;j++);
{
do
{
msgrcv(msgid,&msg,sizeof(int),1,0);
}
while(msg.text==j);
read(fd[0],output,5);
printf( "child   output:\n%s\n ",output);
}
}
exit(0);
}

我想做的是父进程产生一个子进程,父进程输入一行给管道,然后子进程从管道读取显示,做5次.用传递消息来控制同步,也就是父进程写一次,子进程才读一次,子进程读完父进程才再写

但是我执行后只有一次写和读,然后就没有输入提示了

希望能给我指出错误的地方

------解决方案--------------------
个人感觉程序的do while部分有问题.
流程应该是这样的:
父进程写完管道, 发送一个 "写完 "消息, 如1, 阻塞(循环接收消息);
子进程读完管道, 发送一个 "读完 "消息, 如2, 阻塞(循环接收消息);
父进程接收到消息2, 开始写管道;
子进程接收到消息1, 开始读管道.

你的程序子进程只是接收消息, 没有发送, 父进程的阻塞会一直进行, 所以出问题.

还有一种办法是用sync系统调用, 具体查阅相关资料
------解决方案--------------------
楼主的程序里没有建立消息队列的代码呀!
我只看在使用msgid,可是没有看到你给她赋值啊!
使用使用消息队列,一般需要的几个系统调用:
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>

1.建立消息队列
msgkey = ftok(...)
msgid = msgget(msgkey, ...)

2.使用
msgctl(msgid ...)
msgsnd(msgid, ...)
msgrcv(msgid, ...)

3.删除消息队列
msgctl(msgid, IPC_RMID, ...)


还是好好看看书吧!
推荐UNPV2 和 APUE2