【问题标题】:issue executing unix commands using system() in c在 c 中使用 system() 执行 unix 命令的问题
【发布时间】:2021-02-27 05:56:45
【问题描述】:

我目前正在尝试编写一个程序来接受用户输入并在 unix 系统中执行命令,代码可以编译,但是当我运行它时出现分段错误。我认为这可能与 system() 函数的输入数据类型有关,但我似乎无法弄清楚

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

char argument[1024];
main() {
      fgets(argument, 1024, stdin);
      strtok (argument, "\n");
      char *command = strcat("cd ", argument);
      int response = system(command);
      if(response == -1)
      {
      printf("error executing command");
      }
}

如果这看起来微不足道,我深表歉意,我对 c 没有太多经验

【问题讨论】:

  • 您正在尝试连接到字符串文字。更好的方法可能是使用sprintf 来构建您的命令字符串。
  • man strcat: strcat(dest, src)。第一个参数是一个目的地,它应该足够大。您将字符串文字传递给函数。该文字的长度是4 字节,因此它是溢出的。
  • 这样吗? sprintf(命令,“cd %s”,参数);

标签: c unix


【解决方案1】:

您正在 Unix 系统中使用 C 语言进行编程。

编写 C 语言只是为了编写 Unix 本身。 system() 是用 C、Unix、Windows、Linux、Android、MacOS、Python、java 编写的,起初一切都是用 C 编写的,现在大部分都是用 C 编写的。 在 Unix 和衍生产品中有许多 shells,它们只是在用户键入命令时运行命令。 所以使用system() 运行命令并不会增加太多。只是另一个级别的间接,一个很大的安全漏洞,因为你的程序可以被不那么好的人用来做意想不到的事情。使用您的程序。

另一种选择

这是下面程序的输出

Current directory is: /home/testing/projects/tcursor
directory changed to '/tmp'
Enter name of directory to create: thing
'/tmp/thing' created
Now changing to newly created folder
Current directory is: '/tmp/thing'

程序只是

  • cwd/tmp
  • 提示输入要创建的文件夹的名称
  • 创建文件夹
  • cd给它
  • 显示当前目录
  • 出错返回 1,2,3,4,成功返回 0

所以你可以看到cdpwdmkdir的一些C代码

int main(void)
{
    char        asw[30];
    char        buffer[1024];
    char*       p = buffer;
    const char* temp = "/tmp";

    p = getcwd(p,1024);
    printf("Current directory is: %s\n",p);
    int n = chdir(temp);
    if ( n != 0 ) return(1);
    printf("directory changed to '%s'\n", temp);
    printf("Enter name of directory to create: ");
    fgets(asw,30,stdin);
    asw[strlen(asw)-1] = 0;
    n = mkdir(asw, 0777 );
    if ( n != 0 ) return(2);
    printf("'%s' created\n", buffer);
    printf("Now changing to newly created folder\n");
    sprintf(buffer,"%s/%s", temp, asw);
    n = chdir(buffer);
    if ( n != 0 ) return(4);
    p = getcwd(p,1024);
    printf("Current directory is: '%s'\n",p);
    return 0;

不要使用system()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-10-04
    • 2014-05-13
    • 2010-09-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多