我正在使用c ++在unix中做一些工作。我试图在我的两个程序之间创建一个命名管道,并在它们之间来回发送一些文本。一切编译都很好,但当我调用我的系统运行server.cpp时,我收到此错误消息。
./server.cpp: line 8: syntax error near unexpected token '('
./server.cpp: line 8: 'void test()'
导致此错误的原因是什么?我对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;
}
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);
}
答案 0 :(得分:5)
这不是C ++错误,而是UNIX错误。通过运行system("./server.cpp")
,您尝试运行.cpp
文件,就像它是已编译的可执行文件一样。系统认为它是一个shell脚本,并且一旦超过#include
(在shell中被解析为注释,因此被忽略)就会遇到语法错误。
您需要编译server.cpp
并运行生成的二进制文件。 (注意:您可能希望将test()
重命名为main()
。)
g++ -Wall -o server server.cpp
然后在client.cpp
中,将系统调用更改为:
system("./server");