Archive for 01月 3rd, 2008
C中调用shell命令的方法 popen演示
- lily@LLY:~/test$ cat popen.c
- #include《stdio.h》 //这coolcode转不了这个符合,没办法了。。。自己改改。
- int main(){
- FILE * fp;
- char str[1024];
- if(NULL==(fp=popen("pwd","r"))){
- return -1;
- }else{
- printf("%s",fgets(str,1023,fp));
- pclose(fp);
- }
- return 0;
- }
- lily@LLY:~/test$ gcc popen.c
- lily@LLY:~/test$ ./a.out
- /home/lily/test
- lily@LLY:~/test$
另如果只是要执行shell命令,而不管输出的话,有可以用system函数:
man system这么说:
NAME
system – execute a shell command
SYNOPSIS
#include 《stdlib.h》
int system(const char *command);
DESCRIPTION
system() executes a command specified in command by calling /bin/sh -c command, and returns after the command has been completed. During execution of the
command, SIGCHLD will be blocked, and SIGINT and SIGQUIT will be ignored.