I want to implemment ipc as is described in the comments. I'am having trouble with the stat sys call. After receiving file name in server if i write
Code:
printf("%ld\n", st.st_size);
i get 1 when the file has 5M... Then it gives error in the perror when it tries to write. What it wrong?
server: write error
: Bad address
Code:
#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];
struct stat st;
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
{
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;
}