成功返回0,错误返回-1
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> int main(int argc, char **argv) { int fd[2]; char buf[1024] = "every day is good day"; int ret=0; if(pipe(fd) < 0) {//创建无名管道 perror("piple"); exit(1); } pid_t pid; if((pid = fork()) == 0) { //创建一子进程 ret = write(fd[1], buf, strlen(buf)); if (ret < 0) { perror("write"); exit(1); } printf("write %d bytes [%s]\n", ret, buf); } else if(pid > 0) { sleep(1); ret = read(fd[0], buf, sizeof(buf)); printf("%d bytes read from the pipe is [%s]\n", ret, buf); if (ret < 0) { perror("read"); exit(1); } } close(fd[0]); close(fd[1]); return 0; } ---------------------------------------- /pipe# ./test write 21 bytes [every day is good day] 21 bytes read from the pipe is [every day is good day]
#include <stdio.h> #include <stdlib.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> #include <string.h> #define FIFO "/tmp/myfifo" //有名管道文件名 int main(int argc, char **argv) { int fd; int ret = 0; umask(0); char buf[]="hello world"; char buf1[1024]; if (mkfifo(FIFO, 07777) < 0) { perror("mkfifo"); exit(1); } pid_t pid; if ((pid = fork()) == 0){ fd = open(FIFO, O_WRONLY); ret = write(fd, buf, strlen(buf)); printf("write %d bytes, [%s]\n", ret, buf); close(fd); } else if(pid > 0) { sleep(1); fd = open(FIFO, O_RDONLY); ret = read(fd, buf1, sizeof(buf1)); printf("read %d bytes, [%s]\n", ret, buf); close(fd); } } ----------------------------------------------------- /myfifo# ./test write 11 bytes, [hello world] read 11 bytes, [hello world] 第二次运行 myfifo# ./test mkfifo: File exists 因为管道也经创建了 myfifo# ls /tmp/myfifo /tmp/myfifo