怎么在C语言调用系统指令

嵌入式技术

1335人已加入

描述

 system  

 

如果需要在C语言调用系统指令,经常使用system函数,操作简单方便,很容易理解。system的函数原型如下:  
  •  
  •  
  •  
#include 
int system(const char *command);
   参数非常简单,把需要执行的命令作为字符串传入就行。比如:  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
#include #include 
int main(){    system("ls -l");
    return 0;}
   运行结果如下:  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
root@Turbo:~# gcc test.c -o testroot@Turbo:~# ./test total 44drwxr-xr-x  2 root root  4096 Jul  6 09:38 1-programdrwxr-xr-x 17 root root  4096 Nov 24  2021 2-c_pointerdrwxr-xr-x  2 root root  4096 Feb  9  2022 3-parkdrwxr-xr-x  2 root root  4096 Aug  1 17:19 4-thread_polldrwxrwxr-x 68 root root  4096 Feb  3  2022 glibc-2.35-rwxr-xr-x  1 root root 16696 Sep  5 14:50 test-rw-r--r--  1 root root    85 Sep  5 14:50 test.croot@Turbo:~#
   system函数一般用于命令不复杂,也不需要获取命令结果的场景。    exec  

 

exec不是一个函数,属于一个函数族,有一些exec开头的函数,比如:  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
#include 
int execl(const char *pathname, const char *arg, ...                       /* (char  *) NULL */);int execlp(const char *file, const char *arg, ...                       /* (char  *) NULL */);int execle(const char *pathname, const char *arg, ...                       /*, (char *) NULL, char *const envp[] */);int execv(const char *pathname, char *const argv[]);int execvp(const char *file, char *const argv[]);int execvpe(const char *file, char *const argv[],                  char *const envp[]);
   exec的定位和system不太一样,exec更多时候用于启动一个新的进程,用新的进程来代替当前进程。比如:  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
#include #include 
int main(){    execl("/bin/ls", "-l", NULL);
    printf("helloworld
");
    return 0;}
   运行现象:  
  •  
  •  
  •  
  •  
root@Turbo:~# gcc test.c -o testroot@Turbo:~# ./test 1-program  2-c_pointer  3-park  4-thread_poll  glibc-2.35  test  test.croot@Turbo:~#
   需要注意:程序的第8行并没有执行!  程序一旦执行到了execl函数,下面的代码都不会执行。可以理解成:程序跳到了新的进程开始执行,但是进程号并没没有变。  exec也经常配合vfork在子进程中启动新的进程,这样父进程还能继续检测子进程的动态。    popen  

 

如果在C文件中调用系统命令,同时还要获得命令的输出结果,可以使用popen函数。函数原型如下:  
  •  
  •  
  •  
#include 
FILE *popen(const char *command, const char *type);
   popen用于执行 command 指向的命令,并且把命令的输出结果记录在文件中,popen返回该文件的文件流指针。下面的代码直接从文件中读取结果就行。  type表示操作文件的权限,可以选择“r”,“w”,“e”。  比如:  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
#include #include 
int main(){    FILE *fp = popen("date +%X", "r");    if (NULL == fp)         perror("popen");
    char buf[1024] = {0};    fread(buf, 1, sizeof(buf), fp);    printf("%s", buf);
    fclose(fp);
    return 0;}
   最后,如何在C语言中调用Shell脚本?  跟执行命令一样,把普通的命令换成脚本的执行语句即可,比如:  
  •  
FILE *fp = popen("./test.sh""r");
 

  审核编辑:汤梓红


打开APP阅读更多精彩内容
声明:本文内容及配图由入驻作者撰写或者入驻合作网站授权转载。文章观点仅代表作者本人,不代表电子发烧友网立场。文章及其配图仅供工程师学习之用,如有内容侵权或者其他违规问题,请联系本站处理。 举报投诉

全部0条评论

快来发表一下你的评论吧 !

×
20
完善资料,
赚取积分