无名管道:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
int read_pipe(int fd)
{
int n;
char buf[1024];
while(1)
{
n = read(fd,buf,sizeof(buf) - 1);
buf[n] = '\0';
printf("Read %d bytes: %s.\n",n,buf);
if(strncmp(buf,"quit",4) == 0)
break;
}
return 0;
}
int write_pipe(int fd)
{
/*
char buf[] = "hello word";
sizeof(buf) : 11
strlen(buf) : 10
*/
char buf[1024];
while(1)
{
printf(">");
fgets(buf,sizeof(buf),stdin);
buf[strlen(buf) - 1] = '\0';
write(fd,buf,strlen(buf));
}
}
int main(int argc, const char *argv[])
{
pid_t pid;
int fd[2];
if(pipe(fd) < 0)
{
perror("Fail to pipe");
exit(EXIT_FAILURE);
}
if((pid = fork()) < 0)
{
perror("fail to fork");
exit(EXIT_FAILURE);
}
if(pid == 0)
{
close(fd[1]);
read_pipe(fd[0]);
}
if(pid > 0)
{
close(fd[0]);
write_pipe(fd[1]);
}
exit(EXIT_SUCCESS);
}
pipe 读写操作
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <fcntl.h>
#include <unistd.h>
int read_pipe(int r_fd,const char *filename)
{
int n;
int file_fd;
char buf[1024];
if((file_fd = open(filename,O_WRONLY | O_CREAT | O_TRUNC,0666)) < 0)
{
fprintf(stderr,"Fail to open %s : %s.\n",filename,strerror(errno));
exit(EXIT_FAILURE);
}
while(1)
{
n = read(r_fd,buf,sizeof(buf));
if(n == 0)
break;
//错误
//write(filename,buf,strlen(buf));
write(file_fd,buf,n);
}
close(file_fd);
close(r_fd);
return 0;
}
int write_pipe(int w_fd,const char *filename)
{
int n;
int file_fd;
char buf[1024];
if((file_fd = open(filename,O_RDONLY)) < 0)
{
fprintf(stderr,"Fail to open %s : %s.\n",filename,strerror(errno));
exit(EXIT_FAILURE);
}
while(1)
{
n = read(file_fd,buf,sizeof(buf));
if(n == 0)
break;
write(w_fd,buf,n);
}
close(w_fd);
close(file_fd);
return 0;
}
//./a.out src dest
int main(int argc, const char *argv[])
{
pid_t pid;
int pipe_fd[2];
if(argc < 3)
{
fprintf(stderr,"Usage : %s src dest.\n",argv[0]);
exit(EXIT_FAILURE);
}
if(pipe(pipe_fd) < 0)
{
perror("Fail to pipe");
exit(EXIT_FAILURE);
}
if((pid = fork()) < 0)
{
perror("Fail to fork");
exit(EXIT_FAILURE);
}
if(pid == 0)
{
close(pipe_fd[1]);
read_pipe(pipe_fd[0],argv[2]);
}
if(pid > 0)
{
close(pipe_fd[0]);
write_pipe(pipe_fd[1],argv[1]);
}
exit(EXIT_SUCCESS);
}

1212

被折叠的 条评论
为什么被折叠?



