File: Fork.cpp

package info (click to toggle)
libassa 3.5.1-2
  • links: PTS, VCS
  • area: main
  • in suites: wheezy
  • size: 3,268 kB
  • sloc: cpp: 15,703; sh: 12,083; makefile: 379; perl: 51
file content (227 lines) | stat: -rw-r--r-- 6,049 bytes parent folder | download | duplicates (6)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
// -*- c++ -*-
//------------------------------------------------------------------------------
//                              Fork.cpp
//------------------------------------------------------------------------------
//  Copyright (C) 1997-2003,2005  Vladislav Grinchenko
//
//  This library is free software; you can redistribute it and/or
//  modify it under the terms of the GNU Library General Public
//  License as published by the Free Software Foundation; either
//  version 2 of the License, or (at your option) any later version.
//------------------------------------------------------------------------

#include <iostream>
#include <fcntl.h>

#if !defined(WIN32)
#    include <syslog.h>
#endif

#include "assa/Fork.h"
#include "assa/CmdLineOpts.h"
#include "assa/SigAction.h"
#include "assa/EventHandler.h"
#include "assa/SigHandler.h"

using namespace ASSA;

//------------------------------------------------------------------------------
/*
 * Note the use of _exit () instead of exit () in the child's portion.
 * For some GUI toolkits, calling exit() causes problems.
 *
 * From Gtk+ (www.gtk.org) FAQ:
 *
 *  "When GDK opens an X display, it creates a socket file descriptor.
 *   When you use the exit() function, you implicitly close all the
 *   open file descriptors, and the underlying X library really
 *   doesn't like this. The right function to use here is _exit()."
 *
 * From UNIX exit(2) man page:
 *
 *  "The function _exit terminates the calling process "immediately".
 *   Any open file descriptors belonging to the process are closed;
 *   any children of the process are inherited by process 1, init, and
 *   the process's parent is sent a SIGCHLD signal."
 *
 * _exit() doesn't not call standard I/O cleanup routines.
 *
 * From S.A. Rago "Unix System V Network Programming", sec. 2.4, p.74
 *
 *  "When a child terminates, the operationg system sends the SIGCHLD
 *   signal to the parent process. The default disposition for SIGCHLD
 *   is to ignore the signal, but a process can catch the signal and
 *   obtain the status of its children."
 *
 * We also preserve the SIGCHLD action mask here and catch it to get
 * the child's completion status. SIGCHLD signal mask is initially set to
 * SIG_IGN by GenServer, but can be reset later on by a third-party library
 * linked into the application code.
 */
int
Fork::
fork_exec (const string& cmd_,
		   const string& args_,
		   Fork::wait4status_t wait_for_completion_,
		   bool ignore_output_)
{
    trace_with_mask("Fork[static]::fork_exec",FORK);

	DL((FORK,"exec \"%s %s\")\n", cmd_.c_str (), args_.c_str ()));
    if (cmd_.size () == 0) {
		return -1;
    }

#if defined(WIN32)

    return -1;    // NOT IMPLEMENTED YET

#else

    Fork f (Fork::LEAVE_ALONE, wait_for_completion_);

    if (f.isChild ()) {
		string arg_list (cmd_);
		arg_list += " " + args_;
		int argc = 0;
		char** argv = 0;
		CmdLineOpts::str_to_argv (arg_list, argc, argv);

		/** Close all file descriptors and reduped stdout/stderr
			to /dev/null
		*/
		if (ignore_output_) {
			for (int i = 0; i < 1024; i++) {
				(void) close(i);
			}
			pid_t nullfd = open("/dev/null", O_WRONLY | O_CREAT, 0666);
			if (nullfd == -1) {
				syslog (LOG_ERR,"failed to open \"/dev/null\"");
				_exit (-1);
			}

			(void) dup2  (nullfd, 1);
			(void) dup2  (nullfd, 2);
			(void) close (nullfd);
		}

		execvp (cmd_.c_str (), argv);

		EL((ASSAERR,"fork_exec (\"%s\") failed\n", cmd_.c_str ()));
		_exit (-1);
    }

    if (! wait_for_completion_) {
		return f.getChildPID ();
    }

	return f.get_exit_status ();

#endif // defined(WIN32)
}


#if !defined(WIN32)
//------------------------------------------------------------------------------
// Static declarations
//
ASSA_DECL_SINGLETON(ForkList);

//------------------------------------------------------------------------------
// Member functions
//
int
ChildStatusHandler::
handle_signal (int signum_)
{
	trace_with_mask("ChildStatusHandler::handle_signal", FORK);
	DL((FORK, "Caught signal # %d\n", signum_));

	if (signum_ == SIGCHLD) {
		int status;
		m_caught = true;
		pid_t ret = ::wait (&status);
		DL((FORK,"wait() = %d (PID)\n", ret));

		if (ret > 0 && (WIFEXITED (status))) {
			m_exit_status = WEXITSTATUS (status);
		}
		else {
			m_exit_status = ret;
		}
	}

	DL((FORK,"child exit_status = %d\n", m_exit_status));
	return 0;
}

//------------------------------------------------------------------------------
Fork::
Fork (Fork::state_t exit_action_, Fork::wait4status_t catch_status_)
{
	trace_with_mask("Fork::Fork",FORK);

	if (catch_status_ == COLLECT_STATUS) {
		m_local_sh.install (SIGCHLD, &m_chstath, 0, 0, &m_old_disp);
	}

	if ((m_pid = fork()) < 0) {
		EL((ASSAERR,"failed to fork() - out of swap space?\n"));
		exit (1);	                     // die right here
	}

	if (m_pid) {				         // The Parent
		if (exit_action_ != LEAVE_ALONE) {
			ForkList::get_instance()->m_list.push_back (new fnode_t (m_pid, exit_action_));
		}
		if (catch_status_ == COLLECT_STATUS) {
			if (! m_chstath.caught ()) {
				pause ();
			}
			m_local_sh.remove (SIGCHLD, &m_chstath, &m_old_disp, 0);
		}
	}
}


ForkList::
~ForkList()
{
    trace_with_mask("ForkList::~ForkList",FORK);

    list<fnode_t* >::iterator i;
    pid_t pid;

    // Go through the list and send SIGTERM to those children
    // whose flags were set at fork time.

    for (i = m_list.begin(); i != m_list.end(); i++) {
		if ((*i)->needKill()) {
			::kill((*i)->getPID(), SIGTERM);
		}
    }
    // Wait for all children to exit.

    while ( ! m_list.empty() ) { // wait for child to exit
		pid = ::wait(NULL);
		if ( pid < 0 ) { // error on wait
			EL((ASSAERR,"Error on wait()\n"));
			exit (EXIT_FAILURE);
		}
		// Search for child through the list by its pid.
		// If found, remove it from list and release memory.

		list<fnode_t* >::iterator j;

		for (j = m_list.begin(); j != m_list.end(); j++) {
			if ((*j)->getPID() == pid) {
				fnode_t* ep = *j;
				m_list.erase(j);
				delete ep;
				break;
			}
		}
    }
}

#endif // !defined(WIN32)