1、如何定位全局数组的写越界,一个被大量引用的全局数组int a[100],被写越界了,这样的情况如何定位?
最简单的方法是,将数组a[100]改为a[101],然后对访问a[100]的地方设置断点进行调试。因为a[100]应该是没有人访问
的,如果访问就是越界访问,直接可以定位到该位置。
2、在linux下防止某个程序被运行两次的方法
通过文件锁来实现,在程序运行的一开始,检查某文件是否存在,如果存在则说明改程序已经在运行了,如果不存在则利
用open语句创建该文件,程序退出时关闭并删除此文件。
具体代码:
static char file_lock[sizeof(ctl_addr.sun_path)] = /var/run/file.pid;
static bool file_lock_created = FALSE;
static int
create_lock(void)
{
int fd = open(file_lock, O_WRONLY | O_CREAT | O_EXCL | O_TRUNC,
S_IRUSR | S_IRGRP | S_IROTH);
if (fd < 0)
{
if (errno == EEXIST)
{
fprintf(stderr, "file: lock file "%s" already existsn", file_lock);
exit_file(10);
}
else
{
fprintf(stderr, "file: unable to create lock file "%s" (%d %s)n"
, file_lock, errno, strerror(errno));
exit_file(1);
}
}
file_lock_created = TRUE;
return fd;
}
static bool
fill_lock(int lockfd)
{
char buf[30];
pid_t pid;
int len;
pid = getpid();
len = snprintf(buf, sizeof(buf), "%un", (unsigned int) pid);
bool ok = len > 0 && write(lockfd, buf, len) == len;
close(lockfd);
return ok;
}
static void
delete_lock(void)
{
if (file_lock_created)
{
//delete_ctl_socket();
unlink(file_lock);
}
}