管道

#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;	
}

  

转载于:https://www.cnblogs.com/mjn1/p/10753020.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值