1.P0SIX信号量,用信号捕捉ctrl+c,去执行关闭信号量,删除信号
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <sys/msg.h>
#include <sys/sem.h>
#include <semaphore.h>
#include <signal.h>
//定义一个函数规定怎么去处理信号
void func(int a,sem_t* space)
{
sem_close(space);
sem_unlink("/my_spsce");
}
int main()
{
key_t key = ftok("./",2);
//创建共享内存的IPC对象
int shmid = shmget(key, 2,IPC_CREAT | 0666);//共享内存的大小必须是偶数,实际上在本代码中只需要1个
//创建有名信号量并初始化
sem_t *space = sem_open("/my_spsce", O_CREAT,0666, 1);
sem_t *data = sem_open("/my_data", O_CREAT,0666, 0);
char *p = shmat(shmid, NULL, 0);//映射
char *msg = "0123456789";
int i = 0;
//挖个坑
signal(SIGINT,SIG_IGN);//注册信号处理函数
printf("我的进程号是%d\n",getpid());
while(1)
{
sleep(1);
printf("%d\n",i);
i++;
}
}
2.用线程改写jack和rose管道,做到同时双向通信
#include <sys/types.h>
#include <sys/wait.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <sys/shm.h>
#include <sys/sem.h>
#include <semaphore.h>
#define JK_TO_RS "/home/ubuntu/JK_TO_RS"
#define RS_TO_JK "/home/ubuntu/RS_TO_JK"
char *RSTOJK_buf;
int RSTOJK_fd;
void *t1(void *argv)
{
char*
while(1)
{
memset(RSTOJK_buf,0,100);
read(RSTOJK_fd,RSTOJK_buf,100);
printf("rose:%s\n",RSTOJK_buf);
if(strcmp(RSTOJK_buf ,"byebye\n")==0)
{
break;
}
}
}
int main()
{
//定义一个线程号
pthread_t tid;
//创建线程函数
pthread_create(&tid, NULL, t1,NULL);
//线程号,线程属性(接合,分离),
//线程属性若为空,则代表创建一个标准属性的线程
//1.创建有名管道
int JKTORS_ret = mkfifo(JK_TO_RS, 0777);//1.共享文件夹是创建不了管道文件的,windos是不支持管道文件的
//2.管道文件只能创建在Linux的目录下,建议大家创建在家目录,建议用chmod修改权限
if(-1 == JKTORS_ret)
{
perror("creat fifo failed");
}
//2.打开管道文件
int JKTORS_fd = open(JK_TO_RS,O_RDWR);
if(-1 == JKTORS_fd)
{
perror("open fifo failed");
return -1;
}
//1.创建有名管道
int RSTOJK_ret = mkfifo(RS_TO_JK, 0777);//1.共享文件夹是创建不了管道文件的,windos是不支持管道文件的
//2.管道文件只能创建在Linux的目录下,建议大家创建在家目录,建议用chmod修改权限
if(-1 == RSTOJK_ret)
{
perror("creat fifo failed");
}
//2.打开管道文件
RSTOJK_fd = open(RS_TO_JK,O_RDWR);
if(-1 == RSTOJK_fd)
{
perror("open fifo failed");
return -1;
}
//3.往管道文件里读
RSTOJK_buf = malloc(100);
char *JKTORS_buf = malloc(100);
while(1)
{
memset(RSTOJK_buf,0,100);
fgets(RSTOJK_buf,100,stdin);
write(RSTOJK_fd,buf,100);
printf("jack:%s\n",RSTOJK_buf);
if(strcmp(RSTOJK_buf ,"byebye\n")==0)
{
break;
}
}
}