两个进程访问关键部分时出错

时间:2012-11-27 08:22:35

标签: c++ c fork

有人可以告诉我如何解决这个编译错误:

tarek.c: In function ‘main’:
tarek.c:33: warning: incompatible implicit declaration of built-in function ‘exit’
/tmp/ccAEGS6k.o: In function `main':
tarek.c:(.text+0x45): undefined reference to `pthread_mutexattr_init'
tarek.c:(.text+0x56): undefined reference to `pthread_mutexattr_setpshared'
collect2: ld returned 1 exit status

当我编译这个程序时(两个进程使用临界区共享相同的值):

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

int main () {

int stat;

pthread_mutex_t *mutex = (pthread_mutex_t*)mmap (0, sizeof (pthread_mutex_t) + sizeof (long),PROT_READ | PROT_WRITE,
                            MAP_SHARED ,-1, 0);

long *data = (long*)(&mutex[1]); /* map 'data' after mutex */
int pid;

pthread_mutexattr_t attr;
pthread_mutexattr_init (&attr);
pthread_mutexattr_setpshared (&attr, PTHREAD_PROCESS_SHARED);
pthread_mutex_init (mutex, &attr);

*data = 0;

pid = fork ();

pthread_mutex_lock (mutex);
(*data)++;
pthread_mutex_unlock (mutex);

if (!pid) /* child exits */
exit (0);
else
waitpid (pid, &stat, 0);
printf ("data is %ld\n", *data);

}

3 个答案:

答案 0 :(得分:3)

明确提及-pthread库。

这样编译:

gcc -Wall program.c -o program -pthread

它会解决你的问题

`tarek.c:(.text+0x45): undefined reference to `pthread_mutexattr_init'
tarek.c:(.text+0x56): undefined reference to `pthread_mutexattr_setpshared'`

exit()包括#include <stdlib.h>

waitpid()包括#include <sys/wait.h>

了解更多man exit()man waitpid()

答案 1 :(得分:1)

在链接命令

中构建添加-lpthread
gcc -o program program.c -lpthread

答案 2 :(得分:1)

要解决exit()

所需的#include <stdlib.h>错误