我在设置.cpp文件和.html文件之间的正确通信方面遇到了问题。
所以我有三个文件:一个是.cpp服务器,在消息到来之前创建管道和阻塞,.php文件打开管道并在其中写入内容和.html文件,它只有一个按钮,正在运行脚本。
有什么不寻常的是,当我运行我的服务器然后从控制台运行php脚本时,一切都运行正常,但如果我想通过浏览器和html页面进行 - 管道无法打开。
Php和html文件放在/ var / www / html / catalog中,我的cpp文件放在我的主文件夹中。
我正在尝试在/ tmp /文件夹中创建管道。
我尝试将chmod和chown权限更改为这两个路径(我知道apache = www-data)但是现在无济于事。我有100%没有安装SELinux。
我真的很感激任何帮助,我现在已经试图解决这个问题好几个小时......
server.cpp
#include <stdlib.h>
#include <unistd.h>
#include <iostream>
#include <cstring>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
using namespace std;
const char MSG_LENGTH = 9;
string FIFO_1 = "/tmp/fifo";
int main() {
if ( mkfifo(FIFO_1.c_str(), S_IFIFO | 0666 ) == -1 ) {
cout << "Cannot create fifo" << endl;
return 1;
}
cout << "Fifo created" << endl;
int readfd = open(FIFO_1.c_str(), O_RDONLY);
if ( readfd < 0 ) {
cout << "Cannot open fifo" << endl;
return 1;
}
char buffer[1024];
if ( read(readfd, buffer, MSG_LENGTH) < 1 ) {
cout << "Cannot read from fifo" << endl;
return 1;
}
buffer[MSG_LENGTH] = '\0';
cout << "Message: " << buffer << endl;
close(readfd);
unlink(FIFO_1.c_str());
return 0;
}
function.php
<?php
$pipe_name = '/tmp/fifo';
$msg = "message";
$pipe = fopen($pipe_name, 'w');
if ( $pipe == false)
echo "Cannot open fifo";
if ( fwrite($pipe, $msg) == false )
echo 'Cannot write to fifo';
else
echo 'Can write to fifo';
?>
答案 0 :(得分:0)
我正在运行的代码:
#include <stdlib.h>
#include <unistd.h>
#include <iostream>
#include <string>
#include <cstring>
#include <ctime>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
using namespace std;
string FIFO_1 = "/blah/fifo";
int main() {
if ( mkfifo(FIFO_1.c_str(), S_IFIFO | 0666 ) == -1 ) {
cout << "Cannot create fifo" << endl;
// return 1;
}
else
{
cout << "Fifo created" << endl;
}
int readfd = open(FIFO_1.c_str(), O_WRONLY);
if ( readfd < 0 ) {
cout << "Cannot open fifo" << endl;
return 1;
}
int count = 0;
for(;;)
{
count++;
cout << "Sending message " << count << endl;
time_t t = time(NULL);
string msg = ctime(&t);
if ( write(readfd, msg.c_str(), msg.length()) < 1 ) {
cout << "Cannot write to fifo" << endl;
return 1;
}
sleep(1);
}
close(readfd);
// unlink(FIFO_1.c_str());
return 0;
}
PHP代码:
<?php
$pipe_name = '/blah/fifo';
$msg = "";
$pipe = fopen($pipe_name, 'r');
if ( $pipe == false)
{
echo "Cannot open fifo<br/>";
$err = error_get_last();
var_dump($err);
}
else
{
$count = 0;
$data = stream_get_meta_data($pipe);
var_dump($data);
echo "<br/>";
echo date("Y-M-d H:i:s") . "<br/>";
echo "Waiting for message:";
while(1)
{
$msg = fgets($pipe, 30);
$err = error_get_last();
if ($err)
{
echo "Err = "; var_dump($err); echo "<br/>";
}
else
{
echo "Got = " . $msg . "<br/>";
}
$count ++;
if ($count > 20)
{
break;
}
}
}
echo "<br/>Done...";
?>