代碼如下,使用了共享內(nèi)存,但是子線程的代碼執(zhí)行了兩次,不明白為什么#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;
}輸出結(jié)果如下: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
子線程輸出語句輸出兩遍
你想象不到我有多執(zhí)著
2017-04-13 09:31:15