Ich mache eine Übung auf IPC mit Rohren. Das Protokoll ist wie folgt:Interprozesskommunikation in C
- Client (Kind) liest Dateinamen von stdin
- Client sendet Dateinamen über Rohr Server
- Server (Eltern) liest Dateinamen aus Rohr
- Server erhält Informationen über die Datei (stat sys call)
- Server sendet Dateiinformationen über Pipe an Client.
- Client liest aus Rohr und Ausgänge Datei info
Ich bin Probleme mit den letzten Schritten stdout ich weiß nicht, wie richtig diese Informationen zu senden. Im Moment ist die Ausgabe vom Client Müll. Hier ist der 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, 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;
}
Update:
#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;
}
Sie müssen 'dup' stdin. – Dan