zoukankan      html  css  js  c++  java
  • 改变目录到命令所在目录(chdir_to_command)

        char str[80];    
    FILE *fp;

    //chang directory to our command
    bzero(str,sizeof(str));  
       /* 判断argv[0]中是否包含'/',
       * 如果包含,则说明使用的是绝对/相对路径来寻找command所在目录
       *如果不包含,则说明command是被安装到/usr/bin等系统定义的目录中,需要查找命令所在目录
       */
        if(NULL == rindex(argv[0],'/')){  //命令在系统预定义目录中
    sprintf(str,"which %s",argv[0]);  //通过which command来查找command所在目录
    fp = popen(str,"r");
    fgets(str,sizeof(str),fp);
    }else{ //使用相对/绝对路径来寻找command
    strncpy(str,argv[0],sizeof(str));
    }
      //路径最后的格式是***/***/command,我们只需要前面的路径,最后那个command删去。
      //所以把字符串中最后一个'/'改成'\0',这样就变成"***/***\0command"了。
        *rindex(str,'/') = '\0';  
      //改变目录到command所在目录
    if(chdir(str) < 0){
    printf("str:%s\n",str);
    pclose(fp);
    pbc_die("chdir error\n");
    }
    pclose(fp);
  • 相关阅读:
    whereis which type find
    souce and bash 的区别
    systemctl daemon-reload
    linux /etc/profile bashrc bash_profile
    ulimt 和 sysctl
    MySQL 问题总结
    asyncio
    Linux 中 MySQL 操作
    总结一波 Redis 面试题
    os 模块 和 re 模块
  • 原文地址:https://www.cnblogs.com/niocai/p/2254071.html
Copyright © 2011-2022 走看看