V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
Akagi201
V2EX  ›  问与答

困扰已久的问题, C 语言, 链接了第三方的开源库, 库中用了 exit(1)如何避免?

  •  
  •   Akagi201 · Dec 25, 2014 · 3427 views
    This topic created in 4141 days ago, the information mentioned may be changed or developed.

    V2EX上牛X程序员很多, 希望能提供一些思路, 或者别的语言的做法也行.

    困扰已久的问题, C语言, 链接了第三方的开源库, 这个开源库里一些出错处理(比如网络阻塞等情况)在失败时, 会使用exit(1), 还有assert等, 直接终止整个程序了.

    我需要他能一直运行的, 出错了重启这个库, 或者至多仅仅这个线程挂掉.

    比如: openvpn, 链接的程序, 如果参数配置错误, 直接整个程序崩溃.

    有没有什么trick的方法, 把exit() 这种函数直接屏蔽掉.

    14 replies    2014-12-25 22:21:58 +08:00
    goool
        1
    goool  
       Dec 25, 2014
    1、既然是开源的,可考虑改写代码;
    2、在独立的进程里运行这个库,数据以通信方式交换。
    qiukun
        2
    qiukun  
       Dec 25, 2014 via Android
    hook
    Akagi201
        3
    Akagi201  
    OP
       Dec 25, 2014
    @goool 因为改动不现实我才问的, 如果很小的代码直接手改了. 直接的解决办法就是fork了, 不过像用libuv, 他没封装fork.

    @qiukun 详细点说呢?
    way2exluren
        4
    way2exluren  
       Dec 25, 2014
    举个例子,如果你不包含#include <stdio.h>的话,自己写一个exit()函数,自己的函数会被链接替代了标准库里的exit。
    我觉得可以从这方面试试
    way2exluren
        5
    way2exluren  
       Dec 25, 2014
    哦写错了,是 <stdlib.h>
    nealfeng
        6
    nealfeng  
       Dec 25, 2014
    那你就写个监测程序呗。可以多进程或线程。
    KDr2
        7
    KDr2  
       Dec 25, 2014
    @way2exluren 貌似跟头文件没关系,跟链接顺序关系比较大,自定义个exit,链接是放前面貌似就可以了,如果还需要调原来 libc 的 exit 用 dlopen/dlsym 找出来调。
    KDr2
        8
    KDr2  
       Dec 25, 2014
    另外,exit(1) 这个写法,一般指叫做 exit 的常用外部命令 (不过现实中貌似没有这个),exit(3) 指 c library 里的函数。
    way2exluren
        9
    way2exluren  
       Dec 25, 2014
    @KDr2 如果#include <stdlib.h> 不管放在前面还是后面,都会报错的。因为重复定义了exit函数。符号冲突。
    way2exluren
        10
    way2exluren  
       Dec 25, 2014   ❤️ 1
    顺便如果楼主你有源代码。可以直接用一个宏#define exit(x) myexit(x) 全局替换。然后编译成库
    KDr2
        12
    KDr2  
       Dec 25, 2014   ❤️ 1
    @way2exluren 头文件里只有声明,怎么也到不了重复定义那步吧

    [000]kdr2@Debian-X230:~$ cat x.c
    #include <stdlib.h>

    void exit(int status){abort();};
    [000]kdr2@Debian-X230:~$ gcc -Wall -c x.c -o x.a
    [000]kdr2@Debian-X230:~$ ls x.a
    x.a
    [000]kdr2@Debian-X230:~$

    有什么问题。
    way2exluren
        13
    way2exluren  
       Dec 25, 2014
    @KDr2 你是对的,我说错了。
    yangff
        14
    yangff  
       Dec 25, 2014 via Android
    把exit函数改成ret
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   3289 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 42ms · UTC 13:24 · PVG 21:24 · LAX 06:24 · JFK 09:24
    ♥ Do have faith in what you're doing.