Ok, guys I know that I'm asking too much questions, it's just that I really want to understand how things work. So I have a little project:
Make a program in C which runs three processes (A,B,C), which use a common memory (buffer). Process A generates 50 random numbers and writes then into the buffer. Process B writes down every even number into file F1. Process C writes down every odd number into file F2.
So far I have this:
#include <stdio.h>
#include <stdlib.h>
#include <semaphore.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <sys/sem.h>
#include <time.h>
int ID;
int *buffer;
int SemId;
void SemGet(int n)
{
SemId = semget(IPC_PRIVATE, n, 0600);
if (SemId == -1) {
printf("error!\n");
exit(1);
}
}
int SemSetVal(int SemNum, int SemVal)
{
return semctl(SemId, SemNum, SETVAL, &SemVal);
}
int SemOp(int SemNum, int SemOp)
{
struct sembuf SemBuf;
SemBuf.sem_num = SemNum;
SemBuf.sem_op = SemOp;
SemBuf.sem_flg = 0;
return semop(SemId, & SemBuf, 1);
}
void SemRemove(void)
{
(void) semctl(SemId, 0, IPC_RMID, 0);
}
void erase()
{
(void) shmdt((char *) buffer);
(void) shmctl(ID, IPC_RMID, NULL);
exit(0);
}
void process_A();
void process_B();
void process_C();
int main()
{
ID = shmget(IPC_PRIVATE,sizeof(int)*100,0600);
buffer = shmat(ID,NULL,0);
SemGet(2);
SemSetVal(0,0);
SemSetVal(1,0);
int i = 0;
if(fork()==0){
process_A();
}
if(fork()==0){
process_B();
}
if(fork()==0){
process_C();
}
wait(NULL);
wait(NULL);
wait(NULL);
erase();
SemRemove();
}
void process_A(){
srand((unsigned)(time(NULL)));
int i = 0;
for(i = 0; i < 50; i++){
buffer[i] = rand();
SemOp(0,1);
SemOp(1,1);
}
SemOp(0,1);
SemOp(1,1);
exit(0);
}
void process_B(){
FILE *F1 = fopen("F1.txt","w");
int i = 0;
while(i < 50){
SemOp(0,-1);
if(buffer[i]%2 == 1)
fprintf(F1,"%d: %d\n",i,buffer[i]);
i++;
}
fclose(F1);
exit(0);
}
void process_C(){
FILE *F2 = fopen("F2.txt","w");
int i = 0;
while(i < 50){
SemOp(1,-1);
if(buffer[i]%2 == 0)
fprintf(F2,"%d: %d\n",i,buffer[i]);
i++;
}
fclose(F2);
exit(0);
}
And the problem is:
It says:
In function 'main'
on line 49:
'fork' undeclared (first use in this function)
(Each undeclared identifier is reported only once for each function it appears in)
So I've tried somehow to "declare" it, but no sucess by now.
Any ideas?