要将信息从PHP传递给C程序,可以使用以下方法:
exec()
或shell_exec()
函数调用C程序,并将信息作为命令行参数传递给C程序。在C程序中,可以使用argc
和argv
参数来获取传递的信息。例如,在PHP中调用C程序并传递信息:
$information = "Hello, C program!";
$output = shell_exec('./my_c_program ' . escapeshellarg($information));
echo $output;
在C程序中获取信息:
#include <stdio.h>
int main(int argc, char *argv[]) {
if (argc > 1) {
printf("Received information: %s\n", argv[1]);
}
return 0;
}
proc_open()
函数打开C程序的进程,并使用fwrite()
函数将信息写入C程序的标准输入流。在C程序中,可以使用scanf()
或fgets()
函数来读取传递的信息。例如,在PHP中传递信息给C程序:
$information = "Hello, C program!";
$cProgram = proc_open('./my_c_program', [
0 => ['pipe', 'r'], // 标准输入
1 => ['pipe', 'w'], // 标准输出
2 => ['pipe', 'w'], // 标准错误输出
], $pipes);
if (is_resource($cProgram)) {
fwrite($pipes[0], $information);
fclose($pipes[0]);
$output = stream_get_contents($pipes[1]);
fclose($pipes[1]);
proc_close($cProgram);
echo $output;
}
在C程序中获取信息:
#include <stdio.h>
int main() {
char information[100];
scanf("%s", information);
printf("Received information: %s\n", information);
return 0;
}
这些方法可以根据具体需求选择适合的方法来传递信息给C程序。
下一篇:php修改txt内容代码
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站