如何在C程序中调用Shell 笔记

来源:互联网 发布:js算法 编辑:程序博客网 时间:2024/05/20 08:01

Popen()     execlp()       pclose()

System(“command &(要执行的命令)”)

eg:System(“/your/path/script.sh -var1 -var2 ......”);

 

1 eg:

   #include <stdio.h>

   int main(int argc,char * argv[])

   {

        char buf[128];

        FILE *pp;

        if(pp = popen("ls -l","r") == NULL)

        {

              printf("popen() error!\n");

              exit(1);

        }

       while(fgets(buf, sizeof(buf) , pp))

       {

              printf("%s" , buf);

       }

       pclose(pp);

       return 0;

   }

 

2 eg: hello.sh

     #!/bin/sh

     fun(){......}

     在C程序中调用:

      int  main()

      {

             return system("echo \" func; \" / cat hello.sh -| /bin/sh");

      }

  

3 三种方式:system()     popen()   exec系列函数

     1) system(shell 命令或shell 脚本路径)

            会调用fork()产生子进程

            eg:system(“~/path/xx.sh”);

     

      2)popen(char * command,char * type)

            会调用fork产生子进程

            eg:fp = popen(“~/path/xx.sh”,"r");

 

 

原创粉丝点击