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

linux c进程互斥
如何实现,在文件读一行然后创建一个进程来处理,不过每次都是等前面的处理在处理,可以提前读入,并且没处理的进程可以阻塞。



int main()
{
  FILE *srcfp , *destfp ;
  int num = 0 ; ///add up numbers of rows
  char buffer[ MAXSIZE] ;
  pid_t pid ;
  // pthread_mutex_t mutex ;

  void sort(char *buf) ;

  if((srcfp = fopen("../linux/srcfile" , "r")) == NULL)
  {
  printf("open srcfile error!\n") ;
  exit(1) ;
  }

  if((destfp = fopen("../linux/destfile" , "w+")) == NULL)
  {
  printf("open or create destfile error!\n") ;
  exit(1) ;
  }

  // pthread_mutex_init(&mutex , NULL) ;

  while(fgets(buffer , MAXSIZE , srcfp ) != 0)
  {
  //现在想对每次读入的数据创建一个线程(进程)来处理由子进程来处理
  pid = fork() ;
  if(pid > 0 )
  {
  //父进程,不处理
  sleep(1) ;
  /* if (waitpid(pid, NULL, 0) < 0)
  {
  puts("waitpid error");
  }
  //continue ;*/
  }

  if(pid == 0)
  {
  //sleep(1) ;
  printf("%d" , ++num) ;
  printf(" %s\n" ,buffer) ;
  //pthread_mutex_lock(&mutex) ;
  fputs(buffer , destfp) ;
  operation(buffer) ;
  // pthread_mutex_unlock(&mutex) ;
/*
  if(flag == 0) //阻塞
  {
  wait(NULL) ;
  }
*/
  }

  }
  fclose (destfp) ;
  fclose(srcfp) ;

  return 0 ;
}


------解决方案--------------------
lz 这不都写出来了吗

子进程处理完成之后,是不是需要exit ?
------解决方案--------------------
if(pid == 0)时候,让子进程处理一行后exit退出