- 论坛徽章:
- 0
|
我写了一个生产者程序,一个消费者程序,然后主进程execv出来三个生产者进程,三个消费者进程。但是不太稳定,有时候消费者进程总不能退出
a wrong operation to semaphore occurred!: Invalid argument
还产生以上的错误,高手帮忙看看。
代码如下:
主程序:
#include"sharemem.h"
#define ARR_SIZE 20
int
main ()
{
//创建并初始化信号量
int emptyid, fullid, mutex;
if (((emptyid = createsem (".", 'e', 1, B_SIZE)) == -1)
|| ((fullid = createsem (".", 'f', 1, 0)) == -1)
|| ((mutex = createsem (".", 'u', 1, 1)) == -1))
exit (1);
//创建共享内存
char *array, *set, *get;
int arrid, setid, getid;
arrid = createshm (".", 'h', sizeof (int) * ARR_SIZE);
array = shmat (arrid, NULL, 0666);
setid = createshm (".", 's', B_SIZE);
set = shmat (setid, NULL, 0666);
getid = createshm (".", 'g', B_SIZE);
get = shmat (getid, NULL, 0666);
(*set) = 1;
(*get) = 1;
printf ("size1 %d \n", sizeof (int) * ARR_SIZE);
//创建子进程
int i, j;
printf ("请输入要创建生产者进程的个数:\n");
scanf ("%d", &i);
printf ("请输入要创建消费者进程的个数:\n");
scanf ("%d", &j);
int tempi, tempj;
int chld;
int producer[i], sumer[j];
for (tempi = 0; tempi < i; tempi++)
{
chld = vfork ();
if (chld == 0)
execv ("producer", NULL);
else
{
producer[tempi] = chld;
printf ("这是producer主进程,产生生产者进程 %d \n", chld);
}
}
for (tempj = 0; tempj < j; tempj++)
{
chld = vfork ();
if (chld == 0)
execv ("sumer", NULL);
else
{
sumer[tempj] = chld;
printf ("这是sumer主进程,产生消费者进程 %d \n", chld);
}
int k;
for(k = 0; k < 6; k++)
{
k = wait (0);
printf("进程 %d 退出\n", k);
}
sleep (2);
printf ("子进程结束\n");
//关闭共享内存,信号量
shmdt (array);
shmdt (set);
shmdt (get);
shmctl (arrid, IPC_RMID, 0);
shmctl (setid, IPC_RMID, 0);
shmctl (getid, IPC_RMID, 0);
semctl (emptyid, IPC_RMID, 0);
semctl (fullid, IPC_RMID, 0);
semctl (mutex, IPC_RMID, 0);
printf ("父进程结束\n");
exit (0);
}
|
|
|