linux多进程通讯---通过共享磁盘文件

文章目录

1、举例

#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>

int main (void) 
{
  	char buf[64];
  	int i;

  	printf ("read process pid: %d\n", getpid());
  	int fd = open ("data.txt", O_RDONLY);
  	if (fd < 0) 
  	{
    	perror ("open");
    	return -1;
  	}
  	int len = 0;
	int last_len = 0;
  	while (1)
	{
  		if ((len = read(fd, buf, 64)) < 0) 
  		{
    		perror ("read");
    		close (fd);
    		return -2;
  		}
  		printf ("%s", buf);
  		lseek (fd, 0,SEEK_SET);
		sleep (5);
	}
	close (fd);
    return 0;
}
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>

int main(void) 
{
	printf ("write process pid: %d\n", getpid ());
 	char buf[64] = { 0 };
  	int n = 0;
  	while (1) 
  	{
    	if ((n = read (STDIN_FILENO, buf, 64)) > 0) 
		{
      		int fd = open ("data.txt", O_WRONLY|O_CREAT, 0664);
      		if (fd < 0) 
	  		{
        		perror ("open");
        		continue;
      		}   
	  	buf[n] = '\0';
      	write (fd, buf, n + 1); 
      	close (fd);
    	}   
  	}
  	return 0;
}

发布了349 篇原创文章 · 获赞 6 · 访问量 9606

猜你喜欢

转载自blog.csdn.net/qq_23929673/article/details/99539307