我有这段代码:
#include <stdio.h>
#include <unistd.h>
#include <semaphore.h>
#include <sys/shm.h>
#include <sys/stat.h>
#include <sys/types.h>
int main(){
int segment_n;
int segment_sem;
int *shared_n;
sem_t *shared_sem;
int pid_int;
pid_t pid;
segment_n = shmget(IPC_PRIVATE, sizeof(int), S_IRUSR | S_IWUSR);
segment_sem = shmget(IPC_PRIVATE, sizeof(sem_t), S_IRUSR | S_IWUSR);
shared_n = (int *)shmat(segment_n, NULL, 0);
shared_sem = (sem_t *)shmat(segment_sem, NULL, 0);
sem_init(shared_sem, 0, 0);
scanf("%d", shared_n);
pid = fork();
if(pid < 0){
return 1;
} else if(pid == 0){
pid_int = (int)getpid();
if(pid_int > *shared_n){
*shared_n = 1;
}else if(pid_int == *shared_n){
*shared_n = 0;
} else {
*shared_n = -1;
}
sem_post(shared_sem);
return 0;
} else {
sem_wait(shared_sem);
printf("returns: %d\n", *shared_n);
return 0;
}
return 0;
}
程序创建一个子进程,用于验证shared_n中的数字是否为&gt;,&lt;或= =他自己的pid,而不是分别在shared_n 1,-1或0中写入。
问题是,当我编译它时,它给了我这个输出: https://dl.dropboxusercontent.com/u/6701675/informatica/Istantanea%20-%2020062013%20-%2013%3A49%3A14.png
提前感谢您的帮助!
洛伦佐
答案 0 :(得分:0)
您必须使用-pthread链接文件
“gcc -pthread processi_esame.c -o processi”
答案 1 :(得分:0)
这是Linux吗? Linux manpage表示您需要与pthread库链接。
gcc foo.c -o foo -pthread