友链
#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[])
{
/*
#include <unistd.h>
On Alpha, IA-64, MIPS, SuperH, and SPARC/SPARC64; see NOTES
struct fd_pair {
long fd[2];
};
struct fd_pair pipe();
On all other architectures
int pipe(int pipefd[2]);
pipefd数组,0对应读,1对应写
返回值为0代表成功,-1代表失败
匿名管道只能用于具有血缘关系的进程间通信
管道默认是阻塞的,如果读不到数据,就会阻塞,直到管道中有数据
#define _GNU_SOURCE See feature_test_macros(7)
*/
// 子进程发送数据给父进程,父进程读取到数据之后输出
pid_t pid;
//在fork之前,先创建匿名管道
int pidfd[2];
int ret = pipe(pidfd);
if (ret == -1)
{
perror("pipe");
exit(0);
}
pid = fork();
if (pid > 0)
{ //从管道读取数据
printf("PARENT pid: %d\n", getpid());
char buf[1024] = {0};
while (1)
{
int len = read(pidfd[0], buf, sizeof(buf));
printf("PARENT receive :%s, pid: %d\n", buf, getpid());
char *str = "wo shi ni die";
write(pidfd[1], str, strlen(str));
sleep(1);
}
}
else if (pid == 0)
{
// sleep(3);
printf("CHILD pid: %d\n", getpid());
char buf[1024] = {0};
//往管道写数据
while (1)
{
char *str = "cao ni ma";
write(pidfd[1], str, strlen(str));
sleep(1);
int len = read(pidfd[0], buf, sizeof(buf));
printf("CHILD receive :%s, pid: %d\n", buf, getpid());
}
}
// printf("PARENT receive :%s, pid: %d\n", buf, getpid());}
return 0;
}