linux进程通讯-纯文本文件1

一)概述:

  1)纯文本文件是一种原始但却高效的进程间通信方式,当两个不同步执行的进程必须要进行通信时,文件或许是进行IPC的唯一选择.

  2)一般来讲通过纯文本文件在多个进程之间进行过渡,传输数据,而gcc编译程序就是一个例子,它会生成中间文件,最后再将其删除.

  3)当两个进程使用文件进行通信时,无法保证当一个进程在读的时候,另一个进程没有去写,下面的例子用于说明这个问题.

  二)文本文件的IPC和lockf函数

  源程序1如下:

  #include <stdio.h>

  #include <string.h>

  #include <stdlib.h>

  #include <unistd.h>

  #include <sched.h>

  #include <sys/wait.h>

  const char *filename = "messagebuf.dat";

  void error_out(const char *msg)

  {

  perror(msg);

  exit(EXIT_FAILURE);

  }

  void child(void)

  {

  FILE *fp = fopen(filename, "r");

  if (fp == NULL)

  error_out("child:fopen");

  char buf[32];

  fread(buf, sizeof(buf), 1, fp);

  printf("child read: %s\n", buf);

  fclose(fp);

  }

  void parent(void)

  {

  FILE *fp = fopen(filename, "w");

  if (fp == NULL)

  error_out("parent:fopen");

  fprintf(fp, "Hello world");

  fclose(fp);

  }

  int main (int argc, char *argvp[])

  {

  pid_t pid = fork();

  if (pid == 0){

  child();

  }

  else{

  parent();

  int status = 0;

  int r = wait(&status);

  if (r == -1)

  error_out("parent:wait");

  printf("child status=%d\n", WEXITSTATUS(status));

  unlink(filename);

  }

  exit(0);

  }

  gcc file-ipc-naive.c -o file-ipc-naive

  当运行时返回下面的错误信息

  ./file-ipc-naive

  child:fopen: No such file or directory

  child status=1

  我们来分析一下上面的程序,程序运行后即执行了fork,此时派生了子进程,执行了child();而父进程执行了parent();

  子进程通过fopen(filename, "r")试图打开messagebuf.dat文件,而此时如果父进程没有执行到fopen(filename, "w"),这时程序就会报上面的错误.

  而如果我们通过strace运行file-ipc-navie这个程序,返回的结果也许会不同,如下:

  strace -o strace.out -f ./file-ipc-naive

  child read: Hello world;

  child status=0

  原因在于用strace监视程序运行时,有充足的时间让程序可以输出正确的结果,但不是每次都能得到正确的输出.

  为解决这个问题,我们可以用lockf函数对文件进行锁定控制.

你可能感兴趣的:(linux,职场,休闲)