1

My C program runs on Solaris and needs to restart itself when some condition occurs, such as receiving a signal. Now I consider to use exec family functions to implement this features, and there are 3 issues:

  1. I know the file descriptors should be closed before execing, but program uses some third-party libraries, and these libraries open file too, so how can I close these file descriptors?
  2. Except file descriptors, are there any system resources need to be freed?
  3. Except exec family functions, are there any other methods of implementing this function?
Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
Nan Xiao
  • 16,671
  • 18
  • 103
  • 164
  • 1
    Think about shared memory segments (System V IPC style), and similar things. If the program doesn't use them, no problem. If it does, do they need to be cleaned up? It depends on the program and what it does if it finds resources it would normally create already exist. – Jonathan Leffler Jul 15 '13 at 03:42

2 Answers2

4

I would have 2 programs ... one is a launcher of the second one. The launcher is waiting for the return value of the second program, and based on this value it decides to relaunch it or not.

Vincent Cantin
  • 16,192
  • 2
  • 35
  • 57
2

The POSIX spec for the exec family of functions tells you exactly what you should worry about. Read the DESCRIPTION section carefully and see if anything there matters to you (e.g. signal dispositioning). I do not believe any resources other than file descriptors need to be freed.

There is no way to close all file descriptors -- nor to set their close-on-exec flag -- other than to know what they are or to loop through all of them. See (e.g.) this answer.

I agree with the other answer that a better idea is to have a "watcher" process or script that re-launches the main program should it terminate.

[update]

Although there is no standard (POSIX) way to enumerate and/or close all open file descriptors, there is a Solaris-specific interface to do so. (This was news to me.) See alanc's comment below.

Community
  • 1
  • 1
Nemo
  • 70,042
  • 10
  • 116
  • 153
  • 1
    Since the question specified Solaris, libc provides a function to loop over all file descriptors, and another to use that loop to close all from a given point (like everything past stderr) - see http://docs.oracle.com/cd/E26502_01/html/E29034/closefrom-3c.html . – alanc Jul 15 '13 at 15:40