bones7456 all linux

Archive for 01月 3rd, 2008

C中调用shell命令的方法 popen演示

  1. lily@LLY:~/test$ cat popen.c
  2. #include《stdio.h》 //这coolcode转不了这个符合,没办法了。。。自己改改。
  3. int main(){
  4.         FILE * fp;
  5.         char str[1024];
  6.         if(NULL==(fp=popen("pwd","r"))){
  7.                 return -1;
  8.         }else{
  9.                 printf("%s",fgets(str,1023,fp));
  10.                 pclose(fp);
  11.         }
  12.         return 0;
  13. }
  14. lily@LLY:~/test$ gcc popen.c
  15. lily@LLY:~/test$ ./a.out
  16. /home/lily/test
  17. 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.