【操作系统原理】【实验5】管道通信实验

代码:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>

main()
{
	int 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");
		write(fd[1], buf, 50);
		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");
			write(fd[1], buf, 50);
			sleep(5);
			lockf(fd[1], 0, 0);
			exit(0);
		} else {
			wait(0);
			read(fd[0], buf, 50);
			printf("%s\n", buf);
			wait(0);
			read(fd[0], buf, 50);
			printf("%s\n", buf);
			exit(0);
		}
	}
}

上一篇:Linux系统编程学习笔记——文件操作


下一篇:fd一个简单快速的find命令替代方案