

#include
int pipe(int pipefd[2]);
成功时返回0,失败时返回EOF
pfd 包含两个元素的整形数组,用来保存文件描述符
pfd[0]用于读管道;pfd[1]用于写管道
读管道
写管道
子进程往无名管道写字符串,父进程读无名管道字符串并打印。
#include
#include
#include
int main(int argc, const char *argv[])
{
int pfd[2];
int ret;
pid_t pid;
char buf[100] = {0};
ret = pipe(pfd);
if (ret < 0) {
perror("pipe");
return -1;
}
printf("pfd[0] = %d pfd[1] = %d\n", pfd[0], pfd[1]);
pid = fork();
if (pid < 0) {
perror("fork");
return -1;
} else if (0 == pid) { //子进程
close(pfd[0]);
while (1) {
strcpy(buf, "hello world");
write(pfd[1], buf, strlen(buf));
sleep(1);
}
} else { //父进程
close(pfd[1]);
while (1) {
memset(buf, 0, 100);
ret = read(pfd[0], buf, 100);
if (ret > 0) {
printf("read = %s\n", buf);
}
}
}
return 0;
}
2个子进程往无名管道写字符串,父进程读无名管道字符串并打印。
#include
#include
#include
int main(int argc, const char *argv[])
{
int pfd[2];
int ret;
pid_t pid;
char buf[100] = {0};
int i = 0;
ret = pipe(pfd);
if (ret < 0) {
perror("pipe");
return -1;
}
for (i = 0; i < 2; i++) {
ret = fork();
if (ret < 0) {
perror("fork");
return -1;
} else if (0 == ret) { //子进程
break;
} else { //父进程
}
}
if (0 == i) {
close(pfd[0]);
while (1) {
strcpy(buf, "this is child process 1");
write(pfd[1], buf, strlen(buf));
sleep(1);
}
}
if (1 == i) {
close(pfd[0]);
while (1) {
strcpy(buf, "this is child process 2, memset test");
write(pfd[1], buf, strlen(buf));
sleep(2);
}
}
if (2 == i) {
close(pfd[1]);
while (1) {
memset(buf, 0, 100);
ret = read(pfd[0], buf, 100);
if (ret > 0) {
printf("read = %s\n", buf);
}
}
}
return 0;
}
#include
#include
int mkfifo(const char *path, mode_t mode);
成功时返回0,失败时返回EOF
path 创建的管道文件路径
mode 管道文件的权限,如0666
open(const char *path, O_RDONLY);//1
open(const char *path, O_RDONLY | O_NONBLOCK);//2
open(const char *path, O_WRONLY);//3
open(const char *path, O_WRONLY | O_NONBLOCK);//4
#include
#include
#include
#include
#include
#include
int main(int argc, const char *argv[])
{
int ret;
int fd;
char buf[100] = {0};
ret = mkfifo("/home/linux/linux_study/02fifo/myfifo", 0666); //0666(4:r 2:w 1:x)
if (ret < 0) {
perror("mkfifo");
}
fd = open("/home/linux/linux_study/02fifo/myfifo", O_WRONLY);
if (fd < 0) {
perror("open");
return -1;
}
while (1) {
fgets(buf, 100, stdin);
write(fd, buf, strlen(buf));
}
return 0;
}
#include
#include
#include
#include
#include
#include
#include
int main(int argc, const char *argv[])
{
int ret;
int fd;
char buf[100] = {0};
/*
ret = mkfifo("/home/linux/linux_study/02fifo/myfifo", 0666); //0666(4:r 2:w 1:x)
if (ret < 0) {
perror("mkfifo");
}
*/
fd = open("/home/linux/linux_study/02fifo/myfifo", O_RDONLY);
if (fd < 0) {
perror("open");
return -1;
}
while (1) {
memset(buf, 0, 100);
ret = read(fd, buf, 100);
if (ret > 0) {
printf("read fifo = %s\n", buf);
} else if (0 == ret) {
close(fd);
exit(0);
}
}
return 0;
}