嵌入式技术
如果需要在C语言调用系统指令,经常使用system函数,操作简单方便,很容易理解。system的函数原型如下:
参数非常简单,把需要执行的命令作为字符串传入就行。比如:int system(const char *command);
运行结果如下:int main(){system("ls -l");return 0;}
system函数一般用于命令不复杂,也不需要获取命令结果的场景。 execroot@Turbo:~# gcc test.c -o testroot@Turbo:~# ./testtotal 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:~#
exec不是一个函数,属于一个函数族,有一些exec开头的函数,比如:
exec的定位和system不太一样,exec更多时候用于启动一个新的进程,用新的进程来代替当前进程。比如: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[]);
运行现象:int main(){execl("/bin/ls", "-l", NULL);printf("helloworld ");return 0;}
需要注意:程序的第8行并没有执行! 程序一旦执行到了execl函数,下面的代码都不会执行。可以理解成:程序跳到了新的进程开始执行,但是进程号并没没有变。 exec也经常配合vfork在子进程中启动新的进程,这样父进程还能继续检测子进程的动态。 popenroot@Turbo:~# gcc test.c -o testroot@Turbo:~# ./test1-program 2-c_pointer 3-park 4-thread_poll glibc-2.35 test test.croot@Turbo:~#
如果在C文件中调用系统命令,同时还要获得命令的输出结果,可以使用popen函数。函数原型如下:
popen用于执行 command 指向的命令,并且把命令的输出结果记录在文件中,popen返回该文件的文件流指针。下面的代码直接从文件中读取结果就行。 type表示操作文件的权限,可以选择“r”,“w”,“e”。 比如:FILE *popen(const char *command, const char *type);
最后,如何在C语言中调用Shell脚本? 跟执行命令一样,把普通的命令换成脚本的执行语句即可,比如: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;}
FILE *fp = popen("./test.sh", "r");
审核编辑:汤梓红
全部0条评论
快来发表一下你的评论吧 !