2

好的,我想用我的 PHP 脚本创建一个爬虫。我的爬虫的某些部分需要真正快速地处理字符串,这就是为什么我决定使用 C/C++ 程序来协助我的 PHP 脚本完成该特定工作的原因。以下是我的代码:

$op=exec('main $a $b');
echo $op;

main 是使用我的 C 文件生成的可执行文件,main.cmain.exe. 在上面的操作中,我只是做了一个简单的 C 程序,它接受来自 PHP 的 2 个值并返回这两个值的总和。以下是我的 C 程序的外观

#include< stdio.h >
#include< stdlib.h >
int main(int argc, char *argv[])
{
  int i=add(atoi(argv[1]),atoi(argv[2]));
  printf("%d\n",i);
  return 0;
}

int add(int a, int b)
{
  int c;
  c=a+b;
  return c;
}

我试图通过 CMD 执行程序main 1 1,但它返回了2....它成功了!当我像这样在 php 脚本中输入它们时,

$a=1;
$b=1;
$op=exec('main $a $b');
echo $op;

它没有按预期工作,所以我需要对我的代码做任何想法、建议或其他任何事情。如果你能给我举个例子,我会很棒。提前致谢!!!

4

3 回答 3

3

exec由于您要传递变量,因此您应该用双引号将参数括起来。并且您的程序的输出在exec.

exec("main $a $b", $out);
print_r($out);

请参阅exec()参考资料

于 2012-06-17T08:06:02.333 回答
2

该函数atoi()无法区分无效和有效输入。我建议你strtol()改用。

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

void quit(const char *msg) {
  if (msg) fprintf(stderr, "%s\n", msg);
  exit(EXIT_FAILURE);
}

int add(int, int);

int main(int argc, char *argv[]) {
  int a, b, i;
  char *err;

  if (argc != 3) quit("wrong parameter count");
  a = strtol(argv[1], &err, 10);
  if (*err) quit("invalid first argument");
  b = strtol(argv[2], &err, 10);
  if (*err) quit("invalid second argument");

  i = add(a, b);
  printf("%d\n", i);
  return 0;
}

int add(int a, int b) {
  return a + b;
}
于 2012-06-17T08:10:18.843 回答
0

您需要创建一个可执行文件 ./main。然后使用此代码。它的工作原理

<?php
 $a=1;
 $b=1;
 echo exec("./main $a $b"); 
?>
于 2012-06-17T08:36:21.747 回答