+ return ret;
+}
+
+void
+lockfile_unlock (Filelist * fl)
+{
+
+ while (fl->head) {
+ unlink (fl->head->name);
+ filelist_remove (fl, fl->head);
+ }
+}
+
+
+/* If we have a passive lock, check noone has an */
+/* active one, returns 1 if he does, 0 if he doesnt */
+int
+serial_lock_check (Serial_lock * l)
+{
+ Filelist_ent *fle;
+ int locks_found = 0;
+ struct stat buf;
+ struct timeval now, dif;
+
+ if (l->mode == SERIAL_LOCK_ACTIVE)
+ return 0;
+
+ for (fle = l->locks_to_check->head; fle; fle = fle->next) {
+ if (!stat (fle->name, &buf))
+ locks_found++;
+ }
+
+ if (!locks_found)
+ return 0;
+
+ gettimeofday (&now, NULL);
+ timersub (&now, &l->last_stale_purge, &dif);
+
+ if (dif.tv_sec > STALE_CHECK_INTERVAL) {
+ lockfile_remove_stale (l->locks_to_check);
+ l->last_stale_purge = now;
+ }
+
+ return 1;
+}
+
+void
+serial_lock_free (Serial_lock * l)
+{
+ if (!l)
+ return;
+
+ if (l->locks_held) {
+ lockfile_unlock (l->locks_held);
+ filelist_free (l->locks_held);
+ }
+
+ if (l->locks_to_check) {
+ filelist_free (l->locks_to_check);
+ }
+
+ free (l);
+}
+
+
+Serial_lock *
+serial_lock_new (char *dev, int mode)
+{
+ Filelist *fl = lockfile_make_list (dev);
+ Serial_lock *l;
+
+ if (!fl)
+ return NULL;
+
+ l = (Serial_lock *) xmalloc (sizeof (Serial_lock));
+
+ l->mode = mode;
+ l->locks_to_check = fl;
+ l->locks_held = NULL;
+ memset (&l->last_stale_purge, 0, sizeof (l->last_stale_purge));
+
+ if (mode == SERIAL_LOCK_PASSIVE)
+ return l;
+
+ l->locks_held = lockfile_lock (l->locks_to_check);
+ if (!l->locks_held) {
+ serial_lock_free (l);
+ return NULL;
+ }
+
+ return l;
+}
+
+
+#if 0
+int
+main (int argc, char *argv[])
+{
+ Filelist *fl = lockfile_make_list ("/dev/ttyS0");
+ Filelist *fll;
+ Filelist_ent *fle;
+
+ filelist_print (fl, stdout);
+
+ fll = lockfile_lock (fl);
+
+ filelist_print (fll, stdout);
+}
+#endif