2010-08-08 4 views
0
#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

이것은 내 첫 번째 사용자 계정입니다 ... – user414209

+0

코드가 약간 읽기 어려우므로 좀 더 자세히 추적하면 편리합니다. –

답변

0

int c, h_comp = 0, race_length = 0, o = 0, i = 0, Ti = 0; 포크() 데이터 세그먼트 후

도 갈래 것 및 변수는 해당되는 공유 의미 멈출 것이다 :

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

가 실행하는

void turtle_fun() 
{ 
while(h_comp!=1 /* ... */) 
{ 
    /* ... */ 
} 
} 

에 아무런 영향을 미치지 않는다을 다른 과정.

  • 은 구조체, 예를 들어,로 공유하는 데 필요한 모든 필드를 넣어 :

    는 포크() 에드 프로세스에 의해 공유 메모리의 조각을 얻으려면 struct the_struct,
  • 는 새로운 글로벌 변수를 추가 - 포인터를 구조체로,
  • 어떤 fork() 전에 main() 어딘가에 mmap(0, sizeof(struct the_struct), PROT_READ|PTOT_WRITE, MAP_SHARED|MAP_ANONYMOUS, -1, 0);를 사용하여 구조체를위한 메모리를 할당 할 수 있습니다.
  • 그런 식으로 생성 된 메모리는 fork() 후에 공유됩니다.