在c程序中执行Linux命令
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4757512/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Execute a Linux command in the c program
提问by hue
I am trying to execute a Linux command in c program using system system call, but the don't want it to dump the output or error logs on the terminal. What should I do? Is there any other way to do this?
我正在尝试使用系统系统调用在 c 程序中执行 Linux 命令,但不希望它在终端上转储输出或错误日志。我该怎么办?有没有其他方法可以做到这一点?
回答by nos
As the system() call uses a shell to execute the command, you can redirect stdout and stderr to /dev/null, e.g.
由于 system() 调用使用 shell 来执行命令,因此您可以将 stdout 和 stderr 重定向到 /dev/null,例如
system("ls -lh >/dev/null 2>&1");
回答by 0xAX
Show you code.
给你看代码。
Try for example:
尝试例如:
system("ls");
系统(“ls”);
回答by TantrajJa
popen is another way in which you can do the same:
popen 是您可以执行相同操作的另一种方式:
void get_popen()
FILE *pf;
char command[20];
char data[512];
// Execute a process listing
sprintf(command, "ps aux wwwf");
// Setup our pipe for reading and execute our command.
pf = popen(command,"r");
// Error handling
// Get the data from the process execution
fgets(data, 512 , pf);
// the data is now in 'data'
if (pclose(pf) != 0)
fprintf(stderr," Error: Failed to close command stream \n");
return;
}