c-使用带有popen函数的变量

  • 本文关键字:函数 变量 popen c popen
  • 更新时间 :
  • 英文 :


我想在用户输入给定单词的代码中编写代码,并使用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] = '';
char buf[128];
size_t n;
while ((n = fread(buf, 1, sizeof(buf) - 1, fp2)) > 0) {
buf[n] = '';
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! %sn", strerror(errno));
return NULL; 
}
}
return NULL;

正如你所看到的,我目前正在尝试将整个命令作为一个字符串,并在编译时在popen()中使用它,这导致了Illegal instruction: 4,有什么建议可以实现这一点吗?

strcat至少有一个问题。正如医生所说:

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

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

为了使其在基本情况下发挥作用,您可以制作以下内容:

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

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

最新更新