linux下如何用c语言调用shell命令

本文介绍三种从C程序中调用Shell脚本的方法:system()、popen()及exec函数族。system()最简单易用;popen()允许读写Shell输出,开销较小;exec函数族则涉及更多底层细节。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

C程序调用shell脚本共有三种法子 :system()、popen()、exec系列数call_exec1.c ,

system() 不用你自己去产生进程,它已经封装了,直接加入自己的命令
exec 需要你自己 fork 进程,然后exec 自己的命令

popen() 也可以实现执行你的命令,比system 开销小


方法一、system()的使用,我直接上代码吧

 

[html]  view plain  copy
  1. int system(const char *command);  


我在/home/book/shell新建一个test.sh文件如下:


[html]  view plain  copy
  1. <span style="font-size:18px;"><span style="font-size:18px;">#!bin/bash  
  2. echo $HOME  
  3. echo "the is test!"</span></span>  

test.c文件如下:

[html]  view plain  copy
  1. <span style="font-size:18px;"><span style="font-size:18px;">#include<stdlib.h>  
  2.     
  3. int   main()  
  4. {  
  5.   system("bash /home/book/shell/test.sh"); /* chmod +x test.sh ,路径前面要加上bash */  
  6.   return 0;    
  7. }</span></span>  


执行如下命令来编译:

[html]  view plain  copy
  1. <span style="font-size:18px;">gcc test.c -o test  
  2. </span>  

测试命令:

[html]  view plain  copy
  1. <span style="font-size:18px;">./test</span>  

结果如下:

[html]  view plain  copy
  1. <span style="font-size:18px;">/root  
  2. the is test!</span>  


方法二:popen() 会调用fork()产生 子历程,然后从子历程中调用/bin/sh -c来履行 参数command的指令。参数type可应用 “r”代表读取,“w”代表写入。遵循此type值,popen()会建立 管道连到子历程的标准 输出设备 或标准 输入设备 ,然后返回一个文件指针。随后历程便可利用 此文件指针来读取子历程的输出设备 或是写入到子历程的标准 输入设备 中。此外,所有应用 文 件指针(FILE*)操作的函数也都可以应用 ,除了fclose()以外。
 
    返回值:若成功 则返回文件指针,否则返回NULL,差错 原因存于errno中。注意:在编写具SUID/SGID权限的程序时请尽量避免应用 popen(),popen()会继承环境变量,通过环境变量可能会造成系统安全的问题

[html]  view plain  copy
  1. FILE *popen(const char *command, const char *type);  
  2. int pclose(FILE *stream);  

其他不用改变我们直接修改test.c文件:

[html]  view plain  copy
  1. #include<stdio.h>  
  2. int  main()  
  3. {  
  4.     char buffer[80];  
  5.      FILE  *fp=popen("bash /home/book/shell/test.sh","r");  
  6.      fgets(buffer,sizeof(buffer),fp);  
  7.      printf("%s",buffer);  
  8.      pclose(fp);  
  9. return 0;  
  10. }  



方法三:exec函数簇  (我不太懂,copy别人的,也没有验证,习惯方法一)

需要注意的是exec并不是1个函数, 其实它只是一组函数的统称, 它包括下面6个函数:

[html]  view plain  copy
  1. #include <unistd.h>    
  2.     
  3. int execl(const char *path, const char *arg, ...);    
  4.     
  5. int execlp(const char *file, const char *arg, ...);    
  6.     
  7. int execle(const char *path, const char *arg, ..., char *const envp[]);    
  8.     
  9. int execv(const char *path, char *const argv[]);    
  10.     
  11. int execvp(const char *file, char *const argv[]);    
  12.     
  13. int execve(const char *path, char *const argv[], char *const envp[];   

可以见到这6个函数名字不同, 而且他们用于接受的参数也不同.

       实际上他们的功能都是差不多的, 因为要用于接受不同的参数所以要用不同的名字区分它们, 毕竟c语言没有函数重载的功能嘛..  

 

       但是实际上它们的命名是有规律的:

       exec[l or v][p][e]

       exec函数里的参数可以分成3个部分,      执行文件部分,     命令参数部分,   环境变量部分.

        例如我要执行1个命令   ls -l /home/gateman  

        执行文件部分就是  "/usr/bin/ls"

        命令参赛部分就是 "ls","-l","/home/gateman",NULL              见到是以ls开头 每1个空格都必须分开成2个部分, 而且以NULL结尾的啊.

        环境变量部分, 这是1个数组,最后的元素必须是NULL 例如  char * env[] = {"PATH=/home/gateman", "USER=lei", "STATUS=testing", NULL};

        

        好了说下命名规则:

        e后续,  参数必须带环境变量部分,   环境变零部分参数会成为执行exec函数期间的环境变量, 比较少用

        l 后续,   命令参数部分必须以"," 相隔, 最后1个命令参数必须是NULL

        v 后续,   命令参数部分必须是1个以NULL结尾的字符串指针数组的头部指针.         例如char * pstr就是1个字符串的指针, char * pstr[] 就是数组了, 分别指向各个字符串.

        p后续,   执行文件部分可以不带路径, exec函数会在$PATH中找


          

         还有1个注意的是, exec函数会取代执行它的进程,  也就是说, 一旦exec函数执行成功, 它就不会返回了, 进程结束.   但是如果exec函数执行失败, 它会返回失败的信息,  而且进程继续执行后面的代码!



       通常exec会放在fork() 函数的子进程部分, 来替代子进程执行啦, 执行成功后子程序就会消失,  但是执行失败的话, 必须用exit()函数来让子进程退出!

       下面是各个例子:

2.1  execv 函数

[cpp] view plain copy
 
 在CODE上查看代码片派生到我的代码片
  1. int childpid;  
  2. int i;  
  3.   
  4. if (fork() == 0){  
  5.     //child process  
  6.     char * execv_str[] = {"echo""executed by execv",NULL};  
  7.     if (execv("/usr/bin/echo",execv_str) <0 ){  
  8.         perror("error on exec");  
  9.         exit(0);  
  10.     }  
  11. }else{  
  12.     //parent process  
  13.     wait(&childpid);  
  14.     printf("execv done\n\n");  
  15. }  
注意字符串指针数组的定义和赋值

2.2  execvp 函数

[cpp] view plain copy
 
 在CODE上查看代码片派生到我的代码片
  1. if (fork() == 0){  
  2.     //child process  
  3.     char * execvp_str[] = {"echo""executed by execvp",">>""~/abc.txt",NULL};  
  4.     if (execvp("echo",execvp_str) <0 ){  
  5.         perror("error on exec");  
  6.         exit(0);  
  7.     }  
  8. }else{  
  9.     //parent process  
  10.     wait(&childpid);  
  11.     printf("execvp done\n\n");  
  12. }  

2.3 execve 函数

[cpp] view plain copy
 
 在CODE上查看代码片派生到我的代码片
  1. if (fork() == 0){  
  2.     //child process  
  3.     char * execve_str[] = {"env",NULL};  
  4.     char * env[] = {"PATH=/tmp""USER=lei""STATUS=testing", NULL};  
  5.     if (execve("/usr/bin/env",execve_str,env) <0 ){  
  6.         perror("error on exec");  
  7.         exit(0);  
  8.     }  
  9. }else{  
  10.     //parent process  
  11.     wait(&childpid);  
  12.     printf("execve done\n\n");  
  13. }  


2.4 execl 函数

[cpp] view plain copy
 
 在CODE上查看代码片派生到我的代码片
  1. if (fork() == 0){  
  2.     //child process  
  3.     if (execl("/usr/bin/echo","echo","executed by execl" ,NULL) <0 ){  
  4.         perror("error on exec");  
  5.         exit(0);  
  6.     }  
  7. }else{  
  8.     //parent process  
  9.     wait(&childpid);  
  10.     printf("execv done\n\n");  
  11. }  

2.5 execlp 函数

 

[cpp] view plain copy
 
 在CODE上查看代码片派生到我的代码片
  1. if (fork() == 0){  
  2.     //child process  
  3.     if (execlp("echo","echo","executed by execlp" ,NULL) <0 ){  
  4.         perror("error on exec");  
  5.         exit(0);  
  6.     }  
  7. }else{  
  8.     //parent process  
  9.     wait(&childpid);  
  10.     printf("execlp done\n\n");  
  11. }  


2.6 execle 函数

[cpp] view plain copy
 
 在CODE上查看代码片派生到我的代码片
  1. if (fork() == 0){  
  2.     //child process  
  3.     char * env[] = {"PATH=/home/gateman""USER=lei""STATUS=testing", NULL};  
  4.     if (execle("/usr/bin/env","env",NULL,env) <0){  
  5.         perror("error on exec");  
  6.         exit(0);  
  7.     }  
  8. }else{  
  9.     //parent process  
  10.     wait(&childpid);  
  11.     printf("execle done\n\n");  
  12. }  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值