h和t只打印一次......为什么会这样?

时间:2010-08-08 07:23:50

标签: c

#include <stdio.h>
//#include <conio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h> 
#include <sys/types.h>
int t_array[100];
int h_array[100];
int c,h_comp=0,race_length=0,o=0,i=0,Ti=0;

void cursor(int y)
{
 int i;
 printf("%c[%d;%df",0x1B,y,o);
}
void turtle_fun()
{ 
 int Ti=0;
 while(h_comp!=1&&Ti<=race_length-1)
 {
  cursor(10);  
  printf("t      ");
  fflush(stdout);  
  Ti++;
  sleep(3);
 }
}


void hare_fun(int rh[])
{
 int k;int i=0;
 char pos_h;
 close(rh[0]);
 while(c!=1&&i<=race_length-1)
 {

  cursor(5);
  printf("h      ");
  fflush(stdout);
  i++;
  sleep(1);
 }
 h_comp=1;
}



void god_fun(pid_t id)
{

}


void report_fun(int rh[],int rg[],int rt[])
{ 
 int k,m,pos;
 int pos_h,pos_t;
 close(rh[1]);
 if(k=fork()==0)
 hare_fun(rh);
 else
 {
  if(fork()==0)
  turtle_fun();

 }

}


void main()
{
 int rg[2],rh[2],rt[2],gh[2],gt[2],ht[2];
 int child_id;
 pid_t cpid;
 printf("what is the length of the race");
 scanf("%d",&race_length);
 cpid=fork();
 if(cpid==0)
 {
  pipe(rg);
  pipe(rh);
  pipe(rt);
  report_fun(rh,rg,rt);
 }
 else
 {  
  pipe(gh);
  pipe(gt);
  god_fun(cpid);
 }

} 

1 个答案:

答案 0 :(得分:0)

  

int c,h_comp = 0,race_length = 0,o = 0,i = 0,Ti = 0;

fork()之后的数据段也会分叉,变量将停止共享意味着:

void hare_fun(int rh[])
{
 /*...*/
 h_comp=1;
}

对此

没有影响
void turtle_fun()
{ 
 while(h_comp!=1 /* ... */)
 {
   /* ... */
 }
}

在不同的过程中运行。

获取fork()ed进程共享的内存:

  • 将您需要共享的所有字段放入结构中,例如struct the_struct
  • 添加一个新的全局变量 - 指向结构的指针
  • 使用mmap(0, sizeof(struct the_struct), PROT_READ|PTOT_WRITE, MAP_SHARED|MAP_ANONYMOUS, -1, 0);在任何main()之前的fork()某处为结构分配内存。
  • 以这种方式创建的内存将在fork()之后共享。