linux下的示例程序

#if 0
/*
 * 1. 遍历目录-1
 */
#include <stdio.h>
#include <dirent.h>
#include <string.h>
#include <unistd.h>

void show_directory(char* path)
{
    DIR *dir;
    struct dirent*entry;
    static int count=0;
    int i=0;
    int j=0;
    if(NULL==(dir=opendir(path)))
        printf("error opening dir\n");
    else {
        chdir(path);
//        system("pwd");
        count+=1;
        while(entry=readdir(dir))
        {
//            if(strcmp(entry->d_name,".")==0||
//                    strcmp(entry->d_name,"..")==0)
            if((entry->d_name)[0]=='.')
                continue;
            i=0;
            j=0;
            switch(entry->d_type){
                case DT_DIR:
                    while(i++<count)
                        printf("+");
                    printf("\e[32;44m%s\e[0m\n",entry->d_name );
                    show_directory(entry->d_name);
                    break;
                case DT_REG:
                    while(j++<count+4)
                        printf("-");
                    printf("\e[30;41m%s\e[0m\n",entry->d_name );
                    break;
                default:
                    printf("%s\n",entry->d_name );
                    break;
            }
        }
        count-=1;
        chdir("..");
        closedir(dir);
    }
}
int main(int argc,char**argv)
{
    if(argc<2)
    {
        printf("Not enough arguments!\n");
        return -1;
    }
    show_directory(argv[1]);
    return 0;
}
#endif
#if 0
/*
 * 遍历目录-2
 */
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <dirent.h>
#define MAX_PATH 1024
void dirwalk(char *dir,void(*fcn)(char*))
{
    char name[MAX_PATH];
    struct dirent *dp;
    DIR *dfd;
    if((dfd=opendir(dir))==NULL) {
        fprintf(stderr,"dirwalk:can't open %s\n",dir);
        return ;
    }
    while((dp=readdir(dfd))!=NULL){
        if(strcmp(dp->d_name,".")==0||
                strcmp(dp->d_name,"..")==0)
            continue;
        if(strlen(dir)+strlen(dp->d_name)+2>sizeof(name))
            fprintf(stderr,"dirwalk:name %s/%s too long\n",dir,dp->d_name);
        else{
            sprintf(name,"%s/%s",dir,dp->d_name);
            printf("%s\n",name);
            fcn(name);
        }
    }
    closedir(dfd);
}
int main(int argc,char**argv)
{
    char *dir;
    if(argc<2){
        fprintf(stderr,"Usage:dirwalk <dir>\n");
        return 1;
    }
    dir=argv[1];
    dirwalk(dir,dirwalk);
}

#endif
#if 0
/*
 * 遍历目录-3
 */
#include <unistd.h>
#include <stdio.h>
#include <dirent.h>
#include <string.h>
#include <sys/stat.h>

void printdir(char *dir, int depth)
{
    DIR *dp;
    struct dirent *entry;
    struct stat statbuf;

if((dp = opendir(dir)) == NULL) {
        fprintf(stderr,"cannot open directory: %s\n", dir);
        return;
    }
    chdir(dir);
    while((entry = readdir(dp)) != NULL) {
        lstat(entry->d_name,&statbuf);
        if(S_ISDIR(statbuf.st_mode)) {
            /* Found a directory, but ignore . and .. */
            if(strcmp(".",entry->d_name) == 0 || 
                strcmp("..",entry->d_name) == 0)
                continue;
            printf("%*s%s/\n",depth,"",entry->d_name);
            /* Recurse at a new indent level */
            printdir(entry->d_name,depth+4);
        }
        else printf("%*s%s\n",depth,"",entry->d_name);
    }
    chdir("..");
    closedir(dp);
}

int main(int argc, char* argv[])
{
    char *topdir, pwd[2]=".";
    if (argc != 2)
        topdir=pwd;
    else
        topdir=argv[1];

printf("Directory scan of %s:\n",topdir);
    printdir(topdir,0);
    printf("------done-------\n");

return (0);
}

#endif
#if 0
/*
 * 2. 利用管道进行读写
 */
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
void writer(const char *message,int count,FILE* stream)
{
    for(;count>0;--count)
    {
        fprintf(stream,"%s\n",message);
        fflush(stream);
        sleep(1);
    }
}
void reader(FILE*stream)
{
    char buffer[1024];
    while(!feof(stream)&&!ferror(stream)
            &&fgets(buffer,sizeof(buffer),stream)!=NULL)
    {
        fputs(buffer,stdout);
    }
}
int main()
{
    int fds[2];
    pid_t pid;
    pipe(fds);
    pid=fork();
    if(pid==(pid_t)0){
        FILE *stream;
        close(fds[1]);
        stream=fdopen(fds[0],"r");
        reader(stream);
        close(fds[0]);
    }
    else{
        FILE *stream;
        close(fds[0]);
        stream=fdopen(fds[1],"w");
        writer("Hello,world.",10,stream);
        close(fds[1]);
    }
}

#endif
#if 0
/*
 * 3. 利用stat来获得系统文件的相关信息
 */
#include <unistd.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <fcntl.h>
#include <time.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
int main(int argc,char**argv)
{
    struct stat buf;
    mode_t mode;
    char type[80];
    int fd;
    if(argc!=2){
        puts("Usage:mstat {file}");
        exit(EXIT_FAILURE);
    }
    if((fd=open(argv[1],O_RDONLY))<0){
        perror("open");
        exit(EXIT_FAILURE);
    }
    if((fstat(fd,&buf))<0){
        perror("open");
        exit(EXIT_FAILURE);
    }
    mode=buf.st_mode;
    printf("    FILE:%s\n",argv[1]);
    printf("    INODE:%ld\n",buf.st_ino);
    printf("    DEVICE:%d,%d\n",major(buf.st_dev),
            minor(buf.st_dev));
    printf("    MODE:%#o\n",mode&~(S_IFMT));
    printf("    LINKS:%d\n",buf.st_nlink);
    printf("    UID:%d\n",buf.st_uid);
    printf("    GID:%d\n",buf.st_gid);
    if(S_ISLNK(mode))
        strcpy(type,"Symbolic line");
    else if(S_ISREG(mode))
        strcpy(type,"Regular file");
    else if(S_ISDIR(mode))
        strcpy(type,"Directory");
    else if(S_ISCHR(mode))
        strcpy(type,"Character device");
    else if(S_ISBLK(mode))
        strcpy(type,"Block device");
    else if(S_ISFIFO(mode))
        strcpy(type,"FIFO");
    else if(S_ISSOCK(mode))
        strcpy(type,"Socket");
    else
        strcpy(type,"Unknown type");
    printf("    TYPE:%s\n",type);
    printf("    SIZE:%ld\n",buf.st_size);
    printf("BLK SIZE:%ld\n",buf.st_blksize);
    printf(" BLOCKS:%d\n",(int)buf.st_blocks);
    printf("ACCESSED:%s",ctime(&buf.st_atime));
    printf("MODIFIED:%s",ctime(&buf.st_mtime));
    printf(" CHANGED:%s",ctime(&buf.st_ctime));
    if(close(fd)<0){
        perror("close");
        exit(EXIT_FAILURE);
    }
    exit(EXIT_SUCCESS);

}

#endif
#if 0
/*
 * 4. 利用socket进行通信
 * server端程序:
 */
#include <sys/types.h>
#include <sys/socket.h>
#include <stdio.h>
#include <stdlib.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <fcntl.h>
char* read_tempfile(const char *filename){
    int fd;
    size_t length;
    char *buffer;
    fd=open(filename,O_RDONLY);
    lseek(fd,0,SEEK_SET);
    read(fd,&length,sizeof(size_t));
    buffer=malloc(length);
    read(fd,buffer,length);
    close(fd);
    return buffer;
}
int main()
{
    char*buffer;
    char filename[200];
    int length;
    int fd;
   int server_sockfd, client_sockfd;
   int server_len, client_len;
   struct sockaddr_in server_address;
   struct sockaddr_in client_address;
   server_sockfd = socket(AF_INET, SOCK_STREAM, 0);
   server_address.sin_family = AF_INET;
   server_address.sin_addr.s_addr = inet_addr("127.0.0.1");
   server_address.sin_port = 9734;
   server_len = sizeof(server_address);
   bind(server_sockfd, (struct sockaddr *) &server_address, server_len);
   listen(server_sockfd, 5);
   while (1) {
      printf("Server is waiting ....\n");
      client_len = sizeof(client_address);
      client_sockfd = accept(server_sockfd,
            (struct sockaddr *) &client_address,
            (socklen_t *__restrict) &client_len);
      read(client_sockfd, &length, sizeof(length));
      read(client_sockfd,filename,length);
      buffer=read_tempfile(filename);
      printf("client message:%s %s\n",filename,buffer);
      free(buffer);
      close(client_sockfd);
   }
}
#endif
#if 0
/*
 * client端程序:
 */
#include <sys/types.h>
#include <sys/socket.h>
#include <stdio.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <time.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
void write_tempfile(const char *filename,char*buffer,size_t length){
    int fd;
    fd=open(filename,O_WRONLY);
    write(fd,&length,sizeof(length));
    write(fd,buffer,length);
    close(fd);
}
int main() {
   int sockfd;
   int len;
   struct sockaddr_in address;
   int result;
     char *buffer="Hello world oooookkk";
     size_t length=strlen(buffer)+1;
   char filename[]="/home/hfz/tmp/temp_file.axx";
   size_t flen=strlen(filename)+1;

sockfd = socket(AF_INET,SOCK_STREAM, 0);
   address.sin_family = AF_INET;
   address.sin_addr.s_addr = inet_addr("127.0.0.1");
   address.sin_port = 9734;
   len = sizeof(address);
   result = connect(sockfd, (struct sockaddr *) &address, len);
   if (result == -1) {
      perror("连接失败");
      return 1;
   }
   write_tempfile(filename,buffer,length);
   write(sockfd,&flen,sizeof(flen));
   write(sockfd, filename, flen);
   printf("Message sent to server:%s  \n", filename);
   close(sockfd);
   return 0;
}

#endif
#if 0
/*
 * getopt示例2:
 * 5. 利用getopt类似的函数对命令行参数进行解析
 */
#include <stdlib.h>
#include <stdio.h>
//#include <unistd.h>
#include <getopt.h>
const char *program_name;
void print_usage(FILE*stream,int exit_code){
    fprintf(stream,"Usage:%s [options]\n",program_name);
    fprintf(stream,
            "-a argument Use 1\n"
            "-b argument Use 2\n"
            "-c Use 3\n"
            "-d Use 4\n"
            "-e Use 5\n");
    exit(exit_code);
}
int main(int argc,char*argv[]){
    char *servername=getenv("SERVERNAME");
    char *options="a:b::cde";
    int ch;
    program_name=argv[0];
    if(argc==1){
        print_usage(stdout,0);
    }
    if(servername==NULL)
    {
        while((ch=getopt(argc,argv,options))!=-1){
            printf("optind:%d\n",optind);
            printf("optarg:%s\n",optarg);
            printf("ch:%c\n",ch);
            switch(ch)
            {
                case 'a':
                    printf("option a:'%s'\n",optarg);
                    servername="a.com";
                    break;
                case 'b':
                    printf("option b:'%s'\n",optarg);
                    servername="b.com";
                    break;
                case 'c':
                    printf("option c\n");
                    servername="c.com";
                    break;
                case 'd':
                    printf("option d\n");
                    servername="d.com";
                    break;
                case 'e':
                    printf("option e\n");
                    servername="e.com";
                    break;
                default:
                    printf("unknown option:%c\n",ch);
                    servername="localhost.localmain";
                    break;
            }
            printf("optopt+%c\n",optopt);
        }

}
    printf("servername:%s\n",servername);
    return 0;
}

#endif
#if 0
/*
 * 示例程序二:
 */
#include <getopt.h>
#include <stdio.h>
#include <stdlib.h>
const char *program_name;
void print_usage(FILE* stream,int exit_code){
    fprintf(stream,"Usage: %s options [inputfile ...]\n",program_name);
    fprintf(stream,
            "-h --help Display this usage information.\n"
            "-o --output filename Write output to file.\n"
            "-v --verbose Print verbose messages.\n");
    exit(exit_code);
}
int main(int argc,char *argv[])
{
    int next_option;
    const char* const short_options="ho:v";
    const struct option long_options[]={
        {"help",0,NULL,'h'},
        {"output",1,NULL,'o'},
        {"verbose",0,NULL,'v'},
        {NULL,0,NULL,0},
    };
    const char*output_filename=NULL;
    int verbose=0;
    program_name=argv[0];
    if(argc==1){
        print_usage(stdout,0);
    }
    do{
        next_option=getopt_long(argc,argv,short_options,long_options,NULL);
        switch(next_option){
            case 'h':
                print_usage(stdout,0);
            case 'o':
                output_filename=optarg;
                break;
            case 'v':
                verbose=1;
                break;
            case '?':
                print_usage(stderr,1);
            case -1:
                break;
            default:
                abort();
        }
    }while(next_option!=-1);
    if(verbose){
        int i;
        for(i=optind;i<argc;++i)
            printf("Argument:%s\n",argv[i]);
    }
    return 0;
}
#endif
#if 0
/*
 * 6. 多线程并发问题:信号量的使用
 */

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#define NLOOP 5000
int counter;
pthread_mutex_t counter_mutex=PTHREAD_MUTEX_INITIALIZER;
void* doit(void*);
int main()
{
    pthread_t tidA,tidB;
    pthread_create(&tidA,NULL,doit,NULL);
    pthread_create(&tidB,NULL,doit,NULL);

pthread_join(tidA,NULL);
    pthread_join(tidB,NULL);
    return 0;

}
void *doit(void*vptr)
{
    int i,val;
    for(i=0;i<NLOOP;i++)
    {
        pthread_mutex_lock(&counter_mutex);
        val=counter;
        printf("%x:%d\n",(unsigned int)pthread_self(),val+1);
        counter=val+1;
        pthread_mutex_unlock(&counter_mutex);
    }
    return NULL;
}

#endif
#if 0
/*
 * 7. 生产者消费者问题
 */
#include <stdlib.h>
#include <pthread.h>
#include <stdio.h>
#include <semaphore.h>
#define NUM 5
int queue[NUM];
sem_t blank_num,product_num;
void *producer(void *arg)
{
    int p=0;
    while(1){
        sem_wait(&blank_num);
        queue[p]=rand()%1000+1;
        printf("Produce %d\n",queue[p]);
        sem_post(&product_num);
        p=(p+1)%NUM;
        sleep(rand()%5);
    }
}
void *consumer(void *arg)
{
    int c=0;
    while(1){
        sem_wait(&product_num);
        printf("Consume %d\n",queue[c]);
        queue[c]=0;
        sem_post(&blank_num);
        c=(c+1)%NUM;
        sleep(rand()%5);
    }
}
int main()
{
    pthread_t pid,cid;
    sem_init(&blank_num,0,NUM);
    sem_init(&product_num,0,0);
    pthread_create(&pid,NULL,producer,NULL);
    pthread_create(&pid,NULL,consumer,NULL);
    pthread_join(pid,NULL);
    pthread_join(cid,NULL);
    sem_destroy(&blank_num);
    sem_destroy(&product_num);

return 0;
}
#endif
#if 0
/*
 * 示例程序2:
 */
#include <stdlib.h>
#include <pthread.h>
#include <stdio.h>
struct msg{
    struct msg*next;
    int num;
};
struct msg *head;
pthread_cond_t has_product=PTHREAD_COND_INITIALIZER;
pthread_mutex_t lock=PTHREAD_MUTEX_INITIALIZER;
void *consumer(void*p)
{
    struct msg*mp;
    for(;;){
        pthread_mutex_lock(&lock);
        while(head==NULL)
            pthread_cond_wait(&has_product,&lock);
        mp=head;
        head=mp->next;
        pthread_mutex_unlock(&lock);
        printf("Consume %d\n",mp->num);
        free(mp);
        sleep(rand()%5);
    }
}
void *producer(void*p)
{
    struct msg *mp;
    for(;;){
        mp=malloc(sizeof(struct msg));
        mp->num=rand()%1000+1;
        printf("Produce %d\n",mp->num);
        pthread_mutex_lock(&lock);
        mp->next=head;
        head=mp;
        pthread_mutex_unlock(&lock);
        pthread_cond_signal(&has_product);
        sleep(rand()%5);
    }
}
int main()
{
    pthread_t pid,cid;
    srand(time(NULL));
    pthread_create(&pid,NULL,producer,NULL);
    pthread_create(&cid,NULL,consumer,NULL);
    pthread_join(pid,NULL);
    pthread_join(cid,NULL);

return 0;
}

#endif
#if 0
/*
 * 8. 子进程的生成
 */
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main(void)
{
    pid_t child;
    if((child=fork())<0){
        perror("fork");
        exit(EXIT_FAILURE);
    }
    else if(child==0){
        puts("in child");
        printf("child pid=%d\n",getpid());
        printf("child ppid=%d\n",getppid());
        exit(EXIT_SUCCESS);
    }
    else{
        puts("in parent");
        printf("parent pid=%d\n",getpid());
        printf("parent ppid=%d\n",getppid());
        exit(EXIT_SUCCESS);
    }
}

#endif
#if 0
/*
 * 9. 获取IP地址
 */
#include <stdio.h>
#include <netdb.h>
#include <stdlib.h>
int main()
{
    struct addrinfo *res,*pt;
    struct sockaddr_in *sinp;
    const char *addr;
    char abuf[INET_ADDRSTRLEN];
    int succ=0,i=0;
    char a[50];
    scanf("%s",a);
    succ=getaddrinfo(a,NULL,NULL,&res);
    if(!succ)
    {
        printf("ERROR!\n");
        exit(succ);

}
    for(pt=res,i=0;pt!=NULL;pt=pt->ai_next,i++)
    {
        sinp=(struct sockaddr_in*)pt->ai_addr;
        addr=(const char*)inet_ntop(AF_INET,&sinp->sin_addr,abuf,INET_ADDRSTRLEN);
        printf("%2d.IP=%s\n",i,addr);
    }
    return EXIT_SUCCESS;
}

#endif

转载于:https://www.cnblogs.com/xkfz007/archive/2012/08/24/2653797.html

Linux下的示例程序相关推荐

  1. linux下c/c++程序调试拾遗

    linux下c/c++程序调试拾遗 以下为整理c++程序调试过程中经常用到的工具链 1. 调试利器GDB linux下c++程序的调试,绕不过去的第一个就是gdb无疑了: 1.1 启动gdb gdb ...

  2. linux下软件编译终止,[2018年最新整理]linux下编译运行程序命令大全.ppt

    [2018年最新整理]linux下编译运行程序命令大全 1. 项目课题引入 2. Vi编辑器的使用方法 3. Linux中C语言程序的编辑 4. Linux中C语言程序的运行 5. 现场演示案例 课题 ...

  3. linux如何编译wine,利用winelib编译一个可在linux下运行的程序

    利用winelib编译一个可在linux下运行的程序 只是想既可以使用linux的api,又可以使用windows的api #include #include #include #include in ...

  4. linux 编写完程序吗,linux下编写C++程序

    注:本文写的内容全部在ubuntu12.04下完成. 要在linux下写C++程序,要懂的一点编译的知识.下面介绍一下. 源代码->预处理器(负责将代码补充)->汇编程序(生成汇编语言)- ...

  5. Linux下C/C++程序编译链接加载过程中的常见问题及解决方法

    Linux下C/C++程序编译链接加载过程中的常见问题及解决方法 1 头文件包含的问题 报错信息 该错误通常发生在编译时,常见报错信息如下: run.cpp:2:10: fatal error: dl ...

  6. Linux 下几款程序内存泄漏检查工具

    Linux 下几款程序内存泄漏检查工具 chenyoubing | 发布于 2016-07-23 10:08:09 | 阅读量 93 | 无 写这篇博客的原因呢是因为自己在编写基于Nginx磁盘缓存管 ...

  7. 在linux 下编译c程序时“ error:dereferencing pointer to incomplete type”的问题

    在linux 下编译c程序时经常会遇到" error:dereferencing pointer to incomplete type"的问题,该问题的原因是:结构体定义不规范造成 ...

  8. Linux错误27,解决在linux下编译32程序出现“/usr/include/gnu/stubs.h:7:27: 致命错误:gnu/stubs-32.h:没有那个文件或目录问题”...

    centos64位编译32位代码,出现/usr/include/gnu/stubs.h:7:27: 致命错误:gnu/stubs-32.h:没有那个文件或目录,需要安装32位的glibc库文件. 安装 ...

  9. linux 查看进程变量,Linux下查看进程(程序)启动时的环境变量

    Linux下查看进程(程序)启动时的环境变量 Linux的pargs ==================================== 今天又遇到一个老问题: 同事遇到了sqlplus &qu ...

最新文章

  1. nginx安全日志分析脚本的编写
  2. pandas使用groupby函数计算dataframe数据中每个分组的滚动统计值(rolling statistics)的语法:例如分组的N天滚动平均值、滚动中位数、滚动最大最小值、滚动加和等
  3. 两个对于Apriltag图片处理问题讨论
  4. 后端开发工程师的DIV+CSS两栏布局入门
  5. 机器学习系列(2)_从初等数学视角解读逻辑回归
  6. ME22N PO删除控制
  7. MATLAB中cif用于清除什么,cifti-matlab-master 能够对MRI数据进行功能成像 - 下载 - 搜珍网...
  8. 数据分析面试必考的AB-Test知识点整理
  9. EF Core 小坑:DbContextPool 会引起数据库连接池连接耗尽
  10. MongoDB分析工具之三:db.currentOp()
  11. Learun FrameWork,.Net Core3.1工作流引擎平台
  12. 线性方程组解的数目判定
  13. English--consonant_摩擦音_咬舌音
  14. 奇异矩阵及广义逆矩阵
  15. 基于asp.net房屋按揭贷款管理系统
  16. 移动互联网大讨论(二):电话号码:移动互联网最后一个ID
  17. MySQL 下载和安装详解
  18. java语音播报源代码_详解Android 语音播报实现方案(无SDK)
  19. 4.1.7 OS之文件共享(索引节点-硬链接、符号链接-软链接)
  20. 用python打开文件夹的三种方式

热门文章

  1. 【转载】flash时间轴中变量的作用域
  2. Eclipse 导入 Tomcat 源码
  3. 20165204 第十周课下作业补做
  4. alert(1) to win 16
  5. Hadoop(十五)MapReduce程序实例
  6. Edison与Arduino通过USB对接通信
  7. window10安装tensorflow
  8. [数字技巧]最大连续子序列和
  9. POJ1042 Gone Fishing
  10. 多行文本框限制输入字符长度(两种方法)