当命令包含“..”时,系统函数在 C 中不起作用

System function is not working in C when the command contains ".."

这是我的代码:

#include<stdlib.h>
int main()
{
    system("getent passwd {1000..60000}");

    return 1;
}

我认为命令中出现的“..”是导致程序正常运行其他命令的问题的原因。

system 不 运行 你的 正常 shell。它代替 always 运行s /bin/sh。来自 system(3):

DESCRIPTION

The system() library function uses fork(2) to create a child process that executes the shell command specified in command using execl(3) as follows:

          execl("/bin/sh", "sh", "-c", command, (char *) NULL);

system() returns after the command has been completed.

通常/bin/sh是一个不懂{1000..60000}的shell。要 运行 bash 或 zsh 你需要做一些像

system("/bin/bash -c 'getent passwd {1000..60000}'");

不是您关于 system() 问题的答案,但可能对您有用:

#include <pwd.h>
#include <stdio.h>
#include <sys/types.h>

int main() {
  struct passwd *p;
  while (NULL != (p = getpwent())) {
    printf("id=%d name=%s\n", p->pw_uid, p->pw_name);
  }
  endpwent();
  return 0;
}