#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <string.h>
#include <sys/wait.h>
#include <sys/stat.h>
#include <fcntl.h>
#define DEBUG //DEBUG时需要打开
#ifndef DEBUG
#define dbg(format, ...) while(0)
#else
#define dbg(format, ...) printf(format, ##__VA_ARGS__)
#endif
#if 0
// IPC 管道 pipe
int main(void)
{
int flag = -1;
pid_t pid = -1;
int pipefd[2] = {0};
flag = pipe(pipefd);
if(-1 == flag)
{
perror("pipe error");
exit(-1);
}
pid = fork();
if(0 > pid)
{
perror("fork error");
}
if(0 == pid)//子进程
{
char buf[20] = {'0'};
close(pipefd[0]);//关闭读端
while (1)
{
printf("子进程:请输入!\n");
scanf("%s", buf);
getchar();
write(pipefd[1], buf, sizeof(buf));
memset(buf, 0, sizeof(buf));
}
}
if(0 < pid)//父进程
{
char buf[20] = {'0'};
close(pipefd[1]);//关闭写端
while (1)
{
read(pipefd[0], buf, sizeof(buf));
printf("父进程:%s\n",buf);
memset(buf, 0, sizeof(buf));
}
//回收子进程
wait(NULL);
}
return 0;
}
#endif
#if 0
// IPC有名管道fifo,实际可以在无关系的两个进程通讯
#define FIFO_PATH "./myfifo"
int main(void)//输入"exit"退出
{
pid_t pid = -1;
pid = fork();
if(0 > pid)
{
perror("fork error");
}
if(0 < pid)//父进程
{
int fifo_fd = -1;
char buf[20] = {'0'};
while (-1 == access(FIFO_PATH, F_OK))
{
// 创建管道文件
if(!mkfifo(FIFO_PATH, 0777))
{
perror("mkfifo error");
exit(-1);
}
}
fifo_fd = open(FIFO_PATH, O_WRONLY);
while (1)
{
printf("父进程:请输入\n");
scanf("%s",buf);
getchar();//消除回车换行
write(fifo_fd, buf, sizeof(buf));
if(!strncmp("exit", buf, 4))
{
exit(-1);
}
memset(buf, 0, sizeof(buf));
}
}
if(0 == pid)//子进程
{
int fifo_fd = -1;
char buf[20] = {'0'};
sleep(1);//让父进程先创建文件
fifo_fd = open(FIFO_PATH, O_RDONLY);
while (1)
{
read(fifo_fd, buf, sizeof(buf));
printf("子进程输出:%s\n",buf);
if(!strncmp("exit", buf, 4))
{
exit(-1);
}
memset(buf, 0, sizeof(buf));
}
}
return 0;
}
#endif
9.c练习-管道&有名管道
最新推荐文章于 2021-12-23 13:18:10 发布