grep, so my

问题描述 投票:0回答:1
function should include a variable.

here is my current code:popen()As you see what I am current trying is making the whole command as one string and using it in

which lead to

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;

while compiling, any suggestions on what I can do to achieve that?popen() Illegal instruction: 4

I want to write at code where the user inputs a given word and I search for it in a file using cat
c popen
1个回答
© www.soinside.com 2019 - 2024. All rights reserved.