7.메모리,파이프,시그널

7-1 메모리기본

ex)

#include <stdio.h>

#include <stdlib.h>

int main()

{

char *p;

p=(char *)malloc(80);

strcpy(p,"this is test");

printf("%s\n",p);

p=(char *)realloc(p,200);

printf("%s\n",p);

strcat(p,"another block");

printf("%s\n",p);

free(p);

return 1;

}

출력

this is test

this is test

this is testanother block

7-2 메모리 맵파일

ex)

#include <sys/mman.h>

#include <asm/io.h>

#include <sys/types.h>

#include <sys/stat.h>

#include <fcntl.h>

#include <unistd.h>

#include <stdlib.h>

#include <stdio.h>

#include <string.h>

int main()

{

int vhandle;

char *mp;

char *sp;

char data[80];

vhandle=open("/dev/mem", O_RDWR);

mp = (char *)mmap(0, 1000000, PROT_WRITE|PROT_READ, MAP_SHARED, vhandle, 0x8000000);

sp=mp;

memset(sp, 0, 1000000);

strcpy(data,"another test");

memcpy(sp,data,80);

sprintf(data,"this is test");

printf("first data value =%s\n",data);

sp=mp;

memcpy(data,mp,80);

printf("%s\n",data);

munmap(0,1000000);

return 1;

}

7-3 파이프의 개요

ex)

#include <unistd.h>

#include <stdlib.h>

#include <stdio.h>

#include <string.h>

int main()

{

FILE *out;

char buffer[BUFSIZ+1];

int readsize;

memset(buffer,0,sizeof(buffer));

out=popen("ps -ax","r");

if(out != NULL)

{

readsize = fread(buffer,sizeof(char),BUFSIZ,out);

if(readsize > 0)

{

printf("Output was:-\n%s\n",buffer);

}

pclose(out);

return 1;

}

return 0;

}

파이프 출력하기 만들어 보기

7-4 시그널

ex)  시그널 가로채기

#include <signal.h>

#include <stdio.h>

#include <unistd.h>

void checksig(int s)

{

printf("the signal is %d",s);

(void) signal(SIGINT,SIG_DFL);

}

int main()

{

int i;

(void)signal(SIGINT,checksig);

while(1)

{

printf("count ",i);

sleep(1);

}

}

ex) 안전한 시그럴 가로채기

#include <signal.h>

#include <stdio.h>

#include <unistd.h>

void checksig(int s)

{

printf("the signal is %d",s);

}

int main()

{

struct sigaction act;

act.sa_handler =checksig;

sigemptyset(&act.sa_mask);

act.sa_flags =0;

sigaction(SIGINT,&act,0);

while(1){

printf("Hello ");

sleep(1);

}

}

ex)알람 예제

#include <sys/types.h>

#include <signal.h>

#include <stdio.h>

#include <unistd.h>

static int alarm_fired =0;

void ding(int sig)

{

alarm_fired =1;

}

int main()

{

pid_t pid;

printf("alarm application starting\n");

pid=fork();

switch(pid){

case -1:

perror("fork failed");

exit(1);

case 0:

sleep(5);

kill(getppid(),SIGALRM);

exit(0);

}

printf("waiting for alarm to go off\n");

(void)signal(SIGALRM,ding);

pause();

if(alarm_fired)printf("Ding!\n");

printf("done\n");

return 1;

}