- 论坛徽章:
- 0
|
看了一个下午的Posix信号灯,发现有很多问题,可以解决的,不能解决的一大堆,当然,耐心,吴老师告诉我们说,做人不能浮躁,浑浑噩噩的成不了大事。我很相信吴老师的话,这关键是因为她觉得我还是个孺子--可教^_^。所以我硬着头皮往下走,找了N多高手。收获总是和磨砺共存的,所以,今天还是挺有收获的^_^。
首先,二话不说,上可执行代码才是硬道理。空间大,不用担心上全代码会占用太大空间,页数增多,书本价格上涨,降低书本质量,影响爱好者的预算。^_^
semcreate.c
#include
#include
#include
#include
#include
#include
#include
int
main(int argc, char **argv)
{
int c, flags;
sem_t *sem;
unsigned int value;
flags = O_RDWR | O_CREAT;
value = 1;
while ( (c = getopt(argc, argv, "ei:")) != -1) {
switch (c) {
case 'e':
flags |= O_EXCL;
break;
case 'i':
value = atoi(optarg);
break;
}
}
if (optind != argc - 1)
{
printf("usage: semcreate [ -e ] [ -i initalvalue ] ");
exit(0);
}
sem = sem_open(argv[optind], flags, 0666, value);
sem_close(sem);
exit(0);
}//END
semgetvalue.c
#include
#include
#include
#include
#include
#include
#include
int
main(int argc, char **argv)
{
sem_t *sem;
int val;
if (argc != 2)
{
printf("usage: semgetvalue ");
exit(0);
}
sem = sem_open(argv[1], 0);
sem_getvalue(sem, &val);
printf("value = %d\n", val);
exit(0);
}//END
/*************sempost.c**********/
#include
#include
#include
#include
#include
#include
#include
int
main(int argc, char **argv)
{
sem_t *sem;
int val;
if (argc != 2)
{
printf("usage: sempost ");
exit(0);
}
sem = sem_open(argv[1], 0);
sem_post(sem);
sem_getvalue(sem, &val);
printf("value = %d\n", val);
exit(0);
}//END
/******** semunlink.c********/
#include
#include
#include
int
main(int argc, char **argv)
{
if (argc != 2)
{
printf("usage: semunlink ");
exit(0);
}
sem_unlink(argv[1]);
exit(0);
}//END
/*************semwait.c******************/
#include
#include
#include
#include
#include
#include
#include
int
main(int argc, char **argv)
{
sem_t *sem;
int val;
if (argc != 2)
{
printf("usage: semwait ");
exit(0);
}
sem = sem_open(argv[1], 0);
sem_wait(sem);
sem_getvalue(sem, &val);
printf("pid %ld has semaphore, value = %d\n", (long) getpid(), val);
pause(); /* blocks until killed */
exit(0);
}//END
把书上的unpipc.h 转化了一下,大家复制黏贴就可以用了。^_^,方便了像我这样的懒惰的人。
不过这个在编译的时候有点麻烦,必须加入参数-lrt,也就是说上述文件在命令行里面要输入:
cc semcreate.c -o semcreate -lrt
这样才能通过编译
其他的文件当然也是用同样的办法处理了
cc semunlink.c -o semunlink -lrt
cc semwait.c -o semwait -lrt
cc semgetvalue.c -o semgetvalue -lrt
cc sempost.c -o sempost -lrt
上述编译才不会出错。
当然,想到一个文件夹下面有这么多的文件没有一个makefile,每次编译它们实在不是一件容易的事情,所以今天下午把它们的makefile批处理写了一下,当然我是makefile菜鸟,没有写出啥很好的语句,为了方便牛人,我写的倒是很工整,以方便牛人帮我改错。当然,请牛人帮忙是要见缝插针的。
代码没有带回来,明天贴上去。
本文来自ChinaUnix博客,如果查看原文请点:http://blog.chinaunix.net/u2/83146/showart_1342092.html |
|