From 049c69f5c73ec399311548774a055b3bac6968f9 Mon Sep 17 00:00:00 2001 From: luochunsheng Date: Tue, 9 Apr 2019 20:38:13 +0800 Subject: [PATCH] added check if correct symlink exists --- alternatives.c | 39 +++++++++++++++++++++++++-------------- 1 file changed, 25 insertions(+), 14 deletions(-) diff --git a/alternatives.c b/alternatives.c index cdfec6d..b02cce2 100644 --- a/alternatives.c +++ b/alternatives.c @@ -456,6 +456,7 @@ static int removeLinks(struct linkSet * l, const char * altDir, int flags) { static int makeLinks(struct linkSet * l, const char * altDir, int flags) { char * sl; + char buf[PATH_MAX]; sl = alloca(strlen(altDir) + strlen(l->title) + 2); sprintf(sl, "%s/%s", altDir, l->title); @@ -463,12 +464,17 @@ static int makeLinks(struct linkSet * l, const char * altDir, int flags) { if (FL_TEST(flags)) { printf(_("would link %s -> %s\n"), l->facility, sl); } else { - unlink(l->facility); + memset(buf, 0, sizeof(buf)); + readlink(l->facility, buf, sizeof(buf)); - if (symlink(sl, l->facility)) { - fprintf(stderr, _("failed to link %s -> %s: %s\n"), - l->facility, sl, strerror(errno)); - return 1; + if(strcmp(sl, buf) != 0) { + unlink(l->facility); + + if (symlink(sl, l->facility)) { + fprintf(stderr, _("failed to link %s -> %s: %s\n"), l->facility, + sl, strerror(errno)); + return 1; + } } } } else @@ -478,16 +484,21 @@ static int makeLinks(struct linkSet * l, const char * altDir, int flags) { if (FL_TEST(flags)) { printf(_("would link %s -> %s\n"), sl, l->target); } else { - if (unlink(sl) && errno != ENOENT){ - fprintf(stderr, _("failed to remove link %s: %s\n"), - sl, strerror(errno)); - return 1; - } + memset(buf, 0, sizeof(buf)); + readlink(sl, buf, sizeof(buf)); + + if(strcmp(l->target, buf) != 0) { + if (unlink(sl) && errno != ENOENT) { + fprintf(stderr, _("failed to remove link %s: %s\n"), sl, + strerror(errno)); + return 1; + } - if (symlink(l->target, sl)) { - fprintf(stderr, _("failed to link %s -> %s: %s\n"), - sl, l->target, strerror(errno)); - return 1; + if (symlink(l->target, sl)) { + fprintf(stderr, _("failed to link %s -> %s: %s\n"), sl, l->target, + strerror(errno)); + return 1; + } } } -- 1.8.3.1