【发布时间】:2015-11-26 21:16:53
【问题描述】:
我的代码的目的是执行两个子进程并增加一个共享变量计数器。每个进程都应将其增加 100 万。 这是我的代码:
#include <stdio.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
typedef struct
{
int value;
} shared_mem;
shared_mem *counter;
//these next two processes are the ones that increment the counter
process1()
{
int i=0;
for(i=0;i<1000000;i++)
counter->value++;
}
process2()
{
int i=0;
for(i=0;i<1000000;i++)
counter->value++;
}
/* The Main Body */
main()
{
key_t key = IPC_PRIVATE; /* shared memory key */
int shmid; /* shared memory ID */
shared_mem *shmat1;
int pid1; /* process id for child1 */
int pid2; /* process id for child2 */
/* attempts to attach to an existing memory segment */
if (( shmid = shmget(key, sizeof(int), IPC_CREAT | 0666)) < 0)
{
perror("shmget");
return(1);
}
/*attempts the shared memory segment */
if((counter = (shared_mem *)shmat(shmid, NULL, 0)) == (shared_mem *) -1)
{
perror("shmat");
return(1);
}
/*initializing shared memory to 0 */
counter->value = 0;
pid1=fork();
/* fork process one here */
if(pid1==0)
{
printf("I am child 1 with PID %d\n", getpid());
process1();
}
else
{
pid2=fork();
if(pid2==0)
{
printf("I am child 2 with PID %d\n", getpid());
process2();
}
else
{
wait(NULL);
printf("I am parent with PID %d\n", getpid());
printf("Total counter value is: %d\n", counter->value);
}
}
/*deallocate shared memory */
if(shmctl(shmid, IPC_RMID, (struct shmid_ds *)0)== -1)
{
perror("shmctl");
return(-1);
}
return(0);
}
计数器输出在100万左右徘徊,但它不应该在200万左右徘徊吗?我想我不了解流程增量的方式。提前非常感谢,如果代码太长,我深表歉意,但我不确定我可以包含哪些内容以及我可以排除哪些内容。
【问题讨论】:
标签: c unix fork parent-child increment