Организация Web-доступа в среде zLinux на сервере z9 BC

Дипломная работа - Компьютеры, программирование

Другие дипломы по предмету Компьютеры, программирование

дочный режим)

v (выдача краткой информации о версии сервера)

V (выдача полной информации о версии сервера)

h (выдать синтаксис командной строки)

Для запуска демона httpd лучше всего использовать скрипт apachectl. Этот скрипт устанавливает ряд переменных окружения, необходимых для правильной работы сервера под некоторыми операционными системами, а затем запускает исполняемый файл httpd. Скрипт apachectl передаст серверу любую командную строку, так что при вызове можно указывать в его командной строке все необходимые для сервера опции. Также можно вручную внести некоторые изменения в скрипт apachectl, в частности, изменив значение переменной HTTPD для запуска Apache из другого каталога, и указав опции, которые будут передаваться серверу каждый раз при его запуске командой

./bin/apachectl start

Скрипт apachectl принимает следующие команды:(предварительно проверяется синтаксис файла настройки)(нужен mod_status и lynx)(перезапуск без обрывания текущих соединений, статистика не сбрасывается; журналы закрываются не сразу, рекомендуемая пауза - 15 минут)

Содержимое скрипта apachectl представлено ниже:

#!/bin/sh

#

# Licensed to the Apache Software Foundation (ASF) under one or more

# contributor license agreements. See the NOTICE file distributed with

# this work for additional information regarding copyright ownership.

# The ASF licenses this file to You under the Apache License, Version 2.0

# (the "License"); you may not use this file except in compliance with

# the License. You may obtain a copy of the License at

#

#

#

# Unless required by applicable law or agreed to in writing, software

# distributed under the License is distributed on an "AS IS" BASIS,

# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

# See the License for the specific language governing permissions and

# limitations under the License.

#

#

# Apache control script designed to allow an easy command line interface

# to controlling Apache. Written by Marc Slemko, 1997/08/23

#

# The exit codes returned are:

# XXX this doc is no longer correct now that the interesting

# XXX functions are handled by httpd

#0 - operation completed successfully

#1 -

#2 - usage error

#3 - httpd could not be started

#4 - httpd could not be stopped

#5 - httpd could not be started during a restart

#6 - httpd could not be restarted during a restart

#7 - httpd could not be restarted during a graceful restart

#8 - configuration syntax error

#

# When multiple arguments are given, only the error from the _last_

# one is reported. Run "apachectl help" for usage info

#="$@"

#

# |||||||||||||||||||| START CONFIGURATION SECTION ||||||||||||||||||||

# ---------- ----------

#

# the path to your httpd binary, including options if necessary='/opt/apache2/bin/httpd'

#

# pick up any necessary environment variablestest -f /opt/apache2/bin/envvars; then

. /opt/apache2/bin/envvars

#

# a command that outputs a formatted text version of the HTML at the

# url given on the command line. Designed for lynx, however other

# programs may work. ="lynx -dump"

#

# the URL to your server's mod_status status page. If you do not

# have one, then status and fullstatus will not work.="

#

# Set this variable to a command that increases the maximum

# number of file descriptors allowed per child process. This is

# critical for configurations that use many file descriptors,

# such as mass vhosting, or a multithreaded server._MAX_FILES="ulimit -S -n `ulimit -H -n`"

# ---------- ----------

# |||||||||||||||||||| END CONFIGURATION SECTION ||||||||||||||||||||

# Set the maximum number of file descriptors allowed per child process.["x$ULIMIT_MAX_FILES" != "x"] ; then

$ULIMIT_MAX_FILES=0[ "x$ARGV" = "x" ] ; then ="-h"$ARGV in|stop|restart|graceful|graceful-stop)

$HTTPD -k $ARGV=$?

;;|sslstart|start-SSL)The startssl option is no longer supported.Please edit httpd.conf to include the SSL configuration settingsand then use "apachectl start".=2

;;)

$HTTPD -t=$?

;;)

$LYNX $STATUSURL | awk ' /process$/ { print; exit } { print } '

;;)

$LYNX $STATUSURL

;;

*)

$HTTPD $ARGV=$?$ERROR

Первым делом httpd находит и считывает конфигурационный файл httpd.conf. Путь к этому файлу задается еще во время сборки сервера, но его можно изменить и после этого, запустив сервер с опцией -f, как это показано в следующем примере

/usr/local/apache2/bin/apachectl -f /usr/local/apache2/conf/httpd.conf

Если во время запуска не возникло никаких проблем, то сервер отсоединится от консоли и приглашение на ввод командной строки вернется к пользователю практически мгновенно. Это указывает на то, что сервер запустился и теперь выполняет свою работу. Теперь можно, используя браузер, подключиться к нему и увидеть тестовую страницу, находящуюся в каталоге DocumentRoot, а также локальную копию документации.

Если во время запуска Apache произойдет какая-либо фатальная ошибка, то перед тем, как завершить свою работу, сервер пошлет на консоль или в ErrorLog сообщение, описывающее данную ошибку.

Скрипт apachectl разработан таким образом, что он может действовать как стандартный init-скрипт системы SysV. Он может принимать аргументы start, restart, и stop и переводить их в соответствующие сигналы процессу httpd. Поэтому для запуска сервер автоматически после перезагрузки системы, достаточно добавить вызов скрипта apachectl в системные файлы, отвечающие за загрузку операционной среды, расположенные в каталоге /etc/init.d/. Для этого возьмем стандартный init-скрипт httpd.init для Apache из директории /bin/rpm/ нашего дистрибутива и отредактируем его под свои нужды. Содержимое измененного скрипта представлено ниже:

#!/bin/bash

#

# Startup script for the Apache Web Server

#

# chkconfig: - 85 15

# description: Apache is a World Wide Web server. It is used to serve \

# HTML files and CGI.

# processname: httpd

# pidfile: /usr/local/apache2/logs/httpd.pid

# config: /usr/local/apache2/conf/httpd.conf

# Source function library.

/etc/rc.d/init.d/functions

[-f /etc/sysconfig/httpd]; then

/etc/sysconfig/httpd

# Path to the apachectl script, server binary, and short-form for messages.=/opt/apache2/bin/apachectl=/opt/apache2/bin/httpd=$httpd/logs/httpd.pid=httpd=0

# The semantics of these two functions differ from the way apachectl does

# things - attempting to start while running is a failure, and shutdown

# when not running is also a failure. So we just do it the way init scripts

# are expected to behave here.() {-n $"Starting $prog: "$httpd $OPTIONS=$?

[$RETVAL = 0] && touch /var/lock/subsys/httpd$RETVAL

}() {-n $"Stopping $prog: "$httpd=$?

[$RETVAL = 0] && rm -f /var/lock/subsys/httpd $pid

}() {-n $"Reloading $prog: "$httpd -HUP=$?

}

 

# See how we were called."$1" in)

;;)

;;)$httpd=$?

;;)

;;)[-f $pid] ; then

;;)

;;|help|configtest|fullstatus)

$apachectl $@=$?

;;

*)$"Usage: $prog {start|stop|restart|condrestart|reload|status"$"|fullstatus|graceful|h