我使用nanomsg进行请求/接收,当我使用Makefile编译它时,我的代码工作得很好。但是当我尝试使用cmake时,它编译得很好但在尝试发送消息时会遇到Segmentation Fault。
有谁知道发生了什么?我也不确定问题是在我的cmake文件中还是在.cc文件中。
这是一个最小的工作示例。
request.cc(这里省略了.h文件)
Requester::Requester(const char* url) {
int socket = nn_socket(AF_SP, NN_REQ);
assert(socket >= 0);
assert(nn_connect (socket, url) >= 0);
}
Requester::~Requester() {
nn_shutdown(socket, 0);
}
const char* Requester::request_for_sentence(const char* sentence){
int size_sentence = strlen(sentence) + 1;
int bytes = nn_send(socket, sentence, size_sentence, 0); # segmentation fault occurs here
assert(bytes == size_sentence);
char *buf = NULL;
bytes = nn_recv(socket, &buf, NN_MSG, 0);
assert(bytes >= 0);
printf("REQUESTER RECEIVED %s\n", buf);
return buf;
}
request_test.cc
int main(int argc, char** argv) {
extractor::Requester my_requester("ipc:///tmp/extractor.ipc");
const char* output = my_requester.request_for_sentence("some input");
cerr << "output: " << output << endl;
return 0;
}
receiver.cc
int main(int argc, char** argv) {
const char* url = "ipc:///tmp/extractor.ipc";
int socket = nn_socket (AF_SP, NN_REP);
assert(socket >= 0);
assert(nn_bind (socket, url) >= 0);
while(1){
char *buf = NULL;
int bytes = nn_recv(socket, &buf, NN_MSG, 0);
assert (bytes >= 0);
const char* grammar_for_sentence = extract_for_sentence(buf);
cerr << grammar_for_sentence << endl;
int size_grammar = strlen(grammar_for_sentence) + 1; // '\0' too
bytes = nn_send(socket, grammar_for_sentence, size_grammar, 0);
assert(bytes == size_grammar);
nn_freemsg (buf);
}
return 0;
}
Makefile有效:
CC=g++
CFLAGS = -L$HOME/opt/lib -I$HOME/opt/include -lnanomsg
all : run_test run_extract_daemon
run_test : extract_request_test.cc extract_request.o
$(CC) $(CFLAGS) -o run_test extract_request_test.cc extract_request.o -I.
run_extract_daemon : extract_daemon.cc
$(CC) $(CFLAGS) -o run_extract_daemon extract_daemon.cc
extract_request.o : extract_request.cc extract_request.h
$(CC) $(CFLAGS) -c extract_request.cc
clean :
rm run_test run_extract_daemon extract_request.o
不起作用的CMakeLists.txt:
find_package(nanomsg)
if(NANOMSG_FOUND)
include_directories(${NANOMSG_INCLUDE_DIR})
set(extract_request_test_SRCS extract_request_test.cc)
add_executable(run_extractor_request_test ${extract_request_test_SRCS})
target_link_libraries(run_extractor_request_test extractor ${NANOMSG_LIBRARIES})
set(extract_daemon_SRCS extract_daemon.cc)
add_executable(run_daemon ${extract_daemon_SRCS})
target_link_libraries(run_daemon extractor ${NANOMSG_LIBRARIES})
endif(NANOMSG_FOUND)
set(extractor_STAT_SRCS
extract_request.cc
extract_request.h)
add_library(extractor STATIC ${extractor_STAT_SRCS})