我有一个带有共享变量“counter”的多处理程序。父和子都改变了计数器的值,所以计数器的最终值必须是20,但它的类型总是为零而没有任何变化。我试图在很多方面定义“计数器”:作为没有共享内存的全局变量和我从父母和孩子得到1到10的结果,作为共享内存,我在很多地方定义它并且总是得到0。 任何人都可以告诉我为什么会这样吗?为什么计数器的值不是从1到20?我的代码中有错误吗?以及如何将DATASIZE更改为1MB或2 MB?
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
#include <errno.h>
#include <errno.h>
#include <sys/time.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#define SIZE1 sizeof(int)
#define DATASIZE (10<<20)
int *counter;
int main()
{
double A[200][200];
double B[200][200];
double C[200][200];
int i, j, k, m;
int outfile, result, count;
unsigned seed;
struct timeval before, after;
char *buff;
pid_t child_pid ,wpid;
int child_status,shmid1;
key_t key1=2222;
buff = (char *)malloc(sizeof(char)*(1<<20));
srandom(seed);
for (i=0; i<200; i++)
for (j=0; j<200; j++)
{
A[i][j] = random()/100.0;
B[i][j] = random()/100.0;
}
gettimeofday(&before, NULL);
/* counter = mmap(NULL, sizeof *counter, PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANONYMOUS, -1, 0);
*counter=1;*/
child_pid=fork();
shmid1 = shmget(key1, SIZE1, 0666 | IPC_CREAT);
counter = shmat(shmid1, NULL, 0);
*counter=1;
switch (child_pid)
{
case -1:
{
perror("\nfork failed\n");
exit(1);
}
case 0:
{
/* shmid1 = shmget(key1, SIZE1, 0666 | IPC_CREAT);
counter = shmat(shmid1, NULL, 0);*/
printf("\nIam the child ,\n");
for (m=0 ; m < 10; m++)
{
outfile = open("testfile", O_RDWR|O_CREAT|O_APPEND, 0777);
if (outfile <= 0)
perror("\nError opening file\n");
else
{
result = write(outfile, buff, DATASIZE);
if (result <= 0)
perror("\nError writing file\n");
}
close(outfile);
*counter++;
printf("\ncounter from child %d",*counter);
} // end of for
printf("\nI'm the Son, and exiting with status %d \n",child_status );
exit(0);
} // end of case 0
default: // parent process - returns child ID
{
/*shmid1 = shmget(key1, SIZE1, 0666 | IPC_CREAT);
counter = shmat(shmid1, NULL, 0);*/
printf("\nIam the parent, my child process %d is \n",child_pid);
for (m=0 ; m < 10; m++)
{
for (i=0; i<200; i++)
for (j=0; j<200; j++)
{
C[i][j] = 0;
for (k=0; k<200; k++)
C[i][j] += A[i][k]*B[k][j];
}
*counter++;
printf("\ncounter from parent %d",*counter);
}// end of for
printf("\nIam the parent, My child process ID = %d \n",child_pid);
}//end of default
waitpid(child_pid,&child_status,0);
}//end of switch
//shmdt(counter);
free(buff);
gettimeofday(&after, NULL);
count = (after.tv_sec - before.tv_sec) * 1e6;
count += (after.tv_usec - before.tv_usec);
printf("Total time in usec: %d\n", count);
printf("\n multiprocessing end successfully ... \n");
return 0;
};