C语言:daemon socket连接
来源:优易学  2011-11-2 14:15:44   【优易学:中国教育考试门户网】   资料下载   IT书店

  学无止境,最近学习了daemon,socket连接的一些知识,写了二段代码.希望有人来点评,指出其中的错误,或需要改进的地点.在写的过程当中,遇到很多问题,不段的问人,在贴求助.查看C手册,查看网上教程才得以写出. 但C的许多基础知识我还是不懂.并不段的在学习. 由于工作繁忙,学习进度实在是小得可怜,发了很多C语言的基础.在那里我学到了许多知识. 如果打算学习C语言的大家一起吧..我好有个伴.嘿嘿....
  我的意图:读取/proc//net/dev的数据,在服务器端开启守护进程,当客户端通过socket 进行连接时,输出/proc/net/dev 的流量数据.(数据经过筛选)
  server.c
  #include <stdlib.h>
  #include <stdio.h>
  #include <errno.h>
  #include <string.h>
  #include <netdb.h>
  #include <sys/types.h>
  #include <netinet/in.h>
  #include <sys/socket.h>
  #include <syslog.h>
  #include <unistd.h>
  #include <netinet/in.h>
  #include <sys/socket.h>
  #include <arpa/inet.h>
  #include <errno.h>
  #include <sys/ipc.h>
  #include <sys/shm.h>
  /*建立精灵进程*/
  int daemon_init(void)
  { pid_t pid;
  if((pid = fork()) < 0) return(-1);
  else if(pid != 0) exit(0); /* parent exit */
  /* child continues */
  setsid(); /* become session leader */
  chdir("//tmp"); /* change working directory */
  umask(0); /* clear file mode creation mask */
  close(0); /* close stdin */
  close(1); /* close stdout */
  close(2); /* close stderr */
  return(0); }
  /*读取文件数据*/
  void myread(char *buff)
  {
  char buf[1024];
  FILE *fp;
  fp = fopen("/proc/net/dev", "r");
  if(!fp)
  {
  perror("fopen");
  exit(2);
  }
  fgets(buf, 1024, fp);
  fgets(buf, 1024, fp);
  fgets(buf, 1024, fp);
  fgets(buf, 1024, fp);
  fscanf(fp, "%s", buf); /*从第三行开始读*/
  snprintf(buff, 100, "%s", buf);
  fclose(fp);

[1] [2] [3] 下一页

责任编辑:小草

文章搜索:
 相关文章
热点资讯
资讯快报
热门课程培训