![](/img/trans.png)
[英]Cannot get stderr of the execution of a compiled C program with the system command in perl
[英]Get system command output in C program
有沒有更好的方法呢?
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中運行字符串,你應該遵循這個例子,從管道的手冊頁中獲取。
#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);
}
}
您應該修改子進程以使用dup2將標准輸出重定向到管道,然后執行您希望它運行的命令。
使用awk :
#include <stdlib.h>
#include <stdio.h>
void main()
{
int numOfCPU =0;
system ("awk '/processor/{numOfCPU++}END{print numOfCPU}' /proc/cpuinfo");
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.