date
int64
1,220B
1,719B
question_description
stringlengths
28
29.9k
accepted_answer
stringlengths
12
26.4k
question_title
stringlengths
14
159
1,387,757,805,000
What is the proper way to update an init script an ubuntu system? I am trying to upgrade my version of gitlab from 6-0 to 6-1, part of the upgrade consists of replacing the init script. Upgrade instructions - step 6 sudo rm /etc/init.d/gitlab sudo curl --output /etc/init.d/gitlab https://raw.github.com/gitlabhq/gitlabhq/6-1-stable/lib/support/init.d/gitlab sudo chmod +x /etc/init.d/gitlab I find that after updating the init script, calling script does nothing. Normally it prints out the processes id of the gitlab service root@gitlab:/etc/init.d# /etc/init.d/gitlab status root@gitlab:/etc/init.d# (notice how nothing happens) #No gitlab process is running root@gitlab:/etc/init.d# ps aux |grep gitlab root 4519 0.0 0.1 9384 928 pts/0 R+ 20:03 0:00 grep --color=auto gitlab Steps I have taken to troubleshoot this: Make sure it is executable root@gitlab:/etc/init.d# ll gitlab -rwxr-xr-x 1 root root 7195 Sep 28 19:29 gitlab* Strace the script root@gitlab:/etc/init.d# strace ./gitlab execve("./gitlab", ["./gitlab"], [/* 16 vars */]) = 0 brk(0) = 0xb29000 access("/etc/ld.so.nohwcap", F_OK) = -1 ENOENT (No such file or directory) mmap(NULL, 8192, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0x7fd33a1a8000 access("/etc/ld.so.preload", R_OK) = -1 ENOENT (No such file or directory) open("/etc/ld.so.cache", O_RDONLY|O_CLOEXEC) = 3 fstat(3, {st_mode=S_IFREG|0644, st_size=22291, ...}) = 0 mmap(NULL, 22291, PROT_READ, MAP_PRIVATE, 3, 0) = 0x7fd33a1a2000 close(3) = 0 access("/etc/ld.so.nohwcap", F_OK) = -1 ENOENT (No such file or directory) open("/lib/x86_64-linux-gnu/libc.so.6", O_RDONLY|O_CLOEXEC) = 3 read(3, "\177ELF\2\1\1\0\0\0\0\0\0\0\0\0\3\0>\0\1\0\0\0\200\30\2\0\0\0\0\0"..., 832) = 832 fstat(3, {st_mode=S_IFREG|0755, st_size=1811128, ...}) = 0 mmap(NULL, 3925208, PROT_READ|PROT_EXEC, MAP_PRIVATE|MAP_DENYWRITE, 3, 0) = 0x7fd339bc9000 mprotect(0x7fd339d7e000, 2093056, PROT_NONE) = 0 mmap(0x7fd339f7d000, 24576, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_FIXED|MAP_DENYWRITE, 3, 0x1b4000) = 0x7fd339f7d000 mmap(0x7fd339f83000, 17624, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_FIXED|MAP_ANONYMOUS, -1, 0) = 0x7fd339f83000 close(3) = 0 mmap(NULL, 4096, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0x7fd33a1a1000 mmap(NULL, 4096, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0x7fd33a1a0000 mmap(NULL, 4096, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0x7fd33a19f000 arch_prctl(ARCH_SET_FS, 0x7fd33a1a0700) = 0 mprotect(0x7fd339f7d000, 16384, PROT_READ) = 0 mprotect(0x619000, 4096, PROT_READ) = 0 mprotect(0x7fd33a1aa000, 4096, PROT_READ) = 0 munmap(0x7fd33a1a2000, 22291) = 0 getpid() = 4459 rt_sigaction(SIGCHLD, {0x40f100, ~[RTMIN RT_1], SA_RESTORER, 0x7fd339bff4a0}, NULL, 8) = 0 geteuid() = 0 brk(0) = 0xb29000 brk(0xb4a000) = 0xb4a000 getppid() = 4458 stat("/etc/init.d", {st_mode=S_IFDIR|0755, st_size=4096, ...}) = 0 stat(".", {st_mode=S_IFDIR|0755, st_size=4096, ...}) = 0 open("./gitlab", O_RDONLY) = 3 fcntl(3, F_DUPFD, 10) = 10 close(3) = 0 fcntl(10, F_SETFD, FD_CLOEXEC) = 0 rt_sigaction(SIGINT, NULL, {SIG_DFL, [], 0}, 8) = 0 rt_sigaction(SIGINT, {0x40f100, ~[RTMIN RT_1], SA_RESTORER, 0x7fd339bff4a0}, NULL, 8) = 0 rt_sigaction(SIGQUIT, NULL, {SIG_DFL, [], 0}, 8) = 0 rt_sigaction(SIGQUIT, {SIG_DFL, ~[RTMIN RT_1], SA_RESTORER, 0x7fd339bff4a0}, NULL, 8) = 0 rt_sigaction(SIGTERM, NULL, {SIG_DFL, [], 0}, 8) = 0 rt_sigaction(SIGTERM, {SIG_DFL, ~[RTMIN RT_1], SA_RESTORER, 0x7fd339bff4a0}, NULL, 8) = 0 read(10, "#! /bin/sh\n\n# GITLAB\n# Maintaine"..., 8192) = 7195 stat("/usr/local/sbin/sudo", 0x7fffcbf518d0) = -1 ENOENT (No such file or directory) stat("/usr/local/bin/sudo", 0x7fffcbf518d0) = -1 ENOENT (No such file or directory) stat("/usr/sbin/sudo", 0x7fffcbf518d0) = -1 ENOENT (No such file or directory) stat("/usr/bin/sudo", {st_mode=S_IFREG|S_ISUID|0755, st_size=71288, ...}) = 0 clone(child_stack=0, flags=CLONE_CHILD_CLEARTID|CLONE_CHILD_SETTID|SIGCHLD, child_tidptr=0x7fd33a1a09d0) = 4460 wait4(-1, [{WIFEXITED(s) && WEXITSTATUS(s) == 1}], 0, NULL) = 4460 --- SIGCHLD (Child exited) @ 0 (0) --- rt_sigreturn(0x11) = 4460 exit_group(1) = ? I am more familiar with Cent than Ubuntu, and I hear mixed opinions on manually executing update-rc.d. I've tried it anyway per the suggestion of this blog root@gitlab:/etc/init.d# sudo update-rc.d -f gitlab remove Removing any system startup links for /etc/init.d/gitlab ... /etc/rc0.d/K20gitlab /etc/rc1.d/K20gitlab /etc/rc2.d/S20gitlab /etc/rc3.d/S20gitlab /etc/rc4.d/S20gitlab /etc/rc5.d/S20gitlab /etc/rc6.d/K20gitlab root@gitlab:/etc/init.d# update-rc.d gitlab defaults Adding system startup for /etc/init.d/gitlab ... /etc/rc0.d/K20gitlab -> ../init.d/gitlab /etc/rc1.d/K20gitlab -> ../init.d/gitlab /etc/rc6.d/K20gitlab -> ../init.d/gitlab /etc/rc2.d/S20gitlab -> ../init.d/gitlab /etc/rc3.d/S20gitlab -> ../init.d/gitlab /etc/rc4.d/S20gitlab -> ../init.d/gitlab /etc/rc5.d/S20gitlab -> ../init.d/gitlab No luck, the script still doesn't run. Is there anything else that must be done on ubuntu systems to upgrade init scripts? Update1: Looking at /var/log/auth.log shows: vagrant@gitlab:~$ sudo su - root@gitlab:~# /etc/init.d/gitlab status root@gitlab:~# tail /var/log/auth.log Sep 28 20:52:31 gitlab su[2205]: pam_unix(su:session): session closed for user root Sep 28 20:52:31 gitlab sudo: pam_unix(sudo:session): session closed for user root Sep 28 20:52:34 gitlab sudo: vagrant : TTY=pts/0 ; PWD=/home/vagrant ; USER=root ; COMMAND=/bin/su - Sep 28 20:52:34 gitlab sudo: pam_unix(sudo:session): session opened for user root by vagrant(uid=1000) Sep 28 20:52:34 gitlab su[2311]: Successful su for root by root Sep 28 20:52:34 gitlab su[2311]: + /dev/pts/0 root:root Sep 28 20:52:34 gitlab su[2311]: pam_unix(su:session): session opened for user root by vagrant(uid=0) Sep 28 20:52:43 gitlab sudo: root : TTY=pts/0 ; PWD=/root ; USER=git ; COMMAND=/bin/false -c /etc/init.d/gitlab status Sep 28 20:52:43 gitlab sudo: pam_unix(sudo:session): session opened for user git by vagrant(uid=0) Sep 28 20:52:43 gitlab sudo: pam_unix(sudo:session): session closed for user git Update2 I've done a diff of the init scripts between 6-0-stable and 6-1-stable. It appears to have been an almost complete rewrite. The diff is located here: https://gist.github.com/spudstud/6747146#file-diff-gitlab-init-scripts You can see the actual 6-0 script here: https://github.com/gitlabhq/gitlabhq/blob/6-0-stable/lib/support/init.d/gitlab and the 6-1 script here: https://github.com/gitlabhq/gitlabhq/blob/6-1-stable/lib/support/init.d/gitlab Update3 Tried starting script using bash -x root@gitlab:/etc/init.d# bash -x /etc/init.d/gitlab start + RAILS_ENV=production + app_root=/home/git/gitlab + app_user=git + unicorn_conf=/home/git/gitlab/config/unicorn.rb + pid_path=/home/git/gitlab/tmp/pids + socket_path=/home/git/gitlab/tmp/sockets + web_server_pid_path=/home/git/gitlab/tmp/pids/unicorn.pid + sidekiq_pid_path=/home/git/gitlab/tmp/pids/sidekiq.pid + '[' root '!=' git ']' + sudo -u git -H -i /etc/init.d/gitlab start + exit Success, It appears that the script must be run as the user 'git'.
To debug bash or shell scripts, it's useful to either run it with bash -x or edit the script and add a line saying set -x. This will show the execution trace of each line in the script as it is executed, along with the value of variable assignments.
How to update an init script
1,387,757,805,000
I'm running into a strange (to me) problem. I'm running a gentoo with two net interfaces: enp5s0 (wired interface) and wlan0 (wifi). When I try to run a program, for example openvpn, from its script in /etc/init.d, it outputs: * WARNING: openvpn is scheduled to start when net.enp5s0 has started and doesn't start if the interface enp5s0 is not started, even if the other interface is up. In /etc/init.d/openvpn, I've got these lines: depend() { need localmount net use dns after bootmisc } and in /etc/init.d/net.enp5s0 and /etc/init.d/net.wlan0 (which are in fact symlinks to /etc/init.d/net.lo, Gentoo deals with the name of the script to know what it should do): depend() { [...] case "${IFACE}" in lo|lo0) ;; *) after net.lo net.lo0 dbus provide net ;; esac [...] } So, as I understand the case, whichever of my interface provides the net "capacity" (I don't have the correct/canonical word for it), and openvpn should only rely on this capacity, and not on a particular interface. The same problem occurs with all the program that have the need net dependency. What am I missing here? My uname -a if it can be of some help: Linux yavin 3.7.10-gentoo-r1 #2 SMP Sat Apr 20 16:27:52 CEST 2013 x86_64 Intel(R) Core(TM) i3 CPU M 330 @ 2.13GHz GenuineIntel GNU/Linux
Ok, so reading the comments in configuration files does work sometimes... I was right supposing that net works as a "virtual dependency" in the sense that more than one service can actually provide it. And it is actually documented that way in the manual: http://www.gentoo.org/doc/en/handbook/handbook-x86.xml?part=2&chap=4. But in fact, this is configurable and this behavior is not the default (at least, I don't remember having modified it once). The /etc/rc.conf file can be used to customise the way init and the init-scripts work. And there is an interesting option in it. # Do we allow any started service in the runlevel to satisfy the dependency # or do we want all of them regardless of state? For example, if net.eth0 # and net.eth1 are in the default runlevel then with rc_depend_strict="NO" # both will be started, but services that depend on 'net' will work if either # one comes up. With rc_depend_strict="YES" we would require them both to # come up. #rc_depend_strict="YES" As you see, this is exactly what I need, and it was simply defaulted to the wrong value (from my point of view). Setting this option to NO solved my problem. Before: yavin ~ # /etc/init.d/openvpn ineed * Caching service dependencies ... [ ok ] fsck dmcrypt localmount sysfs net.wlan0 net.enp5s0 After (in the case wlan0 is up; I guess I'd have enp5s0 instead of wlan0 if enp5s0 were up): yavin ~ # /etc/init.d/openvpn ineed * Caching service dependencies ... [ ok ] fsck dmcrypt localmount sysfs net.wlan0
"provide net" in gentoo init script doesn't work as I thought
1,387,757,805,000
I've created a gentoo-live system which should be booted from a CF-card. The whole file-system is in a squashfs. I've created a custom initrd which first mounts the CF-card and from there the squashed filesystem into what will become /. I'd like /etc to be writable so I've copied it to the CF-card added a bind. This however does not seem to work. The system boots but /etc is not mounted. I'd like to know if my approach is right and what I can do to fix it or if not what would be the right way to achieve this. Here's the init-script from my initrd: #!/bin/busybox sh mount -t proc none /proc mount -t sysfs none /sys mount /dev/sda1 /mnt/flash mount -o loop /mnt/flash/filesystem.squashfs /mnt/root mount -B /mnt/flash/etc /mnt/root/etc mount -o remount,rw /mnt/root/etc umount /proc umount /sys exec switch_root /mnt/root /sbin/init This is the shortened output of cat /proc/mounts: rootfs / rootfs rw 0 0 /dev/sda1 /mnt/flash ext2 rw,relatime,errors=continue,user_xattr,acl 0 0 /dev/loop0 / squashfs ro,relatime 0 0 ...
BusyBox's built-in mount command doesn't recognize -B; you'll have to use -o bind: mount -o bind /mnt/flash/etc /mnt/root/etc Also, I think the remounting is unnecessary if /mnt/flash is already writable. But try fixing the bind mounting first.
Mount /etc from disc into squashfs
1,387,757,805,000
Here's how I configured my kickstart system initialization script (this is a kickstart conf script snippet): ... %post --log=/root/ks-post.log --interpreter /bin/bash cd /root curl --silent --show-error --retry 5 -O "https://mysecurewebsite.net/init-script7.sh" cp init-script.sh /etc/init.d/initializesystem chmod +x /etc/init.d/initializesystem [ ! -d /etc/rc.d ] && echo "/etc/rc.d/ not present, creating dir." && mkdir /etc/rc.d [ ! -d /etc/rc.d/rc3.d ] && echo "/etc/rc.d/rc3.d/ not present, creating dir." && mkdir /etc/rc.d/rc3.d ln -s /etc/init.d/initializesystem /etc/rc.d/rc3.d/S30initializesystem %end This works great and runs in the background unattended upon first boot after the OS installation. However I would like to make this even more friendly by letting the default bootup tty to display the stdout of this initializesystem script. Currently I have the script writing its progress to a log file, and I have to log in as root and tail -f the log file. I'd like to still be able to do this if I want, but I want to know if it is possible to also just have it automatically show the output without requiring me to log in. One thing to note is that I don't want to make the system completely uninteractive. For instance I would like to be able to Ctrl+Alt+F2 and login to do some administration while this script proceeds. I would also prefer it if a Ctrl+C wasn't able to kill this particular script while it runs, though I suspect that can be an easy thing to set up for handling the SIGINT, so forget that I mentioned it. Is this possible? Using Centos 7 here.
As you indicate yourself, as root you can just write things to /dev/tty1. If your script does write to stdout you can use: yourscript | tee -a /your/log/file > /dev/tty1 if the script directly writes to the log file things are not so easy, you would have to follow the log file and display new content. In that case it is probably easier to change the script to use some print routine in which you can easily double the output. There is no way this can be stopped by using Ctrl+C, not even if you have logged in first on the console, as there is no way for your shell to know where to sent the interrupt. Depending on your startup preferences, whether you have a graphical login or not, you might want to use /dev/tty2 as not to clobber the first screen. You should also consider starting the log with a newline so the first text doesn't appear after the machinename login: prompt that is at the top of the screen. I don't think there is a way to scroll back on the console you have been writing to in this way, but that might not be important.
Run a script as root during boot and display in the default linux terminal?
1,387,757,805,000
I've been studying process management using shell scripts and I'm starting to realise how difficult it is to make sure that it's done right. For example, you can record the PID of a program to a file, wait on it, and clean up the PID file after the program exits. If you were to try and kill this daemon from an init script, for example, you might think of doing something like this: do_stop() { kill $(</var/run/program.pid) } This obviously doesn't work. Between obtaining the PID and sending the kill signal, another process could have died and taken its place. The correct way seems to require using IPC in the parent of the program to send a kill signal to its child. This will ensure that the PID of the process hasn't been reused by another. I've been trying to write my own init scripts that are as correct as possible. In this case, I've been writing one for NRPE. NRPE unfortunately daemonizes and disowns itself to init, which means I can't wait on it. Instead, I came up with the following solution: do_stop() { echo "Stopping (sending SIGTERM to) nrpe" pkill -u nrpe || { echo >&2 "nrpe isn't running"; exit 1; } } The only process that the nrpe user runs is NRPE itself, and considering the system is under my control I consider this a relatively sane solution. What I'm curious about is the atomicity of pkill (if that's the right word to use). I assume pkill follows these steps: Looks up the PID in the process table after parsing the arguments for the process criteria. Sends SIGTERM (by default) to the obtained PID Let's say pkill -u nrpe gives a PID of 42 in step 1. Is it possible that nrpe's process could die and another one could spawn in its place before step 2 occurs?
You are correct to suspect that there is a (small!) atomicity problem. No matter what method you use, whether it's a system-standard utility like start-stop-daemon, a roll-your-own PID file, using pkill to query and kill by user ID, by executable binary, or whatever, there is always an interval between finding what process you want to kill and giving that process ID to the kill system call to send it a signal. Basically, you should just not worry about it. In order to run into trouble, both of the following would have to happen: The target process dies between the time you identity its process ID and the time you actually kill it. The process IDs for newly created process would have to, during the same time interval, happen to cycle around to reuse the process ID just vacated. It's just really unlikely. Note that in the particular case you're studying, you actually do have a way of protecting yourself against this. The only process that the nrpe user runs is NRPE itself, so if you switch to the nrpe user (from root, probably) before issuing the kill command, you might under very unlikely circumstances try to kill a poor innocent process belonging to something else, but you won't have permission to do it and it won't have any effect.
Process management and pkill
1,387,757,805,000
Apologies if this is an obvious answer, I am a Windows admin professionally and only use Linux in my homelab to try to learn new things - so I'm very inexperienced with Linux. I am working on writing a Puppet module to install/configure Sonarr, and am running into trouble with getting Sonarr set up as a service (testing on Ubuntu 14.04 LTS). The install and creation of the script are going fine, but I am running into problems getting the service to actually start. Here is the init.d script I have, courtesy of shameless stealing from the internet: #!/bin/sh ### BEGIN INIT INFO # Provides: nzbdrone # Required-Start: $local_fs $network $syslog # Required-Stop: $local_fs $network $syslog # Default-Start: 2 3 4 5 # Default-Stop: 0 1 6 # Short-Description: Example # Description: Example start-stop-daemon - Debian ### END INIT INFO NAME="nzbdrone" PATH="/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin" APPDIR="/opt/NzbDrone" APPBIN="/usr/bin/mono" APPARGS="/opt/NzbDrone/NzbDrone.exe" USER="nzbdrone" GROUP="nzbdrone" # Include functions set -e . /lib/lsb/init-functions start() { printf "Starting '$NAME'... " start-stop-daemon --start --chuid "$USER:$GROUP" --background --make-pidfile --pidfile /var/run/$NAME.pid --chdir "$APPDIR" --exec "$APPBIN" -- $APPARGS || true printf "done\n" } #We need this function to ensure the whole process tree will be killed killtree() { local _pid=$1 local _sig=${2-TERM} for _child in $(ps -o pid --no-headers --ppid ${_pid}); do killtree ${_child} ${_sig} done kill -${_sig} ${_pid} } stop() { printf "Stopping '$NAME'... " [ -z `cat /var/run/$NAME.pid 2>/dev/null` ] || \ while test -d /proc/$(cat /var/run/$NAME.pid); do killtree $(cat /var/run/$NAME.pid) 15 sleep 0.5 done [ -z `cat /var/run/$NAME.pid 2>/dev/null` ] || rm /var/run/$NAME.pid printf "done\n" } status() { status_of_proc -p /var/run/$NAME.pid "" $NAME && exit 0 || exit $? } case "$1" in start) start ;; stop) stop ;; restart) stop start ;; status) status ;; *) echo "Usage: $NAME {start|stop|restart|status}" >&2 exit 1 ;; esac exit 0 The problem is, this won't start. Or more precisely, it starts but syslog shows that the process is crashing, then being restarted, over and over. The thing that puzzles me is that if I run /etc/init.d/nzbdrone start, the process starts great. It is only when I run service nzbdrone start that it starts the crashing over and over. My google-fu turned up this similar question, but the answer there made mention of environment variables and I can't spot anything in this script that isn't being initialized by the script. Can anyone help me spot what is going on here?
I wound up finding the issue, or possibly issues. I first noticed that in my Puppet code that was creating the user to run the service, the variable for the user's home dir was misspelled (which caused the user's home dir to be set to "/home/" in /etc/passwd). Second, I realized that Puppet does not automatically create the home dir unless you tell it to, so I went ahead and had Puppet manage the user's home dir. Finally, I set the user's shell to /bin/bash after finding another Stack Exchange answer which mentioned that they had a similar issue when their service user's shell was set to /bin/false. When I corrected all of these issues, the service starts great. I'm not sure if it was only one of these or a combination of multiple, but hopefully this will help someone else if they run into similar issues in the future.
Trying to create a service but it won't start
1,387,757,805,000
I have a Raspberry PI running the standard Raspbian distribution. I have this little C program that I need to run at the very end of the shutdown sequence. All it does is send a couple of logical high pulses on a GIPO output to a power supply to tell it to cut the power to the Raspberry board. The shutdown script should be called if, and only if, the system is being powered down but not when the PI is being rebooted or started up. I have been trying and failing to use update-rc.d to do this. The way I understand the update-rc.d documentation what I have to do is: Copy my executable (poweroff.bin), copy it to /sbin and give it the required permissions and a LSB header: #!/bin/sh ### BEGIN INIT INFO # Provides: poweroff # Required-Start: # Required-Stop: $all # Default-Start: # Default-Stop: 0 # Short-Description: Power off. # Description: Send a power off signal to the PM board. # X-Interactive: false ### END INIT INFO /sbin/poweroff.bin exit 0 Create a script called poweroff in /etc/init.d Run the command sudo update-rc.d poweroff stop 99 0. This will yield me a script: /etc/rc0.d/K99poweroff which will call /sbin/poweroff.bin if, and only if the system is being halted. I have three questions: Whenever I run sudo update-rc.d poweroff stop 99 0 . it only results in a script called /etc/rc0.d/K01poweroff being created. What am I doing wrong? what happened to the 99? What is the significance of the start and stop options during run level 0? Should this script be a K99 or an S99? there seems little point in a start script in run level 0. Is run level 0 only used when shutting down? I.e if I do a 'shutdown -r now" does the computer get sent down to run level 0 and then back to runlevel 6?
The numbering requested is ignored by dependency based meta init systems. you have the wrong provides!. The critical clue is from another script. lets take a look at umountroot: ### BEGIN INIT INFO # Provides: umountroot # Required-Start: # Required-Stop: # Should-Stop: halt reboot kexec # Default-Start: # Default-Stop: 0 6 # Short-Description: Mount the root filesystem read-only. ### END INIT INFO Lets look closely at the Should-Stop line. notice that it depends on halt, not poweroff. We can see this definitively by looking at debian's halt script: ### BEGIN INIT INFO # Provides: halt # Required-Start: # Required-Stop: # Default-Start: # Default-Stop: 0 # Short-Description: Execute the halt command. # Description: ### END INIT INFO Note that the update script will still not call it K99, but will probably call it something like K15 unless you have a very complicated set of dependencies. but if you change your provides line to halt, it should work.
Creating a shutdown only script with update-rc.d
1,387,757,805,000
Why is it that I have to type /etc/init.d/apache2 (args) in order to run apache?? Isn't there a way to just apache2 args ??
You don't normally type a command to run Apache: it starts when the system boots. Scripts in /etc/init.d start services and are executed automatically at boot time, if your system is set up correctly. With most distributions, services are enabled by default and will start unless you've done something to disable them. If you've stopped Apache and want to restart it, /etc/init.d/apache2 start is the normal way — or preferably service apache2 start. It would be of little use to have a shorter command since this is not something that you would do as part of normal system use. Commands that are intended for common use are can be executed without specifying their full path; these commands are in directories listed in the PATH environment variable (which Windows imitates).
Executing programs without having to specify a directory?
1,387,757,805,000
So I am trying to start a service on systemd enabled system. Name of service is ossec-hids-authd which is the authentication engine(agents) in ossec(Intrusion Detection Software). When I go and start the init script then systemctl times out and on getting the status I am seeing this error. /etc/init.d/ossec-hids-authd status ● ossec-hids-authd.service - LSB: Authentication Daemon for OSSEC-HIDS. Loaded: loaded (/etc/rc.d/init.d/ossec-hids-authd; bad; vendor preset: disabled) Active: failed (Result: timeout) since Thu 2018-02-22 07:34:28 UTC; 11min ago Docs: man:systemd-sysv-generator(8) Feb 22 07:24:11 ip-10-0-197-117.ec2.internal systemd[1]: Starting LSB: Authentication Daemon for OSSEC-HIDS.... Feb 22 07:24:11 ip-10-0-197-117.ec2.internal ossec-hids-authd[21142]: [39B blob data] Feb 22 07:24:11 ip-10-0-197-117.ec2.internal systemd[1]: PID file /var/run/ossec-authd.pid not readable (yet?) after start. Feb 22 07:24:11 ip-10-0-197-117.ec2.internal ossec-hids-authd[21142]: 2018/02/22 07:24:11 ossec-authd: INFO: Started (pid: 21148). Feb 22 07:34:28 ip-10-0-197-117.ec2.internal systemd[1]: ossec-hids-authd.service start operation timed out. Terminating. Feb 22 07:34:28 ip-10-0-197-117.ec2.internal systemd[1]: Failed to start LSB: Authentication Daemon for OSSEC-HIDS.. Feb 22 07:34:28 ip-10-0-197-117.ec2.internal systemd[1]: Unit ossec-hids-authd.service entered failed state. Feb 22 07:34:28 ip-10-0-197-117.ec2.internal systemd[1]: ossec-hids-authd.service failed. Feb 22 07:40:20 ip-10-0-197-117.ec2.internal ossec-hids-authd[21142]: 2018/02/22 07:40:20 ossec-authd(1225): INFO: SIGNAL [(15)-(Terminated)] Received. Exit Cleaning... Now in the init script this process is actually making pid file in /var/ossec/var/run instead of /var/run and I checked pid file is actually created there. But somehow systemctl is failing to recognize it. Is it possible that systemd does not recognize pid files created outside of /var/run and if such is the case how to do that? Below is the init script #!/bin/sh # # ossec-authd Start the OSSEC-HIDS Authentication Daemon # # chkconfig: 2345 99 01 # description: Provides key signing for OSSEC Clients # processname: ossec-authd # config: /var/ossec/etc/ossec.conf # pidfile: /var/run/ossec-authd.pid ### BEGIN INIT INFO # Provides: ossec-authd # Required-Start: $network $local_fs $remote_fs # Required-Stop: $network $local_fs $remote_fs # Default-Start: 2 3 4 5 # Default-Stop: 0 1 6 # Short-Description: Authentication Daemon for OSSEC-HIDS. # Description: Provides key signing for OSSEC Clients ### END INIT INFO # Author: Brad Lhotsky <[email protected]> NAME=ossec-authd DAEMON=/var/ossec/bin/ossec-authd DAEMON_ARGS="-p 1515 2>&1 >> /var/ossec/logs/ossec-authd.log &" PIDDIR=/var/ossec/var/run SCRIPTNAME=/etc/init.d/ossec-authd . /etc/rc.d/init.d/functions getpid() { for filename in $PIDDIR/${NAME}*.pid; do pidfile=$(basename $filename) pid=$(echo $pidfile |cut -d\- -f 3 |cut -d\. -f 1) kill -0 $pid &> /dev/null RETVAL=$? if [ $RETVAL -eq 0 ]; then PIDFILE=$filename PID=$pid else rm -f $filename fi; done; } start() { echo -n $"Starting $NAME: " daemon $DAEMON $DAEMON_ARGS retval=$? if [ $retval -eq 0 ]; then echo_success echo else echo_failure echo fi return $retval } stop() { echo -n $"Stopping $NAME: " getpid killproc -p $PIDFILE $NAME retval=$? echo return $retval } restart() { stop start } case "$1" in start) start ;; stop) stop ;; status) getpid if [ -z $PIDFILE ]; then status $NAME else status -p $PIDFILE $NAME fi; ;; restart) restart ;; *) echo "Usage: $0 {start|stop|status}" exit 2 ;; esac exit $?
systemd parses an init script's comments to generate temporary .service file at boot or upon daemon-reload command. Change the line # pidfile: /var/run/ossec-authd.pid to # pidfile: /var/ossec/var/run/ossec-authd.pid and run systemctl daemon-reload UPD: now I see that pid file name is generated by authd at runtime and init script has to search for $PIDDIR/${NAME}*.pid. Systemd can not search for pidfile, but can work without it. Sou you may try to remove # pidfile: line completely, or write your own .service file
systemd failing to recognize pid file
1,387,757,805,000
Why programs run at boot/shutdown are written in bash script? If a compiled language (or a faster interpreted language, like Python) was used, then its running time would be shorter.
It is largely historic, partly a matter of control from a system administration aspect, partly a portability issue, partly a debugging issue. "Back in the day", there was no autoconf, dpkg, rpm. You downloaded the software, sometimes from UUCP, compiled the product and determined - with your own conventions - where to install the product. Hooking the product up to the boot/shutdown system was thought to be a duty of the system administrator. The sysadmin would write the rc script and place it in the appropriate place for that system (/etc/inittab, /etc/rcN.d/, /etc/rc.local, /etc/inetd.conf). With fewer of the non-linux systems in the forefront, the advent of rpm and dpkg makes some of these local choices less important. Systems administrators also like to have some measure of control over their systems, and the easiest write, debug and modify later are shell scripts, not C programs. As I alluded to earlier, different UNIX OSs had different ways to boot. Writing a short shell script for your own system was much easier than the developer writing for every possible flavor of UNIX that was coming up (again, this was before even autoconf): SysV, Ultrix, Irix, HP-UX, SunOS, Solaris, NextStep, NonStop, etc. For the most part, they fell into two or three mechanisms, but each had their own twist. Boot systems can get complicated easily. It's good to have a shell script where you can print debugging information, change the flow, handle interactions that the program authors didn't anticipate. If this was a compiled program, it would make finding such errors much more difficult. Modern systems have newer mechanisms, but most will still call shell scripts, largely for the reasons above.
Why is bash used in boot scripts?
1,387,757,805,000
I'm porting a Debian init.d script to CentOS. In the Debian script, it uses start-stop-daemon for launching the process. The script uses start-stop-daemon's --group flag to change to a different group-id when starting the daemon process. How do I set the group-id of the daemon process in the init script on CentOS?
CentOS init scripts use /etc/init.d/functions, which declares a "daemon" function that most other init scripts use. But daemon doesn't accept any group flags. It ends up calling: $nice runuser -s /bin/bash - $user -c "$corelimit >/dev/null 2>&1 ; $*" A quick /sbin/runuser --help shows that runuser accepts a flag to specify group, so try: runuser -g $group; daemon ...
How do I set the group (gid) of a process I'm about to launch?
1,387,757,805,000
I am trying to change user in order to execute a specific command during startup. It fails silently and apparently the userchange isn't carried out as I can tell that the command isn't executed. What am I doing wrong in my below shown initscript? respawn console none start on startup stop on shutdown script su -u anotheruser -c "myCommand" >> "myLogfile.log" end script
I'm assuming you are running recent version of ubuntu or a distribution based on upstart. You can check /var/log/daemon.log for errors. The standard su takes the syntax su [options] [username]. Checkout man 1 su. You might want to try : su -c "myCommand" anotheruser >> "myLogfile.log" Also, a couple of things would happen (mostly not desirable) myLogfile.log would be owned by root. myLogfile.log would be created on / (root directory) if you don't use an absolute path like /tmp/myLogfile.log (because upstart runs with pwd set to /). If you want the file to be owned by anotheruser you might switch the command to. su -c "myCommand >> /tmp/myLogfile.log" anotheruser This might cause problems if you have leftover myLogfile.log owned by root from earlier runs or if have not changed myLogfile.log to something like /tmp/myLogfile.log (normally, regular users can't create files on root dir /).
Changing user in a script?
1,387,757,805,000
I have set up an init-script to control the state of a VirtualBox VM: #!/bin/sh #chkconfig: 35 99 5 #description: vTiger virtual machine ### BEGIN INIT INFO # Provides: vtigervm # Required-Start: $local_fs # Requider-Stop: $stop_fs # Default-Start: 3 5 # Default-Stop: 0 1 2 6 # Short-Description: Manage vTiger virtual machine # Description: Utility to start and stop vTiger virtual machine on VirtualBox ### END INIT INFO start() { echo -n "Starting vTiger" echo su myuser -c '/usr/bin/VBoxManage startvm "vTiger" --type headless' echo "Started virtual machine" >> /var/log/messages } stop() { echo -n "Shutting vTiger down..." echo su myuser-c '/usr/bin/VBoxManage controlvm "vTiger" acpipowerbutton' while [ ! -z "`su - juhani -c '/usr/bin/VBoxManage list runningvms | grep vTiger'`" ]; do echo -n "." sleep 1 done echo "Done." echo "Stopped virtual machine" >> /var/log/messages } status() { echo -n "Running VMs: " su myuser -c '/usr/bin/VBoxManage list runningvms' echo if [ -z "`su - juhani -c '/usr/bin/VBoxManage list runningvms | grep vTiger'`" ]; then RETVAL=3 else RETVAL=0 fi echo "Queried virtual machine status" >> /var/log/messages } echo "Called virtual machine management script with: $1" >> /var/log/messages case "$1" in start) start ;; stop) stop ;; restart|try-restart|condrestart|reload) stop start ;; status) status ;; *) echo $"Usage: $0 {start|stop|restart|status}" exit 1 ;; esac exit $RETVAL The system is CentOS 6.5. If I manually run service [start|stop|status] vtigervm, it works as I expect it to. If the VM is running, $? after the service vtigervm status returns 0, and 3 if it is stopped. I installed it with chkconfig and it created among a few others rc5.d/S99vtigervm and rc0.d/K05vtigervm. The problem When I start the system it starts the "service", but on shutdown it does not even run the scripts. grep "virtual machine" /var/log/messages shows: *[machine starting]* Called virtual machine management script with: start Started virtual machine *[shutdown -h now]* *[machine stopped]* What I expect: *[machine starting]* Called virtual machine management script with: start Started virtual machine *[shutdown -h now]* Called virtual machine management script with: status Queried virtual machine status Called virtual machine management script with: stop Stopped virtual machine *[machine stopped]* File permissions & etc: # ls -lah /etc/rc0.d/ lrwxrwxrwx. 1 root root 13 7.2. 17:49 /etc/rc0.d/K05atd -> ../initd.d/atd lrwxrwxrwx. 1 root root 18 9.2. 00:06 /etc/rc0.d/K05vtigervm -> ../initd.d/vtigervm
Idea #1 Try putting a -x at the top of the service script, this will put the shell into debug mode so that you'll get any output that's being generated by the script. #!/bin/sh -x Idea #2 Also you might want to add the process name to the top of the chkconfig comment macros as well. # processname: vtigervm You may need to change this value to whatever's appropriate for you situation. Idea #3 As suggested in @RickBeam's answer and confirmed by this link I found on the CentOS forums, titled: "chkconfig/init.d not calling shutdown with solution", you'll need to manage the creation and destruction of a file in /var/lock/subsys. You can add these lines to your start() and stop() functions to do it: start() { ... touch /var/lock/subsys/vtigervm } stop() { ... rm -f /var/lock/subsys/vtigervm }
An init-script does not get called on shutdown
1,387,757,805,000
I created a small script backup_files.sh and placed it in /etc/init.d: #/bin/sh logfile=/media/verbatim/log date >> $logfile rsync -av /home/philipp/Documents /media/verbatim/ >> $logfile I would like this script to be executed whenever the computer is rebooted or shut down, so I did the following: sudo ln -s /etc/init.d/backup_files.sh /etc/rc0.d/backup_files.sh sudo ln -s /etc/init.d/backup_files.sh /etc/rc6.d/backup_files.sh Moreover, I made the script executable: sudo chmod +x /etc/init.d/backup_files.sh I tried the script "manually" and it worked just fine. However, if I shutdown or reboot my computer, it is apparently not executed. Does anybody see what I'm doing wrong? Note: I'm using Xubuntu 11.10.
Finally found out that I had to give them particular file names: sudo ln -s /etc/init.d/backup_files.sh /etc/rc0.d/K10backup_files.sh sudo ln -s /etc/init.d/backup_files.sh /etc/rc6.d/K10backup_files.sh The scripts in /etc/rc0.d and /etc/rc6.d are executed at the time of shutdown and reboot respectively. The scripts with their name starting with capital k are executed with an argument stop while those starting with capital S are executed with argument start. Moreover the execution of files is done in lexicographical order. The files in these runlevels are named as: [K | S] + nn + [string] nn -> a two digit number string -> must be a lowercase string More about linux runlevels can be found here
Running script before shutdown seemingly not working
1,387,757,805,000
I am trying to get an init script running that starts nodejs as a daemon. The problem is, that when I executing start-stop-daemon it always returns '0', regardless of what error the nodejs-daemon may return. I got as far as figuring out that the issue arises when using start-stop-daemon with the --background switch. With the switch, start-stop-daemon always returns '0', even when the nodejs-daemon fails. root# start-stop-daemon --start --chuid $GHOST_USER:$GHOST_GROUP --chdir $GHOST_ROOT --make-pidfile --pidfile $PIDFILE --exec $DAEMON --background -- $DAEMON_ARGS ; echo ---error: $? ---error: 0 Note, that the daemon silently failed and is NOT running at this moment! Without the switch, we can actually see the daemon failing to start. root# start-stop-daemon --start --chuid $GHOST_USER:$GHOST_GROUP --chdir $GHOST_ROOT --make-pidfile --pidfile $PIDFILE --exec $DAEMON -- $DAEMON_ARGS ; echo ---error: $? ERROR: Unsupported version of Node Ghost needs Node version ~0.10.0 || ~0.12.0 || ^4.2.0 you are using version 5.10.0 Please see http://support.ghost.org/supported-node-versions/ for more information ---error: 231 Now I am looking to find a solution so I can use the --background switch and having a error code bigger than '0' when it fails to start the nodejs daemon.
This is documented behavior. The foreground process completes after forking the background process. From the man page: -b, --background Typically used with programs that don't detach on their own. This option will force start-stop-daemon to fork before starting the process, and force it into the background. Warning: start-stop-daemon cannot check the exit status if the process fails to execute for any reason. This is a last resort, and is only meant for programs that either make no sense forking on their own, or where it's not feasible to add the code for them to do this themselves.
start-stop-daemon always returns '0' although the process fails
1,387,757,805,000
I built ntpd from source, which process put it in /usr/local/sbin. Of course, the ntp service points to /usr/sbin. So, I thought I could just change the path in the init.d configuration file like this: ### BEGIN INIT INFO # Provides: ntp # Required-Start: $network $remote_fs $syslog # Required-Stop: $network $remote_fs $syslog # Default-Start: 2 3 4 5 # Default-Stop: # Short-Description: Start NTP daemon ### END INIT INFO PATH=/sbin:/bin:/usr/sbin:/usr/bin . /lib/lsb/init-functions DAEMON=/usr/local/sbin/ntpd PIDFILE=/var/run/ntpd.pid ...[etc] I changed the line starting with "DAEMON" to point to the location of the new binary. However, when I try to restart the service I get the error: [ ok ] Stopping NTP server: ntpd. [....] Starting NTP server: ntpd/usr/local/sbin/ntpd: The 'user' option has been disabled. -- built without --enable-clockctl or --enable-linuxcaps or --enable-solarisprivs ntpd - NTP daemon program - Ver. 4.2.7p475 Usage: ntpd [ -<flag> [<val>] | --<name>[{=| }<val>] ]... \ [ <server1> ... <serverN> ] Try 'ntpd --help' for more information. failed! How can I have the service run from /usr/local/sbin instead of /usr/sbin? Solution (based on accepted answer): Apparently when building on Linux you need to use the switch --enable-linuxcaps when building on Linux. Here are the steps necessary on Debian Wheezy: cd ~/install/ntp-dev-4.2.7p475 # or wherever you have the source unpacked make clean # clean out the previous build sudo apt-get install libcap-dev # this library is required by linuxcaps ./configure --enable-linuxcaps # this is the critical switch make sudo make install sudo /etc/init.d/ntp restart # restart ntp ntpq -c "rv 0 version" # make sure you are running the right version The only line you have change in /etc/init.d/ntp is the DAEMON line, as said above.
You've built ntpd without the --enable-linuxcaps option. Without this, ntpd won't recognise the user option -u. Your options are: Recompile with the correct option Remove the -u $UGID from the NTPD_OPTS line in /etc/init.d/ntp
Unable to start locally-built ntpd from system service script
1,387,757,805,000
I am using raspbian. (Debian variant). By default, openvpn is started with /etc/rc2.d/S03openvpn. I set up an /etc/init.d script with a symlink /etc/rc2.d/S04daemonname for a daemon I want to start after openvpn has started and a connection to my vpn provider has been established. The openvpn startup and connection works fine. However my daemon that I want to use the vpn connection seems to start up before the connection is established, since it uses my standard ip. If I kill the daemon and restart it in the terminal, it is then using the desired vpn ip. How would I make it so my daemon runs at startup once the vpn connection is established? Can I do this by waiting until tun0 device has been created (how?), or is the tun0 creation not synonymous with established connection meaning this might be too early? I've also looked into using the run time dependencies LSB tags in the init.d script, but can't find how to make a certain network device (tun0) a requirement and again, I'm unsure whether this would work. There is also a file in /etc/NetworkManager/VPN/ referencing the openvpn service, but I'm not sure how to use this or if the NetworkManager daemon is even being used because /VPN is the only subdirectory of it. I would like solutions that are precise, eg. not just putting my init.d script with a low enough run priority in /etc/rc2.d/ or waiting until the openvpn connection should be established.
You can run scripts from openvpn with e.g. the --up scriptname option. This would seem to me to be better than expecting the connection to be established a certain time after starting the openvpn process. You may have to experiment a bit with the possible ways of running scripts from openvpn, e.g. not using --up but instead using --client-connect etc.; check the openvpn manpage for more information.
Run daemon on startup in Debian once openvpn connection established
1,387,757,805,000
I have set up start-stop-daemon to start my script automatically case "$1" in start) log_begin_msg "starting foo" start-stop-daemon --start --chuid nobody --user nobody --pidfile \ /tmp/foo.pid --startas /usr/local/bin/foo.sh & log_end_msg $? the problem is, it always returns 0 (success),even if the process was not started. How can I capture the return code of start-stop-daemon properly ?
You are not capturing return code of start-stop-daemon. Your problem is that you are launching it in the background and it is started properly. I mean that you are capturing return code of starting something in background that wants to start something in background. Try this: rm /tmp/not_existent_file & echo $? This always prints 0. In order to get the return code of a backgrounded process, you must wait for it to exit with wait. Here is an example: rm /tmp/not_existent_file & wait $! echo $? If you want to start process that is not forking on its own, try to use --background switch and remove & from the end of start-stop-daemon line. See start-stop-deamon manpage
start-stop-daemon returning always 0 (success)
1,387,757,805,000
I have a bunch of PUIAS (RedHat) 6.4 servers and desktops. I noticed after rebooting my computing nodes (done just for testing purposes) that many of the daemons which are started manually after initial installation (ipmi, mcelog, fail2ban) are not running and have to be restarted manually. This server is suppose to run on the run level 3 (no GUI). Similar exercise on the same OS version on the desktops (run level 5) produces totally different outcome. Namely all daemons are properly started. Is this excepted and should I edit /etc/init.d scripts or maybe just write mine which will start services? Is there the other "correct" way of doing this? I am coming from OpenBSD world where build in daemons are simply stared by editing /etc/rc.conf.local and all other daemons are started by editing /etc/rc.local.
(I'm not trying to be pedantic, I just don't know how much you know or don't know, so I'm basically braindumping here) First off, just be aware that Red Hat picks weird stuff to install and enable by default. For instance it's either RHEL5 or RHEL6 that will install avahi and enable it to start at boot. I think both versions install and enable cups for almost all the installation profiles you can pick. RHEL6 doesn't install man by default, etc, etc. On RHEL there are three ways you can manage services: Manually modify the symlinks underneath /etc/rc.d or /etc/rcX.d Use chkconfig (modeled after IRIX's tool of the same name) use the setup command provided by the setuptool package (which may or may not be installed depending on the profile that was selected during the initial install). More details on each: Manual Management: The RHEL/System V startup sequence is thus: /etc/rc.sysinit is ran, which gets most of the critical parts of the operating system such as critical filesystems in place. init then looks into /etc/rcX.d (where X for the runlevel it's booting into) and executes all the files/symlinks contained therein (in alphabetical order). If their name begins with and S it gives the script start as its argv[1]/$1 If their name begins with a K it stops (or kills) the service. Convention has it that dependencies are handled by changing the number after the K or S which has the effect of just changing its alphabetical position. It executes whatever is in /etc/rc.local The actual service scripts will be in /etc/rc.d/init.d (which is also symlinked to on /etc/init.d). If you want a service to start at run level 3 (network but no GUI) you could do this: # cd /etc/rc3.d # ln -s /etc/init.d/myService S99myService Using chkconfig The purpose of chkconfig is basically to automate the above process for you. It has the drawback of requiring that the initscripts have a certain header before you can manage the service with chkconfig. For example, this is the start of the networking service: #! /bin/bash # # network Bring up/down networking # # chkconfig: 2345 10 90 # description: Activates/Deactivates all network interfaces configured to \ # start at boot time. # ### BEGIN INIT INFO # Provides: $network ### END INIT INFO This enables chkconfig and figure out what number it needs to set/modify in order to get dependencies to work out properly. You lose the ability to change order but because of the above it hardly ever actually matters. chkconfig is easier and is frankly what I use most of the time. You can check which services are configured at what run levels via chkconfig --list For example: [root@ditirlns01 ~]# chkconfig --list | head NetworkManager 0:off 1:off 2:off 3:off 4:off 5:off 6:off acpid 0:off 1:off 2:on 3:on 4:on 5:on 6:off anacron 0:off 1:off 2:on 3:on 4:on 5:on 6:off arptables_jf 0:off 1:off 2:on 3:on 4:on 5:on 6:off atd 0:off 1:off 2:off 3:off 4:on 5:on 6:off auditd 0:off 1:off 2:off 3:off 4:off 5:off 6:off autofs 0:off 1:off 2:off 3:off 4:on 5:on 6:off avahi-daemon 0:off 1:off 2:off 3:off 4:on 5:on 6:off avahi-dnsconfd 0:off 1:off 2:off 3:off 4:off 5:off 6:off capi 0:off 1:off 2:off 3:off 4:off 5:off 6:off Or check on the status of particular services: [root@ditirlns01 ~]# chkconfig --list auditd auditd 0:off 1:off 2:off 3:off 4:off 5:off 6:off You can enable a service via chkconfig <serviceName> on Continuing the example above: [root@ditirlns01 ~]# chkconfig auditd on [root@ditirlns01 ~]# chkconfig --list auditd auditd 0:off 1:off 2:on 3:on 4:on 5:on 6:off As you can see chkconfig enable the auditd service for run levels 3 thru 5. If you didn't want that you, can use the --levels option to set specific run levels to enable: [root@ditirlns01 ~]# chkconfig auditd off [root@ditirlns01 ~]# chkconfig auditd on --levels=3 [root@ditirlns01 ~]# chkconfig --list auditd auditd 0:off 1:off 2:off 3:on 4:off 5:off 6:off With setuptool setup is the latest iteration of system management, designed to make common administrative tasks a little easier. It would work that way if Red Hat would install everything needed to make it so. But starting with RHEL6 they separated out setuptool functionality amongst several packages (I guess to make it more comprehensive without clogging the menu). It's a pretty self-explanatory ncurses-based wrapper around chkconfig except that it doesn't let you single out particular run levels: Not much to say about it beyond that. Let me know if that answered you question.
Daemons not starting during the boot on PUIAS (RedHat) 6.4
1,387,757,805,000
I am writing a script to do some tasks at boot up time in my Debian Wheezy AWS EC2 AMI. Sources on the internet say that usual way to do this is to use update-rc.d to install the symlinks needed to set it up to run at boot time. However, when I try this, I get the error $ update-rc.d -bash: update-rc.d: command not found This method has been working for me till Debian Squeeze. Has the standard way to do this changed in Debian 7.0? I am not able to find any documentation that explains how to do it in the official way.
Looks like you're trying to use update-rc.d as an unprivileged user? Since this tool is located in /usr/sbin/ you probably don't have it in your $PATH. So try running it as root user or call it via sudo update-rc.d.
How to make a script run at boot time in Debian Wheezy?
1,387,757,805,000
I have a daemon/service (milter-regex), that is dying. I'm only using it temporarily (A few months), so don't care too much, but I want it to restart when it dies. It is an init.d script. 'service milter-regex start' etc. The init script lives at /etc/init.d/milter-regex I know if I have something in /etc/inittab, it will automagically respawn if it dies. Are init scripts supposed to do this as well, or do I need to put it in inittab? It could be failing to restart as it isn't cleaning up a stale sock file, which I will fix today, but thought I'd ask the question anyway. Running on RHEL4 (Yes, old) Thanks, Brock
Scripts in init.d don't get rerun automatically when the service crashes. If you want to do the minimum amount of work to make sure it runs, inittab may be your best bet. It's icky though, almost as icky as still running RHEL 4.
/etc/init.d/script, or /etc/inittab - respawn on die
1,387,757,805,000
Cleaning up the boot process of a Debian squeeze installation running on kernel 3.2.0-0.bpo.3-amd64, I spotted several mountnfs scripts in /etc/init.d/: # ls /etc/init.d/ | grep mountnfs mountnfs-bootclean.sh mountnfs.sh umountnfs.sh Removing fails, with commands like: # update-rc.d -f mountnfs remove update-rc.d: using dependency based boot sequencing For "mountnfs", I have also tried: umountnfs, mountnfs-bootclean, nfs, nfs-common. Update #1 Also tried without success: umountnfs.sh, mountnfs.sh. The result is that the mountnfs-bootclean, mountnfs and unmountnfs.sh are still in /etc/init.d/ and their corresponding run level folders. Just removing those files using rm doesn't seem the right way. I though that these init.d files belong to installed packages. However I can't really find any installed NFS package: # dpkg --get-selections | grep nfs libnfsidmap2 install How do I correctly remove all mountNFS scripts from init.d?
To check which package a file belongs to, use dpkg -S: $ dpkg -S /etc/init.d/mountnfs.sh initscripts: /etc/init.d/mountnfs.sh mountnfs.sh belongs to an essential package called initscripts. Unless you wrote them, you should never remove scripts from /etc/init.d/. That is why the utility update-rc.d exists: to remove their symlinks from the /etc/rc*.d/ directories in an easier way. update-rc.d requires you to call scripts by their names and, because of their dependencies, disabling them in this order should work: update-rc.d mountnfs-bootclean.sh remove ### mountnfs-bootclean.sh first update-rc.d mountnfs.sh remove update-rc.d umountnfs.sh remove However, I tried that last month, and it will leave you with a broken system (unable to start X, if I can remember well). The thing is that mountnfs-bootclean.sh does some needed system cleanup, although its name doesn't imply, and it depends on mountnfs.sh. So you can't disable either. You may consider that as a bug in Debian init scripts: you are forced to have the init script without having any network filesystems. It's annoying, I know. If you insist in removing them, and need to revert the changes, you'll have to re-enable them in reverse order, because mountnfs-bootclean.sh needs mountnfs.sh to be enabled first: update-rc.d umountnfs.sh defaults update-rc.d mountnfs.sh defaults update-rc.d mountnfs-bootclean.sh defaults ### mountnfs-bootclean.sh last
How to correctly remove mountnfs from /etc/init.d/
1,387,757,805,000
I recently moved a home-grown service I had running on a virtual machine (Debian 7.8) to a physical computer (Debian 8.5) and after the move, my init script stopped working. I understand there were some major changes to the init process etc. between Wheezy and Jessie, but so far as I can tell, the changes should still be compatible with my init script. I'm pretty sure I 'LSBized' the script per the directions on the Debian Wiki and stayed pretty close to the old skeleton example anyway. I did a lot of bumping around, trying to figure out what was going on and I'm pretty sure that the script (usually?) is crashing - or at least stopping - while sourcing the functions at /lib/lsb/init-functions. I have no idea why that would happen. After coming to this conclusion, I trimmed down the init script to a (pretty clumsy) shorter version that does not use the init-functions; it just forks a bash process into a sub-sub shell so it will be orphaned. That seems to work a bit better but it still has occasional issues with the new services set-up. I'm less interested in fixing this duct-tape-and-bailing-wire solution as I am figuring out why my more standard init script is misbehaved. Any ideas? Here's my old init script: #! /bin/sh ### BEGIN INIT INFO # Provides: myd # Required-Start: $remote_fs $syslog # Required-Stop: $remote_fs $syslog # Default-Start: 2 3 4 5 # Default-Stop: 0 1 6 # Short-Description: Initscript for myService daemon ### END INIT INFO # Do NOT "set -e" # PATH should only include /usr/* if it runs after the mountnfs.sh script PATH=/sbin:/usr/sbin:/bin:/usr/bin DESC="myService daemon" NAME=myd DAEMON=/home/uname/myService/bin/$NAME DAEMON_ARGS="" PIDFILE=/var/run/$NAME.pid SCRIPTNAME=/etc/init.d/$NAME # Exit if the package is not installed [ -x "$DAEMON" ] || exit 0 # Load the VERBOSE setting and other rcS variables . /lib/init/vars.sh # Define LSB log_* functions. # Depend on lsb-base (>= 3.2-14) to ensure that this file is present # and status_of_proc is working. . /lib/lsb/init-functions # # Function that starts the daemon/service # do_start() { # Return # 0 if daemon has been started # 1 if daemon was already running # 2 if daemon could not be started start-stop-daemon --start --quiet \ --background \ --pidfile $PIDFILE \ --make-pidfile \ --user uname \ --chuid uname \ --startas /bin/bash \ --test \ -- -c "exec $DAEMON >> /.myd/var/init.log 2>&1" \ || return 1 start-stop-daemon --start --quiet \ --background \ --pidfile $PIDFILE \ --make-pidfile \ --user uname \ --chuid uname \ --startas /bin/bash \ -- -c "exec $DAEMON >> /home/uname/.myd/var/init.log 2>&1" \ || return 2 # Add code here, if necessary, that waits for the process to be ready # to handle requests from services started subsequently which depend # on this one. As a last resort, sleep for some time. return 0 } # # Function that stops the daemon/service # do_stop() { # Return # 0 if daemon has been stopped # 1 if daemon was already stopped # 2 if daemon could not be stopped # other if a failure occurred start-stop-daemon --stop --quiet \ --retry=TERM/30/KILL/5 \ --pidfile $PIDFILE \ --name $NAME RETVAL="$?" [ "$RETVAL" = 2 ] && return 2 # Wait for children to finish too if this is a daemon that forks # and if the daemon is only ever run from this initscript. # If the above conditions are not satisfied then add some other code # that waits for the process to drop all resources that could be # needed by services started subsequently. A last resort is to # sleep for some time. start-stop-daemon --stop --quiet --oknodo \ --retry=0/30/KILL/5 \ --exec $DAEMON [ "$?" = 2 ] && return 2 # Many daemons don't delete their pidfiles when they exit. rm -f $PIDFILE return "$RETVAL" } # # Function that sends a SIGHUP to the daemon/service # do_reload() { # # If the daemon can reload its configuration without # restarting (for example, when it is sent a SIGHUP), # then implement that here. # start-stop-daemon --stop --signal 1 --quiet \ --pidfile $PIDFILE \ --name $NAME return 0 } case "$1" in start) log_daemon_msg "Starting $DESC" "$NAME" do_start case "$?" in 0|1) log_end_msg 0 ;; 2) log_end_msg 1 ;; esac ;; stop) log_daemon_msg "Stopping $DESC" "$NAME" do_stop case "$?" in 0|1) log_end_msg 0 ;; 2) log_end_msg 1 ;; esac ;; status) status_of_proc "$DAEMON" "$NAME" && exit 0 || exit $? ;; #reload|force-reload) # # If do_reload() is not implemented then leave this commented out # and leave 'force-reload' as an alias for 'restart'. # #log_daemon_msg "Reloading $DESC" "$NAME" #do_reload #log_end_msg $? #;; restart|force-reload) # # If the "reload" option is implemented then remove the # 'force-reload' alias # log_daemon_msg "Restarting $DESC" "$NAME" do_stop case "$?" in 0|1) do_start case "$?" in 0) log_end_msg 0 ;; 1) log_end_msg 1 ;; # Old process is still running *) log_end_msg 1 ;; # Failed to start esac ;; *) # Failed to stop log_end_msg 1 ;; esac ;; *) #echo "Usage: $SCRIPTNAME {start|stop|restart|reload|force-reload}" >&2 echo "Usage: $SCRIPTNAME {start|stop|status|restart|force-reload}" >&2 exit 3 ;; esac : And my new (clumsy) script that (mostly) works: #! /bin/sh ### BEGIN INIT INFO # Provides: myd # Required-Start: $remote_fs $syslog # Required-Stop: $remote_fs $syslog # Default-Start: 2 3 4 5 # Default-Stop: 0 1 6 # Short-Description: Initscript for myService daemon ### END INIT INFO # Do NOT "set -e" # PATH should only include /usr/* if it runs after the mountnfs.sh script PATH=/sbin:/usr/sbin:/bin:/usr/bin DESC="myService daemon" NAME=myd DAEMON=/home/uname/myService/bin/$NAME DAEMON_ARGS="" PIDFILE=/var/run/$NAME.pid SCRIPTNAME=/etc/init.d/$NAME # Exit if the package is not installed [ -x "$DAEMON" ] || exit 0 # # Function that starts the daemon/service # do_start() { ( runuser -l uname "$DAEMON" >/dev/null 2>&1 & echo "$!" > "$PIDFILE" ) return 0 } # # Function that stops the daemon/service # do_stop() { PID="$(cat $PIDFILE)" kill "$PID" >/dev/null 2>&1 #Give myd 5 seconds for an orderly shutdown for i in $(seq 1 5); do sleep 1 if [ ! kill -0 "$PID" >/dev/null 2>&1 ]; then rm "$PIDFILE" return 0; fi done #No more playing nice: KILL THE DAEMON if [ kill -0 "$PID" >/dev/null 2>&1 ]; then echo "Orderly shutdown failed, sending kill signal" kill -9 "$PID" >/dev/null 2>&1 fi #Give myd 5 more seconds then fail for i in $(seq 1 5); do sleep 1 if [ ! kill -0 "$PID" >/dev/null 2>&1 ]; then rm "$PIDFILE" return 0; fi done #FAILED echo "Failed to kill $DESC $NAME" return 1 } case "$1" in start) echo "Starting $DESC $NAME" >&2 do_start ;; stop) echo "Stopping $DESC $NAME" >&2 do_stop ;; restart|force-reload) # # If the "reload" option is implemented then remove the # 'force-reload' alias # echo "Restarting $DESC $NAME" >&2 do_stop do_start ;; *) #echo "Usage: $SCRIPTNAME {start|stop|restart|reload|force-reload}" >&2 echo "Usage: $SCRIPTNAME {start|stop|restart|force-reload}" >&2 exit 3 ;; esac : As an aside, after much googling and head-scratching, I'm still not very aware of the new system for dependency booting etc. Can somebody point me in the direction of some (current) documentation for this stuff so I can self educate a little better? I hate being in the dark about the systems I'm working with. Thanks!
You should probably consider converting to a native systemd Unit as your init script is fairly typical, and you could for example entirely remove the stop code and let systemd's default mechanism work for you, since you have a PIDFILE where it can check that the daemon is running and so knows how to kill it (see man systemd.kill). systemd has a large learning curve, but you can start with this blog on converting to systemd by the man himself, Lennart Poettering. Normally, your init script should continue to work, due to the built-in systemd compatibility. See man systemd-sysv-generator and look for the systemd Unit file wrapper for your myd script in /run/systemd/generator.late/myd.service. Check on the status and log of your script with sudo systemctl status myd and stop and start it similarly. Note the gotcha I described in this answer where giving a second start to something systemd thinks is already started will have no effect. See this wiki for converting System V or upstart scripts like yours to native systemd Units.
Debian 7 to 8 Init script trouble
1,387,757,805,000
Raspbian Jessie uses systemd and most system startup processes seem to be run from .service files. There are still a lot of SysV init entries. I gather from reading various articles that Debian 8 has support for both systems. Can anyone explain which SysV init entries are still supported and which not? How does systemd call init entries? Does it ignore if corresponding .service is running? I have found a partial answer in man systemd.service "If a service is requested under a certain name but no unit configuration file is found, systemd looks for a SysV init script by the same name (with the .service suffix removed) and dynamically creates a service unit from that script."
Can anyone explain which SysV init entries are still supported and which not? There isn't a list, and it depends from the script and how well-behaved, bug-free, and conformant to RedHat/LSB conventions it is. How does systemd call init entries? Does it ignore if corresponding .service is running? It does, albeit it is the presence of the service unit file that matters, not whether it is active; and a secondary utility generates native systemd units on the fly that invoke the System V rc scripts. systemd does not invoke them directly. Further reading How does systemd use /etc/init.d scripts? systemd and non-existant *.service files: Are they generic? disable init.d script in systemd Fsck script location debian services not running Porting old sysvinit habits to systemd
Explanation of systemd startup
1,387,757,805,000
Various older Linux distributions, which support System V type init scripts, require one to add LSB header to init script. For example a LSB header from /etc/init.d/sshd from OpenSUSE 11.4: ### BEGIN INIT INFO # Provides: sshd # Required-Start: $network $remote_fs # Required-Stop: $network $remote_fs # Default-Start: 3 5 # Default-Stop: 0 1 2 6 # Description: Start the sshd daemon ### END INIT INFO However, init scripts should be simple bash scripts where every line, which begins with # is a comment. Which utility reads those LSB headers?
On debian it's update-rc.d which calls insserv (which is not usually run directly). On Suse it is probably chkconfig. You can read about it here: suse 11 (note: this all changes in openSUSE 12, which has adopted systemd).
Which utility reads LSB headers in System V style init scripts?
1,429,141,439,000
I have the init.d script show below. I want to start the daemon with the argument --http_root /tv When I start the application without the daemon the argument is accepted However I cannot seem to figure out how to adjust the script below to start the daemon with that argument. I want the argument to be passed every time sudo service tvheadend start is issued. I do not want to pass an argument to the init.d script. How can I achieve that? #! /bin/sh ### BEGIN INIT INFO # Provides: tvheadend # Required-Start: $local_fs $remote_fs udev # Required-Stop: $local_fs $remote_fs # Default-Start: 2 3 4 5 # Default-Stop: 0 1 6 ### END INIT INFO # Author: Andreas Öman # Do NOT "set -e" # PATH should only include /usr/* if it runs after the mountnfs.sh script PATH=/usr/sbin:/usr/bin:/sbin:/bin DESC="Tvheadend" NAME=tvheadend DAEMON=/usr/bin/$NAME PIDFILE=/var/run/$NAME.pid SCRIPTNAME=/etc/init.d/$NAME # Exit if the package is not installed [ -x "$DAEMON" ] || exit 0 # Read configuration variable file if it is present [ -r /etc/default/$NAME ] && . /etc/default/$NAME # Configure command line options [ "$TVH_ENABLED" = "1" ] || exit 0 ARGS="-f" [ -z "$TVH_USER" ] || ARGS="$ARGS -u $TVH_USER" [ -z "$TVH_GROUP" ] || ARGS="$ARGS -g $TVH_GROUP" [ -z "$TVH_CONF_DIR" ] || ARGS="$ARGS -c $TVH_CONF_DIR" [ -z "$TVH_ADAPTERS" ] || ARGS="$ARGS -a $TVH_ADAPTERS" [ "$TVH_IPV6" = "1" ] && ARGS="$ARGS -6" [ -z "$TVH_HTTP_PORT" ] || ARGS="$ARGS --http_port $TVH_HTTP_PORT" [ -z "$TVH_HTTP_ROOT" ] || ARGS="$ARGS --http_root $TVH_HTTP_ROOT" [ -z "$TVH_HTSP_PORT" ] || ARGS="$ARGS --htsp_port $TVH_HTSP_PORT" [ -z "$TVH_ARGS" ] || ARGS="$ARGS $TVH_ARGS" [ "$TVH_DEBUG" = "1" ] && ARGS="$ARGS -s" # Load the VERBOSE setting and other rcS variables [ -f /etc/default/rcS ] && . /etc/default/rcS # Define LSB log_* functions. # Depend on lsb-base (>= 3.0-6) to ensure that this file is present. . /lib/lsb/init-functions # # Function that starts the daemon/service # do_start() { # Return # 0 if daemon has been started # 1 if daemon was already running # 2 if daemon could not be started udevadm settle start-stop-daemon --start --quiet --pidfile $PIDFILE --exec $DAEMON --test > /dev/null \ || return 1 start-stop-daemon --start --quiet --pidfile $PIDFILE --exec $DAEMON -- \ $ARGS \ || return 2 } # # Function that stops the daemon/service # do_stop() { # Return # 0 if daemon has been stopped # 1 if daemon was already stopped # 2 if daemon could not be stopped # other if a failure occurred start-stop-daemon --stop --quiet --retry=TERM/30/KILL/5 --pidfile $PIDFILE --name $NAME RETVAL="$?" [ "$RETVAL" = 2 ] && return 2 # Many daemons don't delete their pidfiles when they exit. rm -f $PIDFILE return "$RETVAL" } case "$1" in start) [ "$VERBOSE" != no ] && log_daemon_msg "Starting $DESC" "$NAME" do_start case "$?" in 0|1) [ "$VERBOSE" != no ] && log_end_msg 0 ;; 2) [ "$VERBOSE" != no ] && log_end_msg 1 ;; esac ;; stop) [ "$VERBOSE" != no ] && log_daemon_msg "Stopping $DESC" "$NAME" do_stop case "$?" in 0|1) [ "$VERBOSE" != no ] && log_end_msg 0 ;; 2) [ "$VERBOSE" != no ] && log_end_msg 1 ;; esac ;; restart|force-reload) # # If the "reload" option is implemented then remove the # 'force-reload' alias # log_daemon_msg "Restarting $DESC" "$NAME" do_stop case "$?" in 0|1) do_start case "$?" in 0) log_end_msg 0 ;; 1) log_end_msg 1 ;; # Old process is still running *) log_end_msg 1 ;; # Failed to start esac ;; *) # Failed to stop log_end_msg 1 ;; esac ;; *) echo "Usage: $SCRIPTNAME {start|stop|restart|force-reload}" >&2 exit 3 ;; esac :
If you don't want to modify the init.d script, change (or create) /etc/default/tvheadend as steeldriver pointed out in his comment, edit (add, extend) the entry: TVH_HTTP_ROOT=/tv This file gets sourced in the init.d script, with this line: [ -r /etc/default/$NAME ] && . /etc/default/$NAME and then [ -z "$TVH_HTTP_ROOT" ] || ARGS="$ARGS --http_root $TVH_HTTP_ROOT" will set the argument to the daemon invocation. Otherwise you can also just change the line. ARGS="-f" in the script to ARGS="-f --http_root /tv" But that gets overwritten on a package update.
Passing variable in init.d script
1,429,141,439,000
We have a startup script that is symbolicly linked to /etc/rc0.d/K01ourapp. Apparently, it is not working as expected during shutdown. The script actually does a few echo calls that may help in troubleshooting. Where does that output get logged (if anywhere)? I am using RHEL5.
Strings sent to the standard output go to /dev/console (most often you can see them on your screen, but not always). To log these messages, you can use bootlogd, which, as described in its man page, "runs in the background and copies all strings sent to the /dev/console device to a logfile", and the default logfile is /var/log/boot.
If a start-up script in `init.d` has standard output, where is that logged if anywhere?
1,429,141,439,000
At work, I'm running linux, and use vagrant on a daily basis. What I find annoying is that the system often hangs when I reboot/shut down, if I forgot to vagrant halt any virtual boxes I may have fired up. To counter this, I'd like to write a shutdown script, along the lines of: #! /bin/sh cd ~/vagrants/vagrant_1 vagrant halt cd ../vagrant_2 vagrant halt exit 0 However, for I'm not too sure if ~ will still be available to me, and even if it is, if the home dir in question will always be the right one, and if the script will have access too it. So I thought I'd do: #! /bin/sh VAGRANT_HOME="~/vagrants/" #or "/home/my_user/vagrants" if [ -d "$VAGRANT_HOME" ]; then cd $VAGRANT_HOMEvagrant_1 vagrant halt cd $VAGRANT_HOMEvagrant_2 vagrant halt fi But even so, I can't help finding this silly, since I have added a couple of aliasses to my .profile file, including: alias vagranthalt="cd ~/vagrants/vagrant_1 && vagrant halt && cd - && cd ~/vagrants/vagrant_2 && vagrant halt && cd -" Which I'd like to use, but I'm not sure if these aliasses will still be available when my script is executed. I think I'll only need it @ runlevel 6, but might also need to symlink the script to run on runlevel 0, too. Basically, what I'd like to know is this: will existing aliasses be available to me, or not? Is there a user executing this script (and will I therefore be able to use ~ for home? should I make sure I have, at least, read-rights on the vagrant dirs in the script Is there another way to ensure the vagrant boxes are shutdown, that is perhaps slightly easier?
If you don't do something special vagrant is a wrapping for virtualbox. You can get a list of running virtualboxes: vboxmanage list runningvms and parse the output to get a vmname, then do: VBoxManage controlvm <vmname> acpipowerbutton Have to do this as the user that started the VMs Put a link to the script in /etc/rc0.d and /etc/rc6.d just like other softwares do ( ls /etc/rc0.d /etc/rc6.d ). My script: # coding: utf-8 import os import pwd from subprocess import check_output, CalledProcessError user_name = 'zelda' def main(): os.chdir('/') cmd = ["vboxmanage", "list", "runningvms"] if os.getuid() == 0: cmd = ['su', '-l', user_name, ] + cmd try: res = check_output(cmd) except CalledProcessError: return for line in res.splitlines(): if not line.strip(): continue # split on first char vmname = line[1:].split(line[0])[0] cmd = ["VBoxManage", "controlvm", vmname, "acpipowerbutton"] if os.getuid() == 0: cmd = ['su', '-l', user_name, ] + cmd check_output(cmd) if __name__ == "__main__": main()
local shutdown scripts (do's and don't's)
1,429,141,439,000
I have centos 6.4 machine. I created my own script using /etc/init.d/ . Below is the snippet which I took from the net and tried it. The problem now I notice which loading my os when this is loaded it start to work and it can't move to load all the whole os any more. What can I do as I can't access the system now. #!/bin/bash # chkconfig: 2345 95 05 # myapp daemon # description: myapp daemon # processname: myapp DAEMON_PATH="/usr/local/bin/" DAEMON=myap1.c #DAEMONOPTS="-my opts" NAME=myap1.c DESC="my packet capture" PIDFILE=/var/run/$NAME.pid SCRIPTNAME=/etc/init.d/$NAME case "$1" in start) printf "%-50s" "Starting $NAME..." insmod /usr/local/pfring/kernel/pf_ring.ko /usr/local/bin/myap1.c #cd $DAEMON_PATH #PID=`$DAEMON > /dev/null 2>&1 & echo $!` #echo "Saving PID" $PID " to " $PIDFILE # if [ -z $PID ]; then # printf "%s\n" "Fail" # else # echo $PID > $PIDFILE # printf "%s\n" "Ok" # fi ;; status) printf "%-50s" "Checking $NAME..." if [ -f $PIDFILE ]; then PID=`cat $PIDFILE` if [ -z "`ps axf | grep ${PID} | grep -v grep`" ]; then printf "%s\n" "Process dead but pidfile exists" else echo "Running" fi else printf "%s\n" "Service not running" fi ;; stop) printf "%-50s" "Stopping $NAME" PID=`cat $PIDFILE` cd $DAEMON_PATH if [ -f $PIDFILE ]; then kill -HUP $PID printf "%s\n" "Ok" rm -f $PIDFILE else printf "%s\n" "pidfile not found" fi ;; restart) $0 stop $0 start ;; *) echo "Usage: $0 {status|start|stop|restart}" exit 1 esac
According to this line # chkconfig: 2345 95 05 in your script, you should be able to boot the system into single user mode and then to disable automatic startup of the script (script is enabled in runlevels 2345 by default). How to boot it in single user mode? At the GRUB splash screen at boot time, press any key to enter the GRUB interactive menu. Select "Red Hat Enterprise Linux" with the version of the kernel that you wish to boot and type a to append the line. Go to the end of the line and type single as a separate word (press the Spacebar and then type single). Press Enter to exit edit mode.
/etc/init.d/ script starts during loads and crash the system
1,429,141,439,000
I successfully installed a script to automatically launch in /etc/init.d on my new Raspberry Pi. Unfortunately, it is a node.js app that never returns, and therefore hangs the device during boot (this is on Debian). Yes, I'm an idiot. Is there a secret handshake I can do during boot to prevent it from running my init.d script so I can get to login and a shell to fix it?
Assuming that the node.js init script runs before sshd or any other external access script (otherwise, you could just login in remotely, disable the script, and then reboot), the easiest thing to do is to take your SD card to another computer and mount it there, find the init script, and move it out of the init directory. Yes, it requires an external system, but you needed an external system to prepare the flash disk anyway, so I hope you still have one around. There's also a safe mode for Raspbian, but it sounds like you aren't running that. Here are relevant forum links in case they might help: Poor scripting stops my pi from booting Safe Mode
init.d script causes boot hang
1,429,141,439,000
i'm just moved to linux world in ubuntu 10.10. i'm using it for normal life, internet and social networks, multimedia enterainement like musics and movie, a bit of coding with c and python.. i've just learned something about run levels and about init and service command line tools. i understand they are powerful tools and contribute to set up the architecture and a solid base of the entire system. (is this an antiquate model? possible evolutions? alternative models?) but i don't undesrtand how they can cross my normal life and where i can use it, if i have to learn about it in a deep way or if a can only know that they exists but probabilly i will never touch them.
They are used to start (initialize) the system and bring up servers. As a normal user you shouldn't have to worry about them. If you want to also turn you machine into, say, an HTTP (web) server you would have to deal with it. Different distros do that differently, however. Many at least have a service command to start and stop them.
how can 'init' and 'service' command can cross normal-user life?
1,429,141,439,000
I could use some help with what I think is a basic request on the newest edition of Linux Mint (which I think would also be applicable to Ubuntu). I have a home system with 3GB of RAM and accounts for family members (4 of them). As the initial login process takes 15-20 seconds and kids are impatient, I'd like a way to have an active session auto-started for each user when the system first boots. ... In other words, a multiple auto-login in the background and a normal login screen. That way, when a user goes to login like normal, their session is already running and is switched to instantly. I have plenty of RAM and this machine always runs, so is there any way to pull this off via some type of login scripts?
Assuming you already have one user that auto-logs in, you can probably use a script that runs after logging in (use gnome-session-properties) that: gets a list of users to auto-login from some file checks for each of those users if they are logged in yet if one is not, use xdotool to switch to the first user (by simulating clicking on Menu and then Logout, etc) Each of these users must auto-run the script as well, thereby daisy chaining the login process if all users are logged in, switch to some specially marked user (the first) that auto logs in, unless that is the user already currently running the script.
Auto-start multiple background user sessions in Linux Mint
1,429,141,439,000
I'm trying to write a script that can set a service to: automatically restart after killed automatically start during boot up I can do this by using /etc/inittab but some of the AIX server that I'm working on don't have inittab. Meaning I cannot set the service to behave like the one in inittab. While I was trying a workaround, I found out about mkssys, rmssys, startsrc and stopsrc. So I tried writing a script using all the command. %post if [ -f /bin/mkssys ]; then mkssys -s myservice -p /opt/fikrie/bin/myservice -a "-n" -u -R -S -f 9 -n 15 startsrc -s myservice else #use the inittab's script here fi %postun if [ -f /bin/stopsrc ]; then stopsrc -s myservice rmssys -s myservice else #use the inittab's script here fi This script almost did the job. The only problem is that the service doesn't start during boot up. Which mean I need to manually start the process when the server first boot up. Is there any command to do this? Did I miss any available option on the mkssys command? I tried to follow sshd service because it is not in the inittab, but does start during boot up. Maybe I could use the same trick for my service. I think the sshd is using the rc.d to start the service during boot up. So I tried writing a script in the same directory as sshd but it doesn't seems to work. Can anyone help or guide me to the correct path?
One of the solution that I found is to use the rc.d directory. Use sshd as example since this process didn't use inittab but can still start automatically during boot up.
Start a service at boot and automatically respawn it if it dies under AIX
1,429,141,439,000
I'm making a special "installer" for an embedded system where I'd like the kernel to boot up, execute a set of things very late in the process where the peripherals have been set up and then reboot the system without the login prompt ever happening. I'm vaguely familiar with init and runlevels, I presume at this point that this is how I'll most easily achieve this. Can I put a script (then where/how?) in the init sequence that runs my stuff and then puts the machine to a reboot afterwards ? If it matters the rootfs is debian.
For Debian 7 and earlier, the easiest option is to put your code in /etc/rc.local. This runs at the very end of the boot sequence, just before the login screen is displayed when you boot into console mode, or just before X is started otherwise. Until this script exits, nothing else happens, so if you reboot the system at the end, you may not see a login screen. If you do, it should disappear quickly. I specified the Debian version above because Debian will be moving from SysV init to systemd in the next major version. While it is likely that this future version of Debian will still allow rc.local and such for backwards compatibility, you'd really want to do it a different way for systemd. That's out of scope for this question, though. More broadly, embedded Linuxes don't have to follow the rules established by desktop Linuxes. Dedicated embedded Linux distros allow you to customize things like how the boot sequence works, specifically to cope with issues like the one you're facing.
Late running of scripts during bootup, ending with a reboot without the login prompt
1,429,141,439,000
It's a fresh install of Sabayon Linux. I installed mysql (equo install dev-db/mysql), configured it (emerge --config ...), but it doesn't start using /etc/init.d script: # /etc/init.d/mysql start * WARNING: mysql is already starting # /etc/init.d/mysql status * You are attempting to run an openrc service on a * system which openrc did not boot. * You may be inside a chroot or you may have used * another initialization system to boot this system. * In this situation, you will get unpredictable results! * If you really want to do this, issue the following command: * touch /run/openrc/softlevel # /etc/init.d/mysql stop * ERROR: mysql stopped by something else Touching /run/openrc/softlevel causes even more errors. Googling doesn't advise much. I remember recent OpenRC migration on my Gentoo box, but there I'm still using init.d scripts. Anything else changed I didn't notice?
Some of services run by process manager such as : upstart, systemd, OpenRC (your case) , SysV and so on. if get ps ax |ergep -i mysql you'll find out myql is running, Use the following documentation: OpenRC doc
Sabayon - mysql (and other services) won't start
1,429,141,439,000
I have installed VMware Player on my Debian squueze, but after the reboot the vmware daemon(/etc/init.d/vmware) does not start up automatically, i have tried without any success to set the daemon startup with insserv : insserv vmware but it gives me the following output : insserv: warning: script 'K01vpnclient_init' missing LSB tags and overrides insserv: warning: current start runlevel(s) (2) of script `vmware' overwrites defaults (2 3 5). insserv: warning: current stop runlevel(s) (0 3 5 6) of script `vmware' overwrites defaults (2 3 5). insserv: warning: script 'vpnclient_init' missing LSB tags and overrides insserv: script vboxdrv: service vboxdrv already provided! and it doesn't work ... Why ? How can i solve the problem ?
LSB tags are the "Linux Standard Base" script headers that tell insserv and chkconfig how to create the companion rc.? scripts. You have to create a LSB header and re-run insserv Edit: Rather after actually taking the time to look at all your information it may have the LSB header but not configured correctly. Search for LSB init scripts and there are several links out there. You have to either configure the LSB header better or differently, or you have to add additional information like the source of the LSB functions. Also, it looks like the header might have been configured for RH or SUSE based distros given that it is starting in 2,3,5. You have some conflicting settings listed in your insserv line. Edit 2: If you don't mind could you put the first 20 or so lines of the /etc/init.d/vmware init script into your question. Thanks Edit 3: Links Debian Wiki: How to LSBize an Init Script The Geek Stuff: How to Write Linux Init Scripts Based on LSB Init Standard
VMWare daemon doesn't startup when system starts
1,429,141,439,000
Background: I'm a Ubuntu/Debian fan and most of my development experience has been on that platform but my current employer uses Redhat. I needed to write a simple init.d script and want the resulting program to run as an unprivileged user. Most resources I found suggest using the daemon function in lieu of start-stop-daemon. Question: Why doesn't the daemon function have an option to set the group like the start-stop-daemon? I'm sure there must be a reason for this, just not sure what that reason is.
You can certainly change the daemon function to set the group or you can write your own mydaemon function to do it. Or in a simplest possible way just call the runuser command that daemon() uses to start your program with particular UID and GID
Why does Redhat's daemon function not have a group setting?
1,429,141,439,000
Using Debian 9 stable, I want to start a custom shell script before starting NGINX processes and shorewall firewall: Do some init work Mount a directory (overlayfs) to overlay /etc with NGINX configuration, shorewall configuration and /etc/hosts The script also ends with sync, not sure if it's a good idea systemctl list-dependencies default.target ● ├─display-manager.service ● ├─systemd-update-utmp-runlevel.service ● └─multi-user.target ● ├─console-setup.service ● ├─cron.service ● ├─dbus.service ● ├─dropbear.service ● ├─myservice.service   <-- My service (link created with systemctl enable) ● ├─networking.service ● ├─nginx.service       <-- To be executed after myservice [...] ● ├─basic.target ● │ ├─-.mount ● │ ├─myservice.service <-- My service (link created with systemctl enable) ● │ ├─shorewall.service  <-- To be executed after myservice myservice.service ATTEMPT 1 [Unit] Description=My startup service Requires=shorewall.service nginx.service Before=shorewall.service nginx.service [Service] RemainAfterExit=yes ExecStart=/usr/local/bin/myservice start ExecStop=/usr/local/bin/myservice stop [Install] WantedBy=multi-user.target WantedBy=basic.target The logs: journalctl [...] Oct 12 11:31:43 server-dev nginx[448]: nginx: [emerg] host not found in upstream "server-dev.com" in /etc/nginx/sites-enabled/default:33 Oct 12 11:31:43 server-dev nginx[448]: nginx: configuration file /etc/nginx/nginx.conf test failed <== NGINX: BAD Oct 12 11:31:43 server-dev systemd[1]: nginx.service: Control process exited, code=exited status=1 Oct 12 11:31:43 server-dev systemd[1]: Failed to start A high performance web server and a reverse proxy server. Oct 12 11:31:43 server-dev systemd[1]: nginx.service: Unit entered failed state. Oct 12 11:31:43 server-dev systemd[1]: nginx.service: Failed with result 'exit-code'. Oct 12 11:31:43 server-dev systemd[1]: Reached target Multi-User System. Oct 12 11:31:43 server-dev systemd[1]: Reached target Graphical Interface. Oct 12 11:31:43 server-dev systemd[1]: Starting Update UTMP about System Runlevel Changes... Oct 12 11:31:43 server-dev systemd[1]: Started Update UTMP about System Runlevel Changes. Oct 12 11:31:43 server-dev server[423]: DO: server start DONE <== END OF SCRIPT myservice Oct 12 11:31:43 server-dev shorewall[449]: Compiling using Shorewall 5.0.15.6... <== SHOREWALL: GOOD Oct 12 11:31:44 server-dev shorewall[449]: Processing /etc/shorewall/shorewall.conf... Oct 12 11:31:44 server-dev shorewall[449]: Loading Modules... Shorewall is systematically started correctly, after the execution of myservice. Nginx is most of the time started during the execution of myservice, before /etc is correctly overlayed (overlaid?), and therefore it fails to initialize properly. myservice.service ATTEMPT 2 I also tried to change the [Install] WantedBy=default.target And change [Unit] Before=multi-user.target It also does not work. How can I ensure that nginx and shorewall start after the execution of myservice?
If you don't specify the type of your systemd service, it defaults to Type=simple. This means the service is considered started at the moment its main service process has been forked off (at which point it isn't even executing the ExecStart command yet). You probably want to use Type=oneshot instead, which waits for the ExecStart command to exit before considering the service started. See man systemd.service for further details.
systemd: finish the execution of custom shell script before starting nginx
1,429,141,439,000
I have a script in /etc/init.d that I'm trying to add echo statements to...but all of my changes seem to be ignored. I'm guessing because the script itself is not actually run but that systemd is doing something behind the scenes to continue running the old version of the script. Is there a way to "load" these changes?
No, there's not a way for systemd to load the changes you made to files in /etc/init.d because systemd is largely ignoring the files anyway. See the gory details at How does systemd use /etc/init.d scripts?. Consider asking a different question about the specific problem you are attempting to solve by editing /etc/init.d files. I could guess that perhaps you are looking for ExecStartPre= or ExecStartPost=. Read man systemd.service for other directives that you can use in your systemd service unit files.
How can I modify an init script on CentOS 7?
1,429,141,439,000
I installed octoprint to my raspberry pi earlier this year in order to control my 3d printers. I've been able to make the pi control 2 printers at once using octoprint. Also I've added a second camera (USB) to view the second printer. I managed to find a way to start the second camera and edit octoprint to see the difference in the two. My only problem is every time I start my raspberry pi up again I have to change to different a working directory: cd ~/mjpg-streamer then this to start the second camera: ./mjpg_streamer -i "./input_raspicam.so -fps 5" -o "./output_http.so -p 8090"& I want to be able to write a script to start the camera on boot so I don't have to ssh to my raspberry, login, and send the commands every day. I've found a lot about writing boot scripts but nothing about changing the working directory inside it. I've been using this to write start scripts (unsuccessfully): sudo nano /etc/init.d/startsecondcamera
Make the startup script do the cd before running mjpg_streamer, just like you're doing manually: #!/bin/sh cd /home/geilisa/mjpg-streamer ./mjpg_streamer -i "./input_raspicam.so -fps 5" -o "./output_http.so -p 8090" This is assuming that your home directory is /home/geilisa. You can't use ~ in the script since it's likely run by root. If running the utility as root is an issue, use sudo -u gelisia ./mjpg_streamer ... in the script to run it as user gelisia instead. An alternative is to add a cron job that runs at boot: @reboot cd /home/geilisa/mjpg-streamer && ./mjpg_streamer -i "./input_raspicam.so -fps 5" -o "./output_http.so -p 8090" Add this in your crontab by using the command crontab -e. This will open an editor with your crontab (possibly an empty file). Add the above line, save, and exit. Most cron's that I know of allows for using @reboot (and @hourly, @daily etc.) instead of the five job scheduling columns that usually goes before the actual command.
Writing start script with different working directory
1,429,141,439,000
TL:DR: In which init level /etc/profile or /etc/environment files are read? I want to create a service (/etc/init.d/myservice) starting a shell script located at /opt/myservice/myservice.sh. However this location (/opt/myservice/) is defined at installation time, so it's not a fixed location. Let's say that I set an environment variable in /etc/profile or /etc/environment like MYSERVICE_PATH=/opt/myservice, set # Default-Start: 3 4 5 on /etc/init.d/myservice file. Could I safely assume that $MYSERVICE_PATH will always be available at those init levels (3,4,5), so my init script could call sh $MYSERVICE_PATH/myservice.sh?
You may be looking in the wrong place to store application configuration information. /etc/profile is used for the configuration of default settings for login shells (e. g. when SSHing in and invoking bash as the login shell). It purpose is not for the configuration of application installation locations and the like. /etc/ as a whole, is, however, exactly that. What is probably the best way to accomplish what you are looking for is to define a configuration file which always lives at e. g. /etc/myservice.conf, which might look something like: # Configuration file for the My Service daemon # # Default settings: # myservice_root - The directory in which the service is installed # Default: /var/run/myservice # myservice_port - The TCP port upon which the service listens for incoming connecitons # Default: 55321 myservice_root=/opt/myservice myservice_port=6466 Your application, then, can always look at /etc/myservice.conf for its configuration, no matter what location on the filesystem it happens to be installed into, and other system administrators can instantly see what the file is for and what options are available to be reconfigured.
In which init level /etc/profile or /etc/environment files are read?
1,429,141,439,000
I wrote a daemon which watches for files in certain directory and if a new file is copied to this directory, then it is committed to SVN. New files appear in this directory only if remote devices copy files there over scp. Now I would like to create a System-V init script for this daemon in OpenSUSE 11.4. It's clear that Required-Start: line should contain only the $sshd boot facility as this ensures that local file-system is mounted, networking is operational and sshd is started. Those three boot facilities are prerequisites for the daemon, i.e. there is no point to start the daemon if sshd is not operational and thus it is impossible that it receives new files over scp. However, I'm bit puzzled how should I configure the Required-Stop: line, which lists any boot facilities which should NOT be stopped before shutting down the daemon. It looks logical to me to have local file systems mounted and networking operational(for uploading the files to SVN) while sshd is stopped(for not receiving any new files) before the daemon is stopped. Required-Stop: $sshd could create a situation where daemon is stopped while a new file is received over scp before the sshd is stopped. So in a nutshell, following approach seems to be most logical to me: # Required-Start: $sshd # Required-Stop: $local_fs $network Am I correct?
According to https://wiki.debian.org/LSBInitScripts in the section on Required-Stop Normally you would include here the same facilities as for the Required-Start keyword. Having this script running before ssh starts isn't a problem like you suggested in the OP it just means this daemon will be waiting for files that will never appear until ssh starts. This script, however, definitely does need the functionality of $local_fs and $network so I would use the following two lines # Required-Start: $local_fs $network # Required-Stop: $local_fs $network
"Required-Stop:" line in System-V type init script LSB header
1,429,141,439,000
Is it a bad idea to put variables needed by a daemon program running at boot on a headless system in /etc/profile.d/? From my understanding profile.d doesn't get executed until someone logs into the system via an interactive shell. So would my daemon process that will eventually need the system variables held in profile.d not have these variables set, until someone logs into the system, or will these be set after rc.local runs on an unattended system? (System is RHEL 6.5 running bash)
It's a bad idea if it doesn't work. I think your concern about profile.d not running unless someone logs in is legitimate. Put an init script in /etc/rc.d/init.d (I think this is the correct directory for Red Hat; in Ubuntu it's /etc/init.d) to start your daemon. In this script you can declare/define any variables you need and when you start the daemon binary those variables should be in scope. The link here explains that process and precisely why it is superior to the rc.local method. The rc.local method, mentioned in another answer, won't work because the variables set up in that script are no longer defined when execution returns to Linux INIT. This is, consequently, before anyone logs in, so it is implicitly before profile.d is run.
profile.d on headless server
1,429,141,439,000
My rc.local is stuck in an infinite loop since I accidentally put a wrong I/O redirection in and it's executing itself over and over again. I'm on Red Hat 6.5 and would like to know how I can start the machine without the rc.local being run so that I may fix the problem? It is also on a virtual machine and not a physical machine with VMware.
Boot into single user mode by going into the Grub menu and select the kernel version and press e to edit press space and type single
rc.local hang on bootup
1,429,141,439,000
So you may get a better idea of the context, this idea comes from the specific problematic of "letting kids being progressively responsible of their own devices". So I was wondering if there is any possibility to prevent power-on in specific periods of time in order to keep computer usage in the negative ones (an example would be to allow connection only between 5 and 6:30 PM). And if not, then to prevent log-in?
Your operating system can’t prevent power-on; that would be controlled by the system firmware (but I’ve never seen anything like that). You can force the system to power off if it’s switched on though, e.g. with a cronjob like * 0-16 * * * /sbin/poweroff to power the system down if it’s on at any time between midnight and 17:00 (excluded) — this runs poweroff every minute between midnight and 16:59. Be careful with this one since the system will shut down even if it’s being used. You can also use /etc/nologin to prevent logins; again, a cronjob can set this up: * 0-16,19-23 * * * touch /etc/nologin * 17-18 * * * rm -f /etc/nologin would prevent new logins outside 17:00-18:59. This won’t affect currently-logged-in users though, which might defeat the purpose in your scenario.
How to schedule a period of time in which power-on or log-in is prevented?
1,496,804,509,000
I created a script to disable the touchpad in my computer. It works ok when I run it in a terminal. I did some work to make it start at startup because I wanted the touchpad to be disabled permanently, but the script did not work at startup. The touchpad was still enabled after startup. This is my configuration: root@debian:/etc# cat /etc/init.d/touchpadOff #! /bin/sh ### BEGIN INIT INFO # Provides: touchpadOff # Required-Start: $remote_fs $syslog # Required-Stop: $remote_fs $syslog # Default-Start: 2 3 4 5 # Default-Stop: 0 1 6 # Short-Description: Start daemon at boot time # Description: Enable service provided by daemon. ### END INIT INFO synclient TouchpadOff=1 root@debian:/etc# ls -l `find -name *touchpadOff` -rwxr-xr-x 1 root root 345 gru 8 02:26 ./init.d/touchpadOff lrwxrwxrwx 1 root root 21 gru 8 01:35 ./rc0.d/K01touchpadOff -> ../init.d/touchpadOff lrwxrwxrwx 1 root root 21 gru 8 01:35 ./rc1.d/K01touchpadOff -> ../init.d/touchpadOff lrwxrwxrwx 1 root root 21 gru 8 02:26 ./rc2.d/S03touchpadOff -> ../init.d/touchpadOff lrwxrwxrwx 1 root root 21 gru 8 02:26 ./rc3.d/S03touchpadOff -> ../init.d/touchpadOff lrwxrwxrwx 1 root root 21 gru 8 02:26 ./rc4.d/S03touchpadOff -> ../init.d/touchpadOff lrwxrwxrwx 1 root root 21 gru 8 02:26 ./rc5.d/S03touchpadOff -> ../init.d/touchpadOff lrwxrwxrwx 1 root root 21 gru 8 01:35 ./rc6.d/K01touchpadOff -> ../init.d/touchpadOff root@debian:/etc# How to make it work at startup in my Debian Jessie?
You have (at least) two choices: Don't load the driver of touchpad into kernel, so echo blacklist [yourdriver] > /etc/modprobe.d/nomouse. Then do a reboot, or manually remove it: rmmod [driver]. synclient only runs after you started X, so put this synclient command to ~/.xinitrc or to /etc/X11/Xsession.d/ or make it one of the startup/autostart applications in your desktop environment.
Disable touchpad in init script
1,496,804,509,000
I have installed X11VNC and starting it on a running System (with X and XFCE running) in a terminal does work. I have written a startup script (used the skeleton in /etc/init.d/skeleton) for that. Runnin that script in a terminal after boot service x11vnc start does actually start the server. Although for some reason the process does not run in background, hence I cannot use the terminal anymore. But main problem is: the server is started on boot and I don't quite know where to start looking for errors and I am not sure (if there are any) where the log files can be found which show errors. #! /bin/sh ### BEGIN INIT INFO # Provides: x11vnc server # Required-Start: lightdm # Required-Stop: # Default-Start: 5 # Default-Stop: 0 1 2 6 # Short-Description: # Description: Start VNC Server ### END INIT INFO # # Please remove the "Author" lines above and replace them # with your own name if you copy and modify this script. # Do NOT "set -e" # PATH should only include /usr/* if it runs after the mountnfs.sh script PATH=/sbin:/usr/sbin:/bin:/usr/bin DESC="Start VNC Server" NAME=x11vnc PASSWD=/etc/x11vnc.pass LOGFILE=/var/log/x11vnc.log DAEMON=/usr/bin/$NAME DAEMON_ARGS="-display :0 -auth /var/run/lightdm/root/:0 -rfbauth /etc/x11vnc.pass" PIDFILE=/var/run/$NAME.pid SCRIPTNAME=/etc/init.d/$NAME # Exit if the package is not installed [ -x "$DAEMON" ] || exit 0 # Read configuration variable file if it is present [ -r /etc/default/$NAME ] && . /etc/default/$NAME # Load the VERBOSE setting and other rcS variables . /lib/init/vars.sh # Define LSB log_* functions. # Depend on lsb-base (>= 3.2-14) to ensure that this file is present # and status_of_proc is working. . /lib/lsb/init-functions # # Function that starts the daemon/service # do_start() { # Return # 0 if daemon has been started # 1 if daemon was already running # 2 if daemon could not be started start-stop-daemon --start --quiet --pidfile $PIDFILE --exec $DAEMON --test> /dev/null \ || return 1 start-stop-daemon --start --quiet --pidfile $PIDFILE --exec $DAEMON -- $DAEMON_ARGS \ || return 2 # Add code here, if necessary, that waits for the process to be ready # to handle requests from services started subsequently which depend # on this one. As a last resort, sleep for some time. } # # Function that stops the daemon/service # do_stop() { # Return # 0 if daemon has been stopped # 1 if daemon was already stopped # 2 if daemon could not be stopped # other if a failure occurred start-stop-daemon --stop --quiet --retry=TERM/30/KILL/5 --pidfile $PIDFILE --name $NAME RETVAL="$?" [ "$RETVAL" = 2 ] && return 2 # Wait for children to finish too if this is a daemon that forks # and if the daemon is only ever run from this initscript. # If the above conditions are not satisfied then add some other code # that waits for the process to drop all resources that could be # needed by services started subsequently. A last resort is to # sleep for some time. start-stop-daemon --stop --quiet --oknodo --retry=0/30/KILL/5 --exec $DAEMON [ "$?" = 2 ] && return 2 # Many daemons don't delete their pidfiles when they exit. rm -f $PIDFILE return "$RETVAL" } # # Function that sends a SIGHUP to the daemon/service # do_reload() { # # If the daemon can reload its configuration without # restarting (for example, when it is sent a SIGHUP), # then implement that here. # start-stop-daemon --stop --signal 1 --quiet --pidfile $PIDFILE --name $NAME return 0 } case "$1" in start) [ "$VERBOSE" != no ] && log_daemon_msg "Starting $DESC" "$NAME" do_start case "$?" in 0|1) [ "$VERBOSE" != no ] && log_end_msg 0 ;; 2) [ "$VERBOSE" != no ] && log_end_msg 1 ;; esac ;; stop) [ "$VERBOSE" != no ] && log_daemon_msg "Stopping $DESC" "$NAME" do_stop case "$?" in 0|1) [ "$VERBOSE" != no ] && log_end_msg 0 ;; 2) [ "$VERBOSE" != no ] && log_end_msg 1 ;; esac ;; status) status_of_proc "$DAEMON" "$NAME" && exit 0 || exit $? ;; #reload|force-reload) # # If do_reload() is not implemented then leave this commented out # and leave 'force-reload' as an alias for 'restart'. # #log_daemon_msg "Reloading $DESC" "$NAME" #do_reload #log_end_msg $? #;; restart|force-reload) # # If the "reload" option is implemented then remove the # 'force-reload' alias # log_daemon_msg "Restarting $DESC" "$NAME" do_stop case "$?" in 0|1) do_start case "$?" in 0) log_end_msg 0 ;; 1) log_end_msg 1 ;; # Old process is still running *) log_end_msg 1 ;; # Failed to start esac ;; *) # Failed to stop log_end_msg 1 ;; esac ;; *) #echo "Usage: $SCRIPTNAME {start|stop|restart|reload|force-reload}" >&2 echo "Usage: $SCRIPTNAME {start|stop|status|restart|force-reload}" >&2 exit 3 ;; esac Running update-rc.d x11vnc defaults didn't help. Also ls /etc/rc?.d/ shows my script in a couple of the files. But I get the following $ insserv -n x11vnc insserv: dryrun, not creating .depend.boot, .depend.start, and .depend.stop $ insserv x11vnc # returnes no errors
After looking around for longer time, I finally found a solution. Using xinetd. I removed the init script from /etc/init.d/ again and did the following. apt-get install xinetd Create content into file /etc/xinetd.d/x11vnc service x11vnc { type = UNLISTED disable = no socket_type = stream protocol = tcp wait = no user = root server = /usr/bin/x11vnc server_args = -inetd -o /var/log/x11vnc.log -display :0 -forever -bg -rfbauth /etc/vncpasswd -shared -enablehttpproxy -forever -nolookup -auth /var/run/lightdm/root/:0 port = 5900 } chmod a+x x11vnc Restart and it was working. The flag -auth depends on your login manager. If you need to find out where the flag should point for you use: ps wwaux | grep auth. This will print the path. Found solution here.
Creating X11VNC Server Initscript not successful on boot (manually started works)
1,496,804,509,000
I tried installing atftpd today. The package installed successfully: # zypper se atftp Loading repository data... Reading installed packages... S | Name | Summary | Type --+-------+---------------------------------+-------- i | atftp | Advanced TFTP Server and Client | package But the service did not start after installation. # service atftpd start Job for atftpd.service failed. See "systemctl status atftpd.service" and "journalctl -xn" for details. # journalctl -xn -- Logs begin at Thu 2015-03-05 22:21:19 CET, end at Fri 2015-03-13 22:45:01 CET. -- Mar 13 22:43:13 server systemd[1]: Configuration file /usr/lib/systemd/system/atftpd.service is marked executable. Please remove executable permission bits. Proceeding anyway. [...] I removed the execution flag and got rid of the error message, but the service still won't start. # chmod -x /usr/lib/systemd/system/atftpd.service # service atftpd start Job for atftpd.service failed. See "systemctl status atftpd.service" and "journalctl -xn" for details. Looking at the systemd service definition file everything looks rather straight forward: # cat /usr/lib/systemd/system/atftpd.service [Unit] Description=Advanced TFTP Server [Service] EnvironmentFile=/etc/sysconfig/atftpd ExecStart=/usr/sbin/atftpd --user $ATFTPD_USER --group $ATFTPD_GROUP $ATFTPD_OPTIONS $ATFTPD_DIRECTORY StandardInput=socket And the environment file seem to define valid values for all the variables: # grep ^ATFT /etc/sysconfig/atftpd ATFTPD_USER="tftp" ATFTPD_GROUP="tftp" ATFTPD_OPTIONS="--daemon --logfile /var/log/atftpd/atftp.log" ATFTPD_USE_INETD="no" ATFTPD_DIRECTORY="/srv/tftpboot" ATFTPD_BIND_ADDRESSES="" Manually running the commands successfully starts the daemon: # systemctl start atftpd.service Job for atftpd.service failed. See "systemctl status atftpd.service" and "journalctl -xn" for details. # ps aux | grep tftp[d] # source /etc/sysconfig/atftpd # /usr/sbin/atftpd --user $ATFTPD_USER --group $ATFTPD_GROUP $ATFTPD_OPTIONS $ATFTPD_DIRECTORY # ps aux | grep tftp[d] tftp 1907 0.0 0.0 11596 152 ? Ss 23:18 0:00 /usr/sbin/atftpd --user tftp --group tftp --daemon --logfile /var/log/atftpd/atftp.log /srv/tftpboot As I am new to atftpd, suse tumbleweed and systemd I don't really know what might be wrong. I've set the --daemon and --logfile explicitly in $AFTPD_OPTIONS, but according to the config file help text that should be the default anyway. The diagnostics text in full: # systemctl start atftpd.service Job for atftpd.service failed. See "systemctl status atftpd.service" and "journalctl -xn" for details. # systemctl status atftpd.service atftpd.service - Advanced TFTP Server Loaded: loaded (/usr/lib/systemd/system/atftpd.service; static) Active: failed (Result: resources) Mar 13 22:59:55 server systemd[1]: atftpd.service failed to run 'start' task: Invalid argument # journalctl -xn -- Logs begin at Thu 2015-03-05 22:21:19 CET, end at Fri 2015-03-13 23:33:13 CET. -- Mar 13 23:25:38 server kernel: SFW2-INext-DROP-DEFLT IN=ens32 OUT= MAC=33:33:00:00:00:fb:98:d6:bb:20:90:a2:86:dd SRC=fe80:0000:0000:0000:189b:b08a:4ad3:89bf DST=ff02:0000:0000:0000:00 Mar 13 23:28:00 server kernel: SFW2-INext-DROP-DEFLT IN=ens32 OUT= MAC=33:33:00:00:00:fb:f0:24:75:e4:6e:54:86:dd SRC=fe80:0000:0000:0000:1c6a:034e:81fc:bb59 DST=ff02:0000:0000:0000:00 Mar 13 23:28:15 server kernel: SFW2-INext-DROP-DEFLT IN=ens32 OUT= MAC=33:33:00:00:00:fb:f0:24:75:e4:6e:54:86:dd SRC=fe80:0000:0000:0000:1c6a:034e:81fc:bb59 DST=ff02:0000:0000:0000:00 Mar 13 23:29:43 server kernel: SFW2-INext-DROP-DEFLT IN=ens32 OUT= MAC=33:33:00:00:00:fb:1c:ab:a7:98:9c:80:86:dd SRC=fe80:0000:0000:0000:00d4:2bc4:7bd3:85f3 DST=ff02:0000:0000:0000:00 Mar 13 23:30:01 server cron[1912]: pam_unix(crond:session): session opened for user root by (uid=0) Mar 13 23:30:01 server systemd[1913]: pam_unix(systemd-user:session): session opened for user root by (uid=0) Mar 13 23:30:01 server CRON[1912]: pam_unix(crond:session): session closed for user root Mar 13 23:33:10 server kernel: SFW2-INext-DROP-DEFLT IN=ens32 OUT= MAC=33:33:00:00:00:fb:6c:40:08:ae:e7:3a:86:dd SRC=fe80:0000:0000:0000:6e40:08ff:feae:e73a DST=ff02:0000:0000:0000:00 Mar 13 23:33:11 server kernel: SFW2-INext-DROP-DEFLT IN=ens32 OUT= MAC=33:33:00:00:00:fb:b4:18:d1:dd:52:cc:86:dd SRC=fe80:0000:0000:0000:b618:d1ff:fedd:52cc DST=ff02:0000:0000:0000:00 Mar 13 23:33:13 server kernel: SFW2-INext-DROP-DEFLT IN=ens32 OUT= MAC=33:33:00:00:00:fb:6c:40:08:ae:e7:3a:86:dd SRC=fe80:0000:0000:0000:6e40:08ff:feae:e73a DST=ff02:0000:0000:0000:00 Why does the service refuse to start? What can I do to fix it? EDIT: Really good answer by @jdebp, thanks! To follow up I can verify that the server does start as expected after reverting my tweaks to the config file. It still won't work, but it does start. ;) Server side $ sudo systemctl status atftpd.{socket,service} atftpd.socket - Advanced tftp Server Activation Socket Loaded: loaded (/usr/lib/systemd/system/atftpd.socket; disabled) Active: active (running) since Mon 2015-03-16 14:45:50 CET; 5h 19min ago Listen: [::]:69 (Datagram) atftpd.service - Advanced TFTP Server Loaded: loaded (/usr/lib/systemd/system/atftpd.service; static) Active: active (running) since Mon 2015-03-16 20:04:49 CET; 16s ago Main PID: 3337 (atftpd) CGroup: /system.slice/atftpd.service └─3337 /usr/sbin/atftpd --user tftp --group tftp /srv/tftpboot Mar 16 20:04:49 server atftpd[3337]: connect: Address family not supported by protocol Mar 16 20:04:54 server atftpd[3337]: connect: Address family not supported by protocol Mar 16 20:04:59 server atftpd[3337]: connect: Address family not supported by protocol Mar 16 20:05:04 server atftpd[3337]: connect: Address family not supported by protocol Client side $ atftp --trace --verbose -l nvidia-bug-report.log.gz -p server 69 Trace mode on. Verbose mode on. sent WRQ <file: nvidia-bug-report.log.gz, mode: octet <>> timeout: retrying... sent WRQ <file: nvidia-bug-report.log.gz, mode: octet <>> timeout: retrying... sent WRQ <file: nvidia-bug-report.log.gz, mode: octet <>> timeout: retrying... sent WRQ <file: nvidia-bug-report.log.gz, mode: octet <>> timeout: retrying... tftp: aborting EDIT2: Forcing the daemon to use ipv4 made the file transfer successful. > grep 0\.0 /etc/sysconfig/atftpd /usr/lib/systemd/system/atftpd.socket /etc/sysconfig/atftpd:ATFTPD_BIND_ADDRESSES="0.0.0.0" /usr/lib/systemd/system/atftpd.socket:ListenDatagram=0.0.0.0:69
Why does the service refuse to start? What can I do to fix it? Because you're starting the wrong thing. Start the right thing. ☺ The giveaway here isStandardInput=socket in the service unit file. This indicates that the dæmon is expecting a socket as its standard input, and systemd is expected to supply it when spawning the dæmon. "But what socket is that?" one asks. systemd doesn't magically know what socket to use, and certainly doesn't connect services to any old socket file descriptors that it just happens to have lying around in process #1. The answer is that, whilst others on the WWW (several years ago) have done it differently, the (more recent) OpenSUSE packaging for atftpd runs atftpd as a fully-fledged socket-activated service. There's a lot written about socket activation in systemd. It is subtle, and explaining it is beyond the scope of this answer. The thing that you need to know about this particular service, here and now, is this: You, the system administrator, do not start/stop your atftpd service by starting/stopping the service unit. You start/stop the socket unit. When the socket is up, systemd monitors it, and traffic to the socket will cause systemd itself to start the service unit, connecting the service to the socket that activated it. So systemctl start atftpd.socket and systemctl stop atftpd.socket are the commands here. (The same with enable and disable of course.) Also use systemctl status atftpd.{service,socket} to see the status of both the socket and service units. (You'll notice that the atftpd.service file has no [Install] section, but the atftpd.socket file does. Again, that's a giveaway that it is the socket unit that one administratively starts/stops/enables/disables here.) By the way, the contents of your /etc/sysconfig/atftpd file are bogus. They don't match the atftpd.sysconfig that is in OpenSUSE. The OpenSUSE one matches what systemd has been told about the dæmon. Your local modifications are unnecessary in one case and outright wrong in the other. Your systemd service unit is defaulting to Type=simple but your /etc/sysconfig/atftpd is using the --daemon option. That is a readiness protocol mismatch. Readiness protocol mismatches cause services not to start correctly, or (more usually) to be (mis-)diagnosed by systemd as failing. So you would still have a problem, of your own making, even when you switched to controlling the socket unit instead of the service unit. Remove the --daemon option that you added in. Your dæmon should not be forking-and-exiting to indicate readiness. It's a fully-fledged socket-activated service in OpenSUSE. The as-shipped file is right. Similarly, systemd will already record all output to syslog, standard output, and standard error by the dæmon; and you are already accessing that journal with the journalctl comand. It is unnecessary to use --logfile and set up a duplicate logging system.
atftpd won't start on opensuse tumbleweed under systemd
1,496,804,509,000
I use Debian Lenny (I know lenny is old and other bla bla) and would like to place a program on the start-up. I use update-rc.d by adding an executable file on /etc/init.d. By referring to http://wiki.debian.org/LSBInitScripts , I need to add a LSB on /etc/init.d/myprogram ### BEGIN INIT INFO # Provides: myprogram # Required-Start: $all # Required-Stop: $remote_fs $syslog # Default-Start: 2 3 4 5 # Default-Stop: 0 1 6 # Short-Description: Start daemon at boot time # Description: Enable service provided by daemon. ### END INIT INFO then do I need to append any script like: DAEMON_PATH="/home/myprogram" DAEMON=node DAEMONOPTS="-my opts" NAME=node DESC="myprogram" PIDFILE=/var/run/$NAME.pid SCRIPTNAME=/etc/init.d/$NAME case "$1" in start) printf "%-50s" "Starting $NAME..." cd $DAEMON_PATH PID=`$DAEMON $DAEMONOPTS > /dev/null 2>&1 & echo $!` #echo "Saving PID" $PID " to " $PIDFILE if [ -z $PID ]; then printf "%s\n" "Fail" else echo $PID > $PIDFILE printf "%s\n" "Ok" fi ;; status) printf "%-50s" "Checking $NAME..." if [ -f $PIDFILE ]; then PID=`cat $PIDFILE` if [ -z "`ps axf | grep ${PID} | grep -v grep`" ]; then printf "%s\n" "Process dead but pidfile exists" else echo "Running" fi else printf "%s\n" "Service not running" fi ;; stop) printf "%-50s" "Stopping $NAME" PID=`cat $PIDFILE` cd $DAEMON_PATH if [ -f $PIDFILE ]; then kill -HUP $PID printf "%s\n" "Ok" rm -f $PIDFILE else printf "%s\n" "pidfile not found" fi ;; restart) $0 stop $0 start ;; *) echo "Usage: $0 {status|start|stop|restart}" exit 1 esac I felt like LSBInitScripts and the above scripts are different thing, but when I check some files on /etc/init.d, they have similar scripts. Could you please clarify if I need the above script or not. If I need the use the script above, do I need to create a .pid file or will it be created automatically?
As far as it's concerned in this context, they're the same thing. The LSB information is just metadata in the form of shell comments added to the init beginning of the script. Just combine those two chunks. It should contain: The interpreter line (e.g., #!/bin/sh) The LSB information, edited to your application's needs. The rest of the script (start/stop functions, etc.). If you need an example you can look at /etc/init.d/skeleton. When you're done, put the file in /etc/init.d/ and use insserv instead of update-rc.d to install the symlinks.
adding a program on start-up by using LSBInitScripts
1,496,804,509,000
I'm running Red Hat 5.1. I have a script called sysinit that I added as a service using chkconfig --add sysinit. I have the following set in the file: #chkconfig 4 01 01 This creates one symlink in my rc4.d directory for S01sysinit. However, I want the script to be run on startup and shutdown. No matter what I do, I cannot get a custom script (Service) to run on shutdown. I even tried separating out my functionality into two scripts, one to run at S01 and the other to run at K01 but it didn't work. I don't want to have to resort to modifying the rc.sysinit file to do what my script should be doing (I shouldn't have to touch that I would think). The reason I need to do this is because I need to unmount a samba share inside the /opt directory before the rc.sysinit file tries to unmount the /opt directory (right now I get "device is busy" failures because the cifs mount is still there). Is there something special I need to do so that my script can run on startup and on shutdown and reboot? Can I have a K01sysinit and S01sysinit in the same run level? Or am I misunderstanding how run levels work? I have the sections for )start and )stop already in the script.
The solution I found was to add the following code: touch /var/lock/subsys/<scriptname> The etc/rc.d/rc file was looking for the lock file when it tried to execute scripts from the symlinks marked with K*. Without that file, the system doesn't know that the "service" is "running".
Can a service script put inside init.d be called at startup and shutdown?
1,496,804,509,000
I have a /etc/rc.d/S11 link to a /etc/init.d file that is trying to set a bash variable of the file system type of a given blkid entry. root@OpenWrt:/# blkid /dev/mmcblk1p3 /dev/mmcblk1p3: UUID="77111d8a-feb7-470c-a489-ffa0e5415c4c" TYPE="f2fs" root@OpenWrt:/# I attempted to tack a awk onto the command root@OpenWrt:/# blkid /dev/mmcblk1p3 | awk '{print $3}' TYPE="f2fs" root@OpenWrt:/# Ideally, I just need the f2fs without the rest. Using awk -F = '{print $3}' returns root@OpenWrt:/# blkid /dev/mmcblk1p3 | awk -F = '{print $3}' "f2fs" root@OpenWrt:/# In the script, I'm trying to set it as a bash variable so I can use it later in the script. CUR_FS=$(blkid /dev/mmcblk1p3 | awk '{print $3}'); However, in the debug message I'm sending to the kernel log, it's blank. echo "[DEBUG] Shield is in ${SHIELD_MODE} Mode - Using /dev/${MNT_POINT} as ${CUR_FS}" > /dev/kmsg Returns [ 34.836024] [DEBUG] Shield is in Gateway Mode - Using /dev/mmcblk1p3 as It's blank. Before someone points out that OpenWrt does not have bash (uses ash by default), I am doing a custom build and baked bash in. Can someone point me in the direction getting the end result of just f2fs without the double-quotes? Writing blkid output to a file gives empty files. blkid /dev/mmcblk1p3 2>&1 > /tmp/output lsblk --noheadings -o FSTYPE /dev/mmcblk1p3 2>&1 > /tmp/output2 Edit Note: lsblk and blkid are separate on my system, so i tried it both ways. Still comes up blank. Could it be that I'm calling it too early? I've also attempted to put the full hard path to the commands, just in case $PATH wasn't set yet - Still blank. Edit 2: It was suggested that the init script was being called too early. I set the script to S99 for testing so that it's called almost last and it the filesystem call is still blank. S99extroot is the script in question. Originally, I had it at S11. K10gpio_switch K99umount S19dropbear S94gpio_switch K10snort S00sysfixtime S19firewall S95done K50dropbear S10boot S20network S96led K85odhcpd S10system S35odhcpd S98sysntpd K89log S11sysctl S50cron S99extroot K90network S12log S50uhttpd S99urandom_seed K90sysfixtime S12rpcd S80ucitrack K98boot S19dnsmasq S90snort root@OpenWrt:/#
I had to delay init until the blk device was available. Put in a while true loop to keep checking for it so I could mknod it.
Reading filesystem type at boot into BASH variable
1,496,804,509,000
I would like to launch a ssh reverse tunnel on system launch. The following line let's me establish the tunnel fine - but I end up being logged into server which I don't want, especially not from an init script. /usr/bin/autossh -M 22222 -o "PubkeyAuthentication=yes" -o "PasswordAuthentication=no" -i /path/to/my/key.key -R 9999:localhost:22 ubuntu@server man autossh says that the -f option should do what I need: causes autossh to drop to the background before running ssh. but the problem is, it doesn't seem to work when I change my command to usr/bin/autossh -f -M.... I've tried this out as part of my init script too which looks like: #! /bin/sh ### BEGIN INIT INFO ### END INIT INFO case "$1" in start) echo "Starting autossh" /usr/bin/autossh -M 22222 -o "PubkeyAuthentication=yes" -o "PasswordAuthentication=no" -i /path/to/the.key -R pppp:localhost:22 user@server ;; stop) echo -n "Shutting down utossk" /usr/bin/killall -KILL autossh ;; *) echo "Usage: $0 {start|stop}" exit 1 esac exit 0 But I need an option to throw it in the background, how do I do this if the -f option doesn't work for me?
What you're looking for is the -N option. From SSH's man page: -N Do not execute a remote command. This is useful for just for‐ warding ports. Your full command would be: /usr/bin/autossh -M 22222 -f -N -o "PubkeyAuthentication=yes" -o "PasswordAuthentication=no" -i /path/to/my/key.key -R pppp:localhost:22 user@server Which is also what I am using (with cron's @reboot), with success. Replace pppp: with the local port you'd like to use.
launch reverse tunnel with autossh on bootup in Ubuntu
1,496,804,509,000
I am running debian Jessie. During startup I want to read some user input. This is done by a custom script in /etc/init.d/ and symlinks in the runlevel dirs. Now I want kdm, which is started by another init script, to be started only after my custom script is finished. I cloud achieve this by adding something like while test -e /tmp/kdm-boot-lock do echo "waiting for lock-file to be deleted by custom-script" sleep 1 done to /etc/init.d/kdm but I would prefer a solution without changing foreign files (which might get changed by updates). So the question is: How can I prevent that a distinct (unchanged) init script (kdm) is started before my custom script finished?
Since you're using initscripts, the right way to defer kdm until your custom script has finished is to declare a dependency from kdm on your custom script, in the LSB header: # Required-Start: ... yourscript in the kdm initscript, and # Provides: yourscript in your custom initscript. To avoid the changes to the kdm initscript being lost on upgrades, you can copy its LSB header to an insserv override file in /etc/insserv/overrides (with the same name), and edit that instead.
Delay an init script until another process is finished?
1,496,804,509,000
I added a script execution command to my rc.local but forgot to run it in a separate tty. The script has an infinite loop and has hung my tty1. Ctrl-C does not do anything and I don't have another bash login that would allow me to kill the script. Is there a keyboard command that will start a bash login? Is there any other way to kill the script?
As rc.local is the last script that is run before the tty's are respawned by /bin/mingetty, therefore, the tty terminals will not be available to log into. However, networking and sshd will be running so just ssh to the host and kill the process as the root user.
Change to rc.local causing hang on tty1
1,496,804,509,000
Most unix servers do have services defined as init scripts, on linux in: /etc/init.d and on hp-ux in: /sbin/init.d. However, what if I just want a single command to be executed when machine boots? I could write a service init script for that purpose, but that seems to me too complicated for just one command, which launches a process which performs something and then immediately terminates. Is there a script, somewhere, in which I can just append a line, similar to autoexec.bat in ms-dos?
If you are using a System V or BSD-like init, you can add a line in /etc/rc.local with the command. I suggest you background it (using &) so that it does not block further startup. If you are using systemd, be aware that it does not read /etc/rc.local by default. You can either write a service to execute /etc/rc.local, or make a service file for the command itself. The latter will likely allay some of your worries about creating an entire init script for a single command -- systemd service files are far easier to read than traditional init files, which are generally fully blown shell scripts.
Run a single command at the start of the machine
1,496,804,509,000
I am using SUSE Linux Enterprise Server 11 (x86_64) as VM Ware virtual machine (that was cloned). Not sure why but network card cannot be configured via yast2. If I go to edit and hit enter Yast will go back to "Control Center". Also in yast2 I can see that the card is "not connected". No idea what it means though. But if I go command line and issue these two commands the network is up and running. ifconfig eth1 10.0.0.xxx netmask 255.255.255.0 broadcast 10.0.0.255 route add default gw 10.0.0.1 eth1 From /var/log/messages Jun 18 14:20:19 Edumate kernel: [ 221.986998] e1000: eth1 NIC Link is Up 1000 Mbps Full Duplex, Flow Control: None Jun 18 14:20:19 Edumate kernel: [ 221.988366] ADDRCONF(NETDEV_UP): eth1: link is not ready Jun 18 14:20:19 Edumate kernel: [ 221.988482] ADDRCONF(NETDEV_CHANGE): eth1: link becomes ready Jun 18 14:20:29 Edumate kernel: [ 232.399704] eth1: no IPv6 routers present Q1: Would anybody know how to fix the network configuration or Q2: What files I update with above two commands so I can have network up and running after each reboot? EDITs removing /etc/udev/rules.d/70-persistent-net.rules and rebooting didn't help content of /etc/sysconfig/network Edu:/var/lib/edu/bdrs # cd /etc/sysconfig/network Edu:/etc/sysconfig/network # ll total 108 -rw-r--r-- 1 root root 13192 Jun 5 16:30 config -rw-rw-rw- 1 root root 13181 Jun 5 15:42 config.backup.by.convert_to_netconfig -rw-r--r-- 1 root root 7482 Jun 18 14:10 dhcp -rw-r--r-- 1 root root 7686 Jun 5 15:42 dhcp.backup.by.convert_to_netconfig drwxr-xr-x 2 root root 4096 Jun 5 15:42 if-down.d drwxr-xr-x 2 root root 4096 Jun 5 15:42 if-up.d -rw------- 1 root root 172 Jan 31 23:45 ifcfg-lo -rw-r--r-- 1 root root 29333 Jan 31 23:45 ifcfg.template -rw-r--r-- 1 root root 239 Jan 31 23:45 ifroute-lo drwx------ 2 root root 4096 May 6 2010 providers -rw-r--r-- 1 root root 22 Jun 18 14:07 routes -rw-r--r-- 1 root root 0 Jun 18 14:07 routes.YaST2save drwxr-xr-x 2 root root 4096 Jun 5 15:42 scripts
On SuSE, you can configure the network manually via files in /etc/sysconfig/network. Create a file called /etc/sysconfig/network/ifcfg-eth1 containing STARTMODE=onboot BOOTPROTO=static IPADDR=10.0.0.xxx NETMASK=255.255.255.0 BROADCAST=10.0.0.255 The default route needs to be set in /etc/sysconfig/network/routes. default 10.0.0.1 - eth1
Need to configure network card manually after each reboot
1,496,804,509,000
I have to tune my laptop's keyboard behaviour by lowering its brightness timeout, so I placed a one-line command in a script file, executed at boot. Here is it: $ cat /usr/local/bin/boot-script.sh #!/bin/bash echo "10s" | sudo tee /sys/devices/platform/dell-laptop/leds/dell\:\:kbd_backlight/stop_timeout Unfortunately, I get an error on boot saying: machi boot-script.sh[362]: tee: '/sys/devices/platform/dell-laptop/leds/dell::kbd_backlight/stop_timeout': No such file or directory machi boot-script.sh[362]: 10s Despite, the file exists: $ cat /sys/devices/platform/dell-laptop/leds/dell::kbd_backlight/stop_timeout 10s Why do I get this error? How can I fix it? Thanks
After some attempts, the only way I found to fix the issue is to force the loading of the related kernel module (dell_laptop in my case) early in the boot process. I am on Arch Linux, and I have achieved it by adding dell_laptop in the MODULES=() array in /etc/mkinitcpio.conf. Furthermore: as @MC68020 stated, the implicated magic file is not yet present when the script is executed why does trick posted by @steve does not work? is there somewhere any other problem? is it the best way to overcome this issue?
Bash script error on boot
1,496,804,509,000
I wrote an LSB init script that can manage multiple instances of my daemon: rcfoo start starts all the instances (which are found in some /etc configuration file), rcfoo stop stops all the instances, rcfoo status displays the status of all instances, and rcfoo reload reloads updates the daemon with a changed configuration. First I wonder how to detect the instances to work on with some [email protected] systemd unit file. AFAIK I must specify all the instances like foo@A, foo@B, and so on. Second my LSB script can report an extended status, meaning it can display whether a service reload is needed (and my reload actually optimizes to only reload the services that need it). How can I make a custom status report? I think a script has to use systemd-notify for custom status messages. Fortunately my final extension to the LSB script, namely manipulating single instances by adding single <instance> (like in rcfoo start single A), is supported out-of-the-box with systemd. So my basic question is the first one.
I found two possible solutions: Write a "wrapper script" that accepts an instance parameter and a command parameter. Then the script has to search whether the instance requested is actually found in the configuration file in /etc. The script actually does provide start, stop, and reload, while the PID of the daemon process is handled by systemd via PIDFile=. In addition write a service unit like [email protected] that contains the wrapper script for ExecStart=, ExecStop=, etc. The instance name is represented by %i there. What's not so nice is the fact that you'll have to know the instance names, and when using an invalid one, systemd creates a non-operational instance that is repeatedly restarting (until cleaned up manually with systemctl reset-failed). The thing with conditional restart wasn't solved with this approach. So you would systemctl start foo@A. Alternatively you can get rid of the wrapper script by writing a generator reads the configuration file and creates a service instance unit file for each instance found. The command-lines being used is assembled by the generator using the config file. Additional shell commands (e.g. to create a runtime-directory, or to wait for daemon fork to complete) are added by the generator via ExecStartPre= and ExecStartPost=. There are some issues unresolved, but the systemd community represented on the development list wasn't actually helpful: They told me generators are an advanced concept that I should not use it, not actually answering my questions. Things missing in this answer are: How to configure a sytemd target that starts and stops all services? I thought I'd have one, but it failed on boot (generated unit file was empty for unknown reasons).
How to migrate a multi-instance LSB script to systemd?
1,496,804,509,000
The Setup I have a machine that is running OpenBSD, it has two SSDs in it: sd0 and sd1. I've setup each SSD with two partitions a and d. From there I've built two mirrors using bioctl: The first mirror is built from sd0a and sd1a ; this shows up as sd2 The second mirror is built from sd0d and sd1d ; this shows up as sd3 The root of the system / is mounted to sd2a. I then used bioctl to build an encrypted softraid on-top of sd3 ; this shows up as sd4. The rest of the system is mounted on sd4 : /usr, /home, /tmp, /var etc.. The Issue When the system boots it obviously complains it can't find /var /usr /tmp etc. I am able to drop to a shell and manually attach the encrypted container with the command: bioctl -c C -l /dev/sd3a softraid0. Then I exit the shell and system boots fine. But when I try to automate this with a script in rc.local or rc.securelevel it doesn't work... Here's the script I've tried in rc.local and rc.securelevel bioctl sd4 > /dev/null 2>&1 if [ $? -ne 0 ]; then echo "Mounting..." bioctl -c C -l /dev/sd3a softraid0 fi Thank you for taking the time to look at this! edit As asked for here is the boot message - I've marked the spot it gets to when it breaks and complains it can't find /var /tmp /usr etc. Mar 12 06:52:10 sql /bsd: avail mem = 33187635200 (31650MB) Mar 12 06:52:10 sql /bsd: mpath0 at root Mar 12 06:52:10 sql /bsd: scsibus0 at mpath0: 256 targets Mar 12 06:52:10 sql /bsd: mainbus0 at root Mar 12 06:52:10 sql /bsd: bios0 at mainbus0: SMBIOS rev. 3.0 @ 0xea820 (69 entries) Mar 12 06:52:10 sql /bsd: bios0: vendor American Megatrends Inc. version "1.70" date 12/18/2017 Mar 12 06:52:10 sql /bsd: bios0: Micro-Star International Co., Ltd. MS-7B09 Mar 12 06:52:10 sql /bsd: acpi0 at bios0: rev 2 Mar 12 06:52:10 sql /bsd: acpi0: sleep states S0 S3 S4 S5 Mar 12 06:52:10 sql /bsd: acpi0: tables DSDT FACP APIC FPDT FIDT SSDT SSDT SSDT MCFG SSDT CRAT CDIT HPET SSDT UEFI SSDT SSDT Mar 12 06:52:10 sql /bsd: acpi0: wakeup devices D0A1(S4) D0A2(S4) D0A3(S4) D0A4(S4) D0A5(S4) D0A6(S4) D0A7(S4) D0B0(S4) D0B1(S4) D0B2(S4) D0B3(S4) D0B4(S4) D0B5(S4) D0B6(S4) D0B7(S4) D0C0(S4) [...] Mar 12 06:52:10 sql /bsd: acpitimer0 at acpi0: 3579545 Hz, 32 bits Mar 12 06:52:10 sql /bsd: acpimadt0 at acpi0 addr 0xfee00000: PC-AT compat Mar 12 06:52:10 sql /bsd: cpu0 at mainbus0: apid 0 (boot processor) Mar 12 06:52:10 sql /bsd: cpu0: AMD Ryzen Threadripper 1900X 8-Core Processor, 3800.79 MHz Mar 12 06:52:10 sql /bsd: cpu0: FPU,VME,DE,PSE,TSC,MSR,PAE,MCE,CX8,APIC,SEP,MTRR,PGE,MCA,CMOV,PAT,PSE36,CFLUSH,MMX,FXSR,SSE,SSE2,HTT,SSE3,PCLMUL,MWAIT,SSSE3,FMA3,CX16,SSE4.1,SSE4.2,MOVBE,POPCNT,AES,XSAVE,AVX,F16C,RDRAND,NXE,MMXX,FFXSR,PAGE1GB,RDTSCP,LONG,LAHF,CMPLEG,SVM,EAPICSP,AMCR8,ABM,SSE4A,MASSE,3DNOWP,OSVW,SKINIT,TOPEXT,ITSC,FSGSBASE,BMI1,AVX2,SMEP,BMI2,RDSEED,ADX,SMAP,CLFLUSHOPT,SHA Mar 12 06:52:10 sql /bsd: cpu0: 64KB 64b/line 4-way I-cache, 32KB 64b/line 8-way D-cache, 512KB 64b/line 8-way L2 cache, 16MB 64b/line 32-way L3 cache Mar 12 06:52:10 sql /bsd: cpu0: ITLB 64 4KB entries fully associative, 64 4MB entries fully associative Mar 12 06:52:10 sql /bsd: cpu0: DTLB 64 4KB entries fully associative, 64 4MB entries fully associative Mar 12 06:52:10 sql /bsd: cpu0: TSC frequency 3800785080 Hz Mar 12 06:52:10 sql /bsd: cpu0: smt 0, core 0, package 0 Mar 12 06:52:10 sql /bsd: mtrr: Pentium Pro MTRR support, 8 var ranges, 88 fixed ranges Mar 12 06:52:10 sql /bsd: cpu0: apic clock running at 100MHz Mar 12 06:52:10 sql /bsd: cpu0: mwait min=64, max=64, IBE Mar 12 06:52:10 sql /bsd: cpu1 at mainbus0: apid 2 (application processor) Mar 12 06:52:10 sql /bsd: cpu1: AMD Ryzen Threadripper 1900X 8-Core Processor, 3800.01 MHz Mar 12 06:52:10 sql /bsd: cpu1: FPU,VME,DE,PSE,TSC,MSR,PAE,MCE,CX8,APIC,SEP,MTRR,PGE,MCA,CMOV,PAT,PSE36,CFLUSH,MMX,FXSR,SSE,SSE2,HTT,SSE3,PCLMUL,MWAIT,SSSE3,FMA3,CX16,SSE4.1,SSE4.2,MOVBE,POPCNT,AES,XSAVE,AVX,F16C,RDRAND,NXE,MMXX,FFXSR,PAGE1GB,RDTSCP,LONG,LAHF,CMPLEG,SVM,EAPICSP,AMCR8,ABM,SSE4A,MASSE,3DNOWP,OSVW,SKINIT,TOPEXT,ITSC,FSGSBASE,BMI1,AVX2,SMEP,BMI2,RDSEED,ADX,SMAP,CLFLUSHOPT,SHA Mar 12 06:52:10 sql /bsd: cpu1: 64KB 64b/line 4-way I-cache, 32KB 64b/line 8-way D-cache, 512KB 64b/line 8-way L2 cache, 16MB 64b/line 32-way L3 cache Mar 12 06:52:10 sql /bsd: cpu1: ITLB 64 4KB entries fully associative, 64 4MB entries fully associative Mar 12 06:52:10 sql /bsd: cpu1: DTLB 64 4KB entries fully associative, 64 4MB entries fully associative Mar 12 06:52:10 sql /bsd: cpu1: smt 0, core 2, package 0 Mar 12 06:52:10 sql /bsd: cpu15 at mainbus0: apid 23 (application processor) Mar 12 06:52:10 sql /bsd: cpu15: AMD Ryzen Threadripper 1900X 8-Core Processor, 3800.01 MHz Mar 12 06:52:10 sql /bsd: cpu15: FPU,VME,DE,PSE,TSC,MSR,PAE,MCE,CX8,APIC,SEP,MTRR,PGE,MCA,CMOV,PAT,PSE36,CFLUSH,MMX,FXSR,SSE,SSE2,HTT,SSE3,PCLMUL,MWAIT,SSSE3,FMA3,CX16,SSE4.1,SSE4.2,MOVBE,POPCNT,AES,XSAVE,AVX,F16C,RDRAND,NXE,MMXX,FFXSR,PAGE1GB,RDTSCP,LONG,LAHF,CMPLEG,SVM,EAPICSP,AMCR8,ABM,SSE4A,MASSE,3DNOWP,OSVW,SKINIT,TOPEXT,ITSC,FSGSBASE,BMI1,AVX2,SMEP,BMI2,RDSEED,ADX,SMAP,CLFLUSHOPT,SHA Mar 12 06:52:10 sql /bsd: cpu15: 64KB 64b/line 4-way I-cache, 32KB 64b/line 8-way D-cache, 512KB 64b/line 8-way L2 cache, 16MB 64b/line 32-way L3 cache Mar 12 06:52:10 sql /bsd: cpu15: ITLB 64 4KB entries fully associative, 64 4MB entries fully associative Mar 12 06:52:10 sql /bsd: cpu15: DTLB 64 4KB entries fully associative, 64 4MB entries fully associative Mar 12 06:52:10 sql /bsd: cpu15: smt 0, core 23, package 0 Mar 12 06:52:10 sql /bsd: "PNP0C14" at acpi0 not configured Mar 12 06:52:10 sql /bsd: acpibtn0 at acpi0: PWRB Mar 12 06:52:10 sql /bsd: "AMDI0030" at acpi0 not configured Mar 12 06:52:10 sql /bsd: "AMDI0010" at acpi0 not configured Mar 12 06:52:10 sql /bsd: "PNP0C14" at acpi0 not configured Mar 12 06:52:10 sql /bsd: "AMDIF030" at acpi0 not configured Mar 12 06:52:10 sql /bsd: "PNP0C14" at acpi0 not configured Mar 12 06:52:10 sql /bsd: cpu0: 3800 MHz: speeds: 3800 3000 2200 MHz Mar 12 06:52:10 sql /bsd: pci0 at mainbus0 bus 0 Mar 12 06:52:10 sql /bsd: pci1 at ppb0 bus 1 Mar 12 06:52:10 sql /bsd: xhci0 at pci1 dev 0 function 0 vendor "AMD", unknown product 0x43ba rev 0x02: msi Mar 12 06:52:10 sql /bsd: usb0 at xhci0: USB revision 3.0 Mar 12 06:52:10 sql /bsd: uhub0 at usb0 configuration 1 interface 0 "AMD xHCI root hub" rev 3.00/1.00 addr 1 Mar 12 06:52:10 sql /bsd: ahci0 at pci1 dev 0 function 1 vendor "AMD", unknown product 0x43b6 rev 0x02: msi, AHCI 1.3.1 Mar 12 06:52:10 sql /bsd: scsibus1 at ahci0: 32 targets Mar 12 06:52:10 sql /bsd: xhci1 at pci3 dev 0 function 0 vendor "ASMedia", unknown product 0x2142 rev 0x00: msi Mar 12 06:52:10 sql /bsd: usb1 at xhci1: USB revision 3.0 Mar 12 06:52:10 sql /bsd: uhub1 at usb1 configuration 1 interface 0 "ASMedia xHCI root hub" rev 3.00/1.00 addr 1 Mar 12 06:52:10 sql /bsd: ppb3 at pci2 dev 2 function 0 vendor "AMD", unknown product 0x43b4 rev 0x02: msi Mar 12 06:52:10 sql /bsd: em0 at pci8 dev 0 function 0 "Intel I211" rev 0x03: msi, address 30:9c:23:64:e8:f3 Mar 12 06:52:10 sql /bsd: ppb8 at pci2 dev 7 function 0 vendor "AMD", unknown product 0x43b4 rev 0x02: msi Mar 12 06:52:10 sql /bsd: pci9 at ppb8 bus 9 Mar 12 06:52:10 sql /bsd: ppb9 at pci0 dev 1 function 2 vendor "AMD", unknown product 0x1453 rev 0x00: msi Mar 12 06:52:10 sql /bsd: pci10 at ppb9 bus 10 Mar 12 06:52:10 sql /bsd: nvme0 at pci10 dev 0 function 0 "Samsung SM961/PM961 NVMe" rev 0x00: msi, NVMe 1.2 Mar 12 06:52:10 sql /bsd: nvme0: Samsung SSD 960 EVO 250GB, firmware 3B7QCXE7, serial S3ESNX0JB78420A Mar 12 06:52:10 sql /bsd: scsibus2 at nvme0: 1 targets Mar 12 06:52:10 sql /bsd: sd0 at scsibus2 targ 0 lun 0: <NVMe, Samsung SSD 960, 3B7Q> SCSI4 0/direct fixed Mar 12 06:52:10 sql /bsd: sd0: 238475MB, 512 bytes/sector, 488397168 sectors Mar 12 06:52:10 sql /bsd: pci11 at ppb10 bus 11 Mar 12 06:52:10 sql /bsd: vendor "AMD", unknown product 0x145a (class instrumentation unknown subclass 0x00, rev 0x00) at pci11 dev 0 function 0 not configured Mar 12 06:52:10 sql /bsd: vendor "AMD", unknown product 0x1456 (class crypto subclass miscellaneous, rev 0x00) at pci11 dev 0 function 2 not configured Mar 12 06:52:10 sql /bsd: xhci2 at pci11 dev 0 function 3 vendor "AMD", unknown product 0x145c rev 0x00: msi Mar 12 06:52:10 sql /bsd: usb2 at xhci2: USB revision 3.0 Mar 12 06:52:10 sql /bsd: uhub2 at usb2 configuration 1 interface 0 "AMD xHCI root hub" rev 3.00/1.00 addr 1 Mar 12 06:52:10 sql /bsd: pchb6 at pci0 dev 8 function 0 vendor "AMD", unknown product 0x1452 rev 0x00 Mar 12 06:52:10 sql /bsd: ppb11 at pci0 dev 8 function 1 vendor "AMD", unknown product 0x1454 rev 0x00 Mar 12 06:52:10 sql /bsd: pci12 at ppb11 bus 12 Mar 12 06:52:10 sql /bsd: vendor "AMD", unknown product 0x1455 (class instrumentation unknown subclass 0x00, rev 0x00) at pci12 dev 0 function 0 not configured Mar 12 06:52:10 sql /bsd: ahci1 at pci12 dev 0 function 2 vendor "AMD", unknown product 0x7901 rev 0x51: msi, AHCI 1.3.1 Mar 12 06:52:10 sql /bsd: scsibus3 at ahci1: 32 targets Mar 12 06:52:10 sql /bsd: azalia0 at pci12 dev 0 function 3 vendor "AMD", unknown product 0x1457 rev 0x00: msi Mar 12 06:52:10 sql /bsd: azalia0: codecs: Realtek/0x1220 Mar 12 06:52:10 sql /bsd: audio0 at azalia0 Mar 12 06:52:10 sql /bsd: vendor "AMD", unknown product 0x790b (class serial bus subclass SMBus, rev 0x59) at pci0 dev 20 function 0 not configured Mar 12 06:52:10 sql /bsd: isa0 at pcib0 Mar 12 06:52:10 sql /bsd: isadma0 at isa0 Mar 12 06:52:10 sql /bsd: com0 at isa0 port 0x3f8/8 irq 4: ns16550a, 16 byte fifo Mar 12 06:52:10 sql /bsd: pckbc0 at isa0 port 0x60/5 irq 1 irq 12 Mar 12 06:52:10 sql /bsd: pckbd0 at pckbc0 (kbd slot) Mar 12 06:52:10 sql /bsd: wskbd0 at pckbd0: console keyboard Mar 12 06:52:10 sql /bsd: vga0 at isa0 port 0x3b0/48 iomem 0xa0000/131072 Mar 12 06:52:10 sql /bsd: wsdisplay0 at vga0 mux 1: console (80x25, vt100 emulation), using wskbd0 Mar 12 06:52:10 sql /bsd: wsdisplay0: screen 1-5 added (80x25, vt100 emulation) Mar 12 06:52:10 sql /bsd: pcppi0 at isa0 port 0x61 Mar 12 06:52:10 sql /bsd: spkr0 at pcppi0 Mar 12 06:52:10 sql /bsd: pci13 at mainbus0 bus 64 Mar 12 06:52:10 sql /bsd: pci14 at ppb12 bus 65 Mar 12 06:52:10 sql /bsd: nvme1 at pci14 dev 0 function 0 "Samsung SM951/PM951 NVMe" rev 0x01: msi, NVMe 1.1 Mar 12 06:52:10 sql /bsd: nvme1: Samsung SSD 950 PRO 512GB, firmware 1B0QBXX7, serial S2GMNX0H921434T Mar 12 06:52:10 sql /bsd: scsibus4 at nvme1: 1 targets Mar 12 06:52:10 sql /bsd: sd1 at scsibus4 targ 0 lun 0: <NVMe, Samsung SSD 950, 1B0Q> SCSI4 0/direct fixed Mar 12 06:52:10 sql /bsd: sd1: 488386MB, 512 bytes/sector, 1000215216 sectors Mar 12 06:52:10 sql /bsd: pchb25 at pci13 dev 2 function 0 vendor "AMD", unknown product 0x1452 rev 0x00 Mar 12 06:52:10 sql /bsd: pchb26 at pci13 dev 3 function 0 vendor "AMD", unknown product 0x1452 rev 0x00 Mar 12 06:52:10 sql /bsd: ppb13 at pci13 dev 3 function 1 vendor "AMD", unknown product 0x1453 rev 0x00: msi Mar 12 06:52:10 sql /bsd: pci15 at ppb13 bus 66 Mar 12 06:52:10 sql /bsd: vendor "ATI", unknown product 0x67df (class display subclass VGA, rev 0xe7) at pci15 dev 0 function 0 not configured Mar 12 06:52:10 sql /bsd: azalia1 at pci15 dev 0 function 1 vendor "ATI", unknown product 0xaaf0 rev 0x00: msi Mar 12 06:52:10 sql /bsd: azalia1: no supported codecs Mar 12 06:52:10 sql /bsd: pchb27 at pci13 dev 4 function 0 vendor "AMD", unknown product 0x1452 rev 0x00 Mar 12 06:52:10 sql /bsd: pchb28 at pci13 dev 7 function 0 vendor "AMD", unknown product 0x1452 rev 0x00 Mar 12 06:52:10 sql /bsd: ppb14 at pci13 dev 7 function 1 vendor "AMD", unknown product 0x1454 rev 0x00 Mar 12 06:52:10 sql /bsd: pci16 at ppb14 bus 67 Mar 12 06:52:10 sql /bsd: vendor "AMD", unknown product 0x145a (class instrumentation unknown subclass 0x00, rev 0x00) at pci16 dev 0 function 0 not configured Mar 12 06:52:10 sql /bsd: vendor "AMD", unknown product 0x1456 (class crypto subclass miscellaneous, rev 0x00) at pci16 dev 0 function 2 not configured Mar 12 06:52:10 sql /bsd: xhci3 at pci16 dev 0 function 3 vendor "AMD", unknown product 0x145c rev 0x00: msi Mar 12 06:52:10 sql /bsd: usb3 at xhci3: USB revision 3.0 Mar 12 06:52:10 sql /bsd: uhub3 at usb3 configuration 1 interface 0 "AMD xHCI root hub" rev 3.00/1.00 addr 1 Mar 12 06:52:10 sql /bsd: pchb29 at pci13 dev 8 function 0 vendor "AMD", unknown product 0x1452 rev 0x00 Mar 12 06:52:10 sql /bsd: ppb15 at pci13 dev 8 function 1 vendor "AMD", unknown product 0x1454 rev 0x00 Mar 12 06:52:10 sql /bsd: pci17 at ppb15 bus 68 Mar 12 06:52:10 sql /bsd: vendor "AMD", unknown product 0x1455 (class instrumentation unknown subclass 0x00, rev 0x00) at pci17 dev 0 function 0 not configured Mar 12 06:52:10 sql /bsd: ahci2 at pci17 dev 0 function 2 vendor "AMD", unknown product 0x7901 rev 0x51: msi, AHCI 1.3.1 Mar 12 06:52:10 sql /bsd: scsibus5 at ahci2: 32 targets Mar 12 06:52:10 sql /bsd: uhidev0 at uhub0 port 21 configuration 1 interface 0 "Microsoft Microsoft\M-. Digital Media oard 3000" rev 2.00/2.00 addr 2 Mar 12 06:52:10 sql /bsd: uhidev0: iclass 3/1 Mar 12 06:52:10 sql /bsd: ukbd0 at uhidev0: 8 variable keys, 6 key codes Mar 12 06:52:10 sql /bsd: wskbd1 at ukbd0 mux 1 Mar 12 06:52:10 sql /bsd: wskbd1: connecting to wsdisplay0 Mar 12 06:52:10 sql /bsd: uhidev1 at uhub0 port 21 configuration 1 interface 1 "Microsoft Microsoft\M-. Digital Media oard 3000" rev 2.00/2.00 addr 2 Mar 12 06:52:10 sql /bsd: uhidev1: iclass 3/0, 3 report ids Mar 12 06:52:10 sql /bsd: uhid0 at uhidev1 reportid 1: input=7, output=0, feature=0 Mar 12 06:52:10 sql /bsd: uhid1 at uhidev1 reportid 3: input=1, output=0, feature=0 Mar 12 06:52:10 sql /bsd: vscsi0 at root Mar 12 06:52:10 sql /bsd: scsibus6 at vscsi0: 256 targets Mar 12 06:52:10 sql /bsd: softraid0 at root Mar 12 06:52:10 sql /bsd: scsibus7 at softraid0: 256 targets Mar 12 06:52:10 sql /bsd: sd2 at scsibus7 targ 1 lun 0: <OPENBSD, SR RAID 1, 006> SCSI2 0/direct fixed Mar 12 06:52:10 sql /bsd: sd2: 20479MB, 512 bytes/sector, 41942512 sectors Mar 12 06:52:10 sql /bsd: sd3 at scsibus7 targ 2 lun 0: <OPENBSD, SR RAID 1, 006> SCSI2 0/direct fixed Mar 12 06:52:10 sql /bsd: sd3: 217992MB, 512 bytes/sector, 446448433 sectors Mar 12 06:52:10 sql /bsd: root on sd2a (1ff7dd9b647c5f6f.a) swap on sd2b dump on sd2b *** This is where I have to drop to a shell and manually attach the encrypted softraid0 *** Mar 12 06:52:10 sql /bsd: sd4 at scsibus7 targ 3 lun 0: <OPENBSD, SR CRYPTO, 006> SCSI2 0/direct fixed Mar 12 06:52:10 sql /bsd: sd4: 217992MB, 512 bytes/sector, 446447905 sectors Mar 12 06:52:10 sql sendsyslog: dropped 1 message, error 57 Mar 12 06:52:10 sql ntpd[66920]: /var/db/ntpd.drift is empty Mar 12 06:52:10 sql savecore: /dev/sd2b: Device not configured Mar 12 06:52:15 sql reorder_kernel: kernel relinking done Also after I manually mount the encrypted softraid and the boot finishes everything works, here is the output from mount: /dev/sd2a on / type ffs (local) /dev/sd4k on /home type ffs (local, nodev, nosuid) /dev/sd4d on /tmp type ffs (local, nodev, nosuid) /dev/sd4f on /usr type ffs (local, nodev) /dev/sd4g on /usr/X11R6 type ffs (local, nodev) /dev/sd4h on /usr/local type ffs (local, nodev, wxallowed) /dev/sd4j on /usr/obj type ffs (local, nodev, nosuid) /dev/sd4i on /usr/src type ffs (local, nodev, nosuid) /dev/sd4e on /var type ffs (local, nodev, nosuid)
So after a bit of digging and reading here's what I've found: rc.local and even rc.securelevel are called far too late in the rc scripts to be used to mount the rest of the file system. A quick grep through the rc scripts made it clear the encrypted softraid needs to be attached just before the "Check filesystems" code runs in rc. To make sure the code only runs on startup I've added the following just above the "Check filesystems" script in rc: # ADDED - This mounts the encrypted filesystem bioctl sd4 > /dev/null 2>&1 if [ $? -ne 0 ]; then echo "Time to decrypt and mount the rest of your filesystem..." bioctl -c C -l /dev/sd3a softraid0 fi To be clear I don't like this solution as I will have to be wary with updates that replace/modify rc but I don't see a way around this. If someone from OpenBSD has a better solution please do let me know! I know this is super basic but I figure this might save someone some time so I leave the question up. Also testing recovery/consistency of encrypted content sitting on top of a mirror that has lost a disk(and has been rebuilt) seems to fail. It doesn't seem to be able to see/handle the encrypted device - it's too bad OpenBSD can't quite yet handle this. You'll have to look at hardware solutions for the mirror and then use FDE in OpenBSD, or use a different O/S. Thanks everyone.
Mounting Encrypted Softraid on OpenBSD
1,496,804,509,000
I am attempting to create a new EC2 instance and I am supplying user-data to the instance at create time. My user-data executes some bash commands that modify the parameters of a properties file for another application (myApplication). The intent is to modify the configuration of myApplication BEFORE it starts. myApplication is configured to start from /etc/init.d . I'm basically trying to do what is described here I see that the chkconfig configuration for /etc/init.d/cloud-init-local is set with priority 50. I am assuming that this is the mechanism by which my user-data script is executed. myApplication is also configured with chkconfig, but with priority 90. The plan is that the user-data is executed BEFORE myApplication starts. But, this is not what I am experiencing. I can see in the cloud-init-output.log file that my user-data does get executed, but myApplication has already started. Is my assumption that my user-data script is executed by /etc/init.d/cloud-init-local wrong? Is my expectation of the behavior of the boot sequence incorrect? Any help is appreciated, thanks!
I think you hit a systemd bug. (One that they thought was a good idea.) Specifically to improve boot speed on sysv scripts that are imported they are run in parallel UNLESS you configure LSB dependencies, which sysv init ignores. The way around this is to either convert both init scripts to be systemd scripts with systemd dependencies. add dependencies to both init scripts. choose another init system that does not try to be smarter than you.
Order of execution for cloud-init-local on AWS Linux
1,416,824,305,000
I need to run a /usr/sbin command in my init script, so there is a dependency for the /usr filesytem to be mounted. To resolve the dependency, I put $local_fs or boot.localfs (I also tried $remote_fs and $all) in the required-start field of init script header, but it does still mount the /usr filesystem and my command in the initscript still fails with "command not found" error. I could resolve the issue by adding boot.localfs in the .depend.boot file, but why could not I resolve from the required-start init script header? Edit: I'm using the SUSE Linux 10.
I figured out the solution, it might just help others. The problem was that just adding the dependency of boot.localfs in my init script was not enough. After adding the dependency, one needs to run the insserv command (as insserv boot.myinitscript) to enable the init script that is changed and it automatically resolves the boot dependency order by adding necessary things to .depend.boot file, which I was adding manually before.
Init script header not resolving dependency
1,416,824,305,000
I need to run a script before shutting down or rebooting my VPS running Debian 8,to keep count of network statistics.I tried adding the script directly to /etc/init.d and symlinking it in /etc/rc0.d and /etc/rc6.d, and adding to it the LSB header, making it like an actual service with start and stop and generating the symlinks with update-rc.d, but nothing has worked, it seems like the script isn't executed at all.Maybe it could have to do with it being an VPS, so it doesn't get recognised by the system when it is apparently shut down or rebooted. I just need a simple mechanism,without having to create a proper service. Also I'd like to know which could be the better way to check if the script is actually being executed or not,some simple way of logging. The script is just this: RESULT=$(bc <<< "scale =2;($(cat /sys/class/net/venet0/statistics/rx_bytes)/1024/1024/1024)+($(cat /sys/class/net/venet0/statistics/tx_bytes)/1024/1024/1024)+($(cat /root/bw))") echo $RESULT > /root/bw
This works for me as /etc/systemd/system/netstat.service: [Unit] Description=Save interface stats on shutdown [Service] Type=oneshot RemainAfterExit=yes ExecStart=/bin/true ExecStop=/bin/sh -c '{ date; ip -s link; } >>/root/ipstat.log' [Install] WantedBy=multi-user.target Enable it with systemctl enable netstat. This won't give you precise statistics, because the network interfaces can still be used during shutdown, but that may be acceptable for you.
Execute simple script before shutdown and reboot
1,416,824,305,000
I am using my laptop in several monitor configurations that do require xorg.conf (say, I am driving a T221 from my laptop) and it's very inconvenient to manually switch them. Is there something in /sys which tells me if something is plugged into a DVI connector? Or a utility or ...?
Note that this broke with the latest Arch Linux upgrade, however the directory /sys/class/drm/ contains all the video outputs. I use head -1 /sys/class/drm/card0-HDMI-A-3/modes to detect the existence of the 3840x2400 mode but one could just check /sys/class/drm/card0-HDMI-A-3/status for connected vs disconnected if the mode was not important which is the exact and fastest answer to my question :)
Detecting monitor on boot time?
1,416,824,305,000
So I am working on building minimal os using busybox. What I want is I want to run my .net program from BIOS. But I am not sure linux will run .net program or not, so to clear my path I am using C program instead of .net program. I am generating initrd.img file successfully. Now before generating initrd.img file. I want to integrate my hello.c program with init file. This command I used to read file and which is reading C program code successfully. echo 'cat /etc/hello.c' >> init Now I want to execute this hello.c. So I tried following command but it not working as cat command. echo 'gcc -o echo /etc/hello.c' >> init echo 'chmod +x echo' >> init echo './echo' >> init This is the error I am getting: /init: line 6: gcc: not found chmod: echo: No such file or directory /init: line 8: ./echo: not found
Your script is failing because you don’t have gcc in your initrd. You should not ship hello.c in your initrd; you should build the program and ship that instead in your initrd. You should also specify the full path to your program when attempting to run it.
How to integrate C program with init file?
1,416,824,305,000
I'm trying to understand what goes on when I start up a linux server. My linux server has files /etc/rc2.d/S03cron, /etc/rc3.d/S03cron, /etc/rc4.d/S03cron, /etc/rc5.d/S03cron which should start the cron daemon 4 times. once at each of those run levels. why is there only one cron process on my system? did it try to start the process 4 times but only the first one works? does the system immediately go to runlevel 5? or does it go through S, 1, 2, 3, 4, 5 like that?
This depends on what init system you are using. In some init systems — old Solaris or SunOS, I think, although it's been way too long — the runlevels are cumulative in the way you are expecting. In others, including every Linux that uses the runlevel concept that I've ever heard of, they're independent descriptions of what things should be started or stopped at that runlevel (which can lead to messiness if you are going between levels and the K (stop) script is missing).
Why do init scripts not run multiple times?
1,416,824,305,000
nvidia-settings -a [gpu:0]/GPUPowerMizerMode=1 now what is the easiest way to run this one bash line of code at startup??? I am running Gnome 3.14.
You can use gnome-session-properties in terminal or using Alt+F2. That opens up Startup Applications Preferences in my Linux Mint (could be different for your distro). Give a name for your command (optional) Write the bash code in Command option Add any comment (optional) Alternatively, you could give a command to execute a bash file (which contains your code) in the commands option. UPDATE: As notified by don_crissti you have to use gnome-tweak-tool instead. I'm guessing it still has similar options.
I need to run a one line startup script under gnome and systemd
1,416,824,305,000
I have set my script to run using the /etc/init.d method. All works good. The problem is that my script does packet capturing and when it restarts the machine after say the crond is loaded then it loads this script of mine and the packet capture process I guess starting then and it halts from going further. Is there any method where I can force it only to start when Linux is fully loaded ? Below is how my script looks like. #!/bin/bash # chkconfig: 2345 95 05 # myapp daemon # description: myapp daemon # processname: myapp DAEMON_PATH="/usr/local/bin/" DAEMON=pc1.c #DAEMONOPTS="-my opts" NAME=pc1.c DESC="my packet capture" PIDFILE=/var/run/$NAME.pid SCRIPTNAME=/etc/init.d/$NAME case "$1" in start) printf "%-50s" "Starting $NAME..." insmod /usr/local/pfring/kernel/pf_ring.ko /usr/local/bin/pc1.c & $! > PIDFILE ;; status) if [ -f $PIDFILE]; then if [ -d /proc/cat $PIDFILE ]; then echo "Process is running"; fi; else echo "Error! PID file is missing!"; fi ;; stop) printf "%-50s" "Stopping $NAME" PID=`cat $PIDFILE` cd $DAEMON_PATH if [ -f $PIDFILE ]; then kill -HUP $PID printf "%s\n" "Ok" rm -f $PIDFILE else printf "%s\n" "pidfile not found" fi ;; restart) $0 stop $0 start ;; *) echo "Usage: $0 {status|start|stop|restart}" exit 1 esac
If you would run the command that runs within your init.d script with '&' after the end of the command, it will become a background process, and the next services could start. If you want the script to run as the final step (it would still block if it does not background) of your boot process, you could run it through /etc/rc.local (or your distro equivalent if you don't have one...)
Similar method to /etc/init.d
1,416,824,305,000
Below is an init script which starts/stops a daemon. The daemon is unfortunately printing the parsed packet data (from /home/nuthan/program/server), a socket server written in perl, listening to a socket for tcp packets from a client. As soon as I start the service, the parsed data (print statements from /home/nuthan/program/server) is echoed on my TTY. And, if I try to kill the terminal, the daemon quits. How do I overcome this? daemon and logging packet data command daemon -18 perl /home/nuthan/program/server -d -v -r -f -O=/var/log/vts.log --daemon #!/bin/bash # # vts Start/Stop Vts. # # description: VTS daemon for vehicle Tracking. # Source function library . /etc/init.d/functions # Get network config . /etc/sysconfig/network RETVAL=0 start() { echo -n $"Starting vts: " # Start me up! daemon -18 perl /home/nuthan/program/server -d -v -r -f -O=/var/log/vts.log --daemon RETVAL=$? echo [ $RETVAL -eq 0 ] && touch /var/lock/subsys/vts touch /var/lock/subsys/vts return $RETVAL } stop() { echo -n $"Stopping vts: " killproc vts RETVAL=$? echo [ $RETVAL -eq 0 ] && rm -f /var/lock/subsys/vtsdaemon return $RETVAL } restart() { stop start } reload() { stop start } case "$1" in start) start ;; stop) stop ;; status) status vts ;; restart) restart ;; condrestart) [ -f /var/lock/subsys/vts ] && restart || : ;; reload) reload ;; *) echo $"Usage: $0 {start|stop|status|restart|condrestart|reload}" exit 1 esac exit 0
You are mixing three commands: deamon, perl and /home/nuthan/program/server without any quotes. Think about the following: How does each of them know, which of the parameters it should interpret? The syntax you used could probably only be correctly interpreted, if: deamon would treat everything after -18 to be the command to run perl would interpret only the first parameter (/home/nuthan/program/server) as the script to run, and all that follows as parameters passed to that script I can suggest two things to fix the issues: Make sure whether you need to call perl explicitly. If the server script contains a proper interpreter declaration (probably /usr/bin/perl) on its first line, and it has executable bit set, you should not need to explicitly call perl. Check the syntax of the daemon command. If it indicates that everything after -18 (in your command) should be treated as a full command to run, then it's ok. Otherwise, you might either need to everything that follows in quotes, or put create an additional function or a wrapper script that would run your entire command - so the entire command line you've written would be changed to daemon -18 your_function or daemon -18 /path/to/your/wrapper_script.sh.
Prevent init daemon echoing on TTY
1,416,824,305,000
I have a very simple SysVinit service in /etc/rc.d: #!/bin/bash PIDFILE="/var/run/test.pid" status() { if [ -f "$PIDFILE" ]; then echo 'Service running' return 1 fi return 0 } start() { if [ -f "$PIDFILE" ] && kill -0 "$(cat "$PIDFILE")"; then echo 'Service already running' return 1 fi echo 'Starting...' test & echo $! > "$PIDFILE" return 0 } stop() { if [ ! -f "$PIDFILE" ] || ! kill -0 "$(cat "$PIDFILE")"; then echo 'Service not running' return 1 fi echo 'Stopping...' kill -15 "$(cat "$PIDFILE")" && rm -f "$PIDFILE" return 0 } case "$1" in start) start ;; stop) stop ;; status) status ;; restart) stop start ;; *) echo "Usage: $0 {start|stop|restart}" exit 1 esac When the system starts it starts the service. But when the system stops, it never calls the stop command. The only reason I can think off is that the system either thinks the service is not running or was not started correctly. But what are the requirements for that? Do you need to return a special exitcode for the start command? Do I need to create a file in /var/lock/subsys to signal that it is active? Anything else that might cause the system to think the service did not start?
It looks like Synology moved from classic SysVinit to upstart in DSM 6 or so, and then to systemd in DSM 7. Both init systems provide backward compatibility for classic SysVinit-style start/stop scripts, but there are some quirks you should be aware of. If you have DSM 7.0 or newer, then after installing the script you probably should run systemctl daemon-reload, so systemd-sysv-generator should automatically create a .service file for it (maybe in /run/systemd). Then you can start your script with systemctl start <script name> - and in fact should do just that, instead of just running the script manually. systemd will be aware of the need to run <your script> stop job only if it has actually executed the corresponding start job. This is because systemd will set up each service as a separate control group of processes as it starts them up (and the administrator running the start script manually doesn't do that). This is something that is completely invisible to the services themselves (unless they specifically go looking for it), and any child processes of the services will inherit this control group membership. If a control group has no processes left in it, it will cease to exist automatically. When shutting down, systemd will just go through the existing control groups and will run the stop command for any non-default control group it finds. Any services that have been started without using systemctl start will be part of the "administrator's interactive session" control group rather than the "service X" control group, and will essentially be just killed without running the corresponding stop script. If you need features like an automatic restart for your service if it dies for some reason, you should consider using the appropriate "native" configuration method for the applicable init system: /etc/init/* files for Upstart in Synology DSM 6.x series /etc/systemd/system/*.service files for systemd in Synology DSM 7.x series and newer. These init systems have built-in automatic restart features you can use with just a little bit of configuration, rather than having to write a wrapper script to watch your service process yourself. Developer Guide for Synology DSM 7 Developer Guide for Synology DSM 6 Possibly helpful notes on configuring services for DSM 6 and 7
Stop not called for init rc.d service
1,416,824,305,000
I'm on Debian 10 Buster. I can't figure out what's wrong with this init.d script? Sometimes it doesn't run at server shutdown. My MySQL error_log fills up with "Status information" when the server reboots due to SIGHUP. Here is a link describing this behavior: MySQL Server response to SIGHUP signals This init.d script /etc/init.d/mysql I'm using was taken directly from the official MySQL release deb with a couple minor modifications by myself, which are documented in the file. And here is the sourced mysql-helpers file referenced by the init.d script. Stopping/starting/restarting MySQL at runtime never produces the SIGHUP, but sometimes the script chokes with no logging info. The .pid is gone, but MySQL silently fails to start. The frustrating part is it sometimes runs at shutdown and sometimes not. It is random; 75% it doesn't run, 25% it does run. Another part of this question could be, Does anyone know where to find a working init.d script for MySQL 5.7.37 on Debian 10?
why you dont try to use systemd to manage daemons, its easier and available since debian Jessie. /etc/systemd/system/servicemysql.service [Unit] Description=MySQL task DefaultDependencies=no Conflicts=reboot.target Before=poweroff.target halt.target shutdown.target Requires=poweroff.target [Service] Type=oneshot ExecStart=/path/to/your/script.sh ExecReload=/usr/bin/kill -HUP $MAINPID RemainAfterExit=yes [Install] WantedBy=shutdown.target Dont forget to give 0644 permissions to this file and after every modification run: systemctl daemon-reload then to enable the daemon run: systemctl enable <name of the service> and to start it run: systemctl start <name of the service> For checking if the service is running execute: systemctl status <name of the service>
Why does this init.d script sometimes not run at shutdown?
1,416,824,305,000
I am running a CentOS (Red Hat Enterprise Linux Server release 7.6 (Maipo)) instance on AWS. I need to add to my boot sequence execution of a rc.local script. How can I do that? I have looked in /ect/rc.d and tried to add the script to a default using systemctl. Nothing works. Can someone point me to a right direction?
There are at least three methods you can use as far as I see it. Using /etc/rc.d/rc.local: Make sure the file is executable or chmod u+x it. Add the commands / script to the end of the file. Using crontab: Run: crontab -e Then add a crontab line like so: @reboot /your/script/here a Userdata script: Since it's an AWS instance, you can create a shell script, upload it to s3 and configure the instance to download and run it at instance creation time. Here's an example of a userdata script I wrote.
Linux CentOS: run rc.local after boot
1,416,824,305,000
I need to run a script upon startup, which I understand needs to be done in the init.d folder. Now this script requires sudo permissions, it prompts the user for the sudo password when being run normally. Is it possible to have my startup script run with sudo permissions automatically granted? Do I need to give the user password-less sudo permission? Ideally I'd have it run without any user interaction.
Normally, the system runs startup scripts with full root access by default, so you don't have to do anything. Note that the script location depends on which init package is used in your system. For classic SysVinit, the start-up scripts are usually located in /etc/init.d and symbolic links indicating their place in the startup/shutdown order are created in /etc/rc<number>.d/ directories, where <number> indicates the runlevel your script is supposed to run on. (A runlevel is sort of "overall system state": on RedHat-style systems, the default runlevel is 5 if you have GUI login enabled, and 3 otherwise. On Debian-style systems, it tends to be 3 always.) Updating the symbolic links in /etc/rc<number>.d/ can be tedious, so there is often a tool that can do it for you. The most common such tool is chkconfig: it requires you to place some specially formatted comments at the beginning of your script (see man chkconfig for details appropriate to your distribution). Then you can just place your script into /etc/init.d and run sudo chkconfig --add <your script name>. If your system uses a newer replacement for SysVinit, like upstart or systemd, they may include a SysVinit compatibility system so the above instructions may still apply; but you should consider learning the new ways too, since SysVinit is considered aged and less than optimal for modern multi-core systems.
Automatic sudo permissions for startup script
1,416,824,305,000
My shell script knowledge is a little shaky, but I want to run a daemon (Ubuntu 14.04) defined in /etc/init.d/unicorn, like so case "$1" in start) check_config check_app_root log_daemon_msg "Starting $DESC" $NAME || true if start-stop-daemon --start --quiet --oknodo --pidfile $PID --exec $DAEMON -- $UNICORN_OPTS; then In a separate file, /etc/default/unicorn, I have the below variables defined: APP_ROOT=/home/rails/myproject ... UNICORN_OPTS="-D -c $CONFIG_RB -E $RAILS_ENV" ... DAEMON="cd $APP_ROOT; $GEM_HOME/bin/bundle exec $GEM_PATH/bin/unicorn" I added "cd $APP_ROOT" because that's the directory from where "$GEM_HOME/bin/bundle" must run. However, when I go to start my service, I get the below error: myuser@myproject:~$ sudo service unicorn restart /home/rails/.gem/bin/bundle * Restarting Unicorn web server unicorn start-stop-daemon: unable to stat //cd (No such file or directory) Is there some other way I can store my options so that I can run my command from the desired directory?
It looks like there are a few problem with what you are doing. --exec only takes one argument, however arguments can be passed at the end of start-stop-daemon following a --. The argument of --exec is also used as an identifier: start-stop-daemon checks to see if there is an instance running (this would make /bin/sh, a very bad candidate. Therefore create a shell-script, that is expected to have one instance running per machine. Pass the absolute path to --exec. Pass any arguments needed by the script at the end after a --.
When running a daemon, how do I execute a command from a given directory?
1,416,824,305,000
Suppose you have write access to a Linux system, with root rights, but no interactive shell. You can only write new files or overwrite existing files. Creation of (sub)directories is possible. It's possible to define file permissions. How would you create a ba(sh) script, to be run after or at system boot? edit: I do not have read permissions on the system either - only write permissions
That depends on what init setup the Linux system in question uses. All the more commonplace ones use text files (and lots of symbolic links) to determine what needs to be run at boot and in what order, whether that's a bash script for sysvinit or a systemd unit file or something for runit or upstart or whatnot. Figure out which init system is being used, then write an init file of the appropriate type with the instructions you want, and drop it into the appropriate directory. Without more information than you're providing in your hypothetical question it's hard to give a more specific answer.
Set script to be executed at/after boot, with only write permissions, but no shell access on the target
1,416,824,305,000
I am creating a mesh interface on my raspberry pi's, using the "standard" set of commands: iw dev wlan0 interface add mesh0 type mp ifdown wlan0 ifconfig mesh0 192.168.202.103 iw dev mesh0 mesh join mymesh I tried putting all of these commands in a .sh script in the /etc/init.d/ folder, but it gets me nowhere. Does it have anything to do with the /etc/network/interfaces file, which looks like this: auto wlan0 auto lo iface lo inet loopback iface eth0 inet static address 192.168.100.103 netmask 255.255.255.0 gateway 192.168.100.1 allow-hotplug wlan0 iface wlan0 inet static address 192.168.200.103 netmask 255.255.255.0 wireless-mode ad-hoc wireless-essid pi Is there any other way I can automate this process, so that every time system boots, the mesh0 interface is there, with the IP address, and the mesh network chosen? Alternatively, is there anything I am doing wrong with this setup (I suppose in the interfaces file), which is preventing the commands from init.d script to be executed? Thank you!
I've managed to do this by making a mesh.sh script containing: #!/bin/sh sleep 5 iw wlan0 interface add mesh0 type mp sleep 1 ifdown wlan0 sleep 1 ifconfig mesh0 ifconfig mesh0 192.168.202.106 iw mesh0 mesh join meshpi Then creating a file called meshboot in /etc/init.d/ containing: #!/bin/sh ### BEGIN INIT INFO # Provides: meshboot # Required-Start: $remote_fs $syslog # Required-Stop: $remote_fs $syslog # Default-Start: 2 3 4 5 # Default-Stop: 0 1 6 # Short-Description: Start daemon at boot time # Description: Enable service provided by daemon. ### END INIT INFO case "$1" in start) sudo /home/pi/mesh.sh ;; stop) ;; esac exit 0 And making it run on boot with update-rc.d meshboot defaults.
Automatic mesh interface
1,416,824,305,000
I need to have a PHP file execute whenever the httpd service starts or restarts. I found that Systemd has a configuration setting called **ExecStartPost, which looks perfect for what I need to do. I updated the /etc/systemd/system/multi-user.target.wants/httpd.service file to reflect the following: [Unit] Description=The Apache HTTP Server After=network.target remote-fs.target nss-lookup.target Documentation=man:httpd(8) Documentation=man:apachectl(8) [Service] Type=notify EnvironmentFile=/etc/sysconfig/httpd ExecStart=/usr/sbin/httpd $OPTIONS -DFOREGROUND ExecStartPost=/bin/php /usr/sbin/php_test ExecReload=/usr/sbin/httpd $OPTIONS -k graceful ExecStop=/bin/kill -WINCH ${MAINPID} # We want systemd to give httpd some time to finish gracefully, but still want # it to kill httpd after TimeoutStopSec if something went wrong during the # graceful stop. Normally, Systemd sends SIGTERM signal right after the # ExecStop, which would kill httpd. We are sending useless SIGCONT here to give # httpd time to finish. KillSignal=SIGCONT PrivateTmp=true [Install] WantedBy=multi-user.target The content of /usr/sbin/php_test is: #!/bin/php <?php echo "Writing to /tmp/php-test.txt...\n"; $myfile = fopen("/tmp/php-test.txt", "w") or die("Unable to open file!"); $txt = "TEST! " . date("F j, Y, g:i a") . PHP_EOL; fwrite($myfile, $txt); fclose($myfile); echo "Done!!\n"; ?> Then I chmod 777 the php file and reloaded the daemon files via systemctl daemon-reload. But when I restart httpd, it doesn't create the /tmp/php-test.txt file that I was expecting to see. If I execute /bin/php /usr/sbin/php_test via the command line, it works perfectly fine. I found a separate StackOverflow thread stating that Systemd reads the .service files from bottom to top, so I moved the ExecStartPost line to right above the ExecStart line, reloaded the daemon files and restarted apache again, with no success... What am I doing wrong here? Thanks! Update 1 I changed the httpd.service file to the following: [Unit] Description=The Apache HTTP Server After=network.target remote-fs.target nss-lookup.target Documentation=man:httpd(8) Documentation=man:apachectl(8) [Service] Type=notify EnvironmentFile=/etc/sysconfig/httpd ExecStart=/usr/sbin/httpd $OPTIONS -DFOREGROUND ExecStartPost=/bin/bash -c "/bin/php -f /tmp/php_test" ExecReload=/usr/sbin/httpd $OPTIONS -k graceful ExecStop=/bin/kill -WINCH ${MAINPID} # We want systemd to give httpd some time to finish gracefully, but still want # it to kill httpd after TimeoutStopSec if something went wrong during the # graceful stop. Normally, Systemd sends SIGTERM signal right after the # ExecStop, which would kill httpd. We are sending useless SIGCONT here to give # httpd time to finish. KillSignal=SIGCONT PrivateTmp=true [Install] WantedBy=multi-user.target And now I get an error (at least that's something to go on!). When I review the logs via journalctl -xe, I see the following: Apr 19 12:47:46 silo-stg-a01.cymedica.com systemd[1]: Starting The Apache HTTP Server... -- Subject: Unit httpd.service has begun start-up -- Defined-By: systemd -- Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel -- -- Unit httpd.service has begun starting up. Apr 19 12:47:46 silo-stg-a01.cymedica.com bash[13268]: Could not open input file: /tmp/php_test Apr 19 12:47:46 silo-stg-a01.cymedica.com systemd[1]: httpd.service: control process exited, code=exited status=1 Apr 19 12:47:47 silo-stg-a01.cymedica.com systemd[1]: Failed to start The Apache HTTP Server. -- Subject: Unit httpd.service has failed -- Defined-By: systemd -- Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel -- -- Unit httpd.service has failed. -- -- The result is failed. Apr 19 12:47:47 silo-stg-a01.cymedica.com systemd[1]: Unit httpd.service entered failed state. Apr 19 12:47:47 silo-stg-a01.cymedica.com systemd[1]: httpd.service failed. The error is Could not open input file: /tmp/php_test.. Not sure what that means yet though. And I'm aware that prefixing the command with a hyphen would let the process move on even if the PHP file fails to execute, but that's not what I'm trying to fix. I need the PHP script to execute properly. FYI, if you're wondering why I have it execute /bin/bash -c "/bin/php -f /tmp/php_test" and not just /bin/php -f /tmp/php_test I was just playing around with trying to have it execute the php script from a bash command. But if I change it to just /bin/php -f /tmp/php_test, I get the exact same error in journalctl Update 2 I notice that if I replace the ExecStartPost line with the PHP command with just: ExecStartPost=/bin/logger "ExecStartPost 1" (which goes just after the ExecStart line), it logs ExecStartPost 1 to the logs just fine... So I think its related to how the php file itself is executed
You have in your unit file: PrivateTmp=true This means systemd will create a separate namespace for the unit's /tmp and /var/tmp directories. Remove the line to use the usual /tmp.
Configuring Systemd to execute extra script after httpd start/restart using ExecStartPost setting not working
1,416,824,305,000
I know, when we run application in shell for a large website, we'd better set ulimit for our shell, But most of the service is started by systemd/sysv. Do I need set the ulimit in the service script (/etc/init.d) ?
You would normally set the ulimit on the user the service runs as in something like /etc/security/limits.conf. For example, if the web service is running as www-data, you would add an entry for www-data to /etc/security/limits.conf setting the relevant limits. If the process runs as root then it's more complicated given the limits in /etc/security/limits.conf would then apply to all root owned processes. One issue with setting the limits in /etc/security/limits.conf is that it relies on processes going through the PAM stack. In the case of services and daemons which don't do that, then yes, modifying the relevant service scripts is an acceptable approach. It's probably necessary to do this on a per process basis, and depending on your distribution, service start scripts are usually package managed meaning you'll get conflicts every time you upgrade.
Do I need set ulimit for system services, such as nginx.service(systemd)/nginx(sysv)?
1,416,824,305,000
I am wondering why during service start up environment variables are not visible. To be more precise: I created service startup scrip according to LSB spec which starts some java process. For this purpose JAVA_HOME env variable is checked first. This env variable is set in /etc/profile.d/java.sh. That is probably not executed while starting the service. I would like uderstand the process and what is the correct solution in such case?
RC scripts are invoked as non-interactive shell scripts. Thus they do not read /etc/profile. Thus you have to explicitly define your variables in your script. Either directly in your script or use some (covering up) techniques lot of RC script use (main variables defined in /etc/sysconfig/$package). See how tomcat6 is doing that (although it is quite overcomplicated according to my opinion).
Why env variable are not visible while starting a service
1,416,824,305,000
I am building minimal operating system using busybox.I am writing init file, I want to call script1.sh file from init file. Challenges I am facing are: After running init file it is showing ./script1.sh : not found In script1.sh it has wine command which calls .exe, I am not wine is supported by busybox. So how Can I run .exe through busybox Please help me to solve above challenges.
Same as previously, specify the full path to your script. If that still doesn’t work, edit your question to include the script’s contents (at least its first line). Busybox doesn’t include Wine; if you need Wine, you’ll have to make it available separately. I take it you’re trying to run a .Net WPF program; there’s no way of doing that only using Busybox.
How to execute wine command through busbox?
1,416,824,305,000
Using Ubuntu 16.04.6 LTS, it is not possible to call the service command to modify the status of any /etc/init/ services. The command starts but is stuck in execution. The services themselves are running still running and stopping though, based on their own configuration (start on, etc.) Scripts that are in /etc/init.d can be interacted with. There's nothing in /var/log/syslog, and nothing special in service-specific logs (/var/log/upstart/<service>.log). initctl -v reload-configuration command is also stuck and prints nothing. I checked the syntax of the init scripts that I know I added using init-checkconf, and it outputs the following : DEBUG: upstart_path=/sbin/upstart DEBUG: initctl_path=/sbin/initctl DEBUG: Setting XDG_RUNTIME_DIR='/tmp/init-checkconf.fbn15XHMSG' DEBUG: confdir=/tmp/init-checkconf.1ZAjdLCNnz DEBUG: file=/etc/init/tiler.conf DEBUG: job=tiler DEBUG: upstart_out=/tmp/init-checkconf-upstart-output.KbilFI2A3x DEBUG: upstart_cmd=/sbin/upstart --user --no-dbus --no-startup-event --verbose --confdir /tmp/init-checkconf.1ZAjdLCNnz DEBUG: Upstart pid=32001 DEBUG: Joining Upstart session 'unix:abstract=/com/ubuntu/upstart-session/0/32001' DEBUG: Waiting for Upstart to initialise (attempt 1) DEBUG: Secondary Upstart (/sbin/upstart --user --no-dbus --no-startup-event --verbose --confdir /tmp/init-checkconf.1ZAjdLCNnz) running with PID 32001 File /etc/init/tiler.conf: syntax ok DEBUG: Stopping secondary Upstart (running with PID 32001) And with the nginx script, which is the default one : DEBUG: upstart_path=/sbin/upstart DEBUG: initctl_path=/sbin/initctl DEBUG: Setting XDG_RUNTIME_DIR='/tmp/init-checkconf.bk34MF5r1W' DEBUG: confdir=/tmp/init-checkconf.1aWnCVHKEp DEBUG: file=/etc/init/nginx.conf DEBUG: job=nginx DEBUG: upstart_out=/tmp/init-checkconf-upstart-output.n7w9BHFOsL DEBUG: upstart_cmd=/sbin/upstart --user --no-dbus --no-startup-event --verbose --confdir /tmp/init-checkconf.1aWnCVHKEp DEBUG: Upstart pid=32107 DEBUG: Joining Upstart session 'unix:abstract=/com/ubuntu/upstart-session/0/32107' DEBUG: Waiting for Upstart to initialise (attempt 1) DEBUG: Secondary Upstart (/sbin/upstart --user --no-dbus --no-startup-event --verbose --confdir /tmp/init-checkconf.1aWnCVHKEp) running with PID 32107 File /etc/init/nginx.conf: syntax ok DEBUG: Stopping secondary Upstart (running with PID 32107) What could be the cause of this problem, and how to fix it ? Thanks for your time P.S. Here is the strace log when running service tiler restart execve("/usr/sbin/service", ["service", "tiler", "restart"], [/* 19 vars */]) = 0 brk(NULL) = 0x55b3bcb00000 access("/etc/ld.so.nohwcap", F_OK) = -1 ENOENT (No such file or directory) access("/etc/ld.so.preload", R_OK) = -1 ENOENT (No such file or directory) open("/etc/ld.so.cache", O_RDONLY|O_CLOEXEC) = 3 fstat(3, {st_mode=S_IFREG|0644, st_size=61892, ...}) = 0 mmap(NULL, 61892, PROT_READ, MAP_PRIVATE, 3, 0) = 0x7fee7dfe1000 close(3) = 0 access("/etc/ld.so.nohwcap", F_OK) = -1 ENOENT (No such file or directory) open("/lib/x86_64-linux-gnu/libc.so.6", O_RDONLY|O_CLOEXEC) = 3 read(3, "\177ELF\2\1\1\3\0\0\0\0\0\0\0\0\3\0>\0\1\0\0\0`\t\2\0\0\0\0\0"..., 832) = 832 fstat(3, {st_mode=S_IFREG|0755, st_size=1868984, ...}) = 0 mmap(NULL, 4096, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0x7fee7dfe0000 mmap(NULL, 3971488, PROT_READ|PROT_EXEC, MAP_PRIVATE|MAP_DENYWRITE, 3, 0) = 0x7fee7da02000 mprotect(0x7fee7dbc2000, 2097152, PROT_NONE) = 0 mmap(0x7fee7ddc2000, 24576, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_FIXED|MAP_DENYWRITE, 3, 0x1c0000) = 0x7fee7ddc2000 mmap(0x7fee7ddc8000, 14752, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_FIXED|MAP_ANONYMOUS, -1, 0) = 0x7fee7ddc8000 close(3) = 0 mmap(NULL, 4096, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0x7fee7dfdf000 mmap(NULL, 4096, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0x7fee7dfde000 arch_prctl(ARCH_SET_FS, 0x7fee7dfdf700) = 0 mprotect(0x7fee7ddc2000, 16384, PROT_READ) = 0 mprotect(0x55b3bc08e000, 8192, PROT_READ) = 0 mprotect(0x7fee7dff1000, 4096, PROT_READ) = 0 munmap(0x7fee7dfe1000, 61892) = 0 getuid() = 0 getgid() = 0 getpid() = 5537 rt_sigaction(SIGCHLD, {0x55b3bbe82540, ~[RTMIN RT_1], SA_RESTORER, 0x7fee7da374c0}, NULL, 8) = 0 geteuid() = 0 brk(NULL) = 0x55b3bcb00000 brk(0x55b3bcb21000) = 0x55b3bcb21000 getppid() = 5535 stat("/home/ubuntu", {st_mode=S_IFDIR|0755, st_size=4096, ...}) = 0 stat(".", {st_mode=S_IFDIR|0755, st_size=4096, ...}) = 0 open("/usr/sbin/service", O_RDONLY) = 3 fcntl(3, F_DUPFD, 10) = 10 close(3) = 0 fcntl(10, F_SETFD, FD_CLOEXEC) = 0 geteuid() = 0 getegid() = 0 rt_sigaction(SIGINT, NULL, {SIG_DFL, [], 0}, 8) = 0 rt_sigaction(SIGINT, {0x55b3bbe82540, ~[RTMIN RT_1], SA_RESTORER, 0x7fee7da374c0}, NULL, 8) = 0 rt_sigaction(SIGQUIT, NULL, {SIG_DFL, [], 0}, 8) = 0 rt_sigaction(SIGQUIT, {SIG_DFL, ~[RTMIN RT_1], SA_RESTORER, 0x7fee7da374c0}, NULL, 8) = 0 rt_sigaction(SIGTERM, NULL, {SIG_DFL, [], 0}, 8) = 0 rt_sigaction(SIGTERM, {SIG_DFL, ~[RTMIN RT_1], SA_RESTORER, 0x7fee7da374c0}, NULL, 8) = 0 read(10, "#!/bin/sh\n\n#####################"..., 8192) = 8192 pipe([3, 4]) = 0 clone(child_stack=0, flags=CLONE_CHILD_CLEARTID|CLONE_CHILD_SETTID|SIGCHLD, child_tidptr=0x7fee7dfdf9d0) = 5538 close(4) = 0 read(3, "service\n", 128) = 8 read(3, "", 128) = 0 close(3) = 0 wait4(-1, [{WIFEXITED(s) && WEXITSTATUS(s) == 0}], 0, NULL) = 5538 --- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_EXITED, si_pid=5538, si_uid=0, si_status=0, si_utime=0, si_stime=0} --- rt_sigreturn({mask=[]}) = 5538 pipe([3, 4]) = 0 clone(child_stack=0, flags=CLONE_CHILD_CLEARTID|CLONE_CHILD_SETTID|SIGCHLD, child_tidptr=0x7fee7dfdf9d0) = 5539 close(4) = 0 read(3, "service\n", 128) = 8 read(3, "", 128) = 0 close(3) = 0 wait4(-1, [{WIFEXITED(s) && WEXITSTATUS(s) == 0}], 0, NULL) = 5539 --- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_EXITED, si_pid=5539, si_uid=0, si_status=0, si_utime=0, si_stime=0} --- rt_sigreturn({mask=[]}) = 5539 stat("/run/systemd/system", 0x7ffdc59d9e90) = -1 ENOENT (No such file or directory) chdir("/") = 0 faccessat(AT_FDCWD, "/etc/init/tiler.conf", R_OK) = 0 open("/dev/null", O_WRONLY|O_CREAT|O_TRUNC, 0666) = 3 fcntl(1, F_DUPFD, 10) = 11 close(1) = 0 fcntl(11, F_SETFD, FD_CLOEXEC) = 0 dup2(3, 1) = 1 close(3) = 0 stat("/usr/local/sbin/which", 0x7ffdc59d9fa0) = -1 ENOENT (No such file or directory) stat("/usr/local/bin/which", 0x7ffdc59d9fa0) = -1 ENOENT (No such file or directory) stat("/usr/sbin/which", 0x7ffdc59d9fa0) = -1 ENOENT (No such file or directory) stat("/usr/bin/which", {st_mode=S_IFREG|0755, st_size=946, ...}) = 0 clone(child_stack=0, flags=CLONE_CHILD_CLEARTID|CLONE_CHILD_SETTID|SIGCHLD, child_tidptr=0x7fee7dfdf9d0) = 5540 wait4(-1, [{WIFEXITED(s) && WEXITSTATUS(s) == 0}], 0, NULL) = 5540 --- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_EXITED, si_pid=5540, si_uid=0, si_status=0, si_utime=0, si_stime=0} --- rt_sigreturn({mask=[]}) = 5540 dup2(11, 1) = 1 close(11) = 0 stat("/usr/local/sbin/initctl", 0x7ffdc59da030) = -1 ENOENT (No such file or directory) stat("/usr/local/bin/initctl", 0x7ffdc59da030) = -1 ENOENT (No such file or directory) stat("/usr/sbin/initctl", 0x7ffdc59da030) = -1 ENOENT (No such file or directory) stat("/usr/bin/initctl", 0x7ffdc59da030) = -1 ENOENT (No such file or directory) stat("/sbin/initctl", {st_mode=S_IFREG|0755, st_size=214216, ...}) = 0 pipe([3, 4]) = 0 clone(child_stack=0, flags=CLONE_CHILD_CLEARTID|CLONE_CHILD_SETTID|SIGCHLD, child_tidptr=0x7fee7dfdf9d0) = 5541 close(4) = 0 stat("/usr/local/sbin/grep", 0x7ffdc59da030) = -1 ENOENT (No such file or directory) stat("/usr/local/bin/grep", 0x7ffdc59da030) = -1 ENOENT (No such file or directory) stat("/usr/sbin/grep", 0x7ffdc59da030) = -1 ENOENT (No such file or directory) stat("/usr/bin/grep", 0x7ffdc59da030) = -1 ENOENT (No such file or directory) stat("/sbin/grep", 0x7ffdc59da030) = -1 ENOENT (No such file or directory) stat("/bin/grep", {st_mode=S_IFREG|0755, st_size=211224, ...}) = 0 clone(child_stack=0, flags=CLONE_CHILD_CLEARTID|CLONE_CHILD_SETTID|SIGCHLD, child_tidptr=0x7fee7dfdf9d0) = 5542 close(3) = 0 close(-1) = -1 EBADF (Bad file descriptor) wait4(-1, 0x7ffdc59d9f5c, 0, NULL) = ? ERESTARTSYS (To be restarted if SA_RESTART is set) --- SIGINT {si_signo=SIGINT, si_code=SI_KERNEL} --- rt_sigreturn({mask=[]}) = -1 EINTR (Interrupted system call) wait4(-1, [{WIFSIGNALED(s) && WTERMSIG(s) == SIGINT}], 0, NULL) = 5542 --- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_KILLED, si_pid=5542, si_uid=0, si_status=SIGINT, si_utime=0, si_stime=0} --- rt_sigreturn({mask=[]}) = 5542 wait4(-1, [{WIFSIGNALED(s) && WTERMSIG(s) == SIGINT}], 0, NULL) = 5541 --- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_KILLED, si_pid=5541, si_uid=0, si_status=SIGINT, si_utime=0, si_stime=0} --- rt_sigreturn({mask=[]}) = 5541 rt_sigprocmask(SIG_SETMASK, [], [], 8) = 0 rt_sigaction(SIGINT, {SIG_DFL, [INT], SA_RESTORER|SA_RESTART, 0x7fee7da374c0}, {0x55b3bbe82540, ~[KILL STOP RTMIN RT_1], SA_RESTORER, 0x7fee7da374c0}, 8) = 0 tgkill(5537, 5537, SIGINT) = 0 --- SIGINT {si_signo=SIGINT, si_code=SI_TKILL, si_pid=5537, si_uid=0} --- +++ killed by SIGINT +++ It is stuck on wait. Also, there's nothing in journalctl
It turns out it was the instance not having enough RAM and stopping processes forcefully
Ubuntu "service" command stuck, can't reload services
1,295,035,247,000
It appears systemd is the hot new init system on the block, same as Upstart was a few years ago. What are the pros/cons for each? Also, how does each compare to other init systems?
2016 Update Most answers here are five years old so it's time for some updates. Ubuntu used to use upstart by default but they abandoned it last year in favor of systemd - see: Grab your pitchforks: Ubuntu to switch to systemd on Monday (The Register) Because of that there is a nice article Systemd for Upstart Users on Ubuntu wiki - very detailed comparison between upstart and systemd and a transition guide from upstart to systemd. (Note that according to the Ubuntu wiki you can still run upstart on current versions of Ubuntu by default by installing the upstart-sysv and running sudo update-initramfs -u but considering the scope of the systemd project I don't know how it works in practice, or whether or not systemd is possible to uninstall.) Most of the info in the Commands and Scripts sections below is adapted from some of the examples used in that article (that is conveniently licensed just like Stack Exchange user contributions under the Creative Commons Attribution-ShareAlike 3.0 License). Here is a quick comparison of common commands and simple scripts, see sections below for detailed explanation. This answer is comparing the old behavior of Upstart-based systems with the new behavior of systemd-based systems, as asked in the question, but note that the commands tagged as "Upstart" are not necessarily Upstart-specific - they are often commands that are common to every non-systemd Linux and Unix system. Commands Running su: upstart: su systemd: machinectl shell (see "su command replacement" section below) Running screen: upstart: screen systemd: systemd-run --user --scope screen (see "Unexpected killing of background processes" section below) Running tmux: upstart: tmux systemd: systemd-run --user --scope tmux (see "Unexpected killing of background processes" section below) Starting job foo: upstart: start foo systemd: systemctl start foo Stopping job foo: upstart: stop foo systemd: systemctl stop foo Restarting job foo: upstart: restart foo systemd: systemctl restart foo Listing jobs: upstart: initctl list systemd: systemctl status Checking configuration of job foo: upstart: init-checkconf /etc/init/foo.conf systemd: systemd-analyze verify /lib/systemd/system/foo.service Listing job's environement variables: upstart: initctl list-env systemd: systemctl show-environment Setting job's environment variable: upstart: initctl set-env foo=bar systemd: systemctl set-environment foo=bar Removing job's environment variable: upstart: initctl unset-env foo systemd: systemctl unset-environment foo Logs In upstart, the logs are normal text files in the /var/log/upstart directory, so you can process them as usual: cat /var/log/upstart/foo.log tail -f /var/log/upstart/foo.log In systemd logs are stored in an internal binary format (not as text files) so you need to use journalctl command to access them: sudo journalctl -u foo sudo journalctl -u foo -f Scripts Example upstart script written in /etc/init/foo.conf: description "Job that runs the foo daemon" start on runlevel [2345] stop on runlevel [016] env statedir=/var/cache/foo pre-start exec mkdir -p $statedir exec /usr/bin/foo-daemon --arg1 "hello world" --statedir $statedir Example systemd script written in /lib/systemd/system/foo.service: [Unit] Description=Job that runs the foo daemon Documentation=man:foo(1) [Service] Type=forking Environment=statedir=/var/cache/foo ExecStartPre=/usr/bin/mkdir -p ${statedir} ExecStart=/usr/bin/foo-daemon --arg1 "hello world" --statedir ${statedir} [Install] WantedBy=multi-user.target su command replacement A su command replacement was merged into systemd in pull request #1022: Add new "machinectl shell" command for su(1)-like behaviour because, according to Lennart Poettering, "su is really a broken concept". He explains that "you can use su and sudo as before, but don't expect that it will work in full". The official way to achieve a su-like behavior is now: machinectl shell It has been further explained by Lennart Poettering in the discussion to issue #825: "Well, there have been long discussions about this, but the problem is that what su is supposed to do is very unclear. [...] Long story short: su is really a broken concept. It will given you kind of a shell, and it’s fine to use it for that, but it’s not a full login, and shouldn’t be mistaken for one." - Lennart Poettering See also: Lennart Poettering merged “su” command replacement into systemd: Test Drive on Fedora Rawhide Systemd Absorbs "su" Command Functionality Systemd Absorbs “su” (Hacker News) Unexpected killing of background processes Commands like: screen tmux nohup no longer work as expected. For example, nohup is a POSIX command to make sure that the process keeps running after you log out from your session. It no longer works on systemd. Also programs like screen and tmux need to be invoked in a special way or otherwise the processes that you run with them will get killed (while not getting those processes killed is usually the main reason of running screen or tmux in the first place). This is not a mistake, it is a deliberate decision, so it is not likely to get fixed in the future. This is what Lennart Poettering has said about this issue: In my view it was actually quite strange of UNIX that it by default let arbitrary user code stay around unrestricted after logout. It has been discussed for ages now among many OS people, that this should possible but certainly not be the default, but nobody dared so far to flip the switch to turn it from a default to an option. Not cleaning up user sessions after logout is not only ugly and somewhat hackish but also a security problem. systemd 230 now finally flipped the switch and finally by default cleans everything up correctly when the user logs out. For more info see: Systemd Starts Killing Your Background Processes By Default Systemd v230 kills background processes after user logs out, breaks screen, tmux Debian Bug #825394: systemd kill background processes after user logs out High-level startup concept In a way systemd works backwards - in upstart jobs start as soon as they can and in systemd jobs start when they have to. At the end of the day the same jobs can be started by both systems and in pretty much the same order, but you think about it looking from an opposite direction so to speak. Here is how Systemd for Upstart Users explains it: Upstart's model for starting processes (jobs) is "greedy event-based", i. e. all available jobs whose startup events happen are started as early as possible. During boot, upstart synthesizes some initial events like startup or rcS as the "tree root", the early services start on those, and later services start when the former are running. A new job merely needs to install its configuration file into /etc/init/ to become active. systemd's model for starting processes (units) is "lazy dependency-based", i. e. a unit will only start if and when some other starting unit depends on it. During boot, systemd starts a "root unit" (default.target, can be overridden in grub), which then transitively expands and starts its dependencies. A new unit needs to add itself as a dependency of a unit of the boot sequence (commonly multi-user.target) in order to become active. Usage in distributions Now some recent data according to Wikipedia: Distributions using upstart by default: Ubuntu (from 9.10 to 14.10) Chrome OS Chromium OS Distributions using systemd by default: Arch Linux - since October 2012 CentOS - since April 2014 (7.14.04) CoreOS - sice October 2013 (v94.0.0) Debian - since April 2015 (v8) Fedora - since May 2011 (v15) Mageia - since May 2012 (v2.0) openSUSE - since September 2012 (v12.2) Red Hat Enterprise Linux - since June 2014 (v7.0) SUSE Linux Enterprise Server - since October 2014 (v12) Ubuntu - since April 2015 (v15.04) (See Wikipedia for up to date info) Distributions using neither Upstart nor systemd: Devuan (Debian fork created that resulted from the systemd controversies in the Debian community that led to a resignation of Ian Jackson) - specifically promotes Init Freedom with the following init systems considered for inclusion: sinit, OpenRC, runit, s6 and shepherd. Void Linux - uses runit as the init system and service supervisor Gentoo - uses OpenRC OS X - uses launchd FreeBSD uses a a traditional BSD-style init (not SysV init) NetBSD uses rc.d DragonFly uses traditional init OpenBSD uses the rc system startup script described here Alpine Linux (relatively new and little known distribution, with strong emphasis on security is getting more popular - e.g. Docker is moving its official images from Ubuntu to Alpine) uses the OpenRC init system Controversy In the past A fork of Debian has been proposed to avoid systemd. The Devuan GNU+Linux was created - a fork of Debian without systemd (thanks to fpmurphy1 for pointing it out in the comments). For more info about this controversy, see: The official Debian position on systemd The systemd controversy Debian Exodus declaration in 2014: As many of you might know already, the Init GR Debian vote promoted by Ian Jackson wasn't useful to protect Debian's legacy and its users from the systemd avalanche. This situation prospects a lock in systemd dependencies which is de-facto threatening freedom of development and has serious consequences for Debian, its upstream and its downstream. The CTTE managed to swap a dependency and gain us time over a subtle install of systemd over sysvinit, but even this process was exhausting and full of drama. Ultimately, a week ago, Ian Jackson resigned. [...] Ian Jackson's resignation: I am resigning from the Technical Committee with immediate effect. While it is important that the views of the 30-40% of the project who agree with me should continue to be represented on the TC, I myself am clearly too controversial a figure at this point to do so. I should step aside to try to reduce the extent to which conversations about the project's governance are personalised. [...] The Init Freedom: Devuan was born out of a controversy over the decision to use as the default init system for Debian. The official Debian position on systemd is full of claims that others have debunked. Interested readers can continue discussing this hot topic in The systemd controversy. However we encourage you to keep your head cool and your voice civil. At Devuan we’re more interested in programming them wrong than looking back. [...] Some websites and articles dedicated to the systemd controversy has been created: Without-Systemd.org Systemd-Free.org The Init Freedom Systemd on Suckless There is a lot of interesting discussion on Hacker News: https://news.ycombinator.com/item?id=7728692 https://news.ycombinator.com/item?id=13387845 https://news.ycombinator.com/item?id=11797075 https://news.ycombinator.com/item?id=12600413 https://news.ycombinator.com/item?id=11845051 https://news.ycombinator.com/item?id=11782364 https://news.ycombinator.com/item?id=12877378 https://news.ycombinator.com/item?id=10483780 https://news.ycombinator.com/item?id=13469935 Similar tendencies in other distros can be observed as well: The Church of Suckless NixOS is looking for followers Philosophy upstart follows the Unix philosophy of DOTADIW - "Do One Thing and Do It Well." It is a replacement for the traditional init daemon. It doesn't do anything other than starting and stopping services. Other tasks are delegated to other specialized subsystems. systemd does much more than that. In addition to starting and stopping services it also manages passwords, logins, terminals, power management, factory resets, log processing, file system mount points, networking and much more - see the NEWS file for some of the features. Plans of expansion According to A Perspective for systemd What Has Been Achieved, and What Lies Ahead presentation by Lennart Poettering in 2014 at GNOME.asia, here are the main objectives of systemd, areas that were already covered and those that were still in progress: systemd objectives: Our objectives Turning Linux from a bag of bits into a competitive General Purpose Operating System. Building the Internet’s Next Generation OS Unifying pointless differences between distributions Bringing innovation back to the core OS Desktop, Server, Container, Embedded, Mobile, Cloud, Cluster, . . . These areas are closer together than you might think Reducing administrator complexity, reliability without supervision Everything introspectable Auto discovery, plug and play is key We fix things where they are broken, never tape over them Areas already covered: What we already cover: init system, journal logging, login management, device management, temporary and volatile file management, binary format registration, backlight save/restore, rfkill save/restore, bootchart, readahead, encrypted storage setup, EFI/GPT partition discovery, virtual machine/container registration, minimal container management, hostname management, locale management, time management, random seed management, sysctl variable management, console managment, . . . Work in progress: What we are working on: network management systemd-networkd Local DNS cache, mDNS responder, LLMNR responder, DNSSEC verification IPC in the kernel kdbus, sd-bus Time synchronisation with NTP systemd-timesyncd More integration with containers Sandboxing of Services Sandboxing of Apps OS Image format Container image format App image format GPT with auto-discovery Stateless systems, instantiatable systems, factory reset /usr is the OS /etc is (optional) configuration /var is (optional) state Atomic node initialisation and updates Integration with the cloud Service management across nodes Verifiable OS images All the way to the firmware Boot Loading Scope of this answer As fpmurphy1 noted in the comments, "It should be pointed out that systemd has expanded its scope of work over the years far beyond simply that of system startup." I tried to include most of the relevant info here. Here I am comparing the common features of Upstart and systemd when used as init systems as asked in the question and I only mention features of systemd that go beyond the scope of an init system because those cannot be compared to Startup, but their presence is important to understand the difference between those two projects. The relevant documentation should be checked for more info. More info More info can be found at: upstart website systemd website Upstart on Wikipedia Systemd on Wikipedia The architecture of systemd on Wikipedia Linus Torvalds and others on Linux's systemd (ZDNet) About the systemd controversy by Robert Graham Init Freedom Campaign Rationale for switching from upstart to systemd? Extras The LinOxide Team has created a Systemd vs SysV Init Linux Cheatsheet.
What are the pros/cons of Upstart and systemd?
1,295,035,247,000
I just switched to debian jessie, and most things run okay, including my graphical display manager wdm. The thing is, I just don't understand how this works. Obviously my /etc/init.d/wdm script is called, because when I put an early exit in there, wdm is not started. But when I alternatively rename the /etc/rc3.d directory (my default runlevel used to be 3), then wdm is still started. I could not find out how systemd finds this script and I do not understand what it does to all the other init.d scripts. When and how does systemd run init.d scrips? In the long run, should I get rid of all init.d scripts?
chaos' answer is what some documentation says. But it's not what systemd actually does. (It's not what van Smoorenburg rc did, either. The van Smoorenburg rc most definitely did not ignore LSB headers, which insserv used to calculate static orderings, for starters.) The Freedesktop documentation, such as that "Incompatibilities" page, is in fact wrong, on these and other points. (The HOME environment variable in fact is often set, for example. This went wholly undocumented anywhere for a long time. It's now documented in the manual, at least, but that Freedesktop WWW page still hasn't been corrected.) The native service format for systemd is the service unit. systemd's service management proper operates solely in terms of those, which it reads from one of nine directories where (system-wide) .service files can live. /etc/systemd/system, /run/systemd/system, /usr/local/lib/systemd/system, and /usr/lib/systemd/system are four of those directories. The compatibility with van Smoorenburg rc scripts is achieved with a conversion program, named systemd-sysv-generator. This program is listed in the /usr/lib/systemd/system-generators/ directory and is thus run automatically by systemd early in the bootstrap process at every boot, and again every time that systemd is instructed to re-load its configuration later on. This program is a generator, a type of ancillary utility whose job is to create service unit files on the fly, in a tmpfs where three more of those nine directories (which are intended to be used only by generators) are located. systemd-sysv-generator generates the service units that run the van Smoorenburg rc scripts from /etc/init.d, if it doesn't find a native systemd service unit by that name already existing in the other six locations. systemd service management only knows about service units. These automatically (re-)generated service units are written to invoke the van Smoorenburg rc scripts. They have, amongst other things: [Unit] SourcePath=/etc/init.d/wibble [Service] ExecStart=/etc/init.d/wibble start ExecStop=/etc/init.d/wibble stop Received wisdom is that the van Smoorenburg rc scripts must have an LSB header, and are run in parallel without honouring the priorities imposed by the /etc/rc?.d/ system. This is incorrect on all points. In fact, they don't need to have an LSB header, and if they do not systemd-sysv-generator can recognize the more limited old RedHat comment headers (description:, pidfile:, and so forth). Moreover, in the absence of an LSB header it will fall back to the contents of the /etc/rc?.d symbolic link farms, reading the priorities encoded into the link names and constructing a before/after ordering from them, serializing the services. Not only are LSB headers not a requirement, and not only do they themselves encode before/after orderings that serialize things to an extent, the fallback behaviour in their complete absence is actually significantly non-parallelized operation. The reason that /etc/rc3.d didn't appear to matter is that you probably had that script enabled via another /etc/rc?.d/ directory. systemd-sysv-generator translates being listed in any of /etc/rc2.d/, /etc/rc3.d/, and /etc/rc4.d/ into a native Wanted-By relationship to systemd's multi-user.target. Run levels are "obsolete" in the systemd world, and you can forget about them. Further reading systemd-sysv-generator. systemd manual pages. Freedesktop.org. "Environment variables in spawned processes". systemd.exec. systemd manual pages. Freedesktop.org. https://unix.stackexchange.com/a/394191/5132 https://unix.stackexchange.com/a/204075/5132 https://unix.stackexchange.com/a/196014/5132 https://unix.stackexchange.com/a/332797/5132
How does systemd use /etc/init.d scripts?
1,295,035,247,000
I just want to know difference between in reboot init 6 shutdown -r now and which is the safest and the best?
There is no difference in them. Internally they do exactly the same thing: reboot uses the shutdown command (with the -r switch). The shutdown command used to kill all the running processes, unmount all the file systems and finally tells the kernel to issue the ACPI power command. The source can be found here. In older distros the reboot command was forcing the processes to exit by issuing the SIGKILL signal (still found in sources, can be invoked with -f option), in most recent distros it defaults to the more graceful and init friendly init 1 -> shutdown -r. This ensures that daemons clean up themselves before shutdown. init 6 tells the init process to shutdown all of the spawned processes/daemons as written in the init files (in the inverse order they started) and lastly invoke the shutdown -r now command to reboot the machine Today there is not much difference as both commands do exactly the same, and they respect the init scripts used to start services/daemons by invoking the shutdown scripts for them. Except for reboot -f -r now as stated below There is a small explanation taken from manpages of why the reboot -f is not safe: -f, --force Force immediate halt, power-off, reboot. Don't contact the init system. Edit: Forgot to mention, in upcoming RHEL distributions you should use the new systemctl command to issue poweroff/reboot. As stated in the manpages of reboot and shutdown they are "a legacy command available for compatibility only." and the systemctl method will be the only one safe.
What is the difference between reboot , init 6 and shutdown -r now?
1,295,035,247,000
This may have more to do with detecting operating systems, but I specifically need the init system currently in use on the system. Fedora 15 and Ubuntu now use systemd, Ubuntu used to use Upstart (long time default until 15.04), while others use variations of System V. I have an application that I am writing to be a cross-platform daemon. The init scripts are being dynamically generated based on parameters that can be passed in on configure. What I'd like to do is only generate the script for the particular init system that they are using. This way the install script can be run reasonably without parameters as root and the daemon can be "installed" automagically. This is what I've come up with: Search for systemd, upstart, etc in /bin Compare /proc/1/comm to the systemd, upstart, etc Ask the user What would be the best cross/platform way of doing this? Kind of related, Can I depend on bash to be on the majority of *nix or is it distribution/OS dependent? Target platforms: Mac OS Linux (all distributions) BSD (all versions) Solaris, Minix, and other *nix
For the second question, the answer is no and you should have a look at Resources for portable shell programming. As for the first part - first of all, you certainly have to be careful. I'd say perform several tests to make sure - because the fact that someone does have systemd (for ex.) installed, does not mean it is actually used as the default init. Also, looking at /proc/1/comm can be misleading, because some installations of various init programs can automatically make /sbin/init a symlink hardlink or even a renamed version of their main program. Maybe the most useful thing could be to look at the init scripts type - because those are what you'll actually be creating, no matter what runs them. As a side note, you might also have a look at OpenRC which aims to provide a structure of init scripts that is compatible with both Linux and BSD systems.
Detect init system using the shell
1,295,035,247,000
Is there a simple way to find out which initsystem is being used e.g by a recent Debian wheezy or Fedora system? I'm aware that Fedora 21 uses systemd initsystem but that is because I read that and because all relevant scripts/symlinks are stored in /etc/systemd/. However, I'm not sure about e.g Debian squeeze or CentOS 6 or 7 and so on. Which techniques exist to verify such initsystem?
You can poke around the system to find indicators. One way is to check for the existence of three directories: /usr/lib/systemd tells you you're on a systemd based system. /usr/share/upstart is a pretty good indicator that you're on an Upstart-based system. /etc/init.d tells you the box has SysV init in its history The thing is, these are heuristics that must be considered together, possibly with other data, not certain indicators by themselves. The Ubuntu 14.10 box I'm looking at right now has all three directories. Why? Because Ubuntu just switched to systemd from Upstart in that version, but keeps Upstart and SysV init for backwards compatibility. In the end, I think the best answer is "experience." You will see that you have logged into a CentOS 7 box and know that it's systemd. How do you learn this? Playing around, RTFMing, etc. The same way you gain all experience. I realize this is not a very satisfactory answer, but that's what happens when there is fragmentation in the market, creating nonstandard designs. It's like asking how you know whether ls accepts -C, or --color, or doesn't do color output at all. Again, the answer is "experience."
How to find out if a system uses SysV, Upstart or Systemd initsystem [duplicate]
1,295,035,247,000
I have a remote machine running Debian 8 (Jessie) with lightdm installed. I want it to start in no-GUI mode, but I don't want to remove all X-related stuff to still be able to run it though SSH with the -X parameter. So how to disable X server autostart without removing it? I tried systemctl stop lightdm, it stops the lightdm, but it runs again after reboot. I also tried systemctl disable lightdm, but it basically does nothing. It renames lightdm's scripts in /etc/rc*.d directories, but it still starts after reboot, so what am I doing wrong? And I can't just update-rc.d lightdm stop, because it's deprecated and doesn't work.
The disable didn't work because the Debian /etc/X11/default-display-manager logic is winding up overriding it. In order to make text boot the default under systemd (regardless of which distro, really): systemctl set-default multi-user.target To change back to booting to the GUI, systemctl set-default graphical.target I confirmed those work on my Jessie VM and Slashback confirmed it on Stretch, too. PS: You don't actually need the X server on your machine to run X clients over ssh. The X server is only needed where the display (monitor) is.
How to disable X server autostart in Debian Jessie?
1,295,035,247,000
I have been studying the Linux kernel behaviour for quite some time now, and it's always been clear to me that: When a process dies, all its children are given back to the init process (PID 1) until they eventually die. However, recently, someone with much more experience than me with the kernel told me that: When a process exits, all its children also die (unless you use NOHUP in which case they get back to init). Now, even though I don't believe this, I still wrote a simple program to make sure of it. I know I should not rely on time (sleep) for tests since it all depends on process scheduling, yet for this simple case, I think that's fairly enough. int main(void){ printf("Father process spawned (%d).\n", getpid()); sleep(5); if(fork() == 0){ printf("Child process spawned (%d => %d).\n", getppid(), getpid()); sleep(15); printf("Child process exiting (%d => %d).\n", getppid(), getpid()); exit(0); } sleep(5); printf(stdout, "Father process exiting (%d).\n", getpid()); return EXIT_SUCCESS; } Here is the program's output, with the associated ps result every time printf talks: $ ./test & Father process spawned (435). $ ps -ef | grep test myuser 435 392 tty1 ./test Child process spawned (435 => 436). $ ps -ef | grep test myuser 435 392 tty1 ./test myuser 436 435 tty1 ./test Father process exiting (435). $ ps -ef | grep test myuser 436 1 tty1 ./test Child process exiting (436). Now, as you can see, this behaves quite as I would have expected it to. The orphan process (436) is given back to init (1) until it dies. However, is there any UNIX-based system on which this behaviour does not apply by default? Is there any system on which the death of a process immediately triggers the death of all its children?
When a process exits, all its children also die (unless you use NOHUP in which case they get back to init). This is wrong. Dead wrong. The person saying that was either mistaken, or confused a particular situation with the the general case. There are two ways in which the death of a process can indirectly cause the death of its children. They are related to what happens when a terminal is closed. When a terminal disappears (historically because the serial line was cut due to a modem hangup, nowadays usually because the user closed the terminal emulator window), a SIGHUP signal is sent to the controlling process running in that terminal — typically, the initial shell started in that terminal. Shells normally react to this by exiting. Before exiting, shells intended for interactive use send HUP to each job that they started. Starting a job from a shell with nohup breaks that second source of HUP signals because the job will then ignore the signal and thus not be told to die when the terminal disappears. Other ways to break the propagation of HUP signals from the shell to the jobs include using the shell's disown builtin if it has one (the job is removed from the shell's list of jobs), and double forking (the shell launches a child which launches a child of its own and exits immediately; the shell has no knowledge of its grandchild). Again, the jobs started in the terminal die not because their parent process (the shell) dies, but because their parent process decides to kill them when it is told to kill them. And the initial shell in the terminal dies not because its parent process dies, but because its terminal disappears (which may or may not coincidentally be because the terminal is provided by a terminal emulator which is the shell's parent process).
Is there any UNIX variant on which a child process dies with its parent?
1,295,035,247,000
I am creating a linux distro and now I need an init program. I can code in c really well and I know quite a bit about linux (not much but I've been using arch linux for development for 4 years), so I thought I should try writing my own basic init script in C. I was just wondering, what tasks does init do to set the system up for a simple shell? (When I ask "what does init do?", I do know what init is and what it's for. I just don't know what tasks it does.) I don't need code and I possibly don't even need basic commands but I do need the order that they are run in.
System 5 init will tell you only a small part of the story. There's a sort of myopia that affects the Linux world. People think that they use a thing called "System 5 init", and that is both what is traditional and the best place to start. Neither is in fact the case. Tradition isn't in fact what such people say it to be, for starters. System 5 init and System 5 rc date to AT&T UNIX System 5, which was almost as far after the first UNIX as we are now (say) after the first version of Linux-Mandrake. 1st Edition UNIX only had init. It did not have rc. The 1st Edition assembly language init (whose code has been restored and made available by Warren Toomey et al.) directly spawned and respawned 12 getty processes, mounted 3 hardwired filesystems from a built-in table, and directly ran a program from the home directory of a user named mel. The getty table was also directly in the program image. It was another decade after UNIX System 5 that the so-called "traditional" Linux init system came along. In 1992, Miquel van Smoorenburg (re-)wrote a Linux init+rc, and their associated tools, which people now refer to as "System 5 init", even though it isn't actually the software from UNIX System 5 (and isn't just init). System 5 init/rc isn't the best place to start, and even if one adds on knowledge of systemd that doesn't cover half of what there is to know. There's been a lot of work in the area of init system design (for Linux and the BSDs) that has happened in the past two decades alone. All sorts of engineering decisions have been discussed, made, designed, implemented, and practised. The commercial Unices did a lot, too. Existing systems to study and and learn from Here is an incomplete list of some of the major init systems other than those two, and one or two of their (several) salient points: Joachim Nilsson's finit went the route of using a more human-readable configuration file. Felix von Leitner's minit went for a filesystem-is-the-database configuration system, small memory footprints, and start/stop dependencies amongst things that init starts. Gerrit Pape's runit went for what I have previously described as the just spawn four shell scripts approach. InitNG aimed to have dependencies, named targets, multiple configuration files, and a more flexible configuration syntax with a whole load more settings for child processes. upstart went for a complete redesign, modelling the system not as services and interdependencies at all, but as events and jobs triggered by them. The design of nosh includes pushing all of the service management out (including even the getty spawning and zombie reaping) into a separate service manager, and just handling operating-system-specific "API" devices/symlinks/directories and system events. sinit is a very simple init. It executes /bin/rc.init whose job it is to start programs, mount filesystem, etc. For this you can use something like minirc. Moreover, about 10 years ago, there was discussion amongst daemontools users and others of using svscan as process #1, which led to projects like Paul Jarc's svscan as process 1 study, Gerrit Pape's ideas, and Laurent Bercot's svscan as process 1. Which brings us to what process #1 programs do. What process #1 programs do Notions of what process #1 is "supposed" to do are by their natures subjective. A meaningful objective design criterion is what process #1 at minimum must do. The kernel imposes several requirements on it. And there are always some operating-system-specific things of various kinds that it has to do. When it comes to what process #1 has traditionally done, then we are not at that minimum and never really have been. There are several things that various operating system kernels and other programs demand of process #1 that one simply cannot escape. People will tell you that fork()ing things and acting as the parent of orphaned processes is the prime function of process #1. Ironically, this is untrue. Dealing with orphaned processes is (with recent Linux kernels, as explained at https://unix.stackexchange.com/a/177361/5132) a part the system that one can largely factor out of process #1 into other processes, such as a dedicated service manager. All of these are service managers, that run outwith process #1: the IBM AIX srcmstr program, the System Resource Controller Gerrit Pape's runsvdir from runit Daniel J. Bernstein's svscan from daemontools, Adam Sampson's svscan from freedt, Bruce Guenter's svscan from daemontools-encore, and Laurent Bercot's s6-svscan from s6 Wayne Marshall's perpd from perp the Service Management Facility in Solaris 10 the service-manager from nosh Similarly, as explained at https://superuser.com/a/888936/38062, the whole /dev/initctl idea doesn't need to be anywhere near process #1. Ironically, it is the highly centralized systemd that demonstrates that it can be moved out of process #1. Conversely, the mandatory things for init, that people usually forget in their off-the-top-of-the-head designs, are things such as handling SIGINT, SIGPWR, SIGWINCH, and so forth sent from the kernel and enacting the various system state change requests sent from programs that "know" that certain signals to process #1 mean certain things. (For example: As explained at https://unix.stackexchange.com/a/196471/5132, BSD toolsets "know" that SIGUSR1 has a specific meaning.) There are also once-off initialization and finalization tasks that one cannot escape, or will suffer greatly from not doing, such as mounting "API" filesystems or flushing the filesystem cache. The basics of dealing with "API" filesystems are little different to the operation of init rom 1st Edition UNIX: One has a list of information hardwired into the program, and one simply mount()s all of the entries in the list. You'll find this mechanism in systems as diverse as BSD (sic!) init, through the nosh system-manager, to systemd. "set the system up for a simple shell" As you have observed, init=/bin/sh doesn't get "API" fileystems mounted, crashes in an ungainly fashion with no cache flush when one types exit (https://unix.stackexchange.com/a/195978/5132), and in general leaves it to the (super)user to manually do the actions that make the system minimally usable. To see what one actually has no choice but to do in process #1 programs, and thus set you on a good course for your stated design goal, your best option is to look at the overlaps in the operation of Gerrit Pape's runit, Felix von Leitner's minit, and the system-manager program from the nosh package. The former two show two attempts to be minimalist, yet still handle the stuff that it is impossible to avoid. The latter is useful, I suggest, for its extensive manual entry for the system-manager program, which details exactly what "API" filesystems are mounted, what initialization tasks are run, and what signals are handled; in a system that by design has the system manager just spawn three other things (the service manager, an accompanying logger, and the program to run the state changes) and only do the unavoidable in process #1.
What exactly does init do?
1,295,035,247,000
Can root kill init process (the process with pid 1)? What would be its consequences?
By default, no, that's not allowed. Under Linux (from man 2 kill): The only signals that can be sent to process ID 1, the init process, are those for which init has explicitly installed signal handlers. This is done to assure the system is not brought down accidentally. Pid 1 (init) can decide to allow itself to be killed, in which case the "kill" is basically a request for it to shut itself down. This is one possible way to implement the halt command, though I'm not aware of any init that does that. On a Mac, killing launchd (its init analogue) with signal 15 (SIGTERM) will immediately reboot the system, without bothering to shut down running programs cleanly. Killing it with the uncatchable signal 9 (SIGKILL) does nothing, showing that Mac's kill() semantics are the same as Linux's in this respect. At the moment, I don't have a Linux box handy that I'm willing to experiment with, so the question of what Linux's init does with a SIGTERM will have to wait. And with init replacement projects like Upstart and Systemd being popular these days, the answer could be variable. UPDATE: On Linux, init explicitly ignores SIGTERM, so it does nothing. @jsbillings has information on what Upstart and Systemd do.
Can root kill init process?
1,295,035,247,000
I'm wanting to understand the Linux init process better in order to netboot a system over ceph rather than nfs. In the process I've come across two forms of switching root. One called switch_root, and the other called pivot_root. These scripts being run from an in memory filesystem (initramfs) obtained via tftp using the pxe boot process. When would you use one over the other? I've seen both used in some init script's placed in root.
I found a wonderful explanation here. However, let me try to put in a shorter format of what I understood in the answer. Shorter Version While the system boots, it needs an early userspace. It can be achieved using either initramfs or initrd. initrd is loaded into ramdisk which is an actual FILE SYSTEM. initramfs is not a file system. For initrd pivot_root is used and for initramfs switch_root is used. Longer Version Now, to the detailed explanation of what I had put above. While both an initramfs and an initrd serve the same purpose, there are 2 differences. The most obvious difference is that an initrd is loaded into a ramdisk. It consists of an actual filesystem (typically ext2) which is mounted in a ramdisk. An initramfs, on the other hand, is not a filesystem. It is simply a (compressed) cpio archive (of type newc) which is unpacked into a tmpfs. This has a side-effect of making the initramfs a bit more optimized and capable of loading a little earlier in the kernel boot process than an initrd. Also, the size of the initramfs in memory is smaller, since the kernel can adapt the size of the tmpfs to what is actually loaded, rather than relying on predefined ramdisk sizes, and it can also clean up the ram that was used whereas ramdisks tend to remain in use (due to details of the pivot_root implementation). There is also another side-effect difference: how the root device (and switching to it) is handled. Since an initrd is an actual filesystem unpacked into ram, the root device must actually be the ramdisk. For an initramfs, there is a kernel "rootfs" which becomes the tmpfs that the initramfs is unpacked into (if the kernel loads an initramfs; if not, then the rootfs is simply the filesystem specified via the root= kernel boot parameter), but this interim rootfs should not be specified as the root= boot parameter (and there wouldn't be a way to do so, since there's no device attached to it). This means that you can still pass your real root device to the kernel when using an initramfs. With an initrd, you have to process what the real root device is yourself. Also, since the "real" root device with an initrd is the ramdisk, the kernel has to really swith root devices from one real device (the ramdisk) to the other (your real root). In the case of an initramfs, the initramfs space (the tmpfs) is not a real device, so the kernel doesn't switch real devices. Thus, while the command pivot_root is used with an initrd, a different command has to be used for an initramfs. Busybox provides switch_root to accomplish this, while klibc offers new_root.
When would you use pivot_root over switch_root?
1,295,035,247,000
Between the recent "Why does 'kill -9 0' end my console session" and "How to get a kernel panic" questions, I got a bur under my saddle and tried kill -9 1 on a mostly up-to-date Arch linux laptop. I did it as user ID "root". I fully expected some kind of crash or panic or shutdown, but nothing happened. I did kill -9 1 again, to no effect. Arch linux machines run systemd these days, so: how does systemd survive a kill -9? I expect there's special case code in the Linux 3.7 kernel, but maybe some other reason exists that I haven't thought of. What about other things that run with PID 1? Slackware still uses init I believe, but I'm scared to try it on my production Slackware server. DD-WRT on my wireless router runs /sbin/init of some sort.
From man 2 kill: The only signals that can be sent to process ID 1, the init process, are those for which init has explicitly installed signal handlers. This is done to assure the system is not brought down accidentally. That is, it is possible for init to do whatever it likes upon receiving SIGKILL (including exiting), but systemd's init does not install any signal handler for it, so nothing happens.
How does systemd survive a kill -9?
1,295,035,247,000
I have always learned that the init process is the ancestor of all processes. Why does process 2 have a PPID of 0? $ ps -ef | head -n 3 UID PID PPID C STIME TTY TIME CMD root 1 0 0 May14 ? 00:00:01 /sbin/init root 2 0 0 May14 ? 00:00:00 [kthreadd]
First, “ancestor” isn't the same thing as “parent”. The ancestor can be the parent's parent's … parent's parent, and the kernel only keeps track of one level. However, when a process dies, its children are adopted by init, so you will see a lot of processes whose parent is 1 on a typical system. Modern Linux systems additionally have a few processes that execute kernel code, but are managed as user processes, as far as scheduling is concerned. (They don't obey the usual memory management rules since they're running kernel code.) These processes are all spawned by kthreadd (it's the init of kernel threads). You can recognize them by the fact that /proc/2/exe (normally a symbolic link to the process executable) can't be read. Also, ps lists them with a name between square brackets (which is possible for normal user processes, but unusual). Most processes whose parent process ID is 2 are kernel processes, but there are also a few kernel helper processes with PPID 2 (see below). Processes 1 (init) and 2 (kthreadd) are created directly by the kernel at boot time, so they don't have a parent. The value 0 is used in their ppid field to indicate that. Think of 0 as meaning “the kernel itself” here. Linux also has some facilities for the kernel to start user processes whose location is indicated via a sysctl parameter in certain circumstances. For example, the kernel can trigger module loading events (e.g. when new hardware is discovered, or when some network protocols are first used) by calling the program in the kernel.modprobe sysctl value. When a program dumps core, the kernel calls the program indicated by kernel.core_pattern if any. Those processes are user processes, but their parent is registered as kthreadd.
init process: ancestor of all processes?
1,295,035,247,000
In UNIX, when a parent process disappears, I thought that all child processes reset init as their parent. Is this not correct all the time? Are there any exceptions?
Moving my comment to an answer.... I don't believe there are exceptions. Found this "sometimes the parent process is killed before its child is killed. In this case, the "parent of all processes," init process, becomes the new PPID (parent process ID). Sometime these processes are called orphan process." source Similarly is described in IBM's blog: "The parent dies or gets killed before the child. In the above scenario, the child process becomes the orphan process (as it has lost its parent). In Linux, the init process comes to the rescue of the orphan processes and adopts them. This means after a child has lost its parent, the init process becomes its new parent process."
New parent process when the parent process dies
1,295,035,247,000
Installing a new system using a GPT partitioned disk dedicated to a single partition, ext4 formatted, extlinux (version 4.05) as bootloader, Ubuntu Core version 13.10 amd64 as rootfs, and Ubuntu linux-image-3.11.0-18-generic as kernel, and extlinux-update to generate bootloader configuration. The result after reboot (still inside a KVM based virtual machine) is an (initramfs) prompt and these messages: mount: can't read '/etc/fstab': No such file or directory mount: mounting /dev on /root/dev failed: No such file or directory mount: mounting /sys on /root/sys failed: No such file or directory mount: mounting /proc on /root/proc failed: No such file or directory The filesystem doesn't have requested /sbin/init. No init found. Try passing init= bootarg. BusyBox is v1.20.2. Regression: the file system has been checked with fsck.ext4 Check for root existence (initramfs) ls -l /dev/[hs]da* ls: /dev/[hs]da*: No such file or directory Root boot argument (initramfs) cat /proc/cmdline initrd=/boot/initrd.img-3.11.0-18-generic ro quiet BOOT_IMAGE=/boot/vmlinuz-3.11.0-18-generic Check loaded modules (initramfs) cat /proc/modules e1000 145368 0 - Live 0xffffffffa0000000 /boot folder content $ sudo ls -l boot -rw------- 1 root root 3296162 Feb 18 22:37 System.map-3.11.0-18-generic -rw-r--r-- 1 root root 1007681 Feb 18 22:37 abi-3.11.0-18-generic -rw-r--r-- 1 root root 163258 Feb 18 22:37 config-3.11.0-18-generic drwxr-xr-x 2 root root 4096 Mar 17 20:13 extlinux -rw-r--r-- 1 root root 4995000 Mar 16 23:35 initrd.img-3.11.0-18-generic -rw------- 1 root root 5634192 Feb 18 22:37 vmlinuz-3.11.0-18-generic How to make this system boot to the expected default bash prompt?
Modify your kernel boot parameter by setting the root=/dev/sdaX option. sdaX would be your / or root partition. Upon booting the next time, you will see that your initramfs tries to mount the partition before trying to access /etc/fstab and mounting the file systems. See question "Does initramfs use /etc/fstab?" for more details.
How to fix boot into initramfs prompt and "mount: can't read '/etc/fstab': No such file or directory" and "No init found"?
1,295,035,247,000
I created the following service, amos.service, and it needs to run as amos (member of the amos group) [Unit] Description=AMOS Service After=network.target [Service] User=amos Group=amos Type=simple WorkingDirectory=/usr/share/amos ExecStart=/usr/share/amos/amos_service.sh start ExecStop=/usr/share/amos/amos_service.sh stop Restart=on-failure [Install] WantedBy=multi-user.target all the permissions have been set on /usr/share/amos to amos:amos the amos_service.sh is as follows: #!/bin/bash CUDIR=$(dirname "$0") cd /usr/share/amos start() { exec /usr/share/amos/run_amos.sh >> /var/log/amos.log 2>&1 } stop() { exec pkill java } case $1 in start|stop) "$1" ;; esac cd "$CURDIR" When I run the service initially without any modifications to the directories, meaning, belonging to root, and amos.service not having the User not Group parameter, everything runs great! Once I change the directories permissions to amos:amos and add the amos.service User & Group, the serive won't work and I get the following : See attached image
Use systemd: To show the problem use journalctl -xe after you started the service. You don't need a bash script, put this in your service file: ExecStart=/usr/share/amos/run_amos.sh There is no need for ExecStop, systemd will stop all child processes. You can view the output with journalctl -u amos.service.
Running a systemd service as a user other than root!
1,295,035,247,000
Transmission is intermittently hanging on my NAS. If I send SIGTERM, it doesn't disappear from the process list and a <defunct> label appears next to it. If I send a SIGKILL, it still doesn't disappear and I can't terminate the parent because the parent is init. The only way I can get rid of the process and restart Transmission is to reboot. I realize the best thing I can do is try and fix Transmission (and I've tried), but I'm a novice at compiling and I wanted to make sure my torrents finished before I start messing around with it.
You cannot kill a <defunct> process (also known as zombie process) as it is already dead. The system keeps zombie processes for the parent to collect the exit status. If the parent does not collect the exit status then the zombie processes will stay around forever. The only way to get rid of those zombie processes are by killing the parent. If the parent is init then you can only reboot. Zombie processes take up almost no resouces so there is no performance cost in letting them linger. Although having zombie processes around usually means there is a bug in some of your programs. Init should usually collect all children. If init has zombie children then there is a bug in init (or somehwere else but a bug it is). http://en.wikipedia.org/wiki/Zombie_process
How can I kill a <defunct> process whose parent is init?
1,295,035,247,000
Not much to put here in the body.
Processes need to have a parent (PPID). The kernel, despite not being a real process, is nevertheless handcrafting some real processes like at least init, and is giving itself the process ID 0. Depending on the OS it might or might not be displayed as a process in ps output but is always displayed as a PPID: eg on Linux: $ ps -ef|head UID PID PPID C STIME TTY TIME CMD root 1 0 0 09:09 ? 00:00:00 /sbin/init root 2 0 0 09:09 ? 00:00:00 [kthreadd] root 3 2 0 09:09 ? 00:00:00 [ksoftirqd/0] ... on Solaris: $ ps -ef|head UID PID PPID C STIME TTY TIME CMD root 0 0 0 Oct 19 ? 0:01 sched root 5 0 0 Oct 19 ? 11:20 zpool-rpool1 root 1 0 0 Oct 19 ? 0:13 /sbin/init root 2 0 0 Oct 19 ? 0:07 pageout root 3 0 1 Oct 19 ? 117:10 fsflush root 341 1 0 Oct 19 ? 0:15 /usr/lib/hal/hald --daemon=yes root 9 1 0 Oct 19 ? 0:59 /lib/svc/bin/svc.startd ... Note also that pid 0 (and -1 and other negative values for that matter) have different meanings depending on what function use them like kill, fork and waitpid. Finally, while the init process is traditionally given pid #1, this is no more the case when OS level virtualization is used like Solaris zones, as there can be more than one init running: $ ps -ef|head UID PID PPID C STIME TTY TIME CMD root 4733 3949 0 11:07:25 ? 0:26 /lib/svc/bin/svc.configd root 4731 3949 0 11:07:24 ? 0:06 /lib/svc/bin/svc.startd root 3949 3949 0 11:07:14 ? 0:00 zsched daemon 4856 3949 0 11:07:46 ? 0:00 /lib/crypto/kcfd root 4573 3949 0 11:07:23 ? 0:00 /usr/sbin/init netcfg 4790 3949 0 11:07:34 ? 0:00 /lib/inet/netcfgd root 4868 3949 0 11:07:48 ? 0:00 /usr/lib/pfexecd root 4897 3949 0 11:07:51 ? 0:00 /usr/lib/utmpd netadm 4980 3949 0 11:07:54 ? 0:01 /lib/inet/nwamd
If computers start counting at 0, why does the init process have a pid of 1?
1,295,035,247,000
As I understand it, a zombie process has died but still exists as a placeholder in the process table until its parent (or init if the zombie is itself an orphan) checks its exit status. And my understanding of orphan processes is they are processes that are still alive and running but whose parent has died. Since a zombie is already dead, its children would be considered orphans, wouldn't they? Would they be affected be reaping the zombie? Specifically, would init adopt them as its children only once the zombie was reaped, or would they be adopted as soon as the parent became a zombie?
As I understand it, a zombie process has died but still exists as a placeholder in the process table until its parent (or init if the zombie is itself an orphan) checks its exit status. Correct. And my understanding of orphan processes is they are processes that are still alive and running but whose parent has died. Correct. Since a zombie is already dead, its children would be considered orphans, wouldn't they? Yes. When the parent dies, it's dead. With respect to its children, it doesn't matter whether the parent stays on as a zombie: the children become orphans at the time the parent dies, and then they lose any connection with their parent. Would they be affected be reaping the zombie? Specifically, would init adopt them as its children only once the zombie was reaped, or would they be adopted as soon as the parent became a zombie? No, and the latter, as per above.
Can a zombie have orphans? Will the orphan children be disturbed by reaping the zombie?
1,295,035,247,000
I need one process run before log in to system. How to run it like services? how do I make services in Linux? In Ubuntu and Fedora? The service is customized tomcat
To run a service without or before logging in to the system (i.e. "on boot"), you will need to create a startup script and add it to the boot sequence. There's three parts to a service script: start, stop and restart. The basic structure of a service script is: #!/bin/bash # RETVAL=0; start() { echo “Starting <Service>” } stop() { echo “Stopping <Service>” } restart() { stop start } case “$1″ in start) start ;; stop) stop ;; restart) restart ;; *) echo $”Usage: $0 {start|stop|restart}” exit 1 esac exit $RETVAL Once you have tweaked the script to your liking, just place it in /etc/init.d/ And, add it to the system service startup process (on Fedora, I am not a Ubuntu user, >D): chkconfig -add <ServiceName> Service will be added to the system boot up process and you will not have to manually start it up again. Cheers!
Start tomcat at startup with administrative privileges
1,295,035,247,000
I'm trying to debug an init script on a Linux system; I'm trying to pass init=/bin/sh to the kernel to make it start sh without starting init so I can run through the init sequence manually. What I've found is that the kernel is starting init anyway. During bootup, one of the printk messages is the command line, and that is showing that the line is being set properly; in addition, I can affect other things using the kernel command line. I have checked to make sure the path exists; it does. This is a busybox system, and init is a symlink to busybox; so to make sure busybox doesn't do strange magic when its PID is 1, I also tried running a non-busybox program as init; that didn't work, either. It seems that no matter what I do, init is run. What could be causing this behavior?
Looking at Linux kernel source, I see that if the file /init exists, the kernel will always attempt to run it on the assumption that it's doing a ramdisk boot. Check your system to see if /init exists, if it does, then that's probably your problem.
What can make passing init=/path/to/program to the kernel not start program as init?