popen 和 system功能详解
popen和system是两个在Linux系统中常用的用于执行外部命令的函数。
- popen函数:
popen函数用于执行一个外部命令,并返回一个文件指针,通过该文件指针可以读取命令的输出内容。
函数原型:
FILE *popen(const char *command, const char *type);
参数说明:
- command:要执行的外部命令的命令行字符串。
- type:打开的文件指针的类型,可以是"r"(只读)或"w"(只写)。
返回值:
- 如果成功打开了一个文件指针,则返回一个指向该文件指针的指针;如果出错,则返回NULL。
使用示例:
#include <stdio.h>
int main()
{
FILE *fp;
char buffer[1024];
fp = popen("ls -l", "r");
if (fp == NULL) {
printf("popen failed!\n");
return -1;
}
while (fgets(buffer, sizeof(buffer), fp) != NULL) {
printf("%s", buffer);
}
pclose(fp);
return 0;
}
上述代码使用popen函数执行了"ls -l"命令,并通过文件指针fp读取了命令的输出内容。
- system函数:
system函数用于执行一个外部命令,并等待该命令执行完毕。
函数原型:
int system(const char *command);
参数说明:
- command:要执行的外部命令的命令行字符串。
返回值:
- 如果成功执行了外部命令,则返回命令的返回值;如果出错,则返回-1。
使用示例:
#include <stdio.h>
int main()
{
int ret;
ret = system("ls -l");
if (ret == -1) {
printf("system failed!\n");
return -1;
}
return 0;
}
上述代码使用system函数执行了"ls -l"命令,并打印了命令的返回值。
需要注意的是,system函数会阻塞当前进程,直到执行的外部命令执行完毕。如果需要在执行外部命令的同时进行其他操作,可以考虑使用多线程或者fork-exec方式
原文地址: https://www.cveoy.top/t/topic/il73 著作权归作者所有。请勿转载和采集!