#include <unistd.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <string.h>
#include <sys/wait.h>
int main(int argc, char *argv[])
{
pid_t pid;
int pipfd[2];
int ret = pipe(pipfd);
if (ret == -1)
{
perror("pipe");
exit(0);
}
pid = fork();
if (pid > 0)
{
printf("PARENT pid: %d\n", getpid());
close(pipfd[1]);
char buf[1024] = {0};
int flags = fcntl(pipfd[0], F_GETFL);
flags |= O_NONBLOCK;
fcntl(pipfd[0], F_SETFL, flags);
while (1)
{
int len = read(pipfd[0], buf, sizeof(buf));
printf("parent read len : %d\n", len);
if (len > 0)
{
printf("parent receives message: %s\n", buf);
}
memset(buf, 0, 1024);
sleep(1);
}
wait(NULL);
}
else if (pid == 0)
{
close(pipfd[0]);
char *str = "cao ni ma";
while (1)
{
printf("child starts writing\n");
int len = write(pipfd[1], str, strlen(str));
sleep(5);
}
}
else
{
perror("for");
exit(0);
}
return 0;
}