#include <unistd.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/stat.h>
#include <fcntl.h>
#define MAXLEN 100
void client(int readfd, int writefd)
{
size_t len;
ssize_t n;
char buf[MAXLEN];
fgets(buf, MAXLEN, stdin);
len = strlen(buf);
if(buf[len-1] == '\n')
len--;
write(writefd, buf, len);
while((n = read(readfd, buf, MAXLEN)) > 0)
write(STDOUT_FILENO, buf, n);
}
void server(int readfd, int writefd)
{
int fd;
ssize_t n;
char buf[MAXLEN+1];
if((n = read(readfd, buf, MAXLEN)) == 0)
{
perror("read error in server");
exit(1);
}
buf[n] = '\0';
if((fd = open(buf, O_RDONLY)) < 0)
{
snprintf(buf+n, sizeof(buf) - n, ": cannot open %s\n", strerror(errno));
n = strlen(buf);
write(writefd, buf, n);
}
else
{
while((n = read(fd, buf, MAXLEN)) > 0)
write(writefd, buf, n);
close(fd);
}
}
int main(int argc, char **argv)
{
int pipe1[2], pipe2[2];
pid_t childpid;
pipe(pipe1);
pipe(pipe2);
if((childpid = fork()) == 0)
{
close(pipe1[1]);
close(pipe2[0]);
server(pipe1[0], pipe2[1]);
exit(0);
}
close(pipe1[0]);
close(pipe2[1]);
client(pipe2[0], pipe1[1]);
waitpid(childpid, NULL, 0);
exit(0);
}
pipe练习(暂存)
最新推荐文章于 2024-07-08 20:32:20 发布