1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

[C]同じ実行ファイルをシンボリックリンク名で使い分けるサンプルコード

Last updated at Posted at 2018-02-16

サンプルコード

main.c
#include <stdio.h>
#include <string.h>

struct command_list {
    char *command;
    int (*func)(int argc, char *argv[]);
};


static int test_a(int argc, char *argv[])
{
    printf("test_a: called\n");
    return (0);
}

static int test_b(int argc, char *argv[])
{
    printf("test_b: called\n");
    return (0);
}


static struct command_list list[] = {
    { .command = "test_a", .func = test_a },
    { .command = "test_b", .func = test_b },
    { .command = NULL,     .func = NULL   }
};


int main(int argc, char *argv[])
{
    int i;
    int ret = 0;

    for (i = 0; list[i].command != NULL; i++) {
        if (strstr(argv[0], list[i].command) != NULL) {
            ret = list[i].func(argc, argv);
        }
    }

    return (ret);
}

使い方

$ gcc main.c
$ ln -s a.out test_a
$ ln -s a.out test_b
$ ./test_a
test_a: called
$ ./test_b
test_b: called

まとめ

strcmpを使っているコードを見かけたが、絶対パスで指定できないのでstrstrを使いましょう。

1
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?