/* 子进程为客户方,父进程为服务器方。当客户请求通过socket传送给服务器方时,服务器会将当前的系统时间返回给客户
该程序参考自《实战linux socket 编程 》 Warren W.Gay
*/
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<errno.h>
#include<time.h>
#include<string.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<sys/wait.h>
int main(int argc,char **argv)
{
int z;
int s[2];
char *msgp;
int mlen;
char buf[80];
pid_t chpid;
z=socketpair(AF_LOCAL,SOCK_STREAM,0,s);
if(z==-1)
{
fprintf(stderr,"%s:socketpair(AF_LOCAL,SOCK_STREAM,0)\n",strerror(errno));
exit(1);
}
if((chpid=fork())==(pid_t)-1)
{
fprintf(stderr,"%s:fork(2)\n",strerror(errno));
exit(1);
}
else if(chpid==0)
{
/*子进程,客户端*/
char rxbuf[80];
printf("Parent PID is %ld",(long)getppid());
close(s[0]);
s[0]=-1;
msgp="%A %d-%b-%Y %1:%M %p";
mlen=strlen(msgp);
printf("Child sending request '%s'\n",msgp);
/*向服务器写入请求*/
z=write(s[1],msgp,mlen);
/*if(shutdown(s[1],SHUT_WR)==-1)
{
fprintf(stderr,"%s:shutdown(2)\n",strerror(errno));
exit(1);
} */
z=read(s[1],rxbuf,sizeof rxbuf);
if(z<0)
{
fprintf(stderr,"%s:read(2)\n",strerror(errno));
exit(1);
}
rxbuf[z]=0;
printf("Server returned '%s'\n",rxbuf);
fflush(stdout);
close(s[1]);
}
else
{
int status;
char txbuf[80];
time_t td;
printf("child PID is %ld",(long)chpid);
fflush(stdout);
close(s[1]);
s[1]=-1;
z=read(s[0],buf,sizeof buf);
if(z<0)
{
fprintf(stderr,"%s:read(2)\n",strerror(errno));
exit(1);
}
buf[z]=0;
time(&td);
strftime(txbuf,sizeof txbuf,buf,localtime(&td));
z=write(s[0],txbuf,strlen(txbuf));
if(z<0)
{
fprintf(stderr,"%s:write(2)\n",strerror(errno));
exit(1);
}
close(s[0]);
waitpid(chpid,&status,0);
}
return 0;
}