msg.c
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<unistd.h>
#include<sys/ipc.h>
#include<sys/shm.h>
#include<sys/types.h>
int main(int argc,char *argv[])
{
int shmsid;
pid_t pid;
key_t key;
char *addr;
//creat shm
key = IPC_PRIVATE;
shmsid = shmget(key,1024,IPC_CREAT|0660);
if(shmsid < 0)
{
perror("shmget");
return -1;
}
addr = (char *)shmat(shmsid,NULL,0);
/*if(addr = (char*)(-1))
{
perror("shmat");
return -1;
}*/
printf("create share memeory add :%08x\n",addr);
strcpy(addr,"this is share memory");
pid = fork();
if(pid < 0)
{
perror("fork");
return -1;
}
if(pid == 0)
{
printf("here is child process,read shm:%s\n",addr);
}
else
{
wait(NULL);
printf("here is parent process,read shm:%s\n",addr);
system("ipcs -m");
//delete shm
if(shmdt(addr) < 0)
{
perror("shmdt");
return -1;
}
if(shmctl(shmsid,IPC_RMID,NULL) < 0)
{
perror("shmctl");
return -1;
}
printf("delete sucess\n");
}
return 0;
}
pipe.c
#include<stdio.h>
#include<unistd.h>
#include<string.h>
#include<stdlib.h>
#define MAX_SIZE 128
int main(int argc,char *argv[])
{
int fd[2];
pid_t pid;
char message[MAX_SIZE];
memset(message,0,sizeof(message));
if(pipe(fd) < 0)
{
perror("pipe");
return -1;
}
pid = fork();
if(pid < 0)
{
perror("fork");
return -1;
}
if(pid == 0)
{
close(fd[0]);
printf("Here is Child Process,wile be written\n");
write(fd[1],"I'm child!!",15);
}
else
{
close(fd[1]);
printf("Here is Parent Process ,wile be read\n");
read(fd[0],message,15);
printf("message = %s\n",message);
}
return 0;
}
sharemem.c
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<unistd.h>
#include<sys/ipc.h>
#include<sys/shm.h>
#include<sys/types.h>
int main(int argc,char *argv[])
{
int shmsid;
pid_t pid;
key_t key;
char *addr;
//creat shm
key = IPC_PRIVATE;
shmsid = shmget(key,1024,IPC_CREAT|0660);
if(shmsid < 0)
{
perror("shmget");
return -1;
}
addr = (char *)shmat(shmsid,NULL,0);
/*if(addr = (char*)(-1))
{
perror("shmat");
return -1;
}*/
printf("create share memeory add :%08x\n",addr);
strcpy(addr,"this is share memory");
pid = fork();
if(pid < 0)
{
perror("fork");
return -1;
}
if(pid == 0)
{
printf("here is child process,read shm:%s\n",addr);
}
else
{
wait(NULL);
printf("here is parent process,read shm:%s\n",addr);
system("ipcs -m");
//delete shm
if(shmdt(addr) < 0)
{
perror("shmdt");
return -1;
}
if(shmctl(shmsid,IPC_RMID,NULL) < 0)
{
perror("shmctl");
return -1;
}
printf("delete sucess\n");
}
return 0;
}