//note: the type of fork() is pid_t ,not int // the child pid is equal fork() ,while fork() is great than (pid_t)0 // this example include socketpair() fork() strftime() localtime() #include<string.h> #include<stdio.h> #include<unistd.h> #include<sys/types.h> #include<sys/socket.h> #include<stdlib.h> #include<time.h> #include<sys/wait.h> int main(int argc, char *argv[]) { int r,s[2]; pid_t chpid; char buf[30],buf1[30]="%A %d-%b-%Y %l:%M %p",buf2[30]; time_t t; r=socketpair(AF_LOCAL,SOCK_STREAM,0,s); if(r<0) { perror("socketpair error"); exit(1); } chpid=fork(); if(chpid<((pid_t)0)) { perror("fork error"); exit(1); } else if(chpid==0) { close(s[1]); r=write(s[0],buf1,30); if(r<0) { perror("write error"); exit(1); } printf("client write complete!/n"); r=read(s[0],buf,30); if(r<0) { perror("read error"); exit(1); } buf[r]=0; printf("Time is %s/n",buf); close(s[0]); } else { close(s[0]); r=read(s[1],buf,30); if(r<0) { perror("read error"); exit(1); } printf("the parent pid is %d/n",getppid()); printf("the childpid pid is %d/n",chpid); buf[r]=0; time(&t); strftime(buf2,30,buf,localtime(&t)); r=write(s[1],buf2,strlen(buf2)); if(r<0) { perror("write error"); exit(1); } close(s[1]); waitpid(chpid,NULL,0); } return 0; }