当前位置:网站首页>Interprocess communication
Interprocess communication
2022-07-27 14:28:00 【amireux512】
Catalog
5.2, Change the way the signal is processed
One , General overview

Two , The method details
1. Famous pipeline
mkfifo Used to create a named pipe in the file system (fifo), But this file only exists in memory ,
It's just a path in the file system .
int mkfifo(const char *pathname, mode_t mode);
@pathname: To create FIFO file ( With path )
@mode: Created FIFO File permissions , Such as 0664
Return value : Successfully returns 0, Failure to return -1,errno Set up
2. Nameless pipe
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <string.h>
#include <signal.h>
#include <stdlib.h>
int main()
{
int pipefd[2];
int r = pipe(pipefd);
if(r == -1)
{
perror("pipe failed");
return -1;
}
pid_t pid = fork();
if(pid > 0)// It is the parent process that returns
{
while(1)
{
char str[32];
read(pipefd[0],str,32);
printf("read buf: %s\n",str);
if(strcmp(str,"over")==0)
{
kill(pid,9);
exit(0);
}
}
}
else // Is the subprocess return
{
while(1)
{
char str[32];
gets(str);
write(pipefd[1],str,strlen(str)+1);
}
}
}
3. Shared memory

1, Apply for one system_v_ipc Of key
key_t ftok(const char *pathname, int proj_id);
2, Create or open a system v Shared memory area
int shmget(key_t key, size_t size, int shmflg);
3,shmat Used to map the shared memory area to the address space of the process
void *shmat(int shmid, const void *shmaddr, int shmflg);
4,shmdt Used to unmap the mapped shared memory area
int shmdt(const void *shmaddr);
5, shmctl Control the shared memory area
int shmctl(int shmid, int cmd, struct shmid_ds *buf);
@shmid: Shared memory area ID, Indicates which shared memory area to operate
@cmd: Command number , There are three common ones
IPC_RMID Used to delete the shared memory , Now the third parameter buf Fill in as NULL
IPC_STAT Used to get the status of shared memory , adopt buf Point to the
Structural variable .
IPC_SET Used to set the status information of the shared memory area , adopt buf Point to the shared memory area used to save
Structure variables of state information .
#include <stdio.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <string.h>
#define KEY_PATH "/home/china"
#define PRO_ID 9527
int main()
{
/*step1: Apply for one system_v_ipc Of key*/
key_t key = ftok(KEY_PATH, PRO_ID);
if(key == -1)
{
perror("ftok failed");
return -1;
}
/*step2: Create a system v Shared memory area */
int shmid = shmget(key, 4096, IPC_CREAT | 0664);
if(shmid == -1)
{
perror("shmget failed");
return -1;
}
/*step3: mapping */
char *shm_p = shmat(shmid, NULL, 0);
if(shm_p == NULL)
{
perror("shmat failed");
return -1;
}
while(1)
{
char str[64];
gets(str);
strcpy(shm_p,str);
if(strcmp(str,"quit") == 0)
break;
}
/*step4: demapping */
shmdt(shm_p);
/*step5: Destroy shared memory */
shmctl(shmid, IPC_RMID, NULL);
}
4, Semaphore

4.1,posix_sem
POSIX Concept :
POSIX Is a portable operating system interface , The box POSIX Standard code , stay POSIX It can be compiled and executed on the operating system .
POSIX Not limited to UNIX/Linux, such as DEC,Open VMS etc. .
Posix Semaphore It is also divided into famous semaphores and unknown semaphores
Famous semaphore : There is a file name in the file system , But it doesn't exist in the file system , It exists in memory
Unknown semaphore : No file name , It is only applicable to threads or related processes
Famous semaphore Unknown semaphore
establish / initialization sem_open() sem_init()
P operation sem_wait()/sem_trywait()
V operation sem_post()
Get the value of semaphore sem_getvalue()
Destroy semaphore sem_unlink() sem_destroy()
#include <stdio.h>
#include <fcntl.h> /* For O_* constants */
#include <sys/stat.h> /* For mode constants */
#include <semaphore.h>
#define SEM_NAME "/test.sem"
int main()
{
int sval;
/*step1: Create a semaphore */
sem_t *sem = sem_open(SEM_NAME, O_CREAT, 0664, 1);
if(sem == SEM_FAILED)
{
perror("sem_open failed");
}
/*step2: Operation semaphore */
sem_wait(sem);//P operation
sem_getvalue(sem, &sval);
printf("i get the sem, the sem value is %d\n",sval);
getchar();
sem_post(sem);//V operation
sem_getvalue(sem, &sval);
printf("i release the sem!,the sem value is %d\n",sval);
/*step3: Destroy semaphore */
sem_unlink(SEM_NAME);
}
4.2,sistem_v_sem
1. apply key
key_t ftok(const char *pathname, int proj_id);
2. call semget To create or open a system_v The amount of signal
int semget(key_t key, int nsems, int semflg);
@nsems: The semaphore you want to create sets the semaphore Number
If we don't create a new semaphore set , Instead, access an existing semaphore set , The parameter here should Designated as 0, Once you have created a semaphore set , We can't change the number of semaphores .
@semflg: Sign a
1) establish PC_CREAT | Permission bits , Such as IPC_CREAT | 0664
2) open 0
3, call semctl Assign an initial value to the semaphore
int semctl(int semid, int semnum, int cmd, ...);
@cmd: Operation command number , Commonly used
GETVAL: Get the value of a semaphore
GETALL: Get the values of all semaphores in this semaphore set
SETVAL: Set the value of a semaphore
SETALL: Set the values of all semaphores in the semaphore set
IPC_RMID: Delete the semaphore set
IPC_SET: Set the status information of the semaphore set
IPC_STAT: Get the state information of the semaphore set
@...arg: Optional parameters , according to cmd What's the situation , Its value is different
if cmd == GETVAL,arg You don't need to ,semctl The return value of is the value of the semaphore
if cmd == GETALL,arg It should be for a short The first address of the array , Used to save the values of all semaphores
if cmd == SETVAL,arg It should be for a short The integer of , Used to specify the value of the semaphore
if cmd == SETALL,arg It should be for a short The first address of the array , Used to save the values of all semaphores
4, call semop On the semaphore pv operation
int semop(int semid, struct sembuf *sops, size_t nsops);
@semid: The semaphore set you want to operate ID
@sops: struct sembuf The first address of the array , Because you can operate multiple semaphores at the same time
@nsops: The second parameter struct sembuf The number of elements in the array
struct sembuf
{
unsigned short sem_num; // Indicates which semaphore you are operating on (0,1,2,3...nsems-1)
short sem_op; // Indicates what you do with the semaphore .
// Whether it's P Operation or V operation , The essence is to operate the value of semaphore
/*
sem_op < 0 , Express P operation
sem_op > 0 , Express V operation
sem_op ==0 , It means no operation
Last ,semval The value is equal to the ==> primary semval + sem_op
*/
short sem_flg; // Operation flag bit
/*
0: General situation . P In operation, if semval<=0, be wait
IPC_NOWAIT: Non blocking ( Don't wait for ).P In operation, if semval<=0, You don't wait , Go straight back to -1
SEM_UNDO: revoke . When the process exits , The operating system will restore the operation of the process on the semaphore . In order to prevent the process from deadlocking .
*/
};
#include <stdio.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/sem.h>
#define PRO_PATH "/home/china"
#define PRO_ID 1234
int main()
{
int r;
/*step1: use ftok Apply to the kernel for a system v ipc Object's key */
key_t key = ftok(PRO_PATH, PRO_ID);
if(key == -1)
{
perror("ftok failed");
return -1;
}
/*step2: use semget To create or open a system v Semaphore set object */
int semid = semget(key, 2, IPC_CREAT | 0664);
if(semid == -1)
{
perror("semget failed");
return -1;
}
/*step3: use semctl Assign an initial value to the semaphore */
r = semctl(semid, 0, SETVAL, 1);
r = semctl(semid, 1, SETVAL, 1);
if(r == -1)
{
perror("semctl failed");
return -1;
}
/*step4: use semop Yes system v Semaphores operate ( Mainly P/V operation )*/
struct sembuf sops[2];
sops[0].sem_num = 0;
sops[0].sem_op = -1;//P operation
sops[0].sem_flg=0;// Block waiting
sops[1].sem_num = 1;
sops[1].sem_op = -1;//P operation
sops[1].sem_flg=0;// Block waiting
r = semop(semid, sops, 2);
printf("i have the sem0 and sem1\n");
getchar();
sops[0].sem_num = 0;
sops[0].sem_op = 1;//V operation
sops[0].sem_flg=0;// Block waiting
sops[1].sem_num = 1;
sops[1].sem_op = 1;//V operation
sops[1].sem_flg=0;// Block waiting
r = semop(semid, sops, 2);
printf("i release the sem0 and sem1\n");
/*step4: Destroy semaphore */
r = semctl(semid, 0, IPC_RMID);
}
5, The signal

5.1 Sending signal
int kill(pid_t pid, int sig);
@pid: Specify the receiver of the signal ( It may be multiple processes )
pid > 0: The recipient's process ID
pid==0: Send a signal to all processes in the same group of calling processes
pid==-1: Send a signal to all processes that the calling process has permission to send
pid<-1: Send a signal to the Group ID be equal to pid The absolute value of all processes
@sig: The value of the signal to be sent
alarm Used to set an alarm clock for the calling process , When the alarm clock times out , There will be ( Send a SIGALRM The signal
To the calling process ), A process can only have one alarm clock at a time .
unsigned int alarm(unsigned int seconds);
@seconds: Set the time of the alarm clock , In seconds
pause Used to wait for a signal , Cause the calling process ( Or thread ) Sleep ( It's stuck there ), Until a signal is received
( Be killed / Execute your own signal processing function ).
int pause(void);
5.2, Change the way the signal is processed
sighandler_t signal(int signum, sighandler_t handler);
@signum: The value of the signal to change the processing method
@handler: Pointer to the signal processing function . There are three situations :
1) SIG_IGN: ignore Ignore
2) SIG_DFL: default Adopt the default processing method of the operating system
3) Pointer of signal processing function written by yourself
Return value :
If the previous processing method of the signal is returned successfully
Return if failed SIG_ERR
Be careful :
Signal processing mode , It can also be fork clone
#include <stdio.h>
#include <unistd.h>
#include <signal.h>
int terminal_flag=0;
void signal_handler(int sigval)
{
switch(sigval)
{
case SIGINT:
terminal_flag=1;break;
case SIGALRM:
puts("haha");
alarm(5);
break;
}
}
int main()
{
int a=2,b=3;
signal(SIGINT, signal_handler);
signal(SIGALRM, signal_handler);
alarm(5);
while(1);
}
边栏推荐
- Windows10 installing SQL Server 2019
- va_ List usage summary
- Unity3d learning note 10 - texture array
- Rtl8762dk environment construction (I)
- <C> C语言哈希表使用
- Spark job uses log4j appender to append logs to local files or mysql
- Jing Xiandong and other senior executives of ant group no longer serve as Alibaba partners to ensure independent decision-making
- YOLOX改进之一:添加CBAM、SE、ECA注意力机制
- 正掩码、反掩码、通配符
- Detoxify! After Harbin Institute of technology was disabled MATLAB, domestic industrial software fought back domineering
猜你喜欢

Jing Xiandong and other senior executives of ant group no longer serve as Alibaba partners to ensure independent decision-making

文献翻译__tvreg v2:用于去噪、反卷积、修复和分割的变分成像方法(部分)

Schematic diagram of C measuring tool
Database storage series (1) column storage

MySQL advanced II. Logical architecture analysis

GoPro access - control and preview GoPro according to GoPro official document /demo

One of yolox improvements: add CBAM, Se, ECA attention mechanism

Leetcode · daily question · 592. fraction addition and subtraction · simulation

Unity3D学习笔记10——纹理数组
![[note] logistic regression](/img/2b/07cc3c26b1b34fbf2f09edaa33668e.jpg)
[note] logistic regression
随机推荐
Navicate报错access violation at address 00000000
poj3461 Oulipo【KMP】
WPF visifire.charts4.6.1 tutorial with source code
Secondary spanning tree [template]
Advanced MySQL III. storage engine
Unity2d -- camera follow
RTL8762DK 环境搭建(一)
Some key information about Max animation (shift+v)
How to solve cache avalanche, breakdown and penetration problems
Positive mask, negative mask, wildcard
Chapter 3 business function development (add clues and remarks, and automatically refresh the added content)
Good architecture is evolved, not designed
面向不平衡数据的电子病历自动分类研究
正掩码、反掩码、通配符
HDU4496 D-City【并查集】
第3章业务功能开发(查看线索明细)
Cultural tourism and data collection | travel to Yunnan in an artistic way
<C> C语言哈希表使用
[luogu_p4556] [Vani has an appointment] tail in rainy days / [template] segment tree merging
Airport cloud business sign analysis