代码如下,使用了共享内存,但是子线程的代码执行了两次,不明白为什么
#include #include #include #include #include #include #include //#include //#include 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=1this is father: *p=1=1opration *sp=5this is son: *sp=5=5this is son: *p=1=5opration *sp=5this is son: *sp=5=5this is son: *p=1=5 |