我有这个代码:
#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中的数字是否>、<或==自己的pid,然后分别写入shared_n 1、-1或0。
问题是,当我编译它时,它给出了以下输出: https://dl.dropboxusercontent.com/u/6701675/informatica/Istantanea%20-%2020062013%20-%2013%3A49%3A14.png
预先感谢您的帮助!
洛伦佐
最佳答案
这是Linux吗? Linux manpage说你需要链接 pthread 库。
gcc foo.c -o foo -pthread
关于c - 在进程(不是线程)中使用 semaphore.h,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17212976/