c - h 和 t 只打印了 1 次...为什么呢?

标签 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);
 }

} 

最佳答案

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

在 fork() 之后,数据段也会被 fork ,并且变量将停止共享,这意味着:

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

不会有任何影响

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

在不同的进程中运行。

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

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

关于c - h 和 t 只打印了 1 次...为什么呢?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3433448/

相关文章:

c - 服务器/客户端通过管道进行通信

c - 搜索 lzw 编码的文件

c - 矩阵相乘

c - 为什么数组中的点头被认为是 'nod' 而不是 'struct nod' ?

c - 流浪 "\150"在程序中,在交换函数中

c - 为什么是 1.2 * 30 = 35?

c - 开关盒内循环内的开关盒

c - fork 进程,信号量,为什么这个输出?

c - 分配字符串时指针存储什么地址?

无法使用 C 中的 visual studio 从双向链表中删除