linux C技巧实例

1.带有缓存的getchar实现。

        getchar每次从文件获取一个字符,这样显得很没有效率,因为每读一个字符计算机都要读一次磁盘,而读磁盘的速度是很慢的。getchar实际上在函数内部声明了一个静态字符缓冲区(字符数组),首次调用getchar,getchar一次性读入n个字符,但每次函数只返回一个字符,只有缓冲区为空(n次getchar调用)之后才需要再次从文件中读取n个字符。这样n次调用只需要读取一个文件,效率大大提高。我们来看看具体怎么实现吧!

int getchar(int fd,char *c)

{//返回-1表示读取失败或者文件结束,1表示正常读取返回

       static int len = 0;

       static char buf[1024];

       char* ptr;

       if(len <= 0){

         again:if((len = read(fd,buf,sizeof(buf)) < 0)

                    {

                    if(errno == EINTR)

                          goto again;//read阻塞时程序中断处理应该重新读文件

                     return -1;

                     }else if(len == 0)

                     {//读取0个字节表示读取到文件结束了

                    return -1;

                    }

                  ptr = buf;

     }else

    {

           *c = *ptr++;

           len --;

    }

    return 1;

}

2.遍历目录树

//interface to be learned are:DIR* opendir(const char*);struct dirent* readdir(DIR*);int closedir(DIR*);int stat(const char*,struct stat*);
//and stl queue;
#include <iostream>
#include <cstring>
#include <queue>
#include <dirent.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <cstdlib>
#include <cstdio>
#include <cerrno>
using namespace std;
char path_max[1024];
void walkDir(const char *path)
{
   queue<char*> q;
   struct stat statbuf;
   struct dirent *ent;
   int fcount,dcount,ocount;
   char *p = new char[strlen(path)+1];//easy to make mistake here for rookies,must be strlen+1
   strcpy(p,path);
   q.push(p);
   fcount = dcount = ocount = 0;
   dcount++;
   while(!q.empty())
   {//all file in q is directory
      p = q.front();
      q.pop();
      DIR *dir = opendir(p);
      if(!dir){perror("opendir:");exit(-1);}
     while((ent = readdir(dir)) != NULL)
     {
        if(strcmp(ent->d_name,".") == 0 || strcmp(ent->d_name,"..") == 0)//escape .. directory to avoid infinite loop
             continue;
        strcpy(path_max,p);
        strcat(path_max,"/");
        strcat(path_max,ent->d_name);
        if(lstat(path_max,&statbuf) < 0)//use lstat instead of stat to avoid infinite loop because a link may point to his ancester directory
        {
            printf("%s:%s \n",path_max,strerror(errno));
            exit(-1);
        }
        if((statbuf.st_mode&S_IFMT) == S_IFREG)
        {
            fcount++;
            cout<<"file:"<<path_max<<" size:"<<statbuf.st_size<<endl;
        }
        else if((statbuf.st_mode&S_IFMT) == S_IFDIR)
        {
            char* p = new char[strlen(path_max)+1];//easy to make mistake here for rookies,must be strlen+1
            strcpy(p,path_max);
            q.push(p);
            cout<<"dir:"<<p<<endl;
            dcount++;
        }
        else if((statbuf.st_mode & S_IFMT) == S_IFLNK)
        {

            cout<<"link:"<<path_max;
            ssize_t s;
            if((s = readlink(path_max,path_max,sizeof(path_max)))<0)
            {printf("%s\n",strerror(errno));exit(-1);}
            path_max[s] = 0;
            cout<<" to "<<path_max;
            ocount ++;
        }else
        {
            cout <<"other:"<<path_max<<endl;
            ocount++;
        }
     }
     closedir(dir);//remember to closedir or "too much open error" will occur
     delete []p;//release the member
   }
   cout<<"files:"<<fcount<<' '<<"dirs:"<<dcount<<' '<<"other:"<<ocount<<endl;
}
3.实现简单的具备重定向的shell程序

#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/wait.h>
#include <stdlib.h>
#include <fcntl.h>
char *arg[10];
int main(int argc,char* argv[])
{
    int i,status;
    char *saveptr;
    char buf[80];
    char *p = NULL,*q;
    int fd,infd,outfd;
    pid_t pid;
    i = 0;
    infd = STDIN_FILENO;outfd = STDOUT_FILENO;//如果发生重定向infd和outfd用来保存标准输入输出的内核文件结构
    while(1)
    {
        fprintf(stderr,"[My Shell]#");
        fgets(buf,80,stdin);
        printf("%s",buf);
        i = 0;
        p = buf;
        while((p = strtok_r(p," \n",&saveptr)))
        {//处理命令参数,must add '\n' as a delimiter or one of the token will include '\n' which leads to error
            if((q = strchr(p,'<')))
            {
                if((fd = open(q+1,O_RDONLY)) < 0){perror("open:");exit(-1);}
                infd = dup(STDIN_FILENO);//复制标准输入的内核文件结构
                dup2(fd,STDIN_FILENO);//重定向
                close(fd);
                p = NULL;
                continue;
            }
            if((q = strchr(p,'>')))
            {
                //printf("%s\n",q+1);
                if((fd = open(q+1,O_WRONLY|O_CREAT|O_TRUNC,0664)) < 0)
                {//文件存在则打开并清空文件,否则创建文件,权限为0664
                    perror("open:");
                    exit(-1);
                }
                outfd = dup(STDOUT_FILENO);//复制标准输入的内核文件结构
                dup2(fd,STDOUT_FILENO);//重定向
                close(fd);
                p = NULL;
                continue;
            }
            arg[i++] = p;
            p = NULL;
        }
        arg[i] = NULL;
        pid = fork();
        if(pid > 0)
        {
            wait(&status);
            /*如果标准输入输出被重定向了,必须修改STDIN_FILENO和STDOUT_FILENO回标准输入输出*/
            if(infd != STDIN_FILENO){dup2(infd,STDIN_FILENO);close(infd);infd = STDIN_FILENO;}
            if(outfd != STDOUT_FILENO){dup2(outfd,STDOUT_FILENO);close(outfd);outfd = STDOUT_FILENO;}
        }
        else if(pid == 0)
        {
            if(execvp(arg[0],arg)<0)
             {
                perror("execvp:");
                exit(-1);
             }
        }
        else{perror("fork:");exit(-1);}
    }
}

4.linux信号处理

#include <signal.h>
#include <unistd.h>
#include <stdio.h>
//信号集的处理sigdelset,sigaddset,sigemptyset,sigfillset,sigismember;
//信号屏蔽字设置sigprocmask
//信号处理函数设置sigaction,信号处理函数类型void (*sa_handler)(int);
void alarm_handle(int sig)
{
    printf("awaked!\n");
}
unsigned int mysleep(unsigned int seconds)
{
    struct sigaction action,oaction;
    sigset_t nset,oset;
    action.sa_handler = alarm_handle;
    action.sa_flags = 0;
    sigemptyset(&action.sa_mask);
    sigemptyset(&nset);
    sigaddset(&nset,SIGALRM);//屏蔽SIGALRM信号
    sigprocmask(SIG_BLOCK,&nset,&oset);
    sigaction(SIGALRM,&action,&oaction);
    alarm(seconds);//设置闹钟
    nset = oset;
    sigdelset(&nset,SIGALRM);//开放SIGALARM信号
    sigaddset(&nset,SIGINT);//屏蔽SIGINT信号
    sigsuspend(&nset);//等待信号发生
    sigaction(SIGALRM,&oaction,NULL);//恢复原来信号处理函数
    sigprocmask(SIG_SETMASK,&oset,NULL);//恢复原来信号掩码
    return alarm(0);
}

5.生产者消费者问题,线程同步练习

#include <pthread.h>
#include <stdio.h>
#include <semaphore.h>
#include <unistd.h>
#include <stdlib.h>
#define NUM 10 //定义循环缓冲区大小为10
struct MyBuf
{
    int r,w;
    int buf[NUM];
    pthread_mutex_t rlock,wlock;
    sem_t spaceleft,productleft;
};//buf为缓冲区rlock为读指针r的互斥锁,wlock为写指针w的互斥锁,spaceleft,productleft为可用空间和产品数的信号量
struct ThreadAttr{
    struct MyBuf *b;
    int n;
};//传给thread的参数结构
void initMyBuf(struct MyBuf *b)
{
    b->r = b->w = 0;
    pthread_mutex_init(&b->rlock,NULL);
    pthread_mutex_init(&b->wlock,NULL);
    sem_init(&b->spaceleft,0,NUM);
    sem_init(&b->productleft,0,0);
}
void destroyMyBuf(struct MyBuf* b)
{
    pthread_mutex_destroy(&b->rlock);
    pthread_mutex_destroy(&b->wlock);
    sem_destroy(&b->spaceleft);
    sem_destroy(&b->productleft);
}
void produceProducts(struct MyBuf *b,int n)
{//生产n个产品,放入struct MyBuf里面
    for(int i = 0;i < n;i++)
    {
        sem_wait(&b->spaceleft);
        pthread_mutex_lock(&b->wlock);
        b->w = b->w%NUM;
        b->buf[b->w++] = (int)pthread_self();
        printf("%d add \n",(int)pthread_self());
        pthread_mutex_unlock(&b->wlock);
        sem_post(&b->productleft);
        sleep(rand()%3);
    }
}
void* producer(void *taddr)
{
    struct ThreadAttr* taddr2 = (struct ThreadAttr*)taddr;
    produceProducts(taddr2->b,taddr2->n);
    return (void*)1;
}
void consumeProducts(struct MyBuf* b,int n)
{//消费n个产品,放入struct MyBuf里面
    for(int i = 0;i < n;i++)
    {
        sem_wait(&b->productleft);
        pthread_mutex_lock(&b->rlock);
        b->r = b->r%NUM;
        printf("%d del \n",b->buf[b->r++]);
        pthread_mutex_unlock(&b->rlock);
        sem_post(&b->spaceleft);
        sleep(rand()%3);
    }
}
void* consumer(void *taddr)
{
    struct ThreadAttr* taddr2 = (struct ThreadAttr*)taddr;
    consumeProducts(taddr2->b,taddr2->n);
    return (void*)2;
}
int main(void )
{
    struct MyBuf buf;
    struct ThreadAttr attr;
    attr.b = &buf;
    attr.n = 5;
    pthread_t c,c1,p,p1,p2;
    srand(time(NULL));
    initMyBuf(&buf);
    pthread_create(&c,0,consumer,&attr);
    pthread_create(&c1,0,consumer,&attr);
    pthread_create(&p,0,producer,&attr);
    pthread_create(&p1,0,producer,&attr);
    pthread_create(&p2,0,producer,&attr);
    pthread_join(c,NULL);
    pthread_join(c1,NULL);
    pthread_join(p,NULL);
    pthread_join(p1,NULL);
    pthread_join(p2,NULL);
    destroyMyBuf(&buf);
}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值