代码: 全选
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#define MSGKEY 75
struct msgform
{ long mtype;
char mtext[256];
};
main(int argc,char *argv[])
{ struct msgform msg;
int msgqid, pid, *pint;
msgqid = msgget(MSGKEY,0777|IPC_CREAT);
printf("msgqid = %d\n\n",msgqid);
pid = getpid();
pint = (int *)msg.mtext;
*pint = pid;
msg.mtype = 1;
msgsnd(msgqid,&msg,sizeof(int),0);
msgrcv(msgqid,(struct msgform *)&msg,sizeof(msg),pid,0);
pint = (int*)msg.mtext;
pid = (int)*pint;
printf("Client %s: receive from Server process %d\n",argv[1],pid);
}
代码: 全选
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#define MSGKEY 75
struct msgform
{ long mtype;
char mtext[256];
};
int msgqid;
main()
{ struct msgform msg;
int i,*pint;
int pid;
extern cleanup();
for (i=0;i<20;i++)
signal(i,cleanup);
msgqid = msgget(MSGKEY,0777|IPC_CREAT);
printf("msgqid = %d\n\n",msgqid);
for(;;)
{
msgrcv(msgqid,(struct msgform *)&msg,256,1,0);
pint = (int *)msg.mtext;
pid = (int)*pint;
printf("Server : receive from Client process %d \n\n",pid);
msg.mtype = pid;
pint = (int *)msg.mtext;
*pint = getpid();
msgsnd(msgqid,&msg,sizeof(int),0);
}
}
cleanup()
{ msgctl(msgqid,IPC_RMID,0);
exit(0);
}
代码: 全选
#include <sys/types.h>
#include <stdio.h>
#include <unistd.h>
main()
{ int pid1,pid2,pid3;
pid1 = vfork();
if (pid1 == 0)
{ printf("\nClient1 process %4d :\n",getpid());
execlp("/home/student/client","client","1",NULL);
}
else
{ pid2 = vfork();
if (pid2 == 0)
{ printf("Client2 process %4d:\n",getpid());
execlp("/home/student/client","client","2",NULL);
}
else
{ pid3 = vfork();
if (pid3 == 0)
{ printf("Server3 process %4d:\n",getpid());
execlp("/home/student/server","server",NULL);
}
else
printf("\nThis is Parent process %4d ! \n\n",getpid());
}
}
wait(0);
wait(0);
wait(0);
}
:
Client1 process 18814 :
Client2 process 18815:
msg: cxa_atexit.c
Aborted
上机的时候(redhat):
[student@localhost ~]$ ./msg
Client1 process 19083 :
msgqid = 65536
Client2 process 19084:
msgqid = 65536
Server3 process 19085:
This is Parent process 19082 !
msgqid = 65536
Server : receive from Client process 4788
Server : receive from Client process 19083
Client 1: receive from Server process 19085
Server : receive from Client process 19084
Client 2: receive from Server process 19085
这是为什么呢?
