我写了一个简单的c程序。使用共享内存和信号量。当我编译程序服务器时,clang lsp警告shamt is invalid in c99
。c
Undefined symbols for architecture x86_64:
"_shamt", referenced from:
_main in server-214a3e.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
但是我在server.c中有主要功能
代码如下:
#include <assert.h>
#include <errno.h>
#include <pthread.h>
#include <semaphore.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/shm.h>
#include <sys/sem.h>
#include <time.h>
#include <unistd.h>
#include <sys/ipc.h>
#include <sys/stat.h>
#include <fcntl.h>
#define MSG_MAX_SIZE 4096
char *server_memory, *client_memory;
sem_t *sig_server, *sig_client;
char message_client[MSG_MAX_SIZE];
char message_server[MSG_MAX_SIZE];
key_t generate_key(int ID) {
key_t res;
if ((res = ftok("/tmp", 'C')) == -1) {
perror("ftok faild ");
exit(1);
}
return res;
}
int get_shm_id(key_t key) {
int res = shmget(key, sizeof(char) * MSG_MAX_SIZE, IPC_CREAT | 0666);
if (res == -1) {
perror("server: Failed to open/creat share memory");
exit(2);
}
return res;
}
int main() {
key_t key_client = generate_key('C');
key_t key_server = generate_key('S');
int shm_server_id = get_shm_id(key_server);
int shm_client_id = get_shm_id(key_client);
server_memory = shamt(shm_server_id, (void *)0, 0);
client_memory = shamt(shm_client_id, (void *)0, 0);
sig_server =
sem_open("/tmp/signal_server", O_CREAT | 0666, S_IRUSR | S_IWUSR, 1);
sig_client =
sem_open("/tmp/signal_client", O_CREAT | 0666, S_IRUSR | S_IWUSR, 1);
while (1) {
printf("enter message,enter q to quit,enter p to pass input\n");
fgets(message_server, MSG_MAX_SIZE, stdin);
if (message_server[0] == 'q') {
// :TODO
exit(0);
} else if (message_server[0] != 'p') {
sem_wait(sig_client);
strcpy(client_memory, message_server);
sem_post(sig_client);
}
if (sem_trywait(sig_server) == -1) {
printf("The client is typing\n");
printf("enter r to reply and or w to wait The other party:");
char c = getchar();
if (c == 'w') {
sem_wait(sig_server);
} else if (c == 'r') {
continue;
} else {
// :TODO
}
}
strcpy(message_client, server_memory);
sem_post(sig_server);
printf("message recived:%s\n", message_client);
}
return 0;
}
我也尝试在Ubuntu 18.04上编译代码,但是编译时出现了更多错误。
/tmp/ccrxmeXg.o: In function `main':
server.c:(.text+0xd5): undefined reference to `shamt'
server.c:(.text+0xf7): undefined reference to `shamt'
server.c:(.text+0x11e): undefined reference to `sem_open'
server.c:(.text+0x143): undefined reference to `sem_open'
server.c:(.text+0x19c): undefined reference to `sem_wait'
server.c:(.text+0x1bf): undefined reference to `sem_post'
server.c:(.text+0x1ce): undefined reference to `sem_trywait'
server.c:(.text+0x209): undefined reference to `sem_wait'
server.c:(.text+0x234): undefined reference to `sem_post'
collect2: error: ld returned 1 exit status
那么如何解决这个问题。我想在Mac OS以及Ubuntu上运行此程序。
请帮助我!