c++ - 意外标记附近出现语法错误 '('

标签 c++ c unix named-pipes

我正在unix上用c++做一些工作。我正在尝试在两个程序之间创建一个命名管道,并在它们之间来回发送一些文本。一切都编译得很好,但是当我进行系统调用来运行 server.cpp 时,我收到此错误消息。

./server.cpp: line 8: syntax error near unexpected token '('
./server.cpp: line 8: 'void test()'

是什么导致了这个错误?我对 UNIX 或命名管道没有太多经验,所以我有点困惑。

这是我的代码

客户端.cpp

#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>

int main()
{
   int fd;

   mkfifo("home/damil/myPipe", 0666);

   fd=open("home/damil/myPipe", O_WRONLY);
   write(fd,"test", sizeof("test")+1);

   system("./server.cpp");
   close(fd);

   return 1; 
}

服务器.cpp

#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>

void test()
{
   int fd;
   char * comm;

   fd = open("home/damil/myPipe", O_RDONLY);   
   read(fd, comm, 1024);
   printf(comm);
   close(fd);
}

最佳答案

这不是 C++ 错误,而是 UNIX 错误。通过运行 system("./server.cpp") 您将尝试运行 .cpp 文件,就好像它是已编译的可执行文件一样。系统认为它是一个 shell 脚本,并在它越过 #include 时立即遇到语法错误(在 shell 中,它被解析为注释,因此被忽略)。

您需要编译server.cpp并运行生成的二进制文件。 (注意:您可能需要将 test() 重命名为 main()。)

g++ -Wall -o server server.cpp

然后在client.cpp中,将系统调用更改为:

system("./server");

关于c++ - 意外标记附近出现语法错误 '(',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21688749/

相关文章:

c++ - 在窗口未激活时获取输入 (Windows)

c++ - 如何使用指针修改 vector

c++ - 匹配 'max'的 'std::function<const int &(const int &, const int &)>'没有重载

c - 在 NUMA 架构中按线程移动内存页

c - 以下代码如何使 PC 发出蜂鸣声?

c - 不使用在另一台机器上工作的代码接收多播数据

c++ - 在运行时创建自定义事件

c - 带有指针变量的地址数组

c - unix DECLARE_WAIT_QUEUE_HEAD (var) var 原型(prototype)?

linux - 系统调用与系统程序