代码:
#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);
}
}
}