意外令牌附近的语法错误'('

And*_*OSU -2 c c++ unix named-pipes

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

./server.cpp: line 8: syntax error near unexpected token '('
./server.cpp: line 8: 'void test()'
Run Code Online (Sandbox Code Playgroud)

导致此错误的原因是什么?我对unix或命名管道没有多少经验,所以我有点难过.

这是我的代码

client.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; 
}
Run Code Online (Sandbox Code Playgroud)

server.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);
}
Run Code Online (Sandbox Code Playgroud)

Joh*_*ica 5

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

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

g++ -Wall -o server server.cpp
Run Code Online (Sandbox Code Playgroud)

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

system("./server");
Run Code Online (Sandbox Code Playgroud)