我一周前开始理解和使用信号量和共享内存,并实际创建了这个程序;问题是我找不到任何问题。我已经看了几个小时了,一切似乎都是正确的。代码编译后我可以创建构建,但是当我执行它时什么也没有发生。
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <stdio.h>
#include <sys/fcntl.h>
#include <semaphore.h>
#define MAXCHILDS 4
#define MAX_SIZE 10
#define MAX_WRITES 4
typedef struct{
int m[MAX_SIZE][MAX_SIZE];
} matrix;
/*fork variables*/
pid_t child[MAXCHILDS];
/*semphores variables */
sem_t *empty, *full, * mutex;
/*share memory id*/
int shmid;
/*shared memory array pointer */
matrix * sh_mem;
/*pointer to matrix*/
int **p;
void init(){
/*create pointer to matrix*/
p = &sh_mem->m;
/*semaphores unlink and creation */
sem_unlink("EMPTY");
empty=sem_open("EMPTY",O_CREAT|O_EXCL,0700,MAX_WRITES);
sem_unlink("FULL");
full=sem_open("FULL",O_CREAT|O_EXCL,0700,0);
sem_unlink("MUTEX");
mutex=sem_open("MUTEX",O_CREAT|O_EXCL,0700,1);
/*initialize shared memory */
shmid = shmget(IPC_PRIVATE,sizeof(matrix),IPC_CREAT|0777);
/*map shared memory*/
sh_mem = (matrix*)shmat(shmid,NULL,0);
if(sh_mem== (matrix*)(-1)){
perror("shmat");
}
}
void writer(int ** m){
int i,k;
for(i = 0;i<MAX_SIZE;i++){
for(k= 0;k<MAX_SIZE;k++){
m[i][k] = 0;
}
}
}
void reader(int **m){
int i = 0;
int k = 0;
for(i = 0;i<MAX_SIZE;i++){
for(k= 0;k<MAX_SIZE;k++){
printf(m[i][k]);
}
printf("\n");
}
}
void terminate() {
sem_close(empty);
sem_close(full);
sem_close(mutex);
sem_unlink("EMPTY");
sem_unlink("FULL");
sem_unlink("MUTEX");
shmctl(shmid, IPC_RMID, NULL);
}
int main(int argc, char **argv)
{
int i;
init();
for(i = 0;i<MAXCHILDS;i++){
if ((child[i] = fork()) < 0) // error occured
{
perror("Fork Failed");
exit(1);
}
if ((child[i] = fork())==0){
writer(sh_mem->m);
exit(0);
}
}
/*father*/
reader(sh_mem->m);
wait(NULL);
terminate();
return 0;
}
children 应该在共享内存中写入矩阵,而父亲应该读取共享内存数组并打印矩阵。 你能帮我解决这个问题吗?感谢您的帮助...
最佳答案
这里的主要错误是 reader
和writer
采用与传递给它们不同类型的参数,如 gcc -Wall
指出:
test.c: In function ‘main’:
test.c:92:13: warning: passing argument 1 of ‘writer’ from incompatible pointer type [enabled by default]
test.c:49:6: note: expected ‘int **’ but argument is of type ‘int (*)[10]’
test.c:97:5: warning: passing argument 1 of ‘reader’ from incompatible pointer type [enabled by default]
test.c:58:6: note: expected ‘int **’ but argument is of type ‘int (*)[10]’
正如所提供的,程序在父进程和每个子进程中都出现了段错误。当我更改 reader
的参数类型时和writer
来自int **m
至int m[MAX_SIZE][MAX_SIZE]
(以及下面的修复),据我所知,程序成功运行。
还有一些其他错误:
- 您需要
#include <sys/wait.h>
. - 全局
int **p
未使用,其初始化具有与读取器和写入器函数相同的类型错误。 printf
调用reader
需要一个格式字符串;我用过"%d "
.- 正如 Jonathan Leffler 指出的那样,您需要调用
fork()
每次仅通过main
中的循环一次.
除了最后一个之外,所有这些都被编译器警告突出显示。
在研究这个程序失败的原因时,我还使用了 strace -f
以确定哪些系统调用和进程实际上被破坏。例如,与信号量相关的系统调用似乎成功返回——尽管正如 Jonathan 指出的那样,您应该检查它们的返回值是否有错误,因为尽早失败可以更轻松地调试问题。
关于c - C 中的 UNIX 共享内存和信号量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13224357/