C/C++程序调用shell命令可以通过以下函数实现:
FILE *popen(const char *command, const char *mode); popen()会调用fork()产生子进程,然后从子进程中调用/bin/sh -c来执行参数command的指令。参数mode可使用r代表读取,w代表写入。依照mode值,popen()会建立管道连接到子进程的标准输出设备或标准输入设备,然后返回一个文件指针。随后进程便可利用此文件指针来读取子进程的输出设备或是写入到子进程的标准输入设备中。 popen()打开的管道需用pclose关闭。 例: #include <stdio.h> int main(int argc, char * argv[]) { FILE * pp; char buffer[128]; pp=popen("ls -l","r"); fgets(buffer,sizeof(buffer),pp); printf("%s",buffer); pclose(pp); return 0; }
int system(const char *command); system()会调用fork()产生子进程,然后从子进程中调用/bin/sh -c来执行参数command的指令。此命令执行完后立即返回原调用进程。返回值=-1,出现错误;返回值=0,调用成功但是没有出现子进程;返回值>0,成功退出的子进程id。 例: #include <stdio.h> int main(int argc, char * argv[]) { system("ls -l"); return 0; }
exec函数族 int execl(const char *path, const char *arg0, ... /*, (char *)0 */); int execv(const char *path, char *const argv[] ); int execle(const char *path, const char *arg0, ... /*,(char *)0, char *const envp[]*/); int execve(const char *path, char *const argv[] , char *const envp[] ); int execlp(const char *file, const char *arg0, ... /*, (char *)0 */); int execvp(const char *file, char *const argv[] ); 具体用法可man 函数名查阅手册