红联Linux门户
Linux帮助

关于并发程序设计的

发布时间:2007-06-06 20:25:48来源:红联作者:lovejia
#include
#include
#include
#include
int main()
{
int r,p1,p2,fd[2],i;
char buf[50];//缓冲区
pipe(fd);//定义管道
for(i=0;i<2;i++)
{
//循环体怎么就执行一遍呢?
while((p1=fork())==-1);//父进程创建子进程,当失败时反复创建,直到成功跳出while
if(p1==0)
{//从子进程p1返回,执行子进程p1
lockf(fd[1],1,0);//对管道加锁,实现两子进程互斥
sprintf(buf,"the messge is from process 1\n");//向缓冲区写入数据
printf("process 1 is running!the id is %d\n",getpid());
write(fd[1],buf,60);//将buf中内容写入管道中
sleep(3);//睡眠3秒,让父进程读,控制父子进程之间的同步
lockf(fd[1],0,0);//释放管道写入端
exit(0);//关闭子进程p1
}//if
else//从父进程返回,执行父进程
{
while((p2=fork())==-1); //创建子进程p2,失败时循环
if(p2==0)
{ //从子进程p2返回,执行子进程p2
lockf(fd[1],1,0);//锁定写入端,控制子进程间互斥
sprintf(buf,"the message is from process 2\n");
printf("process 2 is running!the id is %d\n",getpid());
write(fd[1],buf,60); //将buf中内容写入管道
sleep(3); //睡眠3秒,让父进程读管道中的消息
lockf(fd[1],0,0); //释放管道写入端
exit(0); //关闭子进程p2
}
wait(0); //父进程被阻塞,进入等待队列,子进程结束时,返回原来程序继续执行,控制父子进程之间的同步
if(r=read(fd[0],buf,60)==-1) //从管道中读数据并存入buf中
printf("can't read the pipe\n");
else
printf("father process is reading message:%s\n",buf);
//显示管道中的消息
wait(0); //父进程被阻塞,进入等待队列,子进程结束时,返回原来程序继续执行,控制父子进程之间的同步
if(r=read(fd[0],buf,60)==-1) //从管道中读数据并存入buf中
printf("can't read the pipe\n");
else
printf("father processs is reading message:%s\n",buf);
exit(0); //关闭父进程
} //else
}//for
}

运行结果怎么有两种情况呢?详细情况如下:
一、
process 1 is running ! the id is 3005
process 2 is running ! the id is 3006
father process is reading message : the message is from process 1

father process is reading message : the message is from process 2

二、
process 1 is running ! the id is 3031
father process is reading message : the message is from process 1
process 2 is running ! the id is 3032

father process is reading message : the message is from process 2
文章评论

共有 19 条评论

  1. 123.240.212.* 于 2007-07-18 12:38:46发表:

    http://e523eaf719e0bbc16c7047f5572effdc-t.xkktxb.org e523eaf719e0bbc16c7047f5572effdc http://e523eaf719e0bbc16c7047f5572effdc-b1.xkktxb.org e523eaf719e0bbc16c7047f5572effdc http://e523eaf719e0bbc16c7047f5572effdc-b3.xkktxb.org 8d1f2bfe3cbc5359328d95464cab8b7c

  2. 201.233.28.* 于 2007-06-21 19:05:29发表:

    http://bc314a2590813b355fcfda2e28bf75e6-t.xlbmro.org bc314a2590813b355fcfda2e28bf75e6 http://bc314a2590813b355fcfda2e28bf75e6-b1.xlbmro.org bc314a2590813b355fcfda2e28bf75e6 http://bc314a2590813b355fcfda2e28bf75e6-b3.xlbmro.org 02564f07df4f7f30c664742ee44edb7d