在C程序中获取系统命令输出
有更好的方法吗在C程序中获取系统命令输出,c,unix,io,operating-system,C,Unix,Io,Operating System,有更好的方法吗 int numOfCPU; system("grep -c ^processor /proc/cpuinfo >> /tmp/cpuinfo"); FILE *fp = fopen("/tmp/cpuinfo", "r"); fscanf(fp, "%d", &numOfCPU); fclose(fp); system("rm /tmp/cpuinfo"); 我不想创建一个中间文件,然后将其删除 编辑: 这与从文件中读取无关。命令可以是“ls”或“echo'
int numOfCPU;
system("grep -c ^processor /proc/cpuinfo >> /tmp/cpuinfo");
FILE *fp = fopen("/tmp/cpuinfo", "r");
fscanf(fp, "%d", &numOfCPU);
fclose(fp);
system("rm /tmp/cpuinfo");
我不想创建一个中间文件,然后将其删除
编辑:
这与从文件中读取无关。命令可以是“ls”或“echo'Hello world'”好的,我在另一个答案中感到困惑。无论如何,这个答案中的哲学是相同的。您可以直接使用popen功能 那么你有这样的东西:
int numOfCPU;
FILE *fp = popen("grep -c ^processor /proc/cpuinfo", "r");
fscanf(fp, "%d", &numOfCPU);
pclose(fp);
我希望它会有用。您需要使用重定向和管道来完成您正在尝试执行的操作 popen调用可以帮助您,但是如果您想要更灵活的东西,比如重定向输入,或者更安全的东西,比如不在shell中运行字符串,那么您应该遵循以下示例,摘自pipe的手册页面
#include <sys/wait.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
int
main(int argc, char *argv[])
{
int pipefd[2];
pid_t cpid;
char buf;
if (argc != 2) {
fprintf(stderr, "Usage: %s <string>\n", argv[0]);
exit(EXIT_FAILURE);
}
if (pipe(pipefd) == -1) {
perror("pipe");
exit(EXIT_FAILURE);
}
cpid = fork();
if (cpid == -1) {
perror("fork");
exit(EXIT_FAILURE);
}
if (cpid == 0) { /* Child reads from pipe */
close(pipefd[1]); /* Close unused write end */
while (read(pipefd[0], &buf, 1) > 0)
write(STDOUT_FILENO, &buf, 1);
write(STDOUT_FILENO, "\n", 1);
close(pipefd[0]);
_exit(EXIT_SUCCESS);
} else { /* Parent writes argv[1] to pipe */
close(pipefd[0]); /* Close unused read end */
write(pipefd[1], argv[1], strlen(argv[1]));
close(pipefd[1]); /* Reader will see EOF */
wait(NULL); /* Wait for child */
exit(EXIT_SUCCESS);
}
}
#包括
#包括
#包括
#包括
#包括
int
main(int argc,char*argv[])
{
int-pipefd[2];
pid_t cpid;
焦炉;
如果(argc!=2){
fprintf(stderr,“用法:%s\n”,argv[0]);
退出(退出失败);
}
如果(管道(管道FD)=-1){
佩罗(“管道”);
退出(退出失败);
}
cpid=fork();
如果(cpid==-1){
佩罗尔(“福克”);
退出(退出失败);
}
如果(cpid==0){/*子级从管道读取*/
关闭(pipefd[1]);/*关闭未使用的写入端*/
while(读取(pipefd[0],&buf,1)>0)
写入(STDOUT_文件号和buf,1);
写入(标准输出文件号,“\n”,1);
关闭(pipefd[0]);
_退出(退出成功);
}else{/*父对象将argv[1]写入管道*/
关闭(pipefd[0]);/*关闭未使用的读取端*/
写入(pipefd[1],argv[1],strlen(argv[1]);
关闭(pipefd[1]);/*读卡器将看到EOF*/
等待(NULL);/*等待子项*/
退出(退出成功);
}
}
您应该修改子进程以使用dup2将标准输出重定向到管道,然后使用awk执行您希望它运行的命令。:
#include <stdlib.h>
#include <stdio.h>
void main()
{
int numOfCPU =0;
system ("awk '/processor/{numOfCPU++}END{print numOfCPU}' /proc/cpuinfo");
}
#包括
#包括
void main()
{
int numOfCPU=0;
系统(“awk'/processor/{numocpu++}END{print numocpu}'/proc/cpuinfo”);
}
这是C代码。我想说C++,但是后来我注意到了文件*。我把java标签替换成C,因为代码在C中。同意!例如,该命令在连续几秒钟后提示输出,那么如何对监视器输出进行编程?