mkfifo myfifo 创建一个管道名(手动创建管道结点)
也可以mam 3 mkfifo查看mkfifo函数
下面是手动创建管道结点,运行两个.c文件,实现进程通信
mkfifo myfifo
gcc fifo_w.c -o fifo_w
gcc fifo_r.c -o fifo_r
./fifo_w myfifo
./fifo_r myfifo
//fifo_r.c
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <string.h>
void sys_err(char *str, int exitno)
{
perror(str);
exit(exitno);
}
int main(int argc, char *argv[])
{
int fd, len;
char buf[1024];
if(argc<2){
printf("./a.out fifoname\n");
exit(1);
}
fd = open(argv[1],O_RDONLY);
if(fd<0)
{
sys_err("open", 1);
}
len = read(fd, buf, sizeof(buf));
write(STDOUT_FILENO, buf, len);
close(fd);
return 0;
}
//fifo_w.c
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <string.h>
void sys_err(char *str, int exitno)
{
perror(str);
exit(exitno);
}
int main(int argc, char *argv[])
{
int fd;
char buf[1024] = "hello world\n";
if(argc<2){
printf("./a.out fifoname\n");
exit(1);
}
fd = open(argv[1],O_WRONLY);
if(fd<0)
{
sys_err("open", 1);
}
write(fd, buf, strlen(buf));
close(fd);
return 0;
}