如何从 C 程序执行终端命令?

How can I execute terminal commands from a C program?

我正在用 C 创建一个反向 shell(只是为了练习),但我不知道如何从我的 C 程序执行终端命令。我应该怎么做呢? (我在 POSIX 系统上)(我想得到输出)

how to execute terminal commands from my C program ... (I would like to get the output)

看看popen

例子

#include <stdio.h>

int main(int argc, char ** argv)
{
  if (argc != 2) {
    fprintf(stderr, "Usage: %s <command>\n", *argv);
    return -1;
  }

  FILE * fp = popen(argv[1], "r");

  if (fp != 0) {
    char s[64];

    while (fgets(s, sizeof(s), fp) != NULL)
      fputs(s, stdout);

    pclose(fp);
  }

  return 0;
}

编译与执行:

bruno@bruno-XPS-8300:/tmp$ gcc -Wall o.c
bruno@bruno-XPS-8300:/tmp$ ./a.out date
samedi 11 avril 2020, 17:58:45 (UTC+0200)
bruno@bruno-XPS-8300:/tmp$ a.out "date | wc"
      1       6      42
bruno@bruno-XPS-8300:/tmp$ ./a.out "cat o.c"
#include <stdio.h>

int main(int argc, char ** argv)
{
  if (argc != 2) {
    fprintf(stderr, "Usage: %s <command>\n", *argv);
    return -1;
  }

  FILE * fp = popen(argv[1], "r");

  if (fp != 0) {
    char s[64];

    while (fgets(s, sizeof(s), fp) != NULL)
      fputs(s, stdout);

    pclose(fp);
  }

  return 0;
}
bruno@bruno-XPS-8300:/tmp$