I am LAZY bones? AN ancient AND boring SITE

2008年 01月 03日 的归档

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

以下是 popen.c

#include <stdio.h>
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.