system与popen对比:
popen和system都可以执行外部命令。
popen相当于是先创建一个管道,fork,关闭管道的一端,执行exec,返回一个标准的io文件指针。system相当于是先后调用了fork, exec,wait来执行外部命令。
system
int system(const char *command);
参数:
command:命令
返回值:
错误返回-1
popen,plose
FILE *popen(const char *command, const char *type);
int pclose(FILE *stream);
参数:
command:命令
type:
r:只读
w:只写
返回值:
错误返回-1
demo1:
1.创建文件,写入hello word
2.用system执行cat文件
#include <stdio.h>
#include <stdlib.h>
void result()
{
int ret;
ret = system("cat ./file");
if(ret == -1)
{
printf("command error\n");
perror("why");
exit(-1);
}
}
int main()
{
result();
return 0;
}
结果示例:

demo2:
1.创建文件,写入hello word
2.用popen执行cat文件
#include <stdio.h>
#include <stdlib.h>
void result()
{
FILE *fp;
int fp_read;
char context[20] = {0};
fp = popen("cat ./file","r");
if(fp == NULL)
{
printf("command error\n");
perror("why");
exit(-1);
}
fp_read = fread(context,20,1,fp);
printf("file size is %d ,file context is %s\n",fp_read,context);
pclose(fp);
}
int main()
{
result();
return 0;
}

demo3:
1.创建文件
2.用popen执行输入hello word到文件中
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void result()
{
FILE *fp;
int fp_write;
char write_buf[] = "hello word\n";
fp = popen("cat > ./file","w");
if(fp == NULL)
{
printf("command error\n");
perror("why");
exit(-1);
}
fp_write = fwrite(write_buf,strlen(write_buf),1,fp);
pclose(fp);
}
int main()
{
result();
return 0;
}
结果示例:

文章详细比较了popen和system两个C语言函数在执行外部命令时的不同。popen通过创建管道和fork进程来执行命令,返回一个文件指针,可以进行读写操作。而system则通过fork、exec和wait调用来执行命令,直接返回命令的退出状态。文中通过三个代码示例展示了popen用于读取、写入文件以及system执行cat命令的情况。

被折叠的 条评论
为什么被折叠?



