简体   繁体   English

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

[英]System function is not working in C when the command contains “..”

This is my code:这是我的代码:

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

    return 1;
}

I believe the ".." present in the command is causing the problem cause the program runs properly for other commands.我相信命令中出现的“..”导致了问题,因为程序可以正常运行其他命令。

system does not run your normal shell. system无法正常运行 shell。 It instead always runs /bin/sh .相反,它总是运行/bin/sh From system (3) :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: system ()库function使用fork (2)创建子进程,执行命令中指定的shell命令使用execl (3)如下:

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

system() returns after the command has been completed. system()在命令完成后返回。

Usually /bin/sh is a shell that does not understand {1000..60000} .通常/bin/sh是不理解{1000..60000}的 shell 。 To run bash or zsh you need to do something like要运行 bash 或 zsh 您需要执行类似的操作

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

Not an answer to your question about system(), but may be useful to you:不是您关于 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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM