(本节笔记的实验代码,在这里)
1. 基本概念:
进程间的同步是指一组并发进程进行互相合作,互相等待,使得各进程按照一定的顺序执行的过程。
2. 生产者与消费者问题
2.1 信号量sem_val初始值设为0
2.2 生产者每生产好一件产品,就sem_val + 1(释放信号量)
2.3 消费者开始因sem_val = 0而阻塞,当sem_val > 0 时,就执行消费行为(运行程序)。
3. 函数学习——system()
函数名:
system
函数原型:
int system (const char *command);
函数功能:
在进程中调用系统中的应用程序
所属头文件:
<stdlib.h>
返回值:
成功:把返回值填到status [8:15]中 失败:返回-1
参数说明:
command:一个常量的字符串,为/bin/sh执行的应用程序
范例代码:
system("cp ./test /test");
4. 综合实例:
/*****************************************************************************
* 生产者:新建一个文件,在文件写入数据,设置信号量; *
* 消费者:在生产者生产完成后,把文件复制到指定的地方; *
*****************************************************************************/
/* touch producer */
#include <stdio.h>
#include <sys/types.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/ipc.h>
#include <sys/sem.h>
int main()
{
int fd_product;
int sd_product;
key_t key_product;
struct sembuf sembuf_product;
fd_product = open("./product.txt",O_RDWR | O_CREAT, 0777);
key_product = ftok("/arm",1);
sd_product = semget(key_product, 1, IPC_CREAT);
semctl(sd_product, 0, SETVAL, 0);
sleep(10);
write(fd_product, "The Product Finished!", 21 );
sembuf_product.sem_num = 0;
sembuf_product.sem_op = 1;
sembuf_product.sem_flg = SEM_UNDO;
semop(sd_product, &sembuf_product, 1);
close(fd_product);
return 0;
}
/* touch customer.c */
#include <stdio.h>
#include <sys/types.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/ipc.h>
#include <sys/sem.h>
int main()
{
int sd_product;
key_t key_product;
struct sembuf sembuf_product;
key_product = ftok("/arm",1);
sd_product = semget(key_product, 1, IPC_CREAT);
sembuf_product.sem_num = 0;
sembuf_product.sem_op = -1;
sembuf_product.sem_flg = SEM_UNDO;
semop(sd_product, &sembuf_product, 1);
system("cp ./product.txt ./ship/product.txt");
sembuf_product.sem_num = 0;
sembuf_product.sem_op = 1;
sembuf_product.sem_flg = SEM_UNDO;
semop(sd_product, &sembuf_product, 1);
return 0;
}