- 论坛徽章:
- 0
|
原帖由 spiritX 于 2009-2-5 15:47 发表
消息队列这个搞大了, 应该不需要吧.
solaris下有个mutex_init, 但是着玩意没有参数建立有名的内核对象啊.
int mutex_init(mutex_t *mp, int type, void * arg);
int mutex_lock(mutex_t *mp);
...
为嘛不用文件呢?最简单就是根据参数组合创建一个文件,然后unlink它。这样既可以保证一种参数只有一个进程在执行,而又不会遗留文件。因为就算OS崩溃了也没问题,unlink的文件也会被自动删除的。
char argfile[256];
argfile[0] = 0;
strcat(argfile, "~/");
for(int i = 0; i < argc; ++i)
strcat(argfile, argv[i]);
//... Populate flags
int err = open(argfile, flags);
if (err> 0)
unlink(argfile);
else
exit; |
经测试可用的例子——无论进程崩溃、被杀,还是系统崩溃都不会遗留文件,而且只允许启动一份:
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
int main()
{
char* filename = "./.hello";
int err;
if ((err = open(filename, O_CREAT|O_RDONLY)) != -1)
{
unlink(filename);
while (1);
}
else
{
perror("ERROR");
printf("%d\n", err);
exit(err);
}
} |
#include <unistd.h>
int unlink(const char *pathname);
Description
unlink() deletes a name from the filesystem. If that name was the last link to a file and no processes have the file open the file is deleted and the space it was using is made available for reuse.
If the name was the last link to a file but any processes still have the file open the file will remain in existence until the last file descriptor referring to it is closed.
If the name referred to a symbolic link the link is removed.
If the name referred to a socket, fifo or device the name for it is removed but processes which have the object open may continue to use it.
[ 本帖最后由 fera 于 2009-2-5 17:25 编辑 ] |
|