The stdlib library has a function many people have used: system.

If you want the code to be cross-platform and need the program to wait for one second, a handy way is system("sleep 1");. This way, whether on Windows or Linux, you can easily perform a "wait one second" without writing a lot of extra arguments.

But sometimes, we want to capture the command's output rather than just "execute it". Then we need something new.

管道 is a set of processes linked by standard input and output, so each process's output (stdout) is directly fed as the next process's input (stdin). Each link is implemented by an unnamed pipe. Filter programs are often used in this setup.[1]

We can use some system-provided pipe functions to get this output.

This is not a standard library function; it is system-dependent.

On POSIX, a fairly convenient function is popen.

The prototype of popen is:

C
FILE *popen(const char *command, const char *type);

The manual describes it as

the popen() function opens a process by creating a pipe, forking, and invoking the shell. Since a pipe is by definition unidirectional, the type argument may specify only reading or writing, not both; the resulting stream is correspondingly read-only or write-only.

The gist is that it forks a process, executes the command, stores the result in a pipe, and returns a read-only or write-only file handle. On failure, it returns NULL.

Using popen is simple: like fopen, you pass in two strings and get a file handle. The only difference is that fopen's first argument is a filename, while popen's is a command. As for the rest — once you already have a FILE *, what else is there to learn?

Windows also has a very similar function, except it's named _popen; we can easily handle cross-platform compatibility with a macro.

Enough talk — the code itself can pretty much explain everything.

C
#include <stdlib.h>
#include <stdio.h>
#include <string.h>

#ifndef WIN32 // headers for linux
#include <sys/types.h>
#include <unistd.h>
#endif // WIN32

#ifdef WIN32 // windows
#define _exec(cmd) _popen(cmd, "r")
#else // linux
#define _exec(cmd) popen(cmd, "r")
#endif // WIN32


int main(int argc,char *argv[])
{
    FILE *stream;
    char buf[1024];
    memset(buf,'\0',sizeof(buf));//初始化buf,以免后面写如乱码到文件中
    stream = _exec("echo \"hello, world !\""); //将参数内容命令的输出,得到管道文件句柄
    if(stream != NULL)
    {
	    //将刚刚FILE* stream的数据流读取到buf中
	    fread( buf, sizeof(char), sizeof(buf), stream);
	    fwrite( buf, 1, sizeof(buf), stdout );//将buf中的数据写到stdout
	    //关闭流
	    pclose(stream);
    }else
    {
	//执行失败
    	printf("error!\n");
    }
    return 0;
}

The code uses a pipe to execute

Bash
echo "hello, world!"

this command.

Then it reads the execution result and prints it.

One thing to note is that, because the underlying mechanism forks a process, environment variables are copied directly, so watch out for permission issues and the like.