【操作系统原理】【实验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);
		}
	}
}

posted @ 2021-11-29 13:56  那个白熊  阅读(136)  评论(0编辑  收藏  举报