create_shm.c
#include <stdio.h>
#include <stdlib.h>
#include <sys/shm.h>
int main()
{ int shm_id;
shm_id = shmget(IPC_PRIVATE, 4096, 0666); // 6=110b(rw-)
if (shm_id < 0)
{
perror("shmget id < 0 ");
exit(0);
}
printf("Shared memory area successfully created:%d\n", shm_id);
system("ipcs -m");
}
write_shm.c
#include <stdio.h>
#include <sys/shm.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{ int shm_id;
char *shm_buf;
shm_id = atoi(argv[1]);
shm_buf=shmat(shm_id, 0, 0);
printf("write data to shared memory :\n");
sprintf (shm_buf, "write 123456abc into shared memory");
printf("%s \n", shm_buf);
}
read_shm.c
#include <stdio.h>
#include <sys/shm.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
int shm_id;
char *shm_buf, str[50];
shm_id = atoi(argv[1]);
shm_buf=shmat(shm_id, 0, 0);
printf("Read something from shared memory:\n");
sprintf(str, shm_buf);
printf("%s\n", str);
system("ipcs -m");
}
pipe.c
/*pipe.c*/
#include <unistd.h>
#include <signal.h>
#include <stdio.h>
int pid1,pid2;
main( )
{
int fd[2];
char outpipe[100],inpipe[100];
pipe(fd); /*creat a pipe*/
while ((pid1=fork( )) == -1) ;
if(pid1==0)
{
lockf(fd[1],1,0); //lock
sprintf(outpipe,"child 1 process is sending message!");
/*put the string into outpipe*/
write(fd[1],outpipe,50); /*write 50 bytes to outpipe*/
sleep(5); /*sleep 5 seconds*/
lockf(fd[1],0,0); //unlock
exit(0);
}
else
{
while((pid2=fork( ))==-1);
if(pid2==0)
{ lockf(fd[1],1,0); /*mutual*/
sprintf(outpipe,"child 2 process is sending message!");
write(fd[1],outpipe,50);
sleep(5);
lockf(fd[1],0,0); //unlock
exit(0);
}
else
{ wait(0); /*synchronization*/
read(fd[0],outpipe,50); /*read 50 bytes from inpipe*/
printf("%s\n",outpipe);
wait(0);
read(fd[0],outpipe,50);
printf("%s\n",outpipe);
exit(0);
}
}
}