share1.c

来自「linux下的共享文件范例程序」· C语言 代码 · 共 71 行

C
71
字号
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>


#define BUFSZ 2048 
int main()
{
	int shmid;
	char *shmadd,*a,b;
	pid_t pid,kid;

	if((shmid=shmget(IPC_PRIVATE,BUFSZ,0666))<0)
	{
		perror("shmget");
		exit(1);
	}
	else
		printf("created shared-memory: %d\n",shmid);

	if((shmadd=shmat(shmid, 0,0))<(char *)0){
		perror("shmat");
		exit(1);
	}	
	else
		printf("attached shared-memory\n");


		pid=fork();

	

	


	if ( pid == -1 ){
		perror("pid fork");
		exit(1);
	}

	else if( pid > 0 ){
		a=strcpy(shmadd,"hello");
//		printf("read %s \n",shmadd);
		sleep(1);

	}
	else
	{	
		
		sleep(2);
		printf("read %s \n", shmadd);
			if((shmdt(shmadd))<0){
				perror("shmdt");
				exit(1);
			}
			else
			printf("deleted shared-memory\n");
	
		exit(0);

	
	}


}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?