【发布时间】:2016-05-30 00:34:25
【问题描述】:
我正在使用管道进行 IPC 练习。协议如下:
- client(child) 从标准输入读取文件名
- 客户端通过管道向服务器发送文件名
- 服务器(父)从管道中读取文件名
- 服务器获取文件信息(stat sys call)
- 服务器通过管道向客户端发送文件信息。
- 客户端从管道读取文件信息并输出到标准输出
我在最后一步遇到问题,我不知道如何正确发送此信息。目前客户端的输出是垃圾。这是代码:
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <string.h>
#define BUFSIZE 1024
int main()
{
int fd1[2], fd2[2], pid, n;
char buf[BUFSIZE];
pipe(fd1);
pipe(fd2);
if ((pid = fork()) == 0)
{
close(fd1[0]);
close(fd2[1]);
read(STDIN_FILENO, buf, BUFSIZE); // 1. client(child) reads file name from stdin
int len = strlen(buf);
buf[len - 1] = '\0';
write(fd1[1], buf, len); // 2. client sends file name over pipe to server
while ((n = read(fd2[0], buf, BUFSIZE)) > 0)
{
write (STDOUT_FILENO, buf, n); // 6. client reads file info from pipe and outputs to stdout
}
}
else
{
struct stat st;
close(fd1[1]);
close(fd2[0]);
read(fd1[0], buf, BUFSIZE); // 3. server (parent) reads file name from pipe
stat(buf, &st); // 4. server obtains information about the file (stat sys call)
write(fd2[1], (void *)st.st_size, sizeof(st.st_size)); // 5. server file information over pipe to client.
write(fd2[1], (void *)st.st_atime, sizeof(st.st_atime));
}
return 0;
}
更新:
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <string.h>
#define BUFSIZE 1024
int main()
{
int fd1[2], fd2[2], pid;
size_t n;
char buf[BUFSIZE];
pipe(fd1);
pipe(fd2);
if ((pid = fork()) == 0)
{
close(fd1[0]);
close(fd2[1]);
n = read(STDIN_FILENO, buf, BUFSIZE - 1); // 1. client(child) reads file name from stdin
buf[n] = '\0';
write(fd1[1], buf, n); // 2. client sends file name over pipe to server
while ((n = read(fd2[0], buf, BUFSIZE)) > 0)
{
if ((write (STDOUT_FILENO, buf, n)) != n) // 6. client reads file info from pipe and outputs to stdout
{
perror("client: write error\n");
}
}
}
else
{
struct stat st;
close(fd1[1]);
close(fd2[0]);
read(fd1[0], buf, BUFSIZE); // 3. server (parent) reads file name from pipe
stat(buf, &st); // 4. server obtains information about the file (stat sys call)
if (write(fd2[1], (void *)st.st_size, sizeof(st.st_size)) != sizeof(st.st_size)) // 5. server sends file information over pipe to client
{
perror("server: write error\n");
}
if (write(fd2[1], (void *)st.st_atime, sizeof(st.st_atime)) != sizeof (st.st_atime))
{
perror("server: write error\n");
}
}
return 0;
}
【问题讨论】:
-
你需要
dupstdin。