代码如下,使用了共享内存,但是子线程的代码执行了两次,不明白为什么
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <sys/wait.h>
#include <stdlib.h>
//#include <sys/signal.h>
//#include <stdlib.h>
int main()
{
key_t key;
key = ftok("/tmp", 55);
int size = getpagesize();
int shmid = shmget(key, size, IPC_CREAT|00777);
if(shmid < 0)
{
printf("shmget error\n");
return -1;
}
int *p = (int *)shmat(shmid, NULL, 0);
*p = 1;
printf("\nopration *p=1\nthis is father: *p=1=%d\n", *p);
pid_t pid = fork();
if(pid == 0);
{
int *sp = (int *)shmat(shmid, NULL, 0);
*sp = 5;
printf("\nopration *sp=5\nthis is son: *sp=5=%d\n", *sp);
printf("this is son: *p=1=%d\n", *p);
}
wait(NULL);
return 0;
}输出结果如下:
opration *p=1 this is father: *p=1=1 opration *sp=5 this is son: *sp=5=5 this is son: *p=1=5 opration *sp=5 this is son: *sp=5=5 this is son: *p=1=5
你想象不到我有多执着
遥不可及不放弃