管道

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
int main()
{
	int r, p1, p2, fd[2];
	char buf[50], s[50];
	pipe(fd);	// 创建管道
	while((p1 = fork()) == -1);
	if(p1 == 0)
	{
		lockf(fd[1], 1, 0);
		sprintf(buf, "child process p1 is sending message!\n");
		printf("child process p1!\n");
		write(fd[1], buf, 50);	// 把buf中的字符写入管道
		sleep(5);
		lockf(fd[1], 0, 0);
		exit(0);
	}
	else
	{
		while((p2 = fork()) == -1);
		if(p2 == 0)
		{
			lockf(fd[1], 1, 0);
			sprintf(buf, "child process p2 is sending message!\n");
			printf("child process p2!\n");
			write(fd[1], buf, 50);	// 把buf中的字符写入管道
			sleep(5);
			lockf(fd[1], 0, 0);
			exit(0);
		}
		wait(0);
		if((r = read(fd[0], s, 50) == -1))
		{
			printf("can't read pipe\n");
		}
		else
		{
			printf("%s\n", s);
		}
		wait(0);
		if((r = read(fd[0], s, 50) == -1))
		{
			printf("can't read pipe\n");
		}
		else
		{
			printf("%s\n", s);
		}
		exit(0);
	}
	return 0;
}

  利用系统调用lockf(fd,mode,size),对指定文件的指定区域(由size指示)进行加锁或解锁,以实现进程同步或互斥。其中,fd是文字描述字;mode是锁定方式,=1表示加锁,=0表示解锁;size是指定文件的指定区域,用0表示从当前位置到文件尾

#include <sys/wait.h>
#include <sys/types.h>
#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
int main()
{
	int x, fd[2];
	char buf[30], s[30];
	pipe(fd);
	while((x = fork()) == -1);
	if(x == 0)
	{
		sprintf(buf, "this is an example\n");
		write(fd[1], buf, 30);
		exit(0);
	}
	else
	{
		wait(0);
		read(fd[0], s, 30);
		printf("%s", s);
	}
	return 0;	
}

  

posted @ 2019-04-22 21:07  青衫客36  阅读(147)  评论(0编辑  收藏  举报