利用system函数来执行shell脚本文件问题总结

1.问题

在Android framework层执行如下命令;

    char* cmd= "/system/bin/otherko.sh";
    if ((access(cmd,F_OK)) == -1){
                return 1;
     }
     int status = system(cmd);
     ALOGD("status %d\n",status);

有时候会遇到system函数执行失败,导致程序假死。

2.解决方式

通过在CSDN查阅资料发现,遇到次问题的人很多,而且出了很好的解决方案。下面把查找到最完善的解决方法贴出来,一起研究。目前项目由于已经上线,由于项目模块不属于频繁操作情况,所以一般情况下不会再现场出现,目前只是在研发室自测,结果非常稳定。主要参考一下博客,内容集成了很多优秀工程师的智慧结晶。

https://www.cnblogs.com/tdyizhen1314/p/4902560.html

【C/C++】Linux下使用system()函数一定要谨慎 

曾经的曾经,被system()函数折磨过,之所以这样,是因为对system()函数了解不够深入。只是简单的知道用这个函数执行一个系统命令,这远远不够,它的返回值、它所执行命令的返回值以及命令执行失败原因如何定位,这才是重点。当初因为这个函数风险较多,故抛弃不用,改用其他的方法。这里先不说我用了什么方法,这里必须要搞懂system()函数,因为还是有很多人用了system()函数,有时你不得不面对它。 

先来看一下system()函数的简单介绍: 

#include  

int system(const char *command); 

system() executes a command specified in command by calling /bin/sh -c command, and returns after the command has been completed. During execution of the command, SIGCHLD will be blocked, and SIGINT and SIGQUIT will be ignored.

system()函数调用/bin/sh来执行参数指定的命令,/bin/sh 一般是一个软连接,指向某个具体的shell,比如bash,-c选项是告诉shell从字符串command中读取命令; 在该command执行期间,SIGCHLD是被阻塞的,好比在说:hi,内核,这会不要给我送SIGCHLD信号,等我忙完再说; 在该command执行期间,SIGINT和SIGQUIT是被忽略的,意思是进程收到这两个信号后没有任何动作。 

再来看一下system()函数返回值: 

The value returned is -1 on error (e.g. fork(2) failed), and the return status of the command otherwise. This latter return status is in the format specified in wait(2). Thus, the exit code of the command will be WEXITSTATUS(status). In case /bin/sh could not be executed, the exit status will be that of a command that does exit(127). If the value of command is NULL, system() returns nonzero if the shell is available, and zero if not. 

为了更好的理解system()函数返回值,需要了解其执行过程,实际上system()函数执行了三步操作: 

1.fork一个子进程; 

2.在子进程中调用exec函数去执行command; 

3.在父进程中调用wait去等待子进程结束。 对于fork失败,system()函数返回-1。 如果exec执行成功,也即command顺利执行完毕,则返回command通过exit或return返回的值。 (注意,command顺利执行不代表执行成功,比如command:"rm debuglog.txt",不管文件存不存在该command都顺利执行了) 如果exec执行失败,也即command没有顺利执行,比如被信号中断,或者command命令根本不存在,system()函数返回127. 如果command为NULL,则system()函数返回非0值,一般为1. 

看一下system()函数的源码 

看完这些,

我想肯定有人对system()函数返回值还是不清楚,看源码最清楚,下面给出一个system()函数的实现: 

int system(const char * cmdstring) 

  pid_t pid; 

  int status; 

  if(cmdstring == NULL) 

  { 

    return (1); //如果cmdstring为空,返回非零值,一般为1 

  } 

  if((pi

  • 3
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值