红联Linux门户
Linux帮助

linux多进程通信

发布时间:2015-10-12 09:44:07来源:linux网站作者:勤奋的伙计

信号量机制实现进程通信:

使用sem_open,sem_unlink,sem_getvalue,sem_post,sem_wait,sem_close,等信号量机制


1.sem_sync.h

#ifndef _SEM_SYNC_H_
#define _SEM_SYNC_H_
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <stdio.h>
#include <semaphore.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

char SEM_A_TASK_IS_FREE[]= "a_task_is_free";
char SEM_B_TASK_IS_FREE[]= "b_task_is_free";

#endif


2.进程a

#include "sem_sync.h"

int main()
{
sem_t *sem_a_task_is_free;
sem_t *sem_b_task_is_free;
int val;

sem_a_task_is_free = sem_open(SEM_A_TASK_IS_FREE, O_CREAT, 0644, 1);
sem_b_task_is_free = sem_open(SEM_B_TASK_IS_FREE, O_CREAT, 0644, 0);
if (sem_a_task_is_free == SEM_FAILED || sem_b_task_is_free == SEM_FAILED)
{
perror("unable to create semaphore");
sem_unlink(SEM_A_TASK_IS_FREE);
exit(-1);
}
//while (1 == 1)
{
printf("run a task......\n");
getchar();

sem_getvalue(sem_a_task_is_free, &val);
printf("The sem is %d\n", val);
sem_post(sem_a_task_is_free);
sem_getvalue(sem_a_task_is_free, &val);
printf("The sem after sem post is %d\n", val);
printf("send->a_task_is_free\n");

printf("\nwaite sem_b_task_is_free\n");
//sem_wait(sem_b_task_is_free);
printf("recv<-sem_b_task_is_free\n");
}

sem_close(sem_a_task_is_free);
sem_unlink(SEM_A_TASK_IS_FREE);

_exit(0);
}

//gcc a.c -lpthread  -o a


3.进程b

#include "sem_sync.h"

int main()
{
int val;
sem_t *sem_a_task_is_free;
sem_t *sem_b_task_is_free;

sem_a_task_is_free = sem_open(SEM_A_TASK_IS_FREE, O_CREAT, 0644, 0);
sem_b_task_is_free = sem_open(SEM_B_TASK_IS_FREE, O_CREAT, 0644, 1);
if (sem_a_task_is_free == SEM_FAILED || sem_b_task_is_free == SEM_FAILED)
{
perror("unable to create semaphore");
sem_unlink(SEM_B_TASK_IS_FREE);
exit(-1);
}

//while (1 == 1)
{
printf("\nrun b_task......\n");
sem_getvalue(sem_a_task_is_free, &val);
printf("The sem is %d\n", val);
sleep(1);
//sem_post(sem_b_task_is_free);
printf("send->sem_b_task_is_free\n");
printf("\nwaite a_task_is_free\n");
sem_getvalue(sem_a_task_is_free, &val);
printf("The sem 2 is %d\n", val);
sem_wait(sem_a_task_is_free);
sem_getvalue(sem_a_task_is_free, &val);
printf("The sem 3 is %d\n", val);
printf("recv<-a_task_is_free\n");
}

sem_close(sem_a_task_is_free);
sem_close(sem_b_task_is_free);

sem_unlink(SEM_B_TASK_IS_FREE);
exit(0);
}

//gcc b.c -lpthread -o b

#./a

#./b


备注:只要信号量没有释放,sem_unlink,那信号量值将保持不变,sem_post将使信号量增加1,sem_wait将使信号量减1.


Linux Shell实现多进程并发执行:http://www.linuxdiyf.com/linux/7790.html

Linux下用gdb单步调试多进程方法:http://www.linuxdiyf.com/linux/7516.html