【问题标题】:Using a variable with popen function使用带有 popen 函数的变量
【发布时间】:2020-04-25 16:42:21
【问题描述】:

我想在用户输入给定单词的代码中编写代码,然后使用 cat|grep 在文件中搜索它,因此我的popen() 函数应该包含一个变量。

这是我当前的代码:

void *catgrep(void * param){
    int *sock = (int*) param;
    int new_sock = *sock;

int fd[2];
pipe(fd);
pid_t pid = fork(); 
char word[30];
recv(new_sock, word ,30, 0); //receiving the word to search for from the client
char command[]="grep -w ";
strcat(command, word);

     if(pid==0){
       close(1);
       dup(fd[1]);
       close(fd[0]);
       close(fd[1]);

    char *cat_args[] = {"/bin/cat", "file.txt", NULL};
    execv(cat_args[0], cat_args);
    exit(0);
}

  if(pid > 0){
    close(0);
    dup(fd[0]);
    close (fd[1]);
    close(fd[0]);

    FILE *fp2;
    if ((fp2 = popen(command, "r")) == NULL) {
        perror("popen failed");
        return NULL;
    }

    size_t str_size = 1024;
    char *stringts2 = malloc(str_size);
    if (!stringts2) {
        perror("stringts allocation failed");
         return NULL;
    }

    stringts2[0] = '\0';
    char buf[128];
    size_t n;
    while ((n = fread(buf, 1, sizeof(buf) - 1, fp2)) > 0) {
        buf[n] = '\0';
        size_t capacity = str_size - strlen(stringts2) - 1;
      while (n > capacity) {
            str_size *= 2;
            stringts2 = realloc(stringts2, str_size);
            if (!stringts2) {
                perror("stringts realloation failed");
                 return NULL;
            }
            capacity = str_size - strlen(stringts2) - 1;
        }
        strcat(stringts2, buf);
    }

    if (pclose(fp2) != 0) {
        perror("pclose failed");
         return NULL;
    }
    if(send(new_sock, stringts2, 10000, 0)<0){
       printf("Error in send! %s\n", strerror(errno));
        return NULL; 
    }
}
  return NULL;

如您所见,我目前正在尝试将整个命令作为一个字符串并在 popen() 中使用它,这会在编译时导致 Illegal instruction: 4,关于我可以做些什么来实现这一点有什么建议吗?

【问题讨论】:

    标签: c popen


    【解决方案1】:

    strcat 至少有问题。正如文档所说:

    strcat() 函数应附加一个由 指向的字符串的副本 s2(包括终止的空字节)到字符串的末尾 由 s1 指向。

    但是您没有为command 分配足够的空间来连接更多的字符,并且您不应该尝试将字符添加到字符串文字(这是禁止的)。那么这是一个未定义的行为

    要使其在基本情况下工作,您可以进行以下操作:

    char command[1024];
    sprintf(command,"%s %s","grep -w",word);
    

    请注意,如果您的 word 太长或包含空格,这将不起作用。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-25
      • 1970-01-01
      • 1970-01-01
      • 2012-04-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多