-1
//// first loop it is conduct correctly but, second loop buff or path have strange value
//// please, why can't this code conduct correctly?????
////
#define MAXLINE 4096
#define STDOUT_FILENO 1
void client(int, int), server(int, int);
int main(int argc, char *argv[])
{
char str[MAXLINE];
int maxByte;
int pipe1[2], pipe2[2];
pid_t childpid;
while(1){
pipe(pipe1);
pipe(pipe2);
if((childpid=fork())==0) /* child */ // fork() if child process return 0
{ // else if parent process return child_pid
close(pipe1[0]); // pipe[0] read end of the pipe
close(pipe2[1]); // pipe[1] write end of the pipe
server(pipe2[0], pipe1[1]);
exit(0);
}
/* parent */
close(pipe1[1]);
close(pipe2[0]);
client(pipe1[0], pipe2[1]);
waitpid(childpid, NULL, 0); /* wait for child to terminate */
}
}
void client(int readfd, int writefd)
{
size_t len;
size_t n;
char buff[MAXLINE];
char type[MAXLINE];
char option[MAXLINE];
printf("<client>\n");
/* read pathname */
printf("path: ");
fgets(buff, MAXLINE, stdin);
printf("Read or Write? (r/w)");
fgets(type, MAXLINE, stdin);
printf("Enter correct option(r: byte/w: text)");
fgets(option, MAXLINE, stdin);
strcat(buff, type);
strcat(buff, option);
len = strlen(buff);
if(buff[len-1] == '\n')
len--;
write(writefd, buff, len);
while((n=read(readfd, buff, MAXLINE))>0) {
write(STDOUT_FILENO, buff, n);
}
}
void server(int readfd, int writefd) {
int fd;
int i = 0;
int j = 0;
int tk = 0;
int ok = 0;
int pk = 0;
size_t n;
char buff[MAXLINE+1];
char path[MAXLINE];
char type[MAXLINE];
char option[MAXLINE];
if((n=read(readfd, buff, MAXLINE))==0)
{
printf("end-of-file");
exit(0);
}
buff[n]='\0';
while(buff[j] != '\n') {
path[pk] = buff[j];
j++;
pk++;
}
j++;
while(buff[j] != '\n') {
type[tk] = buff[j];
j++;
tk++;
}
j++;
while(buff[j] != '\0') {
option[ok] = buff[j];
j++;
ok++;
}
printf("Path: %s\n", path);
printf("Type: %s\n", type);
printf("Option: %s\n", option);
if(type[0] == 'r') {
if((fd=open(path,O_RDONLY))<0)
{
snprintf(buff+n, sizeof(buff)-n, ": can't open, %s\n", strerror(errno));
n=strlen(buff);
write(writefd, buff, n);
} else {
while((n=read(fd, buff, MAXLINE))>0) {
write(writefd, buff, atoi(option));
}
close(fd);
}
} else if(type[0] == 'w') {
fd=open(path, O_WRONLY|O_CREAT, S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH);
write(fd, option, strlen(option));
close(fd);
}
}