ensure that ast_safe_system() is thread-safe (issue #4947)

git-svn-id: https://origsvn.digium.com/svn/asterisk/trunk@6603 65c4cc65-6c06-0410-ace0-fbb531ad65f3
This commit is contained in:
Kevin P. Fleming
2005-09-14 22:40:54 +00:00
parent eb332490ff
commit b68657fcec

View File

@@ -349,42 +349,62 @@ static void null_sig_handler(int signal)
} }
AST_MUTEX_DEFINE_STATIC(safe_system_lock);
static unsigned int safe_system_level = 0;
static void *safe_system_prev_handler;
int ast_safe_system(const char *s) int ast_safe_system(const char *s)
{ {
/* XXX This function needs some optimization work XXX */
pid_t pid; pid_t pid;
int x; int x;
int res; int res;
struct rusage rusage; struct rusage rusage;
int status; int status;
void (*prev_handler) = signal(SIGCHLD, null_sig_handler); unsigned int level;
/* keep track of how many ast_safe_system() functions
are running at this moment
*/
ast_mutex_lock(&safe_system_lock);
level = safe_system_level++;
/* only replace the handler if it has not already been done */
if (level == 0)
safe_system_prev_handler = signal(SIGCHLD, null_sig_handler);
ast_mutex_unlock(&safe_system_lock);
pid = fork(); pid = fork();
if (pid == 0) { if (pid == 0) {
/* Close file descriptors and launch system command */ /* Close file descriptors and launch system command */
for (x=STDERR_FILENO + 1; x<4096;x++) { for (x = STDERR_FILENO + 1; x < 4096; x++)
close(x); close(x);
} execl("/bin/sh", "/bin/sh", "-c", s, NULL);
res = execl("/bin/sh", "/bin/sh", "-c", s, NULL);
exit(1); exit(1);
} else if (pid > 0) { } else if (pid > 0) {
for(;;) { for(;;) {
res = wait4(pid, &status, 0, &rusage); res = wait4(pid, &status, 0, &rusage);
if (res > -1) { if (res > -1) {
if (WIFEXITED(status)) res = WIFEXITED(status) ? WEXITSTATUS(status) : -1;
res = WEXITSTATUS(status); break;
else } else if (errno != EINTR)
res = -1;
break; break;
} else {
if (errno != EINTR)
break;
}
} }
} else { } else {
ast_log(LOG_WARNING, "Fork failed: %s\n", strerror(errno)); ast_log(LOG_WARNING, "Fork failed: %s\n", strerror(errno));
res = -1; res = -1;
} }
signal(SIGCHLD, prev_handler);
ast_mutex_lock(&safe_system_lock);
level = --safe_system_level;
/* only restore the handler if we are the last one */
if (level == 0)
signal(SIGCHLD, safe_system_prev_handler);
ast_mutex_unlock(&safe_system_lock);
return res; return res;
} }